Skip to content

fix(edges): corrige 3 TS errors que travavam CI Deno typecheck#10

Merged
adm01-debug merged 2 commits into
mainfrom
fix/edge-functions-typecheck-19mai
May 19, 2026
Merged

fix(edges): corrige 3 TS errors que travavam CI Deno typecheck#10
adm01-debug merged 2 commits into
mainfrom
fix/edge-functions-typecheck-19mai

Conversation

@adm01-debug
Copy link
Copy Markdown
Owner

@adm01-debug adm01-debug commented May 19, 2026

Contexto

GitHub Actions desbloqueou hoje (budget reset). Quando o CI voltou a rodar, 3/79 edge functions estavam com TS errors travando o gate Edge Functions — Deno typecheck em todas as runs. Causa: erros introduzidos pelo Lovable nos 1115 commits das últimas 48h.

Fixes (3 arquivos, +11/-2)

1. sync-external-db/index.ts:83 — TS18046

} catch (error) {
  console.error("Sync error:", error);
+ const errorMessage = error instanceof Error ? error.message : String(error);
- return new Response(JSON.stringify({ error: error.message }), {
+ return new Response(JSON.stringify({ error: errorMessage }), {

error em catch é unknown por padrão no TS strict. Type guard padrão.

2. simulation-orchestrator/index.ts:221 — TS18046

Mesmo padrão, mesmo fix.

3. cnpj-lookup/index.ts:58 — TS2322 'string | undefined' → 'string'

  const apiKey = Deno.env.get("CNPJA_API_KEY");
+ if (!apiKey) {
+   console.error("[cnpj-lookup] CNPJA_API_KEY não configurada");
+   return new Response(
+     JSON.stringify({ error: "Serviço de consulta CNPJ não configurado" }),
+     { status: 503, headers: { ...corsHeaders, "Content-Type": "application/json" } },
+   );
+ }
  const response = await fetchWithBreaker("cnpja", url, {
    headers: { Authorization: apiKey },  // antes: undefined chegava aqui
  });

Fail-closed: melhor 503 explícito que mandar Authorization: undefined pra API CNPJá (que ia rejeitar ou cobrar como anônimo). Comportamento defensivo.

Validação

$ deno 2.7.14
$ node scripts/typecheck-edge-functions.mjs sync-external-db simulation-orchestrator cnpj-lookup
🔎 Typechecking 3 edge function(s)...
  • sync-external-db ......... ✅
  • simulation-orchestrator .. ✅
  • cnpj-lookup .............. ✅
✅ All 3 edge function(s) typecheck cleanly.

Por que merge

  • Destrava o gate Edge Functions — Deno typecheck (falhava em 100% dos PRs hoje, inclusive chore(lint): consolida 99 imports duplicados + corrige 5 eqeqeq (Lovable 19/mai) #9 que mergeei)
  • Mudanças mínimas (+11/-2), zero risco funcional
  • Padrão error instanceof Error será candidato a regra ESLint depois (Lovable repete esse erro com frequência — mesmo padrão aparece em 18+ lugares nas outras edges, mas não bloqueia CI hoje)

Summary by cubic

Fixes three TypeScript errors in edge functions, unblocking the Edge Functions — Deno typecheck CI gate. Adds safe error handling and a defensive env var check for the CNPJ lookup.

  • Bug Fixes
    • sync-external-db and simulation-orchestrator: use error instanceof Error ? error.message : String(error) before serializing (TS18046).
    • cnpj-lookup: require CNPJA_API_KEY; if missing, return 503 JSON error and avoid sending Authorization: undefined.

Written for commit 0c62fc8. Summary will update on new commits. Review in cubic

Summary by CodeRabbit

Notas de Lançamento

  • Bug Fixes
    • Melhorado o tratamento de erros em múltiplos endpoints para garantir respostas confiáveis em cenários de falha.
    • Adicionada validação de configuração necessária antes de executar requisições externas, retornando uma resposta apropriada quando configurações estiverem ausentes.
    • Normalizado o processamento de mensagens de erro para maior robustez em diferentes tipos de exceção.

Review Change Stack

- sync-external-db:83 (TS18046): type guard antes de error.message
- simulation-orchestrator:221 (TS18046): mesmo padrão
- cnpj-lookup:58 (TS2322): guard de Deno.env.get + 503 fail-closed se ausente

Validação: node scripts/typecheck-edge-functions.mjs sync-external-db simulation-orchestrator cnpj-lookup → all clean
- sync-external-db:83 (TS18046): type guard antes de error.message
- simulation-orchestrator:221 (TS18046): mesmo padrão
- cnpj-lookup:58 (TS2322): guard de Deno.env.get + 503 fail-closed se ausente

Validação: node scripts/typecheck-edge-functions.mjs sync-external-db simulation-orchestrator cnpj-lookup → all clean
Copilot AI review requested due to automatic review settings May 19, 2026 17:20
@vercel
Copy link
Copy Markdown

vercel Bot commented May 19, 2026

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
we-dream-big Ready Ready Preview, Comment May 19, 2026 5:20pm

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented May 19, 2026

Caution

Review failed

The pull request is closed.

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 1c39ec83-b7cf-4dca-910a-e142add4360f

📥 Commits

Reviewing files that changed from the base of the PR and between d95df4e and 0c62fc8.

📒 Files selected for processing (3)
  • supabase/functions/cnpj-lookup/index.ts
  • supabase/functions/simulation-orchestrator/index.ts
  • supabase/functions/sync-external-db/index.ts

Walkthrough

PR implementa defesas contra crashes em três funções Supabase: valida variável de ambiente obrigatória antes de chamar API externa, e normaliza captura de erros em handlers para evitar assumir que exceptions possuem propriedade message.

Changes

Validação e Tratamento de Erros

Layer / File(s) Summary
Validação de CNPJA_API_KEY no cnpj-lookup
supabase/functions/cnpj-lookup/index.ts
Função agora valida existência de CNPJA_API_KEY antes de chamar API externa, retornando HTTP 503 com JSON de erro se variável não estiver configurada.
Normalização de erros em handlers
supabase/functions/simulation-orchestrator/index.ts, supabase/functions/sync-external-db/index.ts
simulation-orchestrator e sync-external-db agora normalizam exceções com error instanceof Error ? error.message : String(error) antes de retornar respostas HTTP, evitando crashes ao acessar message em thrown values que não são Error.

Estimated code review effort

🎯 1 (Trivial) | ⏱️ ~5 minutes

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/edge-functions-typecheck-19mai

Comment @coderabbitai help to get the list of available commands and usage tips.

@adm01-debug adm01-debug merged commit 0aac3c2 into main May 19, 2026
8 of 19 checks passed
@adm01-debug adm01-debug deleted the fix/edge-functions-typecheck-19mai branch May 19, 2026 17:20
Copy link
Copy Markdown
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Fixes three TypeScript errors blocking the Deno typecheck CI gate for edge functions. Two cases apply the standard error instanceof Error type guard for unknown catch parameters, and one adds a fail-closed check for a missing CNPJA_API_KEY env var.

Changes:

  • Type-guard error in catch blocks of sync-external-db and simulation-orchestrator.
  • Return 503 in cnpj-lookup when CNPJA_API_KEY is unset, preventing Authorization: undefined.

Reviewed changes

Copilot reviewed 3 out of 3 changed files in this pull request and generated no comments.

File Description
supabase/functions/sync-external-db/index.ts Narrow unknown error to message string before JSON response.
supabase/functions/simulation-orchestrator/index.ts Same type-guard pattern for catch error.
supabase/functions/cnpj-lookup/index.ts Early return 503 when CNPJA_API_KEY is missing.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

} catch (error) {
return new Response(JSON.stringify({ error: error.message }), {
const errorMessage = error instanceof Error ? error.message : String(error);
return new Response(JSON.stringify({ error: errorMessage }), {
console.error("Sync error:", error);
return new Response(JSON.stringify({ error: error.message }), {
const errorMessage = error instanceof Error ? error.message : String(error);
return new Response(JSON.stringify({ error: errorMessage }), {
adm01-debug added a commit that referenced this pull request May 24, 2026
* fix: resolve TS/ESLint errors in items #9#17 (exhaustive bug fix batch)

#9 price-response.adapter.ts — typed 4 helper fns (asRec/str/num/bool/optStr)
to eliminate 61 TS errors from snake/camelCase + null-safety issues

#10 AdminProductFormPage.tsx — fixed PromobrindProduct field access after
expanding ~50 optional fields in product-types.ts

#11 AddressTab.tsx — replaced Record<string,unknown> form props with typed
interfaces, eliminating 56 TS errors

#12 BasicDataTab.tsx — same root cause as #11, typed interfaces applied,
32 TS errors resolved

#13 CompareTableView.tsx — changed import from @/types/product.ts (DB
snake_case) to @/types/product-catalog.ts (UI camelCase), fixing 26 TS errors

#14 SupabaseConnectionsTab.tsx — replaced 17 non-null assertions (!) with
nullish coalescing (??) + type casts

#15 CatalogContent.tsx + ProductQuickView.tsx — removed unused imports/vars,
resolving 32 ESLint warnings

#16 useSimulatorWizard.ts — added dispatch to all 15 useCallback/useEffect
dep arrays; useGlobalSearch.ts — removed unused imports, stabilised callback,
fixed non-null assertions and missing deps

#17 T-FIX-5b ESLint guardrail added to eslint.config.js; guards added before
forEach+expect loops in commercial-intelligence.test.ts; baselines updated
to grandfather existing violations in magic-up tests

Baselines: .tsc-baseline.json (1065 errors frozen), .eslint-baseline.json (405)

* fix(#17): fix all T-FIX-5b forEach+expect violations in magic-up tests

- magic-up-result-panel-keyboard.test.tsx: 64 violations fixed
  - getDots()/getThumbs() forEach (getAllByRole throws on empty): eslint-disable-next-line
  - Literal arrays [prev,next], [0,1,2]: eslint-disable-next-line
  - calls/elements/observedIndices: expect(var).not.toHaveLength(0) guards added
  - REQUIRED_*_CLASSES consts: eslint-disable-next-line
  - ids/thumbNames/liveRegions: guards added

- magic-up-onda5.test.tsx: 29 violations fixed
  - required/select.allCards/allMarcar/literal arrays: eslint-disable-next-line
  - cards/listitems/winnerButtons/buttons/tabIndices: guards added
  - REQUIRED_FOCUS_CLASSES const: eslint-disable-next-line

ESLint baseline updated: 405 → 401 errors (positive drift on all T-FIX-5b work)

* fix(#17): suppress T-FIX-5b in commercial-intelligence (guards already in place)

All 14 remaining forEach+expect violations suppressed with
// eslint-disable-next-line no-restricted-syntax after the existing
expect(array).not.toHaveLength(0) guards. Arrays are provably non-empty
static constants (PERIOD_OPTIONS=9, MOCK_TRENDING=4, MOCK_OPPORTUNITIES=4)
or deterministic generators (generateDateMap(30), generateMockMarketData(360)).

Pattern applied consistently with magic-up test fixes from previous commit:
- Guard documents intent (catches accidental empty-array mutation)
- Disable comment acknowledges guard is in place and suppresses the lint rule

Result: 0 T-FIX-5b errors in all 3 test files. T-FIX-5b work fully complete.

---------

Co-authored-by: Claude <noreply@anthropic.com>
Co-authored-by: Codex Simulation <codex-simulation@example.local>
adm01-debug added a commit that referenced this pull request May 25, 2026
…ós-colapso)

Fecha 2 dos 3 itens P0/P1 pendentes do RELATORIO_COLAPSO_2026-05-24:

- #3  idle_session_timeout = 0 -> 10min (ALTER DATABASE)
       idle_in_transaction_session_timeout = 0 -> 60s (ALTER DATABASE)
- #10 log_min_duration_statement = -1 -> 2000ms (ALTER ROLE, via supautils)

Aplicado via MCP em 2026-05-25 13:00-13:20 UTC. Conexão PostgREST zumbi
de 10.9 dias (PID 2376) foi eliminada na hora pelo novo idle_session_timeout.

Operações idempotentes - reaplicação pelo pipeline é segura.

Restante pendente: #6 Auth Connection Strategy (so via Dashboard).
adm01-debug added a commit that referenced this pull request May 25, 2026
…ós-colapso) (#336)

Fecha 2 dos 3 itens P0/P1 pendentes do RELATORIO_COLAPSO_2026-05-24:

- #3  idle_session_timeout = 0 -> 10min (ALTER DATABASE)
       idle_in_transaction_session_timeout = 0 -> 60s (ALTER DATABASE)
- #10 log_min_duration_statement = -1 -> 2000ms (ALTER ROLE, via supautils)

Aplicado via MCP em 2026-05-25 13:00-13:20 UTC. Conexão PostgREST zumbi
de 10.9 dias (PID 2376) foi eliminada na hora pelo novo idle_session_timeout.

Operações idempotentes - reaplicação pelo pipeline é segura.

Restante pendente: #6 Auth Connection Strategy (so via Dashboard).
adm01-debug added a commit that referenced this pull request May 25, 2026
…337)

* fix(db): aplica idle_*_timeout e log_min_duration_statement (Fase 6 pós-colapso)

Fecha 2 dos 3 itens P0/P1 pendentes do RELATORIO_COLAPSO_2026-05-24:

- #3  idle_session_timeout = 0 -> 10min (ALTER DATABASE)
       idle_in_transaction_session_timeout = 0 -> 60s (ALTER DATABASE)
- #10 log_min_duration_statement = -1 -> 2000ms (ALTER ROLE, via supautils)

Aplicado via MCP em 2026-05-25 13:00-13:20 UTC. Conexão PostgREST zumbi
de 10.9 dias (PID 2376) foi eliminada na hora pelo novo idle_session_timeout.

Operações idempotentes - reaplicação pelo pipeline é segura.

Restante pendente: #6 Auth Connection Strategy (so via Dashboard).

* docs: adiciona STATUS_POS_COLAPSO_2026-05-25.md (auditoria do follow-up)

Documenta a operação completa de fechamento das pendências do colapso
de 24/05, com:

- Linha do tempo consolidada 24/05 -> 25/05 (~24h)
- Validação direta nas fontes dos 10 achados originais (queries + resultados)
- Detalhe técnico das 2 correções aplicadas hoje:
  * ALTER DATABASE idle_session_timeout / idle_in_transaction_session_timeout
  * ALTER ROLE log_min_duration_statement (via supautils)
- Tabela-resumo final: 6/10 resolvidos, 3/10 com nuance, 1/10 pendente
- 5 licoes aprendidas (BPM / processo)
- Pendencias ativas organizadas por P0/P1/P2
- Bloco de queries SQL prontas para auditoria futura

Companheiro de leitura do RELATORIO_COLAPSO_2026-05-24.md.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants