@silasfmartins/testhub 1.0.0

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.
Files changed (296) hide show
  1. package/.github/copilot-instructions.md +520 -0
  2. package/biome.json +37 -0
  3. package/dist/index.d.ts +45 -0
  4. package/dist/index.js +169 -0
  5. package/dist/scripts/consumer-postinstall.d.ts +15 -0
  6. package/dist/scripts/consumer-postinstall.js +785 -0
  7. package/dist/scripts/generate-docs.d.ts +16 -0
  8. package/dist/scripts/generate-docs.js +1363 -0
  9. package/dist/scripts/generate-index.d.ts +2 -0
  10. package/dist/scripts/generate-index.js +314 -0
  11. package/dist/scripts/init-api.d.ts +2 -0
  12. package/dist/scripts/init-api.js +525 -0
  13. package/dist/scripts/init-banco.d.ts +2 -0
  14. package/dist/scripts/init-banco.js +347 -0
  15. package/dist/scripts/init-frontend.d.ts +2 -0
  16. package/dist/scripts/init-frontend.js +627 -0
  17. package/dist/scripts/init-mobile.d.ts +2 -0
  18. package/dist/scripts/init-mobile.js +481 -0
  19. package/dist/scripts/init-scenarios.d.ts +2 -0
  20. package/dist/scripts/init-scenarios.js +846 -0
  21. package/dist/scripts/init-ssh.d.ts +2 -0
  22. package/dist/scripts/init-ssh.js +639 -0
  23. package/dist/scripts/package-versions.d.ts +57 -0
  24. package/dist/scripts/package-versions.js +768 -0
  25. package/dist/scripts/postinstall.d.ts +1 -0
  26. package/dist/scripts/postinstall.js +527 -0
  27. package/dist/scripts/robust-build.d.ts +7 -0
  28. package/dist/scripts/robust-build.js +88 -0
  29. package/dist/scripts/setup-local-packages.d.ts +31 -0
  30. package/dist/scripts/setup-local-packages.js +237 -0
  31. package/dist/scripts/smart-override.d.ts +2 -0
  32. package/dist/scripts/smart-override.js +1360 -0
  33. package/dist/scripts/sync-configs.d.ts +27 -0
  34. package/dist/scripts/sync-configs.js +248 -0
  35. package/dist/scripts/test-biome-parse.d.ts +5 -0
  36. package/dist/scripts/test-biome-parse.js +84 -0
  37. package/dist/scripts/ultracite-setup.d.ts +4 -0
  38. package/dist/scripts/ultracite-setup.js +310 -0
  39. package/dist/scripts/update-all-init-scripts.d.ts +2 -0
  40. package/dist/scripts/update-all-init-scripts.js +52 -0
  41. package/dist/scripts/update-biome-schema.d.ts +15 -0
  42. package/dist/scripts/update-biome-schema.js +124 -0
  43. package/dist/src/AutoCoreFacade.d.ts +145 -0
  44. package/dist/src/AutoCoreFacade.js +217 -0
  45. package/dist/src/api/ApiActions.d.ts +297 -0
  46. package/dist/src/api/ApiActions.js +1905 -0
  47. package/dist/src/api/Certificate.d.ts +60 -0
  48. package/dist/src/api/Certificate.js +79 -0
  49. package/dist/src/api/JsonResponse.d.ts +116 -0
  50. package/dist/src/api/JsonResponse.js +206 -0
  51. package/dist/src/appium/DeviceFarmViewer.d.ts +79 -0
  52. package/dist/src/appium/DeviceFarmViewer.js +1083 -0
  53. package/dist/src/appium/MobileActions.d.ts +347 -0
  54. package/dist/src/appium/MobileActions.js +1632 -0
  55. package/dist/src/appium/MobileConnection.d.ts +160 -0
  56. package/dist/src/appium/MobileConnection.js +772 -0
  57. package/dist/src/config/envLoader.d.ts +123 -0
  58. package/dist/src/config/envLoader.js +361 -0
  59. package/dist/src/config/jest-safe-setup.d.ts +19 -0
  60. package/dist/src/config/jest-safe-setup.js +369 -0
  61. package/dist/src/config/timeouts.d.ts +32 -0
  62. package/dist/src/config/timeouts.js +38 -0
  63. package/dist/src/desktop/DesktopActions.d.ts +46 -0
  64. package/dist/src/desktop/DesktopActions.js +398 -0
  65. package/dist/src/desktop/DesktopConnection.d.ts +32 -0
  66. package/dist/src/desktop/DesktopConnection.js +84 -0
  67. package/dist/src/domain/entities/TestExecution.d.ts +117 -0
  68. package/dist/src/domain/entities/TestExecution.js +150 -0
  69. package/dist/src/domain/entities/TestReport.d.ts +114 -0
  70. package/dist/src/domain/entities/TestReport.js +179 -0
  71. package/dist/src/domain/repositories/ITestRepository.d.ts +196 -0
  72. package/dist/src/domain/repositories/ITestRepository.js +14 -0
  73. package/dist/src/domain/schemas/ValidationSchemas.d.ts +159 -0
  74. package/dist/src/domain/schemas/ValidationSchemas.js +181 -0
  75. package/dist/src/functions/errors/BaseError.d.ts +78 -0
  76. package/dist/src/functions/errors/BaseError.js +245 -0
  77. package/dist/src/functions/errors/ConfigurationError.d.ts +16 -0
  78. package/dist/src/functions/errors/ConfigurationError.js +48 -0
  79. package/dist/src/functions/errors/ErrorCatalog.d.ts +148 -0
  80. package/dist/src/functions/errors/ErrorCatalog.js +157 -0
  81. package/dist/src/functions/errors/GlobalErrorHandler.d.ts +101 -0
  82. package/dist/src/functions/errors/GlobalErrorHandler.js +281 -0
  83. package/dist/src/functions/errors/IntegrationError.d.ts +17 -0
  84. package/dist/src/functions/errors/IntegrationError.js +51 -0
  85. package/dist/src/functions/errors/SecurityError.d.ts +14 -0
  86. package/dist/src/functions/errors/SecurityError.js +42 -0
  87. package/dist/src/functions/errors/SystemError.d.ts +12 -0
  88. package/dist/src/functions/errors/SystemError.js +36 -0
  89. package/dist/src/functions/errors/ValidationError.d.ts +14 -0
  90. package/dist/src/functions/errors/ValidationError.js +61 -0
  91. package/dist/src/functions/errors/index.d.ts +12 -0
  92. package/dist/src/functions/errors/index.js +13 -0
  93. package/dist/src/global-setup.d.ts +1 -0
  94. package/dist/src/global-setup.js +1037 -0
  95. package/dist/src/helpers/BancoActions.d.ts +188 -0
  96. package/dist/src/helpers/BancoActions.js +581 -0
  97. package/dist/src/helpers/EnviromentHelper.d.ts +17 -0
  98. package/dist/src/helpers/EnviromentHelper.js +66 -0
  99. package/dist/src/helpers/ParallelExecutionHelper.d.ts +183 -0
  100. package/dist/src/helpers/ParallelExecutionHelper.js +375 -0
  101. package/dist/src/helpers/SyncSignal.d.ts +15 -0
  102. package/dist/src/helpers/SyncSignal.js +44 -0
  103. package/dist/src/hubdocs/CategoryDetector.d.ts +83 -0
  104. package/dist/src/hubdocs/CategoryDetector.js +401 -0
  105. package/dist/src/hubdocs/DirectStatementInterceptor.d.ts +54 -0
  106. package/dist/src/hubdocs/DirectStatementInterceptor.js +243 -0
  107. package/dist/src/hubdocs/ExecutionTracker.d.ts +107 -0
  108. package/dist/src/hubdocs/ExecutionTracker.js +702 -0
  109. package/dist/src/hubdocs/HubDocs.d.ts +395 -0
  110. package/dist/src/hubdocs/HubDocs.js +3586 -0
  111. package/dist/src/hubdocs/StatementMethodFilter.d.ts +71 -0
  112. package/dist/src/hubdocs/StatementMethodFilter.js +618 -0
  113. package/dist/src/hubdocs/StatementTracker.d.ts +417 -0
  114. package/dist/src/hubdocs/StatementTracker.js +2419 -0
  115. package/dist/src/hubdocs/SwaggerGenerator.d.ts +59 -0
  116. package/dist/src/hubdocs/SwaggerGenerator.js +405 -0
  117. package/dist/src/hubdocs/index.d.ts +9 -0
  118. package/dist/src/hubdocs/index.js +9 -0
  119. package/dist/src/hubdocs/types.d.ts +114 -0
  120. package/dist/src/hubdocs/types.js +5 -0
  121. package/dist/src/infrastructure/DependencyContainer.d.ts +142 -0
  122. package/dist/src/infrastructure/DependencyContainer.js +250 -0
  123. package/dist/src/infrastructure/adapters/AppiumAdapter.d.ts +168 -0
  124. package/dist/src/infrastructure/adapters/AppiumAdapter.js +468 -0
  125. package/dist/src/infrastructure/adapters/OracleAdapter.d.ts +150 -0
  126. package/dist/src/infrastructure/adapters/OracleAdapter.js +388 -0
  127. package/dist/src/infrastructure/adapters/PlaywrightAdapter.d.ts +192 -0
  128. package/dist/src/infrastructure/adapters/PlaywrightAdapter.js +382 -0
  129. package/dist/src/infrastructure/adapters/SSHAdapter.d.ts +141 -0
  130. package/dist/src/infrastructure/adapters/SSHAdapter.js +428 -0
  131. package/dist/src/interfaces.d.ts +501 -0
  132. package/dist/src/interfaces.js +25 -0
  133. package/dist/src/internal/fakes/__fake-actions__.d.ts +17 -0
  134. package/dist/src/internal/fakes/__fake-actions__.js +21 -0
  135. package/dist/src/internal/fakes/__forbidden__.d.ts +10 -0
  136. package/dist/src/internal/fakes/__forbidden__.js +18 -0
  137. package/dist/src/internal/fakes/__honeypot__.d.ts +15 -0
  138. package/dist/src/internal/fakes/__honeypot__.js +24 -0
  139. package/dist/src/octane/OctaneReporter.d.ts +13 -0
  140. package/dist/src/octane/OctaneReporter.js +61 -0
  141. package/dist/src/playwright/CryptoActions.d.ts +20 -0
  142. package/dist/src/playwright/CryptoActions.js +75 -0
  143. package/dist/src/playwright/EnhancedWebActions.d.ts +7 -0
  144. package/dist/src/playwright/EnhancedWebActions.js +65 -0
  145. package/dist/src/playwright/WebActions.d.ts +1599 -0
  146. package/dist/src/playwright/WebActions.js +11788 -0
  147. package/dist/src/playwright/actions/ActionTimeline.d.ts +36 -0
  148. package/dist/src/playwright/actions/ActionTimeline.js +101 -0
  149. package/dist/src/playwright/actions/RecoveryQueue.d.ts +82 -0
  150. package/dist/src/playwright/actions/RecoveryQueue.js +130 -0
  151. package/dist/src/playwright/actions/SelectorCache.d.ts +53 -0
  152. package/dist/src/playwright/actions/SelectorCache.js +96 -0
  153. package/dist/src/playwright/actions/index.d.ts +13 -0
  154. package/dist/src/playwright/actions/index.js +14 -0
  155. package/dist/src/playwright/actions/types.d.ts +147 -0
  156. package/dist/src/playwright/actions/types.js +5 -0
  157. package/dist/src/playwright/fixtures.d.ts +112 -0
  158. package/dist/src/playwright/fixtures.js +718 -0
  159. package/dist/src/playwright/network-logs-reporter.d.ts +7 -0
  160. package/dist/src/playwright/network-logs-reporter.js +66 -0
  161. package/dist/src/playwright/registerRecoveryWrappers.d.ts +1 -0
  162. package/dist/src/playwright/registerRecoveryWrappers.js +54 -0
  163. package/dist/src/security/BuildSecurity.d.ts +12 -0
  164. package/dist/src/security/BuildSecurity.js +138 -0
  165. package/dist/src/security/EulaProtection.d.ts +70 -0
  166. package/dist/src/security/EulaProtection.js +155 -0
  167. package/dist/src/security/HoneypotManager.d.ts +46 -0
  168. package/dist/src/security/HoneypotManager.js +234 -0
  169. package/dist/src/security/KeysManager.d.ts +36 -0
  170. package/dist/src/security/KeysManager.js +158 -0
  171. package/dist/src/security/ProofOfWorkIntegration.d.ts +64 -0
  172. package/dist/src/security/ProofOfWorkIntegration.js +206 -0
  173. package/dist/src/security/SecurityValidation.d.ts +21 -0
  174. package/dist/src/security/SecurityValidation.js +163 -0
  175. package/dist/src/security/SourceMapProtection.d.ts +55 -0
  176. package/dist/src/security/SourceMapProtection.js +220 -0
  177. package/dist/src/security/protector.d.ts +1 -0
  178. package/dist/src/security/protector.js +97 -0
  179. package/dist/src/ssh/SSHActions.d.ts +262 -0
  180. package/dist/src/ssh/SSHActions.js +790 -0
  181. package/dist/src/ssh/SSHClient.d.ts +99 -0
  182. package/dist/src/ssh/SSHClient.js +409 -0
  183. package/dist/src/statements/BaseStatement.d.ts +38 -0
  184. package/dist/src/statements/BaseStatement.js +78 -0
  185. package/dist/src/testContext/AuthStateManager.d.ts +93 -0
  186. package/dist/src/testContext/AuthStateManager.js +256 -0
  187. package/dist/src/testContext/CoverageManager.d.ts +198 -0
  188. package/dist/src/testContext/CoverageManager.js +917 -0
  189. package/dist/src/testContext/TestAnnotations.d.ts +476 -0
  190. package/dist/src/testContext/TestAnnotations.js +2647 -0
  191. package/dist/src/testContext/TestContext.d.ts +138 -0
  192. package/dist/src/testContext/TestContext.js +369 -0
  193. package/dist/src/testContext/UnifiedHtmlGenerator.d.ts +7 -0
  194. package/dist/src/testContext/UnifiedHtmlGenerator.js +264 -0
  195. package/dist/src/testContext/UnifiedReportManager.d.ts +211 -0
  196. package/dist/src/testContext/UnifiedReportManager.js +1206 -0
  197. package/dist/src/testhub/DynamicConfigManager.d.ts +121 -0
  198. package/dist/src/testhub/DynamicConfigManager.js +320 -0
  199. package/dist/src/testhub/SystemsManager.d.ts +119 -0
  200. package/dist/src/testhub/SystemsManager.js +365 -0
  201. package/dist/src/testhub/TestHubClient.d.ts +335 -0
  202. package/dist/src/testhub/TestHubClient.js +1215 -0
  203. package/dist/src/testhub/TestHubReporter.d.ts +62 -0
  204. package/dist/src/testhub/TestHubReporter.js +576 -0
  205. package/dist/src/testhub/TestHubVars.d.ts +116 -0
  206. package/dist/src/testhub/TestHubVars.js +273 -0
  207. package/dist/src/utils/ActionInterceptor.d.ts +59 -0
  208. package/dist/src/utils/ActionInterceptor.js +741 -0
  209. package/dist/src/utils/ArtifactsCompressor.d.ts +43 -0
  210. package/dist/src/utils/ArtifactsCompressor.js +181 -0
  211. package/dist/src/utils/AutoLogsFinal.d.ts +47 -0
  212. package/dist/src/utils/AutoLogsFinal.js +148 -0
  213. package/dist/src/utils/CodeGenSession.d.ts +114 -0
  214. package/dist/src/utils/CodeGenSession.js +264 -0
  215. package/dist/src/utils/ConfigLogger.d.ts +133 -0
  216. package/dist/src/utils/ConfigLogger.js +611 -0
  217. package/dist/src/utils/CustomReporter.d.ts +22 -0
  218. package/dist/src/utils/CustomReporter.js +352 -0
  219. package/dist/src/utils/DataStore.d.ts +171 -0
  220. package/dist/src/utils/DataStore.js +484 -0
  221. package/dist/src/utils/DatabaseInterceptor.d.ts +19 -0
  222. package/dist/src/utils/DatabaseInterceptor.js +295 -0
  223. package/dist/src/utils/DateHelper.d.ts +16 -0
  224. package/dist/src/utils/DateHelper.js +120 -0
  225. package/dist/src/utils/DateValidator.d.ts +4 -0
  226. package/dist/src/utils/DateValidator.js +51 -0
  227. package/dist/src/utils/DocumentGenerator.d.ts +35 -0
  228. package/dist/src/utils/DocumentGenerator.js +129 -0
  229. package/dist/src/utils/EvidenceCapture.d.ts +90 -0
  230. package/dist/src/utils/EvidenceCapture.js +600 -0
  231. package/dist/src/utils/EvidenceReportGenerator.d.ts +70 -0
  232. package/dist/src/utils/EvidenceReportGenerator.js +799 -0
  233. package/dist/src/utils/FrameManagementUtil.d.ts +42 -0
  234. package/dist/src/utils/FrameManagementUtil.js +75 -0
  235. package/dist/src/utils/GlobalStatementsInterceptor.d.ts +1 -0
  236. package/dist/src/utils/GlobalStatementsInterceptor.js +1 -0
  237. package/dist/src/utils/HTMLTemplate.d.ts +1 -0
  238. package/dist/src/utils/HTMLTemplate.js +1034 -0
  239. package/dist/src/utils/InterceptacaoMagica.d.ts +23 -0
  240. package/dist/src/utils/InterceptacaoMagica.js +365 -0
  241. package/dist/src/utils/LogSanitizer.d.ts +35 -0
  242. package/dist/src/utils/LogSanitizer.js +110 -0
  243. package/dist/src/utils/Logger.d.ts +65 -0
  244. package/dist/src/utils/Logger.js +284 -0
  245. package/dist/src/utils/McpLocalClient.d.ts +141 -0
  246. package/dist/src/utils/McpLocalClient.js +871 -0
  247. package/dist/src/utils/PDFEvidenceGenerator.d.ts +20 -0
  248. package/dist/src/utils/PDFEvidenceGenerator.js +156 -0
  249. package/dist/src/utils/SpecFileAnalyzer.d.ts +35 -0
  250. package/dist/src/utils/SpecFileAnalyzer.js +209 -0
  251. package/dist/src/utils/StatementInterceptor.d.ts +18 -0
  252. package/dist/src/utils/StatementInterceptor.js +87 -0
  253. package/dist/src/utils/StatementLogger.d.ts +33 -0
  254. package/dist/src/utils/StatementLogger.js +113 -0
  255. package/dist/src/utils/StatementsInterceptor.d.ts +1 -0
  256. package/dist/src/utils/StatementsInterceptor.js +1 -0
  257. package/dist/src/utils/TeamsFlushHook.d.ts +17 -0
  258. package/dist/src/utils/TeamsFlushHook.js +168 -0
  259. package/dist/src/utils/TerminalLogCapture.d.ts +158 -0
  260. package/dist/src/utils/TerminalLogCapture.js +531 -0
  261. package/dist/src/utils/TestMethodLogger.d.ts +70 -0
  262. package/dist/src/utils/TestMethodLogger.js +95 -0
  263. package/dist/src/utils/UnifiedTeardown.d.ts +4 -0
  264. package/dist/src/utils/UnifiedTeardown.js +400 -0
  265. package/dist/src/utils/XPathCatalog.d.ts +152 -0
  266. package/dist/src/utils/XPathCatalog.js +350 -0
  267. package/dist/src/utils/generators.d.ts +90 -0
  268. package/dist/src/utils/generators.js +167 -0
  269. package/dist/src/utils/testRecovery/ResilientPlaywright.d.ts +152 -0
  270. package/dist/src/utils/testRecovery/ResilientPlaywright.js +715 -0
  271. package/dist/src/utils/testRecovery/TestRecoveryClient.d.ts +801 -0
  272. package/dist/src/utils/testRecovery/TestRecoveryClient.js +1415 -0
  273. package/dist/src/utils/testRecovery/autoFixCode.d.ts +65 -0
  274. package/dist/src/utils/testRecovery/autoFixCode.js +32 -0
  275. package/dist/vitest.config.d.ts +2 -0
  276. package/dist/vitest.config.js +59 -0
  277. package/dist/wdio.conf.d.ts +1 -0
  278. package/dist/wdio.conf.js +420 -0
  279. package/package.json +137 -0
  280. package/protect-loader.mjs +643 -0
  281. package/scripts/consumer-postinstall.ts +975 -0
  282. package/scripts/generate-index.ts +343 -0
  283. package/scripts/init-api.ts +613 -0
  284. package/scripts/init-banco.ts +437 -0
  285. package/scripts/init-frontend.ts +727 -0
  286. package/scripts/init-mobile.ts +558 -0
  287. package/scripts/init-scenarios.ts +925 -0
  288. package/scripts/init-ssh.ts +734 -0
  289. package/scripts/package-versions.ts +978 -0
  290. package/scripts/postinstall.ts +605 -0
  291. package/scripts/smart-override.ts +1675 -0
  292. package/scripts/sync-configs.ts +302 -0
  293. package/scripts/ultracite-setup.ts +370 -0
  294. package/src/types/globals.d.ts +48 -0
  295. package/tsconfig.json +29 -0
  296. package/types/autocore-sync-signal.d.ts +10 -0
@@ -0,0 +1,123 @@
1
+ /**
2
+ * Interface que define as opções disponíveis para o carregamento de variáveis de ambiente
3
+ */
4
+ interface LoadEnvOptions {
5
+ /** Define se deve registrar as configurações carregadas no log */
6
+ logConfig?: boolean;
7
+ /** Define se os logs devem ser gravados em arquivo */
8
+ logToFile?: boolean;
9
+ /** Lista de variáveis de ambiente obrigatórias que devem estar definidas */
10
+ required?: string[];
11
+ /** Arquivos .env personalizados para carregar além dos padrões */
12
+ customEnvFiles?: string[];
13
+ /** Define se deve carregar arquivos específicos do modo de ambiente (ex: .env.test, .env.production) */
14
+ loadModeSpecificFiles?: boolean;
15
+ /** Define se deve aplicar logs silenciosos (para não poluir a saída) */
16
+ silent?: boolean;
17
+ /** Define se deve forçar o recarregamento mesmo se já foi carregado */
18
+ forceReload?: boolean;
19
+ }
20
+ /**
21
+ * Estado interno do carregador de ambiente
22
+ */
23
+ interface EnvLoaderState {
24
+ /** Indica se as variáveis já foram carregadas */
25
+ isLoaded: boolean;
26
+ /** Lista de arquivos .env carregados */
27
+ loadedFiles: string[];
28
+ /** Quantidade de variáveis carregadas */
29
+ loadedVarsCount: number;
30
+ /** Data/hora do último carregamento */
31
+ lastLoadTime: Date | null;
32
+ /** Modo de ambiente detectado (ex: preprod, staging) */
33
+ environmentMode: string | null;
34
+ }
35
+ /**
36
+ * Carrega variáveis de ambiente a partir de arquivos .env.
37
+ *
38
+ * Processa arquivos .env na seguinte ordem de prioridade:
39
+ * 1. Arquivo .env base (para obter ENV se não estiver definido)
40
+ * 2. Arquivo específico do ambiente (.env.preprod, .env.staging, etc)
41
+ * 3. Arquivos personalizados especificados em customEnvFiles
42
+ *
43
+ * Usa um mecanismo de bloqueio para evitar carregamentos múltiplos entre processos.
44
+ *
45
+ * @param options Configurações para controlar o comportamento de carregamento
46
+ * @throws {Error} Se ocorrer erro ao carregar variáveis
47
+ */
48
+ export declare function loadEnv(options?: LoadEnvOptions): void;
49
+ /**
50
+ * Limpa o arquivo de bloqueio usado para garantir que o ambiente
51
+ * seja carregado apenas uma vez entre diferentes processos.
52
+ * Também reseta o estado interno.
53
+ */
54
+ export declare function cleanupEnvLock(): void;
55
+ /**
56
+ * Verifica se uma variável de ambiente específica está definida e não está vazia.
57
+ * @param varName Nome da variável de ambiente.
58
+ * @returns True se definida e não vazia.
59
+ */
60
+ export declare function isEnvVarDefined(varName: string): boolean;
61
+ /**
62
+ * Obtém o valor de uma variável de ambiente ou retorna um valor padrão se não definida.
63
+ * @param varName Nome da variável de ambiente.
64
+ * @param defaultValue Valor padrão caso não definida.
65
+ * @returns Valor da variável ou valor padrão.
66
+ */
67
+ export declare function getEnvVar(varName: string, defaultValue?: string): string;
68
+ /**
69
+ * Obtém informações sobre o estado atual do carregamento de ambiente.
70
+ * @returns Objeto somente leitura com estado do carregador.
71
+ */
72
+ export declare function getEnvState(): Readonly<EnvLoaderState>;
73
+ /**
74
+ * Força o recarregamento das variáveis de ambiente.
75
+ * @param options Opções para o carregamento (opcional).
76
+ */
77
+ export declare function reloadEnv(options?: LoadEnvOptions): void;
78
+ /**
79
+ * Verifica se as variáveis de ambiente foram carregadas.
80
+ * @returns True se carregadas.
81
+ */
82
+ export declare function isEnvLoaded(): boolean;
83
+ /**
84
+ * Obtém lista de arquivos .env carregados.
85
+ * @returns Array de nomes de arquivos carregados.
86
+ */
87
+ export declare function getLoadedEnvFiles(): string[];
88
+ /**
89
+ * Obtém o ambiente atual detectado (ex: preprod, staging).
90
+ * @returns Nome do ambiente ou null.
91
+ */
92
+ export declare function getCurrentEnvironment(): string | null;
93
+ /**
94
+ * Valida se todas as variáveis necessárias para um tipo de projeto estão presentes.
95
+ * @param projectType Tipo do projeto (ex: API, Frontend, Mobile, SSH, Banco, Mixed).
96
+ * @returns Objeto com isValid, missing e warnings.
97
+ */
98
+ export declare function validateEnvironmentForProjectType(projectType: string): {
99
+ isValid: boolean;
100
+ missing: string[];
101
+ warnings: string[];
102
+ };
103
+ /**
104
+ * Utilitário para mascarar valores sensíveis em logs.
105
+ * @param key Nome da variável.
106
+ * @param value Valor da variável.
107
+ * @returns Valor mascarado se sensível, senão valor original.
108
+ */
109
+ export declare function maskSensitiveValue(key: string, value: string): string;
110
+ /**
111
+ * Gera relatório de status das variáveis de ambiente.
112
+ * @returns Objeto com informações do carregamento e validação do projeto.
113
+ */
114
+ export declare function generateEnvReport(): {
115
+ loaded: boolean;
116
+ loadTime: Date | null;
117
+ filesCount: number;
118
+ varsCount: number;
119
+ environment: string | null;
120
+ files: string[];
121
+ projectValidation?: ReturnType<typeof validateEnvironmentForProjectType>;
122
+ };
123
+ export {};
@@ -0,0 +1,361 @@
1
+ import * as dotenv from 'dotenv';
2
+ import * as fs from 'fs';
3
+ import * as path from 'path';
4
+ import { ConfigLogger } from '../utils/ConfigLogger.js';
5
+ /**
6
+ * Caminho para o diretório de bloqueio usado para prevenir carregamentos múltiplos
7
+ * das variáveis de ambiente entre diferentes processos.
8
+ * Usa mkdirSync como operação atômica (mais seguro que writeFileSync).
9
+ */
10
+ const lockDirPath = path.resolve(process.cwd(), '.env.lock');
11
+ /**
12
+ * Estado interno para rastreamento do carregamento de variáveis
13
+ */
14
+ const envState = {
15
+ isLoaded: false,
16
+ loadedFiles: [],
17
+ loadedVarsCount: 0,
18
+ lastLoadTime: null,
19
+ environmentMode: null,
20
+ };
21
+ /**
22
+ * Carrega variáveis de ambiente a partir de arquivos .env.
23
+ *
24
+ * Processa arquivos .env na seguinte ordem de prioridade:
25
+ * 1. Arquivo .env base (para obter ENV se não estiver definido)
26
+ * 2. Arquivo específico do ambiente (.env.preprod, .env.staging, etc)
27
+ * 3. Arquivos personalizados especificados em customEnvFiles
28
+ *
29
+ * Usa um mecanismo de bloqueio para evitar carregamentos múltiplos entre processos.
30
+ *
31
+ * @param options Configurações para controlar o comportamento de carregamento
32
+ * @throws {Error} Se ocorrer erro ao carregar variáveis
33
+ */
34
+ export function loadEnv(options = {}) {
35
+ if (envState.isLoaded && !options.forceReload) {
36
+ if (!options.silent) {
37
+ ConfigLogger.info(`Variáveis de ambiente já carregadas (${envState.loadedVarsCount} variáveis de ${envState.loadedFiles.length} arquivos)`);
38
+ }
39
+ return;
40
+ }
41
+ if (fs.existsSync(lockDirPath) && !options.forceReload) {
42
+ // Limpar locks stale (mais de 30s) para evitar deadlock
43
+ try {
44
+ const stat = fs.statSync(lockDirPath);
45
+ if (Date.now() - stat.mtimeMs > 30_000) {
46
+ fs.rmSync(lockDirPath, { recursive: true, force: true });
47
+ }
48
+ }
49
+ catch {
50
+ // Ignorar erros ao verificar lock stale
51
+ }
52
+ }
53
+ // Adquirir lock atômico via mkdirSync
54
+ let lockAcquired = false;
55
+ try {
56
+ fs.mkdirSync(lockDirPath);
57
+ lockAcquired = true;
58
+ }
59
+ catch {
60
+ if (!options.forceReload) {
61
+ if (!options.silent) {
62
+ ConfigLogger.info('Lock de ambiente já existe, aguardando...');
63
+ }
64
+ // Outro processo está carregando — pular ao invés de competir
65
+ return;
66
+ }
67
+ }
68
+ try {
69
+ // PRIMEIRA etapa - carregar .env base para obter ENV
70
+ const baseEnvPath = path.resolve(process.cwd(), '.env');
71
+ let environmentMode = process.env.NODE_ENV || process.env.ENV;
72
+ let baseVarsCount = 0;
73
+ const loadedFiles = [];
74
+ if (fs.existsSync(baseEnvPath)) {
75
+ if (!options.silent) {
76
+ ConfigLogger.info(`Encontrado arquivo .env: ${baseEnvPath}`);
77
+ }
78
+ // Usar override: true para garantir que ENV seja lido do arquivo
79
+ const baseResult = dotenv.config({ path: baseEnvPath, override: true });
80
+ if (!baseResult.error) {
81
+ baseVarsCount = Object.keys(baseResult.parsed || {}).length;
82
+ loadedFiles.push('.env');
83
+ if (!options.silent) {
84
+ ConfigLogger.success(`Variáveis carregadas com sucesso de .env (${baseVarsCount} variáveis)`);
85
+ }
86
+ // Obter ENV do arquivo carregado se não estava definido
87
+ if (!environmentMode && baseResult.parsed?.ENV) {
88
+ environmentMode = baseResult.parsed.ENV;
89
+ if (!options.silent) {
90
+ ConfigLogger.info(`ENV obtido do arquivo .env: ${environmentMode}`);
91
+ }
92
+ }
93
+ }
94
+ }
95
+ if (!options.silent) {
96
+ const nodeEnv = process.env.NODE_ENV || 'não definido';
97
+ const envVar = process.env.ENV || environmentMode || 'não definido';
98
+ ConfigLogger.info(`Carregando variáveis de ambiente (NODE_ENV=${nodeEnv}, ENV=${envVar})`);
99
+ }
100
+ let loadedVars = 0;
101
+ // SEGUNDA etapa - carregar arquivo específico do ambiente se existir
102
+ if (environmentMode && options.loadModeSpecificFiles !== false) {
103
+ const envSpecificFile = `.env.${environmentMode.toLowerCase()}`;
104
+ const envSpecificPath = path.resolve(process.cwd(), envSpecificFile);
105
+ if (fs.existsSync(envSpecificPath)) {
106
+ if (!options.silent) {
107
+ ConfigLogger.info(`Encontrado arquivo .env: ${envSpecificPath}`);
108
+ }
109
+ // Usar override: true para sobrescrever valores do .env base
110
+ const result = dotenv.config({ path: envSpecificPath, override: true });
111
+ if (result.error) {
112
+ if (!options.silent) {
113
+ ConfigLogger.warning(`Erro ao carregar arquivo ${envSpecificFile}: ${result.error.message}`);
114
+ }
115
+ }
116
+ else {
117
+ const varsCount = Object.keys(result.parsed || {}).length;
118
+ loadedVars += varsCount;
119
+ loadedFiles.push(envSpecificFile);
120
+ if (!options.silent) {
121
+ ConfigLogger.success(`Variáveis carregadas com sucesso de ${envSpecificFile} (${varsCount} variáveis)`);
122
+ }
123
+ }
124
+ }
125
+ else if (!options.silent) {
126
+ ConfigLogger.warning(`Arquivo específico do ambiente não encontrado: ${envSpecificPath}`);
127
+ }
128
+ }
129
+ // TERCEIRA etapa - carregar arquivos personalizados se especificados
130
+ if (options.customEnvFiles && options.customEnvFiles.length > 0) {
131
+ for (const customFile of options.customEnvFiles) {
132
+ const customPath = path.isAbsolute(customFile)
133
+ ? customFile
134
+ : path.resolve(process.cwd(), customFile);
135
+ if (fs.existsSync(customPath)) {
136
+ if (!options.silent) {
137
+ ConfigLogger.info(`Encontrado arquivo .env personalizado: ${customPath}`);
138
+ }
139
+ const result = dotenv.config({ path: customPath, override: true });
140
+ if (!result.error) {
141
+ const varsCount = Object.keys(result.parsed || {}).length;
142
+ loadedVars += varsCount;
143
+ loadedFiles.push(customFile);
144
+ if (!options.silent) {
145
+ ConfigLogger.success(`Variáveis carregadas com sucesso de ${customFile} (${varsCount} variáveis)`);
146
+ }
147
+ }
148
+ }
149
+ }
150
+ }
151
+ // Verificar ambiente final
152
+ const finalEnv = process.env.NODE_ENV || process.env.ENV;
153
+ if (finalEnv) {
154
+ if (!options.silent) {
155
+ ConfigLogger.success(`Ambiente configurado: ${finalEnv}`);
156
+ }
157
+ }
158
+ else if (!options.silent) {
159
+ ConfigLogger.warning('Ambiente não foi definido - usando configurações padrão');
160
+ }
161
+ if (loadedFiles.length > 1 && !options.silent) {
162
+ ConfigLogger.info(`Carregados ${loadedFiles.length} arquivos .env: ${loadedFiles.join(', ')}`);
163
+ ConfigLogger.info(`Ordem de prioridade: ${[...loadedFiles].reverse().join(' > ')}`);
164
+ }
165
+ // Verificar variáveis obrigatórias
166
+ if (options.required &&
167
+ Array.isArray(options.required) &&
168
+ options.required.length > 0) {
169
+ const missing = options.required.filter((varName) => !process.env[varName]);
170
+ if (missing.length > 0) {
171
+ ConfigLogger.warning(`Variáveis obrigatórias não encontradas: ${missing.join(', ')}`);
172
+ }
173
+ else if (!options.silent) {
174
+ ConfigLogger.success('Todas as variáveis obrigatórias estão presentes');
175
+ }
176
+ }
177
+ // Verificação de variáveis sensíveis
178
+ const sensitiveVarsToCheck = [
179
+ 'DB_PASSWORD',
180
+ 'DB_PASS',
181
+ 'SSH_PASSWORD',
182
+ 'SSH_PASS',
183
+ 'API_KEY',
184
+ 'TOKEN',
185
+ 'SECRET',
186
+ 'PRIVATE_KEY',
187
+ ...Object.keys(process.env).filter((key) => key.toLowerCase().includes('password') ||
188
+ key.toLowerCase().includes('secret') ||
189
+ key.toLowerCase().includes('token') ||
190
+ key.toLowerCase().includes('key')),
191
+ ];
192
+ const presentSensitiveVars = [...new Set(sensitiveVarsToCheck)].filter((varName) => !!process.env[varName]);
193
+ if (presentSensitiveVars.length > 0 && !options.silent) {
194
+ ConfigLogger.info(`${presentSensitiveVars.length} variáveis sensíveis configuradas`);
195
+ }
196
+ if (options.logConfig === true) {
197
+ ConfigLogger.logEnvironmentConfig();
198
+ }
199
+ // Atualizar estado interno
200
+ const totalVars = baseVarsCount + loadedVars;
201
+ envState.isLoaded = true;
202
+ envState.loadedFiles = loadedFiles;
203
+ envState.loadedVarsCount = totalVars;
204
+ envState.lastLoadTime = new Date();
205
+ envState.environmentMode = finalEnv || null;
206
+ if (!options.silent) {
207
+ ConfigLogger.success(`${totalVars} variáveis de ambiente carregadas de ${loadedFiles.length} arquivo(s)`);
208
+ }
209
+ }
210
+ catch (error) {
211
+ ConfigLogger.error('Erro ao carregar variáveis de ambiente', error);
212
+ throw error;
213
+ }
214
+ finally {
215
+ // Liberar lock atômico
216
+ if (lockAcquired) {
217
+ try {
218
+ fs.rmSync(lockDirPath, { recursive: true, force: true });
219
+ }
220
+ catch {
221
+ // Ignorar erros ao liberar lock
222
+ }
223
+ }
224
+ }
225
+ }
226
+ /**
227
+ * Limpa o arquivo de bloqueio usado para garantir que o ambiente
228
+ * seja carregado apenas uma vez entre diferentes processos.
229
+ * Também reseta o estado interno.
230
+ */
231
+ export function cleanupEnvLock() {
232
+ if (fs.existsSync(lockDirPath)) {
233
+ try {
234
+ fs.rmSync(lockDirPath, { recursive: true, force: true });
235
+ envState.isLoaded = false;
236
+ }
237
+ catch (error) {
238
+ // Ignora erros ao limpar o lock
239
+ }
240
+ }
241
+ }
242
+ /**
243
+ * Verifica se uma variável de ambiente específica está definida e não está vazia.
244
+ * @param varName Nome da variável de ambiente.
245
+ * @returns True se definida e não vazia.
246
+ */
247
+ export function isEnvVarDefined(varName) {
248
+ return !!process.env[varName] && process.env[varName].trim() !== '';
249
+ }
250
+ /**
251
+ * Obtém o valor de uma variável de ambiente ou retorna um valor padrão se não definida.
252
+ * @param varName Nome da variável de ambiente.
253
+ * @param defaultValue Valor padrão caso não definida.
254
+ * @returns Valor da variável ou valor padrão.
255
+ */
256
+ export function getEnvVar(varName, defaultValue = '') {
257
+ return process.env[varName] || defaultValue;
258
+ }
259
+ /**
260
+ * Obtém informações sobre o estado atual do carregamento de ambiente.
261
+ * @returns Objeto somente leitura com estado do carregador.
262
+ */
263
+ export function getEnvState() {
264
+ return { ...envState };
265
+ }
266
+ /**
267
+ * Força o recarregamento das variáveis de ambiente.
268
+ * @param options Opções para o carregamento (opcional).
269
+ */
270
+ export function reloadEnv(options = {}) {
271
+ loadEnv({ ...options, forceReload: true });
272
+ }
273
+ /**
274
+ * Verifica se as variáveis de ambiente foram carregadas.
275
+ * @returns True se carregadas.
276
+ */
277
+ export function isEnvLoaded() {
278
+ return envState.isLoaded;
279
+ }
280
+ /**
281
+ * Obtém lista de arquivos .env carregados.
282
+ * @returns Array de nomes de arquivos carregados.
283
+ */
284
+ export function getLoadedEnvFiles() {
285
+ return [...envState.loadedFiles];
286
+ }
287
+ /**
288
+ * Obtém o ambiente atual detectado (ex: preprod, staging).
289
+ * @returns Nome do ambiente ou null.
290
+ */
291
+ export function getCurrentEnvironment() {
292
+ return envState.environmentMode;
293
+ }
294
+ /**
295
+ * Valida se todas as variáveis necessárias para um tipo de projeto estão presentes.
296
+ * @param projectType Tipo do projeto (ex: API, Frontend, Mobile, SSH, Banco, Mixed).
297
+ * @returns Objeto com isValid, missing e warnings.
298
+ */
299
+ export function validateEnvironmentForProjectType(projectType) {
300
+ const validationRules = {
301
+ API: ['BASE_URL_API', 'API_URL'],
302
+ Frontend: ['BASE_URL'],
303
+ Mobile: ['USE_MOBILE'],
304
+ SSH: ['SSH_HOST', 'SSH_USER'],
305
+ Banco: ['DB_HOST', 'DB_USER', 'DB_PASS', 'DB_SERVICE'],
306
+ Mixed: [],
307
+ };
308
+ const requiredVars = validationRules[projectType] || [];
309
+ const missing = requiredVars.filter((varName) => !isEnvVarDefined(varName));
310
+ const warnings = [];
311
+ if (projectType === 'Banco' && !process.env.DB_PORT) {
312
+ warnings.push('DB_PORT não definido, usando porta padrão');
313
+ }
314
+ if (projectType === 'SSH' && !process.env.SSH_PORT) {
315
+ warnings.push('SSH_PORT não definido, usando porta 22');
316
+ }
317
+ return {
318
+ isValid: missing.length === 0,
319
+ missing,
320
+ warnings,
321
+ };
322
+ }
323
+ /**
324
+ * Utilitário para mascarar valores sensíveis em logs.
325
+ * @param key Nome da variável.
326
+ * @param value Valor da variável.
327
+ * @returns Valor mascarado se sensível, senão valor original.
328
+ */
329
+ export function maskSensitiveValue(key, value) {
330
+ const sensitivePatterns = [
331
+ 'password',
332
+ 'pass',
333
+ 'secret',
334
+ 'token',
335
+ 'key',
336
+ 'auth',
337
+ ];
338
+ const isSensitive = sensitivePatterns.some((pattern) => key.toLowerCase().includes(pattern));
339
+ if (isSensitive) {
340
+ return value.length > 0 ? '********' : '';
341
+ }
342
+ return value;
343
+ }
344
+ /**
345
+ * Gera relatório de status das variáveis de ambiente.
346
+ * @returns Objeto com informações do carregamento e validação do projeto.
347
+ */
348
+ export function generateEnvReport() {
349
+ const projectType = process.env.PROJECT_TYPE || 'unknown';
350
+ return {
351
+ loaded: envState.isLoaded,
352
+ loadTime: envState.lastLoadTime,
353
+ filesCount: envState.loadedFiles.length,
354
+ varsCount: envState.loadedVarsCount,
355
+ environment: envState.environmentMode,
356
+ files: [...envState.loadedFiles],
357
+ projectValidation: projectType !== 'unknown'
358
+ ? validateEnvironmentForProjectType(projectType)
359
+ : undefined,
360
+ };
361
+ }
@@ -0,0 +1,19 @@
1
+ /**
2
+ * 🔧 AutoCore Jest-Safe Setup - Configuração Avançada Jest/Vitest
3
+ * @silasfmartins/testhub v1.1.48
4
+ *
5
+ * Sistema automático de resolução de conflitos Jest/Vitest para projetos
6
+ * que utilizam ambos os padrões .test.ts e .spec.ts
7
+ *
8
+ * OPÇÃO B COMPLETA: 8 Métodos Avançados de Resolução
9
+ */
10
+ /**
11
+ * 🛡️ Função Principal: Resolver Conflitos Jest/Vitest
12
+ *
13
+ * Implementa 8 métodos de proteção para evitar:
14
+ * - TypeError: Cannot redefine property: Symbol($$jest-matchers-object)
15
+ * - Conflitos entre expect() do Jest vs Vitest
16
+ * - Problemas de Symbol registry
17
+ * - Redefinição de propriedades globais
18
+ */
19
+ export declare function resolveJestVitestConflict(): void;