@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,643 @@
1
+ // AutoCore Protect Loader (Zero-Touch, Offline)
2
+ // Usage: NODE_OPTIONS="--loader ./node_modules/@silasfmartins/testhub/protect-loader.mjs"
3
+ // This loader runs comprehensive offline checks before exposing @silasfmartins/testhub APIs.
4
+
5
+ // 🚨 CRÍTICO: Interceptar Object.defineProperty IMEDIATAMENTE
6
+ // Isso DEVE acontecer ANTES de qualquer import para evitar:
7
+ // "TypeError: Cannot redefine property: Symbol($$jest-matchers-object)"
8
+ const _originalDefineProperty = Object.defineProperty
9
+ Object.defineProperty = function (obj, prop, descriptor) {
10
+ // Detectar se é um símbolo Jest/Vitest/matchers
11
+ const isMatcherSymbol =
12
+ typeof prop === 'symbol' &&
13
+ (prop.toString().includes('jest') ||
14
+ prop.toString().includes('vitest') ||
15
+ prop.toString().includes('matchers'))
16
+
17
+ if (isMatcherSymbol) {
18
+ // Verificar se já existe no objeto
19
+ try {
20
+ const existingDescriptor = Object.getOwnPropertyDescriptor(obj, prop)
21
+
22
+ if (existingDescriptor && !existingDescriptor.configurable) {
23
+ // Já foi definido e não é configurável, ignorar silenciosamente
24
+ return obj
25
+ }
26
+ } catch {
27
+ // Ignorar erros de getOwnPropertyDescriptor
28
+ }
29
+
30
+ // Forçar configurable: true para permitir futuras redefinições
31
+ const safeDescriptor = { ...descriptor, configurable: true }
32
+
33
+ try {
34
+ return _originalDefineProperty.call(Object, obj, prop, safeDescriptor)
35
+ } catch {
36
+ // Se falhar, simplesmente retornar o objeto sem modificar
37
+ return obj
38
+ }
39
+ }
40
+
41
+ // Para outras propriedades, usar comportamento padrão
42
+ return _originalDefineProperty.call(Object, obj, prop, descriptor)
43
+ }
44
+
45
+ import { createHash, randomBytes } from 'node:crypto'
46
+ import { existsSync, promises as fs } from 'node:fs'
47
+ import path from 'node:path'
48
+ import { pathToFileURL } from 'node:url'
49
+
50
+ let checksDone = false
51
+ let degraded = false
52
+ let degradedReason = ''
53
+ let bypassLogged = false // Evitar logs duplicados
54
+ let startupLogged = false
55
+ let stubConfigLogged = false
56
+
57
+ // Contadores de detecção de automação
58
+ const callCounts = new Map()
59
+ const lastCallTime = new Map()
60
+ const startTime = Date.now()
61
+
62
+ async function runComprehensiveChecks(initUrl) {
63
+ if (checksDone) return
64
+ checksDone = true
65
+
66
+ if (!startupLogged) {
67
+ try {
68
+ console.log('[protect-loader] AutoCore Protect Loader: starting comprehensive checks. PID=', process.pid)
69
+ } catch {}
70
+ startupLogged = true
71
+ }
72
+
73
+ try {
74
+ // 🔓 BYPASS AUTOMÁTICO: Verificar ambientes de desenvolvimento e CI
75
+ const environmentBypass =
76
+ process.env.AUTOCORE_BYPASS_PROTECTION === 'true' ||
77
+ process.env.NODE_ENV === 'development' ||
78
+ process.env.NODE_ENV === 'preprod' ||
79
+ process.env.NODE_ENV === 'prodlike' ||
80
+ process.env.NODE_ENV === 'esteira1' ||
81
+ process.env.NODE_ENV === 'esteira2' ||
82
+ process.env.ENV === 'preprod' ||
83
+ process.env.ENV === 'prodlike' ||
84
+ process.env.ENV === 'producao' ||
85
+ process.env.ENV === 'esteira1' ||
86
+ process.env.ENV === 'esteira2' ||
87
+ Boolean(process.env.CI) ||
88
+ Boolean(process.env.TF_BUILD) ||
89
+ Boolean(process.env.GITHUB_ACTIONS) ||
90
+ Boolean(process.env.JENKINS_URL) ||
91
+ Boolean(process.env.BUILD_SOURCEBRANCH) ||
92
+ Boolean(process.env.AGENT_NAME) ||
93
+ Boolean(process.env.SYSTEM_TEAMFOUNDATIONCOLLECTIONURI) ||
94
+ Boolean(process.env.PLAYWRIGHT_BROWSERS_PATH) ||
95
+ Boolean(process.env.VSCODE_PID) ||
96
+ process.argv.includes('--disable-protection') ||
97
+ process.argv.some((arg) => arg.includes('test')) ||
98
+ process.argv.some((arg) => arg.includes('mobile')) ||
99
+ process.argv.some((arg) => arg.includes('playwright')) ||
100
+ process.argv.some((arg) => arg.includes('frontend')) ||
101
+ process.argv.some((arg) => arg.includes('webactions')) ||
102
+ process.argv.some((arg) => arg.includes('--ui')) ||
103
+ process.argv.some((arg) => arg.includes('--debug')) ||
104
+ process.argv.some((arg) => arg.includes('codegen')) ||
105
+ process.argv.some((arg) => arg.includes('--project')) ||
106
+ process.env.npm_lifecycle_event?.includes('test') ||
107
+ process.env.npm_lifecycle_event?.includes('frontend') ||
108
+ process.env.npm_lifecycle_event?.includes('dev') ||
109
+ process.env.npm_lifecycle_event?.includes('ui') ||
110
+ process.env.npm_lifecycle_event?.includes('debug') ||
111
+ process.env.npm_lifecycle_event?.includes('codegen')
112
+
113
+ // 🔧 MODO DEBUG: Ativar logs detalhados quando --debug presente
114
+ if (process.argv.includes('--debug')) {
115
+ process.env.AUTOCORE_DEBUG_LOGS = 'true'
116
+ }
117
+
118
+ // Log único de inicialização para ajudar a rastrear GlobalSetup/logs
119
+ if (!startupLogged) {
120
+ try {
121
+ console.log('[protect-loader] AutoCore Protect Loader initialized. PID=', process.pid)
122
+ } catch {}
123
+ startupLogged = true
124
+ }
125
+
126
+ if (environmentBypass) {
127
+ if (!bypassLogged) {
128
+ console.log('🔓 AutoCore: Bypass automático ativo para ambiente de desenvolvimento/CI')
129
+ bypassLogged = true
130
+ }
131
+ process.env.AUTOCORE_SECURITY_LOADED = 'true'
132
+ // 🔧 GARANTIR que modo degradado não seja ativado com bypass
133
+ process.env.AUTOCORE_DEGRADED_MODE = 'false'
134
+ degraded = false
135
+ degradedReason = ''
136
+ return // Pular todas as verificações
137
+ }
138
+ // 1) Verificação de chaves de instalação
139
+ const home = process.env.HOME || process.env.USERPROFILE || ''
140
+ const keysDir = home ? path.join(home, '.rbqa', 'keys') : ''
141
+
142
+ if (keysDir && existsSync(keysDir)) {
143
+ // Verificar se arquivos de chave existem
144
+ const keyFile = path.join(keysDir, 'autocore.key')
145
+ const idFile = path.join(keysDir, 'install.id')
146
+
147
+ if (!(existsSync(keyFile) && existsSync(idFile))) {
148
+ degraded = true
149
+ degradedReason ||= 'invalid_keys'
150
+ }
151
+ } else {
152
+ degraded = true
153
+ degradedReason ||= 'missing_installation_keys'
154
+ }
155
+
156
+ // 2) Verificação de manifesto de integridade
157
+ try {
158
+ const pkgRoot = process.cwd()
159
+ const manifestPath = path.join(
160
+ pkgRoot,
161
+ 'node_modules',
162
+ '@rbqa',
163
+ 'autocore',
164
+ 'dist',
165
+ 'security.compact.json',
166
+ )
167
+
168
+ if (existsSync(manifestPath)) {
169
+ const manifest = JSON.parse(await fs.readFile(manifestPath, 'utf8'))
170
+
171
+ // Verificar pelo menos um arquivo crítico
172
+ if (manifest.f && manifest.f.length > 0) {
173
+ const indexFile = manifest.f.find((f) => f[0].endsWith('index.js'))
174
+ if (indexFile) {
175
+ const [filePath, expectedHash] = indexFile
176
+ const fullPath = path.join(
177
+ pkgRoot,
178
+ 'node_modules',
179
+ '@rbqa',
180
+ 'autocore',
181
+ 'dist',
182
+ filePath,
183
+ )
184
+
185
+ if (existsSync(fullPath)) {
186
+ const buf = await fs.readFile(fullPath)
187
+ const actualHash = createHash('sha512').update(buf).digest('hex')
188
+
189
+ if (actualHash !== expectedHash) {
190
+ degraded = true
191
+ degradedReason ||= 'integrity_compromised'
192
+ }
193
+ }
194
+ }
195
+ }
196
+ } else {
197
+ // Manifesto ausente é suspeito
198
+ degraded = true
199
+ degradedReason ||= 'missing_manifest'
200
+ }
201
+ } catch {
202
+ degraded = true
203
+ degradedReason ||= 'manifest_read_error'
204
+ }
205
+
206
+ // 3) Verificação de honeypot
207
+ if (process.env.AUTOCORE_HONEYPOT_TRIPPED === 'true') {
208
+ degraded = true
209
+ degradedReason ||= 'honeypot_triggered'
210
+ }
211
+
212
+ // 4) Detecção de ambiente de execução
213
+ const devVars = [
214
+ 'VSCODE_PID',
215
+ 'VSCODE_HANDLES_UNCAUGHT_ERRORS',
216
+ 'PLAYWRIGHT_BROWSERS_PATH',
217
+ 'APPIUM_HOME',
218
+ 'NODE_ENV',
219
+ 'DEBUG',
220
+ 'TERM',
221
+ 'ENV',
222
+ ]
223
+
224
+ const hasDevEnv = devVars.some((v) => process.env[v])
225
+ const isInteractive = process.stdout.isTTY || Boolean(process.env.TERM)
226
+ const isCi = Boolean(
227
+ process.env.CI ||
228
+ process.env.GITHUB_ACTIONS ||
229
+ process.env.JENKINS_URL ||
230
+ process.env.TF_BUILD || // Azure DevOps
231
+ process.env.BUILD_SOURCEBRANCH || // Azure DevOps
232
+ process.env.AGENT_NAME || // Azure DevOps
233
+ process.env.SYSTEM_TEAMFOUNDATIONCOLLECTIONURI, // Azure DevOps
234
+ )
235
+
236
+ // Suspeito se não tem ambiente dev, não é interativo e não é CI conhecido
237
+ if (!(hasDevEnv || isInteractive || isCi)) {
238
+ degraded = true
239
+ degradedReason ||= 'suspicious_environment'
240
+ }
241
+
242
+ // 5) Proof-of-work opcional
243
+ const powTarget = Number(process.env.AUTOCORE_POW_DIFFICULTY || '0')
244
+ if (powTarget > 0 && powTarget <= 3) {
245
+ const nonce = randomBytes(8).toString('hex')
246
+ let solved = false
247
+ const maxAttempts =
248
+ powTarget === 1 ? 1000 : powTarget === 2 ? 5000 : 10_000
249
+
250
+ for (let i = 0; i < maxAttempts; i++) {
251
+ const hash = createHash('sha256')
252
+ .update(`loader:${nonce}:${i}`)
253
+ .digest('hex')
254
+ if (hash.startsWith('0'.repeat(powTarget))) {
255
+ solved = true
256
+ break
257
+ }
258
+ }
259
+
260
+ if (!solved) {
261
+ degraded = true
262
+ degradedReason ||= 'pow_challenge_failed'
263
+ }
264
+ }
265
+
266
+ // 6) Verificação EULA
267
+ if (
268
+ process.env.AUTOCORE_EULA_REQUIRED === 'true' &&
269
+ process.env.AUTOCORE_EULA_ACCEPTED !== 'true'
270
+ ) {
271
+ degraded = true
272
+ degradedReason ||= 'eula_not_accepted'
273
+ }
274
+
275
+ // 7) Timing de inicialização (detecção de startup muito rápido)
276
+ const bootTime = Date.now() - startTime
277
+ if (bootTime < 50) {
278
+ // Menos de 50ms é suspeito
279
+ degraded = true
280
+ degradedReason ||= 'too_fast_initialization'
281
+ }
282
+
283
+ // Marcar estado final
284
+ if (degraded) {
285
+ process.env.AUTOCORE_DEGRADED_MODE = 'true'
286
+ process.env.AUTOCORE_DEGRADED_REASON ||= degradedReason || 'unknown'
287
+ }
288
+
289
+ process.env.AUTOCORE_SECURITY_LOADED = 'true'
290
+ try {
291
+ if (degraded) {
292
+ console.warn('[protect-loader] Security checks completed: DEGRADED -', degradedReason)
293
+ } else {
294
+ console.log('[protect-loader] Security checks completed: OK')
295
+ }
296
+ } catch {}
297
+ } catch (error) {
298
+ // Em caso de erro nas verificações, assumir degradado por segurança
299
+ degraded = true
300
+ process.env.AUTOCORE_DEGRADED_MODE = 'true'
301
+ process.env.AUTOCORE_DEGRADED_REASON ||= 'security_check_failed'
302
+ try {
303
+ console.error('[protect-loader] Security checks failed with error:', error && error.message)
304
+ } catch {}
305
+ }
306
+ }
307
+
308
+ // NOTE: persistent file logging was removed to avoid writing files on user's machine.
309
+ // All diagnostics use console output only.
310
+
311
+ // Detecta padrões de automação por frequência de chamadas
312
+ function detectAutomationPattern(specifier) {
313
+ const now = Date.now()
314
+ const count = callCounts.get(specifier) || 0
315
+ const lastCall = lastCallTime.get(specifier) || 0
316
+
317
+ // Rate limiting: máximo 20 imports por segundo
318
+ if (now - lastCall < 50) {
319
+ // < 50ms entre imports
320
+ callCounts.set(specifier, count + 1)
321
+ if (count > 20) {
322
+ degraded = true
323
+ degradedReason ||= 'automation_pattern_detected'
324
+ process.env.AUTOCORE_DEGRADED_MODE = 'true'
325
+ process.env.AUTOCORE_DEGRADED_REASON ||= degradedReason
326
+ }
327
+ } else {
328
+ callCounts.set(specifier, 1)
329
+ }
330
+
331
+ lastCallTime.set(specifier, now)
332
+ }
333
+
334
+ // Node ESM Loader hooks
335
+ export async function resolve(specifier, context, nextResolve) {
336
+ // Detectar padrões de automação
337
+ detectAutomationPattern(specifier)
338
+
339
+ // Detectar se a resolução vem do transform do Playwright (ele transforma TS configs)
340
+ const parent = context && context.parentURL
341
+ const isPlaywrightTransform =
342
+ typeof parent === 'string' &&
343
+ (parent.includes('playwright/lib/transform') || parent.includes('@playwright/test/lib/transform'))
344
+
345
+ // Se o Playwright está tentando resolver o playwright.config.ts do projeto,
346
+ // deixe o Node/Playwright resolver/carregar o arquivo (não retornar stub).
347
+ if (
348
+ isPlaywrightTransform &&
349
+ typeof specifier === 'string' &&
350
+ specifier.includes('playwright.config.ts')
351
+ ) {
352
+ try {
353
+ return nextResolve(specifier, context)
354
+ } catch (e) {
355
+ // Se resolver falhar aqui, continuar com o fluxo normal (fallback mais adiante)
356
+ }
357
+ }
358
+
359
+ // Interceptar playwright.config.ts ANTES de tentar resolver
360
+ if (
361
+ typeof parent === 'string' &&
362
+ parent.includes('playwright/lib/transform/transform.js') &&
363
+ typeof specifier === 'string' &&
364
+ (specifier.endsWith('playwright.config.ts') || specifier.includes('/playwright.config.ts'))
365
+ ) {
366
+ // Prefer an existing compiled JS config if present so Playwright can run the real config/globalSetup.
367
+ try {
368
+ const cwd = process.cwd()
369
+ const candidates = ['playwright.config.js', 'playwright.config.cjs', 'playwright.config.mjs']
370
+ for (const cand of candidates) {
371
+ const fp = path.join(cwd, cand)
372
+ if (existsSync(fp)) {
373
+ // Let Node/Playwright load the compiled config instead of stubbing
374
+ return nextResolve(pathToFileURL(fp).href, context)
375
+ }
376
+ }
377
+ } catch (e) {
378
+ // ignore and fall back to stub
379
+ }
380
+
381
+ // Intercepting playwright.config.ts to provide a safe stub for Playwright's transform.
382
+ // Intentionally silent to avoid noisy repeated logs during Playwright's internal transforms.
383
+ const stubConfig = `
384
+ // AutoCore: stub config para evitar parse de TypeScript
385
+ // Provide a minimal project so Playwright can read projects[i].use
386
+ const defaultProject = {
387
+ name: 'autocore-stub',
388
+ use: {
389
+ actionTimeout: 0,
390
+ navigationTimeout: 30000,
391
+ }
392
+ };
393
+
394
+ export default {
395
+ timeout: 30000,
396
+ use: {
397
+ actionTimeout: 0,
398
+ navigationTimeout: 30000,
399
+ },
400
+ projects: [defaultProject]
401
+ };
402
+
403
+ export const projects = [defaultProject];
404
+ `
405
+ const encodedConfig = Buffer.from(stubConfig, 'utf8').toString('base64')
406
+ if (!stubConfigLogged) {
407
+ try {
408
+ console.log('[protect-loader] Intercepting playwright.config.ts - returning safe stub to avoid TS transform')
409
+ } catch {}
410
+ stubConfigLogged = true
411
+ }
412
+ return {
413
+ format: 'module',
414
+ shortCircuit: true,
415
+ url: `data:text/javascript;base64,${encodedConfig}`,
416
+ }
417
+ }
418
+
419
+ // Expor SyncSignal como um sub-módulo virtual de @silasfmartins/testhub
420
+ if (
421
+ specifier === '@silasfmartins/testhub/sync-signal' ||
422
+ specifier === '@silasfmartins/testhub/SyncSignal' ||
423
+ specifier === '@silasfmartins/testhub/syncsignal'
424
+ ) {
425
+ // Do not intercept: let Node resolve via package.json exports (./sync-signal -> sync-signal.js)
426
+ return nextResolve(specifier, context)
427
+ }
428
+
429
+ // Verificações principais na primeira resolução do pacote
430
+ if (specifier === '@silasfmartins/testhub' && !checksDone) {
431
+ await runComprehensiveChecks(import.meta.url)
432
+
433
+ // 🔧 VERIFICAR se bypass está ativo antes de aplicar modo degradado
434
+ const bypassActive =
435
+ process.env.AUTOCORE_BYPASS_PROTECTION === 'true' ||
436
+ process.env.NODE_ENV === 'development' ||
437
+ process.env.NODE_ENV === 'preprod' ||
438
+ process.env.NODE_ENV === 'prodlike' ||
439
+ process.env.NODE_ENV === 'esteira1' ||
440
+ process.env.NODE_ENV === 'esteira2' ||
441
+ process.env.ENV === 'preprod' ||
442
+ process.env.ENV === 'prodlike' ||
443
+ process.env.ENV === 'esteira1' ||
444
+ process.env.ENV === 'esteira2' ||
445
+ Boolean(process.env.CI) ||
446
+ Boolean(process.env.PLAYWRIGHT_BROWSERS_PATH) ||
447
+ Boolean(process.env.VSCODE_PID) ||
448
+ process.argv.some((arg) => arg.includes('test')) ||
449
+ process.argv.some((arg) => arg.includes('playwright')) ||
450
+ process.argv.some((arg) => arg.includes('frontend')) ||
451
+ process.argv.some((arg) => arg.includes('--ui')) ||
452
+ process.argv.some((arg) => arg.includes('--debug')) ||
453
+ process.argv.some((arg) => arg.includes('codegen')) ||
454
+ process.argv.some((arg) => arg.includes('--project')) ||
455
+ process.env.npm_lifecycle_event?.includes('test') ||
456
+ process.env.npm_lifecycle_event?.includes('ui') ||
457
+ process.env.npm_lifecycle_event?.includes('debug') ||
458
+ process.env.npm_lifecycle_event?.includes('codegen')
459
+
460
+ if (bypassActive) {
461
+ // 🔧 Com bypass ativo, nunca usar modo degradado
462
+ degraded = false
463
+ process.env.AUTOCORE_DEGRADED_MODE = 'false'
464
+ }
465
+
466
+ // Se a resolução veio do transform do Playwright, não retorne o stub degradado:
467
+ if (isPlaywrightTransform) {
468
+ degraded = false
469
+ process.env.AUTOCORE_DEGRADED_MODE = 'false'
470
+ }
471
+
472
+ if (degraded) {
473
+ // Retornar stub completo quando degradado
474
+ const stubModule = `
475
+ // AutoCore Security: Modo Degradado Ativo
476
+ const noop = () => {}
477
+ const proxy = new Proxy(noop, {
478
+ apply: () => undefined,
479
+ get: () => proxy,
480
+ set: () => true
481
+ })
482
+
483
+ // Logger stub
484
+ export const Logger = {
485
+ info: noop, warn: noop, error: noop, success: noop,
486
+ bloco: noop, debug: noop
487
+ }
488
+
489
+ // Actions stubs
490
+ export const WebActions = proxy
491
+ export const Actions = proxy // Alias para compatibilidade
492
+ export const MobileActions = proxy
493
+ export const MobileConnection = proxy
494
+ export const ApiActions = proxy
495
+ export const BancoActions = proxy
496
+ export const BancoHelper = proxy
497
+ export const ConexaoTestHelper = proxy
498
+ export const SSHActions = proxy
499
+ export const SSHClient = proxy
500
+
501
+ // Test framework stubs
502
+ export const TestContext = proxy
503
+ export const UnifiedReportManager = proxy
504
+ export const TestAnnotations = proxy
505
+
506
+ // Annotation functions (sempre retornam decorator vazio)
507
+ export const Api = () => () => {}
508
+ export const Frontend = () => () => {}
509
+ export const Front = () => () => {}
510
+ export const Mobile = () => () => {}
511
+ export const SSH = () => () => {}
512
+ export const Banco = () => () => {}
513
+ export const Mixed = () => () => {}
514
+ export const Auto = () => () => {}
515
+
516
+ // Utils stubs
517
+ export const DataStore = {
518
+ set: noop, get: () => null, has: () => false,
519
+ remove: () => false, clear: noop
520
+ }
521
+ export const cleanupEnvLock = noop
522
+
523
+ // JsonResponse stub
524
+ export const JsonResponse = function() {
525
+ return {
526
+ get: () => null, getString: () => '',
527
+ getArray: () => [], raw: () => ({})
528
+ }
529
+ }
530
+
531
+ // Default export
532
+ const AutoCoreUnified = {
533
+ Logger, WebActions, Actions, MobileActions, MobileConnection,
534
+ ApiActions, TestContext, DataStore
535
+ }
536
+ export default AutoCoreUnified
537
+
538
+ // Modo degradado silencioso - não quebra o código do usuário
539
+ console.warn('AutoCore: Modo de proteção ativo. Algumas funcionalidades podem estar limitadas.')
540
+ `
541
+
542
+ const encoded = Buffer.from(stubModule, 'utf8').toString('base64')
543
+ return {
544
+ format: 'module',
545
+ shortCircuit: true,
546
+ url: `data:text/javascript;base64,${encoded}`,
547
+ }
548
+ }
549
+ }
550
+
551
+ try {
552
+ return await nextResolve(specifier, context)
553
+ } catch (err) {
554
+ // Módulos conhecidos que têm problemas de ESM resolution (CommonJS legacy)
555
+ // Silenciar erros para estes pois o webdriverio/playwright lidam com fallback interno
556
+ const knownEsmIssues = ['jszip', 'archiver', 'pako', 'setimmediate']
557
+ const isKnownIssue = knownEsmIssues.some((mod) =>
558
+ (typeof specifier === 'string' && specifier.includes(mod)) ||
559
+ (err?.message && err.message.includes(mod))
560
+ )
561
+
562
+ if (!isKnownIssue) {
563
+ // Resolver falhou (módulo não encontrado etc). Em vez de quebrar, retornar stub module
564
+ console.error('[protect-loader] resolve ERROR for', specifier, ':', err && err.message)
565
+ }
566
+
567
+ // Criar stub JS mínimo que exporta objetos vazios para evitar que o processo quebre
568
+ const stub = `export const __autoCoreStub = true; export default {};`
569
+ const encoded = Buffer.from(stub, 'utf8').toString('base64')
570
+ return {
571
+ format: 'module',
572
+ shortCircuit: true,
573
+ url: `data:text/javascript;base64,${encoded}`,
574
+ }
575
+ }
576
+ }
577
+
578
+ export async function load(url, context, nextLoad) {
579
+ // Interceptar playwright.config.ts ANTES de tentar carregar/parsear
580
+ // para evitar SyntaxError quando transform do Playwright tenta carregar arquivo TypeScript
581
+ if (typeof url === 'string' && url.includes('playwright.config.ts')) {
582
+ const stubConfig = `
583
+ // AutoCore: stub config para evitar parse de TypeScript
584
+ const defaultProject = {
585
+ name: 'autocore-stub',
586
+ use: { actionTimeout: 0, navigationTimeout: 30000 }
587
+ };
588
+
589
+ export default {
590
+ timeout: 30000,
591
+ use: { actionTimeout: 0, navigationTimeout: 30000 },
592
+ projects: [defaultProject]
593
+ };
594
+ export const projects = [defaultProject];
595
+ `
596
+ if (!stubConfigLogged) {
597
+ try {
598
+ console.log('[protect-loader] load() intercept: returning safe playwright.config.ts stub')
599
+ } catch {}
600
+ stubConfigLogged = true
601
+ }
602
+ return {
603
+ format: 'module',
604
+ shortCircuit: true,
605
+ source: stubConfig,
606
+ }
607
+ }
608
+
609
+ // Detectar acesso a honeypots
610
+ if (
611
+ url.includes('/internal/fakes/') ||
612
+ url.includes('__honeypot__') ||
613
+ url.includes('__forbidden__') ||
614
+ url.includes('__fake-actions__')
615
+ ) {
616
+ process.env.AUTOCORE_HONEYPOT_TRIPPED = 'true'
617
+ degraded = true
618
+ degradedReason ||= 'honeypot_module_accessed'
619
+ process.env.AUTOCORE_DEGRADED_MODE = 'true'
620
+ process.env.AUTOCORE_DEGRADED_REASON ||= degradedReason
621
+ }
622
+
623
+ try {
624
+ const result = await nextLoad(url, context)
625
+ return result
626
+ } catch (err) {
627
+ // Log de erro apenas quando falhar (mantém logs importantes)
628
+ console.error('[protect-loader] ERROR loading', url, ':', err && err.message)
629
+
630
+ // Se o erro for SyntaxError e o arquivo terminar em .ts, retornar stub
631
+ if (err && err.name === 'SyntaxError' && typeof url === 'string' && url.endsWith('.ts')) {
632
+ console.error('[protect-loader] Interceptando arquivo TypeScript que causou SyntaxError')
633
+ const stub = `const defaultProject = { name: 'autocore-stub', use: { actionTimeout: 0 } }; export default { use: {}, projects: [defaultProject] }; export const projects = [defaultProject];`
634
+ return {
635
+ format: 'module',
636
+ shortCircuit: true,
637
+ source: stub,
638
+ }
639
+ }
640
+
641
+ throw err
642
+ }
643
+ }