Skip to content

Commit

Permalink
Merge pull request #15 from wpdas/feature/core-improvement-beta-23
Browse files Browse the repository at this point in the history
Feature: Core improvement for Beta 23
  • Loading branch information
wpdas authored Apr 22, 2024
2 parents 5375239 + 46510fc commit 26332ff
Show file tree
Hide file tree
Showing 12 changed files with 236 additions and 254 deletions.
32 changes: 22 additions & 10 deletions lib/actions/loadFilesInfo.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
const path = require("path");
const fs = require("fs");
const _ = require("lodash");
const helpers = require("../helpers");
const handleNames = require("./handleNames");
const removeCommentsFromTSX = require("../parsers/removeCommentsFromTSX");
Expand All @@ -11,6 +12,7 @@ const { isWindows } = require("../constants");
const transformComponentReferenceToJSX = require("../parsers/transformComponentReferenceToJSX");
const hasWidgetPropsCheck = require("./hasWidgetPropsCheck");
const { removeImports } = require("../parse");
const filesContentCache = require("../config/filesContentCache");

/**
* Transform statefull components references to JSX (this applies for stateful and stateless components)
Expand Down Expand Up @@ -66,7 +68,7 @@ let processedFiles = [];
let orderedFilesToImport = [];
// Sinal de erro
let hasError = null;
const processFileSchema = (filePath) => {
const processFileSchema = (filePath, processOnlyThisFile) => {
if (hasError) return;

// Verifica cada arquivo jsx e ts para ver se estão quebrados ou não.
Expand Down Expand Up @@ -101,7 +103,7 @@ const processFileSchema = (filePath) => {
}
}

let fileContent = fs.readFileSync(filePath, "utf8");
let fileContent = filesContentCache.getFileContent(filePath);

// Remove comments from file
// INFO: Esta sendo usado para remover comentários de arquivos jsx também
Expand Down Expand Up @@ -170,15 +172,22 @@ const processFileSchema = (filePath) => {
// Push current schema result
contentOrderer.push(currentFileSchema);

// Recursividade
currentFileSchema.nextFilesToLoad.forEach((fileToImport) => {
// Nao pode ser um recurso do alem-vm
// if (!fileToImport.includes(ALEM_VM_FOLDER)) {
processFileSchema(fileToImport);
// }
});
if (!processOnlyThisFile) {
// Recursividade
currentFileSchema.nextFilesToLoad.forEach((fileToImport) => {
// Nao pode ser um recurso do alem-vm
// if (!fileToImport.includes(ALEM_VM_FOLDER)) {
processFileSchema(fileToImport);
// }
});
}
};

/**
* Gera um esquema com os arquivos sendo importados no projeto a partir de um ponto de entrada
* @param {*} entryFile
* @returns
*/
const loadFilesInfo = (entryFile) => {
// Reset state
contentOrderer = [];
Expand All @@ -203,13 +212,16 @@ const loadFilesInfo = (entryFile) => {
return newItem;
});

// Registra uma copia (não referencia na mesmo ponto da memória) do esquema inicial inalterada
const initialFileSchemas = _.cloneDeep(contentOrderer);

// Handle names -> remove const duplicates
contentOrderer = handleNames(contentOrderer);

return {
hasError,
initialFileSchemas,
fileSchemas: contentOrderer,
// orderedFilesToImport: orderedFilesToImport.reverse(),
orderedFilesToImport: contentOrderer
.map((schema) => schema.filePath)
.reverse(),
Expand Down
11 changes: 10 additions & 1 deletion lib/actions/processChildrenWidget.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ const {
} = require("../helpers");
const extractJSXChildren = require("../parsers/extractJSXChildren");
const extractPropsFromJSX = require("../parsers/extractPropsFromJSX");
const extractSpreadsFromJSX = require("../parsers/extractSpreadsFromJSX");
const extractTopLevelJSXElements = require("../parsers/extractTopLevelJSXElements");
const replaceJSXElement = require("../parsers/replaceJSXElement");

Expand Down Expand Up @@ -49,6 +50,7 @@ const processChildrenWidget = (htmlContent, fileSchemas) => {
// for um componente stateful
if (componentSchema && !componentSchema.isModule) {
let childProps = extractPropsFromJSX(htmlElement);
const childSpreads = extractSpreadsFromJSX(htmlElement);

let childChildren = extractJSXChildren(htmlElement);
// INFO: Se tiver child dentro deste child (childChildren), chama essa mesma função recursivamente?
Expand All @@ -59,9 +61,16 @@ const processChildrenWidget = (htmlContent, fileSchemas) => {
childProps = { ...childProps, children: childChildren };
}

const importItemPropsStringSequence =
let importItemPropsStringSequence =
convertObjectToArray(childProps).join(",");

// Adiciona os spreads junto com as propriedades do elemento JSX. Ex:
// <Widget code="..." {...{foo: 2, bar: "oi", ...mySpread1, ...mySpread2}}
// no caso os spreads sao: ...mySpread1 e ...mySpread2
if (childSpreads.length > 0) {
importItemPropsStringSequence += `${importItemPropsStringSequence.length > 0 ? "," : ""} ${childSpreads.join(",")}`;
}

htmlElement = `const TempMethod = () => { return ${htmlElement} \n}`;

htmlElement = replaceJSXElement(
Expand Down
16 changes: 10 additions & 6 deletions lib/actions/transformSchemaToWidget.js
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ const analyzeFunctionSignature = require("../parsers/analyzeFunctionSignature");
const removeFunctionParams = require("../parsers/removeFunctionParams");
const transformAsyncAwait = require("../parsers/transformAsyncAwait");
const compilerOptions = require("./compilerOptions");
const extractSpreadsFromJSX = require("../parsers/extractSpreadsFromJSX");

let processError = null;

Expand Down Expand Up @@ -391,11 +392,7 @@ const swapComponentsForStatelessFiles = (fileSchemas, fileSchema) => {
.replaceAll(MORE_THAN_ONE_SPACE, " ");

let childProps = extractPropsFromJSX(htmlElementString);

// console.log("======= TESTE DO MALACDO PROPS =======");
// console.log(importItemFilePath);
// console.log(childProps);
// console.log("\n\n");
const childSpreads = extractSpreadsFromJSX(htmlElementString);

// get the children
let childChildren = extractJSXChildren(htmlElementString);
Expand All @@ -407,9 +404,16 @@ const swapComponentsForStatelessFiles = (fileSchemas, fileSchema) => {
childProps = { ...childProps, children: childChildren };
}

const importItemPropsStringSequence =
let importItemPropsStringSequence =
convertObjectToArray(childProps).join(",");

// Adiciona os spreads junto com as propriedades do elemento JSX. Ex:
// <Widget code="..." {...{foo: 2, bar: "oi", ...mySpread1, ...mySpread2}}
// no caso os spreads sao: ...mySpread1 e ...mySpread2
if (childSpreads.length > 0) {
importItemPropsStringSequence += `${importItemPropsStringSequence.length > 0 ? "," : ""} ${childSpreads.join(",")}`;
}

// Babel segue os padroes JS, por isso:
// 1 - Adiciona uma uma função no topo
// 2 - Fecha a função no final
Expand Down
43 changes: 28 additions & 15 deletions lib/compiler.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,21 +15,12 @@ const applyOptions = require("./actions/applyOptions");

const distFolder = process.env.DIST_FOLDER || "build";

function compile_files() {
create_dist(distFolder);

let entryFile = path.join(".", "src", "index.tsx");
entryFile = fs.existsSync(entryFile)
? entryFile
: path.join(".", "src", "index.jsx");
if (!fs.existsSync(entryFile)) {
log.error("src/index.tsx or src/index.jsx not found.");
process.exit(1);
}

// Load project files
const filesInfo = loadFilesInfo(entryFile);

/**
* Executa os comandos finais antes de gerar o bundle e arquivos/estrutura de esquemas finais
* @param {{hasError: null;initialFileSchemas: {filePath: any;toImport: any;content: any;}[];fileSchemas: {filePath: string;toImport: string[];content: string;}[];orderedFilesToImport: string[];}} filesInfo
* @returns
*/
function run_final_process(filesInfo) {
// Se não tiver erro
if (filesInfo.hasError) {
// Save bundle file with error info
Expand Down Expand Up @@ -118,6 +109,28 @@ function compile_files() {
}
}

/**
* Le todos os arquivos independentes e compila pela primeira vez
*/
function compile_files() {
create_dist(distFolder);

let entryFile = path.join(".", "src", "index.tsx");
entryFile = fs.existsSync(entryFile)
? entryFile
: path.join(".", "src", "index.jsx");
if (!fs.existsSync(entryFile)) {
log.error("src/index.tsx or src/index.jsx not found.");
process.exit(1);
}

// Load project files
const filesInfo = loadFilesInfo(entryFile);

// Executa processo final para gerar bundle e esquemas de arquivos
run_final_process(filesInfo);
}

module.exports = {
compile_files,
};
32 changes: 32 additions & 0 deletions lib/config/filesContentCache.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
/**
* Recurso criado para melhorar o desempenho durante o desenvolvimento e ler novamente somente
* os arquivos que foram alterados.
*/

const fs = require("fs");

const filesContentCache = {};

const getFileContent = (filePath) => {
// First, try to return the cached content
if (filesContentCache[filePath]) {
return filesContentCache[filePath];
}

// If there's no cache, read file, save cache and return the file content
let fileContent = fs.readFileSync(filePath, "utf8");
filesContentCache[filePath] = fileContent;

return fileContent;
};

const updateFileContent = (filePath) => {
// Read file and save in cache
let fileContent = fs.readFileSync(filePath, "utf8");
filesContentCache[filePath] = fileContent;
};

module.exports = {
getFileContent,
updateFileContent,
};
57 changes: 31 additions & 26 deletions lib/dev.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ const { read_alem_config } = require("./config");
const { build } = require("./build");
const { log } = require("./utils");
const { injectHTML } = require("./parse");
const filesContentCache = require("./config/filesContentCache");

// dist folder name when building an app
const distFolder = process.env.DIST_FOLDER || "build";
Expand Down Expand Up @@ -48,6 +49,10 @@ async function dev(opts) {

watchFolders(["./src"], async (path) => {
loading = log.loading(`Change detected in ${path}, rebuilding...`);

// Atualiza o arquivo no cache para ser acessado posteriormente no re-build()
filesContentCache.updateFileContent(path);

await build().catch((err) => {
loading.error();
log.error(err);
Expand Down Expand Up @@ -219,32 +224,32 @@ async function serveDevJson({ useSocket, useGateway, useOpen, port, network }) {
start = process.env.WSL_DISTRO_NAME ? "explorer.exe" : start;
exec(`${start} http://127.0.0.1:${port}`);
}
log.log(`
┌─────────────────────────────────────────────────────────────┐
│ BosLoader Server is Up and Running │
│ │${
useGateway
? `
│ ➜ Local Gateway: \u001b[32mhttp://127.0.0.1:${port}\u001b[0m │`
: ""
}
│ │
│ ➜ Bos Loader Http: \u001b[32mhttp://127.0.0.1:${port}/api/loader\u001b[0m │${
useSocket
? `
│ ➜ Bos Loader WebSocket: \u001b[32mws://127.0.0.1:${port}\u001b[0m │`
: ""
}
│ │
│ Optionaly, to open local widgets: │
│ 1. Visit either of the following sites: │
│ - https://near.org/flags │
│ - https://everything.dev/flags │
│ 2. Paste the Bos Loader Http URL │
│ │
└─────────────────────────────────────────────────────────────┘
`);
log.sucess(`Alem runnig on port ${port}!`);
// log.log(`
// ┌─────────────────────────────────────────────────────────────┐
// │ BosLoader Server is Up and Running │
// │ │${
// useGateway
// ? `
// │ ➜ Local Gateway: \u001b[32mhttp://127.0.0.1:${port}\u001b[0m │`
// : ""
// }
// │ │
// │ ➜ Bos Loader Http: \u001b[32mhttp://127.0.0.1:${port}/api/loader\u001b[0m │${
// useSocket
// ? `
// │ ➜ Bos Loader WebSocket: \u001b[32mws://127.0.0.1:${port}\u001b[0m │`
// : ""
// }
// │ │
// │ Optionaly, to open local widgets: │
// │ 1. Visit either of the following sites: │
// │ - https://near.org/flags │
// │ - https://everything.dev/flags │
// │ 2. Paste the Bos Loader Http URL │
// │ │
// └─────────────────────────────────────────────────────────────┘
// `);
log.sucess(`Além runnig on port ${port}!`);
})
.on("error", (err) => {
log.error(err);
Expand Down
Loading

0 comments on commit 26332ff

Please sign in to comment.