@codechart/core 0.1.0 → 0.3.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/dist/index.js CHANGED
@@ -249,7 +249,7 @@ var SECRETS = [
249
249
  ];
250
250
  var PATH2 = /(?:^|[\s(])(?:\.{0,2}\/|~\/)[\w.-]+|[\w.-]+\/[\w.-]+\/[\w./-]+|[\w-]+\/[\w-]*\.[A-Za-z0-9]{1,5}\b/;
251
251
  var FILE = /\b[\w-]+\.(?:ts|tsx|js|mjs|cjs|jsx|py|rb|go|java|json|ya?ml|sql|md|css|html|toml|sh)\b/;
252
- var URL = /https?:\/\/|\bwww\.|\b[\w-]+\.(?:com|io|dev|net|org)\b/i;
252
+ var URL2 = /https?:\/\/|\bwww\.|\b[\w-]+\.(?:com|io|dev|net|org)\b/i;
253
253
  var LOWER_CAMEL = /\b[a-z]+[A-Z][A-Za-z0-9]*\b/g;
254
254
  var UPPER_CAMEL = /\b[A-Z][A-Za-z0-9]*[a-z0-9][A-Z][A-Za-z0-9]*\b/g;
255
255
  var ENV_VAR = /\b[A-Z][A-Z0-9]*_[A-Z0-9_]+\b/;
@@ -313,7 +313,7 @@ function camelToken(text2) {
313
313
  return lower ?? (text2.match(UPPER_CAMEL) ?? []).find((w) => !isBrand(w) && ((w.match(/[A-Z]/g) ?? []).length >= 3 || /\d/.test(w)));
314
314
  }
315
315
  var CHECKS = [
316
- ["looks like a web address", (t) => matchToken(t, URL)],
316
+ ["looks like a web address", (t) => matchToken(t, URL2)],
317
317
  ["looks like a file name or path", (t) => pathToken(t) ?? matchToken(t, FILE)],
318
318
  ["looks like code", (t) => t.includes("`") ? "`" : void 0],
319
319
  ...CODE_PATTERNS.filter((p) => p.name !== "quote").map((p) => ["looks like code", (t) => matchToken(t, p.re)]),
@@ -336,8 +336,8 @@ function plainTextIssues(text2) {
336
336
  const words = text2.replace(PLURAL_S, "$1");
337
337
  const issues = [];
338
338
  const seen = /* @__PURE__ */ new Set();
339
- for (const [what, find] of CHECKS) {
340
- const token = find(words);
339
+ for (const [what, find2] of CHECKS) {
340
+ const token = find2(words);
341
341
  if (!token || seen.has(token)) continue;
342
342
  seen.add(token);
343
343
  issues.push(`${what} ("${token}"); write it in plain words`);
@@ -702,18 +702,18 @@ function startIssues(spec, facts, issue) {
702
702
  else if (start.status === "removed") issue(["start"], "the start step cannot be removed; start where the flow begins after the plan");
703
703
  }
704
704
  function linkFlagIssues(spec, link, facts) {
705
- const found = [];
705
+ const found2 = [];
706
706
  if (spec.kind === "summary") {
707
- for (const word of ["planned", "removed"]) if (link[word]) found.push([[word], summaryOnlyExisting(word)]);
707
+ for (const word of ["planned", "removed"]) if (link[word]) found2.push([[word], summaryOnlyExisting(word)]);
708
708
  }
709
- if (link.removed && link.planned) found.push([["removed"], "a link is either planned or removed, not both"]);
709
+ if (link.removed && link.planned) found2.push([["removed"], "a link is either planned or removed, not both"]);
710
710
  const ends = [link.from, link.to];
711
711
  if (ends.some(facts.brandNew) && (link.removed || ends.some(facts.removedStep))) {
712
- found.push([[], "joins a planned step not in the code yet to something the plan removes; they never exist at the same time"]);
712
+ found2.push([[], "joins a planned step not in the code yet to something the plan removes; they never exist at the same time"]);
713
713
  } else if (link.planned && ends.some(facts.removedStep)) {
714
- found.push([["planned"], "a link to a removed step cannot be planned"]);
714
+ found2.push([["planned"], "a link to a removed step cannot be planned"]);
715
715
  }
716
- return found;
716
+ return found2;
717
717
  }
718
718
  function leavesDecision(facts, link) {
719
719
  const from = facts.byId.get(link.from);
@@ -1231,6 +1231,7 @@ var configFileSchema = z7.strictObject({
1231
1231
  auto: z7.enum(RELEASE_AUTO).optional().describe("On a release branch: suggest a release map, draw one, or do nothing (default: suggest)")
1232
1232
  }).optional(),
1233
1233
  useBuiltinRules: z7.boolean().optional(),
1234
+ ignore: z7.array(glob).optional().describe("Paths the desktop app's live map never reads, as globs, on top of .gitignore, dependencies and build output. The CLI doesn't use it."),
1234
1235
  updateCheck: z7.boolean().optional().describe("Global only: look up the newest codechart on npm at most once a day and say when there is one (default true)"),
1235
1236
  rules: z7.array(ruleSchema2).optional()
1236
1237
  });
@@ -1378,8 +1379,10 @@ function loadConfigWithSources(opts) {
1378
1379
  ...(useBuiltinRules ? builtinRules(defaults.flows) : []).map((rule) => ({ rule, source: BUILTIN }))
1379
1380
  ]);
1380
1381
  const release = releaseOf(files, sources);
1382
+ const ignore = [...global?.ignore ?? [], ...repo?.ignore ?? []];
1383
+ sources.ignore = files.filter((f) => f.file?.ignore?.length).map((f) => f.source).join(" + ") || BUILTIN;
1381
1384
  return {
1382
- config: { defaults, web, useBuiltinRules, updateCheck: global?.updateCheck !== false, release, rules: tagged.map((t) => t.rule) },
1385
+ config: { defaults, web, useBuiltinRules, updateCheck: global?.updateCheck !== false, release, ignore, rules: tagged.map((t) => t.rule) },
1383
1386
  sources,
1384
1387
  ruleSources: tagged.map((t) => t.source)
1385
1388
  };
@@ -1746,14 +1749,14 @@ function gitFileDiffs(cwd, range, rels, maxBytes) {
1746
1749
  return out;
1747
1750
  }
1748
1751
  function gitUntracked(cwd, rels) {
1749
- const found = /* @__PURE__ */ new Set();
1752
+ const found2 = /* @__PURE__ */ new Set();
1750
1753
  const wanted = new Set(rels);
1751
1754
  for (const group of chunks(rels)) {
1752
1755
  for (const f of git(cwd, ["--literal-pathspecs", "ls-files", "-z", "--others", "--exclude-standard", "--", ...group]).split("\0")) {
1753
- if (wanted.has(f)) found.add(f);
1756
+ if (wanted.has(f)) found2.add(f);
1754
1757
  }
1755
1758
  }
1756
- return found;
1759
+ return found2;
1757
1760
  }
1758
1761
 
1759
1762
  // src/rules/resolve.ts
@@ -1765,18 +1768,18 @@ function normalizePath(p, root) {
1765
1768
  const rootSlashed = root.replace(/\\/g, "/");
1766
1769
  if (DRIVE_PATH.test(slashed)) {
1767
1770
  if (!DRIVE_PATH.test(rootSlashed)) return slashed;
1768
- const relative5 = path.posix.relative(lowerDrive(rootSlashed), lowerDrive(slashed));
1769
- return isInside(relative5) ? relative5 : slashed;
1771
+ const relative6 = path.posix.relative(lowerDrive(rootSlashed), lowerDrive(slashed));
1772
+ return isInside(relative6) ? relative6 : slashed;
1770
1773
  }
1771
1774
  if (!path.posix.isAbsolute(slashed)) return slashed;
1772
- const relative4 = path.posix.relative(rootSlashed, slashed);
1773
- return isInside(relative4) ? relative4 : slashed;
1775
+ const relative5 = path.posix.relative(rootSlashed, slashed);
1776
+ return isInside(relative5) ? relative5 : slashed;
1774
1777
  }
1775
1778
  function lowerDrive(p) {
1776
1779
  return p.charAt(0).toLowerCase() + p.slice(1);
1777
1780
  }
1778
- function isInside(relative4) {
1779
- return relative4 !== "" && relative4 !== ".." && !relative4.startsWith("../");
1781
+ function isInside(relative5) {
1782
+ return relative5 !== "" && relative5 !== ".." && !relative5.startsWith("../");
1780
1783
  }
1781
1784
  function isPathRule(rule) {
1782
1785
  return rule.paths !== void 0;
@@ -2225,14 +2228,14 @@ function withLock(lock, fn, { waitMs, staleMs, sleep: wait = sleep }) {
2225
2228
  }
2226
2229
  }
2227
2230
  var currentReview = (dir, branch, slug) => listReviews(dir, branch, "all").find((f) => f.review.change.slug === slug);
2228
- function updateReview(found, change, times = DEFAULT_LOCK) {
2229
- const dir = dirname2(found.file);
2230
- const { branch, slug } = found.review.change;
2231
+ function updateReview(found2, change, times = DEFAULT_LOCK) {
2232
+ const dir = dirname2(found2.file);
2233
+ const { branch, slug } = found2.review.change;
2231
2234
  return withLock(
2232
2235
  reviewLock(dir, branch, slug),
2233
2236
  () => {
2234
2237
  const current = currentReview(dir, branch, slug);
2235
- if (!current) throw new Error(`The review notes in ${found.file} can't be read.`);
2238
+ if (!current) throw new Error(`The review notes in ${found2.file} can't be read.`);
2236
2239
  const next = change(current.review);
2237
2240
  if (next !== current.review) writeReview(current.file, next);
2238
2241
  return next;
@@ -2261,8 +2264,8 @@ function unreadableReviews(dir) {
2261
2264
  }
2262
2265
  var sameName = (r, name) => r.change.slug === name || (r.change.title ?? r.change.slug).toLowerCase() === name.toLowerCase();
2263
2266
  function findChange(dir, branch, name, exact = false, which = "tech") {
2264
- const found = listReviews(dir, branch, which).find((f) => name === void 0 || (exact ? f.review.change.slug === name : sameName(f.review, name)));
2265
- if (found) return found;
2267
+ const found2 = listReviews(dir, branch, which).find((f) => name === void 0 || (exact ? f.review.change.slug === name : sameName(f.review, name)));
2268
+ if (found2) return found2;
2266
2269
  const damaged = listReviews(dir, branch, which).length === 0 ? unreadableReviews(dir)[0] : void 0;
2267
2270
  if (damaged) throw new Error(`${damaged} can't be read (damaged): ask your agent to draw the map again.`);
2268
2271
  const where = branch ? ` on branch ${branch}` : " here";
@@ -2509,15 +2512,15 @@ function repoPathResolver(root, at, cwd) {
2509
2512
  function load(c, path2) {
2510
2513
  const hit = c.cache.get(path2);
2511
2514
  if (hit) return hit;
2512
- const { path: found, value } = withCwd(c, path2, (p) => read(c, p), (v) => v === null);
2513
- const target = targetOf(c, found);
2514
- const loaded = { path: found, lines: value, secret: looksSecret(found) || target !== void 0 && looksSecret(target) };
2515
- c.cache.set(path2, loaded);
2516
- return loaded;
2515
+ const { path: found2, value } = withCwd(c, path2, (p) => read(c, p), (v) => v === null);
2516
+ const target = targetOf(c, found2);
2517
+ const loaded2 = { path: found2, lines: value, secret: looksSecret(found2) || target !== void 0 && looksSecret(target) };
2518
+ c.cache.set(path2, loaded2);
2519
+ return loaded2;
2517
2520
  }
2518
2521
  function locate(c, path2) {
2519
- const { path: found, value } = withCwd(c, path2, (p) => present(c, p), (v) => v === false);
2520
- return typeof value === "boolean" ? { path: found, found: value } : value;
2522
+ const { path: found2, value } = withCwd(c, path2, (p) => present(c, p), (v) => v === false);
2523
+ return typeof value === "boolean" ? { path: found2, found: value } : value;
2521
2524
  }
2522
2525
  var MAX_LISTED_FILES = 2e5;
2523
2526
  function likelyPath(c, path2) {
@@ -2568,8 +2571,8 @@ function resolveAnchor(source, match, c) {
2568
2571
  if (!m) return { error: `${source} not found (not path:line or path:start-end)` };
2569
2572
  [, path2, a, b] = m;
2570
2573
  }
2571
- const loaded = load(c, path2);
2572
- const lines = loaded.lines;
2574
+ const loaded2 = load(c, path2);
2575
+ const lines = loaded2.lines;
2573
2576
  const notFound = (why) => ({ error: `${source} not found (${why})` });
2574
2577
  if (lines === null) {
2575
2578
  const where = c.at ? `file does not exist at ${c.at.slice(0, 12)}` : "file does not exist";
@@ -2577,7 +2580,7 @@ function resolveAnchor(source, match, c) {
2577
2580
  return { error: `${source} not found (${where}; ${hint})`, missing: { path: path2, detail: `${where} (${hint})` } };
2578
2581
  }
2579
2582
  if (!Array.isArray(lines)) return lines;
2580
- if (match !== void 0) return findMatch(loaded.path, match, lines, loaded.secret);
2583
+ if (match !== void 0) return findMatch(loaded2.path, match, lines, loaded2.secret);
2581
2584
  const start = Number(a);
2582
2585
  const end = b === void 0 ? start : Number(b);
2583
2586
  if (start < 1) return notFound("lines start at 1");
@@ -2585,9 +2588,9 @@ function resolveAnchor(source, match, c) {
2585
2588
  if (end > lines.length) return notFound(`file has ${lines.length} lines`);
2586
2589
  return {
2587
2590
  snippet: {
2588
- source: loaded.path === path2 ? source : `${loaded.path}:${a}${b === void 0 ? "" : `-${b}`}`,
2591
+ source: loaded2.path === path2 ? source : `${loaded2.path}:${a}${b === void 0 ? "" : `-${b}`}`,
2589
2592
  startLine: start,
2590
- lines: shownLines(loaded.secret, lines.slice(start - 1, Math.min(end, start - 1 + SNIPPET_MAX_LINES)), lines)
2593
+ lines: shownLines(loaded2.secret, lines.slice(start - 1, Math.min(end, start - 1 + SNIPPET_MAX_LINES)), lines)
2591
2594
  }
2592
2595
  };
2593
2596
  }
@@ -2717,23 +2720,23 @@ function checkNode(c, spec, node, diff) {
2717
2720
  const needed = mustExist(spec, node);
2718
2721
  const where = locate(c, node.path);
2719
2722
  if ("error" in where) return { problem: { short: where.error.endsWith(" is outside the repo") ? "outside the repo" : "file unreadable", detail: where.error } };
2720
- const found = where.found ? repoPath(c.root, where.path) : void 0;
2723
+ const found2 = where.found ? repoPath(c.root, where.path) : void 0;
2721
2724
  if (!where.found && needed) {
2722
2725
  const at = c.at ? ` at ${c.at.slice(0, 12)}` : "";
2723
2726
  return { problem: { short: "file missing", detail: `${node.path} does not exist${at}${likelyPath(c, node.path)}` } };
2724
2727
  }
2725
2728
  if (diff) {
2726
2729
  const problem = diffProblem(c, spec, node, where.path, diff);
2727
- if (problem) return { found, problem };
2730
+ if (problem) return { found: found2, problem };
2728
2731
  }
2729
2732
  const explaining = spec.kind === "explain";
2730
- if (!needed || !where.found || node.match === void 0 && !explaining) return { found };
2731
- const loaded = load(c, where.path);
2732
- if (loaded.lines === null || !Array.isArray(loaded.lines)) {
2733
- if (node.match === void 0) return { found };
2734
- return { found, problem: { short: "file unreadable", detail: loaded.lines?.error ?? `${where.path} does not exist` } };
2733
+ if (!needed || !where.found || node.match === void 0 && !explaining) return { found: found2 };
2734
+ const loaded2 = load(c, where.path);
2735
+ if (loaded2.lines === null || !Array.isArray(loaded2.lines)) {
2736
+ if (node.match === void 0) return { found: found2 };
2737
+ return { found: found2, problem: { short: "file unreadable", detail: loaded2.lines?.error ?? `${where.path} does not exist` } };
2735
2738
  }
2736
- return { found, ...matchAndBlock(loaded.path, loaded.lines, loaded.secret, node.match, explaining) };
2739
+ return { found: found2, ...matchAndBlock(loaded2.path, loaded2.lines, loaded2.secret, node.match, explaining) };
2737
2740
  }
2738
2741
  function matchAndBlock(path2, lines, secret, needle, explaining) {
2739
2742
  let match;
@@ -2745,8 +2748,8 @@ function matchAndBlock(path2, lines, secret, needle, explaining) {
2745
2748
  return { match, block: explaining ? blockOf(path2, lines, match?.startLine, secret) : void 0 };
2746
2749
  }
2747
2750
  function looseText(c, path2) {
2748
- const loaded = load(c, path2);
2749
- return loaded.lines !== null && Array.isArray(loaded.lines) ? loose(loaded.lines.join("\n")) : void 0;
2751
+ const loaded2 = load(c, path2);
2752
+ return loaded2.lines !== null && Array.isArray(loaded2.lines) ? loose(loaded2.lines.join("\n")) : void 0;
2750
2753
  }
2751
2754
  function fieldWarnings(c, spec) {
2752
2755
  const warnings = [];
@@ -2797,8 +2800,8 @@ function checkMapNodes(spec, root, opts = {}) {
2797
2800
  continue;
2798
2801
  }
2799
2802
  result.checked++;
2800
- const { problem, found, match, block } = checkNode(c, spec, { ...node, path: node.path }, opts.diff);
2801
- if (found) result.found.set(node.id, found);
2803
+ const { problem, found: found2, match, block } = checkNode(c, spec, { ...node, path: node.path }, opts.diff);
2804
+ if (found2) result.found.set(node.id, found2);
2802
2805
  if (match) result.matches.set(node.id, match);
2803
2806
  if (block) result.blocks.set(node.id, block);
2804
2807
  if (problem) result.mismatches.push({ id: node.id, label: plainLabel(node), ...problem });
@@ -2826,8 +2829,8 @@ function covered(c, file, paths) {
2826
2829
  const where = locate(c, file);
2827
2830
  return "found" in where && !where.found;
2828
2831
  }
2829
- function uncoveredFiles(c, spec, diff, found, ignored = () => false) {
2830
- const paths = spec.nodes.flatMap((n) => n.path === void 0 ? [] : found.has(n.id) ? [found.get(n.id)] : nodeRepoPaths(c, n.path));
2832
+ function uncoveredFiles(c, spec, diff, found2, ignored = () => false) {
2833
+ const paths = spec.nodes.flatMap((n) => n.path === void 0 ? [] : found2.has(n.id) ? [found2.get(n.id)] : nodeRepoPaths(c, n.path));
2831
2834
  const omitted = spec.omitted ?? [];
2832
2835
  return diff.files.filter((f) => !ignored(f) && !omitted.some((o) => explains(o, f)) && !covered(c, f, paths));
2833
2836
  }
@@ -3142,11 +3145,890 @@ function removeSkill(dir, files) {
3142
3145
  rmdirSync(dir);
3143
3146
  return `removed skill: ${dir}`;
3144
3147
  }
3148
+
3149
+ // src/code/model.ts
3150
+ import { z as z9 } from "zod";
3151
+ var LANGS = ["typescript", "javascript", "python", "html", "css", "sql", "bash", "yaml", "json"];
3152
+ var pointSchema = z9.object({ line: z9.number().int().min(1), column: z9.number().int().min(0) });
3153
+ var codeRangeSchema = z9.object({ start: pointSchema, end: pointSchema });
3154
+ var fileInfoSchema = z9.object({
3155
+ path: z9.string().min(1),
3156
+ lang: z9.enum(LANGS),
3157
+ /** sha256 of the file's text as UTF-8, hex. */
3158
+ hash: z9.string().regex(/^[0-9a-f]{64}$/)
3159
+ });
3160
+ var SYMBOL_KINDS = ["class", "interface", "type", "enum", "function", "method", "module", "constant"];
3161
+ var codeSymbolSchema = z9.object({
3162
+ /** `symbolId(file, path, kind)`; a repeated identity in one file gets `~2`, `~3`… in source order. */
3163
+ id: z9.string().min(1),
3164
+ file: z9.string().min(1),
3165
+ /** Names from the outermost definition in, e.g. `['PaymentService', 'charge']`. */
3166
+ path: z9.array(z9.string().min(1)).min(1),
3167
+ kind: z9.enum(SYMBOL_KINDS),
3168
+ range: codeRangeSchema
3169
+ });
3170
+ var importedNameSchema = z9.object({
3171
+ /** The name the other module exports: `default`, `*` for the whole module, or the export's name. */
3172
+ imported: z9.string().min(1),
3173
+ /** The binding in this file; for a re-export, the name this file exports it as (`*` for `export *`). */
3174
+ local: z9.string().min(1),
3175
+ typeOnly: z9.boolean().optional(),
3176
+ /** The repo file that defines it, barrels followed; absent when not proven. */
3177
+ definedIn: z9.string().min(1).optional()
3178
+ });
3179
+ var IMPORT_KINDS = ["import", "export", "require", "dynamic"];
3180
+ var importSchema = z9.object({
3181
+ file: z9.string().min(1),
3182
+ spec: z9.string(),
3183
+ resolved: z9.string().min(1).optional(),
3184
+ status: z9.enum(["resolved", "unknown", "external"]),
3185
+ /** `export` is a re-export (`export … from`); `require` and `dynamic` (`import()`) name no bindings. */
3186
+ kind: z9.enum(IMPORT_KINDS),
3187
+ /** `import type`, `export type`, `typeof import()`. */
3188
+ typeOnly: z9.boolean().optional(),
3189
+ /** Absent for `require` and `import()`; empty for a side-effect `import 'x'`. */
3190
+ names: z9.array(importedNameSchema).optional(),
3191
+ range: codeRangeSchema
3192
+ });
3193
+ var callRefSchema = z9.object({
3194
+ from: z9.string().min(1),
3195
+ name: z9.string().min(1),
3196
+ to: z9.string().min(1).optional(),
3197
+ evidence: z9.enum(["resolved", "name-only"]),
3198
+ range: codeRangeSchema
3199
+ });
3200
+ var symbolId = (file, path2, kind) => `${file}::${path2.join(".")}::${kind}`;
3201
+
3202
+ // src/code/languages.ts
3203
+ var BY_EXTENSION = {
3204
+ ts: "typescript",
3205
+ mts: "typescript",
3206
+ cts: "typescript",
3207
+ tsx: "typescript",
3208
+ js: "javascript",
3209
+ mjs: "javascript",
3210
+ cjs: "javascript",
3211
+ jsx: "javascript",
3212
+ py: "python",
3213
+ pyi: "python",
3214
+ html: "html",
3215
+ htm: "html",
3216
+ css: "css",
3217
+ sql: "sql",
3218
+ sh: "bash",
3219
+ bash: "bash",
3220
+ yml: "yaml",
3221
+ yaml: "yaml",
3222
+ json: "json"
3223
+ };
3224
+ var extension = (path2) => {
3225
+ const base = path2.slice(path2.lastIndexOf("/") + 1);
3226
+ const dot = base.lastIndexOf(".");
3227
+ return dot > 0 ? base.slice(dot + 1).toLowerCase() : "";
3228
+ };
3229
+ function langOf(path2) {
3230
+ return BY_EXTENSION[extension(path2)];
3231
+ }
3232
+ function grammarOf(path2) {
3233
+ const ext = extension(path2);
3234
+ if (ext === "tsx") return "tsx";
3235
+ const lang = BY_EXTENSION[ext];
3236
+ return lang === "typescript" || lang === "javascript" ? lang : void 0;
3237
+ }
3238
+
3239
+ // src/code/parse.ts
3240
+ import { createHash as createHash3 } from "crypto";
3241
+
3242
+ // src/code/grammars.ts
3243
+ import { existsSync as existsSync5, readFileSync as readFileSync3 } from "fs";
3244
+ import { createRequire } from "module";
3245
+ import { fileURLToPath } from "url";
3246
+
3247
+ // src/code/grammar-assets.ts
3248
+ var GRAMMAR_ASSETS = {
3249
+ "tree-sitter-javascript.wasm": "tree-sitter-javascript/tree-sitter-javascript.wasm",
3250
+ "tree-sitter-typescript.wasm": "tree-sitter-typescript/tree-sitter-typescript.wasm",
3251
+ "tree-sitter-tsx.wasm": "tree-sitter-typescript/tree-sitter-tsx.wasm",
3252
+ "javascript-tags.scm": "tree-sitter-javascript/queries/tags.scm",
3253
+ "typescript-tags.scm": "tree-sitter-typescript/queries/tags.scm"
3254
+ };
3255
+
3256
+ // src/code/symbols.ts
3257
+ var KINDS = new Set(SYMBOL_KINDS);
3258
+ var nodeRange = (node) => ({
3259
+ start: { line: node.startPosition.row + 1, column: node.startPosition.column },
3260
+ end: { line: node.endPosition.row + 1, column: node.endPosition.column }
3261
+ });
3262
+ function errorNodes(node, out = []) {
3263
+ if (node.isError || node.isMissing) {
3264
+ out.push(node);
3265
+ return out;
3266
+ }
3267
+ for (let i = 0; i < node.childCount; i++) {
3268
+ const child = node.child(i);
3269
+ if (child?.hasError || child?.isMissing) errorNodes(child, out);
3270
+ }
3271
+ return out;
3272
+ }
3273
+ var WRAPPERS = /* @__PURE__ */ new Set(["export_statement", "ambient_declaration"]);
3274
+ function scopeOf(node) {
3275
+ let parent = node.parent;
3276
+ while (parent && WRAPPERS.has(parent.type)) parent = parent.parent;
3277
+ return parent?.id;
3278
+ }
3279
+ var touches = (def, err) => err.startIndex === err.endIndex ? def.startIndex <= err.startIndex && err.startIndex <= def.endIndex : err.startIndex < def.endIndex && err.endIndex > def.startIndex;
3280
+ function definitions(tree, tags) {
3281
+ const seen = /* @__PURE__ */ new Set();
3282
+ const defs = [];
3283
+ for (const match of tags.matches(tree.rootNode)) {
3284
+ const def = match.captures.find((c) => c.name.startsWith("definition."));
3285
+ const name = match.captures.find((c) => c.name === "name");
3286
+ const kind = def?.name.slice("definition.".length);
3287
+ if (!def || !name || !kind || !KINDS.has(kind) || seen.has(def.node.id)) continue;
3288
+ seen.add(def.node.id);
3289
+ defs.push({ node: def.node, name: name.node.text, kind });
3290
+ }
3291
+ return defs.sort((a, b) => a.node.startIndex - b.node.startIndex || b.node.endIndex - a.node.endIndex);
3292
+ }
3293
+ function nest(defs, errors) {
3294
+ const stack = [];
3295
+ return defs.map((d) => {
3296
+ while (stack.length && stack[stack.length - 1].node.endIndex < d.node.endIndex) stack.pop();
3297
+ const parent = stack[stack.length - 1];
3298
+ const nested = { ...d, path: [...parent?.path ?? [], ...d.name.split(".")], broken: (parent?.broken ?? false) || errors.some((e) => touches(d.node, e)) };
3299
+ stack.push(nested);
3300
+ return nested;
3301
+ });
3302
+ }
3303
+ function extractSymbols(file, tree, tags) {
3304
+ const errors = tree.rootNode.hasError ? errorNodes(tree.rootNode) : [];
3305
+ const symbols = [];
3306
+ const broken = /* @__PURE__ */ new Set();
3307
+ const byId = /* @__PURE__ */ new Map();
3308
+ for (const def of nest(definitions(tree, tags), errors)) {
3309
+ const base = symbolId(file, def.path, def.kind);
3310
+ const prev = byId.get(base);
3311
+ if (prev?.signature && prev.scope === scopeOf(def.node)) {
3312
+ prev.symbol.range = { start: prev.symbol.range.start, end: nodeRange(def.node).end };
3313
+ prev.signature = def.node.type.endsWith("_signature");
3314
+ if (def.broken) broken.add(prev.symbol.id);
3315
+ continue;
3316
+ }
3317
+ const id = prev ? `${base}~${++prev.count}` : base;
3318
+ const symbol = { id, file, path: def.path, kind: def.kind, range: nodeRange(def.node) };
3319
+ byId.set(base, { symbol, signature: def.node.type.endsWith("_signature"), scope: scopeOf(def.node), count: prev?.count ?? 1 });
3320
+ symbols.push(symbol);
3321
+ if (def.broken) broken.add(id);
3322
+ }
3323
+ return { symbols, broken, errors: errors.map(nodeRange) };
3324
+ }
3325
+
3326
+ // src/code/imports.ts
3327
+ var IMPORTS_QUERY = `
3328
+ (import_statement) @import
3329
+ (export_statement) @export
3330
+ (call_expression function: (identifier) @fn arguments: (arguments . [(string) (template_string)] @src) (#eq? @fn "require")) @require
3331
+ (call_expression function: (import) arguments: (arguments . [(string) (template_string)] @src)) @dynamic
3332
+ (member_expression object: (identifier) @cjs (#match? @cjs "^(module|exports)$"))
3333
+ `;
3334
+ var STATEMENTS = /* @__PURE__ */ new Set(["import", "export"]);
3335
+ function literal(node) {
3336
+ if (node?.type === "string") return node.text.slice(1, -1);
3337
+ if (node?.type === "template_string" && !node.namedChildren.some((c) => c?.type === "template_substitution")) return node.text.slice(1, -1);
3338
+ return void 0;
3339
+ }
3340
+ var nameOf = (node) => literal(node) ?? node.text;
3341
+ var hasToken = (node, token) => node.children.some((c) => c?.type === token);
3342
+ function specifierNames(list, typeOnly) {
3343
+ return list.namedChildren.flatMap((s) => {
3344
+ const name = s?.childForFieldName("name");
3345
+ if (!s || !name) return [];
3346
+ const alias = s.childForFieldName("alias");
3347
+ const entry = { imported: nameOf(name), local: nameOf(alias ?? name) };
3348
+ return typeOnly || hasToken(s, "type") ? [{ ...entry, typeOnly: true }] : [entry];
3349
+ });
3350
+ }
3351
+ function importClauseNames(clause, typeOnly) {
3352
+ const flag = typeOnly ? { typeOnly: true } : {};
3353
+ return clause.namedChildren.flatMap((c) => {
3354
+ if (c?.type === "identifier") return [{ imported: "default", local: c.text, ...flag }];
3355
+ const ns = c?.type === "namespace_import" ? c.namedChildren[0] : void 0;
3356
+ if (ns) return [{ imported: "*", local: ns.text, ...flag }];
3357
+ return c?.type === "named_imports" ? specifierNames(c, typeOnly) : [];
3358
+ });
3359
+ }
3360
+ function fromImport(node) {
3361
+ const required = node.namedChildren.find((c) => c?.type === "import_require_clause");
3362
+ if (required) {
3363
+ const spec2 = literal(required.childForFieldName("source"));
3364
+ return spec2 === void 0 ? void 0 : { spec: spec2, kind: "require", range: nodeRange(node) };
3365
+ }
3366
+ const spec = literal(node.childForFieldName("source"));
3367
+ if (spec === void 0) return void 0;
3368
+ const typeOnly = hasToken(node, "type");
3369
+ const clause = node.namedChildren.find((c) => c?.type === "import_clause");
3370
+ const names = clause ? importClauseNames(clause, typeOnly) : [];
3371
+ return { spec, kind: "import", ...typeOnly && { typeOnly }, names, range: nodeRange(node) };
3372
+ }
3373
+ function reexportNames(node, typeOnly) {
3374
+ const clause = node.namedChildren.find((c) => c?.type === "export_clause");
3375
+ if (clause) return specifierNames(clause, typeOnly);
3376
+ const ns = node.namedChildren.find((c) => c?.type === "namespace_export")?.namedChildren[0];
3377
+ const entry = { imported: "*", local: ns ? nameOf(ns) : "*" };
3378
+ return [typeOnly ? { ...entry, typeOnly } : entry];
3379
+ }
3380
+ var DECLARED_NAMES = {
3381
+ lexical_declaration: (n) => n.namedChildren.flatMap((d) => d?.type === "variable_declarator" ? bindings(d.childForFieldName("name")) : [])
3382
+ };
3383
+ DECLARED_NAMES.variable_declaration = DECLARED_NAMES.lexical_declaration;
3384
+ function bindings(node) {
3385
+ if (!node) return [];
3386
+ if (node.type === "identifier" || node.type === "shorthand_property_identifier_pattern") return [node];
3387
+ if (node.type === "assignment_pattern" || node.type === "object_assignment_pattern") return bindings(node.childForFieldName("left"));
3388
+ const value = node.type === "pair_pattern" ? node.childForFieldName("value") : void 0;
3389
+ if (value) return bindings(value);
3390
+ return node.namedChildren.flatMap((c) => c && c.type !== "property_identifier" ? bindings(c) : []);
3391
+ }
3392
+ function outermost(node) {
3393
+ let name = node;
3394
+ while (name.type === "nested_identifier" || name.type === "member_expression") name = name.childForFieldName("object") ?? name.namedChildren[0];
3395
+ return name;
3396
+ }
3397
+ function declarationNames(decl) {
3398
+ const inner = decl.type === "ambient_declaration" ? decl.namedChildren[0] : decl;
3399
+ if (!inner) return [];
3400
+ const many = DECLARED_NAMES[inner.type];
3401
+ if (many) return many(inner).map((n) => n.text);
3402
+ const name = inner.type === "import_alias" ? inner.namedChildren[0] : inner.childForFieldName("name");
3403
+ return name && name.type !== "string" ? [outermost(name).text] : [];
3404
+ }
3405
+ function localExports(node) {
3406
+ if (hasToken(node, "=")) return void 0;
3407
+ if (hasToken(node, "default")) {
3408
+ const value = node.childForFieldName("value");
3409
+ return [value?.type === "identifier" ? { name: "default", local: value.text } : { name: "default" }];
3410
+ }
3411
+ const decl = node.childForFieldName("declaration");
3412
+ if (decl) return declarationNames(decl).map((name) => ({ name }));
3413
+ const clause = node.namedChildren.find((c) => c?.type === "export_clause");
3414
+ return clause ? specifierNames(clause, false).map((s) => ({ name: s.local, local: s.imported })) : [];
3415
+ }
3416
+ function fromCall(node, kind, src) {
3417
+ const spec = literal(src);
3418
+ if (spec === void 0) return void 0;
3419
+ let up = node.parent;
3420
+ while (up && up.type !== "type_query" && !up.type.endsWith("statement")) up = up.parent;
3421
+ return { spec, kind, ...up?.type === "type_query" && { typeOnly: true }, range: nodeRange(node) };
3422
+ }
3423
+ function extractImports(file, tree, query) {
3424
+ const imports = [];
3425
+ const exports = { names: [], complete: !tree.rootNode.hasError };
3426
+ for (const match of query.matches(tree.rootNode)) {
3427
+ const [main] = match.captures.filter((c) => c.name !== "fn" && c.name !== "src");
3428
+ const src = match.captures.find((c) => c.name === "src")?.node;
3429
+ if (!main || main.node.hasError || STATEMENTS.has(main.name) && main.node.parent?.type !== "program") continue;
3430
+ const node = main.node;
3431
+ let spec;
3432
+ if (main.name === "cjs") exports.complete = false;
3433
+ else if (main.name === "import") spec = fromImport(node);
3434
+ else if (main.name === "export") {
3435
+ const source = literal(node.childForFieldName("source"));
3436
+ const typeOnly = hasToken(node, "type");
3437
+ if (source !== void 0) spec = { spec: source, kind: "export", ...typeOnly && { typeOnly }, names: reexportNames(node, typeOnly), range: nodeRange(node) };
3438
+ else {
3439
+ const names = localExports(node);
3440
+ if (names) exports.names.push(...names);
3441
+ else exports.complete = false;
3442
+ }
3443
+ } else if (src) spec = fromCall(node, main.name, src);
3444
+ if (spec) imports.push({ ...spec, file });
3445
+ }
3446
+ return { imports, exports };
3447
+ }
3448
+
3449
+ // src/code/grammars.ts
3450
+ var EXTRA_JS = `
3451
+ (field_definition
3452
+ property: [(property_identifier) (private_property_identifier)] @name
3453
+ value: [(arrow_function) (function_expression)]) @definition.method
3454
+ `;
3455
+ var EXTRA_TS = `
3456
+ (type_alias_declaration name: (type_identifier) @name) @definition.type
3457
+ (enum_declaration name: (identifier) @name) @definition.enum
3458
+ (internal_module name: [(identifier) (nested_identifier)] @name) @definition.module
3459
+ (public_field_definition
3460
+ name: [(property_identifier) (private_property_identifier)] @name
3461
+ value: [(arrow_function) (function_expression)]) @definition.method
3462
+ `;
3463
+ var WASM = {
3464
+ javascript: "tree-sitter-javascript.wasm",
3465
+ typescript: "tree-sitter-typescript.wasm",
3466
+ tsx: "tree-sitter-tsx.wasm"
3467
+ };
3468
+ function assetPath(name) {
3469
+ const built = fileURLToPath(new URL(`./grammars/${name}`, import.meta.url));
3470
+ if (existsSync5(built)) return built;
3471
+ return createRequire(import.meta.url).resolve(GRAMMAR_ASSETS[name]);
3472
+ }
3473
+ function tagsSource(grammar) {
3474
+ const js = readFileSync3(assetPath("javascript-tags.scm"), "utf8");
3475
+ if (grammar === "javascript") return js + EXTRA_JS;
3476
+ return js + readFileSync3(assetPath("typescript-tags.scm"), "utf8") + EXTRA_TS;
3477
+ }
3478
+ var runtime;
3479
+ var loaded = /* @__PURE__ */ new Map();
3480
+ var loadRuntime = () => runtime ??= import("web-tree-sitter").then(async (ts) => {
3481
+ await ts.Parser.init();
3482
+ return ts;
3483
+ });
3484
+ async function load2(grammar) {
3485
+ const ts = await loadRuntime();
3486
+ const language = await ts.Language.load(assetPath(WASM[grammar]));
3487
+ const parser = new ts.Parser();
3488
+ parser.setLanguage(language);
3489
+ return { parser, tags: new ts.Query(language, tagsSource(grammar)), imports: new ts.Query(language, IMPORTS_QUERY) };
3490
+ }
3491
+ function loadGrammar(grammar) {
3492
+ let entry = loaded.get(grammar);
3493
+ if (!entry) {
3494
+ entry = load2(grammar);
3495
+ loaded.set(grammar, entry);
3496
+ }
3497
+ return entry;
3498
+ }
3499
+
3500
+ // src/code/parse.ts
3501
+ function keepLastGood(extracted, lastGood) {
3502
+ if (!extracted.errors.length) return { symbols: extracted.symbols, kept: [] };
3503
+ const good = new Map((lastGood ?? []).map((s) => [s.id, s]));
3504
+ const symbols = extracted.symbols.filter((s) => !extracted.broken.has(s.id) || good.has(s.id));
3505
+ const present2 = new Set(symbols.map((s) => s.id));
3506
+ const kept = [...good.values()].filter((s) => !present2.has(s.id));
3507
+ return { symbols: [...symbols, ...kept], kept: kept.map((s) => s.id) };
3508
+ }
3509
+ async function parseCode(path2, text2, lastGood) {
3510
+ const lang = langOf(path2);
3511
+ if (!lang) return void 0;
3512
+ const file = { path: path2, lang, hash: createHash3("sha256").update(text2).digest("hex") };
3513
+ const grammar = grammarOf(path2);
3514
+ if (!grammar) return { file, symbols: [], parseErrors: [], kept: [], imports: [], exports: { names: [], complete: false } };
3515
+ const { parser, tags, imports: query } = await loadGrammar(grammar);
3516
+ const tree = parser.parse(text2);
3517
+ if (!tree) throw new Error(`tree-sitter returned no tree for ${path2}`);
3518
+ try {
3519
+ const extracted = extractSymbols(path2, tree, tags);
3520
+ const { imports, exports } = extractImports(path2, tree, query);
3521
+ return {
3522
+ file,
3523
+ ...keepLastGood(extracted, lastGood),
3524
+ parseErrors: extracted.errors,
3525
+ imports: imports.map((i) => ({ ...i, status: "unknown" })),
3526
+ exports
3527
+ };
3528
+ } finally {
3529
+ tree.delete();
3530
+ }
3531
+ }
3532
+
3533
+ // src/code/repo.ts
3534
+ import { lstatSync as lstatSync4 } from "fs";
3535
+ import { join as join8 } from "path";
3536
+ import picomatch4 from "picomatch";
3537
+
3538
+ // src/code/resolve/link.ts
3539
+ var isStar = (i) => i.kind === "export" && (i.names ?? []).some((n) => n.local === "*");
3540
+ function through(files, imp, imported, seen) {
3541
+ if (imp.status !== "resolved" || !imp.resolved) return "unknown";
3542
+ return imported === "*" ? { file: imp.resolved, binding: "*" } : find(files, imp.resolved, imported, seen);
3543
+ }
3544
+ function viaStars(files, parsed, name, seen) {
3545
+ const hits = /* @__PURE__ */ new Map();
3546
+ let unsure = !parsed.exports.complete;
3547
+ for (const imp of parsed.imports.filter(isStar)) {
3548
+ const found2 = through(files, imp, name, seen);
3549
+ if (found2 === "unknown") unsure = true;
3550
+ else if (found2 !== "none") hits.set(`${found2.file}\0${found2.binding}`, found2);
3551
+ }
3552
+ if (hits.size > 1 || unsure) return "unknown";
3553
+ return [...hits.values()][0] ?? "none";
3554
+ }
3555
+ function binding(parsed, kind, local) {
3556
+ for (const imp of parsed.imports) {
3557
+ const name = imp.kind === kind ? imp.names?.find((n) => n.local === local) : void 0;
3558
+ if (name) return { imp, imported: name.imported };
3559
+ }
3560
+ return void 0;
3561
+ }
3562
+ function find(files, file, name, seen) {
3563
+ const key = `${file}\0${name}`;
3564
+ if (seen.has(key)) return "none";
3565
+ seen.add(key);
3566
+ const parsed = files.get(file);
3567
+ if (!parsed) return "unknown";
3568
+ const own = parsed.exports.names.find((e) => e.name === name);
3569
+ if (own) {
3570
+ const imported = own.local === void 0 ? void 0 : binding(parsed, "import", own.local);
3571
+ return imported ? through(files, imported.imp, imported.imported, seen) : { file, binding: own.local ?? name };
3572
+ }
3573
+ const reexport = binding(parsed, "export", name);
3574
+ if (reexport) return through(files, reexport.imp, reexport.imported, seen);
3575
+ if (name === "default") return parsed.exports.complete ? "none" : "unknown";
3576
+ return viaStars(files, parsed, name, seen);
3577
+ }
3578
+ function createTracer(files) {
3579
+ const memo = /* @__PURE__ */ new Map();
3580
+ return (file, name) => {
3581
+ const key = `${file}\0${name}`;
3582
+ let found2 = memo.get(key);
3583
+ if (!found2) memo.set(key, found2 = find(files, file, name, /* @__PURE__ */ new Set()));
3584
+ return found2;
3585
+ };
3586
+ }
3587
+ function withDefinitions(imp, trace) {
3588
+ if (!imp.names) return imp;
3589
+ const names = imp.names.map((stated) => {
3590
+ const name = { ...stated };
3591
+ delete name.definedIn;
3592
+ if (imp.status !== "resolved" || !imp.resolved || name.local === "*") return name;
3593
+ const found2 = name.imported === "*" ? { file: imp.resolved, binding: "*" } : trace(imp.resolved, name.imported);
3594
+ return typeof found2 === "object" ? { ...name, definedIn: found2.file } : name;
3595
+ });
3596
+ return { ...imp, names };
3597
+ }
3598
+ function linkImports(files, resolver) {
3599
+ const resolved = files.map((f) => ({
3600
+ ...f,
3601
+ imports: f.imports.map((stated) => {
3602
+ const imp = { ...stated, ...resolver.resolve(f.file.path, stated.spec, stated.kind) };
3603
+ if (imp.status !== "resolved") delete imp.resolved;
3604
+ return imp;
3605
+ })
3606
+ }));
3607
+ const trace = createTracer(new Map(resolved.map((f) => [f.file.path, f])));
3608
+ return resolved.map((f) => ({ ...f, imports: f.imports.map((i) => withDefinitions(i, trace)) }));
3609
+ }
3610
+
3611
+ // src/code/resolve/resolver.ts
3612
+ import { builtinModules } from "module";
3613
+
3614
+ // src/code/resolve/files.ts
3615
+ import { posix as posix2 } from "path";
3616
+ var dirOf = (path2) => {
3617
+ const slash = path2.lastIndexOf("/");
3618
+ return slash < 0 ? "" : path2.slice(0, slash);
3619
+ };
3620
+ function joinRepo(dir, rel) {
3621
+ if (rel.startsWith("/")) return void 0;
3622
+ const path2 = posix2.normalize(posix2.join(dir || ".", rel)).replace(/\/$/, "");
3623
+ if (path2 === ".." || path2.startsWith("../")) return void 0;
3624
+ return path2 === "." ? "" : path2;
3625
+ }
3626
+ var isRelative = (spec) => spec === "." || spec === ".." || spec.startsWith("./") || spec.startsWith("../");
3627
+ var isJsFile = (path2) => /\.[mc]?jsx?$/.test(path2);
3628
+ var TS_ORDER = [".ts", ".tsx", ".js", ".jsx", ".d.ts", ".json"];
3629
+ var JS_ORDER = [".js", ".jsx", ".json", ".ts", ".tsx", ".d.ts"];
3630
+ var EMITTED = {
3631
+ ".js": [".ts", ".tsx"],
3632
+ ".jsx": [".tsx"],
3633
+ ".mjs": [".mts"],
3634
+ ".cjs": [".cts"]
3635
+ };
3636
+ function resolveFile(files, path2, fromJs) {
3637
+ const ext = posix2.extname(path2);
3638
+ const sources = EMITTED[ext];
3639
+ if (sources && !(fromJs && files.has(path2))) {
3640
+ const stem = path2.slice(0, -ext.length);
3641
+ const source = sources.map((s) => stem + s).find((p) => files.has(p));
3642
+ if (source) return source;
3643
+ }
3644
+ if (files.has(path2)) return path2;
3645
+ if (sources) {
3646
+ const declaration = `${path2.slice(0, -ext.length)}.d${ext.replace("js", "ts")}`;
3647
+ if (files.has(declaration)) return declaration;
3648
+ }
3649
+ const order = fromJs ? JS_ORDER : TS_ORDER;
3650
+ const prefix = path2 ? `${path2}/` : "";
3651
+ return order.map((e) => path2 + e).find((p) => files.has(p)) ?? order.map((e) => `${prefix}index${e}`).find((p) => files.has(p));
3652
+ }
3653
+
3654
+ // src/code/resolve/jsonc.ts
3655
+ function stringEnd(text2, i) {
3656
+ let j = i + 1;
3657
+ while (j < text2.length && text2[j] !== '"') j += text2[j] === "\\" ? 2 : 1;
3658
+ return j + 1;
3659
+ }
3660
+ function scan(text2, skip) {
3661
+ let out = "";
3662
+ let i = 0;
3663
+ while (i < text2.length) {
3664
+ if (text2[i] === '"') {
3665
+ const end = stringEnd(text2, i);
3666
+ out += text2.slice(i, end);
3667
+ i = end;
3668
+ continue;
3669
+ }
3670
+ const next = skip(i);
3671
+ if (next === void 0) out += text2[i++];
3672
+ else i = next;
3673
+ }
3674
+ return out;
3675
+ }
3676
+ function comment(text2, i) {
3677
+ if (text2[i] !== "/") return void 0;
3678
+ if (text2[i + 1] === "/") {
3679
+ const end2 = text2.indexOf("\n", i);
3680
+ return end2 < 0 ? text2.length : end2;
3681
+ }
3682
+ if (text2[i + 1] !== "*") return void 0;
3683
+ const end = text2.indexOf("*/", i + 2);
3684
+ return end < 0 ? text2.length : end + 2;
3685
+ }
3686
+ function parseJsonc(text2) {
3687
+ const src = text2.replace(/^\uFEFF/, "");
3688
+ const bare2 = scan(src, (i) => comment(src, i));
3689
+ const closer = /\s*[}\]]/y;
3690
+ const trailing = (i) => {
3691
+ closer.lastIndex = i + 1;
3692
+ return bare2[i] === "," && closer.test(bare2) ? i + 1 : void 0;
3693
+ };
3694
+ try {
3695
+ return JSON.parse(scan(bare2, trailing));
3696
+ } catch {
3697
+ return void 0;
3698
+ }
3699
+ }
3700
+
3701
+ // src/code/resolve/package-json.ts
3702
+ var isObject = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
3703
+ var strings = (v) => Array.isArray(v) ? v.filter((s) => typeof s === "string") : [];
3704
+ function toPackageJson(raw) {
3705
+ if (!isObject(raw)) return void 0;
3706
+ const entries = ["source", "module", "main", "types", "typings"].map((k) => raw[k]).filter((v) => typeof v === "string");
3707
+ const deps = new Set(
3708
+ ["dependencies", "devDependencies", "peerDependencies", "optionalDependencies"].flatMap((k) => isObject(raw[k]) ? Object.keys(raw[k]) : [])
3709
+ );
3710
+ const ws = raw.workspaces;
3711
+ return {
3712
+ ...typeof raw.name === "string" && { name: raw.name },
3713
+ ..."exports" in raw && { exports: raw.exports },
3714
+ ...typeof raw.tsconfig === "string" && { tsconfig: raw.tsconfig },
3715
+ ...isObject(raw.imports) && { imports: raw.imports },
3716
+ entries,
3717
+ deps,
3718
+ workspaces: isObject(ws) ? strings(ws.packages) : strings(ws)
3719
+ };
3720
+ }
3721
+ var CONDITIONS = {
3722
+ import: ["source", "development", "import", "module", "node", "default", "require", "types"],
3723
+ require: ["source", "development", "require", "node", "default", "import", "module", "types"]
3724
+ };
3725
+ function targets(target, star, conditions, depth = 0) {
3726
+ if (typeof target === "string") return [star === void 0 ? target : target.replaceAll("*", star)];
3727
+ if (depth > 8) return [];
3728
+ if (Array.isArray(target)) return target.flatMap((t) => targets(t, star, conditions, depth + 1));
3729
+ if (!isObject(target)) return [];
3730
+ return conditions.flatMap((c) => c in target ? targets(target[c], star, conditions, depth + 1) : []);
3731
+ }
3732
+ function subpathMap(map) {
3733
+ if (isObject(map) && Object.keys(map).some((k) => k.startsWith(".") || k.startsWith("#"))) return map;
3734
+ return { ".": map };
3735
+ }
3736
+ function patternMatch(map, key) {
3737
+ let best;
3738
+ for (const pattern of Object.keys(map)) {
3739
+ const at = pattern.indexOf("*");
3740
+ if (at < 0 || pattern.indexOf("*", at + 1) >= 0) continue;
3741
+ const [prefix, suffix] = [pattern.slice(0, at), pattern.slice(at + 1)];
3742
+ if (key.length < pattern.length || !key.startsWith(prefix) || !key.endsWith(suffix)) continue;
3743
+ if (!best || prefix.length > best.pattern.indexOf("*") || prefix.length === best.pattern.indexOf("*") && pattern.length > best.pattern.length) {
3744
+ best = { pattern, star: key.slice(prefix.length, key.length - suffix.length) };
3745
+ }
3746
+ }
3747
+ return best;
3748
+ }
3749
+ function mapTargets(map, key, kind = "import") {
3750
+ const subpaths = subpathMap(map);
3751
+ if (Object.hasOwn(subpaths, key) && !key.includes("*")) return targets(subpaths[key], void 0, CONDITIONS[kind]);
3752
+ const match = patternMatch(subpaths, key);
3753
+ return match ? targets(subpaths[match.pattern], match.star, CONDITIONS[kind]) : [];
3754
+ }
3755
+
3756
+ // src/code/resolve/packages.ts
3757
+ import picomatch3 from "picomatch";
3758
+ import { parse as parseYaml } from "yaml";
3759
+ var BUILD_DIRS = /* @__PURE__ */ new Set(["dist", "build", "lib", "out", "esm", "cjs", "mjs", "es", "umd", "types", "typings"]);
3760
+ var SOURCE_EXTS = [".ts", ".tsx", ".mts", ".cts", ".js", ".jsx", ".mjs", ".cjs"];
3761
+ var BUILT_EXT = /(\.d)?\.[mc]?[jt]sx?$/;
3762
+ function sourceOf(files, dir, rel) {
3763
+ const segments = rel.split("/");
3764
+ let skip = 0;
3765
+ while (skip < segments.length - 1 && BUILD_DIRS.has(segments[skip])) skip++;
3766
+ if (!skip) return void 0;
3767
+ const stem = segments.slice(skip).join("/").replace(BUILT_EXT, "");
3768
+ const prefix = dir ? `${dir}/` : "";
3769
+ const found2 = new Set([`${prefix}src/${stem}`, `${prefix}${stem}`].flatMap((base) => SOURCE_EXTS.map((e) => base + e).filter((p) => files.has(p))));
3770
+ return found2.size > 1 ? null : [...found2][0];
3771
+ }
3772
+ function inPackage(files, dir, target, fromJs) {
3773
+ const path2 = joinRepo(dir, target);
3774
+ if (path2 === void 0 || dir && path2 !== dir && !path2.startsWith(`${dir}/`)) return void 0;
3775
+ const direct = resolveFile(files, path2, fromJs);
3776
+ if (direct) return direct;
3777
+ return sourceOf(files, dir, dir ? path2.slice(dir.length + 1) : path2);
3778
+ }
3779
+ function packageEntry(files, dir, pkg, subpath, importer) {
3780
+ const candidates = pkg.exports !== void 0 ? mapTargets(pkg.exports, subpath, importer.load).filter((t) => t.startsWith("./")) : subpath === "." ? [...pkg.entries, "./index"] : [subpath];
3781
+ for (const target of candidates) {
3782
+ const file = inPackage(files, dir, target.startsWith(".") ? target : `./${target}`, importer.fromJs);
3783
+ if (file !== void 0) return file ?? void 0;
3784
+ }
3785
+ return void 0;
3786
+ }
3787
+ function splitPackageSpec(spec) {
3788
+ const parts = spec.split("/");
3789
+ const size = spec.startsWith("@") ? 2 : 1;
3790
+ const rest = parts.slice(size).join("/");
3791
+ return { name: parts.slice(0, size).join("/"), subpath: rest ? `./${rest}` : "." };
3792
+ }
3793
+ function workspaceGlobs(root, pnpmYaml) {
3794
+ let pnpm = [];
3795
+ try {
3796
+ const doc = pnpmYaml ? parseYaml(pnpmYaml) : void 0;
3797
+ const list = doc && typeof doc === "object" ? doc.packages : void 0;
3798
+ pnpm = Array.isArray(list) ? list.filter((g) => typeof g === "string") : [];
3799
+ } catch {
3800
+ }
3801
+ return [...root?.workspaces ?? [], ...pnpm].map((g) => g.replace(/^\.\//, "").replace(/\/+$/, ""));
3802
+ }
3803
+ function workspacePackages(files, readPackage, readText) {
3804
+ const globs = workspaceGlobs(readPackage(""), files.has("pnpm-workspace.yaml") ? readText("pnpm-workspace.yaml") : void 0);
3805
+ const out = /* @__PURE__ */ new Map();
3806
+ const include = globs.filter((g) => !g.startsWith("!"));
3807
+ if (!include.length) return out;
3808
+ const matches = picomatch3(include);
3809
+ const negated = globs.filter((g) => g.startsWith("!")).map((g) => g.slice(1));
3810
+ const excluded = negated.length ? picomatch3(negated) : () => false;
3811
+ for (const path2 of files) {
3812
+ if (!path2.endsWith("/package.json")) continue;
3813
+ const dir = dirOf(path2);
3814
+ const name = matches(dir) && !excluded(dir) ? readPackage(dir)?.name : void 0;
3815
+ if (name) out.set(name, out.has(name) ? void 0 : dir);
3816
+ }
3817
+ return out;
3818
+ }
3819
+
3820
+ // src/code/resolve/tsconfig.ts
3821
+ var isObject2 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
3822
+ var strings2 = (v) => Array.isArray(v) ? v.filter((s) => typeof s === "string") : [];
3823
+ var firstListed = (files, path2) => path2 === void 0 ? void 0 : [path2, `${path2}.json`].find((p) => files.has(p));
3824
+ function packageConfig(files, dir, pkg, subpath) {
3825
+ if (pkg?.exports !== void 0) {
3826
+ const target = mapTargets(pkg.exports, subpath).find((t) => t.startsWith("./"));
3827
+ return target === void 0 ? void 0 : firstListed(files, joinRepo(dir, target));
3828
+ }
3829
+ if (subpath !== ".") return firstListed(files, joinRepo(dir, subpath));
3830
+ return firstListed(files, joinRepo(dir, pkg?.tsconfig ?? "tsconfig.json"));
3831
+ }
3832
+ function createTsconfigs(files, read2, packages) {
3833
+ const configs = /* @__PURE__ */ new Map();
3834
+ const nearest = /* @__PURE__ */ new Map();
3835
+ const extendsPath = (from, spec) => {
3836
+ if (isRelative(spec)) return firstListed(files, joinRepo(dirOf(from), spec));
3837
+ const { name, subpath } = splitPackageSpec(spec);
3838
+ const dir = packages.dir(name);
3839
+ return dir === void 0 ? void 0 : packageConfig(files, dir, packages.read(dir), subpath);
3840
+ };
3841
+ const load3 = (path2, seen) => {
3842
+ const cached = configs.get(path2);
3843
+ if (cached) return cached;
3844
+ if (seen.has(path2)) return { complete: false };
3845
+ seen.add(path2);
3846
+ const raw = parseJsonc(read2(path2) ?? "");
3847
+ if (!isObject2(raw)) return { complete: false };
3848
+ let merged = { complete: true };
3849
+ for (const spec of typeof raw.extends === "string" ? [raw.extends] : strings2(raw.extends)) {
3850
+ const base = extendsPath(path2, spec);
3851
+ const opts = base ? load3(base, seen) : { complete: false };
3852
+ merged = { ...merged, ...opts, complete: merged.complete && opts.complete };
3853
+ }
3854
+ if (Array.isArray(raw.files)) merged = { ...merged, emptyFiles: raw.files.length === 0 };
3855
+ if (Array.isArray(raw.include)) merged = { ...merged, include: true };
3856
+ const options = isObject2(raw.compilerOptions) ? raw.compilerOptions : {};
3857
+ if (typeof options.baseUrl === "string") {
3858
+ const baseUrl = joinRepo(dirOf(path2), options.baseUrl);
3859
+ merged = baseUrl === void 0 ? { ...merged, baseUrl: null, complete: false } : { ...merged, baseUrl };
3860
+ }
3861
+ if (isObject2(options.paths)) {
3862
+ const patterns = Object.entries(options.paths).map(([k, v]) => [k, strings2(v)]);
3863
+ merged = { ...merged, paths: { patterns, dir: dirOf(path2) } };
3864
+ }
3865
+ configs.set(path2, merged);
3866
+ return merged;
3867
+ };
3868
+ const configFor = (dir) => {
3869
+ if (nearest.has(dir)) return nearest.get(dir);
3870
+ const prefix = dir ? `${dir}/` : "";
3871
+ const own = [`${prefix}tsconfig.json`, `${prefix}jsconfig.json`].find((p) => files.has(p));
3872
+ const found2 = own ?? (dir ? configFor(dirOf(dir)) : void 0);
3873
+ nearest.set(dir, found2);
3874
+ return found2;
3875
+ };
3876
+ return {
3877
+ /** Options of the tsconfig.json or jsconfig.json nearest to `file`, walking up; undefined when there is none. */
3878
+ forFile: (file) => {
3879
+ const config = configFor(dirOf(file));
3880
+ const opts = config === void 0 ? void 0 : load3(config, /* @__PURE__ */ new Set());
3881
+ return opts && { ...opts, solution: opts.emptyFiles === true && !opts.include };
3882
+ }
3883
+ };
3884
+ }
3885
+ function matchAlias(files, opts, spec, fromJs) {
3886
+ if (!opts.paths) return void 0;
3887
+ let best;
3888
+ for (const [pattern, targets2] of opts.paths.patterns) {
3889
+ const at = pattern.indexOf("*");
3890
+ if (at < 0) {
3891
+ if (pattern !== spec) continue;
3892
+ best = { targets: targets2, prefix: Infinity };
3893
+ break;
3894
+ }
3895
+ const [prefix, suffix] = [pattern.slice(0, at), pattern.slice(at + 1)];
3896
+ if (spec.length < prefix.length + suffix.length || !spec.startsWith(prefix) || !spec.endsWith(suffix) || prefix.length <= (best?.prefix ?? -1)) continue;
3897
+ best = { targets: targets2, star: spec.slice(prefix.length, spec.length - suffix.length), prefix: prefix.length };
3898
+ }
3899
+ if (!best) return void 0;
3900
+ if (opts.baseUrl === null) return "no-file";
3901
+ const base = opts.baseUrl ?? opts.paths.dir;
3902
+ for (const target of best.targets) {
3903
+ const path2 = joinRepo(base, best.star === void 0 ? target : target.replaceAll("*", best.star));
3904
+ const file = path2 === void 0 ? void 0 : resolveFile(files, path2, fromJs);
3905
+ if (file) return { file };
3906
+ }
3907
+ return "no-file";
3908
+ }
3909
+
3910
+ // src/code/resolve/resolver.ts
3911
+ var BUILTINS = new Set(builtinModules);
3912
+ var UNKNOWN = { status: "unknown" };
3913
+ var EXTERNAL = { status: "external" };
3914
+ var RUNTIME_SCHEMES = /^(node|bun|npm|jsr):/;
3915
+ var found = (file) => file ? { status: "resolved", resolved: file } : UNKNOWN;
3916
+ function packageDirs(repo, dir) {
3917
+ const dirs = [];
3918
+ for (let d = dir; d !== void 0; d = d ? dirOf(d) : void 0) if (repo.readPackage(d)) dirs.push(d);
3919
+ return dirs;
3920
+ }
3921
+ var typesPackage = (name) => `@types/${name.startsWith("@") ? name.slice(1).replace("/", "__") : name}`;
3922
+ var declared = (repo, from, name) => BUILTINS.has(name) || packageDirs(repo, dirOf(from)).some((d) => repo.readPackage(d).deps.has(name) || repo.readPackage(d).deps.has(typesPackage(name)));
3923
+ function fromPackageImports(repo, from, spec, load3) {
3924
+ const dir = packageDirs(repo, dirOf(from))[0];
3925
+ const pkg = dir === void 0 ? void 0 : repo.readPackage(dir);
3926
+ for (const target of pkg?.imports ? mapTargets(pkg.imports, spec, load3) : []) {
3927
+ const hit = target.startsWith("./") ? found(inPackage(repo.listed, dir, target, isJsFile(from))) : bare(repo, from, target, load3);
3928
+ if (hit.status !== "unknown") return hit;
3929
+ }
3930
+ return UNKNOWN;
3931
+ }
3932
+ function bare(repo, from, spec, load3) {
3933
+ const fromJs = isJsFile(from);
3934
+ const ts = repo.tsconfigs.forFile(from);
3935
+ const { name, subpath } = splitPackageSpec(spec);
3936
+ const alias = ts && matchAlias(repo.listed, ts, spec, fromJs);
3937
+ if (alias === "no-file") return declared(repo, from, name) ? EXTERNAL : UNKNOWN;
3938
+ if (alias) return found(alias.file);
3939
+ const viaBaseUrl = typeof ts?.baseUrl === "string" ? joinRepo(ts.baseUrl, spec) : void 0;
3940
+ const file = viaBaseUrl === void 0 ? void 0 : resolveFile(repo.listed, viaBaseUrl, fromJs);
3941
+ if (file) return found(file);
3942
+ if (BUILTINS.has(spec)) return EXTERNAL;
3943
+ if (repo.workspaces().has(name)) {
3944
+ const dir = repo.workspaces().get(name);
3945
+ return dir === void 0 ? UNKNOWN : found(packageEntry(repo.listed, dir, repo.readPackage(dir), subpath, { load: load3, fromJs }));
3946
+ }
3947
+ if (spec === "bun") return EXTERNAL;
3948
+ if (ts && (!ts.complete || ts.solution) && !declared(repo, from, name)) return UNKNOWN;
3949
+ return EXTERNAL;
3950
+ }
3951
+ function relative4(repo, from, spec, load3) {
3952
+ const query = spec.indexOf("?");
3953
+ const path2 = joinRepo(dirOf(from), query < 0 ? spec : spec.slice(0, query));
3954
+ if (path2 === void 0) return UNKNOWN;
3955
+ const file = resolveFile(repo.listed, path2, isJsFile(from));
3956
+ const pkg = !file || file.startsWith(path2 ? `${path2}/index.` : "index.") ? repo.readPackage(path2) : void 0;
3957
+ if (pkg?.entries.length) return found(packageEntry(repo.listed, path2, { ...pkg, exports: void 0 }, ".", { load: load3, fromJs: isJsFile(from) }));
3958
+ return found(file);
3959
+ }
3960
+ function resolveSpec(repo, from, spec, load3) {
3961
+ if (RUNTIME_SCHEMES.test(spec)) return EXTERNAL;
3962
+ if (isRelative(spec)) return relative4(repo, from, spec, load3);
3963
+ if (spec.startsWith("#")) return fromPackageImports(repo, from, spec, load3);
3964
+ if (!spec || spec.startsWith("/") || /^[a-z][a-z\d+.-]*:/i.test(spec)) return UNKNOWN;
3965
+ return bare(repo, from, spec, load3);
3966
+ }
3967
+ function createResolver(files, read2) {
3968
+ const listed = new Set(files);
3969
+ const packages = /* @__PURE__ */ new Map();
3970
+ const readPackage = (dir) => {
3971
+ if (!packages.has(dir)) {
3972
+ const path2 = dir ? `${dir}/package.json` : "package.json";
3973
+ packages.set(dir, listed.has(path2) ? toPackageJson(parseJsonc(read2(path2) ?? "")) : void 0);
3974
+ }
3975
+ return packages.get(dir);
3976
+ };
3977
+ let map;
3978
+ const workspaces = () => map ??= workspacePackages(listed, readPackage, read2);
3979
+ const repo = { listed, readPackage, workspaces, tsconfigs: createTsconfigs(listed, read2, { dir: (name) => workspaces().get(name), read: readPackage }) };
3980
+ return { resolve: (from, spec, kind) => resolveSpec(repo, from, spec, kind === "require" ? "require" : "import") };
3981
+ }
3982
+
3983
+ // src/code/repo.ts
3984
+ var DEFAULT_CODE_IGNORE = [
3985
+ "**/node_modules/**",
3986
+ "**/dist/**",
3987
+ "**/build/**",
3988
+ "**/out/**",
3989
+ "**/coverage/**",
3990
+ "**/.next/**",
3991
+ "**/.nuxt/**",
3992
+ "**/.svelte-kit/**",
3993
+ "**/.turbo/**",
3994
+ "**/__pycache__/**",
3995
+ "**/.venv/**",
3996
+ "**/venv/**",
3997
+ "**/*.min.js",
3998
+ "**/*.min.css"
3999
+ ];
4000
+ var MAX_FILE_BYTES = 1024 * 1024;
4001
+ function listCodeFiles(root, ignore = []) {
4002
+ const out = git(root, ["ls-files", "-z", "--cached", "--others", "--exclude-standard"]);
4003
+ const ignored = picomatch4([...DEFAULT_CODE_IGNORE, ...ignore], { dot: true });
4004
+ return [...new Set(out.split("\0"))].filter((p) => p && langOf(p) && !ignored(p)).sort();
4005
+ }
4006
+ function readCodeFile(root, path2) {
4007
+ let text2;
4008
+ try {
4009
+ const full = join8(root, path2);
4010
+ text2 = readRegularFile(full, (st) => st.isFile() && st.size <= MAX_FILE_BYTES && lstatSync4(full).isFile());
4011
+ } catch {
4012
+ return void 0;
4013
+ }
4014
+ return text2?.includes("\0") ? void 0 : text2;
4015
+ }
4016
+ async function parseRepo(root, opts = {}) {
4017
+ const paths = listCodeFiles(root, opts.ignore);
4018
+ const parsed = [];
4019
+ for (const path2 of paths) {
4020
+ const text2 = readCodeFile(root, path2);
4021
+ const file = text2 === void 0 ? void 0 : await parseCode(path2, text2);
4022
+ if (file) parsed.push(file);
4023
+ }
4024
+ return linkImports(parsed, createResolver(paths, (path2) => readCodeFile(root, path2)));
4025
+ }
3145
4026
  export {
3146
4027
  AGENTS,
3147
4028
  BLOCK_MAX,
3148
4029
  BUILTIN_DEFAULTS,
3149
4030
  CODE_PATTERNS,
4031
+ DEFAULT_CODE_IGNORE,
3150
4032
  DEFAULT_RELEASE_BRANCHES,
3151
4033
  DESCRIPTION_CANVASES,
3152
4034
  EDGE_KINDS,
@@ -3154,9 +4036,11 @@ export {
3154
4036
  GENERATED_PATHS,
3155
4037
  GLOBAL_ONLY,
3156
4038
  HTML_NAME,
4039
+ IMPORT_KINDS,
3157
4040
  IN_DIFF,
3158
4041
  KIND_ROW,
3159
4042
  LABEL_LINE_HEIGHT,
4043
+ LANGS,
3160
4044
  LINE_HEIGHT,
3161
4045
  LONG,
3162
4046
  MAX_FLOWS,
@@ -3172,6 +4056,7 @@ export {
3172
4056
  STEP_STATUSES,
3173
4057
  SUMMARY_CHARS_PER_LINE,
3174
4058
  SUMMARY_MAX_LINES,
4059
+ SYMBOL_KINDS,
3175
4060
  THEMES,
3176
4061
  agentsFor,
3177
4062
  anchorContext,
@@ -3183,6 +4068,7 @@ export {
3183
4068
  businessLinkIssues,
3184
4069
  businessSpecJsonSchema,
3185
4070
  businessTexts,
4071
+ callRefSchema,
3186
4072
  carryNotes,
3187
4073
  changeTitle,
3188
4074
  checkFlowAnchors,
@@ -3192,8 +4078,11 @@ export {
3192
4078
  cleanPath,
3193
4079
  clip,
3194
4080
  codeLabelIssue,
4081
+ codeRangeSchema,
4082
+ codeSymbolSchema,
3195
4083
  configJsonSchema,
3196
4084
  copyFiles,
4085
+ createResolver,
3197
4086
  csv,
3198
4087
  dataSchema,
3199
4088
  diffOf,
@@ -3208,6 +4097,7 @@ export {
3208
4097
  explainIssues,
3209
4098
  explainTexts,
3210
4099
  explains,
4100
+ fileInfoSchema,
3211
4101
  fileSlug,
3212
4102
  findChange,
3213
4103
  findMatch,
@@ -3252,6 +4142,7 @@ export {
3252
4142
  gitUntracked,
3253
4143
  gitWorktreeChanges,
3254
4144
  globalConfigPath,
4145
+ grammarOf,
3255
4146
  hasAny,
3256
4147
  hasGitSelection,
3257
4148
  hasHiddenChars,
@@ -3259,6 +4150,8 @@ export {
3259
4150
  headerHeight,
3260
4151
  htmlOutputPath,
3261
4152
  ident,
4153
+ importSchema,
4154
+ importedNameSchema,
3262
4155
  installCopy,
3263
4156
  installPairs,
3264
4157
  isAt,
@@ -3274,11 +4167,14 @@ export {
3274
4167
  journeySchema,
3275
4168
  labelIssues,
3276
4169
  labelLines,
4170
+ langOf,
3277
4171
  lastNoteNumber,
3278
4172
  layoutSpec,
3279
4173
  legacyAgentsFor,
3280
4174
  likelyPath,
4175
+ linkImports,
3281
4176
  linkSchema,
4177
+ listCodeFiles,
3282
4178
  listReviews,
3283
4179
  load,
3284
4180
  loadConfig,
@@ -3297,8 +4193,10 @@ export {
3297
4193
  oneLine2 as oneLine,
3298
4194
  onlyBuiltinsToJudge,
3299
4195
  opencodeConfigDir,
4196
+ parseCode,
3300
4197
  parseConfigFile,
3301
4198
  parseDoc,
4199
+ parseRepo,
3302
4200
  parseStamp,
3303
4201
  pathStr,
3304
4202
  pickLayout,
@@ -3307,6 +4205,7 @@ export {
3307
4205
  plainTextIssues,
3308
4206
  questionsOf,
3309
4207
  quotable,
4208
+ readCodeFile,
3310
4209
  readRegularBytes,
3311
4210
  readRegularFile,
3312
4211
  readReview,
@@ -3340,6 +4239,7 @@ export {
3340
4239
  stepLabel,
3341
4240
  stepSchema2 as stepSchema,
3342
4241
  stripInvisible,
4242
+ symbolId,
3343
4243
  targetExists,
3344
4244
  techIdIssue,
3345
4245
  text,