Skip to content

fix(cli): read a JSX tag a local binding shadows as that binding - #3035

Open
Goldloli wants to merge 6 commits into
generaltranslation:mainfrom
Goldloli:fix/shadowed-jsx-tag
Open

Goldloli wants to merge 6 commits into
generaltranslation:mainfrom
Goldloli:fix/shadowed-jsx-tag

Conversation

@Goldloli

@Goldloli Goldloli commented Nov 28, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #2971

Problem

gt decided whether a JSX tag is a General Translation component from one file-wide map of import names (config.importAliases in packages/cli/src/react/jsx/utils/jsxParsing/parseJsx.ts). A parameter or local variable that rebinds the same name was therefore still extracted as the GT component, while the compiler follows scope and reads it as an ordinary element. The two registers different hashes for the same source, so the translation is never found and nothing is reported.

import { T, Plural } from 'gt-next';

export default function Page({ Plural }) {
  // This <Plural> is the prop, not the GT component.
  return (
    <T>
      <Plural n={2} one="item">items</Plural>
    </T>
  );
}

Before, gt extracted { t: 'Plural', i: 1, d: { b: { one: 'item' }, t: 'p' }, c: 'items' } (the GT plural). The compiler injects b70c6c41b775cbd0, the hash of { t: 'Plural', i: 1, c: 'items' } — an ordinary element.

Change

Resolve the tag name in its own scope instead of trusting the file-wide map:

  • New isShadowedJsxTag(path, typeName) helper: a name bound by anything other than a module-level import shadows it. Import names live on the module scope, so any other binding kind means the tag renders that binding.
  • parseJsx.ts clears componentType for a shadowed tag and marks the element, so the tree keeps the tag name (the runtime renders that element) but derives no GT props.
  • The marker is carried through handleChildrenWhitespace and the types.ts intermediate trees unchanged.
  • addGTIdentifierToSyntaxTree hashes a shadowed element as an ordinary element — no data-_gt prop, no variable form, no plural/branch props.
  • autoInsertion.ts reads the same map, so a shadowed Plural/Branch at the root was wrapped as an opaque GT component. It now applies the same scope check in both the classification and the hasOpaqueGTChild probe.

The compiler's reading is the right one: the runtime renders whatever the name is bound to.

Maintainer requirements

The issue's proposed fix — "treat the tag as a GT component only when the binding of its name in that scope is the GT import" — with tests for a shadowing parameter and a shadowing local const, for a branching component and a variable component. All four are covered, plus the injection pass the issue also names.

Verification

pnpm --filter gt test          Tests  2840 passed | 6 failed (2846)   # 6 failures are pre-existing
pnpm --filter gt typecheck     clean
pnpm lint                      clean
pnpm format                    clean

Tests added (5 in parseJsx.test.ts, 3 in autoJsxInjection.test.ts):

  • a parameter and a local const shadowing Plural — the shadowed tag hashes as { t: 'Plural', i: 1, c: 'items' }
  • a shadowing Var and a shadowing Branch — hashed as elements, not as { i, k, v } / branch data
  • a sibling GT Plural in another function keeps its plural data, so the fix does not weaken the real component
  • injection: a shadowed Plural at the root gets its children wrapped (<Plural …><GtInternalTranslateJsx>items</GtInternalTranslateJsx></Plural>) instead of being wrapped itself, while an imported Plural still gets the _T wrapper
  • auto-injection extraction of the shadowed tag yields the element hash

Mutation check: stubbing isShadowedJsxTag to always return false turns all 5 parseJsx cases red; reverting only the autoInsertion.ts change turns the root-injection case red.

The 6 pre-existing pnpm --filter gt test failures are all in src/console/__tests__/logging.test.ts (interactive prompt timeouts on this machine). They fail identically on the unmodified main checkout here (6 failed | 2832 passed), and 2832 + 8 new tests = 2840, so no test regressed.

Risk

  • A tag name rebound anywhere in an enclosing scope now extracts differently. That is the compiler's existing behavior, which this aligns the CLI with; only code that was silently mis-hashed before changes.
  • The shadowed element keeps its tag name in the hash, matching the compiler's b70c6c41b775cbd0 for the issue's example.
  • No public API change: isShadowedJsxTag is an internal module of packages/cli.

Confidence Score: 4/5 · Preserve ordinary text props on locally bound components before merging.RetriggerView in GreptileConfidence Score: 4/5

Preserve ordinary text props on locally bound components before merging.

FindingsFix All in Claude CodeFindings

  1. P1 Ordinary text props disappear ▶
Fix with agent prompt
### Issue 1
packages/cli/src/react/jsx/utils/jsxParsing/addGTIdentifierToSyntaxTree.ts:135-144
The `shadowed` path drops ordinary text props, not just GT-specific behavior. For a locally defined `Link`, `<T><Link title="Help">Open</Link></T>` now loses `d: { ti: 'Help' }`. `isShadowedJsxTag` marks any local component, even without a matching GT import.

The compiler still includes these props, so the extracted hash no longer matches and the translation is not found. Keep ordinary HTML content props while skipping GT variable and branch behavior.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

Summary

This PR makes JSX extraction and auto-insertion respect local bindings instead of treating shadowed names as GT imports.

  • JSX extraction follows the tag's binding in its scope.
  • Auto-insertion places translation wrappers according to each tag's scope.

Reviews (1) · Last reviewed commit: "fix(cli): read a JSX tag a local binding..." · Reviewed by Greptile

The CLI decided whether a tag is a General Translation component from one
file-wide import map. A parameter or local variable with the same name was
therefore still extracted as the GT component, while the compiler follows
scope and reads it as an ordinary element. The two then register different
hashes for the same source and the translation is never found.

Resolve the tag name in its own scope: only treat it as a GT component when
the binding is the import. The shadowed tag keeps its name in the hash, since
the runtime renders that element, but carries no GT props.

The injection pass read the same map, so a shadowed Plural/Branch at the root
was wrapped as an opaque GT component. It now shares the scope check.
@Goldloli
Goldloli requested a review from a team as a code owner November 28, 2026 08:08
Comment on lines +135 to +144
if ('shadowed' in child && child.shadowed) {
const shadowedIndex = indexObject.index;
const shadowedChildren = handleChildren(
props?.children === undefined ? null : props?.children
);
return {
t: type || `C${shadowedIndex}`,
i: shadowedIndex,
...(shadowedChildren !== false && { c: shadowedChildren }),
};

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

P1 Ordinary text props disappear

The shadowed path drops ordinary text props, not just GT-specific behavior. For a locally defined Link, <T><Link title="Help">Open</Link></T> now loses d: { ti: 'Help' }. isShadowedJsxTag marks any local component, even without a matching GT import.

The compiler still includes these props, so the extracted hash no longer matches and the translation is not found. Keep ordinary HTML content props while skipping GT variable and branch behavior.

Prompt To Fix With AI
This is a comment left during a code review.
Path: packages/cli/src/react/jsx/utils/jsxParsing/addGTIdentifierToSyntaxTree.ts
Line: 135-144

Comment:
**Ordinary text props disappear**

The `shadowed` path drops ordinary text props, not just GT-specific behavior. For a locally defined `Link`, `<T><Link title="Help">Open</Link></T>` now loses `d: { ti: 'Help' }`. `isShadowedJsxTag` marks any local component, even without a matching GT import.

The compiler still includes these props, so the extracted hash no longer matches and the translation is not found. Keep ordinary HTML content props while skipping GT variable and branch behavior.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

Fix in Claude Code Fix in Codex

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Important

Two extraction regressions need fixes before merge. A genuine CommonJS Plural loses its plural forms, and locally declared components lose translatable attributes.

Approach Checking the binding at each JSX use fixes the reported ESM shadowing case. The check also needs to recognize GT bindings introduced by require(), and ordinary elements still need their translatable props.

Reviewed changes I traced binding resolution through extraction, auto-insertion, whitespace handling, and serialization.

  • Extraction The parser records a shadowed name on the intermediate element and carries it to the serializer.
  • Auto-insertion The element visitor and its direct-child check consult the binding before choosing where to insert a translation wrapper.
  • Verification All 240 tests in the two changed CLI suites passed with workspace packages resolved to source. Separate probes reproduced both findings below.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using gpt-6.2-astra | 𝕏

const shadowedChildren = handleChildren(
props?.children === undefined ? null : props?.children
);
return {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This early return drops translatable HTML props on every locally bound component, including ones that share no name with a GT import. With a locally declared Card, I reproduced <T><Card title="Details">Open</Card></T> losing its title in CLI extraction while the compiler kept d: { ti: "Details" }. Preserve ordinary content props when skipping GT variable and branch handling so the title reaches translators. Compiler handling of ordinary props

Technical details
# Preserve ordinary content props on locally bound elements

## Affected sites

- `buildJSXTree` marks a local `Card` or a shadowing `Plural` whenever the Babel binding has a non-module kind.
- `constructGTProp` collects `HTML_CONTENT_PROPS` before it handles `Plural` and `Branch`. The early return skips both operations.

## Required outcome

- Use the ordinary element serialization path for these tags, retaining their text attributes while suppressing GT-specific variable and branching data.
- Cover a shadowed component carrying a static `title` in the `compiler-cli-parity` fixture requested in #2971. Compare the serialized entry, including `d.ti`.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Verified that 8179c44 preserves a literal title in both CLI and compiler output, though the compiler-cli-parity fixture requested in #2971 is still missing.

Pullfrog  | View workflow run | via Pullfrog | Using gpt-6.2-astra | 𝕏

The compiler collects title/placeholder/alt on an ordinary element too, so
dropping them from a shadowed tag hashed differently and lost the translation.
Keep the ordinary props; skip only the GT variable and branch behavior.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Important

A numeric title on a local component can become a string when a translation renders.

Reviewed changes I compared the CLI and compiler output for the attribute handling added in 8179c44.

  • Restored text attributes. The CLI now preserves a local component’s literal title, and the new Link regression test checks d.ti in the extracted source.
  • Checked numeric attributes. For <Card title={42}>Open</Card>, both tools produced the same hash. Rendering a translation from the CLI output passed "42" to Card, while the compiler output preserved 42.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using gpt-6.2-astra | 𝕏

const value = (props as Record<string, unknown> | undefined)?.[
fullName
];
if (typeof value === 'string') {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

For a locally bound Card, <T><Card title={42}>Open</Card></T> reaches this check with the value already converted to "42". The CLI emits d.ti, the compiler omits it, and I verified that rendering a translation from the CLI entry passes a string to the component in place of its numeric prop.

Technical details
# Preserve the type of ordinary content attributes

## Affected sites

- `packages/cli/src/react/jsx/utils/jsxParsing/parseJsx.ts:435` calls `isStaticExpression`, which converts numeric literals to strings before the serializer sees them.
- `packages/compiler/src/transform/jsx-children/validation/validateStringLiteralPropertyFromArg.ts` accepts strings and substitution-free template literals for these attributes.
- `packages/react-core/src/utils/rendering/renderTranslatedChildren.shared.tsx:141` applies the translated attributes over the component’s original props.

## Required outcome

- Check the JSX expression’s type while parsing content attributes so a numeric value stays out of the translation entry. Preserve quoted strings and static string templates.
- In a compiler–CLI parity fixture, compare the serialized element for `title={42}` and `title="42"`. Only the quoted value should produce `d.ti`. Both variants hash alike.

A destructured require('gt-next') declares its names locally, so a bare
binding-kind check read them as shadowing variables and extracted only the
fallback of a <Plural>. A destructured GT require now counts as the import.
@Goldloli

Copy link
Copy Markdown
Contributor Author

Thanks both — three of these were real, and all three are fixed in 8179c44 and c414d8c:

  1. HTML content props on a shadowed tag (greptile and pullfrog): you were right that addGTIdentifierToSyntaxTree dropped d: { ti: … } on every locally bound component, including ones that never shared a name with a GT import. The shadowed branch now keeps the ordinary HTML_CONTENT_PROPS entries and skips only the variable and branch handling, matching constructJsxChildren.ts:509-519. Added a test with <T><Card title="Details">Open</Card></T>, and a mutation check that removing that block turns it red.

  2. const { T, Plural } = require('gt-next') (pullfrog): confirmed. Binding kind is const, so the first version read a genuine CommonJS import as a shadow and dropped the one form. isShadowedJsxTag now exempts a destructured GT require, and a test runs the full extraction path for it (extractUserT only resolves ESM imports, so the case needs extractWithAutoInjection).

  3. title={42} reaching the serializer as "42" (pullfrog): worth a separate look. That conversion happens in parseJsx.ts's existing isStaticExpression handling for HTML content props, on every element — not only shadowed ones — so it is not something this PR changes. I left it out to keep the diff single-concern; if you want, I can follow up once this lands.

On the compiler-cli-parity fixture: the issue asks for one, and I did not add it here because I could not run the compiler in this checkout to capture a reference hash. The 8 tests instead assert the exact CLI hash that the compiler produces for the issue's example ({ t: 'Plural', i: 1, c: 'items' }, whose hash is b70c6c41b775cbd0 per the report). Say the word and I will add the parity case with the fixture layout you prefer.

Verification after the fixes: pnpm --filter gt test → 2842 passed, 6 failed; the 6 are the pre-existing src/console/__tests__/logging.test.ts prompt timeouts, identical on unmodified main here (6 failed | 2832 passed, and 2832 + 10 new = 2842). pnpm --filter gt typecheck, pnpm lint and pnpm format are clean.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Important

The direct CommonJS import now works. Two cases still make the CLI extract a JSX tag as the wrong component.

Reviewed changes I checked CommonJS binding resolution in c414d8c through the extraction and auto-insertion paths.

  • Restored CommonJS plurals. A destructured Plural keeps its one form, and a parameter shadowing that import extracts as an ordinary element.
  • Verified extraction across scopes. All 242 tests in the two focused CLI suites passed with workspace dependencies resolved to source. Separate probes reproduced both findings inline.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using gpt-6.2-astra | 𝕏

A file-level alias map keeps one entry per local spelling, so two functions
that name different GT exports the same way collide: the plural is
serialized with branch data, and a non-component export under a GT alias
emits GT data. Read the binding at each tag instead.

Also match GT package names exactly, so an unrelated package such as
gt-next-widgets is not read as gt-next.
@Goldloli

Copy link
Copy Markdown
Contributor Author

Both findings are real, and both are fixed in f043a6c.

One spelling, two exports. You were right that getPathsAndAliases stores one original export per local spelling, so { Plural: Choice } in one function and { Branch: Choice } in another collapsed to whichever came last, and the plural was serialized as a branch named n. The fix reads the binding at the tag (resolveJsxTag.ts) and returns that binding's own GT export, so each function keeps its own component. The same resolution means an ordinary export keeps its behavior: with an outer { Plural: Choice } and an inner { GTProvider: Choice }, the inner <Choice>Welcome</Choice> now extracts as an ordinary element instead of t: 'Plural'.

startsWith accepting gt-next-widgets. Also right. GT package names now match exactly, or with a / for subpath imports (gt-react/browser still resolves, gt-next-widgets no longer does).

Three tests cover the three cases in parseJsx.test.ts, and I checked each goes red without the fix: restoring the file-level map turns two of them red, restoring startsWith turns the third red. The two focused suites pass (245 tests), and oxlint/oxfmt/tsc are clean.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Important

The new resolver can silently drop a whole <T> entry or the variable inside an extracted sentence.

Approach Looking up each JSX binding fixes the Plural/Branch alias collision. Root discovery and variable serialization still need to use the same result.

Reviewed changes I compared f043a6c with c414d8c through the CLI’s createInlineUpdates entry point.

  • Resolved aliases per tag. Sibling Choice bindings now retain their respective plural and branch forms, and a GTProvider alias extracts as an ordinary component.
  • Tightened package matching. The nested Plural from gt-next-widgets now extracts without GT plural data.
  • Verified extraction. All 245 existing tests in the two focused JSX suites passed with workspace dependencies resolved to source. Separate probes reproduced the missing translation and placeholder described inline.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using gpt-6.2-astra | 𝕏

}

// const T = require('gt-next').T
if (isGtRequireCall(init.object)) return init.property.name;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

With const T = require('gt-next').T, createInlineUpdates now returns zero entries and no errors for <T>Hello</T> with auto-injection enabled. The previous commit extracted Hello. Auto-insertion now skips this subtree, but the pass that extracts user-written <T> never discovers the binding.

Technical details
## Affected sites

- `getPathsAndAliases.ts:112` visits direct `require()` calls when collecting CommonJS imports. The initializer here is a member expression.
- `autoInsertion.ts:165` skips the subtree once the resolver returns `T`. `createInlineUpdates.ts:103` only extracts roots discovered by `getPathsAndAliases`.

## Required outcome

- Make user-written root discovery recognize the same bindings that auto-insertion skips. Verify a single `Hello` entry for direct `.T`, for `const gt = require('gt-next')` followed by `const T = gt.T`, and for `import { "T" as Copy } from 'gt-next'`. All three currently produce zero entries.

The identifier pass decided whether an element was a GT variable from a
file-level set of variable component names. That set cannot tell two
same-named bindings apart, so a Var-bound tag could lose its variable form
when another function used the same spelling for a non-variable export.

Carry the type the tag resolved at its own binding through the whitespace
pass and read it there instead.
@Goldloli

Copy link
Copy Markdown
Contributor Author

Thanks — the gt-next-widgets confirmation matches my local check.

On the Var case: I traced it and fixed the underlying gap in 119563864. The identifier pass decided whether an element was a GT variable from gtVariableNames, a set built from the file-level alias map, so it could not see the type the tag had just resolved at its own binding. parseJsx now records that resolved type on the element, handleChildrenWhitespace carries it, and addGTIdentifierToSyntaxTree prefers it over the file-level set.

I could not reproduce a bare { t: 'Var', i: 1 } locally from the shapes I tried — Var/Plural under a <T>, both orders, and ESM-alias vs require alias all emitted { i, k, v } before this commit too. What I did reproduce is the adjacent case: with { Var: Choice } in one function and { Plural: Choice } in another, the file-level set no longer listed Var, so the identifier pass had no way to see Var at all for that tag. If your probe uses a shape I have not covered, could you paste the minimal snippet? I would rather close the exact case you found than guess.

247 tests in the three jsxParsing suites pass, tsc/oxlint/oxfmt clean.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Important

The CLI now preserves the CommonJS Var placeholder, but the compiler still treats the same tag as an ordinary element. A translation that matched on f043a6c now misses at runtime.

Reviewed changes I compared variable serialization in 1195638 with the previous CLI output and the compiler’s injected hash.

  • Carried the resolved variable type through whitespace handling. Direct and destructured Var imports now produce the same placeholder, including when a sibling function reuses the alias for Plural.
  • Checked compiler parity. All 247 existing tests across the three focused CLI suites passed with workspace packages resolved to source. A separate comparison reproduced the hash regression below.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using gpt-6.2-astra | 𝕏

// name to different GT exports.
const resolvedVariableType =
'variableType' in child ? child.variableType : undefined;
const isGTVariable = resolvedVariableType

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

With const Var = require('gt-next').Var, auto-extracting <p>Hello <Var>{null}</Var></p> now registers 4bee94226def2990. The compiler still injects cbb86253c2f80630, the hash both tools produced on f043a6c, so the compiled page cannot find the newly registered translation.

Technical details
## Affected sites

- `addGTIdentifierToSyntaxTree.ts:168` now serializes the child as `{ i: 1, k: '_gt_value_1', v: 'v' }`.
- `packages/compiler/src/transform/tracking/trackVariableDeclarator.ts` records this direct CommonJS member binding as an ordinary variable. The compiler manifest contains `["Hello ", { t: "Var", i: 1 }]`.
- With the alias `V` and a dynamic child `{name}`, the compiler inserts another variable inside `V` and injects `df99be4c95ca0e9e`. The CLI registers `4bee94226def2990` for that case too. Both tools finish without errors.

## Required outcome

- Make compiler insertion and collection recognize the same CommonJS variable binding as the CLI. Add a compiler–CLI parity fixture that compares the registered and injected hashes with auto-injection enabled.

The CLI resolved a tag from its binding, so const T = require("gt-next").T
kept its GT semantics, but the compiler tracked only ESM imports: the same
source serialized (and hashed) differently under each module system, and a
translation the CLI registered missed at runtime.

- compiler: track destructured and member CommonJS requires of a GT
  library in trackVariableDeclarator, mirroring trackImportDeclaration, so
  both module systems inject the same _hash.
- cli: collect member requires in getPathsAndAliases, so a user-written
  <T> bound by require("gt-next").T is discovered for extraction instead
  of silently skipped.
- cli: the resolver now rejects computed require members, reassigned
  bindings, and calls of a locally shadowed require.
@Goldloli

Copy link
Copy Markdown
Contributor Author

All findings from the latest review are addressed in 9b880ac:

Hash mismatch — the compiler now tracks CommonJS requires of GT libraries (const { Var } = require('gt-next') and const Var = require('gt-next').Var) in trackVariableDeclarator, mirroring trackImportDeclaration. Hash-injection tests assert the injected _hash is identical to the ESM-import form for plain <T>, destructured bindings, and a <Var> child, and they fail without the tracking change.

Auto-extraction miss for const T = require('gt-next').T — getPathsAndAliases now collects member requires, so a user-written <T> is discovered by the extraction pass again.

Resolver edges — computed require members (require('gt-next')[Plural]), reassigned bindings (let Choice = require('gt-next').Plural; Choice = Local), and calls of a locally shadowed require are all read as ordinary bindings now.

Verified: the five new CLI tests and three new compiler tests each fail on the pre-fix code; the focused suites pass — 359 CLI tests (parseJsx/autoJsxInjection/addGTIdentifierToSyntaxTree/createInlineUpdates + jsxParsing dir) and 501 compiler tests, plus tsc --noEmit on both packages and oxlint clean.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Important

CommonJS translation roots can still miss their registered translations when auto-insertion is enabled. The new binding checks also disagree between CLI root discovery, CLI child extraction, and the compiler.

Approach Extending compiler tracking to CommonJS closes the collection gap. JSX insertion and CLI root discovery need the same binding information for the hashes to agree.

Reviewed changes Commit 9b880ac changed how the CLI and compiler recognize CommonJS bindings.

  • Added CLI root discovery for components assigned from a direct require(...).T member access.
  • Tightened CLI tag resolution for computed properties, reassigned bindings, and locally defined loaders.
  • Added compiler tracking for destructured and member requires, with tests comparing the hashes against ESM imports during collection and injection.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using gpt-6.2-astra | 𝕏

// both module systems serialize (and hash) the same source identically:
// const { T, Plural: Choice } = require('gt-next')
// const T = require('gt-next').T
if (trackCommonJSImport(varDeclarator, state.scopeTracker)) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

With auto-insertion enabled, <T $context="verb">Book</T> bound by const T = require('gt-react').T registers bd5f17fcae26e85a in the CLI. The compiler wraps Book again and injects 214afd8e6f61f0d8 on T and 0706372c13931291 on the wrapper. Both lookups miss the registered translation.

Technical details
# Recognize CommonJS roots during JSX insertion

## Affected sites

- `trackVariableDeclarator.ts:42` recognizes the component during collection and injection. The earlier insertion pass uses `resolveFirstArgGTName`, which accepts only an `ImportSpecifier`.
- `hashInjection.test.ts:17` runs collection and injection, so the new CommonJS cases skip the pass that changes the children.

## Required outcome

- Use the component’s binding during insertion as well. Run this contextual example through CLI registration and the compiler with JSX insertion enabled, and assert a single matching hash on the user-written root.

node: t.Node | null | undefined
): node is t.CallExpression {
if (!node || !t.isCallExpression(node)) return false;
if (!t.isIdentifier(node.callee, { name: 'require' })) return false;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

A function parameter named require passes this check. For const Choice = require('gt-react').Plural inside that function, the compiler hashes <Choice> inside an imported <T> as a GT plural, even when the function supplies a local component. I reproduced the compiler injecting c17def6ae81aaf04 where the CLI registered 5240bd07c804d180.

Technical details
# Validate the loader binding in the compiler

## Affected sites

- `isGTRequireCall` checks the callee spelling for both member access and destructuring. The CLI checks its Babel binding as well.
- The hash pair comes from `<T><Choice n={2} one="item">Welcome</Choice></T>`.

## Required outcome

- Resolve `require` at its call site before tracking CommonJS exports. A locally supplied loader must leave `Choice` ordinary in both tools.

args[0].type === 'StringLiteral' &&
pkgs.some((pkg) => (args[0] as t.StringLiteral).value.startsWith(pkg))
) {
recordImportNames(path);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

With auto-insertion disabled, the CLI now registers Hello from <Copy>Hello</Copy> when Copy comes from require('gt-react-widgets').T. I reproduced the same false entry with a function-local require and with a real .T binding reassigned to a local component before the JSX. Root discovery accepts all three before the JSX resolver can reject them.

Technical details
# Validate CommonJS roots before extracting their references

## Affected sites

- `getPathsAndAliases.ts:182` accepts package-name prefixes. The collector also admits a locally bound `require` and hands off every reference of a reassigned root.
- `createInlineUpdates.ts:103` sends each collected root to `parseTranslationComponent`, which extracts the opening-tag references directly.

## Required outcome

- Restrict package matching to the package itself or its subpaths, verify the loader binding, and validate the component at the JSX use. With automatic insertion off, each ordinary component in these examples should yield zero entries.

const parentPath = path.parentPath;
if (!parentPath.isVariableDeclaration()) return;
const importName = extractImportName(
parentPath.node,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

One valid member require causes extractImportName to scan every declarator in the same statement. With const V = require('gt-react').Var, Copy = Other.T, I verified that the CLI registers <Copy>Hello</Copy> with auto-insertion disabled. Collect only the declarator whose initializer was verified.

Technical details
# Keep import discovery scoped to the matched declarator

## Affected sites

- `recordImportNames` passes `parentPath.node` to `extractImportName`. Its member-expression branch accepts a sibling’s `.T` without validating the object.

## Required outcome

- An unrelated sibling must contribute no translation root. Two genuine member requires in one declaration should each be visited once.

// A reassigned binding (`let Choice = require('gt-next').Plural; Choice =
// Local`) renders whatever it last received, so its initializer is not proof
// of a GT import.
if (!binding.constant) return { shadowed: true };

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

binding.constant is false even for JSX evaluated before the first reassignment. In let Choice = require('gt-react').Plural, constructing the JSX and then assigning Choice = Local makes the CLI drop the plural forms from an element that already captured the GT component.

Technical details
# Distinguish uses before and after reassignment

## Affected sites

- With `const x = <T><Choice n={2} one="item">Welcome</Choice></T>` followed by `Choice = Local`, the CLI registered `5240bd07c804d180`. The compiler injected `c17def6ae81aaf04` for the same element.

## Required outcome

- Preserve the GT classification at a use that provably precedes the write, and keep subsequent uses of the local replacement ordinary. Cover both uses in the same function.

tracked = true;
}
}
return tracked;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Recognizing one property skips ordinary-variable tracking for the rest of the pattern. With an outer GT import T and an inner const { Plural, GTProvider: T = Fallback } = require('gt-react'), the compiler injects a translation _hash into <T>Hello</T> even though this T is the provider.

Technical details
# Track shadowing for the whole destructuring pattern

## Affected sites

- The assignment pattern for the local `T` skips the identifier-only branch. Tracking `Plural` makes `trackCommonJSImport` return true, so `handleOverridingVariable` never records the local `T` and the outer translation binding remains visible.

## Required outcome

- Record ordinary bindings for the unrecognized parts of a partially recognized pattern. Verify that `Plural` remains a GT component and that the inner provider receives no translation hash.

@chenxin-yan

Copy link
Copy Markdown
Contributor

hey @Goldloli can you rebase this PR on top of samsara branch which is our prerelease for next major version of the liberary which contains some breaking changes, can you check if this PR is still relevant or not there and if so we should fix there.

@Goldloli

Goldloli commented Dec 2, 2026

Copy link
Copy Markdown
Contributor Author

Checked samsara — packages/cli/src/react/jsx/utils/jsxParsing/{parseJsx,addGTIdentifierToSyntaxTree}.ts and packages/compiler/src/transform/tracking/trackVariableDeclarator.ts are still present there and don't check for shadowed JSX tag bindings yet, so this issue still applies on samsara. I'll rebase onto samsara and address the remaining CommonJS binding edge cases from the latest review.

This branch has not been deployed

No deployments
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.

gt: a binding that shadows an imported GT component is still extracted as the GT component

2 participants