Skip to content

JS/TS: const/let X = require('./m') creates a local node X that shadows the required class (new X() and extends X bind to the import binding) #4621

Closed

Description

@sub4biz

Summary

For a CommonJS import binding const Logger = require('./logger'), the extractor creates a node Logger in the importing file. Inside that file new Logger() and class A extends Logger then resolve to this local node instead of the class defined in ./logger, so the calls / inherits edge ends in the importing file. The class in the required file gets no incoming edge from it.

The same code with an ESM default import (import Logger from './logger') resolves to the class in ./logger, and so does a var binding for calls (var Logger = require('./logger')), because that declaration kind creates no node; there class A extends Logger gets no edge at all.

Checked on v0.9.93, clean checkout. The script below covers const, let, a .ts importing file, var and an ESM import.

Reproduction

Three files. logger.js:

function Logger(p) { this.p = p; }
Logger.prototype.warn = function warn() {};
module.exports = Logger;

gen.js:

class Generator { run() {} }
module.exports = Generator;

use.js (the const variant; the script below also writes let, a .ts importing file, var and ESM variants):

const Logger = require('./logger');
const Generator = require('./gen');
function Watcher() { return new Logger('w'); }
class A extends Generator { go() {} }

Script (writes the files itself, run from the checkout):

import pathlib, tempfile
from graphify.extract import extract

LOGGER = "function Logger(p) { this.p = p; }\nLogger.prototype.warn = function warn() {};\nmodule.exports = Logger;\n"
GEN = "class Generator { run() {} }\nmodule.exports = Generator;\n"
GEN_ESM = "class Generator { run() {} }\nexport default Generator;\n"
BODY = "function Watcher() { return new Logger('w'); }\nclass A extends Generator { go() {} }\n"
VARIANTS = {  # name: (extension of the importing file, import lines, gen.js)
    "const":    ("js", "const Logger = require('./logger');\nconst Generator = require('./gen');\n", GEN),
    "let":      ("js", "let Logger = require('./logger');\nlet Generator = require('./gen');\n", GEN),
    "const-ts": ("ts", "const Logger = require('./logger');\nconst Generator = require('./gen');\n", GEN),
    "var":      ("js", "var Logger = require('./logger');\nvar Generator = require('./gen');\n", GEN),
    "esm":      ("js", "import Logger from './logger';\nimport Generator from './gen';\n", GEN_ESM),
}
for name, (ext, head, gen) in VARIANTS.items():
    d = pathlib.Path(tempfile.mkdtemp())
    (d / "logger.js").write_text(LOGGER, encoding="utf-8")
    (d / "gen.js").write_text(gen, encoding="utf-8")
    (d / f"use.{ext}").write_text(head + BODY, encoding="utf-8")
    r = extract([d / "logger.js", d / "gen.js", d / f"use.{ext}"], cache_root=d / "_cache", root=d, parallel=False)
    n = {x["id"]: x for x in r["nodes"]}
    where = lambda x: pathlib.Path(n[x]["source_file"]).name
    print(name, "| Watcher() calls:", sorted((n[e["target"]]["label"], where(e["target"])) for e in r["edges"]
                                             if e["relation"] == "calls" and n[e["source"]]["label"] == "Watcher()"),
          "| A inherits:", sorted((n[e["target"]]["label"], where(e["target"])) for e in r["edges"]
                                  if e["relation"] == "inherits" and n[e["source"]]["label"] == "A"))

Output on v0.9.93:

const | Watcher() calls: [('Logger', 'use.js')] | A inherits: [('Generator', 'use.js')]
let | Watcher() calls: [('Logger', 'use.js')] | A inherits: [('Generator', 'use.js')]
const-ts | Watcher() calls: [('Logger', 'use.ts')] | A inherits: [('Generator', 'use.ts')]
var | Watcher() calls: [('Logger()', 'logger.js')] | A inherits: []
esm | Watcher() calls: [('Logger()', 'logger.js')] | A inherits: [('Generator', 'gen.js')]

For const, both edges end in use.js (on the binding). For var the call is right and there is no inherits edge at all. For ESM both are right.

A real repository

webpack/webpack at c28d144bc4be7993307718fd74c7f62f9d097bad: lib/asset/AssetGenerator.js has

const Generator = require("../module/Generator");
...
class AssetGenerator extends Generator {

and lib/module/Generator.js defines class Generator. Extracting just these two files (python script.py <path to the webpack checkout>):

import pathlib, sys, tempfile
from graphify.extract import extract

root = pathlib.Path(sys.argv[1]).resolve()  # a webpack checkout at the commit above
r = extract([root / "lib/module/Generator.js", root / "lib/asset/AssetGenerator.js"],
            cache_root=pathlib.Path(tempfile.mkdtemp()), root=root, parallel=False)
n = {x["id"]: x for x in r["nodes"]}
for e in r["edges"]:
    if e["relation"] == "inherits":
        t = n[e["target"]]
        sf = pathlib.Path(t["source_file"])
        print(n[e["source"]]["label"], "inherits", t["label"], "in", (sf.resolve().relative_to(root) if sf.is_absolute() else sf).as_posix())

prints:

ByTypeGenerator inherits Generator in lib/module/Generator.js
AssetGenerator inherits Generator in lib/asset/AssetGenerator.js

ByTypeGenerator is defined inside Generator.js and resolves correctly; AssetGenerator should also end in lib/module/Generator.js.

Over the whole repository (every .js/.mjs/.cjs file outside node_modules, edges whose source file is not under test/), 328 of 336 inherits edges and 741 of 10,977 calls edges end in the source file itself, on a relative-require binding of the target's name. The script that counts them (a few minutes on webpack; run it from the root of the graphify checkout, pass the webpack checkout as the argument):

count script
import pathlib, re, sys, tempfile
from graphify.extract import extract

root = pathlib.Path(sys.argv[1]).resolve()  # a webpack checkout
files = sorted(p for p in root.rglob("*") if p.suffix in {".js", ".mjs", ".cjs"}
               and not {"node_modules", ".git"} & set(p.parts))
r = extract(files, cache_root=pathlib.Path(tempfile.mkdtemp()), root=root, parallel=False)
n = {x["id"]: x for x in r["nodes"]}
def rel(x):
    p = pathlib.Path(n[x]["source_file"])
    return (p.resolve().relative_to(root) if p.is_absolute() else p).as_posix()
binding = lambda name: re.compile(r"^\s*(?:const|let|var)\s+%s\s*=\s*require\(\s*[\"'](\.[^\"']*)[\"']\s*\)" % re.escape(name), re.M)
seen, total, wrong = set(), {"inherits": 0, "calls": 0}, {"inherits": 0, "calls": 0}
for e in r["edges"]:
    if e["relation"] not in total or e["source"] not in n or e["target"] not in n:
        continue
    sf, tf = rel(e["source"]), (rel(e["target"]) if n[e["target"]].get("source_file") else "")
    key = (sf, n[e["source"]]["label"], e["relation"], e.get("context"), tf, n[e["target"]]["label"])
    if sf.startswith("test/") or key in seen:
        continue
    seen.add(key)
    total[e["relation"]] += 1
    if tf == sf and binding(n[e["target"]]["label"].removesuffix("()")).search((root / sf).read_text(encoding="utf-8", errors="replace")):
        wrong[e["relation"]] += 1
print("inherits:", wrong["inherits"], "of", total["inherits"])
print("calls:", wrong["calls"], "of", total["calls"])

Output on v0.9.93 with webpack at c28d144bc4be7993307718fd74c7f62f9d097bad:

inherits: 328 of 336
calls: 741 of 10977

Expected

Both edges end on the class in the required file, as for the ESM default import.

Related

#3778 (closed) concerns calls through require('./m').fn and destructured bindings. This report is the whole-module binding const X = require('./m'), which still behaves as described on v0.9.93.

Activity

  1. github-actions commented on Oct 21, 2026

    @github-actions

    Thanks for opening this issue, @sub4biz. A maintainer will take a look soon.

    If you would like to discuss it in real time, come say hi on our Discord server. For longer-form questions and ideas there is also GitHub Discussions.

    To help us triage, please make sure the report includes what you expected, what actually happened, and the steps (and a small sample) to reproduce it.

  2. safishamsi commented on Oct 22, 2026

    @safishamsi
    Member
  3. sub4biz commented on Oct 23, 2026

    @sub4biz
    Author

    Thanks for the fix. new X() now resolves to the required class. One part of the original report is not covered: class A extends X with const X = require('./gen') now gets no inherits edge (before it ended on the binding node), and new Plugin() for require('some-package') also lost its edge. A repro and numbers on webpack (lib/: 336 inherits edges on 0.9.93, 8 on 0.9.94) are in #4688.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions