@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,36 @@
1
+ import type { Snapshot } from "./model.js";
2
+ export declare function repository(root: string): {
3
+ repo: string;
4
+ commit: string;
5
+ namespace: string;
6
+ };
7
+ /** A parser for files with this extension (unknown extensions use the JavaScript grammar). */
8
+ export declare function parserFor(extension: string): Promise<import("web-tree-sitter").Parser>;
9
+ /** `.cboard.json` `code` block: globs relative to the repository root. */
10
+ export interface CodeConfig {
11
+ include?: string[];
12
+ exclude?: string[];
13
+ maxFileBytes?: number;
14
+ }
15
+ export declare const SKIP_REASONS: readonly ["unknown-language", "binary", "minified", "generated", "vendored", "too-large", "excluded-dir", "excluded-glob"];
16
+ export type SkipReason = (typeof SKIP_REASONS)[number];
17
+ export interface Summary {
18
+ files: Record<string, number>;
19
+ symbols: number;
20
+ edges: number;
21
+ skipped: Record<SkipReason, number>;
22
+ parseErrors: string[];
23
+ /** The working tree had uncommitted changes; they were not synced (HEAD was read). */
24
+ dirty: boolean;
25
+ }
26
+ export declare const DEFAULT_MAX_FILE_BYTES = 1000000;
27
+ /** The optional `code` block of the repository's `.cboard.json`; malformed values are ignored. */
28
+ export declare function codeConfig(root: string): CodeConfig;
29
+ /**
30
+ * Reads the committed HEAD tree of the whole repository (or `roots`). A dirty working tree is
31
+ * not an error: HEAD is read and `summary.dirty` says so. Language adapters other than TS/JS
32
+ * are out of scope here: other languages get file nodes only.
33
+ */
34
+ export declare function extract(root: string, roots?: string[], options?: CodeConfig): Promise<Snapshot & ReturnType<typeof repository> & {
35
+ summary: Summary;
36
+ }>;
@@ -0,0 +1,458 @@
1
+ import { execFileSync } from "node:child_process";
2
+ import { createHash } from "node:crypto";
3
+ import { readFileSync } from "node:fs";
4
+ import { posix, resolve } from "node:path";
5
+ import { adapterFor, openAdapter } from "./adapters/index.js";
6
+ import { globMatcher, languageOf } from "./languages.js";
7
+ const git = (root, args) => execFileSync("git", args, { cwd: root, encoding: "utf8" }).trim();
8
+ export function repository(root) {
9
+ root = resolve(root);
10
+ const commit = git(root, ["rev-parse", "HEAD"]);
11
+ if (!/^[a-f0-9]{40}$/.test(commit))
12
+ throw new Error("Invalid repository commit");
13
+ let repo;
14
+ try {
15
+ repo = git(root, ["remote", "get-url", "origin"]);
16
+ }
17
+ catch {
18
+ repo = "";
19
+ }
20
+ // Strip credentials before persisting identities or provenance.
21
+ if (repo.includes("://")) {
22
+ const url = new URL(repo);
23
+ url.username = "";
24
+ url.password = "";
25
+ url.search = "";
26
+ url.hash = "";
27
+ repo = url.toString();
28
+ }
29
+ repo ||= `local:${git(root, ["rev-parse", "--path-format=absolute", "--git-common-dir"]).replace(/\\/g, "/")}`;
30
+ const namespace = `code:${createHash("sha256").update(repo).digest("hex").slice(0, 32)}`;
31
+ return { repo, commit, namespace };
32
+ }
33
+ /** A parser for files with this extension (unknown extensions use the JavaScript grammar). */
34
+ export async function parserFor(extension) {
35
+ const adapter = adapterFor(languageOf(`x${extension}`) ?? "") ?? adapterFor("javascript");
36
+ if (!adapter)
37
+ throw new Error("No JavaScript adapter");
38
+ return (await openAdapter(adapter)).parser;
39
+ }
40
+ function sourceSnippet(text) {
41
+ if (Buffer.byteLength(text) <= 7800)
42
+ return text;
43
+ let bytes = 0, result = "";
44
+ for (const character of text) {
45
+ const size = Buffer.byteLength(character);
46
+ if (bytes + size > 7800)
47
+ break;
48
+ bytes += size;
49
+ result += character;
50
+ }
51
+ return result;
52
+ }
53
+ export const SKIP_REASONS = [
54
+ "unknown-language",
55
+ "binary",
56
+ "minified",
57
+ "generated",
58
+ "vendored",
59
+ "too-large",
60
+ "excluded-dir",
61
+ "excluded-glob",
62
+ ];
63
+ export const DEFAULT_MAX_FILE_BYTES = 1_000_000;
64
+ const EXCLUDED_DIRS = new Set([
65
+ "node_modules",
66
+ ".git",
67
+ ".claude",
68
+ "vendor",
69
+ "dist",
70
+ "build",
71
+ "target",
72
+ "coverage",
73
+ ".next",
74
+ ".venv",
75
+ "venv",
76
+ "__pycache__",
77
+ "bin",
78
+ "obj",
79
+ "generated",
80
+ ]);
81
+ const MAX_LINE_CHARS = 10_000;
82
+ /** The optional `code` block of the repository's `.cboard.json`; malformed values are ignored. */
83
+ export function codeConfig(root) {
84
+ let parsed;
85
+ try {
86
+ parsed = JSON.parse(readFileSync(resolve(root, ".cboard.json"), "utf8"));
87
+ }
88
+ catch {
89
+ return {};
90
+ }
91
+ const found = parsed?.code;
92
+ if (typeof found !== "object" || !found)
93
+ return {};
94
+ const code = found;
95
+ const globs = (value) => Array.isArray(value) ? value.filter((v) => typeof v === "string") : undefined;
96
+ const config = {};
97
+ const include = globs(code.include), exclude = globs(code.exclude);
98
+ if (include)
99
+ config.include = include;
100
+ if (exclude)
101
+ config.exclude = exclude;
102
+ if (typeof code.maxFileBytes === "number" && code.maxFileBytes > 0)
103
+ config.maxFileBytes = code.maxFileBytes;
104
+ return config;
105
+ }
106
+ /**
107
+ * `.gitattributes` at the repository root only (no nested files, macro attributes or quoted
108
+ * patterns). Supports `linguist-generated` and `linguist-vendored` set, `=true`, unset (`-attr`,
109
+ * `!attr`) or `=false`; the last matching line wins. Patterns use the tiny glob in languages.ts.
110
+ */
111
+ function attributeRules(text) {
112
+ const rules = [];
113
+ for (const line of text.split(/\r?\n/)) {
114
+ const [pattern, ...attrs] = line.trim().split(/\s+/);
115
+ if (pattern && !pattern.startsWith("#"))
116
+ rules.push({ match: globMatcher(pattern), attrs });
117
+ }
118
+ return (path, attr) => {
119
+ let value = false;
120
+ for (const rule of rules)
121
+ if (rule.match(path))
122
+ for (const a of rule.attrs) {
123
+ if (a === attr || a === `${attr}=true`)
124
+ value = true;
125
+ else if (a === `-${attr}` || a === `!${attr}` || a === `${attr}=false`)
126
+ value = false;
127
+ }
128
+ return value;
129
+ };
130
+ }
131
+ /** Reads blobs in one `git cat-file --batch` process; returns contents in request order. */
132
+ function readBlobs(root, shas) {
133
+ if (!shas.length)
134
+ return [];
135
+ const out = execFileSync("git", ["cat-file", "--batch"], {
136
+ cwd: root,
137
+ input: shas.join("\n") + "\n",
138
+ maxBuffer: Infinity,
139
+ });
140
+ const blobs = [];
141
+ let offset = 0;
142
+ for (const sha of shas) {
143
+ const end = out.indexOf(10, offset);
144
+ const [, type, size] = out.subarray(offset, end).toString("latin1").split(" ");
145
+ if (type !== "blob" || size === undefined)
146
+ throw new Error(`Cannot read blob ${sha}`);
147
+ blobs.push(out.subarray(end + 1, end + 1 + Number(size)));
148
+ offset = end + 1 + Number(size) + 1;
149
+ }
150
+ return blobs;
151
+ }
152
+ /**
153
+ * Reads the committed HEAD tree of the whole repository (or `roots`). A dirty working tree is
154
+ * not an error: HEAD is read and `summary.dirty` says so. Language adapters other than TS/JS
155
+ * are out of scope here: other languages get file nodes only.
156
+ */
157
+ export async function extract(root, roots = [], options = {}) {
158
+ root = resolve(root);
159
+ const identity = repository(root);
160
+ const { repo, commit, namespace } = identity;
161
+ const nodes = [], edges = [];
162
+ const nodeByKey = new Map();
163
+ const dirty = git(root, [
164
+ "status",
165
+ "--porcelain",
166
+ "--untracked-files=all",
167
+ ...(roots.length ? ["--", ...roots] : []),
168
+ ]) !== "";
169
+ const summary = {
170
+ files: {},
171
+ symbols: 0,
172
+ edges: 0,
173
+ skipped: Object.fromEntries(SKIP_REASONS.map((r) => [r, 0])),
174
+ parseErrors: [],
175
+ dirty,
176
+ };
177
+ const key = (path, symbol = "") => `${namespace}:${path}${symbol ? `#${symbol}` : ""}`;
178
+ const provenance = (path, startLine = 1, endLine = startLine) => [
179
+ { kind: "repo", repo, commit, path, startLine, endLine },
180
+ ];
181
+ const add = (path, type, title, start = 1, end = start, symbol = "", properties = {}) => {
182
+ const clientKey = key(path, symbol);
183
+ // Qualified paths plus a stable suffix distinguish punctuation-normalized paths
184
+ // and identical layouts in different repository roots.
185
+ title = `${title} [${createHash("sha256").update(clientKey).digest("hex").slice(0, 16)}]`;
186
+ if (clientKey.length > 1024 || title.length > 300)
187
+ throw new Error(`Repository identity exceeds graph limits: ${path}`);
188
+ const created = {
189
+ clientKey,
190
+ namespace,
191
+ type,
192
+ title,
193
+ body: "",
194
+ properties,
195
+ provenance: provenance(path, start, end),
196
+ derivation: "extracted",
197
+ };
198
+ nodes.push(created);
199
+ if (!nodeByKey.has(clientKey))
200
+ nodeByKey.set(clientKey, created);
201
+ return clientKey;
202
+ };
203
+ const edge = (type, from, to, path, line = 1) => edges.push({
204
+ type,
205
+ from,
206
+ to,
207
+ provenance: provenance(path, line),
208
+ derivation: "extracted",
209
+ properties: {},
210
+ });
211
+ const repoKey = add(".", "repository", `Repository ${repo}`);
212
+ const files = [];
213
+ const directories = new Map([[".", repoKey]]);
214
+ const ensureDir = (path) => {
215
+ const old = directories.get(path);
216
+ if (old)
217
+ return old;
218
+ const parent = ensureDir(posix.dirname(path));
219
+ const id = add(path, "module", `Module ${path}`);
220
+ directories.set(path, id);
221
+ edge("contains", parent, id, path);
222
+ return id;
223
+ };
224
+ for (const rootPath of roots)
225
+ if (posix.isAbsolute(rootPath) || rootPath.split(/[\\/]/).includes(".."))
226
+ throw new Error("Scan roots must be repository relative");
227
+ // `-l` gives each blob's size so oversized files are skipped without reading them.
228
+ const tracked = execFileSync("git", ["ls-tree", "-r", "-l", "-z", identity.commit, ...(roots.length ? ["--", ...roots] : [])], { cwd: root, encoding: "utf8", maxBuffer: Infinity })
229
+ .split("\0")
230
+ .filter(Boolean)
231
+ .flatMap((entry) => {
232
+ const tab = entry.indexOf("\t");
233
+ const [mode, type, sha, size] = entry.slice(0, tab).split(/\s+/);
234
+ // Skip submodules (commit entries) and symlinks.
235
+ return type === "blob" && mode !== "120000" && sha
236
+ ? [{ path: entry.slice(tab + 1), sha, size: Number(size) }]
237
+ : [];
238
+ });
239
+ let attribute = () => false;
240
+ const attributes = tracked.find((entry) => entry.path === ".gitattributes");
241
+ if (attributes)
242
+ attribute = attributeRules(readBlobs(root, [attributes.sha])[0]?.toString("utf8") ?? "");
243
+ const maxBytes = options.maxFileBytes ?? DEFAULT_MAX_FILE_BYTES;
244
+ const includes = (options.include ?? []).map(globMatcher);
245
+ const excludes = (options.exclude ?? []).map(globMatcher);
246
+ const skip = (reason) => {
247
+ summary.skipped[reason]++;
248
+ };
249
+ const candidates = [];
250
+ for (const entry of tracked) {
251
+ const { path } = entry;
252
+ if (path
253
+ .split("/")
254
+ .slice(0, -1)
255
+ .some((part) => EXCLUDED_DIRS.has(part)))
256
+ skip("excluded-dir");
257
+ else if ((includes.length && !includes.some((m) => m(path))) || excludes.some((m) => m(path)))
258
+ skip("excluded-glob");
259
+ else if (/\.d\.[cm]?ts$|\.generated\.|\.g\.dart$/.test(path) ||
260
+ attribute(path, "linguist-generated"))
261
+ skip("generated");
262
+ else if (attribute(path, "linguist-vendored"))
263
+ skip("vendored");
264
+ else if (/\.min\./.test(posix.basename(path)))
265
+ skip("minified");
266
+ else if (entry.size > maxBytes)
267
+ skip("too-large");
268
+ else
269
+ candidates.push(entry);
270
+ }
271
+ const contents = readBlobs(root, candidates.map((c) => c.sha));
272
+ const manifests = new Map(); // go.mod: no language, but import resolution reads it
273
+ const decoder = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true });
274
+ const loaded = new Map();
275
+ candidates.forEach(({ path }, index) => {
276
+ const buffer = contents[index] ?? Buffer.alloc(0);
277
+ let text;
278
+ try {
279
+ if (buffer.includes(0))
280
+ throw new Error("NUL");
281
+ text = decoder.decode(buffer);
282
+ }
283
+ catch {
284
+ skip("binary");
285
+ return;
286
+ }
287
+ if (posix.basename(path) === "go.mod")
288
+ manifests.set(path, text);
289
+ const language = languageOf(path, text.slice(0, 200));
290
+ if (!language) {
291
+ skip("unknown-language");
292
+ return;
293
+ }
294
+ if (text.split("\n").some((line) => line.length > MAX_LINE_CHARS)) {
295
+ skip("minified");
296
+ return;
297
+ }
298
+ files.push(path);
299
+ loaded.set(path, {
300
+ text,
301
+ bytes: buffer.length,
302
+ sha256: createHash("sha256").update(buffer).digest("hex"),
303
+ language,
304
+ });
305
+ });
306
+ const imports = [];
307
+ const uses = [];
308
+ const symbols = new Map();
309
+ for (const path of files) {
310
+ const info = loaded.get(path);
311
+ if (!info)
312
+ continue;
313
+ const { text, bytes, sha256, language } = info;
314
+ summary.files[language] = (summary.files[language] ?? 0) + 1;
315
+ const fileProperties = {
316
+ language,
317
+ sha256,
318
+ bytes,
319
+ lines: text === "" ? 0 : text.split("\n").length - (text.endsWith("\n") ? 1 : 0),
320
+ };
321
+ const file = add(path, "file", `File ${path}`, 1, text.split("\n").length, "", fileProperties);
322
+ edge("contains", ensureDir(posix.dirname(path)), file, path);
323
+ if (posix.basename(path) === "package.json") {
324
+ let manifest;
325
+ try {
326
+ manifest = JSON.parse(text);
327
+ }
328
+ catch {
329
+ // Same policy as syntax errors below: keep the file node, flag it, carry on.
330
+ fileProperties.parseError = true;
331
+ summary.parseErrors.push(path);
332
+ continue;
333
+ }
334
+ const config = add(path, "config", `Package configuration ${path}`, 1, text.split("\n").length, "manifest", { manifest });
335
+ edge("contains", file, config, path);
336
+ for (const section of [
337
+ "dependencies",
338
+ "devDependencies",
339
+ "peerDependencies",
340
+ "optionalDependencies",
341
+ ]) {
342
+ for (const [name, version] of Object.entries((manifest[section] ?? {})).sort()) {
343
+ const dependency = add(path, "dependency", `${path} ${section} ${name}`, 1, 1, `${section}:${name}`, { name, version, section });
344
+ edge("depends_on", config, dependency, path);
345
+ }
346
+ }
347
+ continue;
348
+ }
349
+ // Languages without an adapter get file nodes only.
350
+ const adapter = adapterFor(language);
351
+ if (!adapter)
352
+ continue;
353
+ const { parser, symbolNodes, importNodes } = await openAdapter(adapter);
354
+ const tree = parser.parse(text);
355
+ if (!tree) {
356
+ parser.delete();
357
+ throw new Error(`Parse failed: ${path}`);
358
+ }
359
+ try {
360
+ // A file with syntax errors keeps its file node, flagged parseError, with no symbols or
361
+ // imports (a partial tree would give misleading declarations); the sync carries on and the
362
+ // summary lists the file.
363
+ if (tree.rootNode.hasError) {
364
+ fileProperties.parseError = true;
365
+ summary.parseErrors.push(path);
366
+ continue;
367
+ }
368
+ const declarations = symbolNodes(tree.rootNode);
369
+ const importStatements = importNodes(tree.rootNode);
370
+ const visit = (node, scope, parent, exported = false) => {
371
+ const isExport = exported || node.type === "export_statement";
372
+ if (declarations.has(node.id)) {
373
+ const custom = adapter.declaration?.(node);
374
+ const name = custom?.name ??
375
+ adapter.symbolName?.(node) ??
376
+ node.childForFieldName("name")?.text ??
377
+ (node.parent?.type === "export_statement" ? "default" : undefined);
378
+ if (name) {
379
+ const qualified = [...scope, name];
380
+ const symbol = qualified.join(".");
381
+ // Overload declarations share an identity; retain one entity with all declaration ranges.
382
+ const old = nodeByKey.get(key(path, symbol));
383
+ if (old) {
384
+ const first = old.provenance[0];
385
+ if (first)
386
+ first.endLine = node.endPosition.row + 1;
387
+ old.properties.sha256 = createHash("sha256")
388
+ .update(String(old.properties.sha256) + node.text)
389
+ .digest("hex");
390
+ old.body = sourceSnippet(old.body + "\n" + node.text);
391
+ old.properties.bodyTruncated = Buffer.byteLength(old.body + "\n" + node.text) > 7800;
392
+ node.namedChildren.forEach((child) => {
393
+ visit(child, qualified, old.clientKey, false);
394
+ });
395
+ return;
396
+ }
397
+ const id = add(path, "symbol", `${path}#${symbol}`, node.startPosition.row + 1, node.endPosition.row + 1, symbol, {
398
+ kind: declarations.get(node.id) ?? custom?.kind ?? node.type,
399
+ exported: custom?.exported ?? (isExport || (adapter.isExported?.(node, name) ?? false)),
400
+ sha256: createHash("sha256").update(node.text).digest("hex"),
401
+ });
402
+ const symbolNode = nodeByKey.get(id);
403
+ if (symbolNode) {
404
+ symbolNode.body = sourceSnippet(node.text);
405
+ symbolNode.properties.bodyTruncated = Buffer.byteLength(node.text) > 7800;
406
+ }
407
+ symbols.set(`${path}#${symbol}`, id);
408
+ edge("contains", parent, id, path, node.startPosition.row + 1);
409
+ node.namedChildren.forEach((child) => {
410
+ visit(child, qualified, id, false);
411
+ });
412
+ return;
413
+ }
414
+ }
415
+ const statement = importStatements.get(node.id);
416
+ if (statement)
417
+ imports.push({ from: file, path, ...statement });
418
+ for (const use of adapter.uses?.(node, { file, parent, scope }) ?? [])
419
+ uses.push({ from: parent, scope, path, ...use });
420
+ node.namedChildren.forEach((child) => {
421
+ visit(child, scope, parent, isExport);
422
+ });
423
+ };
424
+ visit(tree.rootNode, [], file);
425
+ }
426
+ finally {
427
+ tree.delete();
428
+ parser.delete();
429
+ }
430
+ }
431
+ const seenUses = new Set();
432
+ for (const use of uses) {
433
+ let target;
434
+ for (let depth = use.scope.length; depth >= 0 && !target; depth--)
435
+ target = symbols.get(`${use.path}#${[...use.scope.slice(0, depth), use.name].join(".")}`);
436
+ const signature = JSON.stringify([use.type, use.from, target]);
437
+ if (target && target !== use.from && !seenUses.has(signature)) {
438
+ seenUses.add(signature);
439
+ edges.push({
440
+ type: use.type,
441
+ from: use.from,
442
+ to: target,
443
+ provenance: provenance(use.path, use.line),
444
+ derivation: "inferred",
445
+ properties: { resolution: "same-file lexical name heuristic" },
446
+ });
447
+ }
448
+ }
449
+ const fileSet = new Set(files);
450
+ for (const item of imports) {
451
+ const target = adapterFor(loaded.get(item.path)?.language ?? "")?.resolveImport?.(item.source, item.path, fileSet, (path) => loaded.get(path)?.text ?? manifests.get(path));
452
+ for (const to of [target ?? []].flat())
453
+ edge("imports", item.from, key(to), item.path, item.line);
454
+ }
455
+ summary.symbols = nodes.filter((n) => n.type === "symbol").length;
456
+ summary.edges = edges.length;
457
+ return { ...identity, nodes, edges, summary };
458
+ }
@@ -0,0 +1,5 @@
1
+ export * from "./model.js";
2
+ export * from "./extract.js";
3
+ export * from "./api.js";
4
+ export { options } from "./cli.js";
5
+ export * from "./docs-parse.js";
package/dist/index.js ADDED
@@ -0,0 +1,5 @@
1
+ export * from "./model.js";
2
+ export * from "./extract.js";
3
+ export * from "./api.js";
4
+ export { options } from "./cli.js";
5
+ export * from "./docs-parse.js";
@@ -0,0 +1,9 @@
1
+ /** Languages the TS/JS grammar parses for symbols and imports. */
2
+ export declare const parsedLanguages: Set<string>;
3
+ /** Language for a path; `head` (the file's first bytes as text) is used for shebangs of extensionless scripts. */
4
+ export declare function languageOf(path: string, head?: string): string | undefined;
5
+ /**
6
+ * Tiny glob: `**` any depth, `*` within a segment, `?` one character. A pattern without a slash
7
+ * matches the base name at any depth; a trailing slash means a directory prefix.
8
+ */
9
+ export declare function globMatcher(pattern: string): (path: string) => boolean;
@@ -0,0 +1,128 @@
1
+ /** File extension (lower case, with dot) to language name. */
2
+ const byExtension = {
3
+ ".ts": "typescript",
4
+ ".mts": "typescript",
5
+ ".cts": "typescript",
6
+ ".tsx": "tsx",
7
+ ".js": "javascript",
8
+ ".mjs": "javascript",
9
+ ".cjs": "javascript",
10
+ ".jsx": "jsx",
11
+ ".py": "python",
12
+ ".go": "go",
13
+ ".rs": "rust",
14
+ ".java": "java",
15
+ ".kt": "kotlin",
16
+ ".kts": "kotlin",
17
+ ".swift": "swift",
18
+ ".cs": "csharp",
19
+ ".c": "c",
20
+ ".h": "c",
21
+ ".cpp": "cpp",
22
+ ".cc": "cpp",
23
+ ".cxx": "cpp",
24
+ ".hpp": "cpp",
25
+ ".hh": "cpp",
26
+ ".rb": "ruby",
27
+ ".php": "php",
28
+ ".sh": "shell",
29
+ ".bash": "shell",
30
+ ".zsh": "shell",
31
+ ".ps1": "powershell",
32
+ ".lua": "lua",
33
+ ".luau": "luau",
34
+ ".sql": "sql",
35
+ ".html": "html",
36
+ ".htm": "html",
37
+ ".css": "css",
38
+ ".scss": "scss",
39
+ ".json": "json",
40
+ ".jsonc": "json",
41
+ ".yaml": "yaml",
42
+ ".yml": "yaml",
43
+ ".toml": "toml",
44
+ ".md": "markdown",
45
+ ".mdx": "mdx",
46
+ ".xml": "xml",
47
+ ".vue": "vue",
48
+ ".svelte": "svelte",
49
+ ".dart": "dart",
50
+ ".scala": "scala",
51
+ ".ex": "elixir",
52
+ ".exs": "elixir",
53
+ ".erl": "erlang",
54
+ ".hs": "haskell",
55
+ ".ml": "ocaml",
56
+ ".r": "r",
57
+ ".jl": "julia",
58
+ ".zig": "zig",
59
+ ".nim": "nim",
60
+ ".gd": "gdscript",
61
+ ".tf": "terraform",
62
+ };
63
+ const byFilename = { Dockerfile: "dockerfile", Makefile: "make" };
64
+ const byInterpreter = {
65
+ node: "javascript",
66
+ deno: "typescript",
67
+ bash: "shell",
68
+ sh: "shell",
69
+ zsh: "shell",
70
+ python: "python",
71
+ ruby: "ruby",
72
+ php: "php",
73
+ lua: "lua",
74
+ luau: "luau",
75
+ pwsh: "powershell",
76
+ };
77
+ /** Languages the TS/JS grammar parses for symbols and imports. */
78
+ export const parsedLanguages = new Set(["typescript", "tsx", "javascript", "jsx"]);
79
+ /** Language for a path; `head` (the file's first bytes as text) is used for shebangs of extensionless scripts. */
80
+ export function languageOf(path, head = "") {
81
+ const name = path.slice(path.lastIndexOf("/") + 1);
82
+ const dot = name.lastIndexOf(".");
83
+ if (dot > 0)
84
+ return byExtension[name.slice(dot).toLowerCase()];
85
+ if (byFilename[name])
86
+ return byFilename[name];
87
+ if (dot === -1 && head.startsWith("#!")) {
88
+ const words = (head.split(/\r?\n/, 1)[0] ?? "").slice(2).trim().split(/\s+/);
89
+ const program = (words[0] ?? "").split("/").pop();
90
+ const interpreter = program === "env" ? words.find((w, i) => i > 0 && !w.startsWith("-")) : program;
91
+ // python3 and python3.12 map to python
92
+ return interpreter ? byInterpreter[interpreter.replace(/[\d.]+$/, "")] : undefined;
93
+ }
94
+ return undefined;
95
+ }
96
+ /**
97
+ * Tiny glob: `**` any depth, `*` within a segment, `?` one character. A pattern without a slash
98
+ * matches the base name at any depth; a trailing slash means a directory prefix.
99
+ */
100
+ export function globMatcher(pattern) {
101
+ let glob = pattern.replace(/^\.?\//, "");
102
+ const anchored = glob.slice(0, -1).includes("/");
103
+ if (glob.endsWith("/"))
104
+ glob += "**";
105
+ let source = "";
106
+ for (let i = 0; i < glob.length; i++) {
107
+ const c = glob[i] ?? "";
108
+ if (c === "*" && glob[i + 1] === "*") {
109
+ if (glob[i + 2] === "/") {
110
+ source += "(?:.*/)?";
111
+ i += 2;
112
+ }
113
+ else {
114
+ source += ".*";
115
+ i += 1;
116
+ }
117
+ }
118
+ else if (c === "*")
119
+ source += "[^/]*";
120
+ else if (c === "?")
121
+ source += "[^/]";
122
+ else
123
+ source += c.replace(/[.+^${}()|[\]\\]/g, "\\$&");
124
+ }
125
+ const re = new RegExp(`^${source}$`);
126
+ const dirPrefix = pattern.endsWith("/") && !anchored;
127
+ return (path) => re.test(anchored ? path : dirPrefix ? path : (path.split("/").pop() ?? path));
128
+ }