types-nora-api 0.0.146 → 0.0.148

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,255 @@
1
+ /**
2
+ * UTILITÁRIOS PARA EXTRAÇÃO DE TIPOS
3
+ * Arquivo: extrairClasses.utils.ts
4
+ */
5
+ import * as ts from 'typescript';
6
+ import { readFileSync, existsSync, readdirSync, statSync, mkdirSync } from 'fs';
7
+ import { join } from 'path';
8
+ // ==================================================
9
+ // CONSTANTES E CONFIGURAÇÕES COMPARTILHADAS
10
+ // ==================================================
11
+ /**
12
+ * Marcador para definições que devem ser compartilhadas com o frontend
13
+ */
14
+ export const TIPO_COMPARTILHADO_FRONT_MARKER = '@tipoCompartilhadoFront';
15
+ // ==================================================
16
+ // TYPE GUARDS MELHORADOS
17
+ // ==================================================
18
+ function isNamedNode(node) {
19
+ return 'name' in node &&
20
+ node.name !== undefined &&
21
+ ts.isIdentifier(node.name);
22
+ }
23
+ function isVariableStatement(node) {
24
+ return ts.isVariableStatement(node);
25
+ }
26
+ function isClassDeclarationWithName(node) {
27
+ return ts.isClassDeclaration(node) && node.name !== undefined && ts.isIdentifier(node.name);
28
+ }
29
+ function isInterfaceDeclarationWithName(node) {
30
+ return ts.isInterfaceDeclaration(node) && node.name !== undefined && ts.isIdentifier(node.name);
31
+ }
32
+ function isTypeAliasDeclarationWithName(node) {
33
+ return ts.isTypeAliasDeclaration(node) && node.name !== undefined && ts.isIdentifier(node.name);
34
+ }
35
+ function isEnumDeclarationWithName(node) {
36
+ return ts.isEnumDeclaration(node) && node.name !== undefined && ts.isIdentifier(node.name);
37
+ }
38
+ function isModuleDeclarationWithName(node) {
39
+ return ts.isModuleDeclaration(node) && node.name !== undefined && ts.isIdentifier(node.name);
40
+ }
41
+ function isFunctionDeclarationWithName(node) {
42
+ return ts.isFunctionDeclaration(node) && node.name !== undefined && ts.isIdentifier(node.name);
43
+ }
44
+ // ==================================================
45
+ // VALIDAÇÕES E VERIFICAÇÕES
46
+ // ==================================================
47
+ /**
48
+ * Verifica se um nó AST possui o marcador @tipoCompartilhadoFront
49
+ */
50
+ export function hasTipoCompartilhadoFrontMarker(node, fileContent) {
51
+ const leadingComments = ts.getLeadingCommentRanges(fileContent, node.pos);
52
+ if (!leadingComments)
53
+ return false;
54
+ return leadingComments.some(comment => {
55
+ const commentText = fileContent.substring(comment.pos, comment.end);
56
+ return commentText.includes(TIPO_COMPARTILHADO_FRONT_MARKER);
57
+ });
58
+ }
59
+ /**
60
+ * Verifica se uma declaração de variável deve ser considerada para extração
61
+ */
62
+ export function shouldExtractVariableStatement(node, snippet) {
63
+ const declarationList = node.declarationList;
64
+ const declarations = declarationList.declarations;
65
+ const hasAsConst = snippet.includes(' as const');
66
+ const hasTypeAnnotation = declarations.some(decl => decl.type);
67
+ const hasComplexInitializer = declarations.some(decl => {
68
+ if (!decl.initializer)
69
+ return false;
70
+ return (ts.isObjectLiteralExpression(decl.initializer) ||
71
+ ts.isArrayLiteralExpression(decl.initializer) ||
72
+ ts.isCallExpression(decl.initializer) ||
73
+ ts.isArrowFunction(decl.initializer) ||
74
+ ts.isFunctionExpression(decl.initializer));
75
+ });
76
+ return hasAsConst || hasTypeAnnotation || hasComplexInitializer;
77
+ }
78
+ // ==================================================
79
+ // IDENTIFICAÇÃO DE TIPOS DE NÓ
80
+ // ==================================================
81
+ /**
82
+ * Verifica se um nó deve ser extraído baseado no filtro
83
+ */
84
+ export function shouldExtractNode(node, filterType, fileContent, snippet) {
85
+ // Para filtro ALL, extrai tudo que é extraível
86
+ if (filterType === 'ALL') {
87
+ if (isVariableStatement(node)) {
88
+ return shouldExtractVariableStatement(node, snippet);
89
+ }
90
+ return (isClassDeclarationWithName(node) ||
91
+ isInterfaceDeclarationWithName(node) ||
92
+ isTypeAliasDeclarationWithName(node) ||
93
+ isEnumDeclarationWithName(node) ||
94
+ isModuleDeclarationWithName(node) ||
95
+ isFunctionDeclarationWithName(node));
96
+ }
97
+ // Para filtro MARKED, só extrai se tiver o marcador
98
+ if (filterType === 'MARKED') {
99
+ const hasMarker = hasTipoCompartilhadoFrontMarker(node, fileContent);
100
+ if (isVariableStatement(node)) {
101
+ return hasMarker || shouldExtractVariableStatement(node, snippet);
102
+ }
103
+ return hasMarker && (isClassDeclarationWithName(node) ||
104
+ isInterfaceDeclarationWithName(node) ||
105
+ isTypeAliasDeclarationWithName(node) ||
106
+ isEnumDeclarationWithName(node) ||
107
+ isModuleDeclarationWithName(node) ||
108
+ isFunctionDeclarationWithName(node));
109
+ }
110
+ return false;
111
+ }
112
+ // ==================================================
113
+ // MANIPULAÇÃO DE CONTEÚDO
114
+ // ==================================================
115
+ /**
116
+ * Remove palavras-chave de export mantendo a declaração
117
+ */
118
+ export function removeExportKeywords(content) {
119
+ return content
120
+ .replace(/^export\s+(default\s+)?/gm, '')
121
+ .replace(/export\s+(default\s+)?\{[^}]+\};?\n?/g, '')
122
+ .trim();
123
+ }
124
+ /**
125
+ * Extrai nomes de identificadores de declarações de variável
126
+ */
127
+ export function extractVariableNames(node) {
128
+ const names = [];
129
+ const declarationList = node.declarationList;
130
+ declarationList.declarations.forEach(declaration => {
131
+ if (ts.isIdentifier(declaration.name)) {
132
+ names.push(declaration.name.text);
133
+ }
134
+ });
135
+ return names;
136
+ }
137
+ /**
138
+ * Extrai o nome de um nó nomeado
139
+ */
140
+ export function extractNodeName(node) {
141
+ if (isClassDeclarationWithName(node))
142
+ return node.name.text;
143
+ if (isInterfaceDeclarationWithName(node))
144
+ return node.name.text;
145
+ if (isTypeAliasDeclarationWithName(node))
146
+ return node.name.text;
147
+ if (isEnumDeclarationWithName(node))
148
+ return node.name.text;
149
+ if (isModuleDeclarationWithName(node))
150
+ return node.name.text;
151
+ if (isFunctionDeclarationWithName(node))
152
+ return node.name.text;
153
+ return null;
154
+ }
155
+ // ==================================================
156
+ // PROCESSAMENTO DE ARQUIVOS
157
+ // ==================================================
158
+ /**
159
+ * Encontra recursivamente arquivos .type.ts em um diretório
160
+ */
161
+ export function findTypeFiles(dir) {
162
+ if (!existsSync(dir)) {
163
+ throw new Error(`Diretório não encontrado: ${dir}`);
164
+ }
165
+ let results = [];
166
+ const items = readdirSync(dir);
167
+ for (const item of items) {
168
+ const itemPath = join(dir, item);
169
+ const stat = statSync(itemPath);
170
+ if (stat.isDirectory()) {
171
+ results = results.concat(findTypeFiles(itemPath));
172
+ }
173
+ else if (item.endsWith('.type.ts')) {
174
+ results.push(itemPath);
175
+ }
176
+ }
177
+ return results;
178
+ }
179
+ /**
180
+ * Garante que um diretório existe (cria se necessário)
181
+ */
182
+ export function ensureDirectoryExists(dirPath) {
183
+ if (!existsSync(dirPath)) {
184
+ mkdirSync(dirPath, { recursive: true });
185
+ }
186
+ }
187
+ /**
188
+ * Cria um SourceFile TypeScript para análise AST
189
+ */
190
+ export function createTypeScriptSourceFile(filePath, fileContent) {
191
+ return ts.createSourceFile(filePath, fileContent, ts.ScriptTarget.Latest, true);
192
+ }
193
+ // ==================================================
194
+ // PROCESSAMENTO MODULAR DO OUTPUT
195
+ // ==================================================
196
+ /**
197
+ * Processa um arquivo individual e extrai suas definições
198
+ */
199
+ export function processFile(filePath, filterType) {
200
+ if (!existsSync(filePath)) {
201
+ console.warn(`Arquivo não encontrado: ${filePath}`);
202
+ return { content: '', exportedNames: [], filePath };
203
+ }
204
+ const fileContent = readFileSync(filePath, 'utf8');
205
+ const sourceFile = createTypeScriptSourceFile(filePath, fileContent);
206
+ let extractedContent = '';
207
+ const exportedNames = [];
208
+ ts.forEachChild(sourceFile, (node) => {
209
+ const snippet = fileContent.substring(node.pos, node.end);
210
+ if (shouldExtractNode(node, filterType, fileContent, snippet)) {
211
+ const cleanedContent = removeExportKeywords(snippet);
212
+ extractedContent += `${cleanedContent}\n`;
213
+ // Coleta nomes baseado no tipo de nó
214
+ if (isVariableStatement(node)) {
215
+ const names = extractVariableNames(node);
216
+ exportedNames.push(...names);
217
+ }
218
+ else {
219
+ const name = extractNodeName(node);
220
+ if (name) {
221
+ exportedNames.push(name);
222
+ }
223
+ }
224
+ }
225
+ });
226
+ console.log(`Processado: ${filePath} (${exportedNames.length} definições)`);
227
+ return {
228
+ content: extractedContent,
229
+ exportedNames,
230
+ filePath
231
+ };
232
+ }
233
+ /**
234
+ * Consolida resultados de múltiplos arquivos em conteúdo final
235
+ */
236
+ export function consolidateResults(processingResults, header = '') {
237
+ let consolidatedContent = header;
238
+ const allExportedNames = new Set();
239
+ // Adiciona conteúdo de cada arquivo
240
+ for (const result of processingResults) {
241
+ if (result.content) {
242
+ consolidatedContent += result.content + '\n';
243
+ result.exportedNames.forEach(name => allExportedNames.add(name));
244
+ }
245
+ }
246
+ // Adiciona export final se houver nomes
247
+ if (allExportedNames.size > 0) {
248
+ consolidatedContent += `\nexport {\n ${Array.from(allExportedNames).join(',\n ')}\n};\n`;
249
+ }
250
+ // Limpeza final
251
+ return consolidatedContent
252
+ .replace(/\n{3,}/g, '\n\n')
253
+ .replace(/^\s+$/gm, '')
254
+ .trim();
255
+ }