commit ebb2c80b25322b0e9c8144443968c0aa9e9c4278 Author: Hadi Khazaee Asl Date: Wed Nov 11 19:28:11 2026 +0330 Initialize Commit ... diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..5c3456d --- /dev/null +++ b/.gitignore @@ -0,0 +1,92 @@ +# Logs +logs +*.log +npm-debug.log* +yarn-debug.log* +yarn-error.log* +lerna-debug.log* + +# Diagnostic reports (https://nodejs.org/api/report.html) +report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json + +# Runtime data +pids +*.pid +*.seed +*.pid.lock +.DS_Store + +# Directory for instrumented libs generated by jscoverage/JSCover +lib-cov + +# Coverage directory used by tools like istanbul +coverage +*.lcov + +# nyc test coverage +.nyc_output + +# node-waf configuration +.lock-wscript + +# Compiled binary addons (https://nodejs.org/api/addons.html) +build/Release + +# Dependency directories +node_modules/ +jspm_packages/ + +# TypeScript v1 declaration files +typings/ + +# TypeScript cache +*.tsbuildinfo + +# Optional npm cache directory +.npm + +# Optional eslint cache +.eslintcache + +# Optional REPL history +.node_repl_history + +# Output of 'npm pack' +*.tgz + +# Yarn Integrity file +.yarn-integrity + +# dotenv environment variables file +.env +.env.test + +# parcel-bundler cache (https://parceljs.org/) +.cache + +# next.js build output +.next + +# nuxt.js build output +.nuxt + +# vuepress build output +.vuepress/dist + +# Serverless directories +.serverless/ + +# FuseBox cache +.fusebox/ + +# DynamoDB Local files +.dynamodb/ + +# Webpack +.webpack/ + +# Electron-Forge +out/ + +# +package-lock.json \ No newline at end of file diff --git a/app.electron.js b/app.electron.js new file mode 100644 index 0000000..928647d --- /dev/null +++ b/app.electron.js @@ -0,0 +1,460 @@ +// +//#region Required Modules ... +const url = require("url"); +const path = require("path"); +const { Subject } = require("rxjs"); +const uuid = require("./modules/tools/x-uuid.tools"); +const XLogger = require("./modules/tools/x-logger.tools"); +const windowManager = require('./modules/tools/x-window.tools'); +const { XElectronChannel, XElectronMessage } = require('./modules/services/x-electron.service'); +const { app, shell, Tray, ipcMain, BrowserWindow, Menu } = require("electron"); +//#endregion + +// +//#region Prepare Required Config Data ... +// +// Set Environment ... +process.env.NODE_ENV = 'production'; + +// +const isDevelopment = process.env.NODE_ENV !== "production" ? true : false; // app.isPackaged; +const isMac = process.platform === "darwin" ? true : false; + +// +// Show Logs ... +const showLogs = false; + +// +// Show Debug Window ... +const showDebug = false; + +// +// Force Window to show fullscreen ... +const isFullscreen = false; + +// +// Show Window on Startup ... +const showWindowOnStartup = true; + +// +const iconPath = path.join(__dirname, "www/assets/icon/favicon.png"); +const trayIconPath = path.join(__dirname, "www/assets/icon/icon-16x16.png"); +//#endregion + +// +//#region Handle Logging ... +if (showLogs) { + XLogger.enableLogging(); +} else { + XLogger.disableLogging(); +} + +// +console.log('XLogger State: ', XLogger.isLoggingEnable()); +//#endregion + +// +//#region Global Objects ... +// +let tray; +let mainUrl; +let mainWindow; +let mainWindowID; + +// +const appId = uuid.generateUuid('XSdkManagerApp'); +//#endregion + +// +//#region Subscribers ... +// +const otherChannelsSubject = new Subject(); +const defaultChannelSubject = new Subject(); +const handShakeChannelSubject = new Subject(); + +// +// Register Handshake Handler ... +handShakeChannelSubject + .asObservable() + .subscribe(message => { + // + XLogger.logWarn( + XLogger.XLogMessage( + XLogger.XLogTag.Warn, + `Handshake Channel`, + [message] + ) + ); + }); + +// +// Register Default Handler ... +defaultChannelSubject + .asObservable() + .subscribe(message => { + // + XLogger.logWarn( + XLogger.XLogMessage( + XLogger.XLogTag.Warn, + `Default Channel`, + [message] + ) + ); + }); + +// +// Register Other Handler ... +otherChannelsSubject + .asObservable() + .subscribe(async message => { + // + XLogger.logWarn( + XLogger.XLogMessage( + XLogger.XLogTag.Warn, + `Other Channel`, + [message] + ) + ); + + // + // File Service ... + if (message && message.channel === XElectronChannel.FileService) { + await handleFileServiceAction(message); + } + + // + // Projects Service ... + if (message && message.channel === XElectronChannel.ProjectsService) { + await handleProjectsServiceAction(message); + } + }); +//#endregion + +// +//#region Creator Fuctions ... +/** + * Creat SysTray Object for using in app ... + */ +function createTray() { + // + // Create Tray Instance ... + tray = new Tray(trayIconPath); + XLogger.logDebug(XLogger.XLogMessage(XLogger.XLogTag.Debug, 'Tray Created ...')); + + // + // Attach Event Listener to Tray Click ... + tray.on("click", () => { + // + XLogger.logDebug(XLogger.XLogMessage(XLogger.XLogTag.Debug, 'Tray Clicked ...')); + + // + toggleMainWindow(); + }); + + // + // Attach Event Listener to Tray RightClick ... + tray.on("right-click", () => { + // + XLogger.logDebug(XLogger.XLogMessage(XLogger.XLogTag.Debug, 'Tray Right Clicked ...')); + + // + const contextMenu = Menu.buildFromTemplate([ + { + label: "quit", + click: () => { + // + app.isClosing = true; + app.quit(); + }, + }, + ]); + + // + tray.popUpContextMenu(contextMenu); + }); +} + +/** + * Create Main Window Instance ... + */ +function createWindow() { + // + // Create Main Window ... + mainWindow = new BrowserWindow({ + icon: iconPath, + show: showWindowOnStartup, + width: isDevelopment ? 1200 : 800, + height: isDevelopment ? 800 : 600, + webPreferences: { + nodeIntegration: true, + contextIsolation: false + }, + }); + + // + // Handle FullScreen state if Window shown on startup ... + if (isFullscreen && showWindowOnStartup) { + mainWindow.maximize(); + mainWindow.setFullScreen(true); + } + + // + // Generate Main Windows UUID ... + mainWindowID = uuid.generateUuid("XSdkManagerApp"); + mainWindow.name = mainWindowID; + XLogger.logDebug(XLogger.XLogMessage(XLogger.XLogTag.Debug, `Window ${mainWindowID} Created ...`)); + + // + // Fix new Window Open action ... + mainWindow.webContents.on("new-window", function (e, url) { + e.preventDefault(); + + // + XLogger.logDebug(XLogger.XLogMessage(XLogger.XLogTag.Debug, 'New Window Requested ...')); + + // + shell.openExternal(url); + }); + + // + // Handle load Main Url on Navigate for handling Navigation on Angular Apps ... + mainWindow.webContents.on("will-navigate", function (e, url) { + e.preventDefault(); + + // + XLogger.logDebug(XLogger.XLogMessage(XLogger.XLogTag.Debug, 'Window Will Navigate Called ...')); + + // + mainWindow.loadURL(mainUrl); + }); + + // + // Prepare Main Url ... + mainUrl = url.format({ + pathname: path.join(__dirname, "/www/index.html"), + protocol: "file", + slashes: true, + }); + + // + // Load Content on Main Window ... + mainWindow.loadURL(mainUrl); + + // + // Remove Browser Window Default menu ... + mainWindow.removeMenu(); + + // + // Open Dev Tools on Development environment ... + if (showDebug) { + // + mainWindow.webContents.openDevTools(); + XLogger.logDebug(XLogger.XLogMessage(XLogger.XLogTag.Debug, 'Window Dev Tools Opened ...')); + } + + // + // Handle Window Closed ... + mainWindow.on("closed", () => { + // + mainWindow = null; + windowManager.remove(mainWindowID); + + // + XLogger.logDebug(XLogger.XLogMessage(XLogger.XLogTag.Debug, `Window ${mainWindowID} Closed ...`)); + }); + + // + // Handle Window Close ... + mainWindow.on("close", (e) => { + // + if (!app.isClosing) { + // + e.preventDefault(); + + // + mainWindow.hide(); + + // + XLogger.logDebug(XLogger.XLogMessage(XLogger.XLogTag.Debug, `Window ${mainWindowID} Hided ...`)); + } + + // + return true; + }); + + // + // Send Handshake Message to Angular App for Notifing id of main window ... + mainWindow.webContents.on("did-finish-load", () => { + // + // Instancing new Message for Sending ... + const handshakeMsg = new XElectronMessage( + appId, + mainWindowID, + undefined, + undefined, + XElectronChannel.Handshake, + new Date().getTime() + ); + + // + // Sending Handshake Message to MainWindow ... + sendMessage(handshakeMsg); + + // + XLogger.logDebug(XLogger.XLogMessage(XLogger.XLogTag.Debug, `sending Handshake to Window ${mainWindowID} ...`)); + }); + + // + //#region IPC Handlers ... + // + // Register Event Handler for HandShake ... + ipcMain.on(XElectronChannel.Handshake, (event, message) => { + // + if (!message || !message.sender) { + return; + } + + // + const windowID = message.sender; + windowManager.set(windowID, mainWindow); + + // + handShakeChannelSubject.next(message); + }); + + // + // Register Event Handler for Message ... + ipcMain.on(XElectronChannel.Default, (event, message) => { + defaultChannelSubject.next(message); + }); + + // + const channels = Object.assign({}, XElectronChannel); + delete channels.Default; + delete channels.Handshake; + + // + Object.keys(channels).forEach(channel => { + // + // Register Event Handler for Message on other Channel ... + ipcMain.on(channels[channel], (event, message) => { + otherChannelsSubject.next(message); + }); + }); + //#endregion +} + +/** + * Toggle Show/Hide Main Window ... + */ +function toggleMainWindow() { + // + if (!mainWindow) { + return; + } + + // + XLogger.logDebug(XLogger.XLogMessage(XLogger.XLogTag.Debug, `Toggle Window ...`)); + + // + if (mainWindow.isVisible()) { + mainWindow.hide(); + } else { + // + if (isFullscreen) { + mainWindow.maximize(); + mainWindow.setFullScreen(true); + } + mainWindow.show(); + } +} +//#endregion + +// +//#region Event Emitters ... +/** + * attach event to call when it's ready, to app object ... + */ +app.whenReady().then(() => { + // + XLogger.logDebug(XLogger.XLogMessage(XLogger.XLogTag.Debug, `App Ready ...`)); + + // + createTray(); + createWindow(); +}); + +/** + * attach event to call when all application Windows closed, to app object ... + */ +app.on("window-all-closed", () => { + // + XLogger.logDebug(XLogger.XLogMessage(XLogger.XLogTag.Debug, `All Windows Closed ...`)); + + // + if (!isMac) { + app.quit(); + } +}); + +/** + * attach event to call when application activated, to app object ... + */ +app.on("activate", () => { + // + XLogger.logDebug(XLogger.XLogMessage(XLogger.XLogTag.Debug, `App Activated ...`)); + + // + if (!mainWindow) { + createWindow(); + } +}); +//#endregion + +// +//#region Window Comminucations ... +/** + * send a message to specified window ... + * + * @param {XElectronMessageDto} message the message which required to send ... + */ +function sendMessage(message) { + // + if (!message) { + return; + } + + // + if (!message.sender) { + message.sender = appId; + } + + // + if (!message.reciever) { + message.reciever = mainWindowID; + } + + // + let destWindow = undefined; + if (windowManager.count() === 0) { + destWindow = mainWindow; + } else { + destWindow = windowManager.get(message.reciever); + } + + // + if (!destWindow) { + // + const errorMessage = 'Dest Window not found ...'; + XLogger.logError(XLogger.XLogMessage(XLogger.XLogTag.Error, errorMessage)) + throw errorMessage; + } + + // + // Sending Message to Window ... + destWindow.webContents.send( + message.channel, + JSON.stringify(message) + ); +} +//#endregion diff --git a/modules/models/.gitkeep b/modules/models/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/modules/models/x-base.descriptor.js b/modules/models/x-base.descriptor.js new file mode 100644 index 0000000..7dfdddd --- /dev/null +++ b/modules/models/x-base.descriptor.js @@ -0,0 +1,1157 @@ +// +//#region Imports ... +const XValueTools = require('../tools/x-value.tools'); +const XTypeDectorTools = require('../tools/x-type-detector.tools'); +//#endregion + +// +//#region Constants ... +/** + * base usefull Expression keys ... + */ +const ExpressionKeys = { + From: 'from', + Enum: 'enum', + Type: 'type', + Class: 'class', + Const: 'const', + Export: 'export', + Import: 'import', + Public: 'public', + Exports: 'exports', + Private: 'private', + Extends: 'extends', + Abstract: 'abstract', + Interface: 'interface', + Implements: 'implements', + IGNORED_KEY: '|$IGNORED_KEY$|', +} + +/** + * all available content types for raw contents ... + */ +const ContentTypes = { + Array: 'array', + Object: 'object', + String: 'string', + Unknown: 'unknown', + NonString: 'non_string', + NonStringSelf: 'non_string_self', + NonStringHasClosure: 'non_string_has_closure', + NonStringHasProperty: 'non_string_has_property', +} + +/** + * ng files decorator types ... + */ +const DecoratorTypes = { + Module: 'module', + Unknown: 'unknown', + Component: 'component', + Directive: 'directive', + Injectable: 'injectable' +} + +/** + * all available decorator parts ... + */ +const DecoratorParts = { + Styles: 'styles', + Imports: 'imports', + Exports: 'exports', + Selector: 'selector', + Template: 'template', + Providers: 'providers', + StyleUrls: 'styleUrls', + Bootstrap: 'bootstrap', + ProvidedIn: 'providedIn', + TemplateUrl: 'templateUrl', + Declarations: 'declarations', + EntryComponents: 'entryComponents', + ChangeDetection: 'changeDetection', +} + +const ModuleDecoratorValidParts = [ + DecoratorParts.Imports, + DecoratorParts.Exports, + DecoratorParts.Bootstrap, + DecoratorParts.Providers, + DecoratorParts.Declarations, + DecoratorParts.EntryComponents, +]; + +const ComponentDecoratorValidParts = [ + DecoratorParts.Selector, + DecoratorParts.Template, + DecoratorParts.TemplateUrl, + DecoratorParts.Styles, + DecoratorParts.StyleUrls, + DecoratorParts.ChangeDetection, +]; + +const DirectiveDecoratorValidParts = [ + DecoratorParts.Selector +]; + +const InjectableDecoratorValidParts = [ + DecoratorParts.ProvidedIn +]; + +/** + * all available types for decorator parts ... + */ +const DecoratorPartTypes = { + Array: 'array', + String: 'string' +} +//#endregion + +// +//#region Content Type ... +/** + * check a proposed type is valid content type or not ... + * + * @param {string} type the proposed type to check ... + * @returns + */ +function isValidContentType(type = '') { + // + // Validate Args ... + if (!XValueTools.isValidArg(type)) { + return false; + } + + // + // Normalize Arg ... + type = type.trim(); + + // + let result = Object.values(ContentTypes).includes(type); + return result; +} + +/** + * retrieve a content type ... + * + * @param {string} content a content which going to check ... + * @returns a member of ContentTypes const ... + */ +function getContentType(content = '') { + // + // Validate Args ... + if (!XValueTools.isValidArg(content)) { + return ContentTypes.Unknown; + } + + // + if (XValueTools.isSurroundedObject(content)) { + return ContentTypes.Object; + } else if (XValueTools.isSurroundedArray(content)) { + return ContentTypes.Array; + } else if (XValueTools.isSurroundedString(content)) { + return ContentTypes.String; + } else if ( + content.includes(':') || + content.includes('=') + ) { + // + if ( + content.includes('{') && + content.includes('}') + ) { + return ContentTypes.NonStringHasClosure; + } else if ( + content.includes('[') && + content.includes(']') + ) { + return ContentTypes.NonStringHasClosure; + } else { + // + const colons = XValueTools.findAllIndexes(':', content); + if ( + !XValueTools.hasChildArray(colons) || + colons.length === 1 + ) { + return ContentTypes.NonStringSelf + } + + // + return ContentTypes.NonStringHasProperty; + } + } else { + return ContentTypes.NonString; + } +} +//#endregion + +// +//#region Decorator ... +/** + * determines a property name is valid in Decorator Object or not ... + * + * @param {string} part decorator object property name ... + * @returns is it valid or not ... + */ +function isValidDecoratorPart(part = DecoratorParts.Imports) { + // + // Validate Args ... + if (!XValueTools.isValidArg(part)) { + return false; + } + + // + result = Object.values(DecoratorParts).includes(part); + return result; +} + +/** + * determines a proposed value is valid decorator types or not ... + * + * @param {string} type a child of DecoratorTypes ... + * @returns proposed value is valid type or not ... + */ +function isValidDecoratorType(type = DecoratorTypes.Unknown) { + // + // Validate Args ... + if ( + !XValueTools.isValidArg(type) || + type === DecoratorTypes.Unknown + ) { + return false; + } + + // + result = Object.values(DecoratorTypes).includes(type); + return result; +} + +/** + * determines a part of decorator is valid for specified decorator type or not ... + * + * @param {string} part specified proposed part of DecoratorDescriptor ... + * @param {string} type specified proposed DecoratorType ... + * @returns part is valid for type or not ... + */ +function isValidDecoratorPartForType( + part = DecoratorParts.Imports, + type = DecoratorTypes.Unknown +) { + // + // Validate Args ... + if ( + !isValidDecoratorType(type) || + !isValidDecoratorPart(part) || + !XValueTools.isValidArg(part) || + !XValueTools.isValidArg(type) + ) { + return false; + } + + // + let result = false; + switch (type) { + // + case DecoratorTypes.Module: + result = ModuleDecoratorValidParts + .includes(part); + break; + + // + case DecoratorTypes.Component: + result = ComponentDecoratorValidParts + .includes(part); + break; + + // + case DecoratorTypes.Directive: + result = DirectiveDecoratorValidParts + .includes(part); + break; + + // + case DecoratorTypes.Injectable: + result = InjectableDecoratorValidParts + .includes(part); + break; + } + + // + return result; +} + +/** + * retrieve decorator specific part type ... + * + * @param {string} part Decorator Object property name ... + * @returns decorator part type ... + */ +function getDecoratorPartType(part) { + // + // Validate Args ... + if ( + !isValidDecoratorPart(part) && + !XValueTools.isValidArg(part) + ) { + return undefined; + } + + // + let result = ''; + + // + switch (part) { + // + // Array Parts ... + case DecoratorParts.Styles: + case DecoratorParts.Imports: + case DecoratorParts.Exports: + case DecoratorParts.Providers: + case DecoratorParts.StyleUrls: + case DecoratorParts.Bootstrap: + case DecoratorParts.Declarations: + case DecoratorParts.EntryComponents: + result = DecoratorPartTypes.Array; + break; + + // + // String Parts ... + case DecoratorParts.Selector: + case DecoratorParts.Template: + case DecoratorParts.ProvidedIn: + case DecoratorParts.TemplateUrl: + case DecoratorParts.ChangeDetection: + result = DecoratorPartTypes.String; + break; + } + + // + if (!XValueTools.isValidArg(result)) { + return undefined; + } + + // + return result; +} + +/** + * determines an specific part of decorator is in array type or not ... + * + * @param {string} part Decorator Object property name ... + * @returns + */ +function isDecoratorPartArray(part) { + // + // Validate Args ... + if ( + !isValidDecoratorPart(part) || + !XValueTools.isValidArg(part) + ) { + return false; + } + + // + // Retrieve Decorator Part Type ... + const type = getDecoratorPartType(part); + if (!XValueTools.isValidArg(type)) { + return false; + } + + // + const result = type === DecoratorPartTypes.Array; + return result; +} + +/** + * determines an specific part of decorator is in string type or not ... + * + * @param {string} part Decorator Object property name ... + * @returns + */ +function isDecoratorPartString(part) { + // + // Validate Args ... + if ( + !isValidDecoratorPart(part) || + !XValueTools.isValidArg(part) + ) { + return false; + } + + // + // Retrieve Decorator Part Type ... + const type = getDecoratorPartType(part); + if (!XValueTools.isValidArg(type)) { + return false; + } + + // + const result = type === DecoratorPartTypes.String; + return result; +} + +/** + * extract specified decorator part values from given content ... + * + * @param {string} part the part which reuire to extract from given text, which usually must be DecoratorParts value ... + * @param {string} content given content to tokenize ... + * @param {boolean} isArray determines the given token value is array or not ... + * @returns parsed token's value(s) ... + */ +function extractDecoratorPart( + part = '', + content = '', +) { + // + // Validate Args ... + if ( + !isValidDecoratorPart(part) || + !XValueTools.isValidArg(part) || + !XValueTools.isValidArg(content) + ) { + return undefined; + } + + // + const partType = getDecoratorPartType(part); + const isArray = isDecoratorPartArray(part); + + // + let listSeparator = ','; + let end = isArray ? ']' : '\''; + let start = isArray ? '[' : '\''; + + // + // find token index ... + let partIndex = content.indexOf(part); + if (partIndex === -1) { + return undefined; + } + + // + content = content.substring(partIndex); + partIndex = content.indexOf(part); + if (part === DecoratorParts.Template) { + // + const tIndex = content.indexOf(DecoratorParts.TemplateUrl); + if (partIndex === tIndex) { + return undefined; + } + } + + // + // find start and end index ... + let startIndex = content.indexOf(start, partIndex) + 1; + let endIndex = content.indexOf(end, startIndex) - 1; + + // + // Try to fix string interpolation ... + if (!isArray && (startIndex < 0 || endIndex < 0)) { + startIndex = content.indexOf('`', partIndex + part.length); + endIndex = content.indexOf('`', startIndex + 1); + } + + // + // Try to fix Object ... + if (!isArray && (startIndex < 0 || endIndex < 0)) { + startIndex = part.length; + endIndex = content.indexOf('`', startIndex + 1) > 0 ? + content.indexOf('`', startIndex + 1) : + content.indexOf(',', startIndex + 1) > 0 ? + content.indexOf(',', startIndex + 1) : + content.indexOf('}', startIndex + 1) > 0 ? + content.indexOf('}', startIndex + 1) : + -1; + } + + if (startIndex === -1 || endIndex === -1) { + return undefined; + } + + // + // define regExps for clearing content ... + const regExp = new RegExp( + ' |\n|', + 'g' + ); + + // + // Extract required content and remove all non required contents from it ... + let resultContent = content + .substr(startIndex, (endIndex - startIndex) + 1); + if (isArray) { + resultContent = resultContent.replace(regExp, '').trim(); + } else { + resultContent = resultContent + .replace(',', '') + .replace('}', '') + .replace(':', '').trim(); + } + if (!XValueTools.isValidArg(resultContent)) { + return isArray ? [] : ''; + } + + // + // check content is a list or not ... + const isMultipleDeclaration = resultContent.includes(listSeparator); + + // + // prepare result ... + const outOfClosedIndexes = XValueTools.findAllIndexesOutOfCloseds(listSeparator, resultContent); + const outOfClosedParts = XValueTools.sliceContent(outOfClosedIndexes, resultContent); + let result = isMultipleDeclaration ? + isArray ? + [...outOfClosedParts] : + resultContent : + isArray ? + [resultContent] : + resultContent; + result = isArray ? + result.filter(r => r.length > 0) : + result.trim(); + + // + return result; +} +//#endregion + +// +//#region Parsers ... +/** + * parse given content and extracts it's XKeyValueDescriptor childs ... + * + * @param {string} content a proposed content to parse ... + * @param {boolean} isInterface force parser to parse object content as an interface content, default is false ... + * @returns parsed collection of XKeyValueDescriptor object instance ... + */ +function parseContent( + content = '', + isInterface = false +) { + // + // Validate Args ... + if (!XValueTools.isValidArg(content)) { + return undefined; + } + + // + // Define Result Structure ... + let result = [{ + key: '', + value: undefined, + type: ContentTypes.Unknown, + }]; + result.pop(); + + // + const contentType = getContentType(content); + if (isValidContentType(contentType)) { + result.type = contentType; + } + + // + switch (contentType) { + // + // parse array contents ... + case ContentTypes.Array: + result = parseProperties( + content, + isInterface + ); + break; + + // + //parse object content ... + case ContentTypes.Object: + result = parseProperties( + content, + isInterface + ); + break; + + // + // add content it self ... + case ContentTypes.String: + result.push({ + type: contentType, + value: parseString(content), + key: ExpressionKeys.IGNORED_KEY, + }); + break; + + // + // add content it self without anything ... + case ContentTypes.NonString: + result.push({ + value: content, + type: contentType, + key: ExpressionKeys.IGNORED_KEY, + }); + break; + + // + // parse just one property ... + case ContentTypes.NonStringSelf: + break; + + // + // parse properties more than one ... + case ContentTypes.NonStringHasProperty: + break; + + // + // parse key and values ... + case ContentTypes.NonStringHasClosure: + break; + + // + case ContentTypes.Unknown: + default: + break; + } + + // + return result; +} + +/** + * parse properties of given content and extract it's values ... + * + * @param {string} content the content which going to parse ... + * @param {boolean} isInterface determines the props is for interface or not ... + * @returns parse props as a collection of key/value/type array ... + */ +function parseProperties( + content = '', + isInterface = false +) { + // + let result = [{ + key: '', + value: undefined, + type: ContentTypes.Unknown, + }]; + result.pop(); + + // + // Validate Args ... + if (!XValueTools.isValidArg(content)) { + return result; + } + + // + // Clear Surrounded Chars ... + if (XValueTools.isSurroundedArray(content)) { + content = XValueTools.clearArraySurround(content); + } else if (XValueTools.isSurroundedObject(content)) { + content = XValueTools.clearObjectSurround(content); + } + + // + let individualColonIndexes = []; + if (!!isInterface) { + individualColonIndexes = XValueTools.findAllIndexesOutOfCloseds(';', content); + } else { + individualColonIndexes = XValueTools.findAllIndexesOutOfCloseds(',', content); + } + + // + let parts = []; + if (XValueTools.hasChildArray(individualColonIndexes)) { + parts = XValueTools + .sliceContent(individualColonIndexes, content) + .filter(r => XValueTools.isValidArg(r)); + } else { + parts.push(content); + } + + // + for (const part of parts) { + // + const partType = getContentType(part); + + // + const individualSemicolonIndexes = XValueTools + .findAllIndexesOutOfCloseds( + [':', '='], + part + ); + + // + if (!XValueTools.hasChildArray(individualSemicolonIndexes)) { + // + const parsedContent = parseContent( + part, + isInterface + ) || []; + if (partType === ContentTypes.Object) { + result.push({ + type: partType, + value: parsedContent, + key: ExpressionKeys.IGNORED_KEY, + }); + } else { + result.push(...parsedContent); + } + continue; + } + + // + const sepIndex = individualSemicolonIndexes[0]; + const keyVal = XValueTools.sliceContent([sepIndex], part); + if ( + keyVal.length !== 2 || + !XValueTools.hasChildArray(keyVal) + ) { + continue; + } + + // + let parsedValue = parseContent( + keyVal[1], + isInterface + ); + let type = parsedValue.type || getContentType(keyVal[1]); + if ( + parsedValue.length === 1 && + XValueTools.hasChildArray(parsedValue) && + parsedValue[0].key === ExpressionKeys.IGNORED_KEY && + !Object.values([ContentTypes.Array, ContentTypes.Object]).includes(parsedValue[0].type) + ) { + parsedValue = parsedValue[0].value; + } + + // + result.push({ + type, + key: keyVal[0], + value: parsedValue + }); + } + + // + return result; +} + +/** + * parse a content as string ... + * + * @param {string} content the content which going to parsed ... + * @returns parsed string content ... + */ +function parseString(content = '') { + // + // Validate Args ... + if ( + !XValueTools.isValidArg(content) || + !XValueTools.isSurroundedString(content) + ) { + return ''; + } + + // + if ( + content.startsWith('\'') && + ( + XValueTools.endsWidth('\'', content) || + XValueTools.endsWidth('\',', content) || + XValueTools.endsWidth('\';', content) || + XValueTools.endsWidth('\'\n', content) + ) + ) { + // + const removeFromLastLength = XValueTools.endsWidth('\'', content) ? + 1 : + XValueTools.endsWidth('\',', content) || + XValueTools.endsWidth('\';', content) || + XValueTools.endsWidth('\'\n', content) ? + 2 : + 0; + + // + content = content.substring(1, content.length - removeFromLastLength); + content = XValueTools.surroundBy('\"', content); + } else if ( + content.startsWith('`') && + ( + XValueTools.endsWidth('\`', content) || + XValueTools.endsWidth('\`,', content) || + XValueTools.endsWidth('\`;', content) || + XValueTools.endsWidth('\`\n', content) + ) + ) { + content = XValueTools.surroundBy('\"', content); + } + + // + return content; +} +//#endregion + +// +//#region Expressions ... +function toExpression(content) { + // + let result = ''; + const isKeyValueType = XValueTools.isKeyValueType(content); + if (!isKeyValueType) { + // + const isContentArray = XTypeDectorTools.isArray(content); + if (isContentArray) { + // + const contentResults = ['']; + contentResults.pop(); + + // + for (const contentChild of content) { + // + const contentResult = toExpression(contentChild); + contentResults.push(contentResult); + } + + // + result += '[\n' + contentResults.join(',\n') + '\n]'; + } else { + result += content; + } + } else { + // + // Retrieve Type ... + const keyValType = content.type || ContentTypes.Unknown; + + // + let contentResult = ''; + switch (keyValType) { + // + // String ... + case ContentTypes.String: + // + let surroundSymbol = content.value.charAt(0); + contentResult = XValueTools.clearSurround(surroundSymbol, content.value); + + // + surroundSymbol = contentResult.charAt(0) || ''; + if (surroundSymbol !== '\'' && surroundSymbol !== '`') { + contentResult = XValueTools.surroundBy('\'', contentResult); + } + break; + + // + // NonString ... + case ContentTypes.NonString: + contentResult = content.value; + break; + + // + // Array ... + case ContentTypes.Array: + // + const arrayResult = ['']; + arrayResult.pop(); + + // + if (XTypeDectorTools.isString(content.value)) { + // + const normalContentValue = XValueTools.toNormalArray(content.value); + content.value = [ + ...normalContentValue + ] + } + for (const arrayChild of content.value) { + // + const arrayChildExp = toExpression(arrayChild); + arrayResult.push(arrayChildExp); + } + + // + // TODO: create a way to handle array or objects childs for join ... + let arrayResultContent = ''; + for (let i = 0; i < arrayResult.length; i++) { + // + const nextResult = arrayResult[i + 1]; + arrayResultContent += arrayResult[i] + ( + i < arrayResult.length - 1 ? + (XValueTools.isSurroundedArray(nextResult) || + XValueTools.isSurroundedObject(nextResult)) ? + ',\n' : + ', ' : + '' + ); + } + + // + contentResult = '[\n' + arrayResultContent + '\n]'; + break; + + // + // Object ... + case ContentTypes.Object: + // + let objectResult = '{\n'; + + // + for (let i = 0; i < content.value.length; i++) { + // + const arrayChild = content.value[i]; + const arrayChildExp = toExpression(arrayChild); + objectResult += ( + arrayChild.key !== ExpressionKeys.IGNORED_KEY ? + arrayChild.key + + ': ' : + '' + ) + + arrayChildExp + + ( + i === content.value.length - 1 ? + '' : + ',\n' + ); + } + + // + objectResult += '\n}'; + + // + contentResult = objectResult; + break; + } + + // + result += contentResult; + } + + // + return result; +} +//#endregion + +// +//#region Extractors ... +/** + * extract all occurance indexes of an identifier inside a content ... + * + * @param {string} identifier the value which going to search ... + * @param {string} content the content is going to searched for value ... + * @returns a collection of occurance indexes ... + */ +function extractIdentifierIndexes( + identifier = '', + content = '') { + // + // Prepare Result ... + let result = [0]; + result.pop(); + + // + // Validate Args ... + if ( + !XValueTools.isValidArg(content) || + !XValueTools.isValidArg(identifier) + ) { + return result; + } + + // + // Extract Identifiers ... + result = XValueTools. + findAllIndexes( + identifier, + content + ); + + // + return result; +} + +/** + * check an index of an identifier inside a content is same as identifier or not ... + * + * @param {string} identifier the value which going to search ... + * @param {number} index the item proposed index on content ... + * @param {string} content the content is going to searched for value ... + * @returns is it match identifier or not ... + */ +function validateIdentifierInContent( + identifier = '', + index = -1, + content = '' +) { + // + // Prepare Result ... + let result = false; + + // + // Validate Args ... + if ( + !XValueTools.isValidArg(content) || + !XValueTools.isValidArg(identifier) + ) { + return false; + } + + // + // Normalize Index ... + index = index < 0 ? 0 : index > content.length ? content.length : index; + + // + // + // Check Type after befre content ... + let startIndex = index - 1; + let endIndex = index + identifier.length + 1; + const tIdentifier = content.substring(startIndex, endIndex).trim(); + result = tIdentifier === identifier; + + // + return result; +} + +/** + * extract all occurance indexes of an identifier inside a content and Validate them ... + * + * @param {string} identifier the value which going to search ... + * @param {string} content the content is going to searched for value ... + * @returns a collection of occurance indexes ... + */ +function extractValidIdentifierIndexes( + identifier = '', + content = '' +) { + // + // Prepare Result ... + let result = [0]; + result.pop(); + + // + // Validate Args ... + if ( + !XValueTools.isValidArg(content) || + !XValueTools.isValidArg(identifier) + ) { + return result; + } + + // + // Extract Identifier Indexes ... + result = extractIdentifierIndexes( + identifier, + content + ); + + // + // Filter result to get Valid Identifiers ... + result = result.filter(i => validateIdentifierInContent + ( + identifier, + i, + content + ) + ); + + // + return result; +} + +/** + * determines a content expression starter is exported or not ... + * + * @param {number} index start index for checking export ... + * @param {string} content the content which reuired to check ... + * @returns is exported or not ... + */ +function checkIsExported( + index = 0, + content = '' +) { + // + // Prepare Result ... + let result = false; + + // + // Validate Args ... + if (!XValueTools.isValidArg(content)) { + return result; + } + + // + // Normalize Index ... + index = index < 0 ? 0 : index > content.length ? content.length : index; + + // + const startIndex = index - ExpressionKeys.Export.length - 1; + const endIndex = startIndex + ExpressionKeys.Export.length; + const identifier = content.substring(startIndex, endIndex).trim(); + result = identifier === ExpressionKeys.Export; + + // + return result; +} +//#endregion + +// +//#region Content Cleaners ... +/** + * clear all comments, regions symbols and non required signs from a content ... + * + * @param {string} content the content which used ... + * @returns cleared content ... + */ +function clearContent(content = '') { + // + // Validate Args ... + if (!XValueTools.isValidArg(content)) { + return ''; + } + + // + // Check Content contains Line Return or not ... + if (content.includes('\n')) { + content = content.split('\n') + .map(cc => cc.trim()) + .filter(cc => XValueTools.isValidArg(cc) && + !cc.startsWith('//') && + !cc.startsWith('#')) + .join('\n'); + } + + // + return content; +} +//#endregion + +// +// Module Exports ... +module.exports = { + // + ContentTypes, + ExpressionKeys, + DecoratorTypes, + DecoratorParts, + DecoratorPartTypes, + ModuleDecoratorValidParts, + ComponentDecoratorValidParts, + DirectiveDecoratorValidParts, + InjectableDecoratorValidParts, + + // + getContentType, + isValidContentType, + + // + extractDecoratorPart, + isValidDecoratorPart, + isValidDecoratorType, + getDecoratorPartType, + isDecoratorPartArray, + isDecoratorPartString, + isValidDecoratorPartForType, + + // + parseContent, + clearContent, + checkIsExported, + extractIdentifierIndexes, + validateIdentifierInContent, + extractValidIdentifierIndexes, + + // + toExpression, +} \ No newline at end of file diff --git a/modules/models/x-class.descriptor.js b/modules/models/x-class.descriptor.js new file mode 100644 index 0000000..06e9c6c --- /dev/null +++ b/modules/models/x-class.descriptor.js @@ -0,0 +1,622 @@ +// +//#region Imports ... +const XFileTools = require('../tools/x-file.tools'); +const XValueTools = require('../tools/x-value.tools'); +const XBaseDescriptor = require('./x-base.descriptor'); +const XDecoratorDescriptor = require('./x-decorator.descriptor'); +//#endregion + +/** + * check an object instance is ClassDescriptor or not ... + * + * @param {any} object proposed object to check ... + * @returns + */ +function isDescriptor(object) { + // + if (!object) { + return false; + } + + // + let result = false; + result = + object.hasOwnProperty('raw') && + Array.isArray(object.extends) && + object.hasOwnProperty('name') && + Array.isArray(object.implements) && + object.hasOwnProperty('extends') && + object.hasOwnProperty('isPublic') && + object.hasOwnProperty('decorator') && + object.hasOwnProperty('implements') && + object.hasOwnProperty('isExported') && + object.hasOwnProperty('isExtended') && + object.hasOwnProperty('isAbstract') && + object.hasOwnProperty('hasDecorator') && + object.hasOwnProperty('isImplemented'); + + // + return result; +} + +/** + * retrieve base or filled ClassDescriptor object instance ... + * + * @param {any} value a value provider object ... + * @returns an instance of ClassDescriptor object ... + */ +function createDescriptor(value) { + // + const result = { + raw: '', + name: '', + extends: [], + implements: [], + isPublic: true, + isExported: false, + isExtended: false, + isAbstract: false, + hasDecorator: false, + isImplemented: false, + decorator: { + ...XDecoratorDescriptor.createDescriptor() + }, + }; + + // + //#region Apply Props ... + if (value) { + // + //#region name ... + if (XValueTools.isValidArg(value.name)) { + result.name = value.name; + } + //#endregion + + // + //#region extends ... + if (XValueTools.hasChildArray(value.extends)) { + result.extends = [...value.extends]; + } + //#endregion + + // + //#region implements ... + if (XValueTools.hasChildArray(value.implements)) { + result.implements = [...value.implements]; + } + //#endregion + + // + //#region raw ... + if (XValueTools.isValidArg(value.raw)) { + result.raw = value.raw; + } + //#endregion + + // + //#region isPublic ... + if (!!value.isPublic) { + result.isPublic = true; + } else if (value.isPublic === false) { + result.isPublic = false; + } + //#endregion + + // + //#region isExported ... + if (!!value.isExported) { + result.isExported = true; + } + //#endregion + + // + //#region isExtended ... + if (!!value.isExtended) { + result.isExtended = true; + } + //#endregion + + // + //#region isAbstract ... + if (!!value.isAbstract) { + result.isAbstract = true; + } + //#endregion + + // + //#region hasDecorator ... + if (!!value.hasDecorator) { + result.hasDecorator = true; + } + //#endregion + + // + //#region decorator ... + if (!!result.hasDecorator && value.decorator) { + result.decorator = { + ...XDecoratorDescriptor.createDescriptor(value.decorator) + }; + } else { + result.decorator = undefined; + } + //#endregion + + // + //#region isImplemented ... + if (!!value.isImplemented) { + result.isImplemented = true; + } + //#endregion + } + //#endregion + + // + return result; +} + +/** + * converts an instance of Descriptor to Expression ... + * + * @param descriptor an instance of ClassDescriptor ... + * @returns creator string ... + */ +function toExpression( + descriptor = createDescriptor(), + forceClearContent = false, +) { + // + let result = ''; + + // + // Validate Arg ... + if (!isDescriptor(descriptor)) { + return result; + } + + // + let classContent = ''; + let classContentIndexers = XValueTools.findClosedContent('{', '}', descriptor.raw); + if (XValueTools.hasChildArray(classContentIndexers)) { + // + classContent = XValueTools + .clearObjectSurround(classContentIndexers[0].content); + + // + if (!!forceClearContent) { + classContent = XBaseDescriptor.clearContent(classContent); + } + } + + // + // Handle Class Decorator ... + if ( + !!descriptor.hasDecorator && + XValueTools.isValidArgs(descriptor.decorator.type) && + XBaseDescriptor.isValidDecoratorType(descriptor.decorator.type) + ) { + // + result += XDecoratorDescriptor + .toExpression(descriptor.decorator) + + '\n'; + } + + // + // Handle Class ... + result += + // + // Export ... + ( + descriptor.isExported ? + XBaseDescriptor.ExpressionKeys.Export + + ' ' : + '' + ) + + // + // Public or Private ... + ( + !descriptor.isPublic ? + XBaseDescriptor.ExpressionKeys.Private + + ' ' : + '' + ) + + // + // Abstract ... + ( + descriptor.isAbstract ? + XBaseDescriptor.ExpressionKeys.Abstract + + ' ' : + '' + ) + + // + // Class Definition ... + XBaseDescriptor.ExpressionKeys.Class + + ' ' + + descriptor.name + + ' ' + + // + // Extends ... + ( + descriptor.isExtended ? + XBaseDescriptor.ExpressionKeys.Extends + + ' ' + + descriptor.extends.join(', ') + + ' ' : + '' + ) + + // + // Implements ... + ( + descriptor.isImplemented ? + XBaseDescriptor.ExpressionKeys.Implements + + ' ' + + descriptor.implements.join(', ') + + ' ' : + '' + ) + + // + // Open Class ... + '{\n' + + // + // Class Content ... + ( + XValueTools.isValidArg(classContent) ? + classContent : + '' + ) + + // + // Close Class ... + '\n}'; + + // + return result; +} + +/** + * extract all exists ClassDescriptors ... + * + * @param {string} file a file path ... + * @returns a collection of ClassDescriptors ... + */ +async function extractDescriptors(file = '') { + // + if (!XFileTools.isFileExists(file)) { + return []; + } + + // + const fileContent = await XFileTools.readFile(file); + if (!XValueTools.isValidArg(fileContent)) { + return []; + } + + // + let result = [ + createDescriptor() + ]; + result.pop(); + + // + result = extractDescriptorsFromContent(fileContent); + + // + return result; +} + +/** + * extract all exists ClassDescriptors ... + * + * @param {string} content a file content ... + * @returns a collection of ClassDescriptors ... + */ +function extractDescriptorsFromContent(content = '') { + // + // Prepare result ... + let result = [ + createDescriptor() + ]; + result.pop(); + + // + // Validate Args ... + if ( + !XValueTools.isValidArg(content) || + !content.includes(XBaseDescriptor.ExpressionKeys.Class) + ) { + return result; + } + + // + // Extract all Key Indexes ... + const keyIndexes = XBaseDescriptor. + extractValidIdentifierIndexes(XBaseDescriptor.ExpressionKeys.Class, content); + + // + // Validate Keys Exists on Content ... + if (!XValueTools.hasChildArray(keyIndexes)) { + return result; + } + + // + // Loop through indexes ... + for (let index of keyIndexes) { + // + // create an empty instance of descriptor ... + let descriptor = { + ...createDescriptor() + } + + // + let startIndex = index; + let endIndex = content.indexOf('{', startIndex); + let rawIndexContents = XValueTools.findClosedContent('{', '}', content, endIndex); + if (!XValueTools.hasChildArray(rawIndexContents)) { + continue; + } + + // + let identifier = content.substring( + index + XBaseDescriptor.ExpressionKeys.Class.length, + endIndex + ).trim(); + + // + //#region HasExtends, Extends, HasImplements, Implements ... + // + const hasExtends = identifier.includes(XBaseDescriptor.ExpressionKeys.Extends); + const hasImplements = identifier.includes(XBaseDescriptor.ExpressionKeys.Implements); + + // + descriptor.isExtended = hasExtends; + descriptor.isImplemented = hasImplements; + + // + let extendsStartIndex = -1; + let implementsStartIndex = -1; + + // + // Extends ... + if (!!hasExtends) { + // + extendsStartIndex = identifier + .indexOf(XBaseDescriptor.ExpressionKeys.Extends) + + XBaseDescriptor.ExpressionKeys.Extends.length; + + // + let extendsIdentifier = identifier + .substring(extendsStartIndex) + .trim(); + if (extendsIdentifier + .includes(XBaseDescriptor.ExpressionKeys.Implements)) { + // + let extendsEndIndex = extendsIdentifier + .indexOf(XBaseDescriptor.ExpressionKeys.Implements); + extendsIdentifier = extendsIdentifier + .substring(0, extendsEndIndex) + .trim(); + } + + // + // Continue if it's not Valid ... + if (!XValueTools.isValidArg(extendsIdentifier)) { + continue; + } + + // + // Check if extends is Array or not ... + if (extendsIdentifier.includes(',')) { + descriptor.extends.push( + ...extendsIdentifier + .split(',') + .map(e => e.trim()) + .filter(e => XValueTools.isValidArg(e)) + ) + } else { + descriptor.extends.push(extendsIdentifier); + } + } + + // + // Implements ... + if (!!hasImplements) { + // + implementsStartIndex = identifier + .indexOf(XBaseDescriptor.ExpressionKeys.Implements) + + XBaseDescriptor.ExpressionKeys.Implements.length; + + // + let implementsIdentifier = identifier + .substring(implementsStartIndex) + .trim(); + if (implementsIdentifier + .includes(XBaseDescriptor.ExpressionKeys.Extends)) { + // + let implementsEndIndex = implementsIdentifier + .indexOf(XBaseDescriptor.ExpressionKeys.Extends); + implementsIdentifier = implementsIdentifier + .substring(0, implementsEndIndex) + .trim(); + } + + // + // Continue if it's not Valid ... + if (!XValueTools.isValidArg(implementsIdentifier)) { + continue; + } + + // + // Check if extends is Array or not ... + if (implementsIdentifier.includes(',')) { + descriptor.implements.push( + ...implementsIdentifier + .split(',') + .map(i => i.trim()) + .filter(i => XValueTools.isValidArg(i)) + ) + } else { + descriptor.implements.push(implementsIdentifier); + } + } + //#endregion + + // + //#region Class Name ... + let nameEndIndex = Math.min( + ...[ + extendsStartIndex, + implementsStartIndex, + identifier.length + ] + .filter(i => i >= 0) + ); + identifier = identifier + .substring(0, nameEndIndex) + .replace(XBaseDescriptor.ExpressionKeys.Extends, '') + .replace(XBaseDescriptor.ExpressionKeys.Implements, '') + .trim(); + + // + // Continue if class name is not valid ... + if (!XValueTools.isValidArg(identifier)) { + continue; + } + + // + // Set Descriptor name ... + descriptor.name = identifier; + //#endregion + + // + //#region Exported, Public, Abstract ... + // + const lengthForComeBack = + XBaseDescriptor.ExpressionKeys.Export.length + + XBaseDescriptor.ExpressionKeys.Public.length + + XBaseDescriptor.ExpressionKeys.Private.length + + XBaseDescriptor.ExpressionKeys.Abstract.length; + + // + startIndex = index - lengthForComeBack; + endIndex = index; + identifier = content + .substring(startIndex, endIndex) + .trim(); + + // + // Exported ... + descriptor.isExported = identifier.includes(XBaseDescriptor.ExpressionKeys.Export); + + // + // Public ... + descriptor.isPublic = identifier.includes(XBaseDescriptor.ExpressionKeys.Public) || + !identifier.includes(XBaseDescriptor.ExpressionKeys.Private); + + // + // Abstract ... + descriptor.isAbstract = identifier.includes(XBaseDescriptor.ExpressionKeys.Abstract); + //#endregion + + // + //#region Raw ... + let classStartIndex = Math.max( + ...[ + content.indexOf(XBaseDescriptor.ExpressionKeys.Export, startIndex), + content.indexOf(XBaseDescriptor.ExpressionKeys.Public, startIndex), + content.indexOf(XBaseDescriptor.ExpressionKeys.Private, startIndex), + content.indexOf(XBaseDescriptor.ExpressionKeys.Abstract, startIndex), + ] + .filter(i => i >= 0 && i <= rawIndexContents[0].start) + ); + let classEndIndex = rawIndexContents[0].end + 1; + descriptor.raw = content.substring(classStartIndex, classEndIndex); + //#endregion + + // + //#region Decorator ... + // + const forExtractDecoratorContentEndIndex = content.indexOf(descriptor.raw); + let forExtractDecoratorContent = content.substring(0, forExtractDecoratorContentEndIndex); + + // + let decoratorIndexes = XValueTools + .findAllIndexes('@(.*)\\({', forExtractDecoratorContent) + .map(index => { + return { + startIndex: index, + decoratorContentIndexer: XValueTools + .findClosedContent('({', '})', forExtractDecoratorContent, index)[0] + } + }); + let decoratorIndex = decoratorIndexes + .find(i => i.decoratorContentIndexer.end + 1 === classStartIndex - 1); + if ( + !decoratorIndex && + decoratorIndexes.length === 1 && + XValueTools.hasChildArray(decoratorIndexes) + ) { + // + decoratorIndex = { + // + ...decoratorIndexes[0], + + // + decoratorContentIndexer: { + // + ...decoratorIndexes[0] + .decoratorContentIndexer, + + // + end: classStartIndex - 1, + + // + content: content.substring( + decoratorIndexes[0] + .decoratorContentIndexer + .start, + classStartIndex - 1 + ), + } + }; + } + + // + if (decoratorIndex) { + // + identifier = forExtractDecoratorContent + .substring( + decoratorIndex.startIndex, + decoratorIndex.decoratorContentIndexer.end + 1 + ); + + // + const decorator = XDecoratorDescriptor.extractDescriptorFromContent(identifier); + if (!decorator) { + continue; + } + + // + descriptor.hasDecorator = true; + descriptor.decorator = { + ...decorator + }; + } + //#endregion + + // + result.push(descriptor); + } + + // + return result; +} + +// +// Module Exports ... +module.exports = { + // + isDescriptor, + toExpression, + createDescriptor, + extractDescriptors, + extractDescriptorsFromContent, +} \ No newline at end of file diff --git a/modules/models/x-const.descriptor.js b/modules/models/x-const.descriptor.js new file mode 100644 index 0000000..ae0c3c3 --- /dev/null +++ b/modules/models/x-const.descriptor.js @@ -0,0 +1,354 @@ +// +//#region Imports ... +const XFileTools = require('../tools/x-file.tools'); +const XValueTools = require('../tools/x-value.tools'); +const XBaseDescriptor = require('./x-base.descriptor'); +const XContentDescriptor = require('./x-content.descriptor'); +//#endregion + +/** + * check an object instance is ConstDescriptor or not ... + * + * @param {any} object proposed object to check ... + * @returns + */ +function isDescriptor(object) { + // + if (!object) { + return false; + } + + // + let result = false; + result = + object.hasOwnProperty('raw') && + object.hasOwnProperty('name') && + object.hasOwnProperty('content') && + object.hasOwnProperty('isExported'); + + // + return result; +} + +/** + * retrieve base or filled ConstDescriptor object instance ... + * + * @param {any} value a value provider object ... + * @returns an instance of ConstDescriptor object ... + */ +function createDescriptor(value) { + // + let result = { + raw: '', + name: '', + type: '', + content: { + ...XContentDescriptor.createDescriptor() + }, + isExported: false, + }; + + // + //#region Apply Value ... + if (value) { + // + //#region raw ... + if (XValueTools.isValidArg(value.raw)) { + result.raw = value.raw; + } + //#endregion + + // + //#region name ... + if (XValueTools.isValidArg(value.name)) { + result.name = value.name; + } + //#endregion + + // + //#region type ... + if (XValueTools.isValidArg(value.type)) { + result.type = value.type; + } + //#endregion + + // + //#region content ... + if ( + value.content && + XContentDescriptor.isDescriptor(value.content) + ) { + result.content = { ...value.content }; + } + //#endregion + + // + //#region isExported ... + if (!!value.isExported) { + result.isExported = value.isExported; + } + //#endregion + } + //#endregion + + // + return result; +} + +/** + * converts an instance of Descriptor to Expression ... + * + * @param descriptor an instance of ConstDescriptor ... + * @returns creator string ... + */ +function toExpression(descriptor = createDescriptor()) { + // + let result = ''; + + // + // Validate Arg ... + if (!isDescriptor(descriptor)) { + return result; + } + + // + result += ( + !!descriptor.isExported ? + XBaseDescriptor.ExpressionKeys.Export + ' ' : + '' + ) + + XBaseDescriptor.ExpressionKeys.Const + + ' ' + + descriptor.name + + ( + XValueTools.isValidArg(descriptor.type) ? + ': ' + + descriptor.type : + '' + ) + + ' = '; + + // + let contentExpression = XContentDescriptor.toExpression(descriptor.content, ':'); + if (XValueTools.isValidArg(contentExpression)) { + result += contentExpression; + } + + // + result += ';'; + + // + return result; +} + +/** + * extract all exists ConstDescriptors ... + * + * @param {string} file a file path ... + * @returns a collection of ConstDescriptors ... + */ +async function extractDescriptors(file = '') { + // + if (!XFileTools.isFileExists(file)) { + return []; + } + + // + const fileContent = await XFileTools.readFile(file); + if (!XValueTools.isValidArg(fileContent)) { + return []; + } + + // + let result = [ + createDescriptor() + ]; + result.pop(); + + // + result = extractDescriptorsFromContent(fileContent); + + // + return result; +} + +/** + * extract all exists ConstDescriptors ... + * + * @param {string} content a file content ... + * @returns a collection of ConstDescriptors ... + */ +function extractDescriptorsFromContent(content = '') { + // + // Prepare result ... + let result = [ + createDescriptor() + ]; + result.pop(); + + // + // Validate Args ... + if ( + !XValueTools.isValidArg(content) || + !content.includes(XBaseDescriptor.ExpressionKeys.Const) + ) { + return result; + } + + // + // Extract all Key Indexes ... + const keyIndexes = XBaseDescriptor. + extractValidIdentifierIndexes(XBaseDescriptor.ExpressionKeys.Const, content); + + // + // Validate Keys Exists on Content ... + if (!XValueTools.hasChildArray(keyIndexes)) { + return result; + } + + // + // Loop through indexes ... + for (let index of keyIndexes) { + // + let startIndex = index - 1; + let endIndex = index + XBaseDescriptor.ExpressionKeys.Const.length + 1; + + // + // create an empty instance of descriptor ... + let descriptor = { + ...createDescriptor() + } + + // + //#region Name and Type extractor ... + const nameEndIndex = content.indexOf('=', index); + identifier = content + .substring(index + XBaseDescriptor.ExpressionKeys.Const.length, nameEndIndex) + .trim(); + if (XValueTools.isValidArg(identifier)) { + // + // Check to Extract Type ... + if (identifier.includes(':')) { + // + startIndex = 0; + endIndex = identifier.indexOf(':', startIndex); + + // + descriptor.name = identifier + .substring(startIndex, endIndex) + .trim(); + + // + // Type extraction ... + startIndex = endIndex + 1; + descriptor.type = identifier + .substring(startIndex) + .trim(); + } else { + descriptor.name = identifier; + } + } + //#endregion + + // + //#region Extract isExported ... + const isExported = XBaseDescriptor.checkIsExported(index, content); + descriptor.isExported = isExported; + if (isExported) { + startIndex = index - XBaseDescriptor.ExpressionKeys.Export.length - 1; + } else { + startIndex = index; + } + //#endregion + + // + //#region Extract raw content ... + identifier = content.substring(startIndex); + startIndex = 0; + endIndex = XValueTools.findNearestIndex( + [ + ';', + '{', + '[', + '\n' + ], + identifier, + 0 // nameEndIndex - startIndex + ); + const nearestChar = identifier.charAt(endIndex); + if (nearestChar === '{') { + // + const closedItemsIndexes = XValueTools.findClosedContent('{', '}', identifier, endIndex); + if (!XValueTools.hasChildArray(closedItemsIndexes)) { + continue; + } + + // + endIndex = closedItemsIndexes[0].end; + } else if (nearestChar === '[') { + // + const closedItemsIndexes = XValueTools.findClosedContent('[', ']', identifier, endIndex); + if (!XValueTools.hasChildArray(closedItemsIndexes)) { + continue; + } + + // + endIndex = closedItemsIndexes[0].end; + } + + // + identifier = identifier + .substring(startIndex, endIndex + 1) + .trim(); + if (XValueTools.isValidArg(identifier)) { + descriptor.raw = identifier; + } + //#endregion + + // + //#region Parse Content ... + startIndex = identifier.indexOf('=', 0); + let contentContainer = identifier + .substring(startIndex + 1) + .trim() + + // + // Clear Content ... + contentContainer = XBaseDescriptor + .clearContent(contentContainer); + + // + const contentType = XBaseDescriptor.getContentType(contentContainer); + const parsedContents = XBaseDescriptor.parseContent(contentContainer) || []; + const contentDescriptor = XContentDescriptor.createDescriptor(); + + // + contentDescriptor.type = contentType; + contentDescriptor.childs = [ + ...parsedContents + ]; + + // + descriptor.content = { + ...contentDescriptor + }; + //#endregion + + // + result.push(descriptor); + } + + // + return result; +} + +// +// Module Exports ... +module.exports = { + // + isDescriptor, + toExpression, + createDescriptor, + extractDescriptors, + extractDescriptorsFromContent, +} \ No newline at end of file diff --git a/modules/models/x-content.descriptor.js b/modules/models/x-content.descriptor.js new file mode 100644 index 0000000..cc63554 --- /dev/null +++ b/modules/models/x-content.descriptor.js @@ -0,0 +1,154 @@ +// +//#region Imports ... +const XValueTools = require('../tools/x-value.tools'); +const XBaseDescriptor = require('./x-base.descriptor'); +const XKeyValueDescriptor = require('./x-key-value.descriptor'); +//#endregion + +/** + * check an object is valid ContentDescriptor object ... + * + * @param {any} object proposed object to check ... + * @returns + */ +function isDescriptor(object) { + // + let result = false; + result = object && + object.hasOwnProperty('type') && + object.hasOwnProperty('childs') && + Array.isArray(object.childs) && + ( + object.childs.length > 0 ? + object.childs.every(ch => XKeyValueDescriptor.isDescriptor(ch)) : + true + ); + + // + return result; +} + +/** + * converts an instance of Descriptor to Expression ... + * + * @param descriptor an instance of ContentDescriptor ... + * @param {string} assignSymbol property assign symbol ... + * @returns creator string ... + */ +function toExpression( + descriptor = createDescriptor(), + assignSymbol = ':', + separator = ',' +) { + // + let result = ''; + + // + // Validate Arg ... + if (!isDescriptor(descriptor)) { + return result; + } + + // + // Normalize Property Assign Symbol ... + assignSymbol = !XValueTools.isValidArg(assignSymbol) ? + ':' : + assignSymbol; + + // + const isArrayType = descriptor.type === XBaseDescriptor.ContentTypes.Array; + const isObjectType = descriptor.type === XBaseDescriptor.ContentTypes.Object; + + // + result += ( + isObjectType ? '{\n' : + isArrayType ? '[\n' : + '' + ); + + // + for (let i = 0; i < descriptor.childs.length; i++) { + // + const keyVal = descriptor.childs[i]; + const keyValExpression = XKeyValueDescriptor.toExpression(keyVal, assignSymbol); + + // + if (separator === ';') { + // + result += keyValExpression + ( + i === descriptor.childs.length - 1 ? + separator : + `${separator}\n` + ); + } else { + // + result += keyValExpression + ( + i === descriptor.childs.length - 1 ? + '' : + `${separator}\n` + ); + } + } + + // + result += ( + isObjectType ? '\n}' : + isArrayType ? '\n]' : + '' + ); + + // + return result; +} + +/** + * retrieve base or filled ContentDescriptor object instance ... + * + * @param {any} value value provider object instance ... + * @returns an instance of ContentDescriptor ... + */ +function createDescriptor(value) { + // + let result = { + type: XBaseDescriptor.ContentTypes.Unknown, + childs: [ + XKeyValueDescriptor.createDescriptor() + ] + }; + result.childs.pop(); + + // + //#region Apply Value ... + if (value) { + // + //#region type ... + if (XBaseDescriptor.isValidContentType(value.type)) { + result.type = value.type; + } + //#endregion + + // + //#region childs ... + if ( + XValueTools.hasChildArray(value.childs) && + value.childs.every(ch => XKeyValueDescriptor.isDescriptor(ch)) + ) { + result.childs = [ + ...value.childs + ]; + } + //#endregion + } + //#endregion + + // + return result; +} + +// +// Module Exports ... +module.exports = { + isDescriptor, + toExpression, + createDescriptor, +} \ No newline at end of file diff --git a/modules/models/x-decorator.descriptor.js b/modules/models/x-decorator.descriptor.js new file mode 100644 index 0000000..e58016c --- /dev/null +++ b/modules/models/x-decorator.descriptor.js @@ -0,0 +1,1237 @@ +// +//#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} 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} 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, +} \ No newline at end of file diff --git a/modules/models/x-enum.descriptor.js b/modules/models/x-enum.descriptor.js new file mode 100644 index 0000000..3a68233 --- /dev/null +++ b/modules/models/x-enum.descriptor.js @@ -0,0 +1,307 @@ +// +//#region Imports ... +const XFileTools = require('../tools/x-file.tools'); +const XValueTools = require('../tools/x-value.tools'); +const XBaseDescriptor = require('./x-base.descriptor'); +const XContentDescriptor = require('./x-content.descriptor'); +//#endregion + +/** + * check an object instance is EnumDescriptor or not ... + * + * @param {any} object proposed object to check ... + * @returns + */ +function isDescriptor(object) { + // + if (!object) { + return false; + } + + // + let result = false; + result = + object.hasOwnProperty('raw') && + object.hasOwnProperty('name') && + object.hasOwnProperty('content') && + object.hasOwnProperty('isExported'); + + // + return result; +} + +/** + * retrieve base or filled EnumDescriptor object instance ... + * + * @param {any} value a value provider object ... + * @returns an instance of EnumDescriptor object ... + */ +function createDescriptor(value) { + // + let result = { + raw: '', + name: '', + content: { + ...XContentDescriptor.createDescriptor() + }, + isExported: false, + } + + // + //#region Apply Value ... + if (value) { + // + //#region raw ... + if (XValueTools.isValidArg(value.raw)) { + result.raw = value.raw; + } + //#endregion + + // + //#region name ... + if (XValueTools.isValidArg(value.name)) { + result.name = value.name; + } + //#endregion + + // + //#region content ... + if ( + value.content && + XContentDescriptor.isDescriptor(value.content) + ) { + result.content = { + ...value.content + }; + } + //#endregion + + // + //#region isExported ... + if (!!value.isExported) { + result.isExported = value.isExported; + } + //#endregion + } + //#endregion + + // + return result; +} + +/** + * converts an instance of Descriptor to Expression ... + * + * @param descriptor an instance of EnumDescriptor ... + * @returns creator string ... + */ +function toExpression(descriptor = createDescriptor()) { + // + let result = ''; + + // + // Validate Arg ... + if (!isDescriptor(descriptor)) { + return result; + } + + // + result += ( + !!descriptor.isExported ? + XBaseDescriptor.ExpressionKeys.Export + ' ' : + '' + ) + + XBaseDescriptor.ExpressionKeys.Enum + + ' ' + + descriptor.name + + ' ' + + '{'; + + // + let contentExpression = XContentDescriptor.toExpression(descriptor.content, ' ='); + if (XValueTools.isValidArg(contentExpression)) { + // + if (XValueTools.isSurroundedArray(contentExpression)) { + contentExpression = XValueTools.clearArraySurround(contentExpression); + } else if (XValueTools.isSurroundedObject(contentExpression)) { + contentExpression = XValueTools.clearObjectSurround(contentExpression); + } + + // + if (XValueTools.isValidArg(contentExpression)) { + result += contentExpression; + } + } + + // + result += '}'; + + // + return result; +} + +/** + * extract all exists EnumDescriptors ... + * + * @param {string} file a file path ... + * @returns a collection of EnumDescriptor ... + */ +async function extractDescriptors(file = '') { + // + if (!XFileTools.isFileExists(file)) { + return []; + } + + // + const fileContent = await XFileTools.readFile(file); + if (!XValueTools.isValidArg(fileContent)) { + return []; + } + + // + let result = [ + createDescriptor() + ]; + result.pop(); + + // + result = extractDescriptorsFromContent(fileContent); + + // + return result; +} + +/** + * extract all exists EnumDescriptors ... + * + * @param {string} content a file content ... + * @returns a collection of EnumDescriptor ... + */ +function extractDescriptorsFromContent(content = '') { + // + // Prepare Result ... + let result = [ + createDescriptor() + ]; + result.pop(); + + // + // Validate Args ... + if ( + !XValueTools.isValidArg(content) || + !content.includes(XBaseDescriptor.ExpressionKeys.Enum) + ) { + return result; + } + + // + // Extract all key Indexes ... + const keyIndexes = XBaseDescriptor. + extractValidIdentifierIndexes(XBaseDescriptor.ExpressionKeys.Enum, content); + + // + // Validate them ... + if (!XValueTools.hasChildArray(keyIndexes)) { + return result; + } + + // + // Loop through indexes ... + for (const index of keyIndexes) { + // + let startIndex = index - 1; + let endIndex = index + XBaseDescriptor.ExpressionKeys.Enum.length + 1; + + // + // create an empty instance of descriptor ... + let descriptor = { + ...createDescriptor() + } + + // + //#region Name extractor ... + const nameEndIndex = content.indexOf('{', index); + identifier = content + .substring(index + XBaseDescriptor.ExpressionKeys.Enum.length, nameEndIndex) + .trim(); + if (XValueTools.isValidArg(identifier)) { + descriptor.name = identifier; + } + //#endregion + + // + //#region Extract isExported ... + const isExported = XBaseDescriptor.checkIsExported(index, content); + descriptor.isExported = isExported; + if (isExported) { + startIndex = index - XBaseDescriptor.ExpressionKeys.Export.length - 1; + } + //#endregion + + // + //#region Extract raw content ... + identifier = content.substring(startIndex); + let closedContenstIndexes = XValueTools.findClosedContent('{', '}', identifier); + if (!XValueTools.hasChildArray(closedContenstIndexes)) { + continue; + } + + // + startIndex = 0; + endIndex = closedContenstIndexes[0].end; + if (endIndex < 0) { + continue; + } + + // + const raw = identifier.substring(startIndex, endIndex + 1); + if (!XValueTools.isValidArg(raw)) { + continue; + } + + // + descriptor.raw = raw; + //#endregion + + // + //#region Parse Enum Content ... + startIndex = closedContenstIndexes[0].start; + endIndex = closedContenstIndexes[0].end + 1; + let contentContainer = identifier.substring(startIndex, endIndex); + contentContainer = XBaseDescriptor.clearContent(contentContainer); + + // + const contentType = XBaseDescriptor.getContentType(contentContainer); + const parsedContents = XBaseDescriptor.parseContent(contentContainer); + const contentDescriptor = XContentDescriptor.createDescriptor(); + + // + contentDescriptor.type = contentType; + contentDescriptor.childs = [ + ...parsedContents + ]; + + // + descriptor.content = { + ...contentDescriptor + }; + //#endregion + + // + result.push(descriptor); + } + + // + return result; +} + +// +// Moduile Exports ... +module.exports = { + // + isDescriptor, + toExpression, + createDescriptor, + extractDescriptors, + extractDescriptorsFromContent, +} \ No newline at end of file diff --git a/modules/models/x-export.descriptor.js b/modules/models/x-export.descriptor.js new file mode 100644 index 0000000..8b3d9ad --- /dev/null +++ b/modules/models/x-export.descriptor.js @@ -0,0 +1,480 @@ +// +//#region Imports ... +const XFileTools = require('../tools/x-file.tools'); +const XValueTools = require('../tools/x-value.tools'); +const XBaseDescriptor = require('./x-base.descriptor'); +//#endregion + +/** + * check an object instance is ExportDescriptor or not ... + * + * @param {any} object proposed object to check ... + * @returns + */ +function isDescriptor(object) { + // + if (!object) { + return false; + } + + // + let result = false; + result = Array.isArray(object.objects) && + object.hasOwnProperty('raw') && + object.hasOwnProperty('type') && + object.hasOwnProperty('module') && + object.hasOwnProperty('objects'); + + // + return result; +} + +/** + * retrieve base or filled ExportDescriptor object instance ... + * + * @param {any} value a value provider object ... + * @returns an instance of ExportDescriptor object ... + */ +function createDescriptor(value) { + // + let result = { + raw: '', + type: '', + module: '', + objects: [''] + } + result.objects.pop(); + + // + //#region Apply Value ... + if (value) { + // + //#region raw ... + if (XValueTools.isValidArg(value.raw)) { + result.raw = value.raw; + } + //#endregion + + // + //#region type ... + if ( + XValueTools.isValidArg(value.type) || + XBaseDescriptor.isValidContentType(value.type) + ) { + result.type = value.type; + } + //#endregion + + // + //#region module .. + if (XValueTools.isValidArg(value.module)) { + result.module = value.module; + } + //#endregion + + // + //#region objects ... + if (XValueTools.hasChildArray(value.objects)) { + result.objects = [ + ...value.objects + ]; + } + //#endregion + } + //#endregion + + // + return result; +} + +/** + * converts an instance of Descriptor to Expression ... + * + * @param descriptor an instance of ExportDescriptor ... + * @returns creator string ... + */ +function toExpression(descriptor = createDescriptor()) { + // + let result = ''; + + // + // Validate Arg ... + if (!isDescriptor(descriptor)) { + return result; + } + + // + result += XBaseDescriptor.ExpressionKeys.Export + + ' '; + + // + //#region objects ... + // + if (descriptor.type === XBaseDescriptor.ContentTypes.Object) { + // + let objectsIdentifier = descriptor.objects.join(', '); + objectsIdentifier = `{ ${objectsIdentifier} }`; + + // + result += objectsIdentifier; + } else { + result += descriptor.objects[0]; + } + + // + result += ' '; + //#endregion + + // + //#region module ... + result += XBaseDescriptor.ExpressionKeys.From + + ' ' + + XValueTools.surroundBy('\'', descriptor.module); + //#endregion + + // + result += ';' + + // + return result; +} + +/** + * extract all exists ExportDescriptor ... + * + * @param {string} file a file path ... + * @returns a collection of ExportDescriptor ... + */ +async function extractDescriptors(file = '') { + // + if (!XFileTools.isFileExists(file)) { + return []; + } + + // + const fileContent = await XFileTools.readFile(file); + if (!XValueTools.isValidArg(fileContent)) { + return []; + } + + // + let result = [ + createDescriptor() + ]; + result.pop(); + + // + result = extractDescriptorsFromContent(fileContent); + + // + return result; +} + +/** + * extract all exists ExportDescriptor ... + * + * @param {string} content a file content ... + * @returns a collection of ExportDescriptor ... + */ +function extractDescriptorsFromContent(content = '') { + // + // Prepare Result ... + let result = [ + createDescriptor() + ]; + result.pop(); + + // + // Validate Args ... + if ( + !XValueTools.isValidArg(content) || + !content.includes(XBaseDescriptor.ExpressionKeys.Export) + ) { + return result; + } + + // + // Extract all key Indexes ... + const keyIndexes = XBaseDescriptor. + extractValidIdentifierIndexes(XBaseDescriptor.ExpressionKeys.Export, content) + .filter(i => { + // + // Exports ... + let startIndex = i; + let key = XBaseDescriptor.ExpressionKeys.Exports; + let endIndex = startIndex + key.length; + let subStr = content.substring(startIndex, endIndex); + if (subStr === key) { + return false; + } + + // + // Const ... + startIndex = i + XBaseDescriptor.ExpressionKeys.Export.length + 1; + key = XBaseDescriptor.ExpressionKeys.Const; + endIndex = startIndex + key.length; + subStr = content.substring(startIndex, endIndex); + if (subStr === key) { + return false; + } + + // + // Enum ... + key = XBaseDescriptor.ExpressionKeys.Enum; + endIndex = startIndex + key.length; + subStr = content.substring(startIndex, endIndex); + if (subStr === key) { + return false; + } + + // + // Type ... + key = XBaseDescriptor.ExpressionKeys.Type; + endIndex = startIndex + key.length; + subStr = content.substring(startIndex, endIndex); + if (subStr === key) { + return false; + } + + // + // Class ... + key = XBaseDescriptor.ExpressionKeys.Class; + endIndex = startIndex + key.length; + subStr = content.substring(startIndex, endIndex); + if (subStr === key) { + return false; + } + + // + // Interface ... + key = XBaseDescriptor.ExpressionKeys.Interface; + endIndex = startIndex + key.length; + subStr = content.substring(startIndex, endIndex); + if (subStr === key) { + return false; + } + + // + return true; + }); + + // + // Validate them ... + if (!XValueTools.hasChildArray(keyIndexes)) { + return result; + } + + // + // Loop through indexes ... + for (const index of keyIndexes) { + // + // create an empty instance of descriptor ... + let descriptor = { + ...createDescriptor() + } + + // + let startIndex = index; + let endIndex = XValueTools.findNearestIndex( + [ + ';', + '\n' + ], + content, + startIndex + ); + const nearestChar = content.charAt(endIndex); + if (nearestChar === ';') { + endIndex++; + } + + // + let identifier = content + .substring(startIndex, endIndex) + .trim(); + + // + // Check Identifier must includes FROM ... + if (!identifier.includes(XBaseDescriptor.ExpressionKeys.From)) { + continue; + } + + // + //#region raw ... + const raw = identifier; + descriptor.raw = raw; + //#endregion + + // + const fromIndex = identifier.indexOf(XBaseDescriptor.ExpressionKeys.From); + + // + //#region extracts Objects ... + startIndex = XBaseDescriptor.ExpressionKeys.Import.length; + endIndex = fromIndex; + identifier = identifier + .substring(startIndex, endIndex) + .trim(); + + // + // Clear Unused Content ... + identifier = XBaseDescriptor.clearContent(identifier); + + // + // Clear Also \n ... + identifier = XValueTools.clearContent('\n', identifier); + + // + if (XValueTools.isSurroundedObject(identifier)) { + // + // Clear Object Surround ... + identifier = XValueTools.clearObjectSurround(identifier); + + // + // Extract Imported Objects ... + let importedObjects = identifier + .split(',') + .map(o => o.trim()) + .filter(o => XValueTools.isValidArg(o)); + + // + descriptor.type = XBaseDescriptor.ContentTypes.Object; + descriptor.objects = [ + ...importedObjects + ]; + } else { + // + descriptor.type = XBaseDescriptor.ContentTypes.String; + descriptor.objects.push(identifier) + } + //#endregion + + // + //#region Module ... + startIndex = fromIndex + XBaseDescriptor.ExpressionKeys.From.length; + identifier = raw + .substring(startIndex) + .trim(); + identifier = XValueTools.findClosedStrings(identifier)[0].content; + if (XValueTools.isSurroundedString(identifier)) { + // + const surroundSymbol = identifier.charAt(0); + identifier = XValueTools.clearSurround(surroundSymbol, identifier); + } + + // + descriptor.module = identifier; + //#endregion + + // + result.push(descriptor); + } + + // + return result; +} + +// +//#region Custom Actions ... +function update( + descriptors, + addOrUpdates +) { + // + // Prepare Result ... + let result = [createDescriptor()]; + result.pop(); + + // + //#region Validate Args ... + // + // Validate Descriptors ... + if (XValueTools.hasChildArray(descriptors)) { + // + // Validate All Objects is Descriptor ... + const isAllIsImport = descriptors.every(d => isDescriptor(d)); + if (!isAllIsImport) { + return result; + } + + // + result = [ + ...descriptors + ]; + } + + // + // Validate addOrUpdates ... + if (XValueTools.hasChildArray(addOrUpdates)) { + // + // Validate All Objects is Descriptor ... + const isAllIsImport = addOrUpdates.every(d => isDescriptor(d)); + if (!isAllIsImport) { + return result; + } + } else { + return result; + } + //#endregion + + // + for (const desc of addOrUpdates) { + // + // Find same Module if exists ... + // + let descriptor = createDescriptor(desc); + + // + let existsModuleIndex = result.findIndex(d => descriptor.module === d.module); + if (existsModuleIndex >= 0) { + // + descriptor = result[existsModuleIndex]; + let mustAddObjects = desc.objects.filter(o => o.includes('*') || + !descriptor.objects.includes(o)); + if (XValueTools.hasChildArray(mustAddObjects)) { + descriptor.objects = [ + ...descriptor.objects, + ...mustAddObjects + ]; + } + + // + result[existsModuleIndex] = { + ...descriptor + }; + } else { + // + let mustAddObjects = descriptor.objects.filter(o => o.includes('*') || + result + .map(d => d.objects) + .every(objects => !objects.includes(o)) + ); + + // + descriptor.objects = [ + ...mustAddObjects + ]; + + // + result.push(descriptor); + } + } + + // + return result; +} +//#endregion + +// +// Moduile Exports ... +module.exports = { + // + isDescriptor, + toExpression, + createDescriptor, + extractDescriptors, + extractDescriptorsFromContent, + + // + update, +} \ No newline at end of file diff --git a/modules/models/x-file.descriptor.js b/modules/models/x-file.descriptor.js new file mode 100644 index 0000000..f893d45 --- /dev/null +++ b/modules/models/x-file.descriptor.js @@ -0,0 +1,353 @@ +// +//#region Imports ... +const XFileTools = require('../tools/x-file.tools'); +const XValueTools = require('../tools/x-value.tools'); +const XBaseDescriptor = require('./x-base.descriptor'); +const XEnumDescriptor = require('./x-enum.descriptor'); +const XTypeDescriptor = require('./x-type.descriptor'); +const XClassDescriptor = require('./x-class.descriptor'); +const XConstDescriptor = require('./x-const.descriptor'); +const XImportDescriptor = require('./x-import.descriptor'); +const XExportDescriptor = require('./x-export.descriptor'); +const XInterfaceDescriptor = require('./x-interface.descriptor'); +//#endregion + +/** + * check an object instance is XFileDescriptor or not ... + * + * @param {any} object proposed object to check ... + * @returns + */ +function isDescriptor(object) { + // + if (!object) { + return false; + } + + // + let result = false; + result = + Array.isArray(object.types) && + object.hasOwnProperty('types') && + // + Array.isArray(object.enums) && + object.hasOwnProperty('enums') && + // + Array.isArray(object.consts) && + object.hasOwnProperty('consts') && + // + Array.isArray(object.classes) && + object.hasOwnProperty('classes') && + // + Array.isArray(object.imports) && + object.hasOwnProperty('imports') && + // + Array.isArray(object.exports) && + object.hasOwnProperty('exports') && + // + Array.isArray(object.interfaces) && + object.hasOwnProperty('interfaces'); + + // + return result; +} + +/** + * retrieve base or filled XFileDescriptor object instance ... + * + * @param {any} value a value provider object ... + * @returns an instance of XFileDescriptor object ... + */ +function createDescriptor(value) { + // + let result = { + types: [XTypeDescriptor.createDescriptor()], + enums: [XEnumDescriptor.createDescriptor()], + consts: [XConstDescriptor.createDescriptor()], + classes: [XClassDescriptor.createDescriptor()], + imports: [XImportDescriptor.createDescriptor()], + exports: [XExportDescriptor.createDescriptor()], + interfaces: [XInterfaceDescriptor.createDescriptor()], + }; + + // + result.types.pop(); + result.enums.pop(); + result.consts.pop(); + result.classes.pop(); + result.imports.pop(); + result.exports.pop(); + result.interfaces.pop(); + + // + //#region Apply Value ... + if (value) { + // + //#region types ... + if (XValueTools.hasChildArray(value.types)) { + result.types = [ + ...value.types + ]; + } + //#endregion + + // + //#region enums ... + if (XValueTools.hasChildArray(value.enums)) { + result.enums = [ + ...value.enums + ]; + } + //#endregion + + // + //#region consts ... + if (XValueTools.hasChildArray(value.consts)) { + result.consts = [ + ...value.consts + ]; + } + //#endregion + + // + //#region classes ... + if (XValueTools.hasChildArray(value.classes)) { + result.classes = [ + ...value.classes + ]; + } + //#endregion + + // + //#region imports ... + if (XValueTools.hasChildArray(value.imports)) { + result.imports = [ + ...value.imports + ]; + } + //#endregion + + // + //#region exports ... + if (XValueTools.hasChildArray(value.exports)) { + result.exports = [ + ...value.exports + ]; + } + //#endregion + + // + //#region interfaces ... + if (XValueTools.hasChildArray(value.interfaces)) { + result.interfaces = [ + ...value.interfaces + ]; + } + //#endregion + } + //#endregion + + // + return result; +} + +/** + * converts an instance of Descriptor to Expression ... + * + * @param descriptor an instance of XFileDescriptor ... + * @returns creator string ... + */ +function toExpression(descriptor = createDescriptor()) { + // + let result = ''; + + // + // Validate Arg ... + if (!isDescriptor(descriptor)) { + return result; + } + + // + //#region Imports ... + if (XValueTools.hasChildArray(descriptor.imports)) { + // + const expression = descriptor.imports + .map(d => XImportDescriptor + .toExpression(d) + ).join('\n'); + + // + result += expression + '\n\n'; + } + //#endregion + + // + //#region Enums ... + if (XValueTools.hasChildArray(descriptor.enums)) { + // + const expression = descriptor.enums + .map(d => XEnumDescriptor + .toExpression(d) + ).join('\n'); + + // + result += expression + '\n\n'; + } + //#endregion + + // + //#region Types ... + if (XValueTools.hasChildArray(descriptor.types)) { + // + const expression = descriptor.types + .map(d => XTypeDescriptor + .toExpression(d) + ).join('\n'); + + // + result += expression + '\n\n'; + } + //#endregion + + // + //#region Interfaces ... + if (XValueTools.hasChildArray(descriptor.interfaces)) { + // + const expression = descriptor.interfaces + .map(d => XInterfaceDescriptor + .toExpression(d) + ).join('\n'); + + // + result += expression + '\n\n'; + } + //#endregion + + // + //#region Consts ... + if (XValueTools.hasChildArray(descriptor.consts)) { + // + const expression = descriptor.consts + .map(d => XConstDescriptor + .toExpression(d) + ).join('\n'); + + // + result += expression + '\n\n'; + } + //#endregion + + // + //#region Classes ... + if (XValueTools.hasChildArray(descriptor.classes)) { + // + const expression = descriptor.classes + .map(d => XClassDescriptor + .toExpression(d) + ).join('\n'); + + // + result += expression + '\n\n'; + } + //#endregion + + // + //#region Exports ... + if (XValueTools.hasChildArray(descriptor.exports)) { + // + const expression = descriptor.exports + .map(d => XExportDescriptor + .toExpression(d) + ).join('\n'); + + // + result += expression + '\n\n'; + } + //#endregion + + // + if (XValueTools.endsWidth('\n', result)) { + result = result.substring(0, result.length - 1); + } + + // + return result; +} + +/** + * extract all exists XFileDescriptors ... + * + * @param {string} file a file path ... + * @returns a collection of XFileDescriptors ... + */ +async function extractDescriptor(file = '') { + // + let result = createDescriptor(); + + // + if (!XFileTools.isFileExists(file)) { + return undefined; + } + + // + const fileContent = await XFileTools.readFile(file); + if (!XValueTools.isValidArg(fileContent)) { + return undefined; + } + + // + result = extractDescriptorFromContent(fileContent); + return result; +} + +/** + * extract all exists XFileDescriptors ... + * + * @param {string} content a file content ... + * @returns a collection of XFileDescriptors ... + */ +function extractDescriptorFromContent(content = '') { + // + // Prepare result ... + let result = createDescriptor(); + + // + // Validate Args ... + if (!XValueTools.isValidArg(content)) { + return undefined; + } + + // + const types = XTypeDescriptor.extractDescriptorsFromContent(content); + const enums = XEnumDescriptor.extractDescriptorsFromContent(content); + const consts = XConstDescriptor.extractDescriptorsFromContent(content); + const classes = XClassDescriptor.extractDescriptorsFromContent(content); + const exports = XExportDescriptor.extractDescriptorsFromContent(content); + const imports = XImportDescriptor.extractDescriptorsFromContent(content); + const interfaces = XInterfaceDescriptor.extractDescriptorsFromContent(content); + + // + result = { + types, + enums, + consts, + imports, + exports, + classes, + interfaces, + }; + + // + return result; +} + +// +// Module Exports ... +module.exports = { + // + isDescriptor, + toExpression, + createDescriptor, + extractDescriptor, + extractDescriptorFromContent, +} \ No newline at end of file diff --git a/modules/models/x-import.descriptor.js b/modules/models/x-import.descriptor.js new file mode 100644 index 0000000..d4c575d --- /dev/null +++ b/modules/models/x-import.descriptor.js @@ -0,0 +1,423 @@ +// +//#region Imports ... +const XFileTools = require('../tools/x-file.tools'); +const XValueTools = require('../tools/x-value.tools'); +const XBaseDescriptor = require('./x-base.descriptor'); +//#endregion + +/** + * check an object instance is ImportDescriptor or not ... + * + * @param {any} object proposed object to check ... + * @returns + */ +function isDescriptor(object) { + // + if (!object) { + return false; + } + + // + let result = false; + result = Array.isArray(object.objects) && + object.hasOwnProperty('raw') && + object.hasOwnProperty('type') && + object.hasOwnProperty('module') && + object.hasOwnProperty('objects'); + + // + return result; +} + +/** + * retrieve base or filled ImportDescriptor object instance ... + * + * @param {any} value a value provider object ... + * @returns an instance of ImportDescriptor object ... + */ +function createDescriptor(value) { + // + let result = { + raw: '', + type: '', + module: '', + objects: [''] + } + result.objects.pop(); + + // + //#region Apply Value ... + if (value) { + // + //#region raw ... + if (XValueTools.isValidArg(value.raw)) { + result.raw = value.raw; + } + //#endregion + + // + //#region type ... + if ( + XValueTools.isValidArg(value.type) || + XBaseDescriptor.isValidContentType(value.type) + ) { + result.type = value.type; + } + //#endregion + + // + //#region module .. + if (XValueTools.isValidArg(value.module)) { + result.module = value.module; + } + //#endregion + + // + //#region objects ... + if (XValueTools.hasChildArray(value.objects)) { + result.objects = [ + ...value.objects + ]; + } + //#endregion + } + //#endregion + + // + return result; +} + +/** + * converts an instance of Descriptor to Expression ... + * + * @param descriptor an instance of ImportDescriptor ... + * @returns creator string ... + */ +function toExpression(descriptor = createDescriptor()) { + // + let result = ''; + + // + // Validate Arg ... + if (!isDescriptor(descriptor)) { + return result; + } + + // + result += XBaseDescriptor.ExpressionKeys.Import + + ' '; + + // + //#region objects ... + // + if (descriptor.type === XBaseDescriptor.ContentTypes.Object) { + // + let objectsIdentifier = descriptor.objects.join(', '); + objectsIdentifier = `{ ${objectsIdentifier} }`; + + // + result += objectsIdentifier; + } else { + result += descriptor.objects[0]; + } + + // + result += ' '; + //#endregion + + // + //#region module ... + result += XBaseDescriptor.ExpressionKeys.From + + ' ' + + XValueTools.surroundBy('\'', descriptor.module); + //#endregion + + // + result += ';' + + // + return result; +} + +/** + * extract all exists ImportDescriptor ... + * + * @param {string} file a file path ... + * @returns a collection of ImportDescriptor ... + */ +async function extractDescriptors(file = '') { + // + if (!XFileTools.isFileExists(file)) { + return []; + } + + // + const fileContent = await XFileTools.readFile(file); + if (!XValueTools.isValidArg(fileContent)) { + return []; + } + + // + let result = [ + createDescriptor() + ]; + result.pop(); + + // + result = extractDescriptorsFromContent(fileContent); + + // + return result; +} + +/** + * extract all exists ImportDescriptor ... + * + * @param {string} content a file content ... + * @returns a collection of ImportDescriptor ... + */ +function extractDescriptorsFromContent(content = '') { + // + // Prepare Result ... + let result = [ + createDescriptor() + ]; + result.pop(); + + // + // Validate Args ... + if ( + !XValueTools.isValidArg(content) || + !content.includes(XBaseDescriptor.ExpressionKeys.Import) + ) { + return result; + } + + // + // Extract all key Indexes ... + const keyIndexes = XBaseDescriptor. + extractValidIdentifierIndexes(XBaseDescriptor.ExpressionKeys.Import, content); + + // + // Validate them ... + if (!XValueTools.hasChildArray(keyIndexes)) { + return result; + } + + // + // Loop through indexes ... + for (const index of keyIndexes) { + // + // create an empty instance of descriptor ... + let descriptor = { + ...createDescriptor() + } + + // + let startIndex = index; + let endIndex = XValueTools.findNearestIndex( + [ + ';', + '\n' + ], + content, + startIndex + ); + const nearestChar = content.charAt(endIndex); + if (nearestChar === ';') { + endIndex++; + } + + // + let identifier = content + .substring(startIndex, endIndex) + .trim(); + + // + // Check Identifier must includes FROM ... + if (!identifier.includes(XBaseDescriptor.ExpressionKeys.From)) { + continue; + } + + // + //#region raw ... + const raw = identifier; + descriptor.raw = raw; + //#endregion + + // + const fromIndex = identifier.indexOf(XBaseDescriptor.ExpressionKeys.From); + + // + //#region extracts Objects ... + startIndex = XBaseDescriptor.ExpressionKeys.Import.length; + endIndex = fromIndex; + identifier = identifier + .substring(startIndex, endIndex) + .trim(); + + // + // Clear Unused Content ... + identifier = XBaseDescriptor.clearContent(identifier); + + // + // Clear Also \n ... + identifier = XValueTools.clearContent('\n', identifier); + + // + if (XValueTools.isSurroundedObject(identifier)) { + // + // Type ... + descriptor.type = XBaseDescriptor.ContentTypes.Object; + + // + // Clear Object Surround ... + identifier = XValueTools.clearObjectSurround(identifier); + + // + // Extract Imported Objects ... + let importedObjects = identifier + .split(',') + .map(o => o.trim()) + .filter(o => XValueTools.isValidArg(o)); + + // + descriptor.objects = [ + ...importedObjects + ]; + } else { + // + descriptor.type = XBaseDescriptor.ContentTypes.String; + descriptor.objects.push(identifier) + } + //#endregion + + // + //#region Module ... + startIndex = fromIndex + XBaseDescriptor.ExpressionKeys.From.length; + identifier = raw + .substring(startIndex) + .trim(); + identifier = XValueTools.findClosedStrings(identifier)[0].content; + if (XValueTools.isSurroundedString(identifier)) { + // + const surroundSymbol = identifier.charAt(0); + identifier = XValueTools.clearSurround(surroundSymbol, identifier); + } + + // + descriptor.module = identifier; + //#endregion + + // + result.push(descriptor); + } + + // + return result; +} + +// +//#region Custom Actions ... +function update( + descriptors, + addOrUpdates +) { + // + // Prepare Result ... + let result = [createDescriptor()]; + result.pop(); + + // + //#region Validate Args ... + // + // Validate Descriptors ... + if (XValueTools.hasChildArray(descriptors)) { + // + // Validate All Objects is Descriptor ... + const isAllIsImport = descriptors.every(d => isDescriptor(d)); + if (!isAllIsImport) { + return result; + } + + // + result = [ + ...descriptors + ]; + } + + // + // Validate addOrUpdates ... + if (XValueTools.hasChildArray(addOrUpdates)) { + // + // Validate All Objects is Descriptor ... + const isAllIsImport = addOrUpdates.every(d => isDescriptor(d)); + if (!isAllIsImport) { + return result; + } + } else { + return result; + } + //#endregion + + // + for (const desc of addOrUpdates) { + // + // Find same Module if exists ... + // + let descriptor = createDescriptor(desc); + + // + let existsModuleIndex = result.findIndex(d => descriptor.module === d.module); + if (existsModuleIndex >= 0) { + // + descriptor = result[existsModuleIndex]; + let mustAddObjects = desc.objects.filter(o => o.includes('*') || + !descriptor.objects.includes(o)); + if (XValueTools.hasChildArray(mustAddObjects)) { + descriptor.objects = [ + ...descriptor.objects, + ...mustAddObjects + ]; + } + + // + result[existsModuleIndex] = { + ...descriptor + }; + } else { + // + let mustAddObjects = descriptor.objects + .filter(o => o.includes('*') || + result + .map(d => d.objects) + .every(objects => !objects.includes(o)) + ); + + // + descriptor.objects = [ + ...mustAddObjects + ]; + + // + result.push(descriptor); + } + } + + // + return result; +} +//#endregion + +// +// Moduile Exports ... +module.exports = { + // + isDescriptor, + toExpression, + createDescriptor, + extractDescriptors, + extractDescriptorsFromContent, + // + update, +} \ No newline at end of file diff --git a/modules/models/x-interface.descriptor.js b/modules/models/x-interface.descriptor.js new file mode 100644 index 0000000..12d2058 --- /dev/null +++ b/modules/models/x-interface.descriptor.js @@ -0,0 +1,380 @@ +// +//#region Imports ... +const XFileTools = require('../tools/x-file.tools'); +const XValueTools = require('../tools/x-value.tools'); +const XBaseDescriptor = require('./x-base.descriptor'); +const XContentDescriptor = require('./x-content.descriptor'); +//#endregion + +/** + * check an object instance is InterfaceDescriptor or not ... + * + * @param {any} object proposed object to check ... + * @returns + */ +function isDescriptor(object) { + // + if (!object) { + return false; + } + + // + let result = false; + result = + object.hasOwnProperty('raw') && + object.hasOwnProperty('name') && + Array.isArray(object.extends) && + object.hasOwnProperty('extends') && + object.hasOwnProperty('isExtended') && + object.hasOwnProperty('isExported'); + + // + return result; +} + +/** + * retrieve base or filled InterfaceDescriptor object instance ... + * + * @param {any} value a value provider object ... + * @returns an instance of InterfaceDescriptor object ... + */ +function createDescriptor(value) { + // + let result = { + raw: '', + name: '', + extends: [''], + isExtended: false, + isExported: false, + properties: { + ...XContentDescriptor.createDescriptor() + }, + }; + result.extends.pop(); + + // + //#region Apply Value ... + if (value) { + // + //#region raw ... + if (XValueTools.isValidArg(value.raw)) { + result.raw = value.raw; + } + //#endregion + + // + //#region name ... + if (XValueTools.isValidArg(value.name)) { + result.name = value.name; + } + //#endregion + + // + //#region isExported ... + if (!!value.isExported) { + result.isExported = value.isExported; + } + //#endregion + + // + //#region isExtended ... + if (!!value.isExtended) { + result.isExtended = value.isExtended; + } + //#endregion + + // + //#region extends ... + if (XValueTools.hasChildArray(value.extends)) { + result.extends = [ + ...value.extends + ]; + } + //#endregion + + // + //#region properties ... + if ( + value.properties && + XContentDescriptor.isDescriptor(value.properties) + ) { + result.properties = { + ...value.properties + }; + } + //#endregion + } + //#endregion + + // + return result; +} + +/** + * converts an instance of Descriptor to Expression ... + * + * @param descriptor an instance of InterfaceDescriptor ... + * @returns creator string ... + */ +function toExpression(descriptor = createDescriptor()) { + // + let result = ''; + + // + // Validate Arg ... + if (!isDescriptor(descriptor)) { + return result; + } + + // + result += ( + !!descriptor.isExported ? + XBaseDescriptor.ExpressionKeys.Export + ' ' : + '' + ) + + XBaseDescriptor.ExpressionKeys.Interface + + ' ' + + descriptor.name + + ' ' + + ( + !!descriptor.isExtended && + XValueTools.hasChildArray(descriptor.extends) ? + XBaseDescriptor.ExpressionKeys.Extends + + ' ' + + descriptor.extends.join(', ') + + ' ' : + '' + ); + + // + let contentExpression = XContentDescriptor.toExpression(descriptor.properties, ':', ';'); + if (XValueTools.isValidArg(contentExpression)) { + result += contentExpression; + } + + // + return result; +} + +/** + * extract all exists InterfaceDescriptors ... + * + * @param {string} file a file path ... + * @returns a collection of InterfaceDescriptors ... + */ +async function extractDescriptors(file = '') { + // + if (!XFileTools.isFileExists(file)) { + return []; + } + + // + const fileContent = await XFileTools.readFile(file); + if (!XValueTools.isValidArg(fileContent)) { + return []; + } + + // + let result = [ + createDescriptor() + ]; + result.pop(); + + // + result = extractDescriptorsFromContent(fileContent); + + // + return result; +} + +/** + * extract all exists InterfaceDescriptors ... + * + * @param {string} content a file content ... + * @returns a collection of InterfaceDescriptors ... + */ +function extractDescriptorsFromContent(content = '') { + // + // Prepare result ... + let result = [ + createDescriptor() + ]; + result.pop(); + + // + // Validate Args ... + if ( + !XValueTools.isValidArg(content) || + !content.includes(XBaseDescriptor.ExpressionKeys.Interface) + ) { + return result; + } + + // + // Extract all Key Indexes ... + const keyIndexes = XBaseDescriptor. + extractValidIdentifierIndexes(XBaseDescriptor.ExpressionKeys.Interface, content); + + // + // Validate Keys Exists on Content ... + if (!XValueTools.hasChildArray(keyIndexes)) { + return result; + } + + // + // Loop through indexes ... + for (let index of keyIndexes) { + // + let startIndex = index - 1; + let endIndex = index + XBaseDescriptor.ExpressionKeys.Interface.length + 1; + + // + // create an empty instance of descriptor ... + let descriptor = { + ...createDescriptor() + } + + // + //#region Extract isExported ... + const isExported = XBaseDescriptor.checkIsExported(index, content); + descriptor.isExported = isExported; + if (isExported) { + startIndex = index - XBaseDescriptor.ExpressionKeys.Export.length - 1; + } else { + startIndex = index; + } + //#endregion + + // + // Closed Item ... + let closedContents = XValueTools.findClosedContent('{', '}', content, index); + if (!XValueTools.hasChildArray(closedContents)) { + continue; + } + + // + let interfaceContentIndexer = closedContents[0]; + endIndex = interfaceContentIndexer.start - 1; + + // + identifier = content + .substring(startIndex, endIndex) + .trim(); + + // + //#region extract Name, Extends ... + let name = ''; + let nameCandidate = identifier + .replace(XBaseDescriptor.ExpressionKeys.Export, '') + .replace(XBaseDescriptor.ExpressionKeys.Interface, '') + .trim(); + let extendsIdentifiers = nameCandidate; + if (nameCandidate.includes(XBaseDescriptor.ExpressionKeys.Extends)) { + // + // Name ... + let nameEndIndex = nameCandidate.indexOf(XBaseDescriptor.ExpressionKeys.Extends); + nameCandidate = nameCandidate + .substring(0, nameEndIndex) + .trim(); + + // + //isExtended ... + descriptor.isExtended = true; + extendsIdentifiers = extendsIdentifiers + .substring(nameEndIndex + XBaseDescriptor.ExpressionKeys.Extends.length) + .trim(); + + // + if ( + !XValueTools.isValidArg(nameCandidate) || + !XValueTools.isValidArg(extendsIdentifiers) + ) { + continue; + } + + // + // Extends ... + descriptor.extends = [ + ...extendsIdentifiers + .split(',') + .map(e => e.trim()) + .filter(e => XValueTools.isValidArg(e)) + ]; + + // + name = nameCandidate; + } else { + name = nameCandidate; + } + + // + if (!XValueTools.isValidArg(name)) { + continue; + } + + // + descriptor.name = name; + //#endregion + + // + //#region extract Content ... + let contentContainer = interfaceContentIndexer.content; + + // + // Clear Content ... + contentContainer = XBaseDescriptor + .clearContent(contentContainer); + + // + const contentType = XBaseDescriptor.getContentType(contentContainer); + const parsedContents = XBaseDescriptor.parseContent( + contentContainer, + true + ); + const contentDescriptor = XContentDescriptor.createDescriptor(); + + // + contentDescriptor.type = contentType; + contentDescriptor.childs = [ + ...parsedContents + ]; + + // + descriptor.properties = { + ...contentDescriptor + } + //#endregion + + // + //#region Extract raw content ... + // + endIndex = interfaceContentIndexer.end + 1; + identifier = content + .substring(startIndex, endIndex) + .trim(); + if (!XValueTools.isValidArg(identifier)) { + continue; + } + + // + descriptor.raw = identifier; + //#endregion + + // + result.push(descriptor); + } + + // + return result; +} + +// +// Module Exports ... +module.exports = { + // + isDescriptor, + toExpression, + createDescriptor, + extractDescriptors, + extractDescriptorsFromContent, +} \ No newline at end of file diff --git a/modules/models/x-key-value.descriptor.js b/modules/models/x-key-value.descriptor.js new file mode 100644 index 0000000..2e20ca8 --- /dev/null +++ b/modules/models/x-key-value.descriptor.js @@ -0,0 +1,118 @@ +// +//#region Imports ... +const XValueTools = require('../tools/x-value.tools'); +const XBaseDescriptor = require('./x-base.descriptor'); +//#endregion + +/** + * check an object is valid key/value object ... + * @param {any} object proposed object to check ... + * @returns + */ +function isDescriptor(object) { + // + let result = false; + result = object && + object.hasOwnProperty('key') && + object.hasOwnProperty('type') && + object.hasOwnProperty('value'); + + // + return result; +} + +/** + * retrieve base or filled KeyValueProvider object instance ... + * + * @param {any} value value provider object instance ... + * @returns an instance of KeyValueDescriptor ... + */ +function createDescriptor(value) { + // + const result = { + key: '', + value: undefined, + type: XBaseDescriptor.ContentTypes.Unknown, + }; + + // + //#region Apply Value ... + if (value) { + // + //#region key ... + if (XValueTools.isValidArg(value.key)) { + result.key = value.key; + } + //#endregion + + // + //#region type ... + if ( + XValueTools.isValidArg(value.type) && + XBaseDescriptor.isValidContentType(value.type) + ) { + result.type = value.type; + } + //#endregion + + // + //#region value ... + if (value.value) { + result.value = value.value; + } + //#endregion + } + //#endregion + + // + return result; +} + +/** + * converts an instance of Descriptor to Expression ... + * + * @param descriptor an instance of KeyValueDescriptor ... + * @param {string} assignSymbol property assign symbol ... + * @returns creator string ... + */ +function toExpression( + descriptor = createDescriptor(), + assignSymbol = '' +) { + // + let result = ''; + + // + // Validate Args ... + if (!isDescriptor(descriptor)) { + return result; + } + + // + // Normalize Assign Symbol ... + assignSymbol = !XValueTools.isValidArg(assignSymbol) ? + '' : + assignSymbol; + + // + // Handle Key ... + if (descriptor.key !== XBaseDescriptor.ExpressionKeys.IGNORED_KEY) { + result += descriptor.key + assignSymbol + ' '; + } + + // + // Handle Value ... + const valueExpression = XBaseDescriptor.toExpression(descriptor); + result += valueExpression; + + // + return result; +} + +// +// Module Exports ... +module.exports = { + isDescriptor, + toExpression, + createDescriptor, +} \ No newline at end of file diff --git a/modules/models/x-localization.descriptor.js b/modules/models/x-localization.descriptor.js new file mode 100644 index 0000000..8f7f4db --- /dev/null +++ b/modules/models/x-localization.descriptor.js @@ -0,0 +1,527 @@ +// +//#region Imports ... +const XFileTools = require('../tools/x-file.tools'); +const XValueTools = require('../tools/x-value.tools'); +const XBaseDescriptor = require('./x-base.descriptor'); +const XConstDescriptor = require('./x-const.descriptor'); +const XContentDescriptor = require('./x-content.descriptor'); +//#endregion + +// +//#region Constants ... +/** + * all possible usage of localeResources ... + */ +const LocalizationResourceIdentifiers = { + ResourceIDs: 'ResourceIDs.', + XResourceIDs: 'XResourceIDs.', + XAppResourceIDs: 'AppResourceIDs.', + ThisResourceIDs: 'this.ResourceIDs.', + ThisAppResourceIDs: 'this.AppResourceIDs.', +}; +//#endregion + +// +//#region ResourceIDsDescriptor ... +/** + * check an object instance is ResourceIDsDescriptor or not ... + * + * @param {any} object proposed object to check ... + * @returns + */ +function isResourceIDsDescriptor(object) { + // + if (!object) { + return false; + } + + // + let result = false; + result = + object.hasOwnProperty('resourceIds') && + object.hasOwnProperty('appResourceIds') && + Array.isArray(object.resourceIds) && + Array.isArray(object.appResourceIds); + + // + return result; +} + +/** + * retrieve base or filled ResourceIDsDescriptor object instance ... + * + * @param {any} value a value provider object ... + * @returns an instance of ResourceIDsDescriptor object ... + */ +function createResourceIDsDescriptor(value) { + // + let result = { + resourceIds: [''], + appResourceIds: [''] + } + result.resourceIds.pop(); + result.appResourceIds.pop(); + + // + //#region Apply Value ... + if (value) { + // + //#region ResourceIDs ... + if (XValueTools.hasChildArray(value.resourceIds)) { + result.resourceIds = [ + ...value.resourceIds + ]; + } + //#endregion + + // + //#region appResourceIds ... + if (XValueTools.hasChildArray(value.appResourceIds)) { + result.appResourceIds = [ + ...value.appResourceIds + ]; + } + //#endregion + } + //#endregion + + // + return result; +} + +/** + * extract exists used ResourceIds form files ... + * + * @param {string|string[]} files a file(s) path ... + * @returns an instance of ResourceIDsDescriptor ... + */ +async function extractResourceIDsDescriptor(files) { + // + // Prepare Result ... + let result = createResourceIDsDescriptor(); + + // + // Normalize Files ... + const normalFiles = XValueTools.toNormalArray(files); + + // + // Validate Args ... + if ( + !XValueTools.hasChildArray(normalFiles) || + !normalFiles.every(file => XFileTools.isFileExists(file)) + ) { + return result; + } + + // + const readFileContentTasks = normalFiles.map(file => XFileTools.readFile(file)); + const fileContents = await Promise.all(readFileContentTasks); + if (!XValueTools.hasChildArray(fileContents)) { + return result; + } + + // + result = extractResourceIDsDescriptorFromContent(fileContents); + + // + return result; +} + +/** + * extract exists ResourceIDsDescriptor from file contents ... + * + * @param {string|string[]} contents a file(s) content(s) ... + * @returns an instance of ResourceIDsDescriptor ... + */ +function extractResourceIDsDescriptorFromContent(contents) { + // + // Prepare Result ... + let result = createResourceIDsDescriptor(); + + // + // Validate Args ... + if (!contents) { + return result; + } + + // + // Normalize Contents ... + const normalContents = XValueTools + .toNormalArray(contents) + .map(c => c.trim()) + .filter(c => XValueTools.isValidArg(c)); + if (!XValueTools.hasChildArray(normalContents)) { + return result; + } + + // + // Loop through all normal contents and extract result ... + for (const content of normalContents) { + // + // Find all indexes in File for eachType ... + const indexes = XValueTools.findAllIndexes( + Object.values(LocalizationResourceIdentifiers), + content + ); + if (!XValueTools.hasChildArray(indexes)) { + continue; + } + + // + // Try to Parse Content by indexes ... + for (const idx of indexes) { + // + let identifierToken = content.substring(idx, idx + LocalizationResourceIdentifiers.ThisAppResourceIDs.length); + if (identifierToken.includes(LocalizationResourceIdentifiers.ThisAppResourceIDs)) { + identifierToken = identifierToken.includes(LocalizationResourceIdentifiers.ThisAppResourceIDs); + } else if (identifierToken.includes(LocalizationResourceIdentifiers.ThisResourceIDs)) { + identifierToken = LocalizationResourceIdentifiers.ThisResourceIDs; + } else if (identifierToken.includes(LocalizationResourceIdentifiers.XAppResourceIDs)) { + identifierToken = LocalizationResourceIdentifiers.XAppResourceIDs; + } else if (identifierToken.includes(LocalizationResourceIdentifiers.XResourceIDs)) { + identifierToken = LocalizationResourceIdentifiers.XResourceIDs; + } else if (identifierToken.includes(LocalizationResourceIdentifiers.ResourceIDs)) { + identifierToken = LocalizationResourceIdentifiers.ResourceIDs; + } else { + identifierToken = undefined; + } + + // + if (!XValueTools.isValidArg(identifierToken)) { + continue; + } + + // + let endIndex = XValueTools.findNearestIndex( + [ + ';', + '\"', + ',', + ' ', + ')', + '\n' + ], + content, + idx, + true + ); + + // + const identifier = content + .substring(idx, endIndex) + .replace(identifierToken, ''); + if (XValueTools.isValidArg(identifier)) { + // + switch (identifierToken) { + // + // ResourceIDs ... + case LocalizationResourceIdentifiers.ResourceIDs: + case LocalizationResourceIdentifiers.XResourceIDs: + case LocalizationResourceIdentifiers.ThisResourceIDs: + if (!result.resourceIds.includes(identifier)) { + result.resourceIds.push(identifier); + } + break; + + // + // AppResourceIDs ... + case LocalizationResourceIdentifiers.XAppResourceIDs: + case LocalizationResourceIdentifiers.ThisAppResourceIDs: + if (!result.appResourceIds.includes(identifier)) { + result.appResourceIds.push(identifier); + } + break; + } + } + } + } + + // + return result; +} +//#endregion + +// +//#region LocaleResourceItemDescriptor ... +function isLocaleResourceItemDescriptor(value) { + // + let result = false; + + // + result = value && + value.hasOwnProperty('id') && + value.hasOwnProperty('value'); + + // + return result; +} + +function createLocaleResourceItemDescriptor(value) { + // + let result = { + id: '', + value: '' + }; + + // + //#region Apply Value ... + if (value) { + // + //#region id ... + if (XValueTools.isValidArg(value.id)) { + result.id = value.id; + } + //#endregion + + // + //#region value ... + if (XValueTools.isValidArg(value.value)) { + result.value = value.value; + } + //#endregion + } + //#endregion + + // + return result; +} +//#endregion + +// +//#region LocalizationDescriptor ... +function isLocalizationDescriptor(value) { + // + let result = false; + + // + result = value && + value.hasOwnProperty('name') && + value.hasOwnProperty('locale') && + value.hasOwnProperty('language') && + value.hasOwnProperty('direction') && + value.hasOwnProperty('resources') && + Array.isArray(value.resources) && + (XValueTools.hasChildArray(value.resources) ? + value.resources.every(r => isLocaleResourceItemDescriptor(r)) : true); + + // + return result; +} + +function createLocalizationDescriptor(value) { + // + let result = { + name: '', + locale: '', + language: '', + direction: '', + resources: [ + createLocaleResourceItemDescriptor() + ] + }; + result.resources.pop(); + + // + //#region Apply Value ... + if (value) { + // + //#region name ... + if (XValueTools.isValidArg(value.name)) { + result.name = value.name; + } + //#endregion + + // + //#region locale ... + if (XValueTools.isValidArg(value.locale)) { + result.locale = value.locale; + } + //#endregion + + // + //#region language ... + if (XValueTools.isValidArg(value.language)) { + result.language = value.language; + } + //#endregion + + // + //#region direction ... + if (XValueTools.isValidArg(value.direction)) { + result.direction = value.direction; + } + //#endregion + + // + //#region resources ... + if ( + XValueTools.hasChildArray(value.resources) && + value.resources.every(r => isLocaleResourceItemDescriptor(r)) + ) { + result.resources = [ + ...value.resources + ]; + } + //#endregion + } + //#endregion + + // + return result; +} + +function extractLocalizationDescriptors( + constDescriptor = XConstDescriptor.createDescriptor() +) { + // + let result = [ + createLocalizationDescriptor() + ]; + result.pop(); + + // + // Validate Args ... + if ( + !constDescriptor || + !XConstDescriptor.isDescriptor(constDescriptor) || + !XValueTools.hasChildArray(constDescriptor.content.childs) + ) { + return result; + } + + // + // extract childs of content ... + for (const child of constDescriptor.content.childs) { + // + const localizationDescriptor = createLocalizationDescriptor(); + for (const value of child.value) { + // + if (value.key !== 'resources') { + localizationDescriptor[value.key] = XValueTools.toStringExpression(value.value); + } else { + localizationDescriptor[value.key] = value.value.map(v => { + // + const id = XValueTools + .toStringExpression( + v.value.find( + vv => vv.key === 'id')?.value + ); + + // + const value = XValueTools + .toStringExpression( + v.value.find( + vv => vv.key === 'value')?.value + ); + + // + const result = createLocaleResourceItemDescriptor({ + id, + value, + }); + + // + return result; + }); + } + } + + // + result.push(localizationDescriptor); + } + + // + return result; +} +//#endregion + +// +//#region ResourceIDUsedCase ... +/** + * create an empty/filled LocaleResourceIDUsedCaseDescriptor object instance ... + * + * @param {any} value value provider for filling ... + * @returns an instance of Specific Descriptor ... + */ +function createLocaleResourceIDUsedCaseDescriptor(value) { + // + // Prepare Result ... + let result = { + resourceID: '', + usedCases: [ + '' + ], + }; + result.usedCases.pop(); + + // + //#region Apply Value ... + if (value) { + // + //#region resourceID ... + if (XValueTools.isValidArg(value.resourceID)) { + result.resourceID = value.resourceID; + } + //#endregion + + // + //#region usedCases ... + if (XValueTools.hasChildArray(value.usedCases)) { + result.usedCases = [ + ...value.usedCases + ]; + } + //#endregion + } + //#endregion + + // + return result; +} + +/** + * check an object is LocaleResourceIDUsedCaseDescriptor instance or not ... + * + * @param {any} value proposed object to check ... + * @returns + */ +function isLocaleResourceIDUsedCaseDescriptor(value) { + // + let result = false; + + // + result = value && + value.hasOwnProperty('resourceID') && + value.hasOwnProperty('usedCases') && + Array.isArray(value.usedCases); + + // + return result; +} +//#endregion + +// +// Moduile Exports ... +module.exports = { + // + LocalizationResourceIdentifiers, + + // + isResourceIDsDescriptor, + createResourceIDsDescriptor, + extractResourceIDsDescriptor, + extractResourceIDsDescriptorFromContent, + + // + isLocaleResourceItemDescriptor, + createLocaleResourceItemDescriptor, + + // + isLocalizationDescriptor, + createLocalizationDescriptor, + extractLocalizationDescriptors, + + // + isLocaleResourceIDUsedCaseDescriptor, + createLocaleResourceIDUsedCaseDescriptor, +} \ No newline at end of file diff --git a/modules/models/x-type.descriptor.js b/modules/models/x-type.descriptor.js new file mode 100644 index 0000000..5c14ed5 --- /dev/null +++ b/modules/models/x-type.descriptor.js @@ -0,0 +1,279 @@ +// +//#region Imports ... +const XFileTools = require('../tools/x-file.tools'); +const XValueTools = require('../tools/x-value.tools'); +const XBaseDescriptor = require('./x-base.descriptor'); +//#endregion + +/** + * check an object instance is typeDescriptor or not ... + * + * @param {any} object proposed object to check ... + * @returns + */ +function isDescriptor(object) { + // + if (!object) { + return false; + } + + // + let result = false; + result = + object.hasOwnProperty('raw') && + object.hasOwnProperty('name') && + object.hasOwnProperty('content') && + object.hasOwnProperty('isExported'); + + // + return result; +} + +/** + * retrieve base or filled TypeDescriptor object instance ... + * + * @param {any} value a value provider object ... + * @returns an instance of TypeDescriptor object ... + */ +function createDescriptor(value) { + // + let result = { + raw: '', + name: '', + content: '', + isExported: false, + }; + + // + //#region Apply Value ... + if (value) { + // + //#region raw ... + if (XValueTools.isValidArg(value.raw)) { + result.raw = value.raw; + } + //#endregion + + // + //#region name ... + if (XValueTools.isValidArg(value.name)) { + result.name = value.name; + } + //#endregion + + // + //#region content ... + if (XValueTools.isValidArg(value.content)) { + result.content = value.content; + } + //#endregion + + // + //#region isExported ... + if (!!value.isExported) { + result.isExported = true; + } + //#endregion + } + //#endregion + + // + return result; +} + +/** + * converts an instance of Descriptor to Expression ... + * + * @param descriptor an instance of TypeDescriptor ... + * @returns creator string ... + */ +function toExpression(descriptor = createDescriptor()) { + // + let result = ''; + + // + // Validate Arg ... + if (!isDescriptor(descriptor)) { + return result; + } + + // + result += ( + !!descriptor.isExported ? + XBaseDescriptor.ExpressionKeys.Export + ' ' : + '' + ) + + XBaseDescriptor.ExpressionKeys.Type + + ' ' + + descriptor.name + + ' = ' + + descriptor.content + + ';'; + + // + return result; +} + +/** + * extract all exists TypeDescriptors ... + * + * @param {string} file a file path ... + * @returns a collection of TypeDescriptor ... + */ +async function extractDescriptors(file = '') { + // + if (!XFileTools.isFileExists(file)) { + return []; + } + + // + const fileContent = await XFileTools.readFile(file); + if (!XValueTools.isValidArg(fileContent)) { + return []; + } + + // + let result = [ + createDescriptor() + ]; + result.pop(); + + // + result = extractDescriptorsFromContent(fileContent); + + // + return result; +} + +/** + * extract all exists TypeDescriptors ... + * + * @param {string} content a file content ... + * @returns a collection of TypeDescriptor ... + */ +function extractDescriptorsFromContent(content = '') { + // + // Prepare Result ... + let result = [ + createDescriptor() + ]; + result.pop(); + + // + // Validate Args ... + if ( + !XValueTools.isValidArg(content) || + !content.includes(XBaseDescriptor.ExpressionKeys.Type) + ) { + return result; + } + + // + // Extract all key Indexes ... + const keyIndexes = XBaseDescriptor. + extractValidIdentifierIndexes(XBaseDescriptor.ExpressionKeys.Type, content); + + // + // Validate them ... + if (!XValueTools.hasChildArray(keyIndexes)) { + return result; + } + + // + // Loop through indexes ... + for (const index of keyIndexes) { + // + // Check Type after befre content ... + let startIndex = index - 1; + let endIndex = index + XBaseDescriptor.ExpressionKeys.Type.length + 1; + + // + // create an empty instance of descriptor ... + let descriptor = { + ...createDescriptor() + } + + // + //#region Name extractor ... + const nameEndIndex = content.indexOf('=', index); + identifier = content + .substring(index + XBaseDescriptor.ExpressionKeys.Type.length, nameEndIndex) + .trim(); + if (XValueTools.isValidArg(identifier)) { + descriptor.name = identifier; + } + //#endregion + + // + //#region Extract isExported ... + const isExported = XBaseDescriptor.checkIsExported(index, content); + descriptor.isExported = isExported; + if (isExported) { + startIndex = index - XBaseDescriptor.ExpressionKeys.Export.length - 1; + } + //#endregion + + // + //#region Extract raw content ... + identifier = content.substring(startIndex); + startIndex = 0; + endIndex = XValueTools.findNearestIndex( + [ + ';', + '{', + '\n' + ] + , identifier + ); + const nearestChar = identifier.charAt(endIndex); + if (nearestChar === '{') { + // + const closedItemsIndexes = XValueTools.findClosedContentIndexes('{', '}', identifier, endIndex); + if (!XValueTools.hasChildArray(closedItemsIndexes)) { + continue; + } + + // + endIndex = closedItemsIndexes[0].end; + + } + + // + identifier = identifier + .substring(startIndex, endIndex) + .trim(); + if (XValueTools.isValidArg(identifier)) { + descriptor.raw = identifier; + } + //#endregion + + // + //#region Parse Content ... + startIndex = identifier.indexOf('=', 0); + identifier = identifier + .substring(startIndex + 1) + .trim(); + identifier = XBaseDescriptor.clearContent(identifier); + if (XValueTools.isValidArg(identifier)) { + descriptor.content = identifier; + } + //#endregion + + // + result.push(descriptor); + } + + // + return result; +} + +// +// Module Exports ... +module.exports = { + // + isDescriptor, + toExpression, + createDescriptor, + extractDescriptors, + extractDescriptorsFromContent, +} \ No newline at end of file diff --git a/modules/services/x-electron.service.js b/modules/services/x-electron.service.js new file mode 100644 index 0000000..f770b50 --- /dev/null +++ b/modules/services/x-electron.service.js @@ -0,0 +1,48 @@ + +'use strict'; + +// +const XElectronChannel = { + Default: 'xMessage', + Handshake: 'xHandshake', + FileService: 'xFileService', + ProjectsService: 'xProjectsService', +} + +// +// Module Exports ... +module.exports = { + // + XElectronChannel: XElectronChannel, + + // + XElectronMessage: class XElectronMessage { + // + constructor( + sender = '', + reciever = '', + message = '', + payload = undefined, + channel = undefined, + timestamp = undefined, + ) { + // + if (!timestamp) { + timestamp = Date.now(); + } + + // + if (!channel) { + channel = XElectronChannel.Default; + } + + // + this.sender = sender; + this.reciever = reciever; + this.payload = payload; + this.message = message; + this.timestamp = timestamp; + this.channel = channel; + } + } +} diff --git a/modules/tools/x-file.tools.js b/modules/tools/x-file.tools.js new file mode 100644 index 0000000..8e1a872 --- /dev/null +++ b/modules/tools/x-file.tools.js @@ -0,0 +1,617 @@ +const fs = require('fs'); +const os = require('os'); +const Path = require('path'); +const XValueTools = require('./x-value.tools'); + +/** + * required folder names ... + */ +const FolderNames = { + Documents: 'Documents', +} + +/** + * current os path separators ... + */ +const PathSeparator = Path.sep; + +/** + * current directory ... + */ +const CurrentDir = __dirname; + +// +//#region Global ... +/** + * retrieve a path status ... + * + * @param {string} path a path value to check ... + * @returns an stat object ... + */ +function getStatus(path = '') { + // + if (!XValueTools.isValidArg(path)) { + return undefined; + } + + // + return fs.statSync(path); +} + +/** + * retrieve user's Document path ... + * + * @returns a path ... + */ +function getDocumentsPath() { + return Path.join(os.homedir(), FolderNames.Documents); +} + +/** + * retrieve user's Document contents ... + * + * @returns resources contents as string array ... + */ +function getDocumentsContents() { + return getDirectoryContents(getDocumentsPath()); +} +//#endregion + +// +//#region Path ... +/** + * retrieve the base name of specific address path ... + * + * @param {string} path address of file or folder ... + * @returns string ... + */ +function basename(path = '') { + // + if (!XValueTools.isValidArg(path)) { + return ''; + } + + // + const result = Path.basename(path); + return result; +} + +/** + * join several path segments together ... + * + * @param {...string} path path params ... + * @returns a joined paths ... + */ +function joinPath(...path) { + return Path.join(...path); +} +//#endregion + +// +//#region File ... +/** + * determines a path destination is a file or not ... + * + * @param {string} path a path value to check ... + * @returns a boolean value ... + */ +function isFileExists(path = '') { + // + if (!XValueTools.isValidArg(path)) { + return false; + } + + // + try { + const stat = getStatus(path); + if (!stat) { + return false; + } + + // + return stat.isFile(); + } catch { + return false; + } +} + +/** + * remove a file ... + * + * @param {string} path a file path ... + * @returns {Promise} action done or not ... + */ +function removeFile(path = '') { + return new Promise((resolve) => { + // + if (!isFileExists(path)) { + resolve(false); + } + + // + fs.unlink(path, (err) => { + // + if (err) { + resolve(false); + return; + } + + // + resolve(true); + }); + }); +} + +/** + * copy a file to destination path ... + * + * @param {string} source source file path ... + * @param {string} dest dest folder path ... + * @returns {Promise} action done or not ... + */ +function copyFile( + source = '', + dest = '' +) { + return new Promise((resolve) => { + // + if ( + !isFileExists(source) || + !isDirectoryExists(dest) + ) { + resolve(false); + return; + } + + // + const destFilePath = Path.join(dest, Path.basename(source)); + fs.copyFile(source, destFilePath, (err) => { + // + if (err) { + resolve(false); + return; + } + + // + resolve(true); + }); + }); +} + +/** + * reading specified file content ... + * + * @param {string} path a file path ... + * @returns {Promise} file content ... + */ +function readFile(path = '') { + return new Promise((resolve) => { + // + if (!isFileExists(path)) { + resolve(''); + return; + } + + // + fs.readFile(path, 'utf8', (err, content) => { + // + if (err) { + resolve(undefined); + return; + } + + // + resolve(content); + }); + }); +} + +/** + * write content to a file ... + * + * @param {string} path a file path ... + * @param {string} content the content which going to write to the file ... + * @param {bool} overwrite determines file overwrite if exists ... + * @returns {Promise} action done or not ... + */ +function writeFile( + path = '', + content = '', + overwrite = true +) { + return new Promise((resolve) => { + // + if (isFileExists(path) && !overwrite) { + // + resolve(false); + return; + } + + // + // Normalize Content ... + content = XValueTools.isValidArg(content) ? + content : + ''; + + // + fs.writeFile(path, content, (err) => { + // + if (err) { + // + resolve(false); + return; + } + + // + resolve(true); + }); + }); +} + +/** + * create a file ... + * + * @param {string} path file path ... + * @param {string} fileName file name ... + * @returns {Promise} action done or not ... + */ +function createFile( + path = '', + fileName = '' +) { + return new Promise((resolve) => { + // + const filePath = Path.join(path, fileName); + if ( + isFileExists(filePath) || + !XValueTools.isValidArg(path) || + !XValueTools.isValidArg(fileName) + ) { + // + resolve(false); + return; + } + + // + fs.writeFile(filePath, '', (err) => { + // + if (err) { + // + resolve(false); + return; + } + + // + resolve(true); + }); + }); +} + +/** + * remove a file name extension ... + * + * @param {string} name + * @returns {string} name without extension ... + */ +function removeFileExtension(name = '') { + return name.substring(0, name.lastIndexOf('.')) || name; +} +//#endregion + +// +//#region Directory ... +/** + * create a directory ... + * + * @param {string} path destination path including dir name ... + * @param {boolean} recursive create directories recursively ... + * @returns action done or not ... + */ +function createDirectory( + path = '', + recursive = true +) { + // + let result = false; + + // + if ( + isDirectoryExists(path) || + !XValueTools.isValidArg(path) + ) { + return false; + } + + // + try { + // + fs.mkdirSync(path, { recursive: recursive }); + result = true; + return result; + } catch { + return false; + } +} + +/** + * remove a directory ... + * + * @param {string} path destination path including dir name ... + * @param {boolean} recursive removes directories recursively ... + * @returns {Promise} action done or not ... + */ +function removeDirectory( + path = '', + recursive = false +) { + return new Promise((resolve) => { + // + if (!isDirectoryExists(path)) { + resolve(false); + return; + } + + // + fs.rm(path, { + recursive + }, (err) => { + // + if (err) { + resolve(false); + return; + } + + // + resolve(true); + }); + }); +} + +/** + * determines a path destination is a directory or not ... + * + * @param {string} path a folder path ... + * @returns represent destnation path is Directory or not ... + */ +function isDirectoryExists(path = '') { + // + if (!XValueTools.isValidArg(path)) { + return false; + } + + // + try { + // + const isExists = fs.existsSync(path); + if (!isExists) { + return false; + } + + // + const stat = getStatus(path); + if (!stat) { + return false; + } + + // + const result = stat.isDirectory(); + return result; + } catch { + return false; + } +} + +/** + * retrieve a directory content ... + * + * @param {string} path a folder path ... + * @returns {Promise} a collection of folder files ... + */ +function getDirectoryContents(path = '') { + return new Promise((resolve) => { + // + if (!isDirectoryExists(path)) { + resolve([]); + return; + } + + // + fs.readdir(path, (err, content) => { + // + if (err) { + resolve([]); + return; + } + + // + resolve(content); + }); + }); +} + +/** + * retrieve a directory files ... + * + * @param {string} path a folder path ... + * @returns {Promise} a collection of folder files ... + */ +function getDirectoryFiles( + path = '', + containsHiddenFiles = false +) { + return new Promise((resolve) => { + // + if (!isDirectoryExists(path)) { + resolve([]); + return; + } + + // + fs.readdir(path, (err, content) => { + // + if (err) { + resolve([]); + return; + } + + // + if (!containsHiddenFiles) { + content = content.filter(c => !c.startsWith('.')) + } + + // + const result = []; + content + .forEach(c => { + // + const cPath = Path.join(path, c); + if (isFileExists(cPath)) { + result.push(c); + } + }); + + // + resolve(result); + }); + }); +} + +/** + * retrieve a directory folders ... + * + * @param {string} path a folder path ... + * @returns {Promise} a collection of folder names ... + */ +function getDirectoryFolders(path = '') { + return new Promise((resolve) => { + // + if (!isDirectoryExists(path)) { + resolve([]); + return; + } + + // + fs.readdir(path, (err, content) => { + // + if (err) { + resolve([]); + return; + } + + // + const result = []; + content.forEach(c => { + // + const cPath = Path.join(path, c); + if (isDirectoryExists(cPath)) { + result.push(c); + } + }); + + // + resolve(result); + }); + }); +} + +/** + * copy a folder with all of it's content to dest ... + * + * @param {string} source source folder path ... + * @param {string} dest dest folder path ... + * @returns {Promise} action done or not ... + */ +async function copyFolder( + source = '', + dest = '' +) { + // + if ( + !isDirectoryExists(source) || + !XValueTools.isValidArg(dest) || + !XValueTools.isValidArg(source) + ) { + return false; + } + + // + const folderName = Path.basename(source); + const destPath = Path.join(dest, folderName); + + // + // Create Dest Path folder if not exists ... + if (!isDirectoryExists(destPath)) { + // + let result = createDirectory(destPath, true); + if (!result) { + return false; + } + } + + // + // Files ... + const files = await getDirectoryFiles(source); + if (files && files.constructor === Array && files.length > 0) { + // + const filesPromises = files.map(file => copyFile(Path.join(source, file), destPath)); + const filesResult = (await Promise.all(filesPromises)).every(r => !!r); + if (!filesResult) { + return false; + } + } + + // + // Folders ... + const folders = await getDirectoryFolders(source); + if (folders && folders.constructor === Array && folders.length > 0) { + // + const folderPromises = folders.map(folder => copyFolder(Path.join(source, folder), destPath)); + const filesResult = (await Promise.all(folderPromises)).every(r => !!r); + if (!filesResult) { + return false; + } + } + + // + return true; +} +//#endregion + +// +// Module Exports ... +module.exports = { + // + CurrentDir, + FolderNames, + PathSeparator, + + // + getStatus, + getDocumentsPath, + getDocumentsContents, + + // + basename, + joinPath, + + // + copyFile, + readFile, + writeFile, + createFile, + removeFile, + isFileExists, + removeFileExtension, + + // + copyFolder, + createDirectory, + removeDirectory, + createDirectory, + removeDirectory, + isDirectoryExists, + isDirectoryExists, + getDirectoryFiles, + getDirectoryFolders, + getDirectoryContents, +} \ No newline at end of file diff --git a/modules/tools/x-logger.tools.js b/modules/tools/x-logger.tools.js new file mode 100644 index 0000000..a9f2a5a --- /dev/null +++ b/modules/tools/x-logger.tools.js @@ -0,0 +1,187 @@ + +const baseLogTag = 'XFrameworkElectronApp'; +let enableLogging = true; + +/** + * Log Tags ... + */ +const XLogTag = { + Debug: 'debug', + Info: 'info', + Warn: 'warn', + Error: 'error' +}; + +/** + * retrieve an instance of XLogMessage ... + * + * @param {string} tag tag of logging ... + * @param {string} message content of log message ... + * @param {array of any} args args of content which required to logging ... + * @param {number} timestamp logging time ... + * + * @returns an instance of log message object ... + */ +function XLogMessage(tag, message, args, timestamp) { + // + if (!tag) { + throw 'Tag not provided ...'; + } + + // + if (!message) { + throw 'Message not provided ...'; + } + + // + if (!args) { + args = []; + } + + // + if (!timestamp) { + timestamp = new Date().getTime(); + } + + // + return { + tag, + message, + args, + timestamp, + }; +} + +/** + * log data ... + * + * @param {XLogMessage} message + */ +function log(message) { + // + if (!message || !message.tag || !message.message || !enableLogging) { + return; + } + + // + message.timestamp = new Date().getTime(); + + // + switch (message.tag) { + // + case XLogTag.Debug: + logDebug(message); + break; + // + case XLogTag.Info: + logInfo(message); + break; + // + case XLogTag.Warn: + logWarn(message); + break; + // + case XLogTag.Error: + logError(message); + break; + + // + default: + break; + } +} + +/** + * Log Debug ... + * + * @param {XLogMessage} message + */ +function logDebug(message) { + // + if (!message || !message.message || !enableLogging || message.tag !== XLogTag.Debug) { + return; + } + + // + message.timestamp = new Date().getTime(); + + // + console.debug(`${baseLogTag}:${message.tag} => ${message.message}`, ...message.args); +} + +/** + * Log Info ... + * + * @param {XLogMessage} message + */ +function logInfo(message) { + // + if (!message || !message.message || !enableLogging || message.tag !== XLogTag.Info) { + return; + } + + // + message.timestamp = new Date().getTime(); + + // + console.info(`${baseLogTag}:${message.tag} => ${message.message}`, ...message.args); +} + +/** + * Log Warn ... + * + * @param {XLogMessage} message + */ +function logWarn(message) { + // + if (!message || !message.message || !enableLogging || message.tag !== XLogTag.Warn) { + return; + } + + // + message.timestamp = new Date().getTime(); + + // + console.warn(`${baseLogTag}:${message.tag} => ${message.message}`, ...message.args); +} + +/** + * Log Error ... + * + * @param {XLogMessage} message + */ +function logError(message) { + // + if (!message || !message.message || !enableLogging || message.tag !== XLogTag.Error) { + return; + } + + // + message.timestamp = new Date().getTime(); + + // + console.error(`${baseLogTag}:${message.tag} => ${message.message}`, ...message.args); +} + +// +// Module Eports ... +module.exports = { + // + enableLogging: () => { + enableLogging = true; + }, + disableLogging: () => { + enableLogging = false; + }, + isLoggingEnable: () => { + return enableLogging; + }, + // + XLogTag: XLogTag, + XLogMessage: XLogMessage, + log: log, + logDebug: logDebug, + logInfo: logInfo, + logWarn: logWarn, + logError: logError, +} \ No newline at end of file diff --git a/modules/tools/x-shell.tools.js b/modules/tools/x-shell.tools.js new file mode 100644 index 0000000..1441faf --- /dev/null +++ b/modules/tools/x-shell.tools.js @@ -0,0 +1,203 @@ +// +//#region Imports ... +const os = require('os'); +const process = require('process'); +const { exec } = require("child_process"); +const XFileTools = require('../tools/x-file.tools'); +//#endregion + +// +//#region Constants ... +// +const OS = { + Aix: 'aix', + Darwin: 'darwin', + FreeBSD: 'freebsd', + Linux: 'linux', + OpenBSD: 'openbsd', + SnOS: 'sunos', + Windows: 'win32' +} + +// +const isWindows = process.platform === OS.Windows; +//#endregion + +// +//#region Actions ... +// +//#region Pure shell commands ... +/** + * execute a command using NodeJS on shell ... + * + * @param {string} cmd command to execute ... + * @param {string} cwd working directory ... + * + * @returns Promise instance ... + */ +function execute(cmd, cwd) { + return new Promise((resolve, reject) => { + // + if (!cmd || cmd.toString().length === 0 || (cwd && !XFileTools.isDirectoryExists(cwd))) { + reject('invalid args ...'); + return; + } + + // + exec(cmd, { cwd }, (err, result, stdError) => { + // + if (err) { + reject(err); + return; + } + + // + if (stdError) { + // + // reject(stdError); + // return; + } + + // + resolve(result); + }); + }); +}; + +/** + * determines a command exists on host or not ... + * + * @param {string} name specific command name ... + * + * @returns boolean Promise ... + */ +function checkCommandExists(name) { + return new Promise(resolve => { + // + if (!name) { + resolve(false); + return; + } + + // + const cmd = isWindows ? `${name} >nul 2>&1` : `type ${name} >/dev/null 2>&1`; + execute(cmd).then(result => { + resolve(true); + }) + .catch(err => { + resolve(false); + }); + }); +} +//#endregion + +// +//#region required commands state ... +/** + * check al required commands exists or not ... + * + * @returns + */ +async function isRequiredCommandsExists() { + // + let result = false; + + // + // const isTarExists = await isTarCommandExists(); + // const isCatExists = await isCatCommandExists(); + // const isGrepExists = await isGrepCommandExists(); + // const isSedExists = await isSedCommandExists(); + // const isNpmExists = await isNpmCommandExists(); + const isNgExists = await isNgCommandExists(); + const isIonicExists = await isIonicCommandExists(); + const isCordovaExists = await isCordovaCommandExists(); + + // + result = isNgExists && + isIonicExists && + isCordovaExists; + + // + return result; +} + +/** + * retrieve required commands state object ... + * + * @returns + */ +async function getRequiredCommandsStates() { + // + const result = {}; + + // + // const isTarExists = await isTarCommandExists(); + // const isCatExists = await isCatCommandExists(); + // const isGrepExists = await isGrepCommandExists(); + // const isSedExists = await isSedCommandExists(); + // const isNpmExists = await isNpmCommandExists(); + const isNgExists = await isNgCommandExists(); + const isIonicExists = await isIonicCommandExists(); + const isCordovaExists = await isCordovaCommandExists(); + + // + result['ng'] = isNgExists; + result['ionic'] = isIonicExists; + result['cordova'] = isCordovaExists; + + // + return result; +} +//#endregion + +// +//#region Commonly used Command Checkers ... +/** + * determines ng command exists or not ... + * + * @returns + */ +function isNgCommandExists() { + return checkCommandExists('ng'); +} + +/** + * determines ionic command exists or not ... + * + * @returns + */ +function isIonicCommandExists() { + return checkCommandExists('ionic'); +} + +/** + * determines cordova command exists or not ... + * + * @returns + */ +function isCordovaCommandExists() { + return checkCommandExists('cordova'); +} +//#endregion +//#endregion + +// +// Module Exports ... +module.exports = { + // + execute, + checkCommandExists, + isRequiredCommandsExists, + getRequiredCommandsStates, + + // + // isFxCommandExists, + // isTarCommandExists, + // isCatCommandExists, + // isSedCommandExists, + // isNpmCommandExists, + // isGrepCommandExists, + isNgCommandExists, + isIonicCommandExists, + isCordovaCommandExists, +} \ No newline at end of file diff --git a/modules/tools/x-type-detector.tools.js b/modules/tools/x-type-detector.tools.js new file mode 100644 index 0000000..a050754 --- /dev/null +++ b/modules/tools/x-type-detector.tools.js @@ -0,0 +1,252 @@ +/** + * all supported data types ... + */ +const DataTypes = { + Null: 'null', + Date: 'date', + Array: 'array', + Object: 'object', + String: 'string', + Number: 'number', + Unknown: 'unknown', + Boolean: 'boolean', + Function: 'function', + Undefined: 'undefined', +}; + +/** + * detect type of a content ... + * + * @param {any} value the content which going to check ... + * @returns + */ +function getType(value) { + // + const type = typeof value; + + // + let result = DataTypes.Unknown; + let dateIdentifier = '[object Date]'; + let constructor = value && value.constructor ? + value.constructor.toString() : + ''; + + // + switch (type) { + // + case 'undefined': + result = DataTypes.Undefined; + break; + + // + case 'boolean': + result = DataTypes.Boolean; + break; + + // + case 'string': + result = DataTypes.String; + break; + + // + case 'number': + result = DataTypes.Number; + break; + + // + case 'function': + result = DataTypes.Function; + break; + + // + case 'object': + // + // Null ... + if (value === null) { + result = DataTypes.Null; + } else + // + // Array ... + if (Array.isArray(value)) { + result = DataTypes.Array; + } else + // + // Data ... + if ( + value instanceof Date || + isFunction(value.getMonth) || + constructor.includes(dateIdentifier) || + Object.prototype.toString.call(value) === dateIdentifier + ) { + result = DataTypes.Date; + } else + // + // Object ... + { + result = DataTypes.Object; + } + break; + + // + default: + result = DataTypes.Unknown; + break; + } + + // + return result; +} + +/** + * retrieve an object constructor ... + * + * @param {any} value the content which going to check ... + * @returns + */ +function getConstructor(value) { + // + const result = value && value.constructor ? + value.constructor.toString() : + ''; + + // + return result; +} + +/** + * retrieve an object prototype ... + * + * @param {any} value the content which going to check ... + * @returns + */ +function getPrototype(value) { + // + const result = value ? + Object.prototype.toString.call(value) : + ''; + + // + return result; +} + +/** + * check an object is null or not ... + * + * @param {any} value the content which going to check ... + * @returns + */ +function isNull(value) { + return getType(value) === DataTypes.Null; +} + +/** + * check an object is undefined or not ... + * + * @param {any} value the content which going to check ... + * @returns + */ +function isUndefined(value) { + return getType(value) === DataTypes.Undefined; +} + +/** + * check an object is null or undefined or not ... + * + * @param {any} value the content which going to check ... + * @returns + */ +function isNullOrUndefined(value) { + return isNull(value) || isUndefined(value); +} + +/** + * check an object is a date or not ... + * + * @param {any} value the content which going to check ... + * @returns + */ +function isDate(value) { + return getType(value) === DataTypes.Date; +} + +/** + * check an object is number or not ... + * + * @param {any} value the content which going to check ... + * @returns + */ +function isNumber(value) { + return getType(value) === DataTypes.Number; +} + +/** + * check an object is string or not ... + * + * @param {any} value the content which going to check ... + * @returns + */ +function isString(value) { + return getType(value) === DataTypes.String; +} + +/** + * check an object is boolean or not ... + * + * @param {any} value the content which going to check ... + * @returns + */ +function isBoolean(value) { + return getType(value) === DataTypes.Boolean; +} + +/** + * check an object is an Array or not ... + * + * @param {any} value the content which going to check ... + * @returns + */ +function isArray(value) { + return getType(value) === DataTypes.Array; +} + +/** + * check an object is and Object or not ... + * + * @param {any} value the content which going to check ... + * @returns + */ +function isObject(value) { + return getType(value) === DataTypes.Object; +} + +/** + * check an object is a Function or not ... + * + * @param {any} value the content which going to check ... + * @returns + */ +function isFunction(value) { + return getType(value) === DataTypes.Function; +} + +// +// Module Exports ... +module.exports = { + // + DataTypes, + + // + getType, + getConstructor, + getPrototype, + isNull, + isUndefined, + isNullOrUndefined, + isDate, + isNumber, + isString, + isBoolean, + isArray, + isObject, + isFunction, +} \ No newline at end of file diff --git a/modules/tools/x-uuid.tools.js b/modules/tools/x-uuid.tools.js new file mode 100644 index 0000000..49fc647 --- /dev/null +++ b/modules/tools/x-uuid.tools.js @@ -0,0 +1,37 @@ +// +//#region Imports ... +const uuid = require("uuid"); +//#endregion + +// +//#region Constants ... +const DEFAULT_NAMESPACE = "SaherElm IT Center"; +//#endregion + +/** + * generate a uniqu identifier ... + * + * @param {string} prefix the prefix of generated uuid ... + * @param {string} content the additional content which added to generated uuid ... + * @param {string} nameSpace the proposed name space for generating uuid ... + * @returns a unique universal uuid ... + */ +function generateUuid( + prefix, + content, + nameSpace = DEFAULT_NAMESPACE +) { + // + const uId = content ? uuid.v5(content, nameSpace) : uuid.v4(); + const result = prefix ? `${prefix}_${uId}` : uId; + + // + return result; +} + +// +// Module Exports ... +module.exports = { + DEFAULT_NAMESPACE, + generateUuid, +}; diff --git a/modules/tools/x-value.tools.js b/modules/tools/x-value.tools.js new file mode 100644 index 0000000..4756012 --- /dev/null +++ b/modules/tools/x-value.tools.js @@ -0,0 +1,1397 @@ +const XTypeTools = require('./x-type-detector.tools'); + +/** +* validate a value as an argument ... +* +* @param {string} value the value which going to validate ... +* @returns +*/ +function isValidArg(value) { + // + let result = false; + + // + result = value && + value.length > 0; + + // + return result; +} + +/** + * validate a collection of valuea as an arguments ... + * + * @param {string|string[]} values the value collection which going to checked ... + * @returns + */ +function isValidArgs(values) { + // + // Normalize Values ... + const normalValues = toNormalArray(values); + if (!hasChildArray(normalValues)) { + return false; + } + + // + let result = normalValues.every(nv => isValidArg(nv)); + return result; +} + +/** + * converts content to an array object ... + * + * @param {string|string[]} content the content which required to normalized ... + * @returns {string[]} array object ... + */ +function toNormalArray(content = '') { + // + // Validate Args ... + if (!isValidArg(content)) { + return []; + } + + // + const result = Array.isArray(content) ? + [...content] : + content.includes(',') && + content !== ',' ? + [...content.split(',')] : + [content]; + + // + return result; +} + +/** + * determines value is array and has atleast one child ... + * + * @param {any} value the value which going to checked ... + * @returns {boolean} result of checking ... + */ +function hasChildArray(value) { + // + let result = false; + result = value && + Array.isArray(value) && + value.length > 0; + + // + return result; +} + +/** + * check an string is ends with specified symbol ... + * + * @param {string} symbol specified search symbol ... + * @param {string} value specified search content ... + * @param {boolean} ignoreCase specified search case sensitive or not ... + * @returns + */ +function endsWidth( + symbol = '', + value = '', + ignoreCase = true +) { + // + if (!isValidArg(value)) { + return false; + } + + // + if (!isValidArg(symbol)) { + return true; + } + + // + // TODO: uncomment it if necessary ... + // symbol = symbol.trim(); + + // + let result = false; + const subtractedContent = value.substring(value.length - symbol.length); + result = !!ignoreCase ? + subtractedContent + .toLowerCase() === symbol + .toLowerCase() : + subtractedContent === symbol; + + // + return result; +} + +/** + * surround specified content by provided symbol ... + * + * @param {string} symbol surround string ... + * @param {string} content used content to surrounded by symbol ... + * @returns surrounded content ... + */ +function surroundBy( + symbol = '', + content = '' +) { + // + // Validate Args ... + if (!isValidArg(content)) { + content = ''; + } + + // + if (!isValidArg(symbol)) { + symbol = ''; + } + + // + if (isSurrounded(symbol, content)) { + return content; + } + + // + const result = `${symbol}${content}${symbol}`; + return result; +} + +/** + * convert a parsed sign to clear string ... + * + * @param {string} value a parsed content ... + * @returns clear parsed signs ... + */ +function toStringExpression(value) { + // + let result = ''; + result = value; + + // + if ( + !value || + !isValidArg(value) || + !isSurroundedString(value) + ) { + return result; + } + + // + const startSymbol = value.charAt(0); + const endSymbol = value.charAt(value.length - 1); + + // + if (startSymbol !== endSymbol) { + return result; + } + + // + if ( + startSymbol === "\"" || + startSymbol === "\'" + ) { + result = clearSurround(startSymbol, value); + } + + // + return result; +} + + + +/** + * find and cleare proposed candidates from specified content ... + * + * @param {string|string[]} candidates the proposed string(s) whic going to cleared from content ... + * @param {string} content the destination content which used to find and replace candidates on it ... + * @returns cleared content ... + */ +function clearContent( + candidates, + content +) { + // + // Validate Args ... + if ( + !candidates || + !isValidArg(content) + ) { + return ''; + } + + // + // Normalize candidates ... + const normalCandidates = toNormalArray(candidates) + .filter(c => isValidArg(c)); + if (!hasChildArray(normalCandidates)) { + return content; + } + + // + // define regexp for content ... + const regExpExpression = normalCandidates.join('|'); + const regExp = new RegExp( + regExpExpression, + 'gi' + ); + + // + let result = ''; + result = content.replace(regExp, ''); + + // + return result; +} + +/** + * clear surrounded symbol from content ... + * + * @param {string} symbol specified search symbol ... + * @param {string} content specified content to clear ... + * @returns + */ +function clearSurround( + symbol = '', + content = '' +) { + // + // Validate Args ... + if ( + !isValidArg(content) || + (isValidArg(symbol) && + symbol.length >= content.length - 1) + ) { + return ''; + } + + // + // Validate Surround ... + if (!isSurrounded(symbol, content)) { + return content; + } + + // + if (!isValidArg(symbol)) { + return content; + } + + // + let result = content.substring(symbol.length, content.length - symbol.length); + return result; +} + +/** + * clear object sign ... + * + * @param {string} content + * @returns cleared content ... + */ +function clearObjectSurround(content = '') { + // + // Validate Args ... + if ( + !isValidArg(content) || + !isSurroundedObject(content) + ) { + return content; + } + + // + const endIndex = content.length - ( + endsWidth('}', content) ? + 1 : + endsWidth('},', content) || + endsWidth('};', content) || + endsWidth('}\n', content) ? + 2 : + 0 + ); + + // + const result = content.substring(1, endIndex); + return result; +} + +/** + * clear array sign ... + * + * @param {string} content + * @returns cleared content ... + */ +function clearArraySurround(content = '') { + // + // Validate Args ... + if ( + !isValidArg(content) || + !isSurroundedArray(content) + ) { + return content; + } + + // + const endIndex = content.length - ( + endsWidth(']', content) ? + 1 : + endsWidth('],', content) || + endsWidth('];', content) || + endsWidth(']\n', content) ? + 2 : + 0 + ); + + // + const result = content.substring(1, endIndex); + return result; +} + +/** + * slice a content to individual parts ... + * + * @param {number|number[]} indexes which indexes used to slice ... + * @param {strng} content the content which going to sliced ... + * @returns sliced parts of content ... + */ +function sliceContent(indexes, content) { + // + // Validate Args ... + if ( + !isValidArg(indexes) || + !isValidArg(content) + ) { + return []; + } + + // + // Normalize indexes ... + const normalIndexes = toNormalArray(indexes) + .filter(index => index > -1 && index < content.length); + if (!hasChildArray(normalIndexes)) { + return []; + } + + // + let result = ['']; + result.pop(); + + // + let lastIndex = 0; + for (const index of normalIndexes) { + // + const part = content.substring(lastIndex, index); + if (isValidArg(part)) { + result.push(part.trim()); + } + + // + lastIndex = index + 1; + } + + // + // check remained parts ... + if (lastIndex < content.length) { + // + const part = content.substring(lastIndex); + if (isValidArg(part)) { + result.push(part.trim()); + } + } + + // + return result; +} + + + +/** + * check an string is starts and ends with specified symbol ... + * + * @param {string} symbol specified search symbol ... + * @param {string} content specified search content ... + * @param {boolean} ignoreCase specified search case sensitive or not ... + * @returns + */ +function isSurrounded( + symbol = '', + content = '', + ignoreCase = true +) { + // + // Validate Args ... + if (!isValidArg(content)) { + return false; + } + + // + if (!isValidArg(symbol)) { + return true; + } + + // + symbol = symbol.trim(); + + // + let result = false; + result = (!!ignoreCase ? + content + .toLowerCase() + .startsWith(symbol.toLowerCase()) : + content.startsWith(symbol) + ) && + endsWidth(symbol, content, ignoreCase); + + // + return result; +} + +/** + * determines a content is an string surrounded value or not ... + * + * @param {string} content a content which going to check ... + * @returns + */ +function isSurroundedString(content = '') { + // + // Validate Args ... + if (!isValidArg(content)) { + return false; + } + + // + let result = false; + result = ( + content.startsWith('\'') && + ( + endsWidth('\'', content) || + endsWidth('\',', content) || + endsWidth('\';', content) || + endsWidth('\'\n', content) + ) || + content.startsWith('\"') && + ( + endsWidth('\"', content) || + endsWidth('\",', content) || + endsWidth('\";', content) || + endsWidth('\"\n', content) + ) || + content.startsWith('`') && + ( + endsWidth('\`', content) || + endsWidth('\`,', content) || + endsWidth('\`;', content) || + endsWidth('\`\n', content) + ) + ); + return result; +} + +/** + * check a content is an array content or not ... + * + * @param {string} content + * @returns + */ +function isSurroundedArray(content = '') { + // + // Validate Args ... + if (!isValidArg(content)) { + return false; + } + + // + let result = false; + result = content.startsWith('[') && + ( + endsWidth(']', content) || + endsWidth('],', content) || + endsWidth('];', content) || + endsWidth(']\n', content) + ); + return result; +} + +/** + * check a content is an object content or not ... + * + * @param {string} content + * @returns + */ +function isSurroundedObject(content = '') { + // + // Validate Args ... + if (!isValidArg(content)) { + return false; + } + + // + let result = false; + result = content.startsWith('{') && + ( + endsWidth('}', content) || + endsWidth('},', content) || + endsWidth('};', content) || + endsWidth('}\n', content) + ); + return result; +} + +/** + * check an index model is contains inside anothers or not ... + * + * @param {{ start: number, end: number}} source the source index model to check ... + * @param {...{ start: number, end: number}} dest the collection of index models which going to check ... + * @returns + */ +function isIndexInside(source, ...dest) { + // + let result = false; + + // + // Validate Args ... + if (!source || !dest) { + return result; + } + + // + // Check idx is standard ... + if ( + !source || + !source.end || + !source.start || + source.start > source.end + ) { + return false; + } + + // + // Check types of destinations ... + for (let index of dest) { + // + // Check idx is standard ... + if ( + !index || + !index.end || + !index.start || + index.start > index.end + ) { + return false; + } + } + + // + if (dest.includes(source)) { + dest = dest.filter(d => d !== source); + } + + // + const insideContentIndex = dest.find(dIndex => { + // + const result = source.start >= dIndex.start && + source.start <= dIndex.end && + source.end >= dIndex.start && + source.end <= dIndex.end; + return result; + }); + + // + result = insideContentIndex; + return result; +} + +/** + * check a number exists in + * @param {number} idx the number which going to check ... + * @param {{ start: number, end: number}} index the index model + * @returns + */ +function isInsideIndex(idx = -1, index) { + // + let result = false; + + // + // Validate Args ... + if ( + !index || + !index.hasOwnProperty('end') || + !index.hasOwnProperty('start') + ) { + return result; + } + + // + result = idx > index.start && idx < index.end; + return result; +} + +/** + * determines an object is key/value and type ... + * + * @param {any} content the object which we are going to check ... + * @returns + */ +function isKeyValueType(content) { + // + const result = content && + content.hasOwnProperty('key') && + content.hasOwnProperty('type') && + content.hasOwnProperty('value'); + + // + return result; +} + + + +/** + * find all indexes of token(s) in content ... + * + * @param {string|string[]} tokens the tokens which require to search ... + * @param {string} content the content which using to search ... + * @returns {number[]} all occured indexes ... + */ +function findAllIndexes( + tokens, + content +) { + // + // Validate Args ... + if ( + !isValidArg(tokens) || + !isValidArg(content) + ) { + return []; + } + + // + // normalize tokens ... + const normalTokens = toNormalArray(tokens); + if (!hasChildArray(normalTokens)) { + return []; + } + + // + // Parse contents ... + let match; + const result = []; + const regExp = new RegExp( + normalTokens.join('|'), + 'g' + ); + while ((match = regExp.exec(content)) !== null) { + result.push(match.index); + } + if (!hasChildArray(result)) { + return []; + } + + // + return result; +} + +/** + * find nearest symbol in a content from specified index ... + * + * @param {string|string[]} candidates specifies which symbols to find ... + * @param {string} content te content for seasrch ... + * @param {number} startFromIndex the index of start position ... + * @returns + */ +function findNearest( + candidates, + content = '', + startFromIndex = 0 +) { + // + // Validate Args ... + if ( + !isValidArg(content) || + !isValidArg(candidates) || + !isValidArg(content.trim()) + ) { + return ''; + } + + // + // Normalize Content ... + content = content.trim(); + + // + // Normalize Starts From ... + startFromIndex = startFromIndex < 0 || startFromIndex > content.length - 1 ? 0 : startFromIndex; + + // + // Normalize Symbols ... + const normalCandidates = toNormalArray(candidates); + if (!hasChildArray(normalCandidates)) { + return ''; + } + + // + let nearestIndex = findNearestIndex( + normalCandidates, + content, + startFromIndex + ); + if (nearestIndex < 0) { + return ''; + } + + // + let result = content.substring( + nearestIndex, + nearestIndex + Math.max(...normalCandidates.map(nc => nc.length)) + ).trim(); + return result; +} + +/** + * search candidates in content and find nearest one and return it ... + * + * @param {string|string[]} candidates which candidates required to check ... + * @param {string} content the content which required to search candidates ... + * @param {number} startFromIndex the proposed index to start searching content from on ... + * @returns + */ +function findNearestIndex( + candidates = [''], + content = '', + startFromIndex = 0, + ignoreClosedItems = false +) { + // + // Validate Args ... + if ( + !isValidArg(content) || + !isValidArg(candidates) + ) { + return -1; + } + + // + // Mormalize startFromIndex value ... + startFromIndex = startFromIndex < 0 ? + 0 : + startFromIndex > content.length - 1 ? + content.length - 1 : + startFromIndex; + + // + // Normalize candidates ... + let normalCandidates = toNormalArray(candidates); + + // + if (!!ignoreClosedItems) { + normalCandidates = normalCandidates + .map(c => content.indexOf( + c, + startFromIndex + ) + ).map(c => +c) + .filter(c => +c > -1); + } else { + normalCandidates = findAllIndexesOutOfCloseds(normalCandidates, content) + .filter(c => c >= startFromIndex); + } + if (!hasChildArray(normalCandidates)) { + return -1; + } + + // + let result = -1; + result = Math.min(...normalCandidates); + + // + return result; +} + +/** + * find close index of specific sign in destination content ... + * + * @param {string} openSymbol open of area sign ... + * @param {string} closeSymbol close of area sign ... + * @param {string} content the destination content for parsing ... + * @param {number} startsFrom an start index of content for start parsing ... + * @returns + */ +function findCloseIndex( + openSymbol = '', + closeSymbol = '', + content = '', + startsFrom = -1 +) { + // + // Validate Args ... + if ( + startsFrom < 0 || + !isValidArg(content) || + !isValidArg(openSymbol) || + !isValidArg(closeSymbol) || + openSymbol === closeSymbol || + !content.includes(openSymbol) || + !content.includes(closeSymbol) || + startsFrom > content.length - 1 + ) { + return -1; + } + + // + let result = -1; + + // + let index = startsFrom; + const openSignStack = []; + while (index < content.length) { + // + const openCandidate = content.substring(index, index + openSymbol.length); + const closeCandidate = content.substring(index, index + closeSymbol.length); + + // + if (openCandidate === openSymbol) { + openSignStack.push(index); + } else if (closeCandidate === closeSymbol) { + // + if (openSignStack.length > 0) { + openSignStack.pop(); + } + + // + if (openSignStack.length === 0) { + result = index; + break; + } + } + + // + index++; + } + + // + return result; +} + +/** + * find closed contents of specific sign in destination content ... + * + * @param {string} openSymbol open of area sign ... + * @param {string} closeSymbol close of area sign ... + * @param {string} content the destination content for parsing ... + * @param {number} startsFrom an start index of content for start parsing ... + * @returns + */ +function findClosedContent( + openSymbol = '', + closeSymbol = '', + content = '', + startsFrom = 0, +) { + // + let result = [{ + start: -1, + end: -1, + content: '' + }]; + result.pop(); + + // + // Validate Args ... + if ( + !isValidArg(content) || + !isValidArg(openSymbol) || + !isValidArg(closeSymbol) || + !content.includes(openSymbol) || + !content.includes(closeSymbol) || + openSymbol.length >= content.length || + closeSymbol.length >= content.length + ) { + return result; + } + + // + // Normalize Start From ... + startsFrom = startsFrom < 0 || startsFrom >= content.length ? 0 : startsFrom; + + // + let canContinue = true; + while (!!canContinue) { + // + let openSymbolIndex = content.indexOf(openSymbol, startsFrom); + if (openSymbolIndex < 0) { + // + canContinue = false; + continue; + } + + // + let closeSymbolIndex = findCloseIndex( + openSymbol, + closeSymbol, + content, + openSymbolIndex + ); + if (closeSymbolIndex < 0) { + // + canContinue = false; + continue; + } + if (content.charAt(closeSymbolIndex) !== closeSymbol) { + closeSymbolIndex++; + } + + // + // Prevent ${} string interpolations ... + if ( + openSymbol === '{' && + openSymbolIndex - 1 >= 0 + ) { + // + const prevChar = content.charAt(openSymbolIndex - 1); + if (prevChar === '$') { + continue; + } + } + + // + const item = content + .substring(openSymbolIndex, closeSymbolIndex + 1) + .trim(); + startsFrom = closeSymbolIndex + 1; + result.push({ + start: openSymbolIndex, + end: closeSymbolIndex, + content: item + }); + } + + // + if (!hasChildArray(result)) { + return result; + } + + // + return result; +} + +/** + * extract a collection of closed contents exists in a content ... + * + * @param symbols a collection of open and close contents ... + * @param {string} content a content for searching inside it ... + * @returns a collection of closed content ... + */ +function findClosedContents( + symbols = [ + { + openSymbol: '', + closeSymbol: '' + } + ], + content = '' +) { + // + let result = [{ + start: -1, + end: -1, + content: '' + }]; + result.pop(); + + // + if ( + !isValidArg(content) || + !hasChildArray(symbols) + ) { + return []; + } + + // + symbols.forEach(symbol => { + // + const closedContent = findClosedContent( + symbol.openSymbol, + symbol.closeSymbol, + content + ); + + // + if (hasChildArray(closedContent)) { + result.push( + ...closedContent + ); + } + }); + + // + return result; +} + +/** + * find all string content closed items ... + * + * @param {string} content a content which going to search ... + * @returns a collection of index descriptors ... + */ +function findClosedStrings(content = '') { + // + // Validate Args ... + if (!isValidArg(content)) { + return []; + } + + // + // there are 3 types of strings ... + // ' " and ` + + // + const token1 = '\''; + const token1Stack = [0]; + token1Stack.pop(); + + // + const token2 = '"'; + const token2Stack = [0]; + token2Stack.pop(); + + // + const token3 = '`'; + const token3Stack = [0]; + token3Stack.pop(); + + // + const result = [ + { + start: -1, + end: -1, + content: '' + } + ]; + result.pop(); + + // + for (let i = 0; i < content.length; i++) { + // + const currentChart = content.charAt(i); + + // + //#region Token 1 ... + if (currentChart === token1) { + // + if (!hasChildArray(token1Stack)) { + token1Stack.push(i); + } else { + // + const start = token1Stack.pop(); + const end = i + 1; + const pContent = content.substring(start, end); + result.push({ + start, + end, + content: pContent + }); + } + } + //#endregion + + // + //#region Token 2 ... + if (currentChart === token2) { + // + if (!hasChildArray(token2Stack)) { + token2Stack.push(i); + } else { + // + const start = token2Stack.pop(); + const end = i + 1; + const pContent = content.substring(start, end); + result.push({ + start, + end, + content: pContent + }); + } + } + //#endregion + + // + //#region Token 3 ... + if (currentChart === token3) { + // + if (!hasChildArray(token3Stack)) { + token3Stack.push(i); + } else { + // + const start = token3Stack.pop(); + const end = i + 1; + const pContent = content.substring(start, end); + result.push({ + start, + end, + content: pContent + }); + } + } + //#endregion + } + + // + return result; +} + +/** + * find container indexes from within indexes ... + * + * @param {...{start: number, end: number}} index the collection of indexes to find beiggers inside ... + * @returns + */ +function findContainerIndexes(...index) { + // + let result = [ + { + start: -1, + end: -1, + content: '' + } + ]; + result.pop(); + + // + let concatedIndexes = []; + for (let idx of index) { + // + // Index Childs ... + for (let iix of idx) { + // + // Check idx is standard ... + if ( + !iix || + !iix.end || + !iix.start || + iix.start > iix.end + ) { + continue; + } + + // + // Check index inside another index ... + concatedIndexes.push(iix); + } + } + + // + if (!hasChildArray(concatedIndexes)) { + return result; + } + + // + for (let ccIdx of concatedIndexes) { + // + const isInside = isIndexInside(ccIdx, ...concatedIndexes); + if (isInside) { + continue; + } + + // + if (hasChildArray(result)) { + // + const isInsideResult = isIndexInside(ccIdx, ...result); + if (isInsideResult) { + continue; + } + } + + // + result.push(ccIdx); + } + + // + return result; +} + +/** + * find all tokens indexes inside a content which they are not inside closed items ... + * + * @param {string|string[]} tokens the tokens which require to search ... + * @param {string} content the content which using to search ... + * @returns + */ +function findAllIndexesOutOfCloseds1( + tokens, + content, +) { + // + // Validate Args ... + if (!isValidArg(content)) { + return []; + } + + // + // Extract token Indexes ... + const tokensIndexes = findAllIndexes(tokens, content); + if (!hasChildArray(tokensIndexes)) { + return []; + } + + // + // Extract Closed Objects Indexes ... + const closedArrays = findClosedContent('[', ']', content); + const closedObjects = findClosedContent('{', '}', content); + const closedStrings = findClosedStrings(content); + if ( + !hasChildArray(closedObjects) && + !hasChildArray(closedArrays) && + !hasChildArray(closedStrings) + ) { + return tokensIndexes; + } + + // + // find bigger sloded ... + let containerClosedItems = findContainerIndexes( + closedArrays, + closedObjects, + closedStrings + ).filter(i => !isSurroundedString(i.content)); + + // + let result = [-1]; + result.pop(); + + // + for (let tIdx of tokensIndexes) { + // + let canAdd = true; + for (let ccIndex of containerClosedItems) { + // + canAdd = isInsideIndex(tIdx, ccIndex); + if (canAdd) { + break; + } + } + + // + if (!canAdd) { + result.push(tIdx); + } + } + + // + return result; +} + +/** + * find all tokens indexes inside a content which they are not inside closed items ... + * + * @param {string|string[]} tokens the tokens which require to search ... + * @param {string} content the content which using to search ... + * @returns + */ +function findAllIndexesOutOfCloseds( + tokens, + content, +) { + // + // Define Result ... + let result = [-1]; + result.pop(); + + // + // Validate Args ... + if (!isValidArg(content)) { + return []; + } + + // + // Normalize Tokens ... + const normalizeTokens = toNormalArray(tokens); + if (!hasChildArray(normalizeTokens)) { + return result; + } + + // + // Extract Closed Objects Indexes ... + let openSymbols = [ + '{', + '[', + '\'', + '"', + '`' + ]; + let closeSymbols = [ + '}', + ']', + '\'', + '"', + '`' + ]; + let openStack = []; + let lastOpenSymbol = ''; + let lastClosedIndex = -1; + for (let i = 0; i < content.length; i++) { + // + const prevChar = content.charAt(i - 1) || ''; + const char = content.charAt(i); + const nextChar = content.charAt(i + 1) || ''; + + // + const isToken = normalizeTokens.includes(char); + const isOpenSymbol = openSymbols.includes(char); + const isCloseSymbol = closeSymbols.includes(char); + + // + if (isOpenSymbol && lastOpenSymbol !== char) { + openStack.push(i); + lastOpenSymbol = char === '\'' || char === '"' || char === '`' ? char : lastOpenSymbol; + } else if (isCloseSymbol) { + // + lastOpenSymbol = char === '\'' || char === '"' || char === '`' ? '' : lastOpenSymbol; + let lastPop = openStack.pop(); + if (openStack.length === 0) { + lastClosedIndex = lastPop; + } + } else if (isToken) { + if ( + i > lastClosedIndex && + openStack.length === 0 + ) { + result.push(i); + } + } + } + + // + return result; +} + +// +// Module Exports ... +module.exports = { + // + endsWidth, + surroundBy, + isValidArg, + isValidArgs, + toNormalArray, + hasChildArray, + toStringExpression, + + // + sliceContent, + clearContent, + clearSurround, + clearArraySurround, + clearObjectSurround, + + // + isSurrounded, + isIndexInside, + isInsideIndex, + isKeyValueType, + isSurroundedArray, + isSurroundedString, + isSurroundedObject, + + // + findNearest, + findAllIndexes, + findCloseIndex, + findNearestIndex, + findClosedContent, + findClosedStrings, + findClosedContents, + findAllIndexesOutOfCloseds, + + // +} \ No newline at end of file diff --git a/modules/tools/x-window.tools.js b/modules/tools/x-window.tools.js new file mode 100644 index 0000000..5cf4f35 --- /dev/null +++ b/modules/tools/x-window.tools.js @@ -0,0 +1,125 @@ +/** + * main storage object ... + */ +const windows = {}; + +/** + * retrieve all exists window id's ... + * + * @returns an array of strings which represents window id's ... + */ +function keys() { + return Object.keys(windows); +} + +/** + * retrieve all available windows ... + * + * @returns an array of strings which represent BrowserWindow Objects ... + */ +function values() { + return Object.values(windows); +} + +/** + * retrieve count of available windows ... + * + * @returns number + */ +function count() { + return Object.keys(windows).length; +} + +/** + * check a BrowserWindow id exists or not ... + * + * @param {string} key window id ... + * @returns a boolean value which represent window exists or not ... + */ +function has(key) { + // + if (!key) { + return false; + } + + // + return keys() + .includes(key); +} + +/** + * retrieve a window by providing it's id ... + * + * @param {string} key window id ... + * @returns an instance of Browserwindow instance ... + */ +function get(key) { + // + if (!has(key)) { + return undefined; + } + + // + return windows[key]; +} + +/** + * set a window by it's id ... + * + * @param {string} key window id ... + * @param {BrowserWindow} value specified window instance ... + * @returns a boolean value ... + */ +function set(key, value) { + // + try { + windows[key] = value; + return true; + } catch { + return false; + } +} + +/** + * remove a key/value from windows ... + * + * @param {string} key window id ... + * @returns a boolean value ... + */ +function remove(key) { + // + if (!has(key)) { + return false; + } + + // + try { + // + delete windows[key]; + return true; + } catch { + return false; + } +} + +/** + * clear all registered objects ... + */ +function clear() { + windows = {}; +} + +module.exports = { + // + windows: windows, + + // + has: has, + get: get, + set: set, + keys: keys, + count: count, + clear: clear, + values: values, + remove: remove, +} \ No newline at end of file diff --git a/package.json b/package.json new file mode 100644 index 0000000..a670bd1 --- /dev/null +++ b/package.json @@ -0,0 +1,33 @@ +{ + "name": "x-sdk-manager", + "version": "1.0.0", + "description": "Sdk Manager CLient Application", + "homepage": "https://saherelm.ir", + "author": { + "name": "Hadi Khazaee Asl", + "email": "hadi_khazaee_asl@yahoo.com", + "url": "https://saherelm.ir" + }, + "keywords": [ + "x-framework", + "saherelm" + ], + "scripts": { + "true": "", + "startElectron": "electron .", + "buildElectronWin32": "electron-packager . --platform=win32 --arch=ia32 --icon=www/assets/icon/favicon.ico --overwrite --prune=true --out=dist", + "buildElectronWin64": "electron-packager . --platform=win32 --arch=x64 --icon=www/assets/icon/favicon.ico --overwrite --prune=true --out=dist", + "buildElectronMac64": "electron-packager . --platform=darwin --arch=x64 --icon=www/assets/icon/favicon.icns --overwrite --prune=true --out=dist", + "buildElectronLinux64": "electron-packager . --platform=linux --arch=x64 --icon=www/assets/icon/favicon.png --overwrite --prune=true --out=dist" + }, + "devDependencies": { + "electron-packager": "^15.3.0", + "uuid": "^8.3.2", + "shx": "^0.3.3" + }, + "dependencies": { + "rxjs": "~7.2.0", + "electron": "^13.1.7" + }, + "main": "app.electron.js" +} diff --git a/www/assets/icon/favicon.ico b/www/assets/icon/favicon.ico new file mode 100644 index 0000000..20f5afe Binary files /dev/null and b/www/assets/icon/favicon.ico differ diff --git a/www/assets/icon/icon-16x16.png b/www/assets/icon/icon-16x16.png new file mode 100644 index 0000000..bcda4d2 Binary files /dev/null and b/www/assets/icon/icon-16x16.png differ diff --git a/www/index.css b/www/index.css new file mode 100644 index 0000000..e69de29 diff --git a/www/index.html b/www/index.html new file mode 100644 index 0000000..fbb8257 --- /dev/null +++ b/www/index.html @@ -0,0 +1,3910 @@ + + + + + + XFramework Backend SDK Manager + + + +
+
+ +
+
XFramework Backend SDK Manager
+
تولید سرویس های فراخوانی سرویس دهنده
+
+
+
+ + +
+
+ +
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+
+
+ + غیرفعال +
+
+ +
+ +
+ + +
+
+
📄
+

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

+

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

+ +
+ + +
+
+ +
+
+ طراح و توسعه‌دهنده: هادی خزاعی اصل + | + شرکت: فن آوران ساحر علم +
+
نسخه: 1.5.0
+
+ + + + + + + + + + + +
+ + + +