t1k:cocos:migration:dep-graph
| Field | Value |
|---|---|
| Module | migration |
| Version | 0.3.0 |
| Effort | medium |
| Tools | — |
Keywords: cocos, component name, dep graph, export form, migration, registry, require graph
How to invoke
Section titled “How to invoke”/t1k:cocos:migration: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-migration-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 (auto-installs acorn + acorn-walk on first run; npm install in scripts/ makes them reproducible):
- 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()); 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 attach/cutover). - Builds the requiredBy reverse map + detects circular requires. Also folds in incoming edges from scripts OUTSIDE
assets/script(editor tools, build entry-points) — 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-migration-js2tsemits an arity-tolerance overload ONLY on over-called methods. - 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-migration-js2tsuses it to emit@propertyONLY on real components (a non-component → plain fields, else TS1240). - Writes the registry (map
file → {uuid, exportForm, tsExport, componentName}) + top-levelmethodArity.
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 = 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 |
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) |
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 is a cc-component safe as export default.
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). Manynonefiles “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.
JSON contract
Section titled “JSON contract”{ "version": 1, "scanned": 434, "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": [ { "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": [], "globalsProvided": ["TaskManager"], // window.X = ... defined by this file "globalsUsed": [ { "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": [ { "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": { "getConfig": 3, "continue": 2, "onExit": 0 }, // NAME → max args any call passes (whole-program); js2ts overload targeting "_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": [ { "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": [ { "file": "scripts/TeamHead.js", "name": "GunModel", "line": 15 } ], "externalConsumers": [ { "from": "../preloadModule.js", "target": "managers/EffectManager.js", "usage": "assign" } ] }}# First run (auto-installs acorn, ~5s):node .claude/skills/t1k-cocos-migration-dep-graph/scripts/dep-graph.cjs
# Human-readable summary:node .claude/skills/t1k-cocos-migration-dep-graph/scripts/dep-graph.cjs --pretty
# Write the registry to a file:node .claude/skills/t1k-cocos-migration-dep-graph/scripts/dep-graph.cjs --out tmp/dep-registry.json
# Target a specific folder (STILL full-tree scans for accurate requiredBy, then filters output):node .claude/skills/t1k-cocos-migration-dep-graph/scripts/dep-graph.cjs <scriptRoot>/effects/visual/
# Detail for ONE file (full-tree scan → globally accurate requiredBy + valueRequired):node .claude/skills/t1k-cocos-migration-dep-graph/scripts/dep-graph.cjs --pretty <scriptRoot>/components/visual/Avatar.jsGotchas
Section titled “Gotchas”-
Cocos auto-export + value-require: a bare
cc.Class({...})file →cc-component, BUT Cocos auto-exports it so it CAN still be required as a value → in that casetsExport=export =(see thevalueRequiredflag). Do NOT assume a cc-component is alwaysexport default. -
Sub-path always full-tree scans: passing a single file or sub-dir still scans all of the script root and only then filters the output — so
requiredBy/valueRequired/global stay globally accurate (a folder-only scan gives wrong numbers). -
Bare-global = scope analysis, may surface implicit-global leaks: an undeclared free identifier (e.g.
e,rnd_name) is reported inglobalsUsed— it may be an implicit-global bug, NOT a real global. Review beforedeclare. The scope analysis leans toward over-reporting (safe: better to declare extra than to miss one → TS compile error).
9b. Builtin set is DATA-DRIVEN (not hardcoded): the builtin/ambient set used to filter globalsUsed is DERIVED at runtime: (1) Object.getOwnPropertyNames(globalThis) → JS/ECMAScript globals; (2) parsing declare in creator.d.ts → engine globals (cc, sp, dragonBones, CC_*, Editor); (3) a small stable DOM/Web residual + language-context names (require, module, exports, arguments, self). Mini-game/native platform globals (wx/tt/qq/swan/jsb/…) are deliberately NOT filtered — they’re in no TS lib AND absent from creator.d.ts, so they genuinely need a declare; leaving them unfiltered surfaces them in externalGlobals so the js2ts globals.d.ts generator declares them (SSOT, no duplicated allowlist). The final authority on “what needs a declare” is tsc at the js2ts step.
-
eval/with no longer skips the whole file: AST distinguishes a global
eval(/with-statement (scope-dangerous →scopeUnreliableflag) from a methodobj.eval()/arr.with()(harmless). A scope-unreliable file still has full require/exportForm/window data; only bare-globals are best-effort. -
Aliased require + new:
var $x = require("./X"); new $x()→ the script detects this pattern and marks the usage as"new". Ensuresexport =for file X. -
Incoming edges from OUTSIDE
assets/script(editor + build entry-points) — must be folded or export form is wrong: Cocos compiles EVERY script underassets/(not onlyassets/script). Scanning onlyassets/scriptwould under-report requiredBy → a cc-component value-required ONLY by an external script → wrongly classifiedexport defaultinstead ofexport =→require()at the entry-point breaks. Fix: scan.jsoutside the tree (parent of scanRoot), fold VALUE edges into requiredBy/valueRequired, markexternal:true+_meta.externalConsumers. Only.jsis scanned (acorn can’t parse TS types; out-of-tree.tsdon’t import into the set). -
cc.find("path")/getChildByName("X")are NOT a dep-graph channel (negative result): they are NODE names in the scene hierarchy, NOT script/class names. Node names live in.fire/.prefab(scene graph), do not map to a.jsfile → no script↔script edge. The codemod doesn’t change string literals → paths are invariant. Contrast with gotcha #12:getComponent("X")= class-name (script-dep, FROZEN) ><cc.find/getChildByName= node-name (orthogonal). Do NOT add this channel (YAGNI). -
properties: { x: { type: T } }is NOT a new dependency channel (verified, negative result): iftype: FoothenFooMUST already berequire("./Foo")/imported in scope → the require-graph ALREADY has that edge; a type-ref is merely a “usage” of the require, not a new edge. Deciding which identifier emits@property({type: X})is a transformation of thet1k-cocos-migration-js2tscodemod — NOT dep-graph’s job. Do NOT add a type-ref channel (YAGNI). -
getComponent(“X”) = 4th dependency channel, component name FROZEN: Cocos references a component by its string class-name via
getComponent/addComponent/...("X"). The registered name = cc.Classnameoption if present, else = filename. Codemod consequence (integrity): when converting it must emit@ccclass("<componentName>")with the EXACT original name + keep the file basename, or everygetComponent("X")returns null → crash._meta.frozenComponentNames= names that must not change;_meta.brokenComponentRefs= refs pointing at a non-existent component (pre-existing dead/orphan, do NOT fix). Note: this channel does NOT affecttsExport. -
Cocos 2.x require by BASENAME (not only path): Cocos Creator 2.x registers every script in a flat namespace keyed by basename (script names MUST be unique). So
require("pako")(no./) AND a relativerequire("./Attribute")whose path doesn’t resolve → all resolve via the global basename. Resolver: relative-path (.js/.ts/index) first → basename fallback (unique index). NOT modeling this = missingrequiredByedges → may wrongly assignexport defaultto a cc-component that should beexport =. Safety condition: unique basenames (0 collisions) — on a collision the index drops that name (no guessing)._meta.danglingRequireslists relative requires that fail to resolve (a pre-existing JS bug, do NOT fix per integrity). -
Circular timing: static cycle detection over the graph — not runtime circular detection. A circular require in CommonJS JS still runs (Cocos accepts it); just track it when writing TS to avoid TDZ.
-
UUID from .meta: read from
<file>.js.meta. Null if the file was never imported into the Cocos editor (an orphan file). Check for null before transplanting a UUID. -
Strictly read-only: the script NEVER writes/edits
.jsfiles. If edits are needed — that’s a different skill (t1k-cocos-migration-js2ts). -
Parser fallback: ES5 →
latestscript →latestmodule. UsesecmaVersion: 'latest'because some files are ES2022 with class fields. ES modules are NOT rare: many files already useimport/export(hybrid: ES import + acc.Classbody, orexport default). dep-graph collectsimport ... from,export ... fromre-exports, and dynamicimport('...')as dependency edges — just likerequire(). exportForm recognizes ES exports →es-default/es-named, never misclassifying them asnone/export {}. -
Excluded dirs:
node_modules,temp,library,build,dist,quick-scripts,BackupAssets,.git— skipped automatically.
- Scan:
Bashrunsnode .claude/skills/t1k-cocos-migration-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”t1k-cocos-migration-js2ts— codemod that consumes this skill’s Export-Form Registry as input.t1k-cocos-migration-migrate— orchestrator; usesresults[].extendsAbs/requiresto topo-sort the closure.