From f806d394d1347c2fdc1a8c2ae54023c73f8cdd47 Mon Sep 17 00:00:00 2001 From: Wenderson Pires Date: Mon, 11 Mar 2024 12:41:53 -0300 Subject: [PATCH 1/8] wip --- lib/actions/handleNames.js | 153 +++++++++++++++++++++++++++++++++++ lib/actions/loadFilesInfo.js | 22 ++++- lib/regexp.js | 30 +++++++ 3 files changed, 201 insertions(+), 4 deletions(-) create mode 100644 lib/actions/handleNames.js diff --git a/lib/actions/handleNames.js b/lib/actions/handleNames.js new file mode 100644 index 0000000..2433466 --- /dev/null +++ b/lib/actions/handleNames.js @@ -0,0 +1,153 @@ +/** + * Handle const/var/let names to avoid duplicates + */ + +const { + BETWEEN_EXPORT_CONST_AND_EQUAL, + SPACES, + BETWEEN_EXPORT_DEFAULT_FUNCTION_AND_OPEN_PARENTHESE, + AFTER_EXPORT_DEFAULT, + SPECIAL_CHARACTERS_AND_SPACES, +} = require("../regexp"); + +/** + * Get "export const" items + * @param {string} content + */ +const getExportConsts = (content) => { + let foundItems = content.match(BETWEEN_EXPORT_CONST_AND_EQUAL); + + // Remove spaces + if (foundItems) { + foundItems = foundItems.map((item) => item.replaceAll(SPACES, "")); + } + + return foundItems || []; +}; + +/** + * Get "export default function" items + * @param {string} content + */ +const getExportDefaultFunction = (content) => { + let foundItems = content.match( + BETWEEN_EXPORT_DEFAULT_FUNCTION_AND_OPEN_PARENTHESE, + ); + + // Remove spaces + if (foundItems) { + foundItems = foundItems.map((item) => item.replaceAll(SPACES, "")); + } + + return foundItems || []; +}; + +/** + * Get "export default" items + * @param {string} content + */ +const getExportDefault = (content) => { + // Remove all "export default function" + const _content = content.replaceAll("export default function", ""); + + let foundItems = _content.match(AFTER_EXPORT_DEFAULT); + + // Remove spaces + if (foundItems) { + foundItems = foundItems.map((item) => + item.replaceAll(SPACES, "").replaceAll(SPECIAL_CHARACTERS_AND_SPACES, ""), + ); + } + + return foundItems || []; +}; + +/** + * Generates the exports schema + * + * + * exports organizer - original state + * { + * "caminho/do/arquivo.jsx": [{MyVar: "MyVar"}, {MyVar2: "MyVar2"}] + * } + * + * exports organizer - when the item needs to be changed + * { + * "caminho/do/arquivo.jsx": [{MyVar: "MyVar_newName"}, {MyVar2: "MyVar2_nameName"}] + * } + * + * + * @param {{filePath: string, toImport: string[], content: string}[]} fileSchemas + * @returns {Record}[]>} + */ +const getExportsOrganizer = (fileSchemas) => { + const exportsOrganizer = []; + + fileSchemas.forEach((schema) => { + // Cria lista de exports + exportsOrganizer[schema.filePath] = []; + + let exports = []; + // getExportConsts(schema.content); + // Verifica se já tem os nomes de elementos no conteúdo anterior + // exports = [...exports, ...getExportConsts(schema.content)]; + + exports = [ + ...getExportConsts(schema.content), + ...getExportDefaultFunction(schema.content), + ...getExportDefault(schema.content), + ]; + + exports.forEach((exportItem) => + exportsOrganizer[schema.filePath].push({ [exportItem]: exportItem }), + ); + + // exports.push(...getExportConsts(schema.content)); + // console.log(exports); + }); + + return exportsOrganizer; +}; + +/** + * Handle const/var/let names to avoid duplicates + * @param {{filePath: string, toImport: string[], content: string}[]} fileSchemas + */ +const handleNames = (fileSchemas) => { + /** + * exports organizer - original state + * { + * "caminho/do/arquivo.jsx": [{MyVar: "MyVar"}, {MyVar2: "MyVar2"}] + * } + * + * exports organizer - when the item needs to be changed + * { + * "caminho/do/arquivo.jsx": [{MyVar: "MyVar_newName"}, {MyVar2: "MyVar2_nameName"}] + * } + */ + const exportsOrganizer = getExportsOrganizer(fileSchemas); + + // Observe and changes duplicated names + // reverse (need to load deepest content first) + const itemsToProcess = Object.keys(exportsOrganizer).reverse(); + console.log(itemsToProcess); + + // console.log(exportsOrganizer); +}; + +module.exports = handleNames; + +// 1 - Ler o schema de cada arquivo (loadFilesInfo faz isso) +// 2 - Pegar esses dados e checar conteudo de arquivo por arquivo se tem duplicidade +// 3 - Gerar o seguinte esquema + +/** + * exports organizer + * { + * "caminho/do/arquivo.jsx": [{MyVar: "MyVar_newName"}, {MyVar2: "MyVar2_nameName"}] + * } + */ + +// - Carregar o conteúdo do arquivo anterior +// - No arquivo atual, checar se seus exports / export defaul já existe no conteúdo anterior +// - Se já existir, muda o nome das vars no arquivo atual diff --git a/lib/actions/loadFilesInfo.js b/lib/actions/loadFilesInfo.js index 2692904..d319f8b 100644 --- a/lib/actions/loadFilesInfo.js +++ b/lib/actions/loadFilesInfo.js @@ -2,6 +2,7 @@ const path = require("path"); const fs = require("fs"); const helpers = require("../helpers"); const { removeComments } = require("../parse"); +const handleNames = require("./handleNames"); /** * To be like: @@ -10,7 +11,8 @@ const { removeComments } = require("../parse"); * [ * { * filePath: "file/path/ModuleFile.tsx", - * toImport: ["path/moduleFile1.tsx", "path/moduleFile2.tsx"] + * toImport: ["path/moduleFile1.tsx", "path/moduleFile2.tsx"], + * content: " ..." * nextFilesToLoad: [ * "path/to/import/ModuleFile1.tsx", * "path/to/import/ModuleFile2.tsx", @@ -55,6 +57,7 @@ const processFileSchema = (filePath) => { // pode ser deletado no final do processo nextFilesToLoad: [], toImport: [], + content: fileContent, }; fileImportsPath.forEach((importPath) => { // Usa src para inicio ou o caminho do pai do arquivo sendo processado atualmente @@ -108,11 +111,22 @@ const loadFilesInfo = (entryFile) => { // Finaliza o processo do contentOrderer deletando o campo "filesToImport" // de todos os filhos, já que agora náo são mais necessarios - contentOrderer.map((item) => { - delete item.filesToImport; - return item; + contentOrderer = contentOrderer.map((item) => { + const newItem = { + filePath: item.filePath, + toImport: item.toImport, + content: item.content, + }; + delete newItem.filesToImport; + return newItem; }); + // Handle names -> remove const duplicates + // contentOrderer = handleNames(contentOrderer); + handleNames(contentOrderer); + + // console.log(contentOrderer); + return { filesSchema: contentOrderer, // orderedFilesToImport: orderedFilesToImport.reverse(), diff --git a/lib/regexp.js b/lib/regexp.js index 79bcdb0..673034d 100644 --- a/lib/regexp.js +++ b/lib/regexp.js @@ -16,6 +16,16 @@ const IMPORT_STATEMENT_2 = // # BETWEEN quotation marks const BETWEEN_QUOTES = /(?<=")(.*?)(?=")/gm; +// ENTRE export const e = +const BETWEEN_EXPORT_CONST_AND_EQUAL = /(?<=export const)(.*?)(?==)/gm; + +// ENTRE export default function e ( +const BETWEEN_EXPORT_DEFAULT_FUNCTION_AND_OPEN_PARENTHESE = + /(?<=export default function)(.*?)(?=\()/gm; + +// VALOR DEPOIS DE export default +const AFTER_EXPORT_DEFAULT = /(?<=export default).*/gm; + module.exports = { SPECIAL_CHARACTERS, SPECIAL_CHARACTERS_AND_SPACES, @@ -25,4 +35,24 @@ module.exports = { IMPORT_STATEMENT, IMPORT_STATEMENT_2, BETWEEN_QUOTES, + BETWEEN_EXPORT_CONST_AND_EQUAL, + BETWEEN_EXPORT_DEFAULT_FUNCTION_AND_OPEN_PARENTHESE, + AFTER_EXPORT_DEFAULT, }; + +// ENTRE export const e = +// util para +// export const Bla = .... +// ENCONTRA Bla +// (?<=export const)(.*?)(?=\=) + +// ENTRE export default function e ( +// util para +// export default function Bla(){....} +// ENCONTRA Bla +// (?<=export default function)(.*?)(?=\() + +// export default Bla +// remover todos os "export default function" +// PROCURAR POR: "export default" +// (?<=export default function)(.*?)(?=\n|\r) From cf89be169a85063ac7d281552dbf2a12c1a9c7a2 Mon Sep 17 00:00:00 2001 From: Wenderson Pires Date: Mon, 11 Mar 2024 16:26:12 -0300 Subject: [PATCH 2/8] wip --- lib/actions/handleNames.js | 192 ++++++++++++++++++++++++++++++++++++- lib/parse.js | 11 ++- lib/regexp.js | 8 ++ 3 files changed, 205 insertions(+), 6 deletions(-) diff --git a/lib/actions/handleNames.js b/lib/actions/handleNames.js index 2433466..629869f 100644 --- a/lib/actions/handleNames.js +++ b/lib/actions/handleNames.js @@ -2,12 +2,15 @@ * Handle const/var/let names to avoid duplicates */ +const { process_file } = require("../parse"); const { BETWEEN_EXPORT_CONST_AND_EQUAL, SPACES, BETWEEN_EXPORT_DEFAULT_FUNCTION_AND_OPEN_PARENTHESE, AFTER_EXPORT_DEFAULT, SPECIAL_CHARACTERS_AND_SPACES, + BETWEEN_EXPORT_LET_AND_EQUAL, + BETWEEN_EXPORT_VAR_AND_EQUAL, } = require("../regexp"); /** @@ -25,6 +28,36 @@ const getExportConsts = (content) => { return foundItems || []; }; +/** + * Get "export let" items + * @param {string} content + */ +const getExportLets = (content) => { + let foundItems = content.match(BETWEEN_EXPORT_LET_AND_EQUAL); + + // Remove spaces + if (foundItems) { + foundItems = foundItems.map((item) => item.replaceAll(SPACES, "")); + } + + return foundItems || []; +}; + +/** + * Get "export var" items + * @param {string} content + */ +const getExportVars = (content) => { + let foundItems = content.match(BETWEEN_EXPORT_VAR_AND_EQUAL); + + // Remove spaces + if (foundItems) { + foundItems = foundItems.map((item) => item.replaceAll(SPACES, "")); + } + + return foundItems || []; +}; + /** * Get "export default function" items * @param {string} content @@ -94,6 +127,8 @@ const getExportsOrganizer = (fileSchemas) => { exports = [ ...getExportConsts(schema.content), + ...getExportLets(schema.content), + ...getExportVars(schema.content), ...getExportDefaultFunction(schema.content), ...getExportDefault(schema.content), ]; @@ -109,11 +144,107 @@ const getExportsOrganizer = (fileSchemas) => { return exportsOrganizer; }; +// TODO: gerar hash com hash anterior +let nonce = 0; +/** + * Generate new name + * @param {string} currentName + */ +const newName = (currentName) => { + nonce++; + return `${currentName}_______${nonce}`; +}; + +/** + * Replace the item name inside the content + * @param {string} content + * @param {string} itemName + * @param {string} newItemName + */ +const replaceNamesInContent = (content, itemName, newItemName) => { + // Replace const values + // ex: const App + // nao pega: const AppRoute + // O mesmo para os proximos + // (const App)[^a-zA-Z0-9=] + const constRegExp = new RegExp(`(const ${itemName})[^a-zA-Z0-9=]`, "gm"); + const letRegExp = new RegExp(`(let ${itemName})[^a-zA-Z0-9=]`, "gm"); + const varRegExp = new RegExp(`(var ${itemName})[^a-zA-Z0-9=]`, "gm"); + const functionRegExp = new RegExp( + `(function ${itemName})[^a-zA-Z0-9=]`, + "gm", + ); + + content = content.replaceAll(constRegExp, `const ${newItemName}`); + content = content.replaceAll(letRegExp, `let ${newItemName}`); + content = content.replaceAll(varRegExp, `var ${newItemName}`); + content = content.replaceAll(functionRegExp, `function ${newItemName}`); + + return content; +}; + +/** + * Verifica se o item (const, let, var, function) existe no content + * @param {string} content + * @param {string} itemName + */ +const checkIfItemExistInContent = (content, itemName) => { + // Replace const values + // ex: const App + // nao pega: const AppRoute + // O mesmo para os proximos + // (const App)[^a-zA-Z0-9=] + const constRegExp = new RegExp(`(const ${itemName})[^a-zA-Z0-9=]`, "gm"); + const letRegExp = new RegExp(`(let ${itemName})[^a-zA-Z0-9=]`, "gm"); + const varRegExp = new RegExp(`(var ${itemName})[^a-zA-Z0-9=]`, "gm"); + const functionRegExp = new RegExp( + `(function ${itemName})[^a-zA-Z0-9=]`, + "gm", + ); + + // const + // if (itemName === "Des") { + // const has = content.match(constRegExp); + + // if (has) { + // console.log( + // "NAO TEM? HUMMM ===>", + // constRegExp.test(content), + // // content.match(functionRegExp).join("").replaceAll("(", ""), + // content.includes(`const ${itemName}`), + // ); + // } + // } + + // Function + // if (itemName === "Des") { + // const has = content.match(functionRegExp); + // if (has) { + // console.log( + // "NAO TEM? HUMMM ===>", + // functionRegExp, + // functionRegExp.test(content), + // content.match(functionRegExp).join("").replaceAll("(", ""), + // content.includes(`function ${itemName}`), + // ); + // } + // } + + return Boolean( + content.match(constRegExp) || + content.match(letRegExp) || + content.match(varRegExp) || + content.match(functionRegExp), + ); +}; + /** * Handle const/var/let names to avoid duplicates * @param {{filePath: string, toImport: string[], content: string}[]} fileSchemas */ const handleNames = (fileSchemas) => { + let tempBundle = ""; + /** * exports organizer - original state * { @@ -126,13 +257,70 @@ const handleNames = (fileSchemas) => { * } */ const exportsOrganizer = getExportsOrganizer(fileSchemas); + console.log("BEFORE", exportsOrganizer); // Observe and changes duplicated names // reverse (need to load deepest content first) const itemsToProcess = Object.keys(exportsOrganizer).reverse(); - console.log(itemsToProcess); + // ex: itemKey = caminho/para/arquivo.tsx + itemsToProcess.forEach((itemKey) => { + const fileSchema = fileSchemas.find( + (fileSchema) => fileSchema.filePath === itemKey, + ); + + let fileContent = fileSchema?.content || ""; + + // Processed content + fileContent = process_file(null, fileContent); + + // Checa se o nome dos exports do arquivo já existem no bundle + // ex: exportObj = {MyVar: "MyVar"} + // console.log("BEEEEEEEEEEEEE", exportsOrganizer[itemKey]); + // Exports do arquivo atual + exportsOrganizer[itemKey].forEach((exportObj, objIndex) => { + // exceto o propio arquivo + // console.log("BEEEEEEEEEEEEE", exportsOrganizer[itemKey]); + // if (itemKey !== ) + const exportKeyName = Object.keys(exportObj)[0]; + // console.log(exportKeyName); + // Verifica se ja tem um recurso (const, var, let, function) usando esse nome + console.log( + "BRUUUUTUUUUSSS:", + checkIfItemExistInContent(tempBundle, exportKeyName), + exportKeyName, + ); + if (checkIfItemExistInContent(tempBundle, exportKeyName)) { + // Se tiver, troca o nome no arquivo/conteudo atual... + console.log("TEM IGUAL PAI:", exportKeyName); + // Troca nome do item no organizer + // console.log( + // "FOOO:", + // exportsOrganizer[itemKey][objIndex][exportKeyName], + // ); + /** + * = {"caminho/arquivo.tsx": [index of export key][key name]} + */ + exportsOrganizer[itemKey][objIndex][exportKeyName] = + newName(exportKeyName); + // exportsOrganizer[itemKey][importKeyName] = 'NewName' + + // atualiza o fileContent + + // ...e atualiza o nome do item nos arquivos que dependem dele + } + // console.log(exportObj); + }); + + tempBundle += fileContent; + + // console.log(itemContent); + // Referencia o conteúdo do item + // const itemContent = item; + }); + // console.log(itemsToProcess); - // console.log(exportsOrganizer); + console.log("AFTER:", exportsOrganizer); + // console.log(tempBundle); }; module.exports = handleNames; diff --git a/lib/parse.js b/lib/parse.js index 84bf73b..48a4f85 100644 --- a/lib/parse.js +++ b/lib/parse.js @@ -9,12 +9,15 @@ const sucraseOptions = { disableESTransforms: true, }; -// process each file +// process each file (using its path or its content) // function process_file(filePath, { aliases, account }) { -function process_file(filePath) { - let fileContent = fs.readFileSync(filePath, "utf8"); +function process_file(filePath, _fileContent) { + let fileContent = _fileContent || fs.readFileSync(filePath, "utf8"); - if (filePath.endsWith(".ts") || filePath.endsWith(".tsx")) { + if ( + !_fileContent && + (filePath.endsWith(".ts") || filePath.endsWith(".tsx")) + ) { fileContent = transpileTypescript(fileContent); } diff --git a/lib/regexp.js b/lib/regexp.js index 673034d..2b7b91a 100644 --- a/lib/regexp.js +++ b/lib/regexp.js @@ -19,6 +19,12 @@ const BETWEEN_QUOTES = /(?<=")(.*?)(?=")/gm; // ENTRE export const e = const BETWEEN_EXPORT_CONST_AND_EQUAL = /(?<=export const)(.*?)(?==)/gm; +// ENTRE export let e = +const BETWEEN_EXPORT_LET_AND_EQUAL = /(?<=export let)(.*?)(?==)/gm; + +// ENTRE export var e = +const BETWEEN_EXPORT_VAR_AND_EQUAL = /(?<=export var)(.*?)(?==)/gm; + // ENTRE export default function e ( const BETWEEN_EXPORT_DEFAULT_FUNCTION_AND_OPEN_PARENTHESE = /(?<=export default function)(.*?)(?=\()/gm; @@ -36,6 +42,8 @@ module.exports = { IMPORT_STATEMENT_2, BETWEEN_QUOTES, BETWEEN_EXPORT_CONST_AND_EQUAL, + BETWEEN_EXPORT_LET_AND_EQUAL, + BETWEEN_EXPORT_VAR_AND_EQUAL, BETWEEN_EXPORT_DEFAULT_FUNCTION_AND_OPEN_PARENTHESE, AFTER_EXPORT_DEFAULT, }; From 16f49d9a3c11a2c2cbeceab06265d50de8173f75 Mon Sep 17 00:00:00 2001 From: Wenderson Pires Date: Mon, 11 Mar 2024 17:48:59 -0300 Subject: [PATCH 3/8] wip --- lib/actions/handleNames.js | 123 +++++++++++++++++++++++++++++++++---- lib/parse.js | 26 +++++--- lib/regexp.js | 5 ++ 3 files changed, 134 insertions(+), 20 deletions(-) diff --git a/lib/actions/handleNames.js b/lib/actions/handleNames.js index 629869f..5e1e673 100644 --- a/lib/actions/handleNames.js +++ b/lib/actions/handleNames.js @@ -2,7 +2,7 @@ * Handle const/var/let names to avoid duplicates */ -const { process_file } = require("../parse"); +const { process_file, process_file_content } = require("../parse"); const { BETWEEN_EXPORT_CONST_AND_EQUAL, SPACES, @@ -11,6 +11,7 @@ const { SPECIAL_CHARACTERS_AND_SPACES, BETWEEN_EXPORT_LET_AND_EQUAL, BETWEEN_EXPORT_VAR_AND_EQUAL, + BETWEEN_EXPORT_FUNCTION_AND_OPEN_PARENTHESE, } = require("../regexp"); /** @@ -58,6 +59,21 @@ const getExportVars = (content) => { return foundItems || []; }; +/** + * Get "export function" items + * @param {string} content + */ +const getExportFunction = (content) => { + let foundItems = content.match(BETWEEN_EXPORT_FUNCTION_AND_OPEN_PARENTHESE); + + // Remove spaces + if (foundItems) { + foundItems = foundItems.map((item) => item.replaceAll(SPACES, "")); + } + + return foundItems || []; +}; + /** * Get "export default function" items * @param {string} content @@ -129,6 +145,7 @@ const getExportsOrganizer = (fileSchemas) => { ...getExportConsts(schema.content), ...getExportLets(schema.content), ...getExportVars(schema.content), + ...getExportFunction(schema.content), ...getExportDefaultFunction(schema.content), ...getExportDefault(schema.content), ]; @@ -150,23 +167,48 @@ let nonce = 0; * Generate new name * @param {string} currentName */ -const newName = (currentName) => { +const createNewName = (currentName) => { nonce++; return `${currentName}_______${nonce}`; }; +/** + * Change the fileSchema.content in other files when a dependent item gets its name changed + * @param {string} contentFilePath + * @param {{filePath: string, toImport: string[], content: string}[]} fileSchemas schemas to change the files content when a item gets its name changed + */ +const replaceItemNamesInOtherFilesContent = (fileSchemas) => { + /** + * 1 - quando trocar o nome do item, tem que checar pra ser exato para evitar essa situacao + * App.fooBaar + * AppRoute.blabla + * + * Quero trocar o "App" por "App__2", se nao verificar o valor exato, o "AppRoute" + * também vai ser alterado erroneamente. + */ +}; + /** * Replace the item name inside the content * @param {string} content * @param {string} itemName * @param {string} newItemName + * @param {string} contentFilePath + * @param {{filePath: string, toImport: string[], content: string}[]} fileSchemas schemas to change the files content when a item gets its name changed */ -const replaceNamesInContent = (content, itemName, newItemName) => { +const replaceNamesInContent = ( + content, + itemName, + newItemName, + contentFilePath, + fileSchemas, +) => { // Replace const values // ex: const App // nao pega: const AppRoute // O mesmo para os proximos // (const App)[^a-zA-Z0-9=] + // TODO: reutilizar os do checkIfItemExistInContent const constRegExp = new RegExp(`(const ${itemName})[^a-zA-Z0-9=]`, "gm"); const letRegExp = new RegExp(`(let ${itemName})[^a-zA-Z0-9=]`, "gm"); const varRegExp = new RegExp(`(var ${itemName})[^a-zA-Z0-9=]`, "gm"); @@ -175,12 +217,54 @@ const replaceNamesInContent = (content, itemName, newItemName) => { "gm", ); - content = content.replaceAll(constRegExp, `const ${newItemName}`); - content = content.replaceAll(letRegExp, `let ${newItemName}`); - content = content.replaceAll(varRegExp, `var ${newItemName}`); - content = content.replaceAll(functionRegExp, `function ${newItemName}`); + // content = content.replaceAll(constRegExp, `const ${newItemName}`); + // content = content.replaceAll(letRegExp, `let ${newItemName}`); + // content = content.replaceAll(varRegExp, `var ${newItemName}`); + // content = content.replaceAll(functionRegExp, `function ${newItemName}`); + + // 1 - Testa, se aprovado, mudar o nome dos items no corpo do arquivo + + // Const + const testConst = content.match(constRegExp); + if (testConst) { + const constName = testConst.join(""); + const newConstName = constName.replaceAll(itemName, newItemName); + content = content.replaceAll(constName, newConstName); + fileSchemas = replaceItemNamesInOtherFilesContent( + contentFilePath, + itemName, + newItemName + fileSchemas, + ); + } + + // Let + const testLet = content.match(letRegExp); + if (testLet) { + const letName = testLet.join(""); + const newLetName = letName.replaceAll(itemName, newItemName); + content = content.replaceAll(letName, newLetName); + } + + // Var + const testVar = content.match(varRegExp); + if (testVar) { + const varName = testVar.join(""); + const newVarName = varName.replaceAll(itemName, newItemName); + content = content.replaceAll(varName, newVarName); + } - return content; + // Function + const testFunction = content.match(functionRegExp); + if (testFunction) { + const functionName = testFunction.join(""); + const newFunctionName = functionName.replaceAll(itemName, newItemName); + content = content.replaceAll(functionName, newFunctionName); + } + + // 2 - Ir em todos arquivos que dependem deste arquivo e mudar o nome do item lá + + return { content, fileSchemas }; }; /** @@ -271,7 +355,11 @@ const handleNames = (fileSchemas) => { let fileContent = fileSchema?.content || ""; // Processed content - fileContent = process_file(null, fileContent); + // const transpileTypescript = + // itemKey.endsWith(".ts") || itemKey.endsWith(".tsx"); + // fileContent = process_file_content(fileContent, transpileTypescript); + + // console.log("TEMP:", fileContent); // Checa se o nome dos exports do arquivo já existem no bundle // ex: exportObj = {MyVar: "MyVar"} @@ -300,11 +388,20 @@ const handleNames = (fileSchemas) => { /** * = {"caminho/arquivo.tsx": [index of export key][key name]} */ - exportsOrganizer[itemKey][objIndex][exportKeyName] = - newName(exportKeyName); + const newName = createNewName(exportKeyName); + exportsOrganizer[itemKey][objIndex][exportKeyName] = newName; // exportsOrganizer[itemKey][importKeyName] = 'NewName' - // atualiza o fileContent + // atualiza o fileContent com os novos items + console.log("BEFORE:", fileContent); + fileContent = replaceNamesInContent( + fileContent, + exportKeyName, + newName, + itemKey, + fileSchemas, + ).content; + console.log("AFTER:", fileContent); // ...e atualiza o nome do item nos arquivos que dependem dele } @@ -319,7 +416,7 @@ const handleNames = (fileSchemas) => { }); // console.log(itemsToProcess); - console.log("AFTER:", exportsOrganizer); + // console.log("AFTER:", exportsOrganizer); // console.log(tempBundle); }; diff --git a/lib/parse.js b/lib/parse.js index 48a4f85..b7f3a5c 100644 --- a/lib/parse.js +++ b/lib/parse.js @@ -9,15 +9,26 @@ const sucraseOptions = { disableESTransforms: true, }; -// process each file (using its path or its content) +// process file content +function process_file_content(fileContent, shouldTranspileTypescript) { + if (shouldTranspileTypescript) { + fileContent = transpileTypescript(fileContent); + } + + // Remove imports and exports + fileContent = removeImports(fileContent); + fileContent = removeExports(fileContent); + + // return file content + return fileContent; +} + +// process each file (using its path) // function process_file(filePath, { aliases, account }) { -function process_file(filePath, _fileContent) { - let fileContent = _fileContent || fs.readFileSync(filePath, "utf8"); +function process_file(filePath) { + let fileContent = fs.readFileSync(filePath, "utf8"); - if ( - !_fileContent && - (filePath.endsWith(".ts") || filePath.endsWith(".tsx")) - ) { + if (filePath.endsWith(".ts") || filePath.endsWith(".tsx")) { fileContent = transpileTypescript(fileContent); } @@ -123,6 +134,7 @@ const injectHTML = (html, injections) => { }; module.exports = { + process_file_content, process_file, ignoreFiles, removeComments, diff --git a/lib/regexp.js b/lib/regexp.js index 2b7b91a..32c8dc8 100644 --- a/lib/regexp.js +++ b/lib/regexp.js @@ -25,6 +25,10 @@ const BETWEEN_EXPORT_LET_AND_EQUAL = /(?<=export let)(.*?)(?==)/gm; // ENTRE export var e = const BETWEEN_EXPORT_VAR_AND_EQUAL = /(?<=export var)(.*?)(?==)/gm; +// ENTRE export function e ( +const BETWEEN_EXPORT_FUNCTION_AND_OPEN_PARENTHESE = + /(?<=export function)(.*?)(?=\()/gm; + // ENTRE export default function e ( const BETWEEN_EXPORT_DEFAULT_FUNCTION_AND_OPEN_PARENTHESE = /(?<=export default function)(.*?)(?=\()/gm; @@ -44,6 +48,7 @@ module.exports = { BETWEEN_EXPORT_CONST_AND_EQUAL, BETWEEN_EXPORT_LET_AND_EQUAL, BETWEEN_EXPORT_VAR_AND_EQUAL, + BETWEEN_EXPORT_FUNCTION_AND_OPEN_PARENTHESE, BETWEEN_EXPORT_DEFAULT_FUNCTION_AND_OPEN_PARENTHESE, AFTER_EXPORT_DEFAULT, }; From 94965ffbd7b64546c3bc810d61805291cf9c2eae Mon Sep 17 00:00:00 2001 From: Wenderson Pires Date: Mon, 11 Mar 2024 18:46:46 -0300 Subject: [PATCH 4/8] wip --- lib/actions/handleNames.js | 86 +++++++++++++++++++++++++++++++------- 1 file changed, 72 insertions(+), 14 deletions(-) diff --git a/lib/actions/handleNames.js b/lib/actions/handleNames.js index 5e1e673..d161d76 100644 --- a/lib/actions/handleNames.js +++ b/lib/actions/handleNames.js @@ -175,17 +175,54 @@ const createNewName = (currentName) => { /** * Change the fileSchema.content in other files when a dependent item gets its name changed * @param {string} contentFilePath + * @param {string} itemName + * @param {string} newItemName * @param {{filePath: string, toImport: string[], content: string}[]} fileSchemas schemas to change the files content when a item gets its name changed */ -const replaceItemNamesInOtherFilesContent = (fileSchemas) => { +const replaceItemNamesInOtherFilesContent = ( + contentFilePath, + itemName, + newItemName, + fileSchemas, +) => { /** * 1 - quando trocar o nome do item, tem que checar pra ser exato para evitar essa situacao * App.fooBaar * AppRoute.blabla - * + * * Quero trocar o "App" por "App__2", se nao verificar o valor exato, o "AppRoute" - * também vai ser alterado erroneamente. + * também vai ser alterado erroneamente. ex: "App__2Route". */ + + console.log("CHORAAAA:"); + // console.log(fileSchemas); + fileSchemas.forEach((fileSchema, fileSchemaIndex) => { + // Verifica se esse fileSchema depende do arquivo atual + if (fileSchema.toImport.includes(contentFilePath)) { + // Se tiver, altera o conteúdo deste arquivo para usar o novo nome do item importado + // do arquivo atual + let fileSchemaContent = fileSchema.content; + + // RegExp aqui + // Regex: Troca somente e tão somente o item, nem mais nem menos, evitando assim + // trocar items erronamente como na descricao acima. + const replaceItemRegexp = new RegExp("\\b" + itemName + "\\b", "gm"); + console.log("AAAAAAAA", fileSchemaContent, replaceItemRegexp, fileSchema); + fileSchemaContent = fileSchemaContent.replaceAll( + replaceItemRegexp, + newItemName, + ); + + console.log("BBBBBBBB", fileSchemaContent); + + // Seta novo valor + // console.log("AAAAAAAA", fileSchemas[fileSchemaIndex].content); + fileSchemas[fileSchemaIndex].content = fileSchemaContent; + // console.log("BBBBBBBBB", fileSchemas[fileSchemaIndex].content); + } + }); + + return fileSchemas; }; /** @@ -233,7 +270,7 @@ const replaceNamesInContent = ( fileSchemas = replaceItemNamesInOtherFilesContent( contentFilePath, itemName, - newItemName + newItemName, fileSchemas, ); } @@ -244,6 +281,12 @@ const replaceNamesInContent = ( const letName = testLet.join(""); const newLetName = letName.replaceAll(itemName, newItemName); content = content.replaceAll(letName, newLetName); + fileSchemas = replaceItemNamesInOtherFilesContent( + contentFilePath, + itemName, + newItemName, + fileSchemas, + ); } // Var @@ -252,6 +295,12 @@ const replaceNamesInContent = ( const varName = testVar.join(""); const newVarName = varName.replaceAll(itemName, newItemName); content = content.replaceAll(varName, newVarName); + fileSchemas = replaceItemNamesInOtherFilesContent( + contentFilePath, + itemName, + newItemName, + fileSchemas, + ); } // Function @@ -260,6 +309,12 @@ const replaceNamesInContent = ( const functionName = testFunction.join(""); const newFunctionName = functionName.replaceAll(itemName, newItemName); content = content.replaceAll(functionName, newFunctionName); + fileSchemas = replaceItemNamesInOtherFilesContent( + contentFilePath, + itemName, + newItemName, + fileSchemas, + ); } // 2 - Ir em todos arquivos que dependem deste arquivo e mudar o nome do item lá @@ -341,7 +396,7 @@ const handleNames = (fileSchemas) => { * } */ const exportsOrganizer = getExportsOrganizer(fileSchemas); - console.log("BEFORE", exportsOrganizer); + // console.log("BEFORE", exportsOrganizer); // Observe and changes duplicated names // reverse (need to load deepest content first) @@ -372,11 +427,11 @@ const handleNames = (fileSchemas) => { const exportKeyName = Object.keys(exportObj)[0]; // console.log(exportKeyName); // Verifica se ja tem um recurso (const, var, let, function) usando esse nome - console.log( - "BRUUUUTUUUUSSS:", - checkIfItemExistInContent(tempBundle, exportKeyName), - exportKeyName, - ); + // console.log( + // "BRUUUUTUUUUSSS:", + // checkIfItemExistInContent(tempBundle, exportKeyName), + // exportKeyName, + // ); if (checkIfItemExistInContent(tempBundle, exportKeyName)) { // Se tiver, troca o nome no arquivo/conteudo atual... console.log("TEM IGUAL PAI:", exportKeyName); @@ -393,15 +448,18 @@ const handleNames = (fileSchemas) => { // exportsOrganizer[itemKey][importKeyName] = 'NewName' // atualiza o fileContent com os novos items - console.log("BEFORE:", fileContent); - fileContent = replaceNamesInContent( + // console.log("BEFORE:", fileContent); + const result = replaceNamesInContent( fileContent, exportKeyName, newName, itemKey, fileSchemas, - ).content; - console.log("AFTER:", fileContent); + ); + + fileContent = result.content; + // console.log("SCHEMAAAAA ALTERADO", result.fileSchemas); + // console.log("AFTER:", fileContent); // ...e atualiza o nome do item nos arquivos que dependem dele } From a93e91b650d30edc4abf2dcabb5845a31d12c367 Mon Sep 17 00:00:00 2001 From: Wenderson Pires Date: Mon, 11 Mar 2024 20:37:31 -0300 Subject: [PATCH 5/8] first final version: success after first test --- lib/actions/handleNames.js | 74 +++++++++++++++++++++++++++++++-- lib/actions/loadFilesContent.js | 24 +++++++++-- lib/actions/loadFilesInfo.js | 8 ++-- lib/compiler.js | 9 ++-- lib/helpers.js | 22 +++++++++- lib/parse.js | 7 +--- lib/regexp.js | 13 +++--- 7 files changed, 130 insertions(+), 27 deletions(-) diff --git a/lib/actions/handleNames.js b/lib/actions/handleNames.js index d161d76..1ca73d3 100644 --- a/lib/actions/handleNames.js +++ b/lib/actions/handleNames.js @@ -2,7 +2,6 @@ * Handle const/var/let names to avoid duplicates */ -const { process_file, process_file_content } = require("../parse"); const { BETWEEN_EXPORT_CONST_AND_EQUAL, SPACES, @@ -207,13 +206,13 @@ const replaceItemNamesInOtherFilesContent = ( // Regex: Troca somente e tão somente o item, nem mais nem menos, evitando assim // trocar items erronamente como na descricao acima. const replaceItemRegexp = new RegExp("\\b" + itemName + "\\b", "gm"); - console.log("AAAAAAAA", fileSchemaContent, replaceItemRegexp, fileSchema); + // console.log("AAAAAAAA", fileSchemaContent, replaceItemRegexp, fileSchema); fileSchemaContent = fileSchemaContent.replaceAll( replaceItemRegexp, newItemName, ); - console.log("BBBBBBBB", fileSchemaContent); + // console.log("BBBBBBBB", fileSchemaContent); // Seta novo valor // console.log("AAAAAAAA", fileSchemas[fileSchemaIndex].content); @@ -225,6 +224,28 @@ const replaceItemNamesInOtherFilesContent = ( return fileSchemas; }; +/** + * Replace content in current file (inside the fileSchema) + * @param {string} contentFilePath + * @param {string} content + * @param {{filePath: string, toImport: string[], content: string}[]} fileSchemas schemas to change the files content when a item gets its name changed + */ +const replaceContentInCurrentFile = (contentFilePath, content, fileSchemas) => { + const currentFileSchema = fileSchemas.find( + (item) => item.filePath === contentFilePath, + ); + const fileSchemaIndex = fileSchemas.indexOf(currentFileSchema); + + // Update content + currentFileSchema.content = content; + + fileSchemas[fileSchemaIndex] = currentFileSchema; + + // console.log(currentFileSchema); + + return fileSchemas; +}; + /** * Replace the item name inside the content * @param {string} content @@ -267,6 +288,15 @@ const replaceNamesInContent = ( const constName = testConst.join(""); const newConstName = constName.replaceAll(itemName, newItemName); content = content.replaceAll(constName, newConstName); + + // Replace content (with updated item names) in current file + fileSchemas = replaceContentInCurrentFile( + contentFilePath, + content, + fileSchemas, + ); + + // Replace item names in other files content fileSchemas = replaceItemNamesInOtherFilesContent( contentFilePath, itemName, @@ -281,6 +311,15 @@ const replaceNamesInContent = ( const letName = testLet.join(""); const newLetName = letName.replaceAll(itemName, newItemName); content = content.replaceAll(letName, newLetName); + + // Replace content (with updated item names) in current file + fileSchemas = replaceContentInCurrentFile( + contentFilePath, + content, + fileSchemas, + ); + + // Replace item names in other files content fileSchemas = replaceItemNamesInOtherFilesContent( contentFilePath, itemName, @@ -295,6 +334,15 @@ const replaceNamesInContent = ( const varName = testVar.join(""); const newVarName = varName.replaceAll(itemName, newItemName); content = content.replaceAll(varName, newVarName); + + // Replace content (with updated item names) in current file + fileSchemas = replaceContentInCurrentFile( + contentFilePath, + content, + fileSchemas, + ); + + // Replace item names in other files content fileSchemas = replaceItemNamesInOtherFilesContent( contentFilePath, itemName, @@ -309,6 +357,15 @@ const replaceNamesInContent = ( const functionName = testFunction.join(""); const newFunctionName = functionName.replaceAll(itemName, newItemName); content = content.replaceAll(functionName, newFunctionName); + + // Replace content (with updated item names) in current file + fileSchemas = replaceContentInCurrentFile( + contentFilePath, + content, + fileSchemas, + ); + + // Replace item names in other files content fileSchemas = replaceItemNamesInOtherFilesContent( contentFilePath, itemName, @@ -458,7 +515,13 @@ const handleNames = (fileSchemas) => { ); fileContent = result.content; + // console.log("CHANGED FILE CONTENT:", fileContent); + fileSchemas = result.fileSchemas; + // console.log(itemKey); + // console.log(result.fileSchemas.filter((v) => v.filePath === itemKey)); + // console.log("SCHEMAAAAA ALTERADO", result.fileSchemas); + // console.log("A"); // console.log("AFTER:", fileContent); // ...e atualiza o nome do item nos arquivos que dependem dele @@ -466,6 +529,7 @@ const handleNames = (fileSchemas) => { // console.log(exportObj); }); + // console.log("CHANGED FILE CONTENT:", fileContent); tempBundle += fileContent; // console.log(itemContent); @@ -476,6 +540,10 @@ const handleNames = (fileSchemas) => { // console.log("AFTER:", exportsOrganizer); // console.log(tempBundle); + + // console.log("SCHEMAAAAA ALTERADO", fileSchemas); + + return fileSchemas; }; module.exports = handleNames; diff --git a/lib/actions/loadFilesContent.js b/lib/actions/loadFilesContent.js index 6b7b177..113597e 100644 --- a/lib/actions/loadFilesContent.js +++ b/lib/actions/loadFilesContent.js @@ -1,4 +1,4 @@ -const { process_file } = require("../parse"); +const { process_file, process_file_content } = require("../parse"); // Load App Files Content based on files schema // const loadFilesContent = (orderedFilesToImport) => { @@ -11,7 +11,6 @@ const { process_file } = require("../parse"); // }; /** - * (Recommended) * Load files based on the filePath sequence */ const loadFilesContent = (filesToLoad) => { @@ -23,6 +22,25 @@ const loadFilesContent = (filesToLoad) => { return bundleFile; }; +/** + * (Recommended) + * Load files based on the fileSchemas sequence + * @param {{filePath: string, toImport: string[], content: string}[]} fileSchemas + */ +const loadFilesContentByFileSchemas = (fileSchemas) => { + let bundleFile = ""; + // Reverse sequence to load the deepest first + fileSchemas = fileSchemas.reverse(); + fileSchemas.forEach((fileSchema) => { + const transpileTypescript = + fileSchema.filePath.endsWith(".ts") || + fileSchema.filePath.endsWith(".tsx"); + bundleFile += process_file_content(fileSchema.content, transpileTypescript); + }); + + return bundleFile; +}; + /** * NOTE: Esse modelo joga as dependencias pra cima */ @@ -77,4 +95,4 @@ const loadFilesContent = (filesToLoad) => { // return bundleFile; // }; -module.exports = loadFilesContent; +module.exports = loadFilesContentByFileSchemas; diff --git a/lib/actions/loadFilesInfo.js b/lib/actions/loadFilesInfo.js index d319f8b..3bc28bf 100644 --- a/lib/actions/loadFilesInfo.js +++ b/lib/actions/loadFilesInfo.js @@ -122,13 +122,11 @@ const loadFilesInfo = (entryFile) => { }); // Handle names -> remove const duplicates - // contentOrderer = handleNames(contentOrderer); - handleNames(contentOrderer); - - // console.log(contentOrderer); + contentOrderer = handleNames(contentOrderer); + // console.log("BATINA:", contentOrderer); return { - filesSchema: contentOrderer, + fileSchemas: contentOrderer, // orderedFilesToImport: orderedFilesToImport.reverse(), orderedFilesToImport: contentOrderer .map((schema) => schema.filePath) diff --git a/lib/compiler.js b/lib/compiler.js index 33b1f9a..2d28ce7 100644 --- a/lib/compiler.js +++ b/lib/compiler.js @@ -35,8 +35,10 @@ function compile_files() { const filesInfo = loadFilesInfo(entryFile); - // console.log("Files Schema:"); - // console.log(filesInfo.filesSchema); + console.log("Files Schema:"); + console.log(filesInfo.fileSchemas); + + console.log("orderedFilesToImport", filesInfo.orderedFilesToImport); // NOTE /** @@ -51,7 +53,8 @@ function compile_files() { let bundleContent = toolsFiles.loadHeaderFilesContent(); // Load App files content - bundleContent += loadFilesContent(filesInfo.orderedFilesToImport); + // bundleContent += loadFilesContent(filesInfo.orderedFilesToImport); + bundleContent += loadFilesContent(filesInfo.fileSchemas); // Tools -> Indexer bundleContent += toolsFiles.loadIndexerContent(); diff --git a/lib/helpers.js b/lib/helpers.js index 2034362..bf845e2 100644 --- a/lib/helpers.js +++ b/lib/helpers.js @@ -35,7 +35,7 @@ const getFileImportsElements = (fileContent) => { * @returns */ const getImportStatements = (fileContent) => - fileContent.match(regexp.IMPORT_STATEMENT); + fileContent.match(regexp.GET_ALL_IMPORT_STATEMENT); /** * Get Import's path @@ -47,7 +47,7 @@ const getImportStatements = (fileContent) => */ const getImportsPath = (fileContent) => { let result = []; - const importStatements = fileContent.match(regexp.IMPORT_STATEMENT_2); + const importStatements = fileContent.match(regexp.GET_ALL_IMPORT_STATEMENT); if (importStatements) { importStatements.forEach((value) => @@ -58,6 +58,24 @@ const getImportsPath = (fileContent) => { } return result; + + // let result = []; + + // const regex = + // /import\s+([^{},]+|\{([^{}]+)\})(?:,\s+([^{},]+|\{([^{}]+)\}))*\s+from/g; + + // let matches; + + // while ((matches = regex.exec(fileContent)) !== null) { + // for (let i = 1; i < matches.length; i++) { + // if (matches[i] !== undefined) { + // result.push(matches[i].trim()); + // } + // } + // } + + // // console.log(items); // Saída: ["Sidebar", "Des", "Foo"] + // return result; }; /** diff --git a/lib/parse.js b/lib/parse.js index b7f3a5c..44e0b2f 100644 --- a/lib/parse.js +++ b/lib/parse.js @@ -1,6 +1,7 @@ const fs = require("fs"); const sucrase = require("sucrase"); const { read_bos_config } = require("./config"); +const { EXPORT_AND_EXPORT_DEFAULT } = require("./regexp"); const sucraseOptions = { transforms: ["typescript", "jsx"], @@ -55,11 +56,7 @@ const ignoreFiles = (c) => /\/\*__@ignore__\*\//.test(c); // no stringify json files // const noStringifyJsonFiles = (c) => /\/\*__@noStringify__\*\//.test(c); -const removeExports = (c) => - c - .replaceAll("export const", "const") - .replaceAll("export default function", "function") - .replaceAll(/^(export)(?:.*?(default))*.*$/gm, ""); // TODO: Test export default with multiple lines +const removeExports = (c) => c.replaceAll(EXPORT_AND_EXPORT_DEFAULT, ""); const removeImports = (c) => { // Remove line breaks diff --git a/lib/regexp.js b/lib/regexp.js index 32c8dc8..60ca4b7 100644 --- a/lib/regexp.js +++ b/lib/regexp.js @@ -9,10 +9,9 @@ const GET_ALL_BETWEEN_IMPORT_AND_FROM = /(?<=import)(.*?)(?=from)/gm; const SPACES = /\s/g; // # LINE BREAKS const LINE_BREAKS = /\r?\n|\r/g; -// # IMPORT STATEMENT. ex: import { AppBackground, AppContainer } from "./styles"; -const IMPORT_STATEMENT = /^(import)(?:.*?(as))?(?:.*?(as))?(?:.*?(from))*.*$/gm; -const IMPORT_STATEMENT_2 = - /^[ \t]*(import)\s+(?:\{[^}]*\}|\w+)\s+(from\s+)?["']([^"']+)["'];?$/gm; // USAR ESSE! +// # Pega todos os import statements, inclusive aqueles com quebra de linha +const GET_ALL_IMPORT_STATEMENT = + /(import\s+.*?\s+from\s+['"].*?['"])|(import\s+({[\s\S]+?}|[^{}]+)\s+from\s+['"].*?['"])/g; // # BETWEEN quotation marks const BETWEEN_QUOTES = /(?<=")(.*?)(?=")/gm; @@ -36,14 +35,15 @@ const BETWEEN_EXPORT_DEFAULT_FUNCTION_AND_OPEN_PARENTHESE = // VALOR DEPOIS DE export default const AFTER_EXPORT_DEFAULT = /(?<=export default).*/gm; +const EXPORT_AND_EXPORT_DEFAULT = /export\s+default|export(?!\s+default)/g; + module.exports = { SPECIAL_CHARACTERS, SPECIAL_CHARACTERS_AND_SPACES, GET_ALL_BETWEEN_IMPORT_AND_FROM, SPACES, LINE_BREAKS, - IMPORT_STATEMENT, - IMPORT_STATEMENT_2, + GET_ALL_IMPORT_STATEMENT, BETWEEN_QUOTES, BETWEEN_EXPORT_CONST_AND_EQUAL, BETWEEN_EXPORT_LET_AND_EQUAL, @@ -51,6 +51,7 @@ module.exports = { BETWEEN_EXPORT_FUNCTION_AND_OPEN_PARENTHESE, BETWEEN_EXPORT_DEFAULT_FUNCTION_AND_OPEN_PARENTHESE, AFTER_EXPORT_DEFAULT, + EXPORT_AND_EXPORT_DEFAULT, }; // ENTRE export const e = From 020fca25ed292cc0b2bb65a6fd1677ca9bbabab8 Mon Sep 17 00:00:00 2001 From: Wenderson Pires Date: Mon, 11 Mar 2024 21:39:47 -0300 Subject: [PATCH 6/8] final adjustments --- docs/feature-overview.md | 26 ------- lib/actions/handleNames.js | 131 ++++---------------------------- lib/actions/loadFilesContent.js | 18 +++-- lib/actions/loadFilesInfo.js | 5 +- lib/compiler.js | 20 +---- lib/helpers.js | 18 ----- lib/utils.js | 30 ++++++++ package.json | 2 +- roadmap.md | 2 +- 9 files changed, 63 insertions(+), 189 deletions(-) diff --git a/docs/feature-overview.md b/docs/feature-overview.md index 2756be7..78dc7bc 100644 --- a/docs/feature-overview.md +++ b/docs/feature-overview.md @@ -41,29 +41,3 @@ export const ComponentB = () => { return ; }; ``` - -## Good to Know - -You can't use the same name for things. Otherwise, the compiler will break. - -### Correct - -```ts -// fileA.ts -const MyValue = 2; - -// fileB.ts -const MyValueB = 5; -``` - -### Incorrect - -The example below will break up the app because both consts are using the same name. - -```ts -// fileA.ts -const MyValue = 2; - -// fileB.ts -const MyValue = 5; -``` diff --git a/lib/actions/handleNames.js b/lib/actions/handleNames.js index 1ca73d3..19b4b3e 100644 --- a/lib/actions/handleNames.js +++ b/lib/actions/handleNames.js @@ -12,6 +12,11 @@ const { BETWEEN_EXPORT_VAR_AND_EQUAL, BETWEEN_EXPORT_FUNCTION_AND_OPEN_PARENTHESE, } = require("../regexp"); +const { + capitalize_first_letter, + get_randon_hexadecimal, + get_random_character, +} = require("../utils"); /** * Get "export const" items @@ -136,7 +141,6 @@ const getExportsOrganizer = (fileSchemas) => { exportsOrganizer[schema.filePath] = []; let exports = []; - // getExportConsts(schema.content); // Verifica se já tem os nomes de elementos no conteúdo anterior // exports = [...exports, ...getExportConsts(schema.content)]; @@ -152,23 +156,20 @@ const getExportsOrganizer = (fileSchemas) => { exports.forEach((exportItem) => exportsOrganizer[schema.filePath].push({ [exportItem]: exportItem }), ); - - // exports.push(...getExportConsts(schema.content)); - // console.log(exports); }); return exportsOrganizer; }; -// TODO: gerar hash com hash anterior -let nonce = 0; /** * Generate new name * @param {string} currentName */ -const createNewName = (currentName) => { - nonce++; - return `${currentName}_______${nonce}`; +const createNewName = () => { + let randomHexName = get_randon_hexadecimal(6); + return capitalize_first_letter( + `${get_random_character()}${get_random_character()}_${randomHexName}`, + ); }; /** @@ -193,8 +194,6 @@ const replaceItemNamesInOtherFilesContent = ( * também vai ser alterado erroneamente. ex: "App__2Route". */ - console.log("CHORAAAA:"); - // console.log(fileSchemas); fileSchemas.forEach((fileSchema, fileSchemaIndex) => { // Verifica se esse fileSchema depende do arquivo atual if (fileSchema.toImport.includes(contentFilePath)) { @@ -206,18 +205,14 @@ const replaceItemNamesInOtherFilesContent = ( // Regex: Troca somente e tão somente o item, nem mais nem menos, evitando assim // trocar items erronamente como na descricao acima. const replaceItemRegexp = new RegExp("\\b" + itemName + "\\b", "gm"); - // console.log("AAAAAAAA", fileSchemaContent, replaceItemRegexp, fileSchema); + fileSchemaContent = fileSchemaContent.replaceAll( replaceItemRegexp, newItemName, ); - // console.log("BBBBBBBB", fileSchemaContent); - // Seta novo valor - // console.log("AAAAAAAA", fileSchemas[fileSchemaIndex].content); fileSchemas[fileSchemaIndex].content = fileSchemaContent; - // console.log("BBBBBBBBB", fileSchemas[fileSchemaIndex].content); } }); @@ -241,8 +236,6 @@ const replaceContentInCurrentFile = (contentFilePath, content, fileSchemas) => { fileSchemas[fileSchemaIndex] = currentFileSchema; - // console.log(currentFileSchema); - return fileSchemas; }; @@ -275,12 +268,8 @@ const replaceNamesInContent = ( "gm", ); - // content = content.replaceAll(constRegExp, `const ${newItemName}`); - // content = content.replaceAll(letRegExp, `let ${newItemName}`); - // content = content.replaceAll(varRegExp, `var ${newItemName}`); - // content = content.replaceAll(functionRegExp, `function ${newItemName}`); - - // 1 - Testa, se aprovado, mudar o nome dos items no corpo do arquivo + // 1 - Testa, se aprovado, mudar o nome dos items no corpo do arquivo atual + // 2 - Ir em todos arquivos que dependem deste arquivo e mudar o nome do item lá // Const const testConst = content.match(constRegExp); @@ -374,8 +363,6 @@ const replaceNamesInContent = ( ); } - // 2 - Ir em todos arquivos que dependem deste arquivo e mudar o nome do item lá - return { content, fileSchemas }; }; @@ -398,34 +385,6 @@ const checkIfItemExistInContent = (content, itemName) => { "gm", ); - // const - // if (itemName === "Des") { - // const has = content.match(constRegExp); - - // if (has) { - // console.log( - // "NAO TEM? HUMMM ===>", - // constRegExp.test(content), - // // content.match(functionRegExp).join("").replaceAll("(", ""), - // content.includes(`const ${itemName}`), - // ); - // } - // } - - // Function - // if (itemName === "Des") { - // const has = content.match(functionRegExp); - // if (has) { - // console.log( - // "NAO TEM? HUMMM ===>", - // functionRegExp, - // functionRegExp.test(content), - // content.match(functionRegExp).join("").replaceAll("(", ""), - // content.includes(`function ${itemName}`), - // ); - // } - // } - return Boolean( content.match(constRegExp) || content.match(letRegExp) || @@ -453,7 +412,6 @@ const handleNames = (fileSchemas) => { * } */ const exportsOrganizer = getExportsOrganizer(fileSchemas); - // console.log("BEFORE", exportsOrganizer); // Observe and changes duplicated names // reverse (need to load deepest content first) @@ -466,37 +424,16 @@ const handleNames = (fileSchemas) => { let fileContent = fileSchema?.content || ""; - // Processed content - // const transpileTypescript = - // itemKey.endsWith(".ts") || itemKey.endsWith(".tsx"); - // fileContent = process_file_content(fileContent, transpileTypescript); - - // console.log("TEMP:", fileContent); - // Checa se o nome dos exports do arquivo já existem no bundle - // ex: exportObj = {MyVar: "MyVar"} - // console.log("BEEEEEEEEEEEEE", exportsOrganizer[itemKey]); // Exports do arquivo atual exportsOrganizer[itemKey].forEach((exportObj, objIndex) => { - // exceto o propio arquivo - // console.log("BEEEEEEEEEEEEE", exportsOrganizer[itemKey]); - // if (itemKey !== ) const exportKeyName = Object.keys(exportObj)[0]; - // console.log(exportKeyName); + // Verifica se ja tem um recurso (const, var, let, function) usando esse nome - // console.log( - // "BRUUUUTUUUUSSS:", - // checkIfItemExistInContent(tempBundle, exportKeyName), - // exportKeyName, - // ); if (checkIfItemExistInContent(tempBundle, exportKeyName)) { // Se tiver, troca o nome no arquivo/conteudo atual... - console.log("TEM IGUAL PAI:", exportKeyName); + // Troca nome do item no organizer - // console.log( - // "FOOO:", - // exportsOrganizer[itemKey][objIndex][exportKeyName], - // ); /** * = {"caminho/arquivo.tsx": [index of export key][key name]} */ @@ -505,7 +442,7 @@ const handleNames = (fileSchemas) => { // exportsOrganizer[itemKey][importKeyName] = 'NewName' // atualiza o fileContent com os novos items - // console.log("BEFORE:", fileContent); + // ...e atualiza o nome do item nos arquivos que dependem dele const result = replaceNamesInContent( fileContent, exportKeyName, @@ -515,50 +452,14 @@ const handleNames = (fileSchemas) => { ); fileContent = result.content; - // console.log("CHANGED FILE CONTENT:", fileContent); fileSchemas = result.fileSchemas; - // console.log(itemKey); - // console.log(result.fileSchemas.filter((v) => v.filePath === itemKey)); - - // console.log("SCHEMAAAAA ALTERADO", result.fileSchemas); - // console.log("A"); - // console.log("AFTER:", fileContent); - - // ...e atualiza o nome do item nos arquivos que dependem dele } - // console.log(exportObj); }); - // console.log("CHANGED FILE CONTENT:", fileContent); tempBundle += fileContent; - - // console.log(itemContent); - // Referencia o conteúdo do item - // const itemContent = item; }); - // console.log(itemsToProcess); - - // console.log("AFTER:", exportsOrganizer); - // console.log(tempBundle); - - // console.log("SCHEMAAAAA ALTERADO", fileSchemas); return fileSchemas; }; module.exports = handleNames; - -// 1 - Ler o schema de cada arquivo (loadFilesInfo faz isso) -// 2 - Pegar esses dados e checar conteudo de arquivo por arquivo se tem duplicidade -// 3 - Gerar o seguinte esquema - -/** - * exports organizer - * { - * "caminho/do/arquivo.jsx": [{MyVar: "MyVar_newName"}, {MyVar2: "MyVar2_nameName"}] - * } - */ - -// - Carregar o conteúdo do arquivo anterior -// - No arquivo atual, checar se seus exports / export defaul já existe no conteúdo anterior -// - Se já existir, muda o nome das vars no arquivo atual diff --git a/lib/actions/loadFilesContent.js b/lib/actions/loadFilesContent.js index 113597e..e93adb1 100644 --- a/lib/actions/loadFilesContent.js +++ b/lib/actions/loadFilesContent.js @@ -13,14 +13,14 @@ const { process_file, process_file_content } = require("../parse"); /** * Load files based on the filePath sequence */ -const loadFilesContent = (filesToLoad) => { - let bundleFile = ""; - filesToLoad.forEach((filePath) => { - bundleFile += process_file(filePath); - }); +// const loadFilesContent = (filesToLoad) => { +// let bundleFile = ""; +// filesToLoad.forEach((filePath) => { +// bundleFile += process_file(filePath); +// }); - return bundleFile; -}; +// return bundleFile; +// }; /** * (Recommended) @@ -95,4 +95,6 @@ const loadFilesContentByFileSchemas = (fileSchemas) => { // return bundleFile; // }; -module.exports = loadFilesContentByFileSchemas; +module.exports = { + loadFilesContentByFileSchemas, +}; diff --git a/lib/actions/loadFilesInfo.js b/lib/actions/loadFilesInfo.js index 3bc28bf..ccc8e19 100644 --- a/lib/actions/loadFilesInfo.js +++ b/lib/actions/loadFilesInfo.js @@ -36,8 +36,7 @@ const processFileSchema = (filePath) => { if (orderedFilesToImport.length === 0) { orderedFilesToImport.push(filePath); } - // console.log("\n\n"); - // console.log("Processando:", filePath, "||"); + let parentFolder = "."; if (filePath) { const parentPathParts = filePath.split("/"); @@ -92,7 +91,6 @@ const processFileSchema = (filePath) => { contentOrderer.push(currentFileSchema); // Recursividade - // console.log("RECURSIVIDADE:"); currentFileSchema.nextFilesToLoad.forEach((fileToImport) => { processFileSchema(fileToImport); }); @@ -123,7 +121,6 @@ const loadFilesInfo = (entryFile) => { // Handle names -> remove const duplicates contentOrderer = handleNames(contentOrderer); - // console.log("BATINA:", contentOrderer); return { fileSchemas: contentOrderer, diff --git a/lib/compiler.js b/lib/compiler.js index 2d28ce7..81e08d0 100644 --- a/lib/compiler.js +++ b/lib/compiler.js @@ -35,26 +35,14 @@ function compile_files() { const filesInfo = loadFilesInfo(entryFile); - console.log("Files Schema:"); - console.log(filesInfo.fileSchemas); - - console.log("orderedFilesToImport", filesInfo.orderedFilesToImport); - - // NOTE - /** - * Se essa ordem abaixo nao funcionar, mudar a hierarquia de carga pra carregar - * linearmente todo os items do arquivo sendo processado. - */ - // console.log("\n\n"); - // console.log("Ordered Files to Import:"); - // console.log(filesInfo.orderedFilesToImport); - // Tools -> Header contents let bundleContent = toolsFiles.loadHeaderFilesContent(); // Load App files content // bundleContent += loadFilesContent(filesInfo.orderedFilesToImport); - bundleContent += loadFilesContent(filesInfo.fileSchemas); + bundleContent += loadFilesContent.loadFilesContentByFileSchemas( + filesInfo.fileSchemas, + ); // Tools -> Indexer bundleContent += toolsFiles.loadIndexerContent(); @@ -74,7 +62,7 @@ function compile_files() { bundleContent = parseOptions(bundleContent); // Mimify - bundleContent = mimify(bundleContent); + // bundleContent = mimify(bundleContent); // Add sinatures bundleContent = addSignatures(bundleContent); diff --git a/lib/helpers.js b/lib/helpers.js index bf845e2..8ba0118 100644 --- a/lib/helpers.js +++ b/lib/helpers.js @@ -58,24 +58,6 @@ const getImportsPath = (fileContent) => { } return result; - - // let result = []; - - // const regex = - // /import\s+([^{},]+|\{([^{}]+)\})(?:,\s+([^{},]+|\{([^{}]+)\}))*\s+from/g; - - // let matches; - - // while ((matches = regex.exec(fileContent)) !== null) { - // for (let i = 1; i < matches.length; i++) { - // if (matches[i] !== undefined) { - // result.push(matches[i].trim()); - // } - // } - // } - - // // console.log(items); // Saída: ["Sidebar", "Des", "Foo"] - // return result; }; /** diff --git a/lib/utils.js b/lib/utils.js index 21d386f..d60f8a7 100644 --- a/lib/utils.js +++ b/lib/utils.js @@ -141,9 +141,39 @@ const log = { }, }; +/** + * Generates random hexadecimal value + * @param {number} size + * @returns + */ +const get_randon_hexadecimal = function (size) { + let maxlen = 8; + let min = Math.pow(16, Math.min(size, maxlen) - 1); + let max = Math.pow(16, Math.min(size, maxlen)) - 1; + let n = Math.floor(Math.random() * (max - min + 1)) + min; + let r = n.toString(16); + while (r.length < size) { + r = r + get_randon_hexadecimal(size - maxlen); + } + return r; +}; + +const get_random_character = () => { + const characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; + const randomIndex = Math.floor(Math.random() * characters.length); + return characters.charAt(randomIndex); +}; + +const capitalize_first_letter = (word) => { + return word.charAt(0).toUpperCase() + word.slice(1); +}; + module.exports = { create_dist, for_rfile, for_folder, log, + get_randon_hexadecimal, + get_random_character, + capitalize_first_letter, }; diff --git a/package.json b/package.json index 7abe461..30a2d9e 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "alem", "description": "Create web3 applications for NEAR BOS with a focus on performance and friendly development.", - "version": "0.0.1-alpha.20", + "version": "0.0.1-alpha.21", "main": "main.js", "types": "index.d.ts", "author": "Wenderson Pires - wendersonpires.near", diff --git a/roadmap.md b/roadmap.md index 05b4cfa..5ee6b45 100644 --- a/roadmap.md +++ b/roadmap.md @@ -4,4 +4,4 @@ - Add parameter `parameterName` for `Routes` component. This is going to allow changing the default route param name ("path") that's used to control and watch all routes. - ✔ - Implement feature to the compiler that changes the consts/lets/vars names to avoid conflicts. - Add support to tsconfig.json `baseUrl` and `paths`. -- Support to using the same const names in different files. +- Support to using the same const names in different files. - ✔ From fb628468ca7ab17ce5b52e55e67a0c2b993c33f5 Mon Sep 17 00:00:00 2001 From: Wenderson Pires Date: Mon, 11 Mar 2024 21:43:03 -0300 Subject: [PATCH 7/8] fix typo mimify -> minify --- lib/compiler.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/compiler.js b/lib/compiler.js index 81e08d0..b70b546 100644 --- a/lib/compiler.js +++ b/lib/compiler.js @@ -62,7 +62,7 @@ function compile_files() { bundleContent = parseOptions(bundleContent); // Mimify - // bundleContent = mimify(bundleContent); + bundleContent = mimify(bundleContent); // Add sinatures bundleContent = addSignatures(bundleContent); From 8a171b6d0d5350c37d9adf4c7a4f61deadc7c6e4 Mon Sep 17 00:00:00 2001 From: Wenderson Pires Date: Mon, 11 Mar 2024 21:44:06 -0300 Subject: [PATCH 8/8] fix typo mimify -> minify --- lib/compiler.js | 4 ++-- lib/parse.js | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/lib/compiler.js b/lib/compiler.js index b70b546..8d28e29 100644 --- a/lib/compiler.js +++ b/lib/compiler.js @@ -9,7 +9,7 @@ const { removeBlankLines, applyEnvironment, parseOptions, - mimify, + minify, } = require("./parse"); const saveFinalBundleFile = require("./actions/saveFinalBundleFile"); const addSignatures = require("./actions/addSignatures"); @@ -62,7 +62,7 @@ function compile_files() { bundleContent = parseOptions(bundleContent); // Mimify - bundleContent = mimify(bundleContent); + bundleContent = minify(bundleContent); // Add sinatures bundleContent = addSignatures(bundleContent); diff --git a/lib/parse.js b/lib/parse.js index 44e0b2f..e80872c 100644 --- a/lib/parse.js +++ b/lib/parse.js @@ -104,7 +104,7 @@ const parseOptions = (c) => { return c; }; -const mimify = (c) => +const minify = (c) => c .replace(/\r?\n|\r/gm, "") .replace(/\s+/gm, " ") @@ -139,7 +139,7 @@ module.exports = { removeExports, removeImports, removeBlankLines, - mimify, + minify, applyEnvironment, parseOptions, };