@geml/geml 1.8.2 → 1.8.3

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.
@@ -1,129 +1,129 @@
1
- // geml-code-graph app-entry detection — WHERE does this repo start running?
2
- //
3
- // Emits entry HINTS ({ file, via, name? }) from three signal tiers, each
4
- // carrying an honest `via` label (the codemap never claims an entry without
5
- // saying what convention identified it):
6
- // L2 manifest/layout Cargo [[bin]] & src/main.rs & src/bin/*, package.json
7
- // bin, wrangler.toml main, Nuxt app.vue, Next root
8
- // page, SvelteKit root route, Django manage.py,
9
- // python __main__.py
10
- // L3 source markers workers-rs #[event(...)], createApp().mount() /
11
- // createRoot() / svelte mount (SPA bootstraps),
12
- // .listen() (node servers), export default { fetch }
13
- // (JS workers), Flask()/FastAPI() apps,
14
- // @SpringBootApplication
15
- // (L1 — a function literally named `main` — is already flagged by the scip
16
- // and joern adapters at extraction time; hints here ADD to it.)
17
- //
18
- // Pure by design: given precomputed { files, manifests, pkgs } lists it walks
19
- // nothing; `readText`/`readJson` are injectable, and every source peek is
20
- // bounded to a handful of conventional entry files per project — never a
21
- // repo-wide grep. A hint is only emitted for files the build actually indexes
22
- // (present in `files`), so a pkg-bin pointing at dist/ never leaks in.
23
- import { readFileSync } from "node:fs";
24
- import { join } from "node:path";
25
-
26
- const dirOf = (p) => (p.includes("/") ? p.slice(0, p.lastIndexOf("/")) : "");
27
-
28
- export function detectEntries(root, { files = [], manifests = [], pkgs = [], readText, readJson } = {}) {
29
- readText ??= (p) => readFileSync(p, "utf8");
30
- readJson ??= (p) => JSON.parse(readText(p));
31
- const fileSet = new Set(files);
32
- const hints = [];
33
- const seen = new Set();
34
- const add = (file, via, name) => {
35
- if (!file || !fileSet.has(file)) return;
36
- const k = `${file}${via}${name ?? ""}`;
37
- if (seen.has(k)) return;
38
- seen.add(k);
39
- hints.push(name ? { file, via, name } : { file, via });
40
- };
41
- const tryText = (rel) => {
42
- try { return readText(join(root, ...rel.split("/"))); } catch { return null; }
43
- };
44
-
45
- // ---- Rust: cargo bin targets + workers-rs event handlers ----
46
- for (const m of manifests.filter((x) => x.endsWith("Cargo.toml"))) {
47
- const dir = dirOf(m);
48
- const at = (rel) => (dir ? `${dir}/${rel}` : rel);
49
- add(at("src/main.rs"), "cargo-bin", "main");
50
- for (const f of files) if (f.startsWith(at("src/bin/")) && f.endsWith(".rs")) add(f, "cargo-bin", "main");
51
- const toml = tryText(m);
52
- if (toml) {
53
- for (const b of toml.matchAll(/^\[\[bin\]\][^[]*/gm)) {
54
- const p = /path\s*=\s*"([^"]+)"/.exec(b[0]);
55
- if (p) add(at(p[1].replace(/\\/g, "/")), "cargo-bin", "main");
56
- }
57
- }
58
- for (const rel of ["src/main.rs", "src/lib.rs"]) {
59
- const t = fileSet.has(at(rel)) ? tryText(at(rel)) : null;
60
- if (!t) continue;
61
- for (const ev of t.matchAll(/#\[event\((\w+)[^)]*\)\]\s*(?:pub\s+)?(?:async\s+)?fn\s+([A-Za-z_][A-Za-z0-9_]*)/g)) {
62
- add(at(rel), `worker-${ev[1]}`, ev[2]);
63
- }
64
- }
65
- }
66
-
67
- // ---- Node/TS/frontends: one look per package ----
68
- for (const p of pkgs) {
69
- const dir = dirOf(p);
70
- const at = (rel) => (dir ? `${dir}/${rel}` : rel);
71
- let pkg = {};
72
- try { pkg = readJson(join(root, ...p.split("/"))) ?? {}; } catch { /* unreadable manifest */ }
73
- const deps = { ...pkg.dependencies, ...pkg.devDependencies };
74
- const norm = (v) => (typeof v === "string" ? v.replace(/^\.\//, "").replace(/\\/g, "/") : null);
75
- const bins = typeof pkg.bin === "string" ? [pkg.bin] : Object.values(pkg.bin ?? {});
76
- for (const b of bins) { const f = norm(b); if (f) add(at(f), "pkg-bin"); }
77
- const wrangler = tryText(at("wrangler.toml"));
78
- if (wrangler) {
79
- const mm = /^\s*main\s*=\s*"([^"]+)"/m.exec(wrangler);
80
- if (mm) add(at(norm(mm[1])), "worker-fetch");
81
- }
82
- // Nuxt: the app shell is the entry; individual pages are routes, not
83
- // program starts — deliberately NOT flooded into app-entries.
84
- if (deps.nuxt || fileSet.has(at("nuxt.config.ts")) || fileSet.has(at("nuxt.config.js"))) {
85
- if (fileSet.has(at("app.vue"))) add(at("app.vue"), "nuxt-app");
86
- else add(at("pages/index.vue"), "nuxt-page");
87
- }
88
- if (deps.next) {
89
- for (const rel of ["app/page.tsx", "app/page.jsx", "src/app/page.tsx", "pages/index.tsx", "pages/index.jsx", "src/pages/index.tsx"]) {
90
- if (fileSet.has(at(rel))) { add(at(rel), "next-page"); break; }
91
- }
92
- }
93
- if (deps["@sveltejs/kit"]) add(at("src/routes/+page.svelte"), "kit-route");
94
- // SPA bootstrap / server start markers — conventional entry files only.
95
- for (const rel of ["src/main.ts", "src/main.tsx", "src/main.js", "src/main.jsx",
96
- "src/index.ts", "src/index.tsx", "src/index.js", "index.ts", "index.js",
97
- "src/server.ts", "src/server.js", "server.js", "src/app.ts", "app.js"]) {
98
- const f = at(rel);
99
- if (!fileSet.has(f)) continue;
100
- const t = tryText(f);
101
- if (!t) continue;
102
- if (/createApp\s*\(/.test(t) && /\.mount\s*\(/.test(t)) add(f, "vue-mount");
103
- else if (/createRoot\s*\(|ReactDOM\.render\s*\(/.test(t)) add(f, "react-mount");
104
- else if (deps.svelte && /\bnew\s+\w+\s*\(\s*\{[^}]*target|\bmount\s*\(/.test(t)) add(f, "svelte-mount");
105
- if (/\.listen\s*\(/.test(t)) add(f, "server-listen");
106
- if (/export\s+default\s*\{[^}]*\bfetch\b/s.test(t)) add(f, "worker-fetch");
107
- }
108
- }
109
-
110
- // ---- Python ----
111
- for (const f of files) {
112
- if (/(^|\/)manage\.py$/.test(f)) add(f, "django-manage");
113
- else if (/(^|\/)__main__\.py$/.test(f)) add(f, "py-main");
114
- else if (/(^|\/)(app|main|wsgi|asgi)\.py$/.test(f)) {
115
- const t = tryText(f);
116
- if (t && /\bFlask\s*\(|\bFastAPI\s*\(/.test(t)) add(f, "wsgi-app");
117
- }
118
- }
119
-
120
- // ---- Java: Spring Boot (convention-named files only, never a repo grep) ----
121
- for (const f of files) {
122
- if (/Application\.java$/.test(f)) {
123
- const t = tryText(f);
124
- if (t && /@SpringBootApplication/.test(t)) add(f, "spring-boot", "main");
125
- }
126
- }
127
-
128
- return hints;
129
- }
1
+ // geml-code-graph app-entry detection — WHERE does this repo start running?
2
+ //
3
+ // Emits entry HINTS ({ file, via, name? }) from three signal tiers, each
4
+ // carrying an honest `via` label (the codemap never claims an entry without
5
+ // saying what convention identified it):
6
+ // L2 manifest/layout Cargo [[bin]] & src/main.rs & src/bin/*, package.json
7
+ // bin, wrangler.toml main, Nuxt app.vue, Next root
8
+ // page, SvelteKit root route, Django manage.py,
9
+ // python __main__.py
10
+ // L3 source markers workers-rs #[event(...)], createApp().mount() /
11
+ // createRoot() / svelte mount (SPA bootstraps),
12
+ // .listen() (node servers), export default { fetch }
13
+ // (JS workers), Flask()/FastAPI() apps,
14
+ // @SpringBootApplication
15
+ // (L1 — a function literally named `main` — is already flagged by the scip
16
+ // and joern adapters at extraction time; hints here ADD to it.)
17
+ //
18
+ // Pure by design: given precomputed { files, manifests, pkgs } lists it walks
19
+ // nothing; `readText`/`readJson` are injectable, and every source peek is
20
+ // bounded to a handful of conventional entry files per project — never a
21
+ // repo-wide grep. A hint is only emitted for files the build actually indexes
22
+ // (present in `files`), so a pkg-bin pointing at dist/ never leaks in.
23
+ import { readFileSync } from "node:fs";
24
+ import { join } from "node:path";
25
+
26
+ const dirOf = (p) => (p.includes("/") ? p.slice(0, p.lastIndexOf("/")) : "");
27
+
28
+ export function detectEntries(root, { files = [], manifests = [], pkgs = [], readText, readJson } = {}) {
29
+ readText ??= (p) => readFileSync(p, "utf8");
30
+ readJson ??= (p) => JSON.parse(readText(p));
31
+ const fileSet = new Set(files);
32
+ const hints = [];
33
+ const seen = new Set();
34
+ const add = (file, via, name) => {
35
+ if (!file || !fileSet.has(file)) return;
36
+ const k = `${file}${via}${name ?? ""}`;
37
+ if (seen.has(k)) return;
38
+ seen.add(k);
39
+ hints.push(name ? { file, via, name } : { file, via });
40
+ };
41
+ const tryText = (rel) => {
42
+ try { return readText(join(root, ...rel.split("/"))); } catch { return null; }
43
+ };
44
+
45
+ // ---- Rust: cargo bin targets + workers-rs event handlers ----
46
+ for (const m of manifests.filter((x) => x.endsWith("Cargo.toml"))) {
47
+ const dir = dirOf(m);
48
+ const at = (rel) => (dir ? `${dir}/${rel}` : rel);
49
+ add(at("src/main.rs"), "cargo-bin", "main");
50
+ for (const f of files) if (f.startsWith(at("src/bin/")) && f.endsWith(".rs")) add(f, "cargo-bin", "main");
51
+ const toml = tryText(m);
52
+ if (toml) {
53
+ for (const b of toml.matchAll(/^\[\[bin\]\][^[]*/gm)) {
54
+ const p = /path\s*=\s*"([^"]+)"/.exec(b[0]);
55
+ if (p) add(at(p[1].replace(/\\/g, "/")), "cargo-bin", "main");
56
+ }
57
+ }
58
+ for (const rel of ["src/main.rs", "src/lib.rs"]) {
59
+ const t = fileSet.has(at(rel)) ? tryText(at(rel)) : null;
60
+ if (!t) continue;
61
+ for (const ev of t.matchAll(/#\[event\((\w+)[^)]*\)\]\s*(?:pub\s+)?(?:async\s+)?fn\s+([A-Za-z_][A-Za-z0-9_]*)/g)) {
62
+ add(at(rel), `worker-${ev[1]}`, ev[2]);
63
+ }
64
+ }
65
+ }
66
+
67
+ // ---- Node/TS/frontends: one look per package ----
68
+ for (const p of pkgs) {
69
+ const dir = dirOf(p);
70
+ const at = (rel) => (dir ? `${dir}/${rel}` : rel);
71
+ let pkg = {};
72
+ try { pkg = readJson(join(root, ...p.split("/"))) ?? {}; } catch { /* unreadable manifest */ }
73
+ const deps = { ...pkg.dependencies, ...pkg.devDependencies };
74
+ const norm = (v) => (typeof v === "string" ? v.replace(/^\.\//, "").replace(/\\/g, "/") : null);
75
+ const bins = typeof pkg.bin === "string" ? [pkg.bin] : Object.values(pkg.bin ?? {});
76
+ for (const b of bins) { const f = norm(b); if (f) add(at(f), "pkg-bin"); }
77
+ const wrangler = tryText(at("wrangler.toml"));
78
+ if (wrangler) {
79
+ const mm = /^\s*main\s*=\s*"([^"]+)"/m.exec(wrangler);
80
+ if (mm) add(at(norm(mm[1])), "worker-fetch");
81
+ }
82
+ // Nuxt: the app shell is the entry; individual pages are routes, not
83
+ // program starts — deliberately NOT flooded into app-entries.
84
+ if (deps.nuxt || fileSet.has(at("nuxt.config.ts")) || fileSet.has(at("nuxt.config.js"))) {
85
+ if (fileSet.has(at("app.vue"))) add(at("app.vue"), "nuxt-app");
86
+ else add(at("pages/index.vue"), "nuxt-page");
87
+ }
88
+ if (deps.next) {
89
+ for (const rel of ["app/page.tsx", "app/page.jsx", "src/app/page.tsx", "pages/index.tsx", "pages/index.jsx", "src/pages/index.tsx"]) {
90
+ if (fileSet.has(at(rel))) { add(at(rel), "next-page"); break; }
91
+ }
92
+ }
93
+ if (deps["@sveltejs/kit"]) add(at("src/routes/+page.svelte"), "kit-route");
94
+ // SPA bootstrap / server start markers — conventional entry files only.
95
+ for (const rel of ["src/main.ts", "src/main.tsx", "src/main.js", "src/main.jsx",
96
+ "src/index.ts", "src/index.tsx", "src/index.js", "index.ts", "index.js",
97
+ "src/server.ts", "src/server.js", "server.js", "src/app.ts", "app.js"]) {
98
+ const f = at(rel);
99
+ if (!fileSet.has(f)) continue;
100
+ const t = tryText(f);
101
+ if (!t) continue;
102
+ if (/createApp\s*\(/.test(t) && /\.mount\s*\(/.test(t)) add(f, "vue-mount");
103
+ else if (/createRoot\s*\(|ReactDOM\.render\s*\(/.test(t)) add(f, "react-mount");
104
+ else if (deps.svelte && /\bnew\s+\w+\s*\(\s*\{[^}]*target|\bmount\s*\(/.test(t)) add(f, "svelte-mount");
105
+ if (/\.listen\s*\(/.test(t)) add(f, "server-listen");
106
+ if (/export\s+default\s*\{[^}]*\bfetch\b/s.test(t)) add(f, "worker-fetch");
107
+ }
108
+ }
109
+
110
+ // ---- Python ----
111
+ for (const f of files) {
112
+ if (/(^|\/)manage\.py$/.test(f)) add(f, "django-manage");
113
+ else if (/(^|\/)__main__\.py$/.test(f)) add(f, "py-main");
114
+ else if (/(^|\/)(app|main|wsgi|asgi)\.py$/.test(f)) {
115
+ const t = tryText(f);
116
+ if (t && /\bFlask\s*\(|\bFastAPI\s*\(/.test(t)) add(f, "wsgi-app");
117
+ }
118
+ }
119
+
120
+ // ---- Java: Spring Boot (convention-named files only, never a repo grep) ----
121
+ for (const f of files) {
122
+ if (/Application\.java$/.test(f)) {
123
+ const t = tryText(f);
124
+ if (t && /@SpringBootApplication/.test(t)) add(f, "spring-boot", "main");
125
+ }
126
+ }
127
+
128
+ return hints;
129
+ }
@@ -1,56 +1,56 @@
1
- // Source exclusion for the codemap build.
2
- //
3
- // Two mechanisms, both matching on a symbol's repo-relative POSIX file path:
4
- // 1. .gitignore — the default. Whatever git ignores (vendored copies, build
5
- // output, dependency dumps) never enters the graph. Uses `git check-ignore`
6
- // so the semantics are exactly git's, including un-committed .gitignore
7
- // edits (check-ignore reads the working tree).
8
- // 2. --exclude <glob> — explicit, repeatable, for paths git still tracks that
9
- // you nonetheless don't want in the graph.
10
- // Neither touches the raw indexer output; excluded symbols are dropped before
11
- // emit, and the edge tables (which key on surviving anchors) follow.
12
-
13
- import { execFileSync as _execFileSync } from "node:child_process";
14
-
15
- // Minimal gitignore-flavoured glob: `**` spans path separators, `*` stays
16
- // within a segment, everything else is literal. Anchored to the whole path.
17
- export function globToRegExp(glob) {
18
- // The glob comes from a `--exclude` argument, so nothing in it may reach the
19
- // compiled pattern as *syntax*. Split on the wildcards, keeping them (the
20
- // capture group), which leaves the array strictly alternating: even indices
21
- // are literal text, odd indices are `*`, `**` or `**/`. Literals go through a
22
- // total regex-metacharacter escape; wildcards map to fixed patterns. Neither
23
- // path can carry an unescaped metacharacter through.
24
- const parts = String(glob).split(/(\*\*\/?|\*)/);
25
- let re = "";
26
- for (let i = 0; i < parts.length; i++) {
27
- if (i % 2 === 0) re += parts[i].replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
28
- else re += parts[i] === "*" ? "[^/]*" : ".*"; // `**` and `**/` span separators
29
- }
30
- return new RegExp("^" + re + "$");
31
- }
32
-
33
- // Ask git which of `files` it ignores. Returns a Set of the ignored paths.
34
- // check-ignore exits 1 when nothing matches and 128 when git is unavailable /
35
- // the dir is not a repo — both mean "ignore nothing", not a build failure.
36
- // The injected runner is named `run`, not `exec`: it is always an execFile-shaped
37
- // (program, args[]) call that spawns NO shell, whereas a callback named `exec`
38
- // reads — to a human skimming, and to a static analyser — as the shell-string
39
- // child_process API. The name should not imply the dangerous one.
40
- export function gitIgnored(root, files, run = _execFileSync) {
41
- if (!files.length) return new Set();
42
- try {
43
- const out = run("git", ["-C", root, "check-ignore", "--stdin"], { input: files.join("\n"), encoding: "utf8" });
44
- return new Set(out.split(/\r?\n/).filter(Boolean));
45
- } catch (e) {
46
- const out = e && e.stdout ? String(e.stdout) : "";
47
- return new Set(out.split(/\r?\n/).filter(Boolean));
48
- }
49
- }
50
-
51
- // Build a predicate (file) => shouldExclude.
52
- export function makeExcluder({ root, globs = [], gitignore = true, files = [], run } = {}) {
53
- const res = globs.map(globToRegExp);
54
- const ignored = gitignore ? gitIgnored(root, files, run) : new Set();
55
- return (file) => ignored.has(file) || res.some((r) => r.test(file));
56
- }
1
+ // Source exclusion for the codemap build.
2
+ //
3
+ // Two mechanisms, both matching on a symbol's repo-relative POSIX file path:
4
+ // 1. .gitignore — the default. Whatever git ignores (vendored copies, build
5
+ // output, dependency dumps) never enters the graph. Uses `git check-ignore`
6
+ // so the semantics are exactly git's, including un-committed .gitignore
7
+ // edits (check-ignore reads the working tree).
8
+ // 2. --exclude <glob> — explicit, repeatable, for paths git still tracks that
9
+ // you nonetheless don't want in the graph.
10
+ // Neither touches the raw indexer output; excluded symbols are dropped before
11
+ // emit, and the edge tables (which key on surviving anchors) follow.
12
+
13
+ import { execFileSync as _execFileSync } from "node:child_process";
14
+
15
+ // Minimal gitignore-flavoured glob: `**` spans path separators, `*` stays
16
+ // within a segment, everything else is literal. Anchored to the whole path.
17
+ export function globToRegExp(glob) {
18
+ // The glob comes from a `--exclude` argument, so nothing in it may reach the
19
+ // compiled pattern as *syntax*. Split on the wildcards, keeping them (the
20
+ // capture group), which leaves the array strictly alternating: even indices
21
+ // are literal text, odd indices are `*`, `**` or `**/`. Literals go through a
22
+ // total regex-metacharacter escape; wildcards map to fixed patterns. Neither
23
+ // path can carry an unescaped metacharacter through.
24
+ const parts = String(glob).split(/(\*\*\/?|\*)/);
25
+ let re = "";
26
+ for (let i = 0; i < parts.length; i++) {
27
+ if (i % 2 === 0) re += parts[i].replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
28
+ else re += parts[i] === "*" ? "[^/]*" : ".*"; // `**` and `**/` span separators
29
+ }
30
+ return new RegExp("^" + re + "$");
31
+ }
32
+
33
+ // Ask git which of `files` it ignores. Returns a Set of the ignored paths.
34
+ // check-ignore exits 1 when nothing matches and 128 when git is unavailable /
35
+ // the dir is not a repo — both mean "ignore nothing", not a build failure.
36
+ // The injected runner is named `run`, not `exec`: it is always an execFile-shaped
37
+ // (program, args[]) call that spawns NO shell, whereas a callback named `exec`
38
+ // reads — to a human skimming, and to a static analyser — as the shell-string
39
+ // child_process API. The name should not imply the dangerous one.
40
+ export function gitIgnored(root, files, run = _execFileSync) {
41
+ if (!files.length) return new Set();
42
+ try {
43
+ const out = run("git", ["-C", root, "check-ignore", "--stdin"], { input: files.join("\n"), encoding: "utf8" });
44
+ return new Set(out.split(/\r?\n/).filter(Boolean));
45
+ } catch (e) {
46
+ const out = e && e.stdout ? String(e.stdout) : "";
47
+ return new Set(out.split(/\r?\n/).filter(Boolean));
48
+ }
49
+ }
50
+
51
+ // Build a predicate (file) => shouldExclude.
52
+ export function makeExcluder({ root, globs = [], gitignore = true, files = [], run } = {}) {
53
+ const res = globs.map(globToRegExp);
54
+ const ignored = gitignore ? gitIgnored(root, files, run) : new Set();
55
+ return (file) => ignored.has(file) || res.some((r) => r.test(file));
56
+ }
package/codemap/find.mjs CHANGED
@@ -1,49 +1,49 @@
1
- #!/usr/bin/env node
2
- // geml codemap find <name> [codemap-dir]
3
- //
4
- // Locate a function/class by (substring, case-insensitive) name in a built
5
- // codemap. Prints each candidate as <name> \t <doc>#<id> \t <src> — the
6
- // document + block id to open, and the true source location. NO browser: pure
7
- // stdout, so it pipes/greps. `dir` defaults to ./.geml-code-graph.
8
- //
9
- // Same index the MCP `geml_codemap_search` tool and the viewer search box use
10
- // (_index/name-lookup.json); a name with several rows is real ambiguity
11
- // (overloads / same short name across classes) — every candidate is printed.
12
- //
13
- // The matching rule and the src lookup are IMPORTED, not repeated here: this
14
- // command and `geml_codemap_search` answer the same question, and two copies of
15
- // "what counts as a match" would drift the moment one of them is tuned.
16
- import { existsSync } from "node:fs";
17
- import { join } from "node:path";
18
- import { searchNames, srcOf } from "./mcp-server.mjs";
19
-
20
- // `find x | head` closes stdout after a few lines — that is normal pipe
21
- // usage, not an error (POSIX would kill us silently with SIGPIPE; Windows
22
- // node surfaces it as an EPIPE error event): exit quietly instead of
23
- // crashing with an unhandled-error stack trace.
24
- process.stdout.on("error", (e) => { if (e.code === "EPIPE") process.exit(0); throw e; });
25
-
26
- const args = process.argv.slice(2);
27
- if (!args.length || args[0] === "--help" || args[0] === "-h") {
28
- console.error("usage: geml codemap find <name> [codemap-dir] # locate a symbol by substring name (dir defaults to ./.geml-code-graph)");
29
- process.exit(args.length ? 0 : 2);
30
- }
31
- const query = args[0];
32
- const dir = args[1] || ".geml-code-graph";
33
- const lookupPath = join(dir, "_index", "name-lookup.json");
34
- if (!existsSync(lookupPath)) {
35
- console.error(`no name-lookup at ${lookupPath} — build the codemap first (geml codemap build)`);
36
- process.exit(1);
37
- }
38
- const { names, lookup } = searchNames(dir, query);
39
- if (!names.length) { console.error(`no symbol matching "${query}"`); process.exit(1); }
40
-
41
- let n = 0;
42
- for (const name of names) {
43
- for (const c of lookup[name]) {
44
- const src = srcOf(dir, c.doc, c.id);
45
- process.stdout.write(`${name}\t${c.doc}#${c.id}${src ? `\t${src}` : ""}\n`);
46
- n++;
47
- }
48
- }
49
- console.error(`\n${n} match(es) for "${query}" across ${names.length} name(s).`);
1
+ #!/usr/bin/env node
2
+ // geml codemap find <name> [codemap-dir]
3
+ //
4
+ // Locate a function/class by (substring, case-insensitive) name in a built
5
+ // codemap. Prints each candidate as <name> \t <doc>#<id> \t <src> — the
6
+ // document + block id to open, and the true source location. NO browser: pure
7
+ // stdout, so it pipes/greps. `dir` defaults to ./.geml-code-graph.
8
+ //
9
+ // Same index the MCP `geml_codemap_search` tool and the viewer search box use
10
+ // (_index/name-lookup.json); a name with several rows is real ambiguity
11
+ // (overloads / same short name across classes) — every candidate is printed.
12
+ //
13
+ // The matching rule and the src lookup are IMPORTED, not repeated here: this
14
+ // command and `geml_codemap_search` answer the same question, and two copies of
15
+ // "what counts as a match" would drift the moment one of them is tuned.
16
+ import { existsSync } from "node:fs";
17
+ import { join } from "node:path";
18
+ import { searchNames, srcOf } from "./mcp-server.mjs";
19
+
20
+ // `find x | head` closes stdout after a few lines — that is normal pipe
21
+ // usage, not an error (POSIX would kill us silently with SIGPIPE; Windows
22
+ // node surfaces it as an EPIPE error event): exit quietly instead of
23
+ // crashing with an unhandled-error stack trace.
24
+ process.stdout.on("error", (e) => { if (e.code === "EPIPE") process.exit(0); throw e; });
25
+
26
+ const args = process.argv.slice(2);
27
+ if (!args.length || args[0] === "--help" || args[0] === "-h") {
28
+ console.error("usage: geml codemap find <name> [codemap-dir] # locate a symbol by substring name (dir defaults to ./.geml-code-graph)");
29
+ process.exit(args.length ? 0 : 2);
30
+ }
31
+ const query = args[0];
32
+ const dir = args[1] || ".geml-code-graph";
33
+ const lookupPath = join(dir, "_index", "name-lookup.json");
34
+ if (!existsSync(lookupPath)) {
35
+ console.error(`no name-lookup at ${lookupPath} — build the codemap first (geml codemap build)`);
36
+ process.exit(1);
37
+ }
38
+ const { names, lookup } = searchNames(dir, query);
39
+ if (!names.length) { console.error(`no symbol matching "${query}"`); process.exit(1); }
40
+
41
+ let n = 0;
42
+ for (const name of names) {
43
+ for (const c of lookup[name]) {
44
+ const src = srcOf(dir, c.doc, c.id);
45
+ process.stdout.write(`${name}\t${c.doc}#${c.id}${src ? `\t${src}` : ""}\n`);
46
+ n++;
47
+ }
48
+ }
49
+ console.error(`\n${n} match(es) for "${query}" across ${names.length} name(s).`);