fix(migrate): codemod ctx não reescreve mais dentro de strings e comentários - #511
Open
JonasJesus42 wants to merge 1 commit into
Open
fix(migrate): codemod ctx não reescreve mais dentro de strings e comentários#511JonasJesus42 wants to merge 1 commit into
JonasJesus42 wants to merge 1 commit into
Conversation
…comments
`transformCtxCompat` walks the file character by character with no notion of
string or comment boundaries, so a `ctx.` occurring as *text* was rewritten the
same as one occurring as code:
console.log('ctx.device:', ctx.device);
-> console.log('ctx?.device:', ctx?.device);
The call site is patched correctly and the message next to it is silently
corrupted — it still compiles, so nothing catches it. Same for double-quoted
strings, line and block comments, and template literal text.
Adds a literal/comment guard to the scan loop. Template literals are tracked
with a small context stack rather than skipped wholesale, because their `${}`
interpolations ARE code: `` `${ctx.vtex.account}` `` must still be rewritten
while `` `ctx.device` `` must not.
Regex literals are deliberately left untracked, and the reason is in a comment:
telling `/re/` from division requires real parsing, and guessing wrong would
consume live code. A `ctx.` inside a regex in a loader is vanishingly rare next
to that risk.
Five regression tests, four of which fail against the previous implementation
(verified by reverting the source and re-running).
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Contexto
O codemod
transformCtxCompat(migração Fresh → TanStack) transforma leituras dectxem optional chainspara que uma app não configurada no site alvo devolva
undefinedem vez de lançar — sem isso owithSectionLoaderengole a exceção e a seção renderiza em branco.Ele varre o arquivo caractere a caractere, sem nenhuma noção de fronteira de string ou comentário. O
resultado é que um
ctx.que aparece como texto era reescrito igual a um que aparece como código:A chamada é corrigida certo e a mensagem ao lado é corrompida em silêncio. E compila, então nada pega —
nem build, nem typecheck, nem teste. Vale igual para strings com aspas duplas, comentários de linha e de
bloco, e o texto de template literals.
Nenhum teste cobria isso.
O que muda
Um guard de literal/comentário no laço de varredura. Ao encontrar
//,/* */,'…'ou"…", o trecho écopiado verbatim em vez de escaneado.
Template literals não são pulados por inteiro, porque suas interpolações são código de verdade. São
rastreados com uma pequena pilha de contexto, de modo que:
Isso também cobre template aninhado (
`a${`b${ctx.device}`}c`) e aspas escapadas dentro de string.Regex literais ficam deliberadamente de fora, e o motivo está num comentário no código: distinguir
/re/de uma divisão exige parsing de verdade, e errar o palpite faria o scanner consumir código vivo. Um
ctx.dentro de uma regex num loader é raríssimo perto desse risco.
Por que não
ts-morphO
blocks-clijá depende dets-morph, e reescrever por AST eliminaria a classe inteira de bug em vez detratar os casos que a gente lembrou. Não fiz isso aqui porque o scanner carrega lógica já testada e sutil
(
isAssignTarget, chains já opcionais, acesso computado balanceado), e a reescrita traria risco de regressãodesproporcional ao bug. Fica como um caminho conhecido caso o scanner precise crescer de novo.
Validação
Cinco testes de regressão. Quatro deles falham contra a implementação anterior — verifiquei revertendo o
source e rodando a suíte, para o teste não ser decorativo:
13testes no arquivo (8 existentes + 5 novos), todos passando. Suíte completa em2589passando; as 4falhas em
draft previewsão pré-existentes nomain. Lint e typecheck limpos.Procedência
Encontrado por um
/code-reviewque se anunciava como sendo do #510. Não é: o #510 tem 16 arquivos e nenhumdeles é
ctx-compat.ts(conferido pela API do GitHub). O review provavelmente rodou sobre o diff local deoutro workspace. O bug, porém, é real e independente de qualquer PR — daí este ir separado.
🤖 Generated with Claude Code
Summary by cubic
Corrige o codemod
transformCtxCompatpara não reescreverctx.dentro de strings, comentários e texto de template literals. Antes,console.log('ctx.device:', ctx.device)viravaconsole.log('ctx?.device:', ctx?.device), corrompendo mensagens em silêncio sem quebrar compilação.O que mudou
${}.Written for commit 1a25167. Summary will update on new commits.