@codyn06/cboard 0.0.1 → 0.2.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.
- package/LICENSE +21 -0
- package/README.md +71 -3
- package/THIRD_PARTY_NOTICES +29 -0
- package/bin/cboard-context.js +15 -0
- package/bin/cboard.js +5 -0
- package/dist/adapters/bash.d.ts +2 -0
- package/dist/adapters/bash.js +14 -0
- package/dist/adapters/c-family.d.ts +2 -0
- package/dist/adapters/c-family.js +81 -0
- package/dist/adapters/csharp.d.ts +2 -0
- package/dist/adapters/csharp.js +47 -0
- package/dist/adapters/extra-languages.d.ts +3 -0
- package/dist/adapters/extra-languages.js +15 -0
- package/dist/adapters/go.d.ts +2 -0
- package/dist/adapters/go.js +42 -0
- package/dist/adapters/grammar.d.ts +21 -0
- package/dist/adapters/grammar.js +54 -0
- package/dist/adapters/index.d.ts +20 -0
- package/dist/adapters/index.js +62 -0
- package/dist/adapters/java.d.ts +2 -0
- package/dist/adapters/java.js +36 -0
- package/dist/adapters/kotlin.d.ts +2 -0
- package/dist/adapters/kotlin.js +65 -0
- package/dist/adapters/lua-family.d.ts +2 -0
- package/dist/adapters/lua-family.js +186 -0
- package/dist/adapters/php.d.ts +2 -0
- package/dist/adapters/php.js +28 -0
- package/dist/adapters/python.d.ts +2 -0
- package/dist/adapters/python.js +68 -0
- package/dist/adapters/ruby.d.ts +2 -0
- package/dist/adapters/ruby.js +46 -0
- package/dist/adapters/rust.d.ts +2 -0
- package/dist/adapters/rust.js +85 -0
- package/dist/adapters/swift.d.ts +2 -0
- package/dist/adapters/swift.js +38 -0
- package/dist/adapters/types.d.ts +61 -0
- package/dist/adapters/types.js +1 -0
- package/dist/adapters/typescript.d.ts +2 -0
- package/dist/adapters/typescript.js +52 -0
- package/dist/api.d.ts +56 -0
- package/dist/api.js +439 -0
- package/dist/cboard.d.ts +2 -0
- package/dist/cboard.js +151 -0
- package/dist/cli.d.ts +27 -0
- package/dist/cli.js +180 -0
- package/dist/docs-parse.d.ts +64 -0
- package/dist/docs-parse.js +762 -0
- package/dist/docs.d.ts +39 -0
- package/dist/docs.js +243 -0
- package/dist/extract.d.ts +36 -0
- package/dist/extract.js +480 -0
- package/dist/index.d.ts +5 -0
- package/dist/index.js +5 -0
- package/dist/issues.d.ts +44 -0
- package/dist/issues.js +138 -0
- package/dist/languages.d.ts +9 -0
- package/dist/languages.js +128 -0
- package/dist/model.d.ts +85 -0
- package/dist/model.js +1 -0
- package/dist/wake.d.ts +13 -0
- package/dist/wake.js +33 -0
- package/grammars/LICENSES/README.md +3 -0
- package/grammars/LICENSES/c.LICENSE +21 -0
- package/grammars/LICENSES/kotlin.LICENSE +21 -0
- package/grammars/LICENSES/lua.LICENSE +21 -0
- package/grammars/LICENSES/luau.LICENSE +21 -0
- package/grammars/LICENSES/swift.LICENSE +21 -0
- package/grammars/manifest.json +39 -0
- package/grammars/tree-sitter-c.wasm +0 -0
- package/grammars/tree-sitter-kotlin.wasm +0 -0
- package/grammars/tree-sitter-lua.wasm +0 -0
- package/grammars/tree-sitter-luau.wasm +0 -0
- package/grammars/tree-sitter-swift.wasm +0 -0
- package/kit/cboard-connect.js +869 -0
- package/kit/cboard-kit/brief.js +512 -0
- package/kit/cboard-kit/config.js +250 -0
- package/kit/cboard-kit/connect-check.js +95 -0
- package/kit/cboard-kit/device.js +192 -0
- package/kit/cboard-kit/drift.js +55 -0
- package/kit/cboard-kit/headers.js +46 -0
- package/kit/cboard-kit/mcp.js +97 -0
- package/kit/cboard-kit/references.js +70 -0
- package/kit/cboard-kit/skill/SKILL.md +170 -0
- package/kit/cboard-kit/wait.js +45 -0
- package/package.json +47 -5
- package/queries/bash/imports.scm +11 -0
- package/queries/bash/symbols.scm +1 -0
- package/queries/c/imports.scm +2 -0
- package/queries/c/symbols.scm +10 -0
- package/queries/cpp/imports.scm +2 -0
- package/queries/cpp/symbols.scm +11 -0
- package/queries/csharp/imports.scm +2 -0
- package/queries/csharp/symbols.scm +10 -0
- package/queries/go/imports.scm +2 -0
- package/queries/go/symbols.scm +8 -0
- package/queries/java/imports.scm +2 -0
- package/queries/java/symbols.scm +9 -0
- package/queries/javascript/imports.scm +3 -0
- package/queries/javascript/symbols.scm +16 -0
- package/queries/kotlin/imports.scm +2 -0
- package/queries/kotlin/symbols.scm +4 -0
- package/queries/lua/imports.scm +5 -0
- package/queries/lua/symbols.scm +6 -0
- package/queries/luau/imports.scm +5 -0
- package/queries/luau/symbols.scm +9 -0
- package/queries/php/imports.scm +6 -0
- package/queries/php/symbols.scm +7 -0
- package/queries/python/imports.scm +3 -0
- package/queries/python/symbols.scm +8 -0
- package/queries/ruby/imports.scm +2 -0
- package/queries/ruby/symbols.scm +4 -0
- package/queries/rust/imports.scm +5 -0
- package/queries/rust/symbols.scm +11 -0
- package/queries/swift/imports.scm +2 -0
- package/queries/swift/symbols.scm +5 -0
- package/queries/typescript/imports.scm +3 -0
- package/queries/typescript/symbols.scm +20 -0
package/dist/extract.js
ADDED
|
@@ -0,0 +1,480 @@
|
|
|
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
|
+
let warnedLocal = false;
|
|
9
|
+
/** Stable identity that `connect` stores in `.cboard.json` (the root commit hash). */
|
|
10
|
+
function configuredRepoId(root) {
|
|
11
|
+
try {
|
|
12
|
+
const id = JSON.parse(readFileSync(resolve(root, ".cboard.json"), "utf8")).repoId;
|
|
13
|
+
return typeof id === "string" ? id : "";
|
|
14
|
+
}
|
|
15
|
+
catch {
|
|
16
|
+
return "";
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
export function repository(root) {
|
|
20
|
+
root = resolve(root);
|
|
21
|
+
const commit = git(root, ["rev-parse", "HEAD"]);
|
|
22
|
+
if (!/^[a-f0-9]{40}$/.test(commit))
|
|
23
|
+
throw new Error("Invalid repository commit");
|
|
24
|
+
let repo;
|
|
25
|
+
try {
|
|
26
|
+
repo = git(root, ["remote", "get-url", "origin"]);
|
|
27
|
+
}
|
|
28
|
+
catch {
|
|
29
|
+
repo = "";
|
|
30
|
+
}
|
|
31
|
+
// Strip credentials before persisting identities or provenance.
|
|
32
|
+
if (repo.includes("://")) {
|
|
33
|
+
const url = new URL(repo);
|
|
34
|
+
url.username = "";
|
|
35
|
+
url.password = "";
|
|
36
|
+
url.search = "";
|
|
37
|
+
url.hash = "";
|
|
38
|
+
repo = url.toString();
|
|
39
|
+
}
|
|
40
|
+
if (!repo) {
|
|
41
|
+
const repoId = configuredRepoId(root);
|
|
42
|
+
if (repoId)
|
|
43
|
+
repo = `local:${repoId}`;
|
|
44
|
+
else {
|
|
45
|
+
repo = `local:${git(root, ["rev-parse", "--path-format=absolute", "--git-common-dir"]).replace(/\\/g, "/")}`;
|
|
46
|
+
if (!warnedLocal) {
|
|
47
|
+
warnedLocal = true;
|
|
48
|
+
console.error("cboard: no origin remote and no repoId in .cboard.json; this clone gets its own namespace. Run `cboard connect` to store a stable repoId.");
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
const namespace = `code:${createHash("sha256").update(repo).digest("hex").slice(0, 32)}`;
|
|
53
|
+
return { repo, commit, namespace };
|
|
54
|
+
}
|
|
55
|
+
/** A parser for files with this extension (unknown extensions use the JavaScript grammar). */
|
|
56
|
+
export async function parserFor(extension) {
|
|
57
|
+
const adapter = adapterFor(languageOf(`x${extension}`) ?? "") ?? adapterFor("javascript");
|
|
58
|
+
if (!adapter)
|
|
59
|
+
throw new Error("No JavaScript adapter");
|
|
60
|
+
return (await openAdapter(adapter)).parser;
|
|
61
|
+
}
|
|
62
|
+
function sourceSnippet(text) {
|
|
63
|
+
if (Buffer.byteLength(text) <= 7800)
|
|
64
|
+
return text;
|
|
65
|
+
let bytes = 0, result = "";
|
|
66
|
+
for (const character of text) {
|
|
67
|
+
const size = Buffer.byteLength(character);
|
|
68
|
+
if (bytes + size > 7800)
|
|
69
|
+
break;
|
|
70
|
+
bytes += size;
|
|
71
|
+
result += character;
|
|
72
|
+
}
|
|
73
|
+
return result;
|
|
74
|
+
}
|
|
75
|
+
export const SKIP_REASONS = [
|
|
76
|
+
"unknown-language",
|
|
77
|
+
"binary",
|
|
78
|
+
"minified",
|
|
79
|
+
"generated",
|
|
80
|
+
"vendored",
|
|
81
|
+
"too-large",
|
|
82
|
+
"excluded-dir",
|
|
83
|
+
"excluded-glob",
|
|
84
|
+
];
|
|
85
|
+
export const DEFAULT_MAX_FILE_BYTES = 1_000_000;
|
|
86
|
+
const EXCLUDED_DIRS = new Set([
|
|
87
|
+
"node_modules",
|
|
88
|
+
".git",
|
|
89
|
+
".claude",
|
|
90
|
+
"vendor",
|
|
91
|
+
"dist",
|
|
92
|
+
"build",
|
|
93
|
+
"target",
|
|
94
|
+
"coverage",
|
|
95
|
+
".next",
|
|
96
|
+
".venv",
|
|
97
|
+
"venv",
|
|
98
|
+
"__pycache__",
|
|
99
|
+
"bin",
|
|
100
|
+
"obj",
|
|
101
|
+
"generated",
|
|
102
|
+
]);
|
|
103
|
+
const MAX_LINE_CHARS = 10_000;
|
|
104
|
+
/** The optional `code` block of the repository's `.cboard.json`; malformed values are ignored. */
|
|
105
|
+
export function codeConfig(root) {
|
|
106
|
+
let parsed;
|
|
107
|
+
try {
|
|
108
|
+
parsed = JSON.parse(readFileSync(resolve(root, ".cboard.json"), "utf8"));
|
|
109
|
+
}
|
|
110
|
+
catch {
|
|
111
|
+
return {};
|
|
112
|
+
}
|
|
113
|
+
const found = parsed?.code;
|
|
114
|
+
if (typeof found !== "object" || !found)
|
|
115
|
+
return {};
|
|
116
|
+
const code = found;
|
|
117
|
+
const globs = (value) => Array.isArray(value) ? value.filter((v) => typeof v === "string") : undefined;
|
|
118
|
+
const config = {};
|
|
119
|
+
const include = globs(code.include), exclude = globs(code.exclude);
|
|
120
|
+
if (include)
|
|
121
|
+
config.include = include;
|
|
122
|
+
if (exclude)
|
|
123
|
+
config.exclude = exclude;
|
|
124
|
+
if (typeof code.maxFileBytes === "number" && code.maxFileBytes > 0)
|
|
125
|
+
config.maxFileBytes = code.maxFileBytes;
|
|
126
|
+
return config;
|
|
127
|
+
}
|
|
128
|
+
/**
|
|
129
|
+
* `.gitattributes` at the repository root only (no nested files, macro attributes or quoted
|
|
130
|
+
* patterns). Supports `linguist-generated` and `linguist-vendored` set, `=true`, unset (`-attr`,
|
|
131
|
+
* `!attr`) or `=false`; the last matching line wins. Patterns use the tiny glob in languages.ts.
|
|
132
|
+
*/
|
|
133
|
+
function attributeRules(text) {
|
|
134
|
+
const rules = [];
|
|
135
|
+
for (const line of text.split(/\r?\n/)) {
|
|
136
|
+
const [pattern, ...attrs] = line.trim().split(/\s+/);
|
|
137
|
+
if (pattern && !pattern.startsWith("#"))
|
|
138
|
+
rules.push({ match: globMatcher(pattern), attrs });
|
|
139
|
+
}
|
|
140
|
+
return (path, attr) => {
|
|
141
|
+
let value = false;
|
|
142
|
+
for (const rule of rules)
|
|
143
|
+
if (rule.match(path))
|
|
144
|
+
for (const a of rule.attrs) {
|
|
145
|
+
if (a === attr || a === `${attr}=true`)
|
|
146
|
+
value = true;
|
|
147
|
+
else if (a === `-${attr}` || a === `!${attr}` || a === `${attr}=false`)
|
|
148
|
+
value = false;
|
|
149
|
+
}
|
|
150
|
+
return value;
|
|
151
|
+
};
|
|
152
|
+
}
|
|
153
|
+
/** Reads blobs in one `git cat-file --batch` process; returns contents in request order. */
|
|
154
|
+
function readBlobs(root, shas) {
|
|
155
|
+
if (!shas.length)
|
|
156
|
+
return [];
|
|
157
|
+
const out = execFileSync("git", ["cat-file", "--batch"], {
|
|
158
|
+
cwd: root,
|
|
159
|
+
input: shas.join("\n") + "\n",
|
|
160
|
+
maxBuffer: Infinity,
|
|
161
|
+
});
|
|
162
|
+
const blobs = [];
|
|
163
|
+
let offset = 0;
|
|
164
|
+
for (const sha of shas) {
|
|
165
|
+
const end = out.indexOf(10, offset);
|
|
166
|
+
const [, type, size] = out.subarray(offset, end).toString("latin1").split(" ");
|
|
167
|
+
if (type !== "blob" || size === undefined)
|
|
168
|
+
throw new Error(`Cannot read blob ${sha}`);
|
|
169
|
+
blobs.push(out.subarray(end + 1, end + 1 + Number(size)));
|
|
170
|
+
offset = end + 1 + Number(size) + 1;
|
|
171
|
+
}
|
|
172
|
+
return blobs;
|
|
173
|
+
}
|
|
174
|
+
/**
|
|
175
|
+
* Reads the committed HEAD tree of the whole repository (or `roots`). A dirty working tree is
|
|
176
|
+
* not an error: HEAD is read and `summary.dirty` says so. Language adapters other than TS/JS
|
|
177
|
+
* are out of scope here: other languages get file nodes only.
|
|
178
|
+
*/
|
|
179
|
+
export async function extract(root, roots = [], options = {}) {
|
|
180
|
+
root = resolve(root);
|
|
181
|
+
const identity = repository(root);
|
|
182
|
+
const { repo, commit, namespace } = identity;
|
|
183
|
+
const nodes = [], edges = [];
|
|
184
|
+
const nodeByKey = new Map();
|
|
185
|
+
const dirty = git(root, [
|
|
186
|
+
"status",
|
|
187
|
+
"--porcelain",
|
|
188
|
+
"--untracked-files=all",
|
|
189
|
+
...(roots.length ? ["--", ...roots] : []),
|
|
190
|
+
]) !== "";
|
|
191
|
+
const summary = {
|
|
192
|
+
files: {},
|
|
193
|
+
symbols: 0,
|
|
194
|
+
edges: 0,
|
|
195
|
+
skipped: Object.fromEntries(SKIP_REASONS.map((r) => [r, 0])),
|
|
196
|
+
parseErrors: [],
|
|
197
|
+
dirty,
|
|
198
|
+
};
|
|
199
|
+
const key = (path, symbol = "") => `${namespace}:${path}${symbol ? `#${symbol}` : ""}`;
|
|
200
|
+
const provenance = (path, startLine = 1, endLine = startLine) => [
|
|
201
|
+
{ kind: "repo", repo, commit, path, startLine, endLine },
|
|
202
|
+
];
|
|
203
|
+
const add = (path, type, title, start = 1, end = start, symbol = "", properties = {}) => {
|
|
204
|
+
const clientKey = key(path, symbol);
|
|
205
|
+
// Qualified paths plus a stable suffix distinguish punctuation-normalized paths
|
|
206
|
+
// and identical layouts in different repository roots.
|
|
207
|
+
title = `${title} [${createHash("sha256").update(clientKey).digest("hex").slice(0, 16)}]`;
|
|
208
|
+
if (clientKey.length > 1024 || title.length > 300)
|
|
209
|
+
throw new Error(`Repository identity exceeds graph limits: ${path}`);
|
|
210
|
+
const created = {
|
|
211
|
+
clientKey,
|
|
212
|
+
namespace,
|
|
213
|
+
type,
|
|
214
|
+
title,
|
|
215
|
+
body: "",
|
|
216
|
+
properties,
|
|
217
|
+
provenance: provenance(path, start, end),
|
|
218
|
+
derivation: "extracted",
|
|
219
|
+
};
|
|
220
|
+
nodes.push(created);
|
|
221
|
+
if (!nodeByKey.has(clientKey))
|
|
222
|
+
nodeByKey.set(clientKey, created);
|
|
223
|
+
return clientKey;
|
|
224
|
+
};
|
|
225
|
+
const edge = (type, from, to, path, line = 1) => edges.push({
|
|
226
|
+
type,
|
|
227
|
+
from,
|
|
228
|
+
to,
|
|
229
|
+
provenance: provenance(path, line),
|
|
230
|
+
derivation: "extracted",
|
|
231
|
+
properties: {},
|
|
232
|
+
});
|
|
233
|
+
const repoKey = add(".", "repository", `Repository ${repo}`);
|
|
234
|
+
const files = [];
|
|
235
|
+
const directories = new Map([[".", repoKey]]);
|
|
236
|
+
const ensureDir = (path) => {
|
|
237
|
+
const old = directories.get(path);
|
|
238
|
+
if (old)
|
|
239
|
+
return old;
|
|
240
|
+
const parent = ensureDir(posix.dirname(path));
|
|
241
|
+
const id = add(path, "module", `Module ${path}`);
|
|
242
|
+
directories.set(path, id);
|
|
243
|
+
edge("contains", parent, id, path);
|
|
244
|
+
return id;
|
|
245
|
+
};
|
|
246
|
+
for (const rootPath of roots)
|
|
247
|
+
if (posix.isAbsolute(rootPath) || rootPath.split(/[\\/]/).includes(".."))
|
|
248
|
+
throw new Error("Scan roots must be repository relative");
|
|
249
|
+
// `-l` gives each blob's size so oversized files are skipped without reading them.
|
|
250
|
+
const tracked = execFileSync("git", ["ls-tree", "-r", "-l", "-z", identity.commit, ...(roots.length ? ["--", ...roots] : [])], { cwd: root, encoding: "utf8", maxBuffer: Infinity })
|
|
251
|
+
.split("\0")
|
|
252
|
+
.filter(Boolean)
|
|
253
|
+
.flatMap((entry) => {
|
|
254
|
+
const tab = entry.indexOf("\t");
|
|
255
|
+
const [mode, type, sha, size] = entry.slice(0, tab).split(/\s+/);
|
|
256
|
+
// Skip submodules (commit entries) and symlinks.
|
|
257
|
+
return type === "blob" && mode !== "120000" && sha
|
|
258
|
+
? [{ path: entry.slice(tab + 1), sha, size: Number(size) }]
|
|
259
|
+
: [];
|
|
260
|
+
});
|
|
261
|
+
let attribute = () => false;
|
|
262
|
+
const attributes = tracked.find((entry) => entry.path === ".gitattributes");
|
|
263
|
+
if (attributes)
|
|
264
|
+
attribute = attributeRules(readBlobs(root, [attributes.sha])[0]?.toString("utf8") ?? "");
|
|
265
|
+
const maxBytes = options.maxFileBytes ?? DEFAULT_MAX_FILE_BYTES;
|
|
266
|
+
const includes = (options.include ?? []).map(globMatcher);
|
|
267
|
+
const excludes = (options.exclude ?? []).map(globMatcher);
|
|
268
|
+
const skip = (reason) => {
|
|
269
|
+
summary.skipped[reason]++;
|
|
270
|
+
};
|
|
271
|
+
const candidates = [];
|
|
272
|
+
for (const entry of tracked) {
|
|
273
|
+
const { path } = entry;
|
|
274
|
+
if (path
|
|
275
|
+
.split("/")
|
|
276
|
+
.slice(0, -1)
|
|
277
|
+
.some((part) => EXCLUDED_DIRS.has(part)))
|
|
278
|
+
skip("excluded-dir");
|
|
279
|
+
else if ((includes.length && !includes.some((m) => m(path))) || excludes.some((m) => m(path)))
|
|
280
|
+
skip("excluded-glob");
|
|
281
|
+
else if (/\.d\.[cm]?ts$|\.generated\.|\.g\.dart$/.test(path) ||
|
|
282
|
+
attribute(path, "linguist-generated"))
|
|
283
|
+
skip("generated");
|
|
284
|
+
else if (attribute(path, "linguist-vendored"))
|
|
285
|
+
skip("vendored");
|
|
286
|
+
else if (/\.min\./.test(posix.basename(path)))
|
|
287
|
+
skip("minified");
|
|
288
|
+
else if (entry.size > maxBytes)
|
|
289
|
+
skip("too-large");
|
|
290
|
+
else
|
|
291
|
+
candidates.push(entry);
|
|
292
|
+
}
|
|
293
|
+
const contents = readBlobs(root, candidates.map((c) => c.sha));
|
|
294
|
+
const manifests = new Map(); // go.mod: no language, but import resolution reads it
|
|
295
|
+
const decoder = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true });
|
|
296
|
+
const loaded = new Map();
|
|
297
|
+
candidates.forEach(({ path }, index) => {
|
|
298
|
+
const buffer = contents[index] ?? Buffer.alloc(0);
|
|
299
|
+
let text;
|
|
300
|
+
try {
|
|
301
|
+
if (buffer.includes(0))
|
|
302
|
+
throw new Error("NUL");
|
|
303
|
+
text = decoder.decode(buffer);
|
|
304
|
+
}
|
|
305
|
+
catch {
|
|
306
|
+
skip("binary");
|
|
307
|
+
return;
|
|
308
|
+
}
|
|
309
|
+
if (posix.basename(path) === "go.mod")
|
|
310
|
+
manifests.set(path, text);
|
|
311
|
+
const language = languageOf(path, text.slice(0, 200));
|
|
312
|
+
if (!language) {
|
|
313
|
+
skip("unknown-language");
|
|
314
|
+
return;
|
|
315
|
+
}
|
|
316
|
+
if (text.split("\n").some((line) => line.length > MAX_LINE_CHARS)) {
|
|
317
|
+
skip("minified");
|
|
318
|
+
return;
|
|
319
|
+
}
|
|
320
|
+
files.push(path);
|
|
321
|
+
loaded.set(path, {
|
|
322
|
+
text,
|
|
323
|
+
bytes: buffer.length,
|
|
324
|
+
sha256: createHash("sha256").update(buffer).digest("hex"),
|
|
325
|
+
language,
|
|
326
|
+
});
|
|
327
|
+
});
|
|
328
|
+
const imports = [];
|
|
329
|
+
const uses = [];
|
|
330
|
+
const symbols = new Map();
|
|
331
|
+
for (const path of files) {
|
|
332
|
+
const info = loaded.get(path);
|
|
333
|
+
if (!info)
|
|
334
|
+
continue;
|
|
335
|
+
const { text, bytes, sha256, language } = info;
|
|
336
|
+
summary.files[language] = (summary.files[language] ?? 0) + 1;
|
|
337
|
+
const fileProperties = {
|
|
338
|
+
language,
|
|
339
|
+
sha256,
|
|
340
|
+
bytes,
|
|
341
|
+
lines: text === "" ? 0 : text.split("\n").length - (text.endsWith("\n") ? 1 : 0),
|
|
342
|
+
};
|
|
343
|
+
const file = add(path, "file", `File ${path}`, 1, text.split("\n").length, "", fileProperties);
|
|
344
|
+
edge("contains", ensureDir(posix.dirname(path)), file, path);
|
|
345
|
+
if (posix.basename(path) === "package.json") {
|
|
346
|
+
let manifest;
|
|
347
|
+
try {
|
|
348
|
+
manifest = JSON.parse(text);
|
|
349
|
+
}
|
|
350
|
+
catch {
|
|
351
|
+
// Same policy as syntax errors below: keep the file node, flag it, carry on.
|
|
352
|
+
fileProperties.parseError = true;
|
|
353
|
+
summary.parseErrors.push(path);
|
|
354
|
+
continue;
|
|
355
|
+
}
|
|
356
|
+
const config = add(path, "config", `Package configuration ${path}`, 1, text.split("\n").length, "manifest", { manifest });
|
|
357
|
+
edge("contains", file, config, path);
|
|
358
|
+
for (const section of [
|
|
359
|
+
"dependencies",
|
|
360
|
+
"devDependencies",
|
|
361
|
+
"peerDependencies",
|
|
362
|
+
"optionalDependencies",
|
|
363
|
+
]) {
|
|
364
|
+
for (const [name, version] of Object.entries((manifest[section] ?? {})).sort()) {
|
|
365
|
+
const dependency = add(path, "dependency", `${path} ${section} ${name}`, 1, 1, `${section}:${name}`, { name, version, section });
|
|
366
|
+
edge("depends_on", config, dependency, path);
|
|
367
|
+
}
|
|
368
|
+
}
|
|
369
|
+
continue;
|
|
370
|
+
}
|
|
371
|
+
// Languages without an adapter get file nodes only.
|
|
372
|
+
const adapter = adapterFor(language);
|
|
373
|
+
if (!adapter)
|
|
374
|
+
continue;
|
|
375
|
+
const { parser, symbolNodes, importNodes } = await openAdapter(adapter);
|
|
376
|
+
const tree = parser.parse(text);
|
|
377
|
+
if (!tree) {
|
|
378
|
+
parser.delete();
|
|
379
|
+
throw new Error(`Parse failed: ${path}`);
|
|
380
|
+
}
|
|
381
|
+
try {
|
|
382
|
+
// A file with syntax errors keeps its file node, flagged parseError, with no symbols or
|
|
383
|
+
// imports (a partial tree would give misleading declarations); the sync carries on and the
|
|
384
|
+
// summary lists the file.
|
|
385
|
+
if (tree.rootNode.hasError) {
|
|
386
|
+
fileProperties.parseError = true;
|
|
387
|
+
summary.parseErrors.push(path);
|
|
388
|
+
continue;
|
|
389
|
+
}
|
|
390
|
+
const declarations = symbolNodes(tree.rootNode);
|
|
391
|
+
const importStatements = importNodes(tree.rootNode);
|
|
392
|
+
const visit = (node, scope, parent, exported = false) => {
|
|
393
|
+
const isExport = exported || node.type === "export_statement";
|
|
394
|
+
if (declarations.has(node.id)) {
|
|
395
|
+
const custom = adapter.declaration?.(node);
|
|
396
|
+
const name = custom?.name ??
|
|
397
|
+
adapter.symbolName?.(node) ??
|
|
398
|
+
node.childForFieldName("name")?.text ??
|
|
399
|
+
(node.parent?.type === "export_statement" ? "default" : undefined);
|
|
400
|
+
if (name) {
|
|
401
|
+
const qualified = [...scope, name];
|
|
402
|
+
const symbol = qualified.join(".");
|
|
403
|
+
// Overload declarations share an identity; retain one entity with all declaration ranges.
|
|
404
|
+
const old = nodeByKey.get(key(path, symbol));
|
|
405
|
+
if (old) {
|
|
406
|
+
const first = old.provenance[0];
|
|
407
|
+
if (first)
|
|
408
|
+
first.endLine = node.endPosition.row + 1;
|
|
409
|
+
old.properties.sha256 = createHash("sha256")
|
|
410
|
+
.update(String(old.properties.sha256) + node.text)
|
|
411
|
+
.digest("hex");
|
|
412
|
+
old.body = sourceSnippet(old.body + "\n" + node.text);
|
|
413
|
+
old.properties.bodyTruncated = Buffer.byteLength(old.body + "\n" + node.text) > 7800;
|
|
414
|
+
node.namedChildren.forEach((child) => {
|
|
415
|
+
visit(child, qualified, old.clientKey, false);
|
|
416
|
+
});
|
|
417
|
+
return;
|
|
418
|
+
}
|
|
419
|
+
const id = add(path, "symbol", `${path}#${symbol}`, node.startPosition.row + 1, node.endPosition.row + 1, symbol, {
|
|
420
|
+
kind: declarations.get(node.id) ?? custom?.kind ?? node.type,
|
|
421
|
+
exported: custom?.exported ?? (isExport || (adapter.isExported?.(node, name) ?? false)),
|
|
422
|
+
sha256: createHash("sha256").update(node.text).digest("hex"),
|
|
423
|
+
});
|
|
424
|
+
const symbolNode = nodeByKey.get(id);
|
|
425
|
+
if (symbolNode) {
|
|
426
|
+
symbolNode.body = sourceSnippet(node.text);
|
|
427
|
+
symbolNode.properties.bodyTruncated = Buffer.byteLength(node.text) > 7800;
|
|
428
|
+
}
|
|
429
|
+
symbols.set(`${path}#${symbol}`, id);
|
|
430
|
+
edge("contains", parent, id, path, node.startPosition.row + 1);
|
|
431
|
+
node.namedChildren.forEach((child) => {
|
|
432
|
+
visit(child, qualified, id, false);
|
|
433
|
+
});
|
|
434
|
+
return;
|
|
435
|
+
}
|
|
436
|
+
}
|
|
437
|
+
const statement = importStatements.get(node.id);
|
|
438
|
+
if (statement)
|
|
439
|
+
imports.push({ from: file, path, ...statement });
|
|
440
|
+
for (const use of adapter.uses?.(node, { file, parent, scope }) ?? [])
|
|
441
|
+
uses.push({ from: parent, scope, path, ...use });
|
|
442
|
+
node.namedChildren.forEach((child) => {
|
|
443
|
+
visit(child, scope, parent, isExport);
|
|
444
|
+
});
|
|
445
|
+
};
|
|
446
|
+
visit(tree.rootNode, [], file);
|
|
447
|
+
}
|
|
448
|
+
finally {
|
|
449
|
+
tree.delete();
|
|
450
|
+
parser.delete();
|
|
451
|
+
}
|
|
452
|
+
}
|
|
453
|
+
const seenUses = new Set();
|
|
454
|
+
for (const use of uses) {
|
|
455
|
+
let target;
|
|
456
|
+
for (let depth = use.scope.length; depth >= 0 && !target; depth--)
|
|
457
|
+
target = symbols.get(`${use.path}#${[...use.scope.slice(0, depth), use.name].join(".")}`);
|
|
458
|
+
const signature = JSON.stringify([use.type, use.from, target]);
|
|
459
|
+
if (target && target !== use.from && !seenUses.has(signature)) {
|
|
460
|
+
seenUses.add(signature);
|
|
461
|
+
edges.push({
|
|
462
|
+
type: use.type,
|
|
463
|
+
from: use.from,
|
|
464
|
+
to: target,
|
|
465
|
+
provenance: provenance(use.path, use.line),
|
|
466
|
+
derivation: "inferred",
|
|
467
|
+
properties: { resolution: "same-file lexical name heuristic" },
|
|
468
|
+
});
|
|
469
|
+
}
|
|
470
|
+
}
|
|
471
|
+
const fileSet = new Set(files);
|
|
472
|
+
for (const item of imports) {
|
|
473
|
+
const target = adapterFor(loaded.get(item.path)?.language ?? "")?.resolveImport?.(item.source, item.path, fileSet, (path) => loaded.get(path)?.text ?? manifests.get(path));
|
|
474
|
+
for (const to of [target ?? []].flat())
|
|
475
|
+
edge("imports", item.from, key(to), item.path, item.line);
|
|
476
|
+
}
|
|
477
|
+
summary.symbols = nodes.filter((n) => n.type === "symbol").length;
|
|
478
|
+
summary.edges = edges.length;
|
|
479
|
+
return { ...identity, nodes, edges, summary };
|
|
480
|
+
}
|
package/dist/index.d.ts
ADDED
package/dist/index.js
ADDED
package/dist/issues.d.ts
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import { ContextApi } from "./api.js";
|
|
2
|
+
export interface GithubIssue {
|
|
3
|
+
number: number;
|
|
4
|
+
title: string;
|
|
5
|
+
body?: string | null;
|
|
6
|
+
state: string;
|
|
7
|
+
html_url: string;
|
|
8
|
+
labels?: (string | {
|
|
9
|
+
name?: string;
|
|
10
|
+
})[];
|
|
11
|
+
pull_request?: unknown;
|
|
12
|
+
}
|
|
13
|
+
export interface IssueRequest {
|
|
14
|
+
owner: string;
|
|
15
|
+
name: string;
|
|
16
|
+
state: "all" | "open";
|
|
17
|
+
limit?: number | undefined;
|
|
18
|
+
}
|
|
19
|
+
export type IssueSource = (request: IssueRequest) => Promise<GithubIssue[]>;
|
|
20
|
+
export interface IssuesOptions {
|
|
21
|
+
state: "all" | "open";
|
|
22
|
+
limit?: number | undefined;
|
|
23
|
+
}
|
|
24
|
+
/** owner/name from an https or ssh GitHub remote URL. */
|
|
25
|
+
export declare function parseGithubRemote(remote: string): {
|
|
26
|
+
owner: string;
|
|
27
|
+
name: string;
|
|
28
|
+
};
|
|
29
|
+
/** Flags: --repo, --project, --server, --token-env, --state all|open, --limit N. */
|
|
30
|
+
export declare function issuesSyncOptions(argv: string[]): Record<string, string> & IssuesOptions;
|
|
31
|
+
/** gh api first; GITHUB_TOKEN with fetch when gh is missing or fails. */
|
|
32
|
+
export declare const githubSource: IssueSource;
|
|
33
|
+
/**
|
|
34
|
+
* Mirrors issues into the graph with the code sync's reconcile, in its own namespace. When the
|
|
35
|
+
* list is partial (--state open or --limit) unseen issues are kept, not superseded.
|
|
36
|
+
*/
|
|
37
|
+
export declare function runIssuesSync(api: ContextApi, identity: {
|
|
38
|
+
repo: string;
|
|
39
|
+
namespace: string;
|
|
40
|
+
}, source: IssueSource, options: IssuesOptions): Promise<{
|
|
41
|
+
issues: number;
|
|
42
|
+
contributions: number;
|
|
43
|
+
}>;
|
|
44
|
+
export declare function issuesSync(argv: string[], source?: IssueSource): Promise<void>;
|
package/dist/issues.js
ADDED
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
import { execFile } from "node:child_process";
|
|
2
|
+
import { createHash } from "node:crypto";
|
|
3
|
+
import { resolve } from "node:path";
|
|
4
|
+
import { promisify } from "node:util";
|
|
5
|
+
import { ContextApi, reconcile } from "./api.js";
|
|
6
|
+
import { resolveSync } from "./cli.js";
|
|
7
|
+
import { repository } from "./extract.js";
|
|
8
|
+
const run = promisify(execFile);
|
|
9
|
+
const BODY_MAX = 4000;
|
|
10
|
+
/** owner/name from an https or ssh GitHub remote URL. */
|
|
11
|
+
export function parseGithubRemote(remote) {
|
|
12
|
+
const match = /github\.com[/:]([^/\s]+)\/([^/\s]+?)(?:\.git)?\/?$/i.exec(remote);
|
|
13
|
+
if (!match?.[1] || !match[2])
|
|
14
|
+
throw new Error(`The origin remote is not a GitHub repository: ${remote || "(none)"}`);
|
|
15
|
+
return { owner: match[1], name: match[2] };
|
|
16
|
+
}
|
|
17
|
+
/** Flags: --repo, --project, --server, --token-env, --state all|open, --limit N. */
|
|
18
|
+
export function issuesSyncOptions(argv) {
|
|
19
|
+
const result = {};
|
|
20
|
+
for (let i = 0; i < argv.length; i += 2) {
|
|
21
|
+
const name = argv[i]?.replace(/^--/, "");
|
|
22
|
+
const value = argv[i + 1];
|
|
23
|
+
if (!name ||
|
|
24
|
+
!["repo", "project", "server", "token-env", "state", "limit"].includes(name) ||
|
|
25
|
+
!value ||
|
|
26
|
+
value.startsWith("--"))
|
|
27
|
+
throw new Error("Invalid arguments; use [--state all|open] [--limit N] [--repo PATH --project UUID --server URL --token-env ENV_NAME]");
|
|
28
|
+
result[name] = value;
|
|
29
|
+
}
|
|
30
|
+
const state = result.state ?? "all";
|
|
31
|
+
if (state !== "all" && state !== "open")
|
|
32
|
+
throw new Error("--state must be all|open");
|
|
33
|
+
const limit = result.limit === undefined ? undefined : Number(result.limit);
|
|
34
|
+
if (limit !== undefined && !(Number.isInteger(limit) && limit > 0))
|
|
35
|
+
throw new Error("--limit must be a positive integer");
|
|
36
|
+
return { ...result, state, ...(limit === undefined ? {} : { limit }) };
|
|
37
|
+
}
|
|
38
|
+
const NO_ACCESS = "Cannot read GitHub issues: install and authenticate the gh CLI (gh auth login) or set GITHUB_TOKEN";
|
|
39
|
+
/** gh api first; GITHUB_TOKEN with fetch when gh is missing or fails. */
|
|
40
|
+
export const githubSource = async ({ owner, name, state, limit }) => {
|
|
41
|
+
const path = `repos/${owner}/${name}/issues?state=${state}&per_page=100`;
|
|
42
|
+
try {
|
|
43
|
+
const { stdout } = await run("gh", ["api", "--paginate", path, "--jq", ".[]"], {
|
|
44
|
+
maxBuffer: 256 * 1024 * 1024,
|
|
45
|
+
});
|
|
46
|
+
return stdout
|
|
47
|
+
.split("\n")
|
|
48
|
+
.filter(Boolean)
|
|
49
|
+
.map((line) => JSON.parse(line));
|
|
50
|
+
}
|
|
51
|
+
catch (error) {
|
|
52
|
+
const token = process.env.GITHUB_TOKEN?.trim();
|
|
53
|
+
if (!token)
|
|
54
|
+
throw new Error(NO_ACCESS, { cause: error });
|
|
55
|
+
return fetchIssues(path, token, limit);
|
|
56
|
+
}
|
|
57
|
+
};
|
|
58
|
+
async function fetchIssues(path, token, limit) {
|
|
59
|
+
const issues = [];
|
|
60
|
+
for (let page = 1;; page++) {
|
|
61
|
+
const response = await fetch(`https://api.github.com/${path}&page=${String(page)}`, {
|
|
62
|
+
headers: {
|
|
63
|
+
authorization: `Bearer ${token}`,
|
|
64
|
+
accept: "application/vnd.github+json",
|
|
65
|
+
"user-agent": "cboard",
|
|
66
|
+
},
|
|
67
|
+
});
|
|
68
|
+
if (!response.ok)
|
|
69
|
+
throw new Error(`GitHub API ${String(response.status)} for ${path}`);
|
|
70
|
+
const batch = (await response.json());
|
|
71
|
+
issues.push(...batch);
|
|
72
|
+
// Pull requests are dropped later, so the limit is applied there, not here.
|
|
73
|
+
if (batch.length < 100 || (limit !== undefined && issues.length >= limit * 4))
|
|
74
|
+
return issues;
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
function snapshotOf(issues, namespace, repoKey) {
|
|
78
|
+
const nodes = [];
|
|
79
|
+
const edges = [];
|
|
80
|
+
for (const i of issues) {
|
|
81
|
+
const clientKey = `${namespace}:#${String(i.number)}`;
|
|
82
|
+
// Issue nodes cite the issue URL (the graph's url provenance), not a repository commit.
|
|
83
|
+
const provenance = [{ kind: "url", ref: i.html_url }];
|
|
84
|
+
nodes.push({
|
|
85
|
+
clientKey,
|
|
86
|
+
namespace,
|
|
87
|
+
type: "open_issue",
|
|
88
|
+
title: `#${String(i.number)} ${i.title}`.slice(0, 300),
|
|
89
|
+
body: (i.body ?? "").trim().slice(0, BODY_MAX),
|
|
90
|
+
status: i.state === "open" ? "open" : "resolved",
|
|
91
|
+
properties: {
|
|
92
|
+
url: i.html_url,
|
|
93
|
+
labels: (i.labels ?? [])
|
|
94
|
+
.map((l) => (typeof l === "string" ? l : l.name))
|
|
95
|
+
.filter((l) => !!l),
|
|
96
|
+
},
|
|
97
|
+
provenance,
|
|
98
|
+
derivation: "extracted",
|
|
99
|
+
});
|
|
100
|
+
edges.push({
|
|
101
|
+
type: "part_of",
|
|
102
|
+
from: clientKey,
|
|
103
|
+
to: repoKey,
|
|
104
|
+
provenance,
|
|
105
|
+
derivation: "extracted",
|
|
106
|
+
properties: {},
|
|
107
|
+
});
|
|
108
|
+
}
|
|
109
|
+
return { nodes, edges };
|
|
110
|
+
}
|
|
111
|
+
/**
|
|
112
|
+
* Mirrors issues into the graph with the code sync's reconcile, in its own namespace. When the
|
|
113
|
+
* list is partial (--state open or --limit) unseen issues are kept, not superseded.
|
|
114
|
+
*/
|
|
115
|
+
export async function runIssuesSync(api, identity, source, options) {
|
|
116
|
+
const { owner, name } = parseGithubRemote(identity.repo);
|
|
117
|
+
const repoKey = `${identity.namespace}:.`;
|
|
118
|
+
const repoNode = (await api.all({ namespace: identity.namespace, types: "repository" })).nodes.find((n) => n.clientKey === repoKey && n.lifecycle === "active");
|
|
119
|
+
if (!repoNode)
|
|
120
|
+
throw new Error("The repository node is missing from the graph; run `cboard sync` first");
|
|
121
|
+
const namespace = `issues:${createHash("sha256").update(identity.repo).digest("hex").slice(0, 32)}`;
|
|
122
|
+
const fetched = await source({ owner, name, state: options.state, limit: options.limit });
|
|
123
|
+
const issues = fetched
|
|
124
|
+
.filter((i) => !i.pull_request)
|
|
125
|
+
.sort((a, b) => a.number - b.number)
|
|
126
|
+
.slice(0, options.limit);
|
|
127
|
+
const snapshot = snapshotOf(issues, namespace, repoKey);
|
|
128
|
+
const complete = options.state === "all" && options.limit === undefined;
|
|
129
|
+
const result = await reconcile(api, snapshot, namespace, complete, new Map([[repoKey, repoNode.id]]));
|
|
130
|
+
return { issues: issues.length, contributions: result.contributions };
|
|
131
|
+
}
|
|
132
|
+
export async function issuesSync(argv, source = githubSource) {
|
|
133
|
+
const args = issuesSyncOptions(argv);
|
|
134
|
+
const root = resolve(args.repo ?? process.cwd());
|
|
135
|
+
const { project, token, server } = resolveSync(args, root);
|
|
136
|
+
const result = await runIssuesSync(new ContextApi(server, project, token), repository(root), source, { state: args.state, limit: args.limit });
|
|
137
|
+
console.log(JSON.stringify(result));
|
|
138
|
+
}
|
|
@@ -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;
|