Skip to content

Commit

Permalink
extractJSXElements error display
Browse files Browse the repository at this point in the history
  • Loading branch information
wpdas committed Mar 30, 2024
1 parent d99c0cb commit 13e7f1c
Show file tree
Hide file tree
Showing 5 changed files with 85 additions and 29 deletions.
7 changes: 4 additions & 3 deletions lib/actions/loadFilesContent.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ const loadFilesContentByFileSchemas = (fileSchemas) => {
// Get Normal js files & Widget files (components transformed to BOS Widgets)
const completeFileSchemas = transformSchemaToWidget(fileSchemas);

completeFileSchemas.forEach((fileSchema) => {
completeFileSchemas.fileSchemas.forEach((fileSchema) => {
bundleFile += fileSchema.finalFileBundle;
});

Expand Down Expand Up @@ -47,7 +47,7 @@ const loadComponentCodesObjectByFileSchemas = (
additionalFileSchemas,
);

completeFileSchemas.forEach((fileSchema) => {
completeFileSchemas.fileSchemas.forEach((fileSchema) => {
if (fileSchema.widgetName && !fileSchema.isModule) {
componentsCodes += `
${fileSchema.widgetName}: \`${scapeBacktick(fileSchema.finalFileBundle)}\`,
Expand All @@ -65,7 +65,8 @@ const loadComponentCodesObjectByFileSchemas = (
/** Código final do componente App de entrada do projet apenas. (src/index.tsx | .jsx) */
appComponentFinalBundle,
/** Esquema final de todos os arquivos processados */
completeFileSchemas,
completeFileSchemas: completeFileSchemas.fileSchemas,
error: completeFileSchemas.processError,
};
};

Expand Down
4 changes: 2 additions & 2 deletions lib/actions/renderErrorDisplay.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
const { escapeHtmlEntities, cleanErrorMessage } = require("../helpers");
const { cleanErrorMessage, scapeBacktick } = require("../helpers");

/**
* Cria o elemento JSX para mostrar o Erro encontrado.
Expand All @@ -20,7 +20,7 @@ style={{
wordWrap: "break-word",
color: "#990000",
}}
>${escapeHtmlEntities(cleanErrorMessage(error))}</pre>
>${`{\`${scapeBacktick(cleanErrorMessage(error))}\`}`}</pre>
</div>`;

module.exports = renderErrorDisplay;
47 changes: 43 additions & 4 deletions lib/actions/transformSchemaToWidget.js
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,8 @@ const analyzeFunctionSignature = require("../parsers/analyzeFunctionSignature");
const removeFunctionParams = require("../parsers/removeFunctionParams");
const transformAsyncAwait = require("../parsers/transformAsyncAwait");

let processError = null;

/**
* @param {string} content
*/
Expand Down Expand Up @@ -449,6 +451,8 @@ const swapComponentsForStatelessFiles = (fileSchemas, fileSchema) => {
importFileSchema.filePath === importItemFileSource,
);

console.log("PROCESSING A");

const importItemWidgetComponentName =
importItemWidget.widgetName ||
getComponentName(importItemWidget.finalFileBundle);
Expand All @@ -464,8 +468,12 @@ const swapComponentsForStatelessFiles = (fileSchemas, fileSchema) => {
// importItemWidgetComponentName,
// );

console.log("PROCESSING B");

const jsxOnly = extractJSX(fileSchema.content);

console.log("PROCESSING C");

const fixedJsxOnly =
jsxOnly.length > 1
? `<>${jsxOnly.join("\n")}</>`
Expand All @@ -476,18 +484,29 @@ const swapComponentsForStatelessFiles = (fileSchemas, fileSchema) => {
importItemWidgetComponentName,
);

// Seta qualquer erro se tiver
if (!processError && componentElements.error) {
processError = `${fileSchema.filePath}: ${componentElements.error}`;
console.log("\n");
console.log("ERRO AQUI?", processError);
console.log("\n");
}
if (processError) return;

console.log("PROCESSING D");

// console.log(componentElements);

// Transfor cada componente em Widget com suas propriedades
componentElements.forEach((div, divIndex) => {
componentElements.elements.forEach((div, divIndex) => {
// Converte as propriedades em um texto contendo a sequencia de chaves e valores das propriedades do Componente
// const childProps = (
// importItemElements[divIndex]
// ? importItemElements[divIndex]
// : { props: {} }
// ).props;

const htmlElementString = componentElements[divIndex]
const htmlElementString = componentElements.elements[divIndex]
.toString()
.replaceAll(LINE_BREAKS, "")
.replaceAll(MORE_THAN_ONE_SPACE, " ");
Expand Down Expand Up @@ -790,15 +809,19 @@ const prepareAlemDependencies = (fileSchema) => {
return fileSchema;
};

// * @returns {{filePath: string, toImport: string[], content: string, finalFileBundle: string, componentImportItems:[], componentParamsItems:[], componentComponentItems: [], widgetName?: string, htmlElementsProps: {}}[]}

/**
* @param {{filePath: string, toImport: string[], content: string}[]} fileSchemas
* @param {*} additionalFileSchemas FileSchemas to be added to the list of main fileSchemas. It's going to be added first before
* the process starts. This is util to inject previous schema files like Além importable items.
* @returns {{filePath: string, toImport: string[], content: string, finalFileBundle: string, componentImportItems:[], componentParamsItems:[], componentComponentItems: [], widgetName?: string, htmlElementsProps: {}}[]}
*/
const transformSchemaToWidget = (fileSchemas, additionalFileSchemas) => {
// TODO: trocar esse nome, transformSchemaToWidget -> transformSchemaToWidgetSchema
// Reset error state
processError = null;

console.log("A");
// Tag alem files (INFO: Isso não está servindo pra nada atualmente)
fileSchemas.forEach((fileSchema, fileSchemaIndex) => {
const isAlemImportableFile = fileSchema.filePath.includes(
Expand All @@ -809,31 +832,41 @@ const transformSchemaToWidget = (fileSchemas, additionalFileSchemas) => {
fileSchemas[fileSchemaIndex] = fileSchema;
});

console.log("B");
// Caso tenha dependencias do Alem (inportable items), prepara eles para serem injetados
// Remove os elementos da chave em que está e coloca em uma nova linha contendo seu caminho
// até a lib alem-vm/importable/item...
fileSchemas.forEach((fileSchema, fileSchemaIndex) => {
fileSchemas[fileSchemaIndex] = prepareAlemDependencies(fileSchema);
});

console.log("C");

// Adiciona schemas já processados dos items importáveis do Além (hahaha)
if (additionalFileSchemas) {
fileSchemas = [...additionalFileSchemas, ...fileSchemas];
}

console.log("D");

// Gera o primeiro finalFileBundle e widgetName(para Widgets somente), parametros e imports
fileSchemas.forEach((fileSchema, fileSchemaIndex) => {
fileSchemas[fileSchemaIndex] = processSchema(fileSchema);
});

console.log("E");

fileSchemas.forEach((fileSchema, fileSchemaIndex) => {
// Processa arquivos que contenham elementos html mas são stateless
console.log("Current file:", fileSchema.filePath);
fileSchemas[fileSchemaIndex] = swapComponentsForStatelessFiles(
fileSchemas,
fileSchema,
);
});

console.log("F");

// Prepara lista de arquivos a serem injetados dentro de cada arquivo
fileSchemas.forEach((fileSchema, fileSchemaIndex) => {
fileSchemas[fileSchemaIndex] = prepareListOfInjections(
Expand All @@ -842,6 +875,8 @@ const transformSchemaToWidget = (fileSchemas, additionalFileSchemas) => {
);
});

console.log("G");

// Copia e cola o conteúdo de arquivos não .tsx | .jsx para dentro dos arquivos que dependem deles
fileSchemas.forEach((fileSchema, fileSchemaIndex) => {
fileSchemas[fileSchemaIndex] = injectFilesDependencies(
Expand All @@ -850,6 +885,8 @@ const transformSchemaToWidget = (fileSchemas, additionalFileSchemas) => {
);
});

console.log("H");

// Faz transformação de async/await para o formato promisify
fileSchemas.forEach((fileSchema, fileSchemaIndex) => {
fileSchema.finalFileBundle = transformAsyncAwait(
Expand All @@ -858,7 +895,9 @@ const transformSchemaToWidget = (fileSchemas, additionalFileSchemas) => {
fileSchemas[fileSchemaIndex] = fileSchema;
});

return fileSchemas;
console.log("ERRRROOOO?", processError);

return { fileSchemas, processError };
};

module.exports = transformSchemaToWidget;
9 changes: 9 additions & 0 deletions lib/compiler.js
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,15 @@ function compile_files() {
alemImportableFilesSchema,
);

if (finishedSchemaProcessForWidgets.error) {
// Save bundle file with error info
const errorDisplay = renderErrorDisplay(
finishedSchemaProcessForWidgets.error,
);
saveFinalBundleFile(errorDisplay);
return;
}

let widgetsCodes = finishedSchemaProcessForWidgets.componentsCodes;

// Alem VM -> Header contents
Expand Down
47 changes: 27 additions & 20 deletions lib/parsers/extractJSXElements.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ const babel = require("@babel/core");
const traverse = require("@babel/traverse").default;
const generate = require("@babel/generator").default;
const presetReactPath = require("./presetReactPath");
const { log } = require("../utils");

/**
* Extract JSX Elements and return an array with them
Expand All @@ -20,33 +21,39 @@ const presetReactPath = require("./presetReactPath");
function extractJSXElements(code, filterByElementType) {
// V2
const elements = [];
let error = null;

// Parse the code to AST
const ast = babel.parse(code, {
presets: [presetReactPath],
});
try {
// Parse the code to AST
const ast = babel.parse(code, {
presets: [presetReactPath],
});

// Traverse the AST to find elements of the specified type
traverse(ast, {
JSXElement(path) {
// Caso tenha filtro, retorna somente os elementos que sao do nome especificado
if (filterByElementType) {
// Verifica se o nome do elemento corresponde ao filterByElementType
if (path.node.openingElement.name.name === filterByElementType) {
// Utiliza generate para extrair o código completo do elemento JSX
// Traverse the AST to find elements of the specified type
traverse(ast, {
JSXElement(path) {
// Caso tenha filtro, retorna somente os elementos que sao do nome especificado
if (filterByElementType) {
// Verifica se o nome do elemento corresponde ao filterByElementType
if (path.node.openingElement.name.name === filterByElementType) {
// Utiliza generate para extrair o código completo do elemento JSX
const { code: elementCode } = generate(path.node);
elements.push(elementCode);
}
} else {
// Se não tiver filtro, retorna todos os elementos
const { code: elementCode } = generate(path.node);
elements.push(elementCode);
}
} else {
// Se não tiver filtro, retorna todos os elementos
const { code: elementCode } = generate(path.node);
elements.push(elementCode);
}
},
});
},
});
} catch (error_) {
error = `The compiler was unable to process this line. Try another way. \n ${error_}`;
}

return elements;
return { elements, error };
}

// function extractJSXElements(code, elementType) {
// const elements = [];

Expand Down

0 comments on commit 13e7f1c

Please sign in to comment.