Files
xSdkManager/modules/models/x-decorator.descriptor.js
2026-11-11 19:28:11 +03:30

1237 lines
30 KiB
JavaScript

//
//#region Imports ...
const XFileTools = require('../tools/x-file.tools');
const XValueTools = require('../tools/x-value.tools');
const XBaseDescriptor = require('./x-base.descriptor');
const XTypeDetectorTools = require('../tools/x-type-detector.tools');
//#endregion
/**
* determines a proposed value is a descriptor or not ...
*
* @param {any} descriptor the proposed value to check ...
* @returns value is a valid descriptor or not ...
*/
function isDescriptor(descriptor) {
//
// Prepare Result ...
let result = false;
//
//#region Validate Args ...
if (!descriptor) {
return result;
}
//
const descriptorType = descriptor.type;
if (
!XValueTools.isValidArg(descriptorType) ||
!XBaseDescriptor.isValidDecoratorType(descriptorType)
) {
return result;
}
//
const descriptorKeys = Object
.keys(descriptor)
.filter(k => k !== 'raw' && k !== 'type');
if (!XValueTools.hasChildArray(descriptorKeys)) {
return result;
}
//#endregion
//
result = descriptorKeys.every(k => XBaseDescriptor
.isValidDecoratorPartForType(k, descriptorType));
//
return result;
}
/**
* retrieve base or filled DecoratorDescriptor object instance ...
*
* @param {any} value a value provider object ...
* @returns an instance of DecoratorDescriptor object ...
*/
function createDescriptor(value, forceFullProperty = false) {
//
// Define base Model ...
let result = {
raw: '',
type: '',
styles: [],
imports: [],
exports: [],
selector: '',
template: '',
providers: [],
styleUrls: [],
bootstrap: [],
providedIn: '',
templateUrl: '',
declarations: [],
entryComponents: [],
changeDetection: '',
};
//
//#region Apply Value ...
if (value) {
//
// Prepare Input Values ...
Object.keys(value).forEach(part => {
//
let partValue = value[part];
//
// Check Part is Valid for Decorator ...
if (XBaseDescriptor.isValidDecoratorPart(part)) {
//
// Retrieve Part Type ...
const type = XBaseDescriptor.getDecoratorPartType(part);
if (XValueTools.isValidArg(type)) {
//
switch (type) {
//
// Array ...
case XBaseDescriptor.DecoratorPartTypes.Array:
//
// Normalize Arrray ...
partValue = XValueTools.toNormalArray(partValue);
//
// Add Specific Signs if not have ...
// TODO: Complete sorroundation if reqired ...
// partValue = partValue.map(pv => {
// //
// });
break;
//
// String ...
case XBaseDescriptor.DecoratorPartTypes.String:
//
// Add Specific Signs if not have ...
// TODO: Complete sorroundation if reqired ...
break;
}
//
value[part] = partValue;
}
}
});
//
//#region raw ...
if (XValueTools.isValidArg(value.raw)) {
result.raw = value.raw;
}
//#endregion
//
//#region type ...
if (XValueTools.isValidArg(value.type)) {
result.type = value.type;
}
//#endregion
//
//#region styles ...
if (XValueTools.hasChildArray(value.styles)) {
result.styles = value.styles;
} else if (!forceFullProperty) {
result.styles = undefined;
}
//#endregion
//
//#region imports ...
if (XValueTools.hasChildArray(value.imports)) {
result.imports = value.imports;
} else if (!forceFullProperty) {
result.imports = undefined;
}
//#endregion
//
//#region exports ...
if (XValueTools.hasChildArray(value.exports)) {
result.exports = value.exports;
} else if (!forceFullProperty) {
result.exports = undefined;
}
//#endregion
//
//#region selector ...
if (XValueTools.isValidArg(value.selector)) {
result.selector = value.selector;
} else if (!forceFullProperty) {
result.selector = undefined;
}
//#endregion
//
//#region template ...
if (XValueTools.isValidArg(value.template)) {
result.template = value.template;
} else if (!forceFullProperty) {
result.template = undefined;
}
//#endregion
//
//#region providers ...
if (XValueTools.hasChildArray(value.providers)) {
result.providers = value.providers;
} else if (!forceFullProperty) {
result.providers = undefined;
}
//#endregion
//
//#region styleUrls ...
if (XValueTools.hasChildArray(value.styleUrls)) {
result.styleUrls = value.styleUrls;
} else if (!forceFullProperty) {
result.styleUrls = undefined;
}
//#endregion
//
//#region bootstrap ...
if (XValueTools.hasChildArray(value.bootstrap)) {
result.bootstrap = value.bootstrap;
} else if (!forceFullProperty) {
result.bootstrap = undefined;
}
//#endregion
//
//#region providedIn ...
if (XValueTools.isValidArg(value.providedIn)) {
result.providedIn = value.providedIn;
} else if (!forceFullProperty) {
result.providedIn = undefined;
}
//#endregion
//
//#region templateUrl ...
if (XValueTools.isValidArg(value.templateUrl)) {
result.templateUrl = value.templateUrl;
} else if (!forceFullProperty) {
result.templateUrl = undefined;
}
//#endregion
//
//#region declarations ...
if (XValueTools.hasChildArray(value.declarations)) {
result.declarations = value.declarations;
} else if (!forceFullProperty) {
result.declarations = undefined;
}
//#endregion
//
//#region entryComponents ...
if (XValueTools.hasChildArray(value.entryComponents)) {
result.entryComponents = value.entryComponents;
} else if (!forceFullProperty) {
result.entryComponents = undefined;
}
//#endregion
//
//#region changeDetection ...
if (XValueTools.isValidArg(value.changeDetection)) {
result.changeDetection = value.changeDetection;
} else if (!forceFullProperty) {
result.changeDetection = undefined;
}
//#endregion
}
//#endregion
//
//#region Apply Selection Parts based on Module Type ...
if (
XValueTools.isValidArg(result.type) &&
Object.values(XBaseDescriptor.DecoratorTypes).includes(result.type)
) {
//
const raw = result.raw;
const type = result.type;
//
switch (result.type) {
//
// Unknown ...
case XBaseDescriptor.DecoratorTypes.Unknown:
result = undefined;
break;
//
// Module ...
case XBaseDescriptor.DecoratorTypes.Module:
//
let validModuleDecorator = {};
Object.values(XBaseDescriptor.ModuleDecoratorValidParts).forEach(p => {
validModuleDecorator[p] = result[p];
});
//
result = {
...validModuleDecorator
}
break;
//
// Directive ...
case XBaseDescriptor.DecoratorTypes.Directive:
//
let validDirectiveDecorator = {};
Object.values(XBaseDescriptor.DirectiveDecoratorValidParts).forEach(p => {
validDirectiveDecorator[p] = result[p];
});
//
result = {
...validDirectiveDecorator
}
break;
//
// Component ...
case XBaseDescriptor.DecoratorTypes.Component:
//
let validComponentDecorator = {};
Object.values(XBaseDescriptor.ComponentDecoratorValidParts).forEach(p => {
validComponentDecorator[p] = result[p];
});
//
result = {
...validComponentDecorator
}
break;
//
// Injectable ...
case XBaseDescriptor.DecoratorTypes.Injectable:
//
let validInjectableDecorator = {};
Object.values(XBaseDescriptor.InjectableDecoratorValidParts).forEach(p => {
validInjectableDecorator[p] = result[p];
});
//
result = {
...validInjectableDecorator
}
break;
}
//
result.raw = raw;
result.type = type;
}
//#endregion
//
//#region remove all undefined keys ...
if (value && !forceFullProperty) {
//
Object.keys(result).forEach(key => {
if (!result[key]) {
delete result[key];
}
});
}
//#endregion
//
return result;
}
/**
* converts an instance of Descriptor to Expression ...
*
* @param descriptor an instance of DecoratorDescriptor ...
* @returns creator string ...
*/
function toExpression(descriptor = createDescriptor()) {
//
let result = '';
//
// Validate Arg ...
if (
!XBaseDescriptor.isValidDecoratorType(descriptor.type) ||
!Object.keys(descriptor).filter(k => k !== 'raw' && k !== 'type').every(key => XBaseDescriptor.isValidDecoratorPartForType(key, descriptor.type))
) {
return result;
}
//
let decoTypeParam = Object.keys(XBaseDescriptor.DecoratorTypes).find(key => XBaseDescriptor.DecoratorTypes[key] === descriptor.type);
if (!XValueTools.isValidArg(decoTypeParam)) {
return '';
}
//
// Change module to NG Module ...
if (decoTypeParam.toLowerCase() === XBaseDescriptor.DecoratorTypes.Module) {
decoTypeParam = 'NgModule';
}
//
result += '@' + decoTypeParam + '({';
//
// selector ...
if (XValueTools.isValidArg(descriptor.selector)) {
descriptor.selector = XValueTools.surroundBy('\'', descriptor.selector);
}
//
// template ...
if (XValueTools.isValidArg(descriptor.template)) {
descriptor.template = XValueTools.surroundBy('`', descriptor.template);
}
//
// providedIn
if (XValueTools.isValidArg(descriptor.providedIn)) {
descriptor.providedIn = XValueTools.surroundBy('\'', descriptor.providedIn);
}
//
// templateUrl
if (XValueTools.isValidArg(descriptor.templateUrl)) {
descriptor.templateUrl = XValueTools.surroundBy('\'', descriptor.templateUrl);
}
//
const decType = descriptor.type;
const decParts = Object.keys(descriptor).filter(k => k !== 'type' && k !== 'raw');
//
// Loop Through Parts and make them to Expression ...
for (const part of decParts) {
//
const partValue = descriptor[part];
//
result += '\n' + part + ': ';
if (XTypeDetectorTools.isArray(partValue)) {
result += '[ ' + partValue.join(', ') + ' ]';
} else {
result += partValue;
}
//
result += ',';
}
//
result += '\n})';
//
return result;
}
/**
* extract all exists DecoratorDescriptors ...
*
* @param {string} file a file path ...
* @returns a collection of DecoratorDescriptors ...
*/
async function extractDescriptor(file = '') {
//
if (!XFileTools.isFileExists(file)) {
return [];
}
//
const fileContent = await XFileTools.readFile(file);
if (!XValueTools.isValidArg(fileContent)) {
return [];
}
//
let result = [
createDescriptor()
];
result.pop();
//
result = extractDescriptorFromContent(fileContent);
//
return result;
}
/**
* extract all exists DecoratorDescriptors ...
*
* @param {string} content a file content ...
* @returns a collection of DecoratorDescriptors ...
*/
function extractDescriptorFromContent(content = '') {
//
// Prepare Result ...
let result = {
...createDescriptor()
}
//
// Validate Args ...
if (!XValueTools.isValidArg(content)) {
return undefined;
}
//
// Check Content must Contains Decorator ...
const hasDec = hasDecoratorFromContent(content);
if (!hasDec) {
return undefined;
}
//
// Retrieve Exists Decorator type ...
const decType = getDecoratorTypeFromContent(content);
//
// Raw Content of descriptor ...
let raw = extractDecoratorContentByContent(
content,
false
);
result.raw = raw;
result.type = decType;
//
let decoratorContent = extractDecoratorContentByContent(content);
if (!XValueTools.isValidArg(decoratorContent)) {
return undefined;
}
//
switch (decType) {
//
case XBaseDescriptor.DecoratorTypes.Module:
//
XBaseDescriptor.ModuleDecoratorValidParts.forEach(key => {
//
result[key] = XBaseDescriptor.extractDecoratorPart(key, decoratorContent);
//
if (!result[key]) {
delete result[key];
}
});
break;
//
case XBaseDescriptor.DecoratorTypes.Component:
//
XBaseDescriptor.ComponentDecoratorValidParts.forEach(key => {
//
result[key] = XBaseDescriptor.extractDecoratorPart(key, decoratorContent);
//
if (!result[key]) {
delete result[key];
}
});
break;
//
case XBaseDescriptor.DecoratorTypes.Directive:
//
XBaseDescriptor.DirectiveDecoratorValidParts.forEach(key => {
//
result[key] = XBaseDescriptor.extractDecoratorPart(key, decoratorContent);
//
if (!result[key]) {
delete result[key];
}
});
break;
//
case XBaseDescriptor.DecoratorTypes.Injectable:
//
XBaseDescriptor.InjectableDecoratorValidParts.forEach(key => {
//
result[key] = XBaseDescriptor.extractDecoratorPart(key, decoratorContent);
//
if (!result[key]) {
delete result[key];
}
});
break;
//
default:
result = undefined;
break;
}
//
// Cleanup Unused Keys ...
if (result && XValueTools.hasChildArray(Object.keys(result))) {
//
Object.keys(result).forEach(key => {
//
const isArray = XTypeDetectorTools.isArray(result[key]);
//
if (
(!isArray && !XValueTools.isValidArg(result[key])) ||
(isArray && !XValueTools.hasChildArray(result[key]))
) {
delete result[key];
}
});
}
//
return result;
}
//
//#region Custom Actions ...
//
//#region hasDescriptor ...
/**
* determines a file has decorator or not
*
* @param {string} file file path ...
* @returns {Promise<boolean>} has decorator or not ...
*/
async function hasDecorator(file) {
//
let result = false;
//
// read file content ..
const content = await XFile.readFile(file);
result = hasDecoratorFromContent(content);
//
return result;
}
/**
* determines a file content has decorator or not
*
* @param {string} content file content ...
* @returns {boolean} has decorator or not ...
*/
function hasDecoratorFromContent(content) {
//
let result = false;
//
// Validate Args ...
if (!XValueTools.isValidArg(content)) {
return false;
}
//
// read file content ..
result = content &&
content.length > 1 &&
content.includes('@') &&
content.includes('({') &&
content.includes('})');
//
return result;
}
//#endregion
//
//#region decoratorContent ...
/**
* extract decorator content of specified file ...
*
* @param {string} file a file path ...
* @param {boolean} removeExtras remove all extra chars like comments and whitespaces ...
* @returns the content of decorator object ...
*/
async function extractDecoratorContent(
file,
removeExtras = true
) {
//
let result = '';
//
// Validate Args ...
if (!XFile.isFileExists(file)) {
return undefined;
}
//
const content = await XFile.readFile(file);
result = extractDecoratorContentByContent(content, removeExtras);
if (!XValueTools.isValidArg(result)) {
return undefined;
}
//
return result;
}
/**
* extract decorator content of specified file content ...
*
* @param {string} content a file content ...
* @param {boolean} removeExtras remove all extra chars like comments and whitespaces ...
* @returns the content of decorator object ...
*/
function extractDecoratorContentByContent(
content,
removeExtras = true
) {
//
let result = '';
//
// check content has decorator or not ...
const hasDec = hasDecoratorFromContent(content);
if (!hasDec) {
return undefined;
}
//
// find decorator start and ends indexes ...
const sIndex = content.indexOf('({');
const lIndex = content.lastIndexOf('})');
if (sIndex === -1 || lIndex === -1) {
return undefined;
}
//
// retrieve decorator content ...
result = content
.substr(sIndex + 1, (lIndex - sIndex));
//
// remove extra contents from decorator ...
if (!!removeExtras) {
result = result.split('\n')
.filter(line =>
!line
.trim()
.startsWith('//') && line.length > 0)
.join('\n');
}
if (!XValueTools.isValidArg(result)) {
return undefined;
}
//
// return result ...
return result;
}
//#endregion
//
//#region types ...
/**
* determines specific file's decorator type ...
*
* @param {string} file a file path ...
* @returns {Promise<string>} one of DecoratorType object values ...
*/
async function getDecoratorType(file) {
//
let result = XBaseDescriptor.DecoratorTypes.Unknown;
//
const hasDec = await hasDecorator(file);
if (!hasDec) {
return result;
}
//
const content = await XFileTools.readFile(file);
result = getDecoratorTypeFromContent(content);
//
return result;
}
/**
* determines specific content's decorator type ...
*
* @param {string} content a file content ...
* @returns {string} one of DecoratorType object values ...
*/
function getDecoratorTypeFromContent(content) {
//
let result = XBaseDescriptor.DecoratorTypes.Unknown;
//
const hasDec = hasDecoratorFromContent(content);
if (!hasDec) {
return result;
}
//
let eIndex = content.indexOf('({');
//
content = content.substr(0, eIndex + 2);
eIndex = content.indexOf('({');
let sIndex = content.indexOf('@');
while (eIndex - sIndex > 20) {
sIndex = content.indexOf('@', sIndex + 1);
}
//
const typeContent = (content.substr(sIndex + 1, (eIndex - sIndex) - 1)).toLowerCase();
if (!typeContent || typeContent.length === 0) {
return result;
}
//
result = typeContent.includes(XBaseDescriptor.DecoratorTypes.Module) ?
XBaseDescriptor.DecoratorTypes.Module :
typeContent.includes(XBaseDescriptor.DecoratorTypes.Component) ?
XBaseDescriptor.DecoratorTypes.Component :
typeContent.includes(XBaseDescriptor.DecoratorTypes.Directive) ?
XBaseDescriptor.DecoratorTypes.Directive :
typeContent.includes(XBaseDescriptor.DecoratorTypes.Injectable) ?
XBaseDescriptor.DecoratorTypes.Injectable :
XBaseDescriptor.DecoratorTypes.Unknown;
//
return result;
}
/**
* determines decorator type of an specific file ...
*
* @param {string} decType determines a type DecoratorTypes ...
* @param {string} file destination file to check ...
* @returns
*/
async function isDecoratorOf(
decType,
file
) {
//
let result = false;
//
// Validate Args ...
const availableDecTypes = Object.values(DecoratorTypes);
if (
!XValueTools.isValidArg(file) ||
!XValueTools.isValidArg(decType) ||
!availableDecTypes.includes(decType)
) {
return false;
}
//
// reading file content ...
const content = await XFile.readFile(file);
if (!XValueTools.isValidArg(content)) {
return false;
}
//
result = isDecoratorOfFromContent(decType, content);
return result;
}
/**
* determines decorator type of a content ...
*
* @param {string} decType determines a type DecoratorTypes ...
* @param {string} content file content to check ...
* @returns
*/
function isDecoratorOfFromContent(
decType,
content
) {
//
let result = false;
//
// Validate Args ...
const availableDecTypes = Object.values(DecoratorTypes);
if (
!XValueTools.isValidArg(content) ||
!XValueTools.isValidArg(decType) ||
!availableDecTypes.includes(decType)
) {
return false;
}
//
const hasDec = hasDecoratorFromContent(content);
if (!hasDec) {
return false;
}
//
const contentDecType = getDecoratorTypeFromContent(content);
if (!XValueTools.isValidArg(contentDecType)) {
return result;
}
//
result = contentDecType === decType;
return result;
}
/**
* determine a file is module or not ...
*
* @param {string} file a file path ...
* @returns
*/
async function isModule(file) {
//
const result = await isDecoratorOf(
XBaseDescriptor.DecoratorTypes.Module,
file
);
//
return result;
}
/**
* determine a content is module or not ...
*
* @param {string} content a file content ...
* @returns
*/
function isModuleFromContent(content) {
//
const result = isDecoratorOfFromContent(
XBaseDescriptor.DecoratorTypes.Module,
content
);
//
return result;
}
/**
* determine a file is directive or not ...
*
* @param {string} file a file path ...
* @returns
*/
async function isDirective(file) {
//
const result = await isDecoratorOf(
XBaseDescriptor.DecoratorTypes.Directive,
file
);
//
return result;
}
/**
* determine a content is directive or not ...
*
* @param {string} content a file content ...
* @returns
*/
function isDirectiveFromContent(content) {
//
const result = isDecoratorOfFromContent(
XBaseDescriptor.DecoratorTypes.Directive,
content
);
//
return result;
}
/**
* determine a file is component or not ...
*
* @param {string} file a file path ...
* @returns
*/
async function isComponent(file) {
//
const result = await isDecoratorOf(
XBaseDescriptor.DecoratorTypes.Component,
file
);
//
return result;
}
/**
* determine a content is component or not ...
*
* @param {string} content a file content ...
* @returns
*/
function isComponentFromContent(content) {
//
const result = isDecoratorOfFromContent(
XBaseDescriptor.DecoratorTypes.Component,
content
);
//
return result;
}
/**
* determine a file is injectable or not ...
*
* @param {string} file a file path ...
* @returns
*/
async function isInjectable(file) {
//
const result = await isDecoratorOf(
XBaseDescriptor.DecoratorTypes.Injectable,
file
);
//
return result;
}
/**
* determine a content is injectable or not ...
*
* @param {string} content a file content ...
* @returns
*/
function isInjectableFromContent(content) {
//
const result = isDecoratorOfFromContent(
XBaseDescriptor.DecoratorTypes.Injectable,
content
);
//
return result;
}
//#endregion
/**
* retrieve required args and update a descriptor based on provided values ...
*
* @param {any} descriptor an instance of XDecoratorDescriptor object which is source ...
* @param {any} updateBy an instance of XDecoratorDescriptor object which used to update source ...
* @param {string|string[]} parts selected parts of XDecoratorDescriptor to update manually ...
* @param {string|string[]} objects selected objects which inserted into specified parts ...
* @returns update source descriptor ...
*/
function update(
descriptor,
updateBy,
parts,
objects
) {
//
// Prepare Result ...
let result = createDescriptor(descriptor);
//
//#region Validate Args ...
//
// Validate descriptor ...
if (
!descriptor ||
!isDescriptor(descriptor)
) {
return result;
}
//
// Validate Types ...
const decType = descriptor.type;
if (
!XBaseDescriptor.isValidDecoratorType(decType) ||
(
updateBy &&
isDescriptor(updateBy) &&
(
descriptor.type !== updateBy.type ||
!XBaseDescriptor.isValidDecoratorType(updateBy.type)
)
)
) {
return result;
}
//#endregion
//
//#region Handle UpdateBy ...
if (
updateBy &&
isDescriptor(updateBy)
) {
//
const descriptorKeys = Object
.keys(descriptor)
.filter(k => k !== 'raw' && k !== 'type');
//
const updateByKeys = Object
.keys(updateBy)
.filter(k => k !== 'raw' && k !== 'type');
//
const usedKeysForUpdate = [
//
// required keys is UpdateBy ...
...updateByKeys,
...descriptorKeys
.filter(k => !updateByKeys.includes(k))
];
//
for (const key of usedKeysForUpdate) {
//
// determines key type ...
const isArray = XBaseDescriptor
.isDecoratorPartArray(key);
//
// Update key valeu ...
result[key] = !isArray ?
updateByKeys.includes(key) ?
updateBy[key] :
descriptor[key] :
[
...(
XValueTools.hasChildArray(updateBy[key]) ?
updateBy[key] :
[]
),
...(
XValueTools
.hasChildArray(
descriptor[key]) ?
descriptor[key] :
[]
)
.filter(v => !(
XValueTools.hasChildArray(updateBy[key]) ?
updateBy[key] :
[]
)
.includes(v))
];
}
}
//#endregion
//
//#region Handle Objects and Parts ...
if (parts && objects) {
//
// Normalize Parts ...
const normalParts = XValueTools
.toNormalArray(parts)
.map(r => r.trim())
.filter(r =>
XValueTools.isValidArg(r) &&
XBaseDescriptor.isValidDecoratorPart(r) &&
XBaseDescriptor.isValidDecoratorPartForType(r, decType));
//
// Normalize Objects ...
const normalObjects = XValueTools
.toNormalArray(objects)
.map(r => XTypeDetectorTools.isString(r) ?
r.trim() :
r)
.filter(r => XValueTools.isValidArg(r));
//
if (
XValueTools.hasChildArray(normalParts) &&
XValueTools.hasChildArray(normalObjects)
) {
//
for (const object of normalObjects) {
for (const part of normalParts) {
//
const isArrayPartType = XBaseDescriptor
.isDecoratorPartArray(part);
if (!isArrayPartType) {
result[part] = object;
} else {
//
result[part] = [
...result[part]
.filter(r => r !== object),
object
];
}
}
}
}
}
//#endregion
//
return result;
}
//#endregion
//
// Module Exports ...
module.exports = {
//
isDescriptor,
toExpression,
createDescriptor,
extractDescriptor,
extractDescriptorFromContent,
//
hasDecorator,
hasDecoratorFromContent,
//
extractDecoratorContent,
extractDecoratorContentByContent,
//
isModule,
isDirective,
isComponent,
isInjectable,
isDecoratorOf,
getDecoratorType,
isModuleFromContent,
isDirectiveFromContent,
isComponentFromContent,
isInjectableFromContent,
isDecoratorOfFromContent,
getDecoratorTypeFromContent,
//
update,
}