@codyn06/cboard 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (107) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +68 -2
  3. package/THIRD_PARTY_NOTICES +29 -0
  4. package/bin/cboard-context.js +15 -0
  5. package/bin/cboard.js +5 -0
  6. package/dist/adapters/bash.d.ts +2 -0
  7. package/dist/adapters/bash.js +14 -0
  8. package/dist/adapters/c-family.d.ts +2 -0
  9. package/dist/adapters/c-family.js +81 -0
  10. package/dist/adapters/csharp.d.ts +2 -0
  11. package/dist/adapters/csharp.js +47 -0
  12. package/dist/adapters/extra-languages.d.ts +3 -0
  13. package/dist/adapters/extra-languages.js +15 -0
  14. package/dist/adapters/go.d.ts +2 -0
  15. package/dist/adapters/go.js +42 -0
  16. package/dist/adapters/grammar.d.ts +21 -0
  17. package/dist/adapters/grammar.js +54 -0
  18. package/dist/adapters/index.d.ts +20 -0
  19. package/dist/adapters/index.js +62 -0
  20. package/dist/adapters/java.d.ts +2 -0
  21. package/dist/adapters/java.js +36 -0
  22. package/dist/adapters/kotlin.d.ts +2 -0
  23. package/dist/adapters/kotlin.js +65 -0
  24. package/dist/adapters/lua-family.d.ts +2 -0
  25. package/dist/adapters/lua-family.js +186 -0
  26. package/dist/adapters/php.d.ts +2 -0
  27. package/dist/adapters/php.js +28 -0
  28. package/dist/adapters/python.d.ts +2 -0
  29. package/dist/adapters/python.js +68 -0
  30. package/dist/adapters/ruby.d.ts +2 -0
  31. package/dist/adapters/ruby.js +46 -0
  32. package/dist/adapters/rust.d.ts +2 -0
  33. package/dist/adapters/rust.js +85 -0
  34. package/dist/adapters/swift.d.ts +2 -0
  35. package/dist/adapters/swift.js +38 -0
  36. package/dist/adapters/types.d.ts +61 -0
  37. package/dist/adapters/types.js +1 -0
  38. package/dist/adapters/typescript.d.ts +2 -0
  39. package/dist/adapters/typescript.js +52 -0
  40. package/dist/api.d.ts +50 -0
  41. package/dist/api.js +421 -0
  42. package/dist/cboard.d.ts +2 -0
  43. package/dist/cboard.js +97 -0
  44. package/dist/cli.d.ts +27 -0
  45. package/dist/cli.js +180 -0
  46. package/dist/docs-parse.d.ts +64 -0
  47. package/dist/docs-parse.js +762 -0
  48. package/dist/extract.d.ts +36 -0
  49. package/dist/extract.js +458 -0
  50. package/dist/index.d.ts +5 -0
  51. package/dist/index.js +5 -0
  52. package/dist/languages.d.ts +9 -0
  53. package/dist/languages.js +128 -0
  54. package/dist/model.d.ts +85 -0
  55. package/dist/model.js +1 -0
  56. package/grammars/LICENSES/README.md +3 -0
  57. package/grammars/LICENSES/c.LICENSE +21 -0
  58. package/grammars/LICENSES/kotlin.LICENSE +21 -0
  59. package/grammars/LICENSES/lua.LICENSE +21 -0
  60. package/grammars/LICENSES/luau.LICENSE +21 -0
  61. package/grammars/LICENSES/swift.LICENSE +21 -0
  62. package/grammars/manifest.json +39 -0
  63. package/grammars/tree-sitter-c.wasm +0 -0
  64. package/grammars/tree-sitter-kotlin.wasm +0 -0
  65. package/grammars/tree-sitter-lua.wasm +0 -0
  66. package/grammars/tree-sitter-luau.wasm +0 -0
  67. package/grammars/tree-sitter-swift.wasm +0 -0
  68. package/kit/cboard-connect.js +490 -0
  69. package/kit/cboard-kit/brief.js +386 -0
  70. package/kit/cboard-kit/config.js +215 -0
  71. package/kit/cboard-kit/connect-check.js +52 -0
  72. package/kit/cboard-kit/headers.js +25 -0
  73. package/kit/cboard-kit/mcp.js +62 -0
  74. package/kit/cboard-kit/skill/SKILL.md +154 -0
  75. package/package.json +53 -4
  76. package/queries/bash/imports.scm +11 -0
  77. package/queries/bash/symbols.scm +1 -0
  78. package/queries/c/imports.scm +2 -0
  79. package/queries/c/symbols.scm +10 -0
  80. package/queries/cpp/imports.scm +2 -0
  81. package/queries/cpp/symbols.scm +11 -0
  82. package/queries/csharp/imports.scm +2 -0
  83. package/queries/csharp/symbols.scm +10 -0
  84. package/queries/go/imports.scm +2 -0
  85. package/queries/go/symbols.scm +8 -0
  86. package/queries/java/imports.scm +2 -0
  87. package/queries/java/symbols.scm +9 -0
  88. package/queries/javascript/imports.scm +3 -0
  89. package/queries/javascript/symbols.scm +16 -0
  90. package/queries/kotlin/imports.scm +2 -0
  91. package/queries/kotlin/symbols.scm +4 -0
  92. package/queries/lua/imports.scm +5 -0
  93. package/queries/lua/symbols.scm +6 -0
  94. package/queries/luau/imports.scm +5 -0
  95. package/queries/luau/symbols.scm +9 -0
  96. package/queries/php/imports.scm +6 -0
  97. package/queries/php/symbols.scm +7 -0
  98. package/queries/python/imports.scm +3 -0
  99. package/queries/python/symbols.scm +8 -0
  100. package/queries/ruby/imports.scm +2 -0
  101. package/queries/ruby/symbols.scm +4 -0
  102. package/queries/rust/imports.scm +5 -0
  103. package/queries/rust/symbols.scm +11 -0
  104. package/queries/swift/imports.scm +2 -0
  105. package/queries/swift/symbols.scm +5 -0
  106. package/queries/typescript/imports.scm +3 -0
  107. package/queries/typescript/symbols.scm +20 -0
@@ -0,0 +1,2 @@
1
+ import type { LanguageAdapter } from "./types.js";
2
+ export declare const luaAdapters: Record<string, LanguageAdapter>;
@@ -0,0 +1,186 @@
1
+ import { posix } from "node:path";
2
+ const SCRIPT_EXTENSIONS = [".luau", ".lua"];
3
+ const SCRIPT_KINDS = [".server", ".client", ""];
4
+ const FILE_SUFFIXES = SCRIPT_KINDS.flatMap((kind) => SCRIPT_EXTENSIONS.map((e) => kind + e));
5
+ const INIT_FILE = /^init(\.server|\.client)?\.luau?$/;
6
+ /** `local f = function` / `M.f = function`: the assigned name (single target only). */
7
+ function symbolName(node) {
8
+ if (node.type !== "assignment_statement")
9
+ return undefined;
10
+ const targets = node.firstNamedChild;
11
+ return targets?.type === "variable_list" && targets.namedChildCount === 1
12
+ ? targets.firstNamedChild?.text
13
+ : undefined;
14
+ }
15
+ /** Name of the table the chunk returns (`return M`), if it is a plain identifier. */
16
+ function returnedModule(chunk) {
17
+ for (let i = chunk.namedChildCount - 1; i >= 0; i--) {
18
+ const child = chunk.namedChild(i);
19
+ if (child?.type === "return_statement") {
20
+ const value = child.firstNamedChild?.firstNamedChild;
21
+ return value?.type === "identifier" && child.firstNamedChild?.namedChildCount === 1
22
+ ? value.text
23
+ : undefined;
24
+ }
25
+ }
26
+ return undefined;
27
+ }
28
+ /** Module members (`function M.f`, `function M:m`, `M.f = function`) of the returned table, and `export type`. */
29
+ function isExported(node, name) {
30
+ if (node.type === "type_definition")
31
+ return node.text.startsWith("export");
32
+ const chunk = node.parent;
33
+ if (chunk?.type !== "chunk")
34
+ return false;
35
+ const owner = /^([^.:]+)[.:]/.exec(name)?.[1];
36
+ return owner !== undefined && owner === returnedModule(chunk);
37
+ }
38
+ const rojoMaps = new WeakMap();
39
+ const instanceKey = (path) => path.join("\0");
40
+ /** Instance name of a script file under a mapped folder, or undefined for non-script files. */
41
+ function scriptInstance(relative) {
42
+ const parts = relative.split("/");
43
+ const base = parts.pop() ?? "";
44
+ const suffix = FILE_SUFFIXES.find((s) => base.endsWith(s) && base.length > s.length);
45
+ if (!suffix)
46
+ return undefined;
47
+ return INIT_FILE.test(base) ? parts : [...parts, base.slice(0, -suffix.length)];
48
+ }
49
+ function rojoMap(files, read) {
50
+ const cached = rojoMaps.get(files);
51
+ if (cached)
52
+ return cached;
53
+ const map = { fileToInstance: new Map(), instanceToFile: new Map() };
54
+ const mapFile = (file, instance) => {
55
+ if (!map.instanceToFile.has(instanceKey(instance))) {
56
+ map.instanceToFile.set(instanceKey(instance), file);
57
+ map.fileToInstance.set(file, instance);
58
+ }
59
+ };
60
+ const walk = (node, instance) => {
61
+ if (typeof node !== "object" || !node)
62
+ return;
63
+ const entries = Object.entries(node);
64
+ const target = node["$path"];
65
+ const path = typeof target === "string" ? posix.normalize(target.replace(/\\/g, "/")) : undefined;
66
+ if (path !== undefined) {
67
+ if (files.has(path))
68
+ mapFile(path, instance);
69
+ else
70
+ for (const file of files)
71
+ if (file.startsWith(`${path}/`)) {
72
+ const inner = scriptInstance(file.slice(path.length + 1));
73
+ if (inner)
74
+ mapFile(file, [...instance, ...inner]);
75
+ }
76
+ }
77
+ for (const [name, child] of entries)
78
+ if (!name.startsWith("$"))
79
+ walk(child, [...instance, name]);
80
+ };
81
+ const projects = [...files]
82
+ .filter((f) => !f.includes("/") && f.endsWith(".project.json"))
83
+ .sort((a, b) => Number(b === "default.project.json") - Number(a === "default.project.json") ||
84
+ a.localeCompare(b));
85
+ for (const project of projects) {
86
+ try {
87
+ walk(JSON.parse(read(project) ?? "").tree, []);
88
+ }
89
+ catch {
90
+ // A malformed project file maps nothing.
91
+ }
92
+ }
93
+ rojoMaps.set(files, map);
94
+ return map;
95
+ }
96
+ /** Top-level `local X = <expression>` lines; later resolved when X is used as a require base. */
97
+ function aliases(text) {
98
+ const found = new Map();
99
+ for (const m of text.matchAll(/^local\s+([A-Za-z_]\w*)\s*(?::[^=\n]+)?=\s*([^\n]+?)\s*;?\s*(?:--.*)?$/gm))
100
+ if (m[1] && m[2])
101
+ found.set(m[1], m[2]);
102
+ return found;
103
+ }
104
+ const STEP = /^(?:\.\s*([A-Za-z_]\w*)|:\s*(?:GetService|WaitForChild|FindFirstChild)\s*\(\s*(["'])(.*?)\2\s*(?:,[^()]*)?\)|\[\s*(["'])(.*?)\4\s*\])/;
105
+ /** Instance path of a simple expression: game/script/alias followed by .Name, :GetService(..) etc. */
106
+ function instancePath(expression, fromPath, map, aliasOf, depth = 0) {
107
+ const base = /^\s*([A-Za-z_]\w*)/.exec(expression);
108
+ if (!base?.[1] || depth > 5)
109
+ return undefined;
110
+ let rest = expression.slice(base[0].length);
111
+ let path;
112
+ if (base[1] === "game")
113
+ path = [];
114
+ else if (base[1] === "script")
115
+ path = map.fileToInstance.get(fromPath);
116
+ else {
117
+ const alias = aliasOf.get(base[1]);
118
+ path = alias === undefined ? undefined : instancePath(alias, fromPath, map, aliasOf, depth + 1);
119
+ }
120
+ for (rest = rest.trimStart(); path && rest; rest = rest.trimStart()) {
121
+ const step = STEP.exec(rest);
122
+ if (!step)
123
+ return undefined;
124
+ const name = step[1] ?? step[3] ?? step[5];
125
+ if (name === undefined)
126
+ return undefined;
127
+ if (step[1] === "Parent") {
128
+ if (!path.length)
129
+ return undefined;
130
+ path = path.slice(0, -1);
131
+ }
132
+ else
133
+ path = [...path, name];
134
+ rest = rest.slice(step[0].length);
135
+ }
136
+ return path;
137
+ }
138
+ // ---- string requires ---------------------------------------------------------------------------
139
+ function resolveString(spec, fromPath, files, rootFirst) {
140
+ const dir = posix.dirname(fromPath);
141
+ const base = posix.basename(fromPath);
142
+ const own = INIT_FILE.test(base)
143
+ ? dir
144
+ : posix.join(dir, base.replace(/(\.(server|client))?\.luau?$/, ""));
145
+ const relative = spec.startsWith("@self/")
146
+ ? [posix.join(own, spec.slice(6))]
147
+ : spec.startsWith("./") || spec.startsWith("../")
148
+ ? [posix.join(dir, spec)]
149
+ : [];
150
+ // `a.b` (Lua module path) is relative to the repository root; `a/b` or `a` to the requiring file.
151
+ const bare = spec.includes("/") ? spec : spec.replace(/\./g, "/");
152
+ const targets = relative.length
153
+ ? relative
154
+ : rootFirst
155
+ ? [bare, posix.join(dir, bare)]
156
+ : [posix.join(dir, spec), bare];
157
+ for (const target of targets.map((t) => posix.normalize(t))) {
158
+ for (const candidate of [
159
+ target,
160
+ ...SCRIPT_EXTENSIONS.map((e) => target + e),
161
+ ...SCRIPT_EXTENSIONS.map((e) => `${target}/init${e}`),
162
+ ])
163
+ if (files.has(candidate) && SCRIPT_EXTENSIONS.some((e) => candidate.endsWith(e)))
164
+ return candidate;
165
+ }
166
+ return undefined;
167
+ }
168
+ const resolveImport = (rootFirst) => (source, fromPath, files, read) => {
169
+ const quoted = /^(["'])([^"'\\]*)\1$/.exec(source.trim());
170
+ if (quoted?.[2] !== undefined)
171
+ return resolveString(quoted[2], fromPath, files, rootFirst);
172
+ const map = rojoMap(files, read);
173
+ const path = instancePath(source, fromPath, map, aliases(read(fromPath) ?? ""));
174
+ return path && map.instanceToFile.get(instanceKey(path));
175
+ };
176
+ const adapter = (grammar, rootFirst) => ({
177
+ grammar: { vendored: grammar },
178
+ queries: grammar,
179
+ resolveImport: resolveImport(rootFirst),
180
+ symbolName,
181
+ isExported,
182
+ });
183
+ export const luaAdapters = {
184
+ luau: adapter("luau", false),
185
+ lua: adapter("lua", true),
186
+ };
@@ -0,0 +1,2 @@
1
+ import type { LanguageAdapter } from "./types.js";
2
+ export declare const phpAdapter: LanguageAdapter;
@@ -0,0 +1,28 @@
1
+ import { posix } from "node:path";
2
+ /** Methods are public unless marked `private` or `protected`; everything else counts as exported. */
3
+ function isExported(node) {
4
+ if (node.type !== "method_declaration")
5
+ return true;
6
+ const visibility = node.children.find((c) => c.type === "visibility_modifier")?.text;
7
+ return visibility !== "private" && visibility !== "protected";
8
+ }
9
+ /**
10
+ * `source` is the argument of require/include: `'x.php'`, `__DIR__ . '/x.php'` or the same in
11
+ * parentheses, resolved relative to the including file. Interpolated or computed paths do not resolve.
12
+ * shortcut: `use` namespace imports and PSR-4 maps from composer.json are not followed.
13
+ */
14
+ const resolveImport = (source, fromPath, files) => {
15
+ const text = source.trim().replace(/^\(([^]*)\)$/, "$1");
16
+ const literal = /^(?:(?:__DIR__|dirname\s*\(\s*__FILE__\s*\))\s*\.\s*)?(["'])([^"'$\\{]+)\1$/.exec(text.trim());
17
+ const path = literal?.[2];
18
+ if (!path)
19
+ return undefined;
20
+ const target = posix.join(posix.dirname(fromPath), path.replace(/^\/+/, ""));
21
+ return files.has(target) ? target : undefined;
22
+ };
23
+ export const phpAdapter = {
24
+ grammar: { builtin: "php" },
25
+ queries: "php",
26
+ isExported,
27
+ resolveImport,
28
+ };
@@ -0,0 +1,2 @@
1
+ import type { LanguageAdapter } from "./types.js";
2
+ export declare const pythonAdapter: LanguageAdapter;
@@ -0,0 +1,68 @@
1
+ import { posix } from "node:path";
2
+ /** Name, kind and exported flag of a def/class, or of a decorated one (named after what it wraps). */
3
+ function declaration(node) {
4
+ const inner = node.type === "decorated_definition" ? node.childForFieldName("definition") : node;
5
+ const name = inner?.childForFieldName("name")?.text;
6
+ if (!inner || !name)
7
+ return undefined;
8
+ // A leading underscore marks a private name; dunders (`__init__`) count as exported.
9
+ return { name, kind: inner.type, exported: !name.startsWith("_") || /^__.*__$/.test(name) };
10
+ }
11
+ /** Imported names of a `from x import a as b, (c)` tail or of an `import a.b as c, d` list. */
12
+ const names = (text) => text
13
+ .replace(/#.*$/gm, "")
14
+ .replace(/[()\\]/g, " ")
15
+ .split(",")
16
+ .map((part) => /[\w.]+/.exec(part)?.[0])
17
+ .filter((n) => !!n);
18
+ /** Directory ("" or "src") holding the package that a dotted name starts with, if any. */
19
+ const absoluteRoot = (dotted, files) => ["", "src"].find((root) => files.has(posix.join(root, dotted.split(".")[0] ?? "", "__init__.py")));
20
+ /**
21
+ * `source` is the whole import statement. Relative imports resolve against the importing file's
22
+ * package; absolute ones only into packages (folders with `__init__.py`) under the repo root or `src/`.
23
+ * shortcut: a statement with several names yields one edge (the first that resolves), and
24
+ * a `from` import never resolves `__init__.py` re-exports of a name.
25
+ */
26
+ function resolveImport(source, fromPath, files) {
27
+ const text = source.trim();
28
+ const module = (stem) => [`${stem}.py`, posix.join(stem, "__init__.py")].find((p) => files.has(p));
29
+ const from = /^from\s+(\.*)([\w.]*)\s+import\s+([^]*)$/.exec(text);
30
+ if (from) {
31
+ const [, dots = "", dotted = "", imported = ""] = from;
32
+ let root;
33
+ if (dots) {
34
+ root = posix.dirname(fromPath);
35
+ for (let i = 1; i < dots.length; i++)
36
+ root = posix.dirname(root);
37
+ }
38
+ else
39
+ root = absoluteRoot(dotted, files);
40
+ if (root === undefined)
41
+ return undefined;
42
+ const pkg = posix.join(root, dotted.replaceAll(".", "/"));
43
+ for (const name of names(imported)) {
44
+ const submodule = module(posix.join(pkg, name));
45
+ if (submodule)
46
+ return submodule;
47
+ }
48
+ return dotted
49
+ ? module(pkg)
50
+ : files.has(posix.join(pkg, "__init__.py"))
51
+ ? posix.join(pkg, "__init__.py")
52
+ : undefined;
53
+ }
54
+ const plain = /^import\s+([^]*)$/.exec(text);
55
+ for (const name of names(plain?.[1] ?? "")) {
56
+ const root = absoluteRoot(name, files);
57
+ const target = root === undefined ? undefined : module(posix.join(root, name.replaceAll(".", "/")));
58
+ if (target)
59
+ return target;
60
+ }
61
+ return undefined;
62
+ }
63
+ export const pythonAdapter = {
64
+ grammar: { builtin: "python" },
65
+ queries: "python",
66
+ declaration,
67
+ resolveImport,
68
+ };
@@ -0,0 +1,2 @@
1
+ import type { LanguageAdapter } from "./types.js";
2
+ export declare const rubyAdapter: LanguageAdapter;
@@ -0,0 +1,46 @@
1
+ import { posix } from "node:path";
2
+ const VISIBILITY = new Set(["public", "private", "protected"]);
3
+ /** `class A::B` is named `A.B`. */
4
+ const symbolName = (node) => node.childForFieldName("name")?.text.replaceAll("::", ".");
5
+ /**
6
+ * Instance methods are exported unless private or protected: either after a bare `private` /
7
+ * `protected` line in the same body, or wrapped as `private def x`. Classes, modules and singleton
8
+ * methods count as exported.
9
+ * shortcut: `private :name` and `private_class_method` calls are not followed.
10
+ */
11
+ function isExported(node, name) {
12
+ if (node.type !== "method")
13
+ return true;
14
+ if (name === "initialize")
15
+ return false;
16
+ const wrapper = node.parent?.type === "argument_list" ? node.parent.parent : undefined;
17
+ const wrapped = wrapper?.childForFieldName("method")?.text;
18
+ if (wrapped && VISIBILITY.has(wrapped))
19
+ return wrapped === "public";
20
+ for (let s = node.previousNamedSibling; s; s = s.previousNamedSibling)
21
+ if (s.type === "identifier" && VISIBILITY.has(s.text))
22
+ return s.text === "public";
23
+ return true;
24
+ }
25
+ /**
26
+ * `source` is the whole call. `require_relative "x"` is relative to the file; `require "x"` only
27
+ * resolves to `lib/x.rb`. Only plain string literals resolve.
28
+ */
29
+ const resolveImport = (source, fromPath, files) => {
30
+ const call = /^(require_relative|require)\b\s*\(?\s*(["'])([^"'#\\]+)\2/.exec(source.trim());
31
+ const name = call?.[3];
32
+ if (!name)
33
+ return undefined;
34
+ const file = name.endsWith(".rb") ? name : `${name}.rb`;
35
+ const target = call[1] === "require_relative"
36
+ ? posix.join(posix.dirname(fromPath), file)
37
+ : posix.join("lib", file);
38
+ return files.has(target) ? target : undefined;
39
+ };
40
+ export const rubyAdapter = {
41
+ grammar: { builtin: "ruby" },
42
+ queries: "ruby",
43
+ symbolName,
44
+ isExported,
45
+ resolveImport,
46
+ };
@@ -0,0 +1,2 @@
1
+ import type { LanguageAdapter } from "./types.js";
2
+ export declare const rustAdapter: LanguageAdapter;
@@ -0,0 +1,85 @@
1
+ import { posix } from "node:path";
2
+ /** Methods of an `impl` block are named `Type.method`; exported means any `pub` / `pub(...)`. */
3
+ function declaration(node) {
4
+ const name = node.childForFieldName("name")?.text;
5
+ if (!name)
6
+ return undefined;
7
+ const exported = node.children.some((c) => c.type === "visibility_modifier");
8
+ const impl = node.parent?.parent;
9
+ if (impl?.type !== "impl_item")
10
+ return { name, exported };
11
+ const type = /^[\w:]+/.exec(impl.childForFieldName("type")?.text ?? "")?.[0];
12
+ return { name: type ? `${type.split("::").pop() ?? type}.${name}` : name, exported };
13
+ }
14
+ const ROOT_FILES = ["lib.rs", "main.rs", "mod.rs"];
15
+ /** Folder holding the child modules of a module file (`a.rs` owns `a/`, `mod.rs` and crate roots own their folder). */
16
+ const childDir = (file) => ROOT_FILES.includes(posix.basename(file))
17
+ ? posix.dirname(file)
18
+ : posix.join(posix.dirname(file), posix.basename(file, ".rs"));
19
+ /** Module file defined by a folder: `dir.rs`, `dir/mod.rs`, or the crate root when `dir` is `src`. */
20
+ const moduleOfDir = (dir, files) => [`${dir}.rs`, ...ROOT_FILES.map((f) => posix.join(dir, f))].find((p) => files.has(p));
21
+ const child = (file, name, files) => [`${name}.rs`, posix.join(name, "mod.rs")]
22
+ .map((p) => posix.join(childDir(file), p))
23
+ .find((p) => files.has(p));
24
+ const parent = (file, files) => moduleOfDir(ROOT_FILES.includes(posix.basename(file))
25
+ ? posix.dirname(posix.dirname(file))
26
+ : posix.dirname(file), files);
27
+ /** `src/lib.rs` or `src/main.rs` of the crate whose `Cargo.toml` is nearest above the file. */
28
+ function crateRoot(fromPath, files) {
29
+ for (let dir = posix.dirname(fromPath);; dir = posix.dirname(dir)) {
30
+ if (files.has(posix.join(dir, "Cargo.toml")))
31
+ return ["lib.rs", "main.rs"].map((f) => posix.join(dir, "src", f)).find((p) => files.has(p));
32
+ if (dir === ".")
33
+ return undefined;
34
+ }
35
+ }
36
+ /**
37
+ * `source` is a whole `use` statement, or the name of a `mod foo;`. `mod foo;` resolves next to the declaring file (Rust 2018 layout:
38
+ * inside `src/a.rs` it is `src/a/foo.rs` or `src/a/foo/mod.rs`). `use` paths starting `crate`,
39
+ * `self` or `super` walk module files as far as they exist; trailing item names are ignored, and a
40
+ * `{a, b}` list resolves those that are modules. External crates and file-level-only: `use`
41
+ * and `mod` inside inline modules or functions are not read.
42
+ * shortcut: no `#[path]` attributes and no 2015-style `use a::b` paths, add when a repo needs them.
43
+ */
44
+ function resolveImport(source, fromPath, files) {
45
+ const text = source.trim();
46
+ if (/^\w+$/.test(text))
47
+ return child(fromPath, text, files); // `mod foo;` (the name only)
48
+ const use = /^(?:pub(?:\([^)]*\))?\s+)?use\s+(?:::)?([\w:]+?)(?:::\s*(\{[^}]*\}|\*)|\s+as\s|\s*;|\s*$)/.exec(text);
49
+ const [first, ...rest] = (use?.[1] ?? "").split("::");
50
+ if (!first || !["crate", "self", "super"].includes(first))
51
+ return undefined;
52
+ const start = first === "crate" ? crateRoot(fromPath, files) : fromPath;
53
+ // `super` is walked as a segment (each one steps up a module); `crate` and `self` only pick the start.
54
+ return start
55
+ ? walk(start, first === "super" ? [first, ...rest] : rest, use?.[2], fromPath, files)
56
+ : undefined;
57
+ }
58
+ function walk(start, segments, list, fromPath, files) {
59
+ let current = start;
60
+ for (const segment of segments) {
61
+ if (segment === "super") {
62
+ const up = parent(current, files);
63
+ if (!up)
64
+ return undefined;
65
+ current = up;
66
+ continue;
67
+ }
68
+ const next = child(current, segment, files);
69
+ if (!next)
70
+ break;
71
+ current = next;
72
+ }
73
+ const members = (list?.match(/\b\w+/g) ?? [])
74
+ .map((name) => child(current, name, files))
75
+ .filter((p) => !!p);
76
+ const targets = members.length ? members : [current];
77
+ const result = targets.filter((p) => p !== fromPath);
78
+ return result.length ? result : undefined;
79
+ }
80
+ export const rustAdapter = {
81
+ grammar: { builtin: "rust" },
82
+ queries: "rust",
83
+ declaration,
84
+ resolveImport,
85
+ };
@@ -0,0 +1,2 @@
1
+ import type { LanguageAdapter } from "./types.js";
2
+ export declare const swiftAdapter: LanguageAdapter;
@@ -0,0 +1,38 @@
1
+ const KEYWORDS = new Set(["class", "struct", "enum", "actor", "extension"]);
2
+ const access = (node) => node.children
3
+ .find((c) => c.type === "modifiers")
4
+ ?.children.find((c) => c.type === "visibility_modifier")?.text;
5
+ /**
6
+ * Exported = `public` or `open`. Without a modifier, members of a protocol or of an extension
7
+ * take the access of their enclosing declaration; everything else is internal.
8
+ */
9
+ function exported(node) {
10
+ const own = access(node);
11
+ if (own)
12
+ return own === "public" || own === "open";
13
+ const owner = node.parent?.parent;
14
+ return owner?.type === "protocol_declaration" ||
15
+ (owner?.type === "class_declaration" && owner.children.some((c) => c.type === "extension"))
16
+ ? exported(owner)
17
+ : false;
18
+ }
19
+ function declaration(node) {
20
+ const name = node.childForFieldName("name")?.text.replace(/\s+/g, "");
21
+ if (!name)
22
+ return undefined;
23
+ let kind = "function";
24
+ if (node.type === "protocol_declaration")
25
+ kind = "protocol";
26
+ else if (node.type === "class_declaration")
27
+ kind = node.children.find((c) => !c.isNamed && KEYWORDS.has(c.type))?.type ?? "class";
28
+ else if (node.parent?.type.endsWith("_body"))
29
+ kind = "method";
30
+ return { name, kind, exported: exported(node) };
31
+ }
32
+ // Swift resolves files by module, not by path, so there is no resolveImport: imports add no edges.
33
+ // An extension is named after the type it extends, so it merges with that type's symbol in the same file.
34
+ export const swiftAdapter = {
35
+ grammar: { vendored: "swift" },
36
+ queries: "swift",
37
+ declaration,
38
+ };
@@ -0,0 +1,61 @@
1
+ import type { Node } from "web-tree-sitter";
2
+ /** Where a language's tree-sitter grammar (a wasm file) comes from. */
3
+ export type GrammarSource =
4
+ /** `@vscode/tree-sitter-wasm/wasm/tree-sitter-<name>.wasm`. */
5
+ {
6
+ builtin: string;
7
+ }
8
+ /** `grammars/manifest.json` entry for this language; the file's sha256 is verified before loading. */
9
+ | {
10
+ vendored: string;
11
+ };
12
+ /** A same-file name use found by an adapter heuristic; resolved to an inferred edge after parsing. */
13
+ export interface Use {
14
+ name: string;
15
+ type: string;
16
+ line: number;
17
+ }
18
+ /** Where the walk is when it hands a node to an adapter heuristic. */
19
+ export interface WalkContext {
20
+ /** Graph key of the enclosing file. */
21
+ file: string;
22
+ /** Graph key of the nearest enclosing symbol, or `file` at top level. */
23
+ parent: string;
24
+ /** Qualified names of the enclosing symbols. */
25
+ scope: string[];
26
+ }
27
+ /**
28
+ * Everything the extractor needs for one language. Queries live in `queries/<dir>/`:
29
+ * - symbols: captures `@symbol` (kind = node type), `@function` (kind "function") or `@type` (kind "type") on declarations.
30
+ * - imports: each pattern captures `@import` (the statement) and `@source` (the module specifier
31
+ * text) or `@source.string` (a quoted string literal; the quotes are stripped).
32
+ */
33
+ export interface LanguageAdapter {
34
+ grammar: GrammarSource;
35
+ /** Directory under `queries/` holding `symbols.scm` and `imports.scm`. */
36
+ queries: string;
37
+ /**
38
+ * Maps an import specifier to a file in the snapshot, or undefined when it is not a file of this
39
+ * repository (package, alias) or is ambiguous; an array gives one edge per file (a Go package,
40
+ * a C# namespace). `read` returns the text of a snapshot file or of a manifest such as `go.mod`.
41
+ * Without it, imports produce no edges.
42
+ */
43
+ resolveImport?: (source: string, fromPath: string, files: ReadonlySet<string>,
44
+ /** Text of another loaded file of the snapshot (project files, manifests such as go.mod). */
45
+ read: (path: string) => string | undefined) => string | string[] | undefined;
46
+ /**
47
+ * Names a captured declaration when the node has no `name` field (a decorated definition) and/or
48
+ * overrides its kind and exported flag (default: node type, and "inside an export statement").
49
+ */
50
+ declaration?: (node: Node) => {
51
+ name: string;
52
+ kind?: string;
53
+ exported?: boolean;
54
+ } | undefined;
55
+ /** Symbol name when the declaration has no `name` field (e.g. `f = function() end`). */
56
+ symbolName?: (node: Node) => string | undefined;
57
+ /** True when the language's own export rule (not an `export` statement) exposes this declaration. */
58
+ isExported?: (node: Node, name: string) => boolean;
59
+ /** Extra per-node heuristics (calls, references, implements, ...); the result becomes inferred edges. */
60
+ uses?: (node: Node, context: WalkContext) => Use[];
61
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,2 @@
1
+ import type { LanguageAdapter } from "./types.js";
2
+ export declare const typescriptAdapters: Record<string, LanguageAdapter>;
@@ -0,0 +1,52 @@
1
+ import { posix } from "node:path";
2
+ /** Relative imports only; `./x.js` may mean `./x.ts`. Unique match among the snapshot's files wins. */
3
+ function resolveImport(source, fromPath, files) {
4
+ if (!source.startsWith("."))
5
+ return undefined;
6
+ const target = posix.normalize(posix.join(posix.dirname(fromPath), source));
7
+ const candidates = [
8
+ target,
9
+ ...[".ts", ".tsx", ".js", ".jsx", "/index.ts", "/index.tsx", "/index.js", "/index.jsx"].map((ext) => target + ext),
10
+ ...(/\.js$/.test(target)
11
+ ? [target.replace(/\.js$/, ".ts"), target.replace(/\.js$/, ".tsx")]
12
+ : []),
13
+ ].filter((p) => files.has(p));
14
+ return new Set(candidates).size === 1 ? candidates[0] : undefined;
15
+ }
16
+ /** Same-file name heuristics: calls of plain identifiers, type references, implements clauses. */
17
+ function uses(node, { file, parent }) {
18
+ if (parent === file)
19
+ return [];
20
+ const line = node.startPosition.row + 1;
21
+ const found = [];
22
+ if (node.type === "call_expression") {
23
+ const target = node.childForFieldName("function");
24
+ if (target?.type === "identifier")
25
+ found.push({ name: target.text, type: "calls", line });
26
+ }
27
+ if (node.type === "type_identifier" && node.parent?.childForFieldName("name")?.id !== node.id)
28
+ found.push({ name: node.text, type: "references", line });
29
+ if (node.type === "implements_clause")
30
+ for (const target of node.namedChildren)
31
+ if (target.type === "type_identifier")
32
+ found.push({ name: target.text, type: "implements", line });
33
+ return found;
34
+ }
35
+ const typescript = (name) => ({
36
+ grammar: { builtin: name },
37
+ queries: "typescript",
38
+ resolveImport,
39
+ uses,
40
+ });
41
+ const javascript = {
42
+ grammar: { builtin: "javascript" },
43
+ queries: "javascript",
44
+ resolveImport,
45
+ uses,
46
+ };
47
+ export const typescriptAdapters = {
48
+ typescript: typescript("typescript"),
49
+ tsx: typescript("tsx"),
50
+ javascript,
51
+ jsx: javascript,
52
+ };
package/dist/api.d.ts ADDED
@@ -0,0 +1,50 @@
1
+ import type { Contribution, Receipt, Result, Snapshot } from "./model.js";
2
+ export declare class GraphHttpError extends Error {
3
+ readonly status: number;
4
+ constructor(status: number);
5
+ }
6
+ export declare class GraphToolError extends Error {
7
+ readonly tool: string;
8
+ readonly code: string;
9
+ constructor(tool: string, code: string);
10
+ }
11
+ export declare class ContextApi {
12
+ private readonly project;
13
+ private readonly token;
14
+ private readonly base;
15
+ private readonly mcp;
16
+ constructor(server: string, project: string, token: string);
17
+ private request;
18
+ /**
19
+ * Writes go through the MCP submit_contribution tool: the CDN firewall in front of the hosted
20
+ * service blocks code-sync payloads on the REST contribution route (Cloudflare 403 "Blocked").
21
+ */
22
+ private callTool;
23
+ /** True when the server has recorded this contribution (it was applied or deliberately returned). */
24
+ contributionRecorded(id: string): Promise<boolean>;
25
+ query(filters: Record<string, string>): Promise<Result>;
26
+ all(filters: Record<string, string>): Promise<Result>;
27
+ submit(body: Contribution): Promise<Receipt>;
28
+ nodeEdges(id: string): Promise<Result["edges"]>;
29
+ allEdges(namespace: string): Promise<Result["edges"]>;
30
+ }
31
+ /**
32
+ * Each contribution is one SERIALIZABLE transaction with pairwise similarity() queries, so cost
33
+ * grows roughly quadratically with batch size; 50 stays under the 5 s statement timeout (#43).
34
+ */
35
+ export declare const BATCH_ITEMS = 50;
36
+ export declare function chunks<T>(items: T[], make: (items: T[]) => Contribution): T[][];
37
+ /**
38
+ * Submits one batch. On a server error or statement timeout the batch is retried once as two
39
+ * halves, but only after the server confirms it never recorded the original contribution. A
40
+ * failure of either half propagates and stops the run. Returns one receipt per submitted piece.
41
+ */
42
+ export declare function submitBatch<T>(api: ContextApi, group: T[], make: (items: T[]) => Contribution): Promise<{
43
+ items: T[];
44
+ receipt: Receipt;
45
+ }[]>;
46
+ /** Server state is authoritative; local state is never used to skip reconciliation. */
47
+ export declare function reconcile(api: ContextApi, snapshot: Snapshot, namespace: string, supersede?: boolean): Promise<{
48
+ contributions: number;
49
+ digest: string;
50
+ }>;