t1k:cocos:base:dep-graph
| Field | Value |
|---|---|
| Module | base |
| Version | 3.3.2 |
| Effort | medium |
| Tools | — |
Keywords: acorn, ast, component-graph, dep-graph, export-form, require-graph
How to invoke
Section titled “How to invoke”/t1k:cocos:base:dep-graphWhen to use this skill
Section titled “When to use this skill”Activate when you need to:
- Know which files use
module.exports =(require-target) vs a barecc.Class(cc-component). - Produce the Export-Form Registry before running the
t1k-cocos-base-js2tscodemod. - Get the require-graph map: who requires whom, reverse deps, circular cycles.
- Decide
export =vsexport defaultper file when writing the TS version.
Do NOT use for: editing JS, generating TS, or cutover — this is a read-only scanner.
What the skill does
Section titled “What the skill does”Node.js CLI script scripts/dep-graph.cjs. Install its pinned parser dependencies once with cd scripts && npm ci --ignore-scripts; the scanner itself is offline/read-only and never invokes a package manager:
- Scans every
*.jsunder the target dir (defaultClient/assets/script/). - Parses the AST with acorn (ES5 →
latestscript →latestmodule fallback;latestis required to read class fields likex = Date.now()in ES2022 files). Never skips a file because of eval/with — it detects a globaleval()/with-statement via AST (accurate, never confused byobj.eval()such askit.eval()); only flagsscopeUnreliablefor the bare-global portion. - Classifies the exportForm of each file (see table below).
- Collects every
require('...')+ ESimport...from, classifying usage (assign/new/member/bare). - Resolves per the Cocos 2.x model: relative-path (
.js/.ts/index) FIRST, then a global-basename fallback (Cocos registers every script by its unique basename →require("pako"), or a relative path that fails to resolve, still resolves by name). A relative require that resolves to nothing is listed in_meta.danglingRequires(a pre-existing bug in the JS). - Reads the uuid from
<file>.meta(used to transplant uuids during cutover). - Builds the requiredBy reverse map + detects circular requires. Also folds in incoming edges from scripts OUTSIDE
assets/script(editor tools,preloadModule.js,Startup.js…) — Cocos compiles every script underassets/, and those can value-require into the set → affectingvalueRequired/export-form. Such edges are markedexternal:true. - Analyzes globals:
globalsProvided(window.X = ...defined by the file) +globalsUsed(window.X+ bare free-globals via scope analysis) → feedsdeclaregeneration when converting to TS. - Analyzes the component-name graph (4th dependency channel): collects
getComponent/addComponent/...("X")string refs (AST), the registeredcomponentNameper file (= cc.Classnameoption, else filename), reversecomponentRefBy,_meta.frozenComponentNames(names the codemod MUST preserve), and_meta.brokenComponentRefs(string refs that match no component → dead/orphan). - Emits JSON facts to stdout — the skill body / agent reasons over them.
- Collects the method call-arity map (
methodArity: NAME → max args any call passes, whole-program; over-approximated by name) sot1k-cocos-base-js2tsemits an arity-tolerance overload ONLY on over-called methods (a method called with more args than it declares), keeping non-over-called methods clean. - Computes transitive component-ness (
isComponentper file): walks each cc.Classextendschain to acc.*engine component base (ENGINE_COMPONENT_BASES) —extends cc.Component✓,extends require("./Proto")follows the chain, no-extends✗.t1k-cocos-base-js2tsuses it to emit@propertyONLY on real components (a non-component likeEntity extends Proto→ plain fields, else TS1240). - Writes the registry (map
file → {uuid, exportForm, tsExport, componentName}) + top-levelmethodArityconsumed byt1k-cocos-base-js2ts.
Export-Form → TS export form decision table
Section titled “Export-Form → TS export form decision table”| exportForm | Detection condition | TS export form | Notes |
|---|---|---|---|
commonjs-class | module.exports = cc.Class(...) or = <var assigned cc.Class> | export = | JS require() from other files keeps working unchanged |
commonjs-object | module.exports = { ... } or = function(){} | export = | Keeps require() compatibility |
commonjs-named | Only exports.foo = ... (no module.exports assignment) | named (re-export each field) | Uncommon, review manually |
cc-component | Top-level bare cc.Class({...}) (no module.exports), Cocos auto-registers | export = if valueRequired, otherwise export default | ⚠️ Cocos auto-export → this file CAN be required as a value |
none | No export at all (side-effect/patch: assigns window.X, or cc.X = cc.Class(...) patches the engine) | always export {} (even if valueRequired) | none has no value → require() always returns {}; export = would CHANGE require’s return value (e.g. net.js window.net) = behavior change. Internal cc.Class patches are preserved, NO @ccclass |
es-default | Already an ES module: has export default <expr> | export default | Module system ALREADY migrated; preserve. ES export wins over an in-file cc.Class (the module’s real value is the default binding). 7 files. |
es-named | Already an ES module: export class/const/function, export { a }, export * from (no default) | named | Preserve. NEVER export {} (would delete real exports → break import X from). 1 file (sdk.js). |
General principle (every row above follows it): the TS export form must preserve the value require() currently returns for real consumers + keep class-registration/side-effects. valueRequired only changes the form when the file HAS a value to export (cc-component); a none file has no value, so it is always export {}.
CORE gotcha (usage-aware): Cocos 2.x auto-exports the cc.Class() result → a cc-component file CAN still be require()’d as a VALUE (e.g. var X = require("./Avatar"); ...ctor: X). Therefore tsExport is NOT decided by exportForm alone: if ANY file requires it with usage assign/new/member (flag valueRequired=true) → it MUST be export = (keep module.exports = X), otherwise require() returns {default:X} and the untouched JS consumer breaks. Only when valueRequired=false (only bare/never required) is a cc-component safe as export default. Real example: Avatar.js is a cc-component but required by 12 files (10 as VALUE) → export =.
Global graph (window.X + bare global)
Section titled “Global graph (window.X + bare global)”dep-graph tracks globals as a 2nd dependency channel in parallel with require:
globalsProvided: files that assignwindow.X = ...(provider). ~361 global names in the project; 53/95nonefiles actually “export” via a global this way (the registry still records exportForm=none, but globalsProvided shows they provide a global).globalsUsed:window.Xreads + bare free-globals (via scope analysis) → the list needingdeclare const X: any/declare global { interface Window {...} }for the TS to compile._meta.globalProvidedBy: global → defining file._meta.externalGlobals: bare globals used but defined by NO file → SDK/runtime needing a declare (sdk44×,net,kit,MAX,HUMAN…).
JSON contract
Section titled “JSON contract”{ "version": 1, "scanned": 434, "elapsedMs": 4800, "results": [ { "file": "managers/LevelManager.js", // relative to target dir "uuid": "3f7a1c29-...", // from .meta, null if absent "exportForm": "cc-component", // see table above "requires": [ { "spec": "./Entity", "line": 3, "internal": true, "usage": "assign" // assign|new|member|bare } ], "requiredBy": ["managers/GameManager.js"], "requiredByDetail": [ // each require edge into this file { "file": "managers/GameManager.js", "usage": "assign", "line": 42 }, { "file": "../preloadModule.js", "usage": "assign", "line": 5, "external": true } // outside assets/script ], "valueRequired": true, // true if any usage is assign/new/member "circular": [], // array of cycle paths, if any "globalsProvided": ["TaskManager"], // window.X = ... defined by this file "globalsUsed": [ // need a `declare` when converting to TS { "name": "user", "kind": "window" }, { "name": "net", "kind": "bare" } ], "scopeUnreliable": false, // true if a global eval()/with is present → bare-global best-effort "componentName": "LevelManager", // registered name (= cc.Class name option, else filename); null if not a component "componentRefs": [ // getComponent("X") strings inside this file { "name": "Avatar", "line": 88, "method": "getComponent" } ], "componentRefBy": ["managers/GameSystem.js"] // who calls getComponent("LevelManager") → FROZEN name } ], "registry": { "managers/LevelManager.js": { "uuid": "3f7a1c29-...", "exportForm": "cc-component", "valueRequired": true, "tsExport": "export =", // usage-aware: valueRequired → export = "componentName": "LevelManager", // codemod MUST emit @ccclass("LevelManager") "isComponent": true // transitively extends cc.Component? → @property valid (else plain fields/accessors) } }, "methodArity": { // NAME → max args any call passes (whole-program); js2ts overload targeting "getConfig": 3, "continue": 2, "onExit": 0 // getConfig over-called (3 > 2 params) → overload; onExit never → clean }, "_meta": { "exportFormCounts": { "cc-component": 301, "commonjs-object": 27, ... }, "circularFiles": [...], "topRequired": [{ "file": "...", "requiredBy": 12 }], "globalProvidedBy": { "TaskManager": ["managers/TaskManager.js"] }, "externalGlobals": { "sdk": 44, "net": 30 }, // used but defined by no file → SDK/runtime "danglingRequires": [ // relative require that resolves to nothing = pre-existing JS bug { "file": "scripts/TalentDefine.js", "spec": "../components/combat/buffs/BulletOnShot", "line": 1507 } ], "frozenComponentNames": ["Item", "battleBottomUI", "LocalLabel"], // referenced via getComponent("X") → codemod MUST keep @ccclass name exact "brokenComponentRefs": [ // getComponent("X") matching no component = dead/orphan { "file": "scripts/TeamHead.js", "name": "GunModel", "line": 15 } ], "externalConsumers": [ // edges from scripts OUTSIDE assets/script requiring into the set (already folded) { "from": "../preloadModule.js", "target": "managers/EffectManager.js", "usage": "assign" } ] }}Usage & Gotchas
Section titled “Usage & Gotchas”Full CLI flags (--pretty, --out, target-dir filtering, per-file detail) and all 15 numbered
gotchas (parser fallback to ecmaVersion: latest, Cocos-2.x basename-require resolution,
circular-cycle detection, out-of-tree incoming edges, three negative-result channels the scanner
deliberately does NOT track): references/usage-and-gotchas.md.
Load-bearing facts a downstream consumer MUST honor:
getComponent("X")component names are FROZEN. The registered name is a component’sgetComponent-visible identity;t1k-cocos-base-js2tsmust emit@ccclass("<componentName>")with the EXACT original name, or everygetComponent("X")call against it returnsnullat runtime — a silent crash, not a compile error.- UUID read from
.metacan benull(a file never imported into the Cocos editor is an orphan) — check for null before transplanting a UUID during cutover. - Strictly read-only. This scanner never writes or edits
.jsfiles.
- Scan:
Bashrunsnode .claude/skills/t1k-cocos-base-dep-graph/scripts/dep-graph.cjs [options] [dir] - Registry analysis: the skill body reads the JSON output and reasons about exportForm, requiredBy, circular
- Do NOT use Grep to detect exports — too slow and inaccurate with aliased patterns
See also
Section titled “See also”plans/reports/2026-05-29-js-to-ts-migration-brainstorm.md— full migration context (§5.2).claude/skills/cocos2x-scope-audit/— same architecture, run before dep-graph to surface implicit globalst1k-cocos-base-js2ts(proof v0.1.0) — codemod that consumes this skill’s Export-Form Registry as input