diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 95f963b..5b241a6 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1,6 +1,7 @@ name: CI on: + workflow_dispatch: push: branches: [main] pull_request: @@ -21,3 +22,20 @@ jobs: # The committed bundle (engine.mjs + engine.d.mts + grammars) must be # byte-reproducible from source — consumers vendor those exact bytes. - run: pnpm run check:build + + smoke-node18: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version: 18 + # The published artifacts are committed and dependency-free. Exercise + # those directly: the dev toolchain intentionally requires newer Node. + - name: Import library and run CLI on Node 18 + run: | + node -e 'import("./scripts/engine.mjs").then(m => { if (typeof m.scanRepo !== "function") process.exit(1) })' + node scripts/cli.mjs scan --repo tests/fixtures/mini-repo --out /tmp/codeindex-node18-scan.json + node scripts/cli.mjs search client --repo tests/fixtures/mini-repo --out /tmp/codeindex-node18-search.json + test -s /tmp/codeindex-node18-scan.json + test -s /tmp/codeindex-node18-search.json diff --git a/.github/workflows/grammars-repin.yml b/.github/workflows/grammars-repin.yml index c16db35..ec5cd57 100644 --- a/.github/workflows/grammars-repin.yml +++ b/.github/workflows/grammars-repin.yml @@ -11,13 +11,10 @@ name: Grammars repin # bundle (`pnpm build` — web-tree-sitter's JS is inlined into engine.mjs by # tsup, so its wasm and its bundled runtime move together), then runs the full # gate (typecheck / test / reproducible-bundle). Only if every gate is green AND -# something actually changed does it push the result straight to `main`. On any -# failure the run simply goes red and the next cron retries — no branch, no PR. -# -# GITHUB_TOKEN is enough here: it can push to this repo, and GitHub's -# anti-recursion rule means that push does NOT re-trigger CI/release workflows -# (the gate already ran in this job before the push), so a grammar bump never -# accidentally cuts a release. +# something actually changed does it update a dedicated pull request. Grammar +# bytes are part of the engine's versioned output: merging the `fix(grammars)` +# commit therefore cuts a patch release and publishes a matching grammar asset, +# instead of silently changing wasm under an existing ENGINE_VERSION. on: workflow_dispatch: @@ -25,7 +22,9 @@ on: - cron: "41 3 * * *" # daily, 03:41 UTC (offset from other repos' crons) permissions: + actions: write contents: write + pull-requests: write jobs: repin: @@ -55,7 +54,7 @@ jobs: - name: Stop if nothing changed id: diff run: | - if git diff --quiet -- package.json pnpm-lock.yaml scripts/engine.mjs scripts/engine.d.mts scripts/cli.mjs scripts/grammars; then + if git diff --quiet -- package.json pnpm-lock.yaml scripts/engine.mjs scripts/engine.d.mts scripts/engine.browser.mjs scripts/engine.browser.d.mts scripts/cli.mjs scripts/grammars; then echo "changed=false" >> "$GITHUB_OUTPUT" echo "Grammars already up to date — nothing to re-pin." else @@ -68,13 +67,14 @@ jobs: pnpm run typecheck pnpm test - - name: Commit re-pinned grammars + - name: Commit re-pinned grammars on the automation branch if: steps.diff.outputs.changed == 'true' run: | + git switch -c automation/grammars-repin git config user.name "github-actions[bot]" git config user.email "41898282+github-actions[bot]@users.noreply.github.com" - git add package.json pnpm-lock.yaml scripts/engine.mjs scripts/engine.d.mts scripts/cli.mjs scripts/grammars - git commit -m "chore(grammars): bump tree-sitter grammars to latest and re-vendor wasm" + git add package.json pnpm-lock.yaml scripts/engine.mjs scripts/engine.d.mts scripts/engine.browser.mjs scripts/engine.browser.d.mts scripts/cli.mjs scripts/grammars + git commit -m "fix(grammars): bump tree-sitter grammars and re-vendor wasm" # Reproducible-bundle gate LAST, against the just-committed tree: it rebuilds # and `git diff --exit-code`s, proving the committed bytes are what source @@ -84,6 +84,30 @@ jobs: if: steps.diff.outputs.changed == 'true' run: pnpm run check:build - - name: Push to main + - name: Push automation branch and open or refresh the pull request if: steps.diff.outputs.changed == 'true' - run: git push + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + REMOTE_SHA=$(git ls-remote --heads origin refs/heads/automation/grammars-repin | cut -f1) + if [ -n "$REMOTE_SHA" ]; then + git push "--force-with-lease=refs/heads/automation/grammars-repin:$REMOTE_SHA" origin HEAD:refs/heads/automation/grammars-repin + else + git push origin HEAD:refs/heads/automation/grammars-repin + fi + PR=$(gh pr list --head automation/grammars-repin --state open --json number --jq '.[0].number // empty') + if [ -n "$PR" ]; then + gh pr edit "$PR" \ + --title "fix(grammars): bump tree-sitter grammars and re-vendor wasm" \ + --body "Automated grammar repin. The full test and reproducible-build gates passed; merging creates a patch release so ENGINE_VERSION and the downloadable grammar asset remain aligned." + else + gh pr create \ + --base main \ + --head automation/grammars-repin \ + --title "fix(grammars): bump tree-sitter grammars and re-vendor wasm" \ + --body "Automated grammar repin. The full test and reproducible-build gates passed; merging creates a patch release so ENGINE_VERSION and the downloadable grammar asset remain aligned." + fi + # GITHUB_TOKEN-created PR events do not recursively start CI. An + # explicit workflow_dispatch is allowed and attaches the normal CI + # checks (including Node 18 smoke) to this branch's HEAD. + gh workflow run ci.yml --ref automation/grammars-repin diff --git a/.gitignore b/.gitignore index e421a30..c92dbe3 100644 --- a/.gitignore +++ b/.gitignore @@ -7,6 +7,7 @@ tests/.e2e-cache/ scripts/embed-asset/model.json scripts/embed-asset/.venv/ .codeindex/ +.codeindex-edit-*/ # The EXTENDED tree-sitter grammar tier lives only in the GitHub release asset, # never in git: `node scripts/fetch-grammars.mjs --extended` regenerates it, and diff --git a/README.md b/README.md index 0f2c59b..2a55f46 100644 --- a/README.md +++ b/README.md @@ -716,6 +716,14 @@ codeindex mcp --repo /path/to/workspace An explicit per-call `repo` still wins, so a pinned server can still answer about another checkout. `--server-name ` overrides the announced `serverInfo.name` for hosts that embed the server under their own identity. +Add `--watch` to a pinned server for proactive recursive filesystem +invalidation. Every request still verifies freshness with the normal stat walk +because a request can arrive before its filesystem event; the watcher is a hint, +not a correctness oracle. Directories excluded by the scanner (`.git`, build +outputs, dependency caches, `.codeindex`, edit temporaries, etc.) are ignored by +the watcher too. Git commit metadata is still refreshed by the per-request +check. When the platform cannot provide recursive watching, the server warns +and continues with those normal freshness scans. **Prime the index first** and activation becomes a load, not a rebuild: `codeindex index --repo --out /.codeindex`. The first tool call diff --git a/package.json b/package.json index 99b15b9..0d33cec 100644 --- a/package.json +++ b/package.json @@ -70,9 +70,9 @@ "@tree-sitter-grammars/tree-sitter-kotlin": "1.1.0", "@tree-sitter-grammars/tree-sitter-lua": "0.4.1", "@tree-sitter-grammars/tree-sitter-zig": "1.1.2", - "@types/node": "^20.14.0", - "esbuild": "0.28.1", - "semantic-release": "^25.0.8", + "@types/node": "^20.19.43", + "esbuild": "0.28.2", + "semantic-release": "^25.0.9", "tree-sitter-bash": "0.25.1", "tree-sitter-c": "^0.24.1", "tree-sitter-c-sharp": "^0.23.5", @@ -90,10 +90,13 @@ "tree-sitter-typescript": "^0.23.2", "tsup": "^8.3.0", "typescript": "^5.5.0", - "vitest": "^4.1.0", + "vitest": "^4.1.11", "web-tree-sitter": "^0.26.13" }, "pnpm": { + "overrides": { + "esbuild": "0.28.2" + }, "onlyBuiltDependencies": [ "esbuild" ] diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index f8b7be8..e2f2344 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -4,19 +4,22 @@ settings: autoInstallPeers: true excludeLinksFromLockfile: false +overrides: + esbuild: 0.28.2 + importers: .: devDependencies: '@semantic-release/changelog': specifier: ^6.0.3 - version: 6.0.3(semantic-release@25.0.8(typescript@5.9.3)) + version: 6.0.3(semantic-release@25.0.9(typescript@5.9.3)) '@semantic-release/exec': specifier: ^6.0.3 - version: 6.0.3(semantic-release@25.0.8(typescript@5.9.3)) + version: 6.0.3(semantic-release@25.0.9(typescript@5.9.3)) '@semantic-release/git': specifier: ^10.0.1 - version: 10.0.1(semantic-release@25.0.8(typescript@5.9.3)) + version: 10.0.1(semantic-release@25.0.9(typescript@5.9.3)) '@tree-sitter-grammars/tree-sitter-hcl': specifier: 1.2.0 version: 1.2.0 @@ -30,14 +33,14 @@ importers: specifier: 1.1.2 version: 1.1.2 '@types/node': - specifier: ^20.14.0 + specifier: ^20.19.43 version: 20.19.43 esbuild: - specifier: 0.28.1 - version: 0.28.1 + specifier: 0.28.2 + version: 0.28.2 semantic-release: - specifier: ^25.0.8 - version: 25.0.8(typescript@5.9.3) + specifier: ^25.0.9 + version: 25.0.9(typescript@5.9.3) tree-sitter-bash: specifier: 0.25.1 version: 0.25.1 @@ -90,8 +93,8 @@ importers: specifier: ^5.5.0 version: 5.9.3 vitest: - specifier: ^4.1.0 - version: 4.1.10(@types/node@20.19.43)(vite@8.1.5(@types/node@20.19.43)(esbuild@0.28.1)) + specifier: ^4.1.11 + version: 4.1.11(@types/node@20.19.43)(vite@8.1.5(@types/node@20.19.43)(esbuild@0.28.2)) web-tree-sitter: specifier: ^0.26.13 version: 0.26.13 @@ -131,314 +134,158 @@ packages: '@emnapi/wasi-threads@1.2.2': resolution: {integrity: sha512-c95qOXkHdydNKhscBTebqEC1CVAZpyqOfVfBzQ1qgzyl3gfeldUjIggDbIZgDKsHLgnsM+igH7TJ/eAasaVuMA==} - '@esbuild/aix-ppc64@0.27.7': - resolution: {integrity: sha512-EKX3Qwmhz1eMdEJokhALr0YiD0lhQNwDqkPYyPhiSwKrh7/4KRjQc04sZ8db+5DVVnZ1LmbNDI1uAMPEUBnQPg==} + '@esbuild/aix-ppc64@0.28.2': + resolution: {integrity: sha512-XExcO+dvLKvVtNTibSTBej1NCAbaGhWn9Ww1ZPx80qsahhPFe/8jgWP0IchNe0F3HwkU7n8ejhH8bjonqht8mQ==} engines: {node: '>=18'} cpu: [ppc64] os: [aix] - '@esbuild/aix-ppc64@0.28.1': - resolution: {integrity: sha512-Svl7tq8k/08+p6CXPpRjQ1fKX+1odH/BQbb48fV6fj3CWHhsoIOoY87w1oHXm0qEpkIK3ZfVgp0hed3XBXzXMQ==} - engines: {node: '>=18'} - cpu: [ppc64] - os: [aix] - - '@esbuild/android-arm64@0.27.7': - resolution: {integrity: sha512-62dPZHpIXzvChfvfLJow3q5dDtiNMkwiRzPylSCfriLvZeq0a1bWChrGx/BbUbPwOrsWKMn8idSllklzBy+dgQ==} + '@esbuild/android-arm64@0.28.2': + resolution: {integrity: sha512-5YfKeeI8qWfBZIX+u2xZC3Zlb3Os/gLS2sbEKM+I4ZOcsWmHS2WLysCcQZDAFRslDUU5Oiq44gf6PYN1vGwG5A==} engines: {node: '>=18'} cpu: [arm64] os: [android] - '@esbuild/android-arm64@0.28.1': - resolution: {integrity: sha512-34EGEbCIAgosYz6goLcopX6Mo7NyGv9tfwEM2/7Ce2VcVRk568iSvniGWcUXIy7wEDR1wzolcxcriFVrWYcwBg==} - engines: {node: '>=18'} - cpu: [arm64] - os: [android] - - '@esbuild/android-arm@0.27.7': - resolution: {integrity: sha512-jbPXvB4Yj2yBV7HUfE2KHe4GJX51QplCN1pGbYjvsyCZbQmies29EoJbkEc+vYuU5o45AfQn37vZlyXy4YJ8RQ==} - engines: {node: '>=18'} - cpu: [arm] - os: [android] - - '@esbuild/android-arm@0.28.1': - resolution: {integrity: sha512-0k2F129Xdio1TdJfzJ8sy1Q47vUD2NnwdhiAf7drUN1EBTfPf4hsFCtmMgu/6m8JSzsBrlmVjudMBQqOfG8usQ==} + '@esbuild/android-arm@0.28.2': + resolution: {integrity: sha512-kXXoiPVVGQcnIYGOeaovwOURpniDBpSq4A03qkQ+BMQqtGG6HYap3xne9C1O1yo4TR3qxlCX5IqqmX6fFo2Lqg==} engines: {node: '>=18'} cpu: [arm] os: [android] - '@esbuild/android-x64@0.27.7': - resolution: {integrity: sha512-x5VpMODneVDb70PYV2VQOmIUUiBtY3D3mPBG8NxVk5CogneYhkR7MmM3yR/uMdITLrC1ml/NV1rj4bMJuy9MCg==} + '@esbuild/android-x64@0.28.2': + resolution: {integrity: sha512-O387ite7SzUyCcy3JQX4P4bLtEA7bLLkx+esve5JHnyYfNTxcVpXZo9jhdB0lTKN44gztELTdU7nS8Nr16Fs1Q==} engines: {node: '>=18'} cpu: [x64] os: [android] - '@esbuild/android-x64@0.28.1': - resolution: {integrity: sha512-dbwY7ltSMDWsRatcRpCnES4F+im88OCUgGZjy52shC7GqHRE/cYlxNbB4Z4UpJswpcc4Qxd2oE/ufM0p61IKng==} - engines: {node: '>=18'} - cpu: [x64] - os: [android] - - '@esbuild/darwin-arm64@0.27.7': - resolution: {integrity: sha512-5lckdqeuBPlKUwvoCXIgI2D9/ABmPq3Rdp7IfL70393YgaASt7tbju3Ac+ePVi3KDH6N2RqePfHnXkaDtY9fkw==} - engines: {node: '>=18'} - cpu: [arm64] - os: [darwin] - - '@esbuild/darwin-arm64@0.28.1': - resolution: {integrity: sha512-TZbWkQY7kvTAXbXUT7uVACR5cMHsDiSz9z7ZKAX/RTq/WJEk3QyRr0wZpNhBDX+/0CtdqUIJlOiodQcta6tY3Q==} + '@esbuild/darwin-arm64@0.28.2': + resolution: {integrity: sha512-n4KqkOQrraxHJcgjM1RvwbigfQKIKJVpM7xp+KsxiyUSrRdIXnt73VhrPAx0fV44hgfmIVKjxMN9J1t5jySVkw==} engines: {node: '>=18'} cpu: [arm64] os: [darwin] - '@esbuild/darwin-x64@0.27.7': - resolution: {integrity: sha512-rYnXrKcXuT7Z+WL5K980jVFdvVKhCHhUwid+dDYQpH+qu+TefcomiMAJpIiC2EM3Rjtq0sO3StMV/+3w3MyyqQ==} - engines: {node: '>=18'} - cpu: [x64] - os: [darwin] - - '@esbuild/darwin-x64@0.28.1': - resolution: {integrity: sha512-zfdzgK9ACBNZLI/CyHTOx81SyNbM6YXn7rxSgX97VjyiPl9W1i4Ka4fgKECEoFCKGpvBj5qArWIGgQjOwkgskQ==} + '@esbuild/darwin-x64@0.28.2': + resolution: {integrity: sha512-uq6suIWYP37qzGddBKPw5QEQPi6HiLGsO7UmkpfyaYNQ3D+rN6w6WfwH+nuqcGXWvawGwxOEroO4YGnFh95azw==} engines: {node: '>=18'} cpu: [x64] os: [darwin] - '@esbuild/freebsd-arm64@0.27.7': - resolution: {integrity: sha512-B48PqeCsEgOtzME2GbNM2roU29AMTuOIN91dsMO30t+Ydis3z/3Ngoj5hhnsOSSwNzS+6JppqWsuhTp6E82l2w==} + '@esbuild/freebsd-arm64@0.28.2': + resolution: {integrity: sha512-n+I0BTSRIoy+d6RPKnEVwql5UwBJolytvY4mAOIEJorKlqgPII8ix6slVVrfZ5Tnj7glIZvloylbB/EJPMWEXw==} engines: {node: '>=18'} cpu: [arm64] os: [freebsd] - '@esbuild/freebsd-arm64@0.28.1': - resolution: {integrity: sha512-wG2EA8ENdEI0qhkSZMjfqrdY+ziCYCPMmtZjjIwOmXFjmyzEHn+UUxk5of+SYsjtfs3VpnlC7QLzSI5hY/rOAw==} - engines: {node: '>=18'} - cpu: [arm64] - os: [freebsd] - - '@esbuild/freebsd-x64@0.27.7': - resolution: {integrity: sha512-jOBDK5XEjA4m5IJK3bpAQF9/Lelu/Z9ZcdhTRLf4cajlB+8VEhFFRjWgfy3M1O4rO2GQ/b2dLwCUGpiF/eATNQ==} + '@esbuild/freebsd-x64@0.28.2': + resolution: {integrity: sha512-78XJTJkvPs0kz2w61301PJjXl4g7q3JqiYMZ/M/yVI73EHBrCRTgkhu9oqG7vPqq+a/yadEW8aD+agKlk5xrmg==} engines: {node: '>=18'} cpu: [x64] os: [freebsd] - '@esbuild/freebsd-x64@0.28.1': - resolution: {integrity: sha512-i7dZ9vQgnvSCzi/rYCXNgtF/U+eKZNJBzu3eTQbRgHnM7tNSizLOkRFAl3qzVc/Op/u5YkHHa4pf/3DOYHthLQ==} - engines: {node: '>=18'} - cpu: [x64] - os: [freebsd] - - '@esbuild/linux-arm64@0.27.7': - resolution: {integrity: sha512-RZPHBoxXuNnPQO9rvjh5jdkRmVizktkT7TCDkDmQ0W2SwHInKCAV95GRuvdSvA7w4VMwfCjUiPwDi0ZO6Nfe9A==} - engines: {node: '>=18'} - cpu: [arm64] - os: [linux] - - '@esbuild/linux-arm64@0.28.1': - resolution: {integrity: sha512-yHs+0uc8+nvEAfAfxrWQKK5peSNzBc4PegcMO0EJ2hT71uA7vB8Ihg2e77R2P7SG5uYjPbHlLLmve4LLLRCf0g==} + '@esbuild/linux-arm64@0.28.2': + resolution: {integrity: sha512-pW4AC0P3it8c7do9MVM4p51FzHzdM/TZrerurgRcHJ2WTa1VQ1CIq18xncfpBJw4ojkiZZrKW2yIBWBP92j6Ug==} engines: {node: '>=18'} cpu: [arm64] os: [linux] - '@esbuild/linux-arm@0.27.7': - resolution: {integrity: sha512-RkT/YXYBTSULo3+af8Ib0ykH8u2MBh57o7q/DAs3lTJlyVQkgQvlrPTnjIzzRPQyavxtPtfg0EopvDyIt0j1rA==} + '@esbuild/linux-arm@0.28.2': + resolution: {integrity: sha512-XlDnu2q5yoqems+xay6wSAcg9DDD7K9RLKZEBOMZm3ckNpJBvOX20tSfby8KfrrhINDyv9V2YVZKY/SpoGJI8w==} engines: {node: '>=18'} cpu: [arm] os: [linux] - '@esbuild/linux-arm@0.28.1': - resolution: {integrity: sha512-qVXBOHQS+d5Y722GwJzJUtOLlX7km3CraOaGormF1pDtPd2C/l1SHRPgjLunLGe51Sh5YYWKMFDyV4SxgMQYTQ==} - engines: {node: '>=18'} - cpu: [arm] - os: [linux] - - '@esbuild/linux-ia32@0.27.7': - resolution: {integrity: sha512-GA48aKNkyQDbd3KtkplYWT102C5sn/EZTY4XROkxONgruHPU72l+gW+FfF8tf2cFjeHaRbWpOYa/uRBz/Xq1Pg==} - engines: {node: '>=18'} - cpu: [ia32] - os: [linux] - - '@esbuild/linux-ia32@0.28.1': - resolution: {integrity: sha512-d1z4ZuP0ajrfz/FhGT4vv278rX8KnPPJx8i5+AtK7TYbx9Le9F1hyzurZpkEyjkGa9dUGhQow4C1NmeGvqxN2w==} + '@esbuild/linux-ia32@0.28.2': + resolution: {integrity: sha512-CYbnj78HsIeA+DhgUKgFCfvNsTHFhMMrinUrMZpDXJXKN8T3XViTZ/+wtHeVxEWY8ewSzTFN+nRmSwO2tZaLUQ==} engines: {node: '>=18'} cpu: [ia32] os: [linux] - '@esbuild/linux-loong64@0.27.7': - resolution: {integrity: sha512-a4POruNM2oWsD4WKvBSEKGIiWQF8fZOAsycHOt6JBpZ+JN2n2JH9WAv56SOyu9X5IqAjqSIPTaJkqN8F7XOQ5Q==} - engines: {node: '>=18'} - cpu: [loong64] - os: [linux] - - '@esbuild/linux-loong64@0.28.1': - resolution: {integrity: sha512-M5sRjUVZrkm1OAPR3dlOYzNmN+loZKGVi1VUQGrwuqLcbR6qeAz+famMhjASeH3YVKvZz+zT1jlh/keC3Rj/lg==} + '@esbuild/linux-loong64@0.28.2': + resolution: {integrity: sha512-buwkd8nsph4R+ajRvw0qM5Hja/TXQow3ptzWO2EbG/cqcIkHloRrdlBtQlshyYGTNFvfkfJ5tpPLVkY4DtsPfQ==} engines: {node: '>=18'} cpu: [loong64] os: [linux] - '@esbuild/linux-mips64el@0.27.7': - resolution: {integrity: sha512-KabT5I6StirGfIz0FMgl1I+R1H73Gp0ofL9A3nG3i/cYFJzKHhouBV5VWK1CSgKvVaG4q1RNpCTR2LuTVB3fIw==} - engines: {node: '>=18'} - cpu: [mips64el] - os: [linux] - - '@esbuild/linux-mips64el@0.28.1': - resolution: {integrity: sha512-mRObBZeHh2OxcBFPWE/FjylkRgZdYuiTR3vaTozquCGOH14iP9oN4x4Ge81CoIDYQrXmIxpFumJBu5MtZpnQJQ==} + '@esbuild/linux-mips64el@0.28.2': + resolution: {integrity: sha512-ZVykbDyk7519VwiNb9Lcj9m8XM6v5V9uKPvrEMkkEedVewf+0itkhahp4HDpgERXhwLRpWFypsGbG/J8s0QjJA==} engines: {node: '>=18'} cpu: [mips64el] os: [linux] - '@esbuild/linux-ppc64@0.27.7': - resolution: {integrity: sha512-gRsL4x6wsGHGRqhtI+ifpN/vpOFTQtnbsupUF5R5YTAg+y/lKelYR1hXbnBdzDjGbMYjVJLJTd2OFmMewAgwlQ==} - engines: {node: '>=18'} - cpu: [ppc64] - os: [linux] - - '@esbuild/linux-ppc64@0.28.1': - resolution: {integrity: sha512-slScBsMAb3GFDcdrCgLwZtPYRoH2H/youv10QiZyRjmsP48fznoveWytSgCI/R0ZcUgpc0ZhIUEx6LHts8yrfQ==} + '@esbuild/linux-ppc64@0.28.2': + resolution: {integrity: sha512-CAXl+Dtd9UUuJd8pKKdwh6MLm3MUMiqMPmhZ3tTSXPqfyQ3vDl6R5hZdZ/kYojK4ofXtdfSv1tFq8XzWx3heNQ==} engines: {node: '>=18'} cpu: [ppc64] os: [linux] - '@esbuild/linux-riscv64@0.27.7': - resolution: {integrity: sha512-hL25LbxO1QOngGzu2U5xeXtxXcW+/GvMN3ejANqXkxZ/opySAZMrc+9LY/WyjAan41unrR3YrmtTsUpwT66InQ==} + '@esbuild/linux-riscv64@0.28.2': + resolution: {integrity: sha512-GeXCej4IQtU1B+QlDV8W/RRvbzI3O/Stss+/bCXv4lZls5WGRtu2a+3JkA3i4qIUlMXpcHebWpF8AkJhATowuA==} engines: {node: '>=18'} cpu: [riscv64] os: [linux] - '@esbuild/linux-riscv64@0.28.1': - resolution: {integrity: sha512-kw0owk1o0GFETUJyW0jc0G4Yzs0BHZn0JDZ8JRT088vjJYX777BAs1fDGxAC+q831qOs2DTC96mNsG2opdfyyQ==} - engines: {node: '>=18'} - cpu: [riscv64] - os: [linux] - - '@esbuild/linux-s390x@0.27.7': - resolution: {integrity: sha512-2k8go8Ycu1Kb46vEelhu1vqEP+UeRVj2zY1pSuPdgvbd5ykAw82Lrro28vXUrRmzEsUV0NzCf54yARIK8r0fdw==} + '@esbuild/linux-s390x@0.28.2': + resolution: {integrity: sha512-3H1weTYZPxt/WOhByszQZybS9w5lKzUn1FDMsgEChbHWQwHYQQRfBxgCcZvPhjHfKyJjIievvMmEUawJrdY9Dg==} engines: {node: '>=18'} cpu: [s390x] os: [linux] - '@esbuild/linux-s390x@0.28.1': - resolution: {integrity: sha512-/lAIjX8aYFRByhh6L5rYtPEDRqa9de/4V/juOXcta5frjvzXO4/sqEtyytse0g3zZFuWu5cDN0MkLz2qRDD2Ag==} - engines: {node: '>=18'} - cpu: [s390x] - os: [linux] - - '@esbuild/linux-x64@0.27.7': - resolution: {integrity: sha512-hzznmADPt+OmsYzw1EE33ccA+HPdIqiCRq7cQeL1Jlq2gb1+OyWBkMCrYGBJ+sxVzve2ZJEVeePbLM2iEIZSxA==} - engines: {node: '>=18'} - cpu: [x64] - os: [linux] - - '@esbuild/linux-x64@0.28.1': - resolution: {integrity: sha512-u/anNYF2mmVOEDwLtnQ1wOr3EZ9sTNGLWrsYGYwHWzGA3Si84IOkHXlbWTD1NB+9/1lcnweYKO54uhxZydNzfA==} + '@esbuild/linux-x64@0.28.2': + resolution: {integrity: sha512-4xTZr1FUmSoQW4XIWmit3tzQrUTZM+N3P0XV8xROKYF50XfI7xeO90+1bZvNwxIufQ9hDQVRJH5YhgPVF8A/HQ==} engines: {node: '>=18'} cpu: [x64] os: [linux] - '@esbuild/netbsd-arm64@0.27.7': - resolution: {integrity: sha512-b6pqtrQdigZBwZxAn1UpazEisvwaIDvdbMbmrly7cDTMFnw/+3lVxxCTGOrkPVnsYIosJJXAsILG9XcQS+Yu6w==} + '@esbuild/netbsd-arm64@0.28.2': + resolution: {integrity: sha512-sSATRjPeDBg3pdgHoQfoYBob11Kk1FGa9lui5RIHZCoCkJa9QKlvl3/vKz2usCmYYjs7ymJR/2Nnsqe+Hjt5nw==} engines: {node: '>=18'} cpu: [arm64] os: [netbsd] - '@esbuild/netbsd-arm64@0.28.1': - resolution: {integrity: sha512-oks0DYbLwWMmaakTsCb+zL4E+aHRVLom9IJZOAthMQEPiQmydXHkziYEsGYRx0uNV/IjEKGAV941JzH02pflqw==} - engines: {node: '>=18'} - cpu: [arm64] - os: [netbsd] - - '@esbuild/netbsd-x64@0.27.7': - resolution: {integrity: sha512-OfatkLojr6U+WN5EDYuoQhtM+1xco+/6FSzJJnuWiUw5eVcicbyK3dq5EeV/QHT1uy6GoDhGbFpprUiHUYggrw==} - engines: {node: '>=18'} - cpu: [x64] - os: [netbsd] - - '@esbuild/netbsd-x64@0.28.1': - resolution: {integrity: sha512-aeL6lAnN89Hz43Mlh1G8ARasbuoYvSITDEx0tHh5b7jJnHcssqgjy9Yx430GDpmCa6OyrKoS0aNRjKundRizGg==} + '@esbuild/netbsd-x64@0.28.2': + resolution: {integrity: sha512-lqnzCV+mM0gIADaKihiCg6ifgfU2L3h5E33rNQBN1Y4MaVGnzryzmvvf7UHxprpQdE8hpqLolJ9Rl+SkIRDpyw==} engines: {node: '>=18'} cpu: [x64] os: [netbsd] - '@esbuild/openbsd-arm64@0.27.7': - resolution: {integrity: sha512-AFuojMQTxAz75Fo8idVcqoQWEHIXFRbOc1TrVcFSgCZtQfSdc1RXgB3tjOn/krRHENUB4j00bfGjyl2mJrU37A==} + '@esbuild/openbsd-arm64@0.28.2': + resolution: {integrity: sha512-AL2qJILH7lNjrDmCQDvdxMfAUIv8KMNZOvrwAQ8i8//ntL9FflhOyMJ8OZSMBb8/AWXe3/5v5S20y3zCoZWKoQ==} engines: {node: '>=18'} cpu: [arm64] os: [openbsd] - '@esbuild/openbsd-arm64@0.28.1': - resolution: {integrity: sha512-MEFJe5C3R8pwXdZ5Y21oo6m7ePiS0d9pWucn99O/wvyJZChoIQKrQDxKrGeW8F5+T0okTHesAmDeiHDTIq0V/Q==} - engines: {node: '>=18'} - cpu: [arm64] - os: [openbsd] - - '@esbuild/openbsd-x64@0.27.7': - resolution: {integrity: sha512-+A1NJmfM8WNDv5CLVQYJ5PshuRm/4cI6WMZRg1by1GwPIQPCTs1GLEUHwiiQGT5zDdyLiRM/l1G0Pv54gvtKIg==} + '@esbuild/openbsd-x64@0.28.2': + resolution: {integrity: sha512-QtiuPytchRyC4rwUKhexJdQKvDuZ6hWloi3igqPQNUJCS1/v9EiO3UTOXR6A3FoMo4fnAKbWJdqaIwhOzh8qEw==} engines: {node: '>=18'} cpu: [x64] os: [openbsd] - '@esbuild/openbsd-x64@0.28.1': - resolution: {integrity: sha512-i/ZLIOafE0Z8cI/XANJAixoJL/uRAoS2xOA3rb0xN+KK0K177cMAsQYkzHtBrtMXAKuAc7HGgcWiZ/sRC1Nxgw==} - engines: {node: '>=18'} - cpu: [x64] - os: [openbsd] - - '@esbuild/openharmony-arm64@0.27.7': - resolution: {integrity: sha512-+KrvYb/C8zA9CU/g0sR6w2RBw7IGc5J2BPnc3dYc5VJxHCSF1yNMxTV5LQ7GuKteQXZtspjFbiuW5/dOj7H4Yw==} + '@esbuild/openharmony-arm64@0.28.2': + resolution: {integrity: sha512-WkhYDmpTjLvGlScA1rwjRUmhl4k8oXR3cIbtqWmELgU/dFeHHlEllxDvdWcNJV9rbzCexB5vz8gtNewWLgCT7Q==} engines: {node: '>=18'} cpu: [arm64] os: [openharmony] - '@esbuild/openharmony-arm64@0.28.1': - resolution: {integrity: sha512-ge+Z7EXFNt2BO1oAMsVpiQ8EwndV9i1xXerAeTIK7AtPs3bKFXQM7nlRxDSIUIMeueR1CNXxqztLzdNeReKBJg==} - engines: {node: '>=18'} - cpu: [arm64] - os: [openharmony] - - '@esbuild/sunos-x64@0.27.7': - resolution: {integrity: sha512-ikktIhFBzQNt/QDyOL580ti9+5mL/YZeUPKU2ivGtGjdTYoqz6jObj6nOMfhASpS4GU4Q/Clh1QtxWAvcYKamA==} - engines: {node: '>=18'} - cpu: [x64] - os: [sunos] - - '@esbuild/sunos-x64@0.28.1': - resolution: {integrity: sha512-BEjgtECkL3vY+SaSQ6nzVfiALUeFxpawyp8Jmf5PtYhf1Ug40N1h/hxlhts+f1FvSvarEigdxS3BlSMI2PJLcQ==} + '@esbuild/sunos-x64@0.28.2': + resolution: {integrity: sha512-GPMSkTOtMnv2U2F8gxe4Io6qmVs+YKyp832Etqqxr0hFngmXQ3rzwytelm3GIn7T4VviRUlf3sOgBOiTdvaf7g==} engines: {node: '>=18'} cpu: [x64] os: [sunos] - '@esbuild/win32-arm64@0.27.7': - resolution: {integrity: sha512-7yRhbHvPqSpRUV7Q20VuDwbjW5kIMwTHpptuUzV+AA46kiPze5Z7qgt6CLCK3pWFrHeNfDd1VKgyP4O+ng17CA==} - engines: {node: '>=18'} - cpu: [arm64] - os: [win32] - - '@esbuild/win32-arm64@0.28.1': - resolution: {integrity: sha512-lCv9eK/H6ZJWbE7bh2nw54CZ9M2nupBxJcTsdk/QQnWkdSjKGuxmmH8/GWrlT1eMmZfn4dGcCjRte397WqfQXA==} + '@esbuild/win32-arm64@0.28.2': + resolution: {integrity: sha512-PIhhEkE9uPBleRBrQEJpUn7MBnibZzbGzYWPmY3x+YoVg/95zbjB4CxPPOQ8l5tYYM4mMaCthF8/1DIfBQQyWQ==} engines: {node: '>=18'} cpu: [arm64] os: [win32] - '@esbuild/win32-ia32@0.27.7': - resolution: {integrity: sha512-SmwKXe6VHIyZYbBLJrhOoCJRB/Z1tckzmgTLfFYOfpMAx63BJEaL9ExI8x7v0oAO3Zh6D/Oi1gVxEYr5oUCFhw==} - engines: {node: '>=18'} - cpu: [ia32] - os: [win32] - - '@esbuild/win32-ia32@0.28.1': - resolution: {integrity: sha512-zvb/mB2bSCoJOpoCBgYKKpX6YM6mJBlBUVUtVj41DlZJVEB6/0CKlRYxP5wWl1C1ILiCoAU5wZZ4q1P3qeS6Eg==} + '@esbuild/win32-ia32@0.28.2': + resolution: {integrity: sha512-YmJbfTlvU7Sdn9BB+4PRES4oB6pxgS37MAONj+hBr/cpXS1aBPKXxNnDbu+QCWPj0o9dgyxeq79g6c5P8KeuYA==} engines: {node: '>=18'} cpu: [ia32] os: [win32] - '@esbuild/win32-x64@0.27.7': - resolution: {integrity: sha512-56hiAJPhwQ1R4i+21FVF7V8kSD5zZTdHcVuRFMW0hn753vVfQN8xlx4uOPT4xoGH0Z/oVATuR82AiqSTDIpaHg==} - engines: {node: '>=18'} - cpu: [x64] - os: [win32] - - '@esbuild/win32-x64@0.28.1': - resolution: {integrity: sha512-bm4Mowrv+GXMlpWX++EcXw/iLyd1o3+bJkC2DkWXYVvgZCqD/bSj9ctZeAMC3cIxgjRVR2Dufaiu4YPxr5gW1A==} + '@esbuild/win32-x64@0.28.2': + resolution: {integrity: sha512-5ebpxr3nWMzrL/rnUI755Jkuee0bHL/Gq0WTF9lvcpv73wAp5eu8MfBUgWK9bhWvZjj7yX8etf/8tI8Ney695g==} engines: {node: '>=18'} cpu: [x64] os: [win32] @@ -450,8 +297,8 @@ packages: resolution: {integrity: sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==} engines: {node: '>=6.0.0'} - '@jridgewell/sourcemap-codec@1.5.5': - resolution: {integrity: sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og==} + '@jridgewell/sourcemap-codec@1.6.0': + resolution: {integrity: sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw==} '@jridgewell/trace-mapping@0.3.31': resolution: {integrity: sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==} @@ -467,50 +314,62 @@ packages: resolution: {integrity: sha512-P4YJBPdPSpWTQ1NU4XYdvHvXJJDxM6YwpS0FZHRgP7YFkdVxsWcpWGy/NVqlAA7PcPCnMacXlRm1y2PFZRWL/w==} engines: {node: '>= 20'} - '@octokit/core@7.0.6': - resolution: {integrity: sha512-DhGl4xMVFGVIyMwswXeyzdL4uXD5OGILGX5N8Y+f6W7LhC1Ze2poSNrkF/fedpVDHEEZ+PHFW0vL14I+mm8K3Q==} + '@octokit/core@7.0.8': + resolution: {integrity: sha512-L7y8eYc+AwxGr2PWI4WFt1VG4TiJ66c26BD16mXpYIlXxG0SMigM1+m4aTSlYyBr5BlQsGAlz8uDCoZN4SEMcg==} engines: {node: '>= 20'} - '@octokit/endpoint@11.0.3': - resolution: {integrity: sha512-FWFlNxghg4HrXkD3ifYbS/IdL/mDHjh9QcsNyhQjN8dplUoZbejsdpmuqdA76nxj2xoWPs7p8uX2SNr9rYu0Ag==} + '@octokit/endpoint@11.0.5': + resolution: {integrity: sha512-iXa654H3yFafF/ieHkukfbgWo2rmXD2ceD0ZOtrPhw1bc3FDch1d9N/TNs0FQ1/cIbwb7kspUX8jzIs8nzb9DQ==} engines: {node: '>= 20'} - '@octokit/graphql@9.0.3': - resolution: {integrity: sha512-grAEuupr/C1rALFnXTv6ZQhFuL1D8G5y8CN04RgrO4FIPMrtm+mcZzFG7dcBm+nq+1ppNixu+Jd78aeJOYxlGA==} + '@octokit/graphql@9.0.5': + resolution: {integrity: sha512-bt/hm03LeU6Vy7FwTrkkC9p3XGT/lBwClglMqxBSe5/q0E5CdJTXeAqEI0vlw89/LF/G6tryTIH8HirZ3prMVg==} engines: {node: '>= 20'} '@octokit/openapi-types@27.0.0': resolution: {integrity: sha512-whrdktVs1h6gtR+09+QsNk2+FO+49j6ga1c55YZudfEG+oKJVvJLQi3zkOm5JjiUXAagWK2tI2kTGKJ2Ys7MGA==} + '@octokit/openapi-types@28.0.0': + resolution: {integrity: sha512-0rFyLuyHvIj6uuZWuDslxkowFYdPXoNIkeAv4b27dzm2Tf4vGWXnPsMcxs7d65kLdMERgP3wc1AEPlqMz8e1cQ==} + + '@octokit/openapi-types@29.0.1': + resolution: {integrity: sha512-9qWOMFNxxLokERcms42rU0PTLqQmVs7g5E41TI4mCOxmpFayD1rfC7XxOL55cG9MBZLFlC31BrR37myMKardwg==} + '@octokit/plugin-paginate-rest@14.0.0': resolution: {integrity: sha512-fNVRE7ufJiAA3XUrha2omTA39M6IXIc6GIZLvlbsm8QOQCYvpq/LkMNGyFlB1d8hTDzsAXa3OKtybdMAYsV/fw==} engines: {node: '>= 20'} peerDependencies: '@octokit/core': '>=6' - '@octokit/plugin-retry@8.1.0': - resolution: {integrity: sha512-O1FZgXeiGb2sowEr/hYTr6YunGdSAFWnr2fyW39Ah85H8O33ELASQxcvOFF5LE6Tjekcyu2ms4qAzJVhSaJxTw==} + '@octokit/plugin-retry@8.1.1': + resolution: {integrity: sha512-VCVvZ/R1+u3WuiBWpNavZ0mY4aaJNAsENrpBP9aLSR2QyOpQgd7DhM5j4AW7z4MQpnJYgwBPf0XqPQoNBRdQwg==} engines: {node: '>= 20'} peerDependencies: '@octokit/core': '>=7' - '@octokit/plugin-throttling@11.0.3': - resolution: {integrity: sha512-34eE0RkFCKycLl2D2kq7W+LovheM/ex3AwZCYN8udpi6bxsyjZidb2McXs69hZhLmJlDqTSP8cH+jSRpiaijBg==} + '@octokit/plugin-throttling@11.0.5': + resolution: {integrity: sha512-LIdrkrUv+DWbKeg/49rGuFJ3SU0d3hUS+B4MhNZLepBoNUFXms8Ic9edJjrlx+zycqJHjrMRudVpVb/bAXM2Lw==} engines: {node: '>= 20'} peerDependencies: '@octokit/core': ^7.0.0 - '@octokit/request-error@7.1.0': - resolution: {integrity: sha512-KMQIfq5sOPpkQYajXHwnhjCC0slzCNScLHs9JafXc4RAJI+9f+jNDlBNaIMTvazOPLgb4BnlhGJOTbnN0wIjPw==} + '@octokit/request-error@7.1.2': + resolution: {integrity: sha512-XZRuT3xZ84D3gYErI1DZvhJ33dCWVV6uzBtWkaBB4TvA/L6eOeTZodxLFVB44bBEEo3vEx7y00UfX1tBLrtLRg==} engines: {node: '>= 20'} - '@octokit/request@10.0.11': - resolution: {integrity: sha512-+s7HUxjfFqOMS9VlIwDffq0MikjSAK0gSpG73W+meAvVAvX4MBrHYTK5Bj3Uot55qFT4gzUtfzE4mGWY4Br8/Q==} + '@octokit/request@10.0.16': + resolution: {integrity: sha512-A0zWGjHzISIb+9ccG8s0dq7LKO5zVpJLRICjgUb+sJxEWqn8RUHB1rD3AE51+PECvXHIxqZ1VVvs4fHTSD9nUQ==} engines: {node: '>= 20'} '@octokit/types@16.0.0': resolution: {integrity: sha512-sKq+9r1Mm4efXW1FCk7hFSeJo4QKreL/tTbR0rz/qx/r1Oa2VV83LTA/H/MuCOX7uCIJmQVRKBcbmWoySjAnSg==} + '@octokit/types@17.0.0': + resolution: {integrity: sha512-ByP1v7YL5SMveFPP7+sj0/ZuWCOOg/Chs4NafOMpq6WNIM/hdGY0S7C0TCGDBWu1aGmOxmUIhMx3cO+IdwYZ1Q==} + + '@octokit/types@18.0.0': + resolution: {integrity: sha512-l6bAF43PNxkJp6g+W4PjoUSSkxHomXw2nOum5CTftJz1NlV3vu93NImgOYtLf6CbBUb5j+fiuzW0PPQ5JTSvZA==} + '@oxc-project/types@0.139.0': resolution: {integrity: sha512-r9gHphtCs+1M7J0pw6Sn/hh/Wpa/iQrOOkrNAlVLF/gHq+/CJmHIWKKUUhdWjcD6CIa8idarspCsASiXCXvFUw==} @@ -880,11 +739,11 @@ packages: '@types/normalize-package-data@2.4.4': resolution: {integrity: sha512-37i+OaWTh9qeK4LSHPsyRC7NahnGotNuZvjLSgcPzblpHB3rrCJxAOgI5gCdKm7coonsaX1Of0ILiTcnZjbfxA==} - '@vitest/expect@4.1.10': - resolution: {integrity: sha512-YsCn+qAk1GWjQOWFEsEcL2gNQ0zmVmQu3T03qP6UyjhtmdtwtbuI+DASn/7iQB3HGTXkdBwGddzxPlmiql5vlA==} + '@vitest/expect@4.1.11': + resolution: {integrity: sha512-VX2x5vNJXET47KAFzwERI+KRMtTTCSWTfSMKsW7JsUsXV4psq++e3DvZpuTDOpHcxytiDs6p2nhVb2tVDiiUYw==} - '@vitest/mocker@4.1.10': - resolution: {integrity: sha512-v0xaezt+DKEmKfaxg133ldzADrwLGd7Ze1MfQQTYfvs8OqZIwbxyxaYURivwV7sWy5fqn3rH5uOrSp07bp44Ow==} + '@vitest/mocker@4.1.11': + resolution: {integrity: sha512-2XJVD55d1o5AZous5CCGKS74g/riOj9odEt2bQpCVZeblHyHdnMeFl4jl0XjU21stf4mbjUkew2eXQZt65g5CQ==} peerDependencies: msw: ^2.4.9 vite: ^6.0.0 || ^7.0.0 || ^8.0.0 @@ -894,20 +753,20 @@ packages: vite: optional: true - '@vitest/pretty-format@4.1.10': - resolution: {integrity: sha512-W1HsjSH4MXQ9YfmmhLAoIYf1HRfekQCGngeIgcei6MP5QQGWUe0gkopdZQaVCFO+JDJMrAJGwa5pRpNpvy4P8Q==} + '@vitest/pretty-format@4.1.11': + resolution: {integrity: sha512-yiZzPbGTS9Sr/JpFl8zHrcIkAofNbFV6k21vIgQN/cY/oxZeXhJv5sc/MBJ5jFKWmWs+oJHw0UXLZjmf931+Vw==} - '@vitest/runner@4.1.10': - resolution: {integrity: sha512-IKI6kpIH+LmpROplyLwBBaCfMgOZOMsygVa6BARD6ahA04VRuJSa6OaVG7kRvSEMD870Vd91rSSw0eegtWyLGg==} + '@vitest/runner@4.1.11': + resolution: {integrity: sha512-LztvUgdwMNJMIkj3hQnnxiC2Xy1zNxq928W/xhjCLaNCzqTZOudjwbQf6v9IntZGPw132i2Lq2rgTRZHD3JHNw==} - '@vitest/snapshot@4.1.10': - resolution: {integrity: sha512-xRkfOT1qpTAi/Ti4Y1LtfRc3kEuqxGw59eN2jN9pRWMtS/XDevekhcFSqvQqjUNGksfjMJu3Y+oJ+4Ypn2OaJw==} + '@vitest/snapshot@4.1.11': + resolution: {integrity: sha512-pN7ikn1ON7h8ee4gIAp4AzyK+zBtJPzVbqOgu5LCEh4VaJVbPQcgYQYJIMGQPXVeJJq1fnfazis7a5pFNPahog==} - '@vitest/spy@4.1.10': - resolution: {integrity: sha512-PLf/Ugvoq5wO/b4rwYCR1h2PSIdXz7wnkQFMiUpLdtM7l6pqVFcQIBEHyT1+l+cj7mNwAfZHzqXqDyjvOuwbDw==} + '@vitest/spy@4.1.11': + resolution: {integrity: sha512-apNa/prQy2qCeywhnixOHPRCgGNhvg7T4Dapfl1GahLp/R+uhBm5cPyFoNVyqsNd2h1nJxL6BqqdIjiABL60YA==} - '@vitest/utils@4.1.10': - resolution: {integrity: sha512-fy9am/HWxbaGt/Sawrp90vt6Y6jQwf1RX77cz3uwoJwJVMli/e1IEwRPnMNJ7vKfPTwo0diXifkpPvwH9v7nGA==} + '@vitest/utils@4.1.11': + resolution: {integrity: sha512-zTCVGpyFsGWBhllOyKlTw/vnr6D9qxsfSDyfbyZmTyjHw5N/VuvzHpHoQjm2ZJzn4RJgx5w4r7V0er69CmLgPQ==} acorn@8.17.0: resolution: {integrity: sha512-xRQbDb9BnwDafYNn6Vwl839DYVjqXYb1XVGtWAZ1kcDc6iwAL4hg3B1dZlRiuENFeO2H53gFG3in621AdERVAg==} @@ -934,8 +793,8 @@ packages: resolution: {integrity: sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==} engines: {node: '>=8'} - ansi-regex@6.2.2: - resolution: {integrity: sha512-Bq3SmSpyFHaWjPk8If9yc6svM8c56dB5BAtW4Qbw5jHTwwXXcTLoRMkpDJp6VL0XzlWaCHTXrkFURMYmD0sLqg==} + ansi-regex@6.3.0: + resolution: {integrity: sha512-WpDfL7NO6j7tH88IDBNVdUJxDh9nmCteAVW9dsep846XdwF4naCBK+/tGLX3KJgcpgMRXCFlTM2hKGoK9FsdrQ==} engines: {node: '>=12'} ansi-styles@3.2.1: @@ -980,7 +839,7 @@ packages: resolution: {integrity: sha512-3WrrOuZiyaaZPWiEt4G3+IffISVC9HYlWueJEBWED4ZH4aIAC2PnkdnuRrR94M+w6yGWn4AglWtJtBI8YqvgoA==} engines: {node: ^12.20.0 || ^14.13.1 || >=16.0.0} peerDependencies: - esbuild: '>=0.18' + esbuild: 0.28.2 cac@6.7.14: resolution: {integrity: sha512-b6Ilus+c3RrdDk+JhLKUAQfzzgLEPy6wcXqS7f/xe1EETvsDP6GORG7SFuOs6cID5YkqchW/LXZbX5bc8j7ZcQ==} @@ -1068,9 +927,9 @@ packages: resolution: {integrity: sha512-5IKcdX0nnYavi6G7TtOhwkYzyjfJlatbjMjuLSfE2kYT5pMDOilZ4OvMhi637CcDICTmz3wARPoyhqyX1Y+XvA==} engines: {node: ^14.18.0 || >=16.10.0} - content-type@2.0.0: - resolution: {integrity: sha512-j/O/d7GcZCyNl7/hwZAb606rzqkyvaDctLmckbxLzHvFBzTJHuGEdodATcP3yIRoDrLHkIATJuvzbFlp/ki2cQ==} - engines: {node: '>=18'} + content-type@3.0.0: + resolution: {integrity: sha512-AIi5H6p0xk5uknXcN3/rmhP8jgp69OfSe/JuKiQAFprJ7UGw7mwj7m4XcmDzlrnJDG+cGpphAINGdU3g3g7kDw==} + engines: {node: '>=22'} conventional-changelog-angular@8.3.1: resolution: {integrity: sha512-6gfI3otXK5Ph5DfCOI1dblr+kN3FAm5a97hYoQkqNZxOaYa5WKfXH+AnpsmS+iUH2mgVC2Cg2Qw9m5OKcmNrIg==} @@ -1169,16 +1028,11 @@ packages: error-ex@1.3.4: resolution: {integrity: sha512-sqQamAnR14VgCr1A618A3sGrygcpK+HEbenA/HiEAkkUwcZIIB/tgWqHFxWgOyDh4nB4JCRimh79dR5Ywc9MDQ==} - es-module-lexer@2.3.1: - resolution: {integrity: sha512-shc1dbU90Yl/xq1QrC7QRtfcwURZuVRfPhZbDoldJ1cn1gzDvBaBWlv0eFolj5+0znnPJz5TXLxsN77X/12KTA==} - - esbuild@0.27.7: - resolution: {integrity: sha512-IxpibTjyVnmrIQo5aqNpCgoACA/dTKLTlhMHihVHhdkxKyPO1uBBthumT0rdHmcsk9uMonIWS0m4FljWzILh3w==} - engines: {node: '>=18'} - hasBin: true + es-module-lexer@2.3.2: + resolution: {integrity: sha512-poHGpORABojJJucnV9KbOavETW8lBVnphkW77ER5/BQ5Fz7oXSoCNek7IH3vR5nRjdsEz926ibFYX8KtLQmdyw==} - esbuild@0.28.1: - resolution: {integrity: sha512-HrJrvZv5ayxBzPfwphOoNzkzOIIlifzk0KJrGK2c8R4+LKpMtpYLQeUdjnwjWv/LZlkH2laZk+4w78pi99D4Vw==} + esbuild@0.28.2: + resolution: {integrity: sha512-HKVLS8dvII+xoKW9kmqxbRKrnWEXfJJr/FZhhJmiqIB0e053QNYFqOBouTMO/k5sID4MvCiUCvv8b9M4h32wIA==} engines: {node: '>=18'} hasBin: true @@ -1253,6 +1107,10 @@ packages: resolution: {integrity: sha512-w8ZNZr2mKIc7qeNaQ9AVPT1+iFaI+Avd4xudVOvdDJ8VytREi1Ft5Ih7hd9jjehod8vAM5GMsfQ/TpPf4EyoEA==} engines: {node: '>=14.14'} + fs-extra@11.4.0: + resolution: {integrity: sha512-EQsFzMUJkCKGr1ePqlYADkIUmHW1s3ZXr5Yqy6wbGrfUCphpl2maM/kyOIRA2HpP3AaFQTZXD4ldjek+nccddA==} + engines: {node: '>=14.14'} + fsevents@2.3.3: resolution: {integrity: sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==} engines: {node: ^8.16.0 || ^10.6.0 || >=11.0.0} @@ -1424,8 +1282,8 @@ packages: js-tokens@4.0.0: resolution: {integrity: sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==} - js-yaml@4.3.0: - resolution: {integrity: sha512-1td788aAnnZ5qs7V2QIRl1owjtYpbKt749Y3xauqQgwIIGF/xXWz1wMTEBx5O3LK3lXLVuqXPdPxj2BoFHaW9Q==} + js-yaml@4.3.2: + resolution: {integrity: sha512-SFNOvSJ+Dgf/9An904Yx+CgSlIPCkIpao4qo51lpee25TIRejdH3rhR4EZMGoNx3/TP3O+wzWuiTFl4sqbltzA==} hasBin: true json-parse-better-errors@1.0.2: @@ -1434,8 +1292,8 @@ packages: json-parse-even-better-errors@2.3.1: resolution: {integrity: sha512-xyFwyhro/JEof6Ghe2iz2NcXoj2sloNsWr/XsERDK/oiPCfaNhl5ONfp+jQdAZRQQ0IJWNzH9zIZF7li91kh2w==} - json-with-bigint@3.5.10: - resolution: {integrity: sha512-Vcx+JVNEBts/xfcoCS69sKrOhOk/3TVlvlT+XzUOefVKnnrbYSCKpDCm10pohsJFtsJVYnwa/cXRZ4eElzaM6w==} + json-with-bigint@3.5.12: + resolution: {integrity: sha512-uwbF/wSSuOgC7qqlq27Xp5B6a2MHVug3t0idZdTqu0JnlFvgJuH7ju+KAk/J06C7GfhoYy2gnb9wz2INqcne7w==} jsonfile@6.2.1: resolution: {integrity: sha512-zwOTdL3rFQ/lRdBnntKVOX6k5cKJwEc1HdilT71BWEu7J41gXIB2MRp+vxduPSwZJPWBxEzv4yH1wYLJGUHX4Q==} @@ -1670,8 +1528,8 @@ packages: resolution: {integrity: sha512-9qny7Z9DsQU8Ou39ERsPU4OZQlSTP47ShQzuKZ6PRXpYLtIFgl/DEBYEXKlvcEa+9tHVcK8CF81Y2V72qaZhWA==} engines: {node: '>=18'} - npm@11.18.0: - resolution: {integrity: sha512-T67M4L5wNm0cZ7EBLErcEkY1SmzEW/WJ+SADBzsFUY1UdAPfFHXFQtZ6SEXiK0+vzXysCvAsepbMaBTwnrAD+w==} + npm@11.19.1: + resolution: {integrity: sha512-ztsxKxt/kkIaAs+2i0GU6I+DRmUdrNasxTZKJe9TCdSjKxlhah/4r/hl5ygMD6XAg1qZ9c2TNomR4qgOydp10g==} engines: {node: ^20.17.0 || >=22.9.0} hasBin: true bundledDependencies: @@ -1777,8 +1635,8 @@ packages: resolution: {integrity: sha512-nQja7m7gSKuewoVRen45CtVfODR3crN3goVQ0DDZ9N3yHxgpkuBhZqsaiotSQRrADUrne346peY7kT3TSACykg==} engines: {node: '>=4'} - p-map@7.0.6: - resolution: {integrity: sha512-I4Prw6ivkd6p8PiYR1tXASOAOBzIJwu0TB7fqaX0c/8c3QAehNYmX57EijyGGGBt3c/BIowGwV03RVBtXvHEVg==} + p-map@7.0.7: + resolution: {integrity: sha512-VaWRu2i4FJNRtiRWCuuQRgfQ1B7a6+gMSrO+3j0EQi/k0ULfS9kosRxGoiqwzIjZTDI02tGfk5mXXltLg6QtfQ==} engines: {node: '>=18'} p-reduce@2.1.0: @@ -1852,10 +1710,6 @@ packages: resolution: {integrity: sha512-V7+vQEJ06Z+c5tSye8S+nHUfI51xoXIXjHQ99cQtKUkQqqO1kO/KCJUfZXuB47h/YBlDhah2H3hdUGXn8ie0oA==} engines: {node: '>=8.6'} - picomatch@4.0.5: - resolution: {integrity: sha512-RvwwcruNjI1ncT5xRakeyS9Lf8lcItv34KD+aif+VH9kduAyfYBipGh12274xtenIPZ119/R9BdTBa8gAwSh0A==} - engines: {node: '>=12'} - picomatch@4.0.7: resolution: {integrity: sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==} engines: {node: '>=12'} @@ -1897,8 +1751,8 @@ packages: resolution: {integrity: sha512-u82N74LFzG8ca+dD8puPnplTXoGH4fTPpVGuIbt36G3qvNlkvfD0lEAZSxaly3KX8TS/L1A1gsCEmvKmBcVbkQ==} engines: {node: ^10 || ^12 || >=14} - pretty-ms@9.3.0: - resolution: {integrity: sha512-gjVS5hOP+M3wMm5nmNOucbIrqudzs9v/57bWRHQWLYklXqoXKrVfYW2W9+glfGsqtPgpiz5WwyEEB+ksXIx3gQ==} + pretty-ms@9.3.1: + resolution: {integrity: sha512-HzMy3Geq23nVALD/M2LliU+F+M+gVNsvkQWWqeBZ8HDiCgzo6YPJ/Omrmtq24EFrIsk0a3EkQGEd7bDOo+IhGA==} engines: {node: '>=18'} process-nextick-args@2.0.1: @@ -1972,8 +1826,8 @@ packages: safe-buffer@5.1.2: resolution: {integrity: sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==} - semantic-release@25.0.8: - resolution: {integrity: sha512-w/iZ0bur36rKffXZYmIUmy068eoBY3Ij1DCCddx2JwWEM5Tg+eU9ld/E9qSInVvPASyyR2Ln/XGfQ9OZrMlhtw==} + semantic-release@25.0.9: + resolution: {integrity: sha512-bxve7csK0/Txr++CkfrmV+X1r4jqiSOw2WsSad9E2S68R+ZfLBwDn8IceM8WfiOmKQIHgsQc1cNA8Dzg7U75pg==} engines: {node: ^22.14.0 || >= 24.10.0} hasBin: true @@ -2059,6 +1913,10 @@ packages: resolution: {integrity: sha512-tsaTIkKW9b4N+AEj+SVA+WhJzV7/zMhcSu78mLKWSk7cXMOSHsBKFWUs0fWwq8QyK3MgJBQRX6Gbi4kYbdvGkQ==} engines: {node: '>=18'} + string-width@8.2.2: + resolution: {integrity: sha512-GaPUh5gfdrYzqeVNZvUfT23vYYxXzKYidUcnMtJg/3rxRV63EFZy3k6xfKlmfeJD0176lnUV/Usr3XcwSvFzpg==} + engines: {node: '>=20'} + string_decoder@1.1.1: resolution: {integrity: sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==} @@ -2143,16 +2001,16 @@ packages: tinyexec@0.3.2: resolution: {integrity: sha512-KQQR9yN7R5+OSwaK0XQoj22pwHoTlgYqmUscPYoknOoWCWfj/5/ABTMRi69FrKU5ffPVh5QcFikpWJI/P1ocHA==} - tinyexec@1.2.4: - resolution: {integrity: sha512-SHf/r48b7vOrjve9PxJo3MN5v5yuyjHvdUcrQffT3WXMUfnGmHDVbC4k3sHJaJTgZCwpUplIaAo5ANtMyp3YHg==} + tinyexec@1.3.0: + resolution: {integrity: sha512-QKAl9m8gWWGHV8jZcPeym6j+XULi6tOf1mT83WYJ4Lk2ytW/uwAWkrP0uFsdoYMdueVJ0qs26wZ+23xeB4ibNQ==} engines: {node: '>=18'} tinyglobby@0.2.17: resolution: {integrity: sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==} engines: {node: '>=12.0.0'} - tinyrainbow@3.1.0: - resolution: {integrity: sha512-Bf+ILmBgretUrdJxzXM0SgXLZ3XfiaUuOj/IKQHuTXip+05Xn+uyEYdVg0kYDipTBcLrCVyUzAPz7QmArb0mmw==} + tinyrainbow@3.1.1: + resolution: {integrity: sha512-yau8yJdTt989Mm0Bd/236QnzEiPf2xLLTqUZRUJOo/3CB078LSwzei343DgtJVmfJKJE3TMINY1u42SQsP6mXw==} engines: {node: '>=14.0.0'} to-regex-range@5.0.1: @@ -2342,8 +2200,8 @@ packages: resolution: {integrity: sha512-TeTSQ6H5YHvpqVwBRcnLDCBnDOHWYu7IvGbHT6N8AOymcr9PJGjc1GTtiWZTYg0NCgYwvnYWEkVChQAr9bjfwA==} engines: {node: '>=16'} - type-fest@5.8.0: - resolution: {integrity: sha512-YGYEVz3Fm5iy/AybuA0oyNFq7H4CgQNfRp/qfe8nurE1kuCeNm3/vfm9X4Mtl+qLyaKJUh5xrFZwogr41SMjYA==} + type-fest@5.9.0: + resolution: {integrity: sha512-yANm3Jr3GiJ1qgJlxGAVxTOIcEOk1rhQHamlXtnrCK7EHP4HeM9OGxtMg/W7HFdrVzw/ZWJKGVIJusVH85sLtw==} engines: {node: '>=20'} typescript@5.9.3: @@ -2362,12 +2220,12 @@ packages: undici-types@6.21.0: resolution: {integrity: sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==} - undici@6.27.0: - resolution: {integrity: sha512-YmfV3YnEDzXRC5lZ2jWtWWHKGUm1zIt8AhesR1tens+HTNv+YZlN/dp6G727LOvMJ8xjP9Be7Y2Sdr96LDm+pg==} + undici@6.28.0: + resolution: {integrity: sha512-LIY910g9TI13YS95lrMFrs8Rm/u/irgHeTWoKCoteeJ04CUJ92eEfj0rVn+7VKMPBpUPiUoBKfhNyLI23EE/KA==} engines: {node: '>=18.17'} - undici@7.28.0: - resolution: {integrity: sha512-cRZYrTDwWznlnRiPjggAGxZXanty6M8RV1ff8Wm4LWXBp7/IG8v5DnOm74DtUBp9OONpK75YlPnIjQqX0dBDtA==} + undici@7.29.0: + resolution: {integrity: sha512-IDxfleLmmbSskfWSUATiN1nfn2rDuvnMOqb5CWR92iIfojA0Ud+ulOAAEQ57LPr9rWmsreUyf5lwyao+7GNNVw==} engines: {node: '>=20.18.1'} unicode-emoji-modifier-base@1.0.0: @@ -2414,7 +2272,7 @@ packages: peerDependencies: '@types/node': ^20.19.0 || >=22.12.0 '@vitejs/devtools': ^0.3.0 - esbuild: ^0.27.0 || ^0.28.0 + esbuild: 0.28.2 jiti: '>=1.21.0' less: ^4.0.0 sass: ^1.70.0 @@ -2450,20 +2308,20 @@ packages: yaml: optional: true - vitest@4.1.10: - resolution: {integrity: sha512-R9jUTe5S4Qb0HCd4TNqpC7oGcrMssMRGXLW80ubjWsW9VH5GF8y1Y0SFLY9AbqSk6nt0PnOx4H4WNJYZ13GUPw==} + vitest@4.1.11: + resolution: {integrity: sha512-fhACrNXUidIbGSBr5FlbuBkO7VWC1ZyLl0DO4CU2DrQoAPxX84Ysxs+HeGQpii5lZWV1Q4gBZTTu49mF+A6Edw==} engines: {node: ^20.0.0 || ^22.0.0 || >=24.0.0} hasBin: true peerDependencies: '@edge-runtime/vm': '*' '@opentelemetry/api': ^1.9.0 '@types/node': ^20.0.0 || ^22.0.0 || >=24.0.0 - '@vitest/browser-playwright': 4.1.10 - '@vitest/browser-preview': 4.1.10 - '@vitest/browser-webdriverio': 4.1.10 - '@vitest/coverage-istanbul': 4.1.10 - '@vitest/coverage-v8': 4.1.10 - '@vitest/ui': 4.1.10 + '@vitest/browser-playwright': 4.1.11 + '@vitest/browser-preview': 4.1.11 + '@vitest/browser-webdriverio': 4.1.11 + '@vitest/coverage-istanbul': 4.1.11 + '@vitest/coverage-v8': 4.1.11 + '@vitest/ui': 4.1.11 happy-dom: '*' jsdom: '*' vite: ^6.0.0 || ^7.0.0 || ^8.0.0 @@ -2538,8 +2396,8 @@ packages: resolution: {integrity: sha512-Nt9ZJjXTv5R8MHbqby/wXQ6Gi0Bb3TcYZkR1bzuL4yB2OxWPkXknz513gEF0GoA6tn00UpbPvERW8rzCuWCA6w==} engines: {node: '>=10'} - yargs@18.0.0: - resolution: {integrity: sha512-4UEqdc2RYGHZc7Doyqkrqiln3p9X2DZVxaGbwhn2pi7MrRagKaOcIKe8L3OxYcbhXLgLFUS3zAYuQjKBQgmuNg==} + yargs@18.1.0: + resolution: {integrity: sha512-2rAgRKu54VsHkqI0/tYkmluGXHD4KW7yZoycuqDQ15QOTnc2VVfy0nN/1eMhnQLO00A+dwtK20xuCnc1YGeUyg==} engines: {node: ^20.19.0 || ^22.12.0 || >=23} yarn@1.22.22: @@ -2547,8 +2405,8 @@ packages: engines: {node: '>=4.0.0'} hasBin: true - yoctocolors@2.1.2: - resolution: {integrity: sha512-CzhO+pFNo8ajLM2d2IW/R93ipy99LWjtwblvC1RsoSUMZgyLbYFr221TnSNT7GjGdYui6P459mw9JH/g/zW2ug==} + yoctocolors@2.2.0: + resolution: {integrity: sha512-xYqdZFUK/VYazNl/oCDYN+3WloWQwMfZxBoiNt6qNyk+xfOdi598muWE42rNZFp1kNOiqW936q5RhUdnpqElSg==} engines: {node: '>=18'} snapshots: @@ -2565,7 +2423,7 @@ snapshots: '@actions/http-client@4.0.1': dependencies: tunnel: 0.0.6 - undici: 6.27.0 + undici: 6.28.0 '@actions/io@3.0.2': {} @@ -2596,175 +2454,97 @@ snapshots: tslib: 2.8.1 optional: true - '@esbuild/aix-ppc64@0.27.7': - optional: true - - '@esbuild/aix-ppc64@0.28.1': - optional: true - - '@esbuild/android-arm64@0.27.7': - optional: true - - '@esbuild/android-arm64@0.28.1': - optional: true - - '@esbuild/android-arm@0.27.7': - optional: true - - '@esbuild/android-arm@0.28.1': - optional: true - - '@esbuild/android-x64@0.27.7': - optional: true - - '@esbuild/android-x64@0.28.1': - optional: true - - '@esbuild/darwin-arm64@0.27.7': - optional: true - - '@esbuild/darwin-arm64@0.28.1': - optional: true - - '@esbuild/darwin-x64@0.27.7': - optional: true - - '@esbuild/darwin-x64@0.28.1': - optional: true - - '@esbuild/freebsd-arm64@0.27.7': - optional: true - - '@esbuild/freebsd-arm64@0.28.1': - optional: true - - '@esbuild/freebsd-x64@0.27.7': - optional: true - - '@esbuild/freebsd-x64@0.28.1': - optional: true - - '@esbuild/linux-arm64@0.27.7': - optional: true - - '@esbuild/linux-arm64@0.28.1': - optional: true - - '@esbuild/linux-arm@0.27.7': - optional: true - - '@esbuild/linux-arm@0.28.1': - optional: true - - '@esbuild/linux-ia32@0.27.7': - optional: true - - '@esbuild/linux-ia32@0.28.1': - optional: true - - '@esbuild/linux-loong64@0.27.7': + '@esbuild/aix-ppc64@0.28.2': optional: true - '@esbuild/linux-loong64@0.28.1': + '@esbuild/android-arm64@0.28.2': optional: true - '@esbuild/linux-mips64el@0.27.7': + '@esbuild/android-arm@0.28.2': optional: true - '@esbuild/linux-mips64el@0.28.1': + '@esbuild/android-x64@0.28.2': optional: true - '@esbuild/linux-ppc64@0.27.7': + '@esbuild/darwin-arm64@0.28.2': optional: true - '@esbuild/linux-ppc64@0.28.1': + '@esbuild/darwin-x64@0.28.2': optional: true - '@esbuild/linux-riscv64@0.27.7': + '@esbuild/freebsd-arm64@0.28.2': optional: true - '@esbuild/linux-riscv64@0.28.1': + '@esbuild/freebsd-x64@0.28.2': optional: true - '@esbuild/linux-s390x@0.27.7': + '@esbuild/linux-arm64@0.28.2': optional: true - '@esbuild/linux-s390x@0.28.1': + '@esbuild/linux-arm@0.28.2': optional: true - '@esbuild/linux-x64@0.27.7': + '@esbuild/linux-ia32@0.28.2': optional: true - '@esbuild/linux-x64@0.28.1': + '@esbuild/linux-loong64@0.28.2': optional: true - '@esbuild/netbsd-arm64@0.27.7': + '@esbuild/linux-mips64el@0.28.2': optional: true - '@esbuild/netbsd-arm64@0.28.1': + '@esbuild/linux-ppc64@0.28.2': optional: true - '@esbuild/netbsd-x64@0.27.7': + '@esbuild/linux-riscv64@0.28.2': optional: true - '@esbuild/netbsd-x64@0.28.1': + '@esbuild/linux-s390x@0.28.2': optional: true - '@esbuild/openbsd-arm64@0.27.7': + '@esbuild/linux-x64@0.28.2': optional: true - '@esbuild/openbsd-arm64@0.28.1': + '@esbuild/netbsd-arm64@0.28.2': optional: true - '@esbuild/openbsd-x64@0.27.7': + '@esbuild/netbsd-x64@0.28.2': optional: true - '@esbuild/openbsd-x64@0.28.1': + '@esbuild/openbsd-arm64@0.28.2': optional: true - '@esbuild/openharmony-arm64@0.27.7': + '@esbuild/openbsd-x64@0.28.2': optional: true - '@esbuild/openharmony-arm64@0.28.1': + '@esbuild/openharmony-arm64@0.28.2': optional: true - '@esbuild/sunos-x64@0.27.7': + '@esbuild/sunos-x64@0.28.2': optional: true - '@esbuild/sunos-x64@0.28.1': + '@esbuild/win32-arm64@0.28.2': optional: true - '@esbuild/win32-arm64@0.27.7': + '@esbuild/win32-ia32@0.28.2': optional: true - '@esbuild/win32-arm64@0.28.1': - optional: true - - '@esbuild/win32-ia32@0.27.7': - optional: true - - '@esbuild/win32-ia32@0.28.1': - optional: true - - '@esbuild/win32-x64@0.27.7': - optional: true - - '@esbuild/win32-x64@0.28.1': + '@esbuild/win32-x64@0.28.2': optional: true '@jridgewell/gen-mapping@0.3.13': dependencies: - '@jridgewell/sourcemap-codec': 1.5.5 + '@jridgewell/sourcemap-codec': 1.6.0 '@jridgewell/trace-mapping': 0.3.31 '@jridgewell/resolve-uri@3.1.2': {} - '@jridgewell/sourcemap-codec@1.5.5': {} + '@jridgewell/sourcemap-codec@1.6.0': {} '@jridgewell/trace-mapping@0.3.31': dependencies: '@jridgewell/resolve-uri': 3.1.2 - '@jridgewell/sourcemap-codec': 1.5.5 + '@jridgewell/sourcemap-codec': 1.6.0 '@napi-rs/wasm-runtime@1.2.3(@emnapi/core@1.11.1)(@emnapi/runtime@1.11.1)': dependencies: @@ -2775,64 +2555,76 @@ snapshots: '@octokit/auth-token@6.0.0': {} - '@octokit/core@7.0.6': + '@octokit/core@7.0.8': dependencies: '@octokit/auth-token': 6.0.0 - '@octokit/graphql': 9.0.3 - '@octokit/request': 10.0.11 - '@octokit/request-error': 7.1.0 - '@octokit/types': 16.0.0 + '@octokit/graphql': 9.0.5 + '@octokit/request': 10.0.16 + '@octokit/request-error': 7.1.2 + '@octokit/types': 18.0.0 before-after-hook: 4.0.0 universal-user-agent: 7.0.3 - '@octokit/endpoint@11.0.3': + '@octokit/endpoint@11.0.5': dependencies: - '@octokit/types': 16.0.0 + '@octokit/types': 18.0.0 universal-user-agent: 7.0.3 - '@octokit/graphql@9.0.3': + '@octokit/graphql@9.0.5': dependencies: - '@octokit/request': 10.0.11 - '@octokit/types': 16.0.0 + '@octokit/request': 10.0.16 + '@octokit/types': 18.0.0 universal-user-agent: 7.0.3 '@octokit/openapi-types@27.0.0': {} - '@octokit/plugin-paginate-rest@14.0.0(@octokit/core@7.0.6)': + '@octokit/openapi-types@28.0.0': {} + + '@octokit/openapi-types@29.0.1': {} + + '@octokit/plugin-paginate-rest@14.0.0(@octokit/core@7.0.8)': dependencies: - '@octokit/core': 7.0.6 + '@octokit/core': 7.0.8 '@octokit/types': 16.0.0 - '@octokit/plugin-retry@8.1.0(@octokit/core@7.0.6)': + '@octokit/plugin-retry@8.1.1(@octokit/core@7.0.8)': dependencies: - '@octokit/core': 7.0.6 - '@octokit/request-error': 7.1.0 - '@octokit/types': 16.0.0 + '@octokit/core': 7.0.8 + '@octokit/request-error': 7.1.2 + '@octokit/types': 17.0.0 bottleneck: 2.19.5 - '@octokit/plugin-throttling@11.0.3(@octokit/core@7.0.6)': + '@octokit/plugin-throttling@11.0.5(@octokit/core@7.0.8)': dependencies: - '@octokit/core': 7.0.6 - '@octokit/types': 16.0.0 + '@octokit/core': 7.0.8 + '@octokit/types': 17.0.0 bottleneck: 2.19.5 - '@octokit/request-error@7.1.0': + '@octokit/request-error@7.1.2': dependencies: - '@octokit/types': 16.0.0 + '@octokit/types': 18.0.0 - '@octokit/request@10.0.11': + '@octokit/request@10.0.16': dependencies: - '@octokit/endpoint': 11.0.3 - '@octokit/request-error': 7.1.0 - '@octokit/types': 16.0.0 - content-type: 2.0.0 - json-with-bigint: 3.5.10 + '@octokit/endpoint': 11.0.5 + '@octokit/request-error': 7.1.2 + '@octokit/types': 18.0.0 + content-type: 3.0.0 + json-with-bigint: 3.5.12 universal-user-agent: 7.0.3 '@octokit/types@16.0.0': dependencies: '@octokit/openapi-types': 27.0.0 + '@octokit/types@17.0.0': + dependencies: + '@octokit/openapi-types': 28.0.0 + + '@octokit/types@18.0.0': + dependencies: + '@octokit/openapi-types': 29.0.1 + '@oxc-project/types@0.139.0': {} '@pnpm/config.env-replace@1.1.0': {} @@ -2975,15 +2767,15 @@ snapshots: '@sec-ant/readable-stream@0.4.1': {} - '@semantic-release/changelog@6.0.3(semantic-release@25.0.8(typescript@5.9.3))': + '@semantic-release/changelog@6.0.3(semantic-release@25.0.9(typescript@5.9.3))': dependencies: '@semantic-release/error': 3.0.0 aggregate-error: 3.1.0 fs-extra: 11.3.6 lodash: 4.18.1 - semantic-release: 25.0.8(typescript@5.9.3) + semantic-release: 25.0.9(typescript@5.9.3) - '@semantic-release/commit-analyzer@13.0.1(semantic-release@25.0.8(typescript@5.9.3))': + '@semantic-release/commit-analyzer@13.0.1(semantic-release@25.0.9(typescript@5.9.3))': dependencies: conventional-changelog-angular: 8.3.1 conventional-changelog-writer: 8.4.0 @@ -2993,7 +2785,7 @@ snapshots: import-from-esm: 2.0.0 lodash-es: 4.18.1 micromatch: 4.0.8 - semantic-release: 25.0.8(typescript@5.9.3) + semantic-release: 25.0.9(typescript@5.9.3) transitivePeerDependencies: - supports-color @@ -3001,7 +2793,7 @@ snapshots: '@semantic-release/error@4.0.0': {} - '@semantic-release/exec@6.0.3(semantic-release@25.0.8(typescript@5.9.3))': + '@semantic-release/exec@6.0.3(semantic-release@25.0.9(typescript@5.9.3))': dependencies: '@semantic-release/error': 3.0.0 aggregate-error: 3.1.0 @@ -3009,11 +2801,11 @@ snapshots: execa: 5.1.1 lodash: 4.18.1 parse-json: 5.2.0 - semantic-release: 25.0.8(typescript@5.9.3) + semantic-release: 25.0.9(typescript@5.9.3) transitivePeerDependencies: - supports-color - '@semantic-release/git@10.0.1(semantic-release@25.0.8(typescript@5.9.3))': + '@semantic-release/git@10.0.1(semantic-release@25.0.9(typescript@5.9.3))': dependencies: '@semantic-release/error': 3.0.0 aggregate-error: 3.1.0 @@ -3023,16 +2815,16 @@ snapshots: lodash: 4.18.1 micromatch: 4.0.8 p-reduce: 2.1.0 - semantic-release: 25.0.8(typescript@5.9.3) + semantic-release: 25.0.9(typescript@5.9.3) transitivePeerDependencies: - supports-color - '@semantic-release/github@12.0.9(semantic-release@25.0.8(typescript@5.9.3))': + '@semantic-release/github@12.0.9(semantic-release@25.0.9(typescript@5.9.3))': dependencies: - '@octokit/core': 7.0.6 - '@octokit/plugin-paginate-rest': 14.0.0(@octokit/core@7.0.6) - '@octokit/plugin-retry': 8.1.0(@octokit/core@7.0.6) - '@octokit/plugin-throttling': 11.0.3(@octokit/core@7.0.6) + '@octokit/core': 7.0.8 + '@octokit/plugin-paginate-rest': 14.0.0(@octokit/core@7.0.8) + '@octokit/plugin-retry': 8.1.1(@octokit/core@7.0.8) + '@octokit/plugin-throttling': 11.0.5(@octokit/core@7.0.8) '@semantic-release/error': 4.0.0 aggregate-error: 5.0.0 debug: 4.4.3 @@ -3043,34 +2835,34 @@ snapshots: lodash-es: 4.18.1 mime: 4.1.0 p-filter: 4.1.0 - semantic-release: 25.0.8(typescript@5.9.3) + semantic-release: 25.0.9(typescript@5.9.3) tinyglobby: 0.2.17 - undici: 7.28.0 + undici: 7.29.0 url-join: 5.0.0 transitivePeerDependencies: - kerberos - supports-color - '@semantic-release/npm@13.1.5(semantic-release@25.0.8(typescript@5.9.3))': + '@semantic-release/npm@13.1.5(semantic-release@25.0.9(typescript@5.9.3))': dependencies: '@actions/core': 3.0.1 '@semantic-release/error': 4.0.0 aggregate-error: 5.0.0 env-ci: 11.2.0 execa: 9.6.1 - fs-extra: 11.3.6 + fs-extra: 11.4.0 lodash-es: 4.18.1 nerf-dart: 1.0.0 normalize-url: 9.0.1 - npm: 11.18.0 + npm: 11.19.1 rc: 1.2.8 read-pkg: 10.1.0 registry-auth-token: 5.1.1 - semantic-release: 25.0.8(typescript@5.9.3) + semantic-release: 25.0.9(typescript@5.9.3) semver: 7.8.5 tempy: 3.2.0 - '@semantic-release/release-notes-generator@14.1.1(semantic-release@25.0.8(typescript@5.9.3))': + '@semantic-release/release-notes-generator@14.1.1(semantic-release@25.0.9(typescript@5.9.3))': dependencies: conventional-changelog-angular: 8.3.1 conventional-changelog-writer: 8.4.0 @@ -3080,7 +2872,7 @@ snapshots: import-from-esm: 2.0.0 lodash-es: 4.18.1 read-package-up: 11.0.0 - semantic-release: 25.0.8(typescript@5.9.3) + semantic-release: 25.0.9(typescript@5.9.3) transitivePeerDependencies: - supports-color @@ -3133,46 +2925,46 @@ snapshots: '@types/normalize-package-data@2.4.4': {} - '@vitest/expect@4.1.10': + '@vitest/expect@4.1.11': dependencies: '@standard-schema/spec': 1.1.0 '@types/chai': 5.2.3 - '@vitest/spy': 4.1.10 - '@vitest/utils': 4.1.10 + '@vitest/spy': 4.1.11 + '@vitest/utils': 4.1.11 chai: 6.2.2 - tinyrainbow: 3.1.0 + tinyrainbow: 3.1.1 - '@vitest/mocker@4.1.10(vite@8.1.5(@types/node@20.19.43)(esbuild@0.28.1))': + '@vitest/mocker@4.1.11(vite@8.1.5(@types/node@20.19.43)(esbuild@0.28.2))': dependencies: - '@vitest/spy': 4.1.10 + '@vitest/spy': 4.1.11 estree-walker: 3.0.3 magic-string: 0.30.21 optionalDependencies: - vite: 8.1.5(@types/node@20.19.43)(esbuild@0.28.1) + vite: 8.1.5(@types/node@20.19.43)(esbuild@0.28.2) - '@vitest/pretty-format@4.1.10': + '@vitest/pretty-format@4.1.11': dependencies: - tinyrainbow: 3.1.0 + tinyrainbow: 3.1.1 - '@vitest/runner@4.1.10': + '@vitest/runner@4.1.11': dependencies: - '@vitest/utils': 4.1.10 + '@vitest/utils': 4.1.11 pathe: 2.0.3 - '@vitest/snapshot@4.1.10': + '@vitest/snapshot@4.1.11': dependencies: - '@vitest/pretty-format': 4.1.10 - '@vitest/utils': 4.1.10 + '@vitest/pretty-format': 4.1.11 + '@vitest/utils': 4.1.11 magic-string: 0.30.21 pathe: 2.0.3 - '@vitest/spy@4.1.10': {} + '@vitest/spy@4.1.11': {} - '@vitest/utils@4.1.10': + '@vitest/utils@4.1.11': dependencies: - '@vitest/pretty-format': 4.1.10 + '@vitest/pretty-format': 4.1.11 convert-source-map: 2.0.0 - tinyrainbow: 3.1.0 + tinyrainbow: 3.1.1 acorn@8.17.0: {} @@ -3194,7 +2986,7 @@ snapshots: ansi-regex@5.0.1: {} - ansi-regex@6.2.2: {} + ansi-regex@6.3.0: {} ansi-styles@3.2.1: dependencies: @@ -3224,9 +3016,9 @@ snapshots: dependencies: fill-range: 7.1.1 - bundle-require@5.1.0(esbuild@0.27.7): + bundle-require@5.1.0(esbuild@0.28.2): dependencies: - esbuild: 0.27.7 + esbuild: 0.28.2 load-tsconfig: 0.2.5 cac@6.7.14: {} @@ -3315,7 +3107,7 @@ snapshots: consola@3.4.2: {} - content-type@2.0.0: {} + content-type@3.0.0: {} conventional-changelog-angular@8.3.1: dependencies: @@ -3346,7 +3138,7 @@ snapshots: dependencies: env-paths: 2.2.1 import-fresh: 3.3.1 - js-yaml: 4.3.0 + js-yaml: 4.3.2 parse-json: 5.2.0 optionalDependencies: typescript: 5.9.3 @@ -3400,65 +3192,36 @@ snapshots: dependencies: is-arrayish: 0.2.1 - es-module-lexer@2.3.1: {} + es-module-lexer@2.3.2: {} - esbuild@0.27.7: + esbuild@0.28.2: optionalDependencies: - '@esbuild/aix-ppc64': 0.27.7 - '@esbuild/android-arm': 0.27.7 - '@esbuild/android-arm64': 0.27.7 - '@esbuild/android-x64': 0.27.7 - '@esbuild/darwin-arm64': 0.27.7 - '@esbuild/darwin-x64': 0.27.7 - '@esbuild/freebsd-arm64': 0.27.7 - '@esbuild/freebsd-x64': 0.27.7 - '@esbuild/linux-arm': 0.27.7 - '@esbuild/linux-arm64': 0.27.7 - '@esbuild/linux-ia32': 0.27.7 - '@esbuild/linux-loong64': 0.27.7 - '@esbuild/linux-mips64el': 0.27.7 - '@esbuild/linux-ppc64': 0.27.7 - '@esbuild/linux-riscv64': 0.27.7 - '@esbuild/linux-s390x': 0.27.7 - '@esbuild/linux-x64': 0.27.7 - '@esbuild/netbsd-arm64': 0.27.7 - '@esbuild/netbsd-x64': 0.27.7 - '@esbuild/openbsd-arm64': 0.27.7 - '@esbuild/openbsd-x64': 0.27.7 - '@esbuild/openharmony-arm64': 0.27.7 - '@esbuild/sunos-x64': 0.27.7 - '@esbuild/win32-arm64': 0.27.7 - '@esbuild/win32-ia32': 0.27.7 - '@esbuild/win32-x64': 0.27.7 - - esbuild@0.28.1: - optionalDependencies: - '@esbuild/aix-ppc64': 0.28.1 - '@esbuild/android-arm': 0.28.1 - '@esbuild/android-arm64': 0.28.1 - '@esbuild/android-x64': 0.28.1 - '@esbuild/darwin-arm64': 0.28.1 - '@esbuild/darwin-x64': 0.28.1 - '@esbuild/freebsd-arm64': 0.28.1 - '@esbuild/freebsd-x64': 0.28.1 - '@esbuild/linux-arm': 0.28.1 - '@esbuild/linux-arm64': 0.28.1 - '@esbuild/linux-ia32': 0.28.1 - '@esbuild/linux-loong64': 0.28.1 - '@esbuild/linux-mips64el': 0.28.1 - '@esbuild/linux-ppc64': 0.28.1 - '@esbuild/linux-riscv64': 0.28.1 - '@esbuild/linux-s390x': 0.28.1 - '@esbuild/linux-x64': 0.28.1 - '@esbuild/netbsd-arm64': 0.28.1 - '@esbuild/netbsd-x64': 0.28.1 - '@esbuild/openbsd-arm64': 0.28.1 - '@esbuild/openbsd-x64': 0.28.1 - '@esbuild/openharmony-arm64': 0.28.1 - '@esbuild/sunos-x64': 0.28.1 - '@esbuild/win32-arm64': 0.28.1 - '@esbuild/win32-ia32': 0.28.1 - '@esbuild/win32-x64': 0.28.1 + '@esbuild/aix-ppc64': 0.28.2 + '@esbuild/android-arm': 0.28.2 + '@esbuild/android-arm64': 0.28.2 + '@esbuild/android-x64': 0.28.2 + '@esbuild/darwin-arm64': 0.28.2 + '@esbuild/darwin-x64': 0.28.2 + '@esbuild/freebsd-arm64': 0.28.2 + '@esbuild/freebsd-x64': 0.28.2 + '@esbuild/linux-arm': 0.28.2 + '@esbuild/linux-arm64': 0.28.2 + '@esbuild/linux-ia32': 0.28.2 + '@esbuild/linux-loong64': 0.28.2 + '@esbuild/linux-mips64el': 0.28.2 + '@esbuild/linux-ppc64': 0.28.2 + '@esbuild/linux-riscv64': 0.28.2 + '@esbuild/linux-s390x': 0.28.2 + '@esbuild/linux-x64': 0.28.2 + '@esbuild/netbsd-arm64': 0.28.2 + '@esbuild/netbsd-x64': 0.28.2 + '@esbuild/openbsd-arm64': 0.28.2 + '@esbuild/openbsd-x64': 0.28.2 + '@esbuild/openharmony-arm64': 0.28.2 + '@esbuild/sunos-x64': 0.28.2 + '@esbuild/win32-arm64': 0.28.2 + '@esbuild/win32-ia32': 0.28.2 + '@esbuild/win32-x64': 0.28.2 escalade@3.2.0: {} @@ -3504,16 +3267,16 @@ snapshots: is-plain-obj: 4.1.0 is-stream: 4.0.1 npm-run-path: 6.0.0 - pretty-ms: 9.3.0 + pretty-ms: 9.3.1 signal-exit: 4.1.0 strip-final-newline: 4.0.0 - yoctocolors: 2.1.2 + yoctocolors: 2.2.0 expect-type@1.4.0: {} - fdir@6.5.0(picomatch@4.0.5): + fdir@6.5.0(picomatch@4.0.7): optionalDependencies: - picomatch: 4.0.5 + picomatch: 4.0.7 figures@2.0.0: dependencies: @@ -3550,6 +3313,12 @@ snapshots: jsonfile: 6.2.1 universalify: 2.0.1 + fs-extra@11.4.0: + dependencies: + graceful-fs: 4.2.11 + jsonfile: 6.2.1 + universalify: 2.0.1 + fsevents@2.3.3: optional: true @@ -3690,7 +3459,7 @@ snapshots: js-tokens@4.0.0: {} - js-yaml@4.3.0: + js-yaml@4.3.2: dependencies: argparse: 2.0.1 @@ -3698,7 +3467,7 @@ snapshots: json-parse-even-better-errors@2.3.1: {} - json-with-bigint@3.5.10: {} + json-with-bigint@3.5.12: {} jsonfile@6.2.1: dependencies: @@ -3793,7 +3562,7 @@ snapshots: magic-string@0.30.21: dependencies: - '@jridgewell/sourcemap-codec': 1.5.5 + '@jridgewell/sourcemap-codec': 1.6.0 make-asynchronous@1.1.0: dependencies: @@ -3804,7 +3573,7 @@ snapshots: marked-terminal@7.3.0(marked@15.0.12): dependencies: ansi-escapes: 7.3.0 - ansi-regex: 6.2.2 + ansi-regex: 6.3.0 chalk: 5.6.2 cli-highlight: 2.1.11 cli-table3: 0.6.5 @@ -3894,7 +3663,7 @@ snapshots: path-key: 4.0.0 unicorn-magic: 0.3.0 - npm@11.18.0: {} + npm@11.19.1: {} object-assign@4.1.1: {} @@ -3916,7 +3685,7 @@ snapshots: p-filter@4.1.0: dependencies: - p-map: 7.0.6 + p-map: 7.0.7 p-limit@1.3.0: dependencies: @@ -3926,7 +3695,7 @@ snapshots: dependencies: p-limit: 1.3.0 - p-map@7.0.6: {} + p-map@7.0.7: {} p-reduce@2.1.0: {} @@ -3982,8 +3751,6 @@ snapshots: picomatch@2.3.2: {} - picomatch@4.0.5: {} - picomatch@4.0.7: {} pify@3.0.0: {} @@ -4013,7 +3780,7 @@ snapshots: picocolors: 1.1.1 source-map-js: 1.2.1 - pretty-ms@9.3.0: + pretty-ms@9.3.1: dependencies: parse-ms: 4.0.0 @@ -4040,14 +3807,14 @@ snapshots: dependencies: find-up-simple: 1.0.1 read-pkg: 10.1.0 - type-fest: 5.8.0 + type-fest: 5.9.0 read-pkg@10.1.0: dependencies: '@types/normalize-package-data': 2.4.4 normalize-package-data: 8.0.0 parse-json: 8.3.0 - type-fest: 5.8.0 + type-fest: 5.9.0 unicorn-magic: 0.4.0 read-pkg@9.0.1: @@ -4134,13 +3901,13 @@ snapshots: safe-buffer@5.1.2: {} - semantic-release@25.0.8(typescript@5.9.3): + semantic-release@25.0.9(typescript@5.9.3): dependencies: - '@semantic-release/commit-analyzer': 13.0.1(semantic-release@25.0.8(typescript@5.9.3)) + '@semantic-release/commit-analyzer': 13.0.1(semantic-release@25.0.9(typescript@5.9.3)) '@semantic-release/error': 4.0.0 - '@semantic-release/github': 12.0.9(semantic-release@25.0.8(typescript@5.9.3)) - '@semantic-release/npm': 13.1.5(semantic-release@25.0.8(typescript@5.9.3)) - '@semantic-release/release-notes-generator': 14.1.1(semantic-release@25.0.8(typescript@5.9.3)) + '@semantic-release/github': 12.0.9(semantic-release@25.0.9(typescript@5.9.3)) + '@semantic-release/npm': 13.1.5(semantic-release@25.0.9(typescript@5.9.3)) + '@semantic-release/release-notes-generator': 14.1.1(semantic-release@25.0.9(typescript@5.9.3)) aggregate-error: 5.0.0 cosmiconfig: 9.0.2(typescript@5.9.3) debug: 4.4.3 @@ -4163,7 +3930,7 @@ snapshots: resolve-from: 5.0.0 semver: 7.8.5 signale: 1.4.0 - yargs: 18.0.0 + yargs: 18.1.0 transitivePeerDependencies: - kerberos - supports-color @@ -4242,6 +4009,11 @@ snapshots: get-east-asian-width: 1.6.0 strip-ansi: 7.2.0 + string-width@8.2.2: + dependencies: + get-east-asian-width: 1.6.0 + strip-ansi: 7.2.0 + string_decoder@1.1.1: dependencies: safe-buffer: 5.1.2 @@ -4252,7 +4024,7 @@ snapshots: strip-ansi@7.2.0: dependencies: - ansi-regex: 6.2.2 + ansi-regex: 6.3.0 strip-bom@3.0.0: {} @@ -4325,14 +4097,14 @@ snapshots: tinyexec@0.3.2: {} - tinyexec@1.2.4: {} + tinyexec@1.3.0: {} tinyglobby@0.2.17: dependencies: - fdir: 6.5.0(picomatch@4.0.5) - picomatch: 4.0.5 + fdir: 6.5.0(picomatch@4.0.7) + picomatch: 4.0.7 - tinyrainbow@3.1.0: {} + tinyrainbow@3.1.1: {} to-regex-range@5.0.1: dependencies: @@ -4437,12 +4209,12 @@ snapshots: tsup@8.5.1(postcss@8.5.26)(typescript@5.9.3): dependencies: - bundle-require: 5.1.0(esbuild@0.27.7) + bundle-require: 5.1.0(esbuild@0.28.2) cac: 6.7.14 chokidar: 4.0.3 consola: 3.4.2 debug: 4.4.3 - esbuild: 0.27.7 + esbuild: 0.28.2 fix-dts-default-cjs-exports: 1.0.1 joycon: 3.1.1 picocolors: 1.1.1 @@ -4471,7 +4243,7 @@ snapshots: type-fest@4.41.0: {} - type-fest@5.8.0: + type-fest@5.9.0: dependencies: tagged-tag: 1.0.0 @@ -4484,9 +4256,9 @@ snapshots: undici-types@6.21.0: {} - undici@6.27.0: {} + undici@6.28.0: {} - undici@7.28.0: {} + undici@7.29.0: {} unicode-emoji-modifier-base@1.0.0: {} @@ -4513,7 +4285,7 @@ snapshots: spdx-correct: 3.2.0 spdx-expression-parse: 3.0.1 - vite@8.1.5(@types/node@20.19.43)(esbuild@0.28.1): + vite@8.1.5(@types/node@20.19.43)(esbuild@0.28.2): dependencies: lightningcss: 1.33.0 picomatch: 4.0.7 @@ -4522,30 +4294,30 @@ snapshots: tinyglobby: 0.2.17 optionalDependencies: '@types/node': 20.19.43 - esbuild: 0.28.1 + esbuild: 0.28.2 fsevents: 2.3.3 - vitest@4.1.10(@types/node@20.19.43)(vite@8.1.5(@types/node@20.19.43)(esbuild@0.28.1)): + vitest@4.1.11(@types/node@20.19.43)(vite@8.1.5(@types/node@20.19.43)(esbuild@0.28.2)): dependencies: - '@vitest/expect': 4.1.10 - '@vitest/mocker': 4.1.10(vite@8.1.5(@types/node@20.19.43)(esbuild@0.28.1)) - '@vitest/pretty-format': 4.1.10 - '@vitest/runner': 4.1.10 - '@vitest/snapshot': 4.1.10 - '@vitest/spy': 4.1.10 - '@vitest/utils': 4.1.10 - es-module-lexer: 2.3.1 + '@vitest/expect': 4.1.11 + '@vitest/mocker': 4.1.11(vite@8.1.5(@types/node@20.19.43)(esbuild@0.28.2)) + '@vitest/pretty-format': 4.1.11 + '@vitest/runner': 4.1.11 + '@vitest/snapshot': 4.1.11 + '@vitest/spy': 4.1.11 + '@vitest/utils': 4.1.11 + es-module-lexer: 2.3.2 expect-type: 1.4.0 magic-string: 0.30.21 obug: 2.1.4 pathe: 2.0.3 - picomatch: 4.0.5 + picomatch: 4.0.7 std-env: 4.2.0 tinybench: 2.9.0 - tinyexec: 1.2.4 + tinyexec: 1.3.0 tinyglobby: 0.2.17 - tinyrainbow: 3.1.0 - vite: 8.1.5(@types/node@20.19.43)(esbuild@0.28.1) + tinyrainbow: 3.1.1 + vite: 8.1.5(@types/node@20.19.43)(esbuild@0.28.2) why-is-node-running: 2.3.0 optionalDependencies: '@types/node': 20.19.43 @@ -4597,15 +4369,15 @@ snapshots: y18n: 5.0.8 yargs-parser: 20.2.9 - yargs@18.0.0: + yargs@18.1.0: dependencies: cliui: 9.0.1 escalade: 3.2.0 get-caller-file: 2.0.5 - string-width: 7.2.0 + string-width: 8.2.2 y18n: 5.0.8 yargs-parser: 22.0.0 yarn@1.22.22: {} - yoctocolors@2.1.2: {} + yoctocolors@2.2.0: {} diff --git a/scripts/engine.browser.d.mts b/scripts/engine.browser.d.mts index 2ebfb42..1ac5b79 100644 --- a/scripts/engine.browser.d.mts +++ b/scripts/engine.browser.d.mts @@ -1,6 +1,6 @@ declare const ENGINE_VERSION = "2.28.0"; declare const SCHEMA_VERSION = 5; -declare const EXTRACTOR_VERSION = 13; +declare const EXTRACTOR_VERSION = 14; type FileKind = "code" | "doc" | "config" | "asset" | "other"; type EdgeKind = "contains" | "doc-link" | "import" | "call" | "extends" | "implements" | "use" | "mention"; type Tier = 0 | 1 | 2; @@ -1553,6 +1553,7 @@ interface McpServerOptions { defaultRepo?: string; maxResponseBytes?: number; profile?: string; + watch?: boolean; } declare function runMcpServer(opts?: McpServerOptions): Promise; diff --git a/scripts/engine.browser.mjs b/scripts/engine.browser.mjs index cfe8448..8a02955 100644 --- a/scripts/engine.browser.mjs +++ b/scripts/engine.browser.mjs @@ -1,71 +1,73 @@ -var Au=Object.defineProperty;var O=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(r){throw n=[r],r}};var xi=(e,t)=>{for(var n in t)Au(e,n,{get:t[n],enumerable:!0})};function Ga(e){let t="";for(let r=0;r{"use strict";Tu=new TextDecoder("utf-8"),Iu=new TextDecoder("utf-16le"),Ha=new TextEncoder,za="0123456789abcdef";T=class e extends Uint8Array{static from(t,n){if(typeof t=="string"){if(n==="hex"){let l=new e(t.length>>1);for(let c=0;ca+l.byteLength,0),s=new e(r),o=0;for(let a of t){if(o+a.byteLength>r){s.set(a.subarray(0,r-o),o);break}s.set(a,o),o+=a.byteLength}return s}subarray(t,n){return super.subarray(t,n)}toString(t,n,r){let s=n!==void 0||r!==void 0?this.subarray(n??0,r??this.length):this;switch((t??"utf8").toLowerCase()){case"utf8":case"utf-8":return Tu.decode(s);case"utf16le":case"utf-16le":case"ucs2":case"ucs-2":return Iu.decode(s);case"latin1":case"binary":case"ascii":return Ga(s);case"hex":{let o="";for(let a of s)o+=za[a>>4]+za[a&15];return o}case"base64":return btoa(Ga(s));default:throw new TypeError(`Unknown encoding: ${t}`)}}swap16(){if(this.length%2!==0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let t=0;t"/",exit:e=>{throw new Error(`process.exit(${e??0}) is not available in the browser build`)},hrtime:Object.assign(e=>{let t=performance.now(),n=Math.floor(t/1e3),r=Math.floor(t%1e3*1e6);return e?[n-e[0],r-e[1]]:[n,r]},{bigint:()=>BigInt(Math.floor(performance.now()*1e6))}),memoryUsage:()=>({rss:0,heapTotal:0,heapUsed:0,external:0,arrayBuffers:0}),stdout:{write:e=>(console.log(e.replace(/\n$/,"")),!0),isTTY:!1},stderr:{write:e=>(console.warn(e.replace(/\n$/,"")),!0),isTTY:!1},on:()=>v,emitWarning:e=>console.warn(e)}});var fe,We,fn,qe=O(()=>{"use strict";S();fe="2.28.0",We=5,fn=13});function qa(e,t){let n="",r=0,s=-1,o=0,a=0;for(let l=0;l<=e.length;++l){if(l2){let c=n.lastIndexOf("/");c===-1?(n="",r=0):(n=n.slice(0,c),r=n.length-1-n.lastIndexOf("/")),s=l,o=0;continue}else if(n.length!==0){n="",r=0,s=l,o=0;continue}}t&&(n+=n.length>0?"/..":"..",r=2)}else n.length>0?n+="/"+e.slice(s+1,l):n=e.slice(s+1,l),r=l-s-1;s=l,o=0}else a===46&&o!==-1?++o:o=-1}return n}function Vr(e){if(e.length===0)return".";let t=e.charCodeAt(0)===47,n=e.charCodeAt(e.length-1)===47,r=qa(e,!t);return r.length===0&&!t&&(r="."),r.length>0&&n&&(r+="/"),t?"/"+r:r}function Jr(e){return e.length>0&&e.charCodeAt(0)===47}function I(...e){if(e.length===0)return".";let t;for(let n of e)n.length>0&&(t=t===void 0?n:t+"/"+n);return t===void 0?".":Vr(t)}function Ae(...e){let t="",n=!1;for(let s=e.length-1;s>=0&&!n;s--){let o=e[s];o===void 0||o.length===0||(t=t.length===0?o:o+"/"+t,n=o.charCodeAt(0)===47)}n||(t=t.length===0?"/":"/"+t);let r=qa(t,!1);return r.length>0?"/"+r:"/"}function Nu(e,t){if(e===t)return"";let n=Ae(e),r=Ae(t);if(n===r)return"";let s=n.slice(1).split("/").filter(Boolean),o=r.slice(1).split("/").filter(Boolean),a=0;for(;a=1;--s)if(e.charCodeAt(s)===47){if(!r){n=s;break}}else r=!1;return n===-1?t?"/":".":t&&n===1?"//":e.slice(0,n)}function ke(e,t){let n=0,r=-1,s=!0;for(let a=e.length-1;a>=0;--a)if(e.charCodeAt(a)===47){if(!s){n=a+1;break}}else r===-1&&(s=!1,r=a+1);if(r===-1)return"";let o=e.slice(n,r);return t!==void 0&&t!==o&&o.endsWith(t)?o.slice(0,o.length-t.length):o}function Kr(e){let t=-1,n=0,r=-1,s=!0,o=0;for(let a=e.length-1;a>=0;--a){let l=e.charCodeAt(a);if(l===47){if(!s){n=a+1;break}continue}r===-1&&(s=!1,r=a+1),l===46?t===-1?t=a:o!==1&&(o=1):t!==-1&&(o=-1)}return t===-1||r===-1||o===0||o===1&&t===r-1&&t===n+1?"":e.slice(t,r)}function Ou(e){let t=Jr(e)?"/":"",n=ke(e),r=Kr(e),s=Se(e);return{root:t,dir:s==="."&&t===""?"":s,base:n,ext:r,name:n.slice(0,n.length-r.length)}}function Fu(e){let t=e.dir||e.root||"",n=e.base||(e.name??"")+(e.ext??"");return t?t===e.root?t+n:t+"/"+n:n}function Pu(e){return e}var D,ky,ie=O(()=>{"use strict";S();D={sep:"/",delimiter:":",normalize:Vr,isAbsolute:Jr,join:I,resolve:Ae,relative:Nu,dirname:Se,basename:ke,extname:Kr,parse:Ou,format:Fu,toNamespacedPath:Pu},ky={...D,posix:D,win32:D}});function Be(e){let t=e.startsWith("/")?e:"/"+e,n=Vr(t);return n.length>1&&n.endsWith("/")?n.slice(0,-1):n}function Ht(e,t){let n=new Error(`ENOENT: no such file or directory, ${t} '${e}'`);return n.code="ENOENT",n.errno=-2,n.path=e,n.syscall=t,n}function Va(e,t){let n=new Error(`ENOTDIR: not a directory, ${t} '${e}'`);return n.code="ENOTDIR",n.errno=-20,n.path=e,n.syscall=t,n}function mn(e){let t=Be(e),n=ge.get(t);if(n){if(n.kind!=="dir")throw Va(e,"mkdir");return n}let r={kind:"dir",mtimeMs:0,children:new Set};return ge.set(t,r),t!==Bt&&mn(Se(t)).children.add(ke(t)),r}function $u(){ge.clear(),ge.set(Bt,{kind:"dir",mtimeMs:0,children:new Set})}function Ja(e){for(let t of e){let n=Be(t.path);mn(Se(n)).children.add(ke(n)),ge.set(n,{kind:"file",size:t.size,mtimeMs:0,bytes:t.bytes})}}function Xr(e,t){let n=Be(e),r=ge.get(n);if(r&&r.kind==="file"){r.bytes=t,r.size=t.byteLength;return}Ja([{path:n,size:t.byteLength,bytes:t}])}function Du(e){let t=ge.get(Be(e));return!!t&&t.kind==="file"&&t.bytes!==void 0}function Lu(){let e=0;for(let[t,n]of[...ge]){if(n.kind!=="file"||n.bytes!==void 0)continue;ge.delete(t);let r=ge.get(Se(t));r&&r.kind==="dir"&&r.children.delete(ke(t)),e++}return e}function ju(){let e=0;for(let t of ge.values())t.kind==="file"&&t.bytes&&(e+=t.bytes.byteLength);return e}function Uu(e,t,n){return{name:e,parentPath:t,path:t,isFile:()=>n==="file",isDirectory:()=>n==="dir",isSymbolicLink:st,isBlockDevice:st,isCharacterDevice:st,isFIFO:st,isSocket:st}}function Wu(e){return{size:e.kind==="file"?e.size:0,mtimeMs:e.mtimeMs,mtime:new Date(e.mtimeMs),isFile:()=>e.kind==="file",isDirectory:()=>e.kind==="dir",isSymbolicLink:st,isBlockDevice:st,isCharacterDevice:st,isFIFO:st,isSocket:st}}function z(e){return ge.has(Be(e))}function Ve(e){let t=ge.get(Be(e));if(!t)throw Ht(e,"stat");return Wu(t)}function Zr(e){let t=Be(e);if(!ge.has(t))throw Ht(e,"realpath");return t}function pn(e,t){let n=Be(e),r=ge.get(n);if(!r)throw Ht(e,"scandir");if(r.kind!=="dir")throw Va(e,"scandir");let s=[...r.children];return t?.withFileTypes?s.map(o=>{let a=ge.get(n===Bt?`/${o}`:`${n}/${o}`);return Uu(o,n,a?.kind==="dir"?"dir":"file")}):s}function te(e,t){let n=ge.get(Be(e));if(!n)throw Ht(e,"open");if(n.kind!=="file"){let s=new Error("EISDIR: illegal operation on a directory, read");throw s.code="EISDIR",s}if(!n.bytes)throw Ht(e,"open");let r=T.from(n.bytes);return t?r.toString(typeof t=="string"?t:t.encoding):r}function Re(e,t){let n=typeof t=="string"?new TextEncoder().encode(t):t;Xr(e,n)}function ft(e,t){mn(e)}function Xa(e){let t=`${e}${Bu++}`;return mn(t),t}function zt(e,t){let n=Be(e),r=ge.get(n);if(!r){if(t?.force)return;throw Ht(e,"unlink")}if(r.kind==="dir")for(let o of[...r.children])zt(n===Bt?`/${o}`:`${n}/${o}`,t);ge.delete(n);let s=ge.get(Se(n));s&&s.kind==="dir"&&s.children.delete(ke(n))}function Si(e,t){let n=Be(e),r=ge.get(n);if(!r)throw Ht(e,"rename");let s=Be(t);if(r.kind==="dir"){mn(s);for(let o of[...r.children])Si(n===Bt?`/${o}`:`${n}/${o}`,s===Bt?`/${o}`:`${s}/${o}`)}else mn(Se(s)).children.add(ke(s)),ge.set(s,r);zt(n,{force:!0})}var Bt,ge,st,Ka,Bu,we=O(()=>{"use strict";S();ie();Bt="/",ge=new Map([[Bt,{kind:"dir",mtimeMs:0,children:new Set}]]);st=()=>!1;Ka=Ve;Bu=0});function Za(e,t,n){let r=new Error(`spawnSync ${e} ENOENT`);return r.code="ENOENT",r.errno=-2,r.syscall=`spawnSync ${e}`,r.path=e,{pid:0,output:[],stdout:"",stderr:"",status:null,signal:null,error:r}}function Ya(e,t,n){let r=new Map,s={pid:void 0,stdin:null,stdout:null,stderr:null,on(a,l){let c=r.get(a)??[];return c.push(l),r.set(a,c),s},kill:()=>!1},o=new Error(`spawn ${e} ENOENT`);return o.code="ENOENT",o.syscall=`spawn ${e}`,o.path=e,Promise.resolve().then(()=>{for(let a of r.get("error")??[])a(o);for(let a of r.get("close")??[])a(null)}),s}var ki=O(()=>{S()});function me(e,t,n={}){let r=Za(e,t,{cwd:n.cwd,input:n.input,encoding:"utf8",timeout:n.timeoutMs??12e4,maxBuffer:67108864,env:n.env??v.env}),s=!!r.error&&r.error.code==="ENOENT";return{ok:!r.error&&r.status===0,status:r.status,stdout:r.stdout??"",stderr:r.stderr??(r.error?String(r.error.message):""),missing:s}}function it(e){let t=Qa.get(e);if(t!==void 0)return t;let n=me(v.platform==="win32"?"where":"which",[e]),r=n.ok&&n.stdout.trim().length>0;return Qa.set(e,r),r}function Ei(e){return e.toLowerCase().replace(/^https?:\/\//,"").replace(/^git@/,"").replace(/\.git$/,"").replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,120)}function Hu(e,t){return e.length<=t?e:e.slice(0,t)+` -\u2026 [truncated ${e.length-t} chars]`}function zu(e,t){let n=e.replace(/\s+/g," ").trim();if(n.length<=t)return n;let r=n.slice(0,t).replace(/\s+\S*$/,"");return r||(r=n.slice(0,t)),(r.match(/`/g)?.length??0)%2===1&&(r=r.replace(/`[^`]*$/,"")),r.lastIndexOf("[")>r.lastIndexOf("]")&&(r=r.slice(0,r.lastIndexOf("["))),r.replace(/\s+$/,"")+"\u2026"}function He(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function mt(e){return e.normalize("NFKD").replace(/[̀-ͯ]/g,"")}function Yr(e){let t=new Set,n=[];for(let r of mt(e).split(/[^A-Za-z0-9_]+/)){if(!r)continue;let s=r.toLowerCase();r.length<2||el.has(s)||t.has(s)||(t.add(s),n.push(r))}return n}function Qr(e){let t=[];for(let n of mt(e).split(/[^A-Za-z0-9_]+/))n&&(n.length<2||el.has(n.toLowerCase()))&&t.push(n);return t}function Gu(e){let t=Yr(e),n=r=>{let s=0;return/\d/.test(r)&&(s+=3),/[A-Z]/.test(r)&&!/^[A-Z0-9]+$/.test(r)&&(s+=2),/_/.test(r)&&(s+=2),r.length>=8?s+=1.5:r.length>=5&&(s+=.5),s};return t.map((r,s)=>({k:r,s:n(r),i:s})).sort((r,s)=>s.s-r.s||r.i-s.i).map(r=>r.k)}function vi(e,t,n=60){let r=new Map;for(let s of e)s.forEach((o,a)=>{let l=t(o);r.set(l,(r.get(l)??0)+1/(n+a+1))});return r}function pt(e){let t=mt(e).replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1 $2"),n=[],r=new Set,s=o=>{o.length<2||r.has(o)||(r.add(o),n.push(o))};/\s/.test(e.trim())||s(mt(e).toLowerCase().replace(/[^a-z0-9_]+/g,""));for(let o of t.split(/[^A-Za-z0-9]+/))s(o.toLowerCase());return n}function Ri(e){if(e.length<4)return e;let t=e;return t.endsWith("ies")&&t.length>4?t=t.slice(0,-3)+"y":t.endsWith("sses")?t=t.slice(0,-2):(t.endsWith("ses")&&t.length>4||t.endsWith("s")&&!t.endsWith("ss")&&!t.endsWith("us")&&!t.endsWith("is"))&&(t=t.slice(0,-1)),t.endsWith("ying")&&t.length>5?t=t.slice(0,-4)+"y":t.endsWith("ing")&&t.length>5?t=t.slice(0,-3):t.endsWith("ed")&&t.length>4&&(t=t.slice(0,-2)),t.endsWith("e")&&t.length>3&&(t=t.slice(0,-1)),t}var Qa,el,Me=O(()=>{"use strict";S();ki();Qa=new Map;el=new Set(["the","a","an","is","are","was","were","be","been","being","do","does","did","how","what","why","when","where","which","who","whom","this","that","these","those","of","in","on","to","for","with","and","or","but","if","then","else","than","as","at","by","from","into","about","it","its","i","you","we","they","he","she","there","here","can","could","should","would","will","shall","may","might","must","have","has","had","not","no","yes","so","such","only","any","some","all","get","set","use","used","using","work","works","working","handle","handled","happen","happens","default","value","values","please","explain","tell","me","my","our"])});function qu(e){let t="";for(let n=0;n{"use strict";S();Me()});function Le(e,t={}){let n=t.maxFileBytes??1048576,r=t.maxFiles??1/0,s=t.gitignore!==!1,o=t.ignoreDirs?new Set(t.ignoreDirs):Pn,a=[],l=!1,c=0,d;try{d=Zr(e)}catch{return{files:a,capped:l,excluded:c}}let u=m=>m===d||m.startsWith(d+"/"),f=[{dir:e,rel:"",rules:[]}],p=new Set;e:for(;f.length;){let m=f.pop(),g;try{g=Zr(m.dir)}catch{continue}if(p.has(g)||(p.add(g),!u(g)))continue;let h;try{h=pn(m.dir,{withFileTypes:!0}).sort((y,x)=>y.namex.name?1:0)}catch{continue}let _=m.rules;if(s&&h.some(y=>y.name===".gitignore")){let y=Mi(G(I(m.dir,".gitignore")),m.rel);y.length&&(_=[..._,...y])}for(let y of h){let x=y.name,E=I(m.dir,x),w=m.rel?`${m.rel}/${x}`:x,k=y.isSymbolicLink();if(y.isDirectory()&&o.has(x))continue;let C;try{C=k?Ve(E):Ka(E)}catch{continue}if(C.isDirectory()){if(o.has(x)||k||s&&_.length&&es(_,w,!0))continue;f.push({dir:E,rel:w,rules:_});continue}if(!C.isFile())continue;if(C.size>n){c++;continue}if(Ai.has(x.toLowerCase())){c++;continue}let A=Kr(x).toLowerCase();if(Ti.has(A)){c++;continue}if(x.endsWith(".min.js")||x.endsWith(".min.css")){c++;continue}if(s&&_.length&&es(_,w,!1)){c++;continue}if(k)try{if(!u(Zr(E)))continue}catch{continue}if(a.length>=r){l=!0;break e}a.push({rel:w.split("/").join("/"),abs:E,size:C.size,ext:A,mtimeMs:C.mtimeMs})}}return{files:a,capped:l,excluded:c}}function G(e){try{let t=te(e);if(t.length>=2&&t[0]===255&&t[1]===254)return t.subarray(2,2+(t.length-2&-2)).toString("utf16le");if(t.length>=2&&t[0]===254&&t[1]===255){let r=T.from(t.subarray(2,2+(t.length-2&-2)));return r.swap16(),r.toString("utf16le")}if(t.length>=3&&t[0]===239&&t[1]===187&&t[2]===191)return t.subarray(3).toString("utf8");if(t.includes(0))return"";let n=t.toString("utf8");return n.includes("\uFFFD")?t.toString("latin1"):n}catch{return""}}var Pn,Ai,Ti,Vu,Te=O(()=>{"use strict";S();we();ie();Ci();Pn=new Set([".git","node_modules",".pnpm","bower_components","vendor","dist","build","out","target",".next",".nuxt",".svelte-kit",".turbo","coverage","__pycache__",".venv","venv",".tox",".mypy_cache",".pytest_cache",".gradle",".idea",".vscode",".cache","tmp",".ultraindex",".codeindex","Pods","DerivedData",".terraform","elm-stuff",".dart_tool"]),Ai=new Set(["package-lock.json","npm-shrinkwrap.json","yarn.lock","pnpm-lock.yaml","bun.lockb","composer.lock","cargo.lock","poetry.lock","pipfile.lock","gemfile.lock","go.sum","flake.lock","packages.lock.json","podfile.lock","mix.lock"]),Ti=new Set([".png",".jpg",".jpeg",".gif",".webp",".bmp",".ico",".icns",".svg",".pdf",".zip",".gz",".tar",".tgz",".bz2",".xz",".7z",".rar",".jar",".war",".class",".so",".dylib",".dll",".exe",".bin",".o",".a",".wasm",".woff",".woff2",".ttf",".otf",".eot",".mp3",".mp4",".mov",".avi",".webm",".wav",".flac",".ogg",".lock",".min.js",".map"]),Vu=2e4});function ns(e){let t=me("git",["-C",e,"rev-parse","--short","HEAD"]);return t.ok?t.stdout.trim():void 0}function Ni(e){return me("git",["-C",e,"rev-parse","--is-inside-work-tree"]).ok}function Oi(e,t){let n=l=>me("git",[...ot(e),"rev-parse","--verify","--quiet",`${l}^{commit}`]).ok,r=l=>{let c=me("git",[...ot(e),"merge-base",l,"HEAD"]);return c.ok?c.stdout.trim():void 0};if(t){if(!n(t))return{error:`base ref "${t}" not found (tried git rev-parse --verify)`};let l=r(t);return l?{ref:t,mergeBase:l}:{error:`no merge-base between "${t}" and HEAD`}}let s=me("git",[...ot(e),"symbolic-ref","--quiet","refs/remotes/origin/HEAD"]),o=[...s.ok?[s.stdout.trim().replace("refs/remotes/","")]:[],"origin/main","origin/master","main","master"];for(let l of o){if(!n(l))continue;let c=r(l);if(c)return{ref:l,mergeBase:c}}let a=me("git",[...ot(e),"rev-parse","HEAD"]);return a.ok?{ref:"HEAD",mergeBase:a.stdout.trim(),note:"base: HEAD (no default branch found \u2014 reviewing uncommitted work)"}:{error:"cannot resolve HEAD \u2014 empty repository?"}}function Fi(e,t){let n=[],r=me("git",[...ot(e),"diff","-z","-M","--name-status",...Ii(t)]);if(r.ok){let a=r.stdout.split("\0"),l=0;for(;l[a.path,a])),o=me("git",[...ot(e),"diff","-z","-M","--numstat",...Ii(t)]);if(o.ok){let a=o.stdout.split("\0"),l=0;for(;ln.length>0):[]}function Je(e,t={}){let n=new Map,r=t.since?[`${t.since}..HEAD`]:[],s=me("git",[...ot(e),"log",...r,"--pretty=format:","--name-only","-z"]);if(!s.ok)return{churn:n,ok:!1};for(let o of s.stdout.split("\0")){let a=o.replace(/^\n+/,"").trim();a&&n.set(a,(n.get(a)??0)+1)}return{churn:n,ok:!0}}function Ju(e,t){let n=new Set,r=me("git",[...ot(e),"diff","-z","--name-only",t,"--"]);if(r.ok)for(let s of r.stdout.split("\0"))s&&n.add(s);for(let s of rs(e))n.add(s);return n}var ot,Ii,Gt=O(()=>{"use strict";S();Me();ot=e=>["-C",e,"-c","core.quotePath=false"],Ii=e=>e.staged?["--cached"]:[e.mergeBase]});function Ku(e){return typeof e=="string"?new TextEncoder().encode(e):e}function Xu(e,t){if(e.length===1)return e[0];let n=new Uint8Array(t),r=0;for(let s of e)n.set(s,r),r+=s.byteLength;return n}function nl(e){let t=Math.floor(e.byteLength/536870912|0),n=e.byteLength<<3>>>0,r=Math.ceil((e.byteLength+9)/64),s=new Uint8Array(r*64);s.set(e),s[e.byteLength]=128;let o=new DataView(s.buffer);return o.setUint32(s.byteLength-8,t,!1),o.setUint32(s.byteLength-4,n,!1),o}function $i(e,t){return(e<>>32-t)>>>0}function at(e,t){return(e>>>t|e<<32-t)>>>0}function Zu(e){let t=nl(e),n=1732584193,r=4023233417,s=2562383102,o=271733878,a=3285377520,l=new Uint32Array(80);for(let u=0;u>>0;h=g,g=m,m=$i(p,30),p=f,f=E}n=n+f>>>0,r=r+p>>>0,s=s+m>>>0,o=o+g>>>0,a=a+h>>>0}let c=new Uint8Array(20),d=new DataView(c.buffer);return[n,r,s,o,a].forEach((u,f)=>d.setUint32(f*4,u,!1)),c}function Qu(e){let t=nl(e),n=1779033703,r=3144134277,s=1013904242,o=2773480762,a=1359893119,l=2600822924,c=528734635,d=1541459225,u=new Uint32Array(64);for(let m=0;m>>3,W=at(F,17)^at(F,19)^F>>>10;u[C]=u[C-16]+N+u[C-7]+W>>>0}let g=n,h=r,_=s,y=o,x=a,E=l,w=c,k=d;for(let C=0;C<64;C++){let A=at(x,6)^at(x,11)^at(x,25),F=x&E^~x&w,N=k+A+F+Yu[C]+u[C]>>>0,W=at(g,2)^at(g,13)^at(g,22),q=g&h^g&_^h&_,X=W+q>>>0;k=w,w=E,E=x,x=y+N>>>0,y=_,_=h,h=g,g=N+X>>>0}n=n+g>>>0,r=r+h>>>0,s=s+_>>>0,o=o+y>>>0,a=a+x>>>0,l=l+E>>>0,c=c+w>>>0,d=d+k>>>0}let f=new Uint8Array(32),p=new DataView(f.buffer);return[n,r,s,o,a,l,c,d].forEach((m,g)=>p.setUint32(g*4,m,!1)),f}function ef(e){let t="";for(let n of e)t+=tl[n>>4]+tl[n&15];return t}function tf(e){let t="";for(let n of e)t+=String.fromCharCode(n);return btoa(t)}function gn(e){let t=e.toLowerCase().replace("-","");if(t!=="sha1"&&t!=="sha256")throw new Error(`createHash: unsupported algorithm "${e}" in the browser build (sha1, sha256)`);let n=[],r=0,s={update(o){let a=Ku(o);return n.push(a),r+=a.byteLength,s},digest(o){let a=r===0?new Uint8Array(0):Xu(n,r),l=t==="sha1"?Zu(a):Qu(a);return o==="hex"?ef(l):o==="base64"?tf(l):l}};return s}var Yu,tl,ss=O(()=>{S();Yu=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]);tl="0123456789abcdef"});function ve(e){return gn("sha1").update(e).digest("hex")}function nf(e,t=8){return ve(e).slice(0,t)}var Rt=O(()=>{"use strict";S();ss()});function ne(e,t,n,r){let s=[],o=t.split(/\r?\n/);for(let a=0;a()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(r){throw n=[r],r}};var Oi=(e,t)=>{for(var n in t)qu(e,n,{get:t[n],enumerable:!0})};function tl(e){let t="";for(let r=0;r{"use strict";Gu=new TextDecoder("utf-8"),Vu=new TextDecoder("utf-16le"),Qa=new TextEncoder,el="0123456789abcdef";T=class e extends Uint8Array{static from(t,n){if(typeof t=="string"){if(n==="hex"){let l=new e(t.length>>1);for(let c=0;ca+l.byteLength,0),s=new e(r),o=0;for(let a of t){if(o+a.byteLength>r){s.set(a.subarray(0,r-o),o);break}s.set(a,o),o+=a.byteLength}return s}subarray(t,n){return super.subarray(t,n)}toString(t,n,r){let s=n!==void 0||r!==void 0?this.subarray(n??0,r??this.length):this;switch((t??"utf8").toLowerCase()){case"utf8":case"utf-8":return Gu.decode(s);case"utf16le":case"utf-16le":case"ucs2":case"ucs-2":return Vu.decode(s);case"latin1":case"binary":case"ascii":return tl(s);case"hex":{let o="";for(let a of s)o+=el[a>>4]+el[a&15];return o}case"base64":return btoa(tl(s));default:throw new TypeError(`Unknown encoding: ${t}`)}}swap16(){if(this.length%2!==0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let t=0;t"/",exit:e=>{throw new Error(`process.exit(${e??0}) is not available in the browser build`)},hrtime:Object.assign(e=>{let t=performance.now(),n=Math.floor(t/1e3),r=Math.floor(t%1e3*1e6);return e?[n-e[0],r-e[1]]:[n,r]},{bigint:()=>BigInt(Math.floor(performance.now()*1e6))}),memoryUsage:()=>({rss:0,heapTotal:0,heapUsed:0,external:0,arrayBuffers:0}),stdout:{write:e=>(console.log(e.replace(/\n$/,"")),!0),isTTY:!1},stderr:{write:e=>(console.warn(e.replace(/\n$/,"")),!0),isTTY:!1},on:()=>R,emitWarning:e=>console.warn(e)}});var fe,He,mn,Xe=F(()=>{"use strict";k();fe="2.28.0",He=5,mn=14});function nl(e,t){let n="",r=0,s=-1,o=0,a=0;for(let l=0;l<=e.length;++l){if(l2){let c=n.lastIndexOf("/");c===-1?(n="",r=0):(n=n.slice(0,c),r=n.length-1-n.lastIndexOf("/")),s=l,o=0;continue}else if(n.length!==0){n="",r=0,s=l,o=0;continue}}t&&(n+=n.length>0?"/..":"..",r=2)}else n.length>0?n+="/"+e.slice(s+1,l):n=e.slice(s+1,l),r=l-s-1;s=l,o=0}else a===46&&o!==-1?++o:o=-1}return n}function Yr(e){if(e.length===0)return".";let t=e.charCodeAt(0)===47,n=e.charCodeAt(e.length-1)===47,r=nl(e,!t);return r.length===0&&!t&&(r="."),r.length>0&&n&&(r+="/"),t?"/"+r:r}function Qr(e){return e.length>0&&e.charCodeAt(0)===47}function I(...e){if(e.length===0)return".";let t;for(let n of e)n.length>0&&(t=t===void 0?n:t+"/"+n);return t===void 0?".":Yr(t)}function Ne(...e){let t="",n=!1;for(let s=e.length-1;s>=0&&!n;s--){let o=e[s];o===void 0||o.length===0||(t=t.length===0?o:o+"/"+t,n=o.charCodeAt(0)===47)}n||(t=t.length===0?"/":"/"+t);let r=nl(t,!1);return r.length>0?"/"+r:"/"}function Ju(e,t){if(e===t)return"";let n=Ne(e),r=Ne(t);if(n===r)return"";let s=n.slice(1).split("/").filter(Boolean),o=r.slice(1).split("/").filter(Boolean),a=0;for(;a=1;--s)if(e.charCodeAt(s)===47){if(!r){n=s;break}}else r=!1;return n===-1?t?"/":".":t&&n===1?"//":e.slice(0,n)}function ke(e,t){let n=0,r=-1,s=!0;for(let a=e.length-1;a>=0;--a)if(e.charCodeAt(a)===47){if(!s){n=a+1;break}}else r===-1&&(s=!1,r=a+1);if(r===-1)return"";let o=e.slice(n,r);return t!==void 0&&t!==o&&o.endsWith(t)?o.slice(0,o.length-t.length):o}function es(e){let t=-1,n=0,r=-1,s=!0,o=0;for(let a=e.length-1;a>=0;--a){let l=e.charCodeAt(a);if(l===47){if(!s){n=a+1;break}continue}r===-1&&(s=!1,r=a+1),l===46?t===-1?t=a:o!==1&&(o=1):t!==-1&&(o=-1)}return t===-1||r===-1||o===0||o===1&&t===r-1&&t===n+1?"":e.slice(t,r)}function Ku(e){let t=Qr(e)?"/":"",n=ke(e),r=es(e),s=_e(e);return{root:t,dir:s==="."&&t===""?"":s,base:n,ext:r,name:n.slice(0,n.length-r.length)}}function Xu(e){let t=e.dir||e.root||"",n=e.base||(e.name??"")+(e.ext??"");return t?t===e.root?t+n:t+"/"+n:n}function Zu(e){return e}var $,qy,oe=F(()=>{"use strict";k();$={sep:"/",delimiter:":",normalize:Yr,isAbsolute:Qr,join:I,resolve:Ne,relative:Ju,dirname:_e,basename:ke,extname:es,parse:Ku,format:Xu,toNamespacedPath:Zu},qy={...$,posix:$,win32:$}});function sl(){return++rl}function Ue(e){let t=e.startsWith("/")?e:"/"+e,n=Yr(t);return n.length>1&&n.endsWith("/")?n.slice(0,-1):n}function Ct(e,t){let n=new Error(`ENOENT: no such file or directory, ${t} '${e}'`);return n.code="ENOENT",n.errno=-2,n.path=e,n.syscall=t,n}function il(e,t){let n=new Error(`ENOTDIR: not a directory, ${t} '${e}'`);return n.code="ENOTDIR",n.errno=-20,n.path=e,n.syscall=t,n}function pn(e){let t=Ue(e),n=me.get(t);if(n){if(n.kind!=="dir")throw il(e,"mkdir");return n}let r={kind:"dir",mtimeMs:0,mode:511,children:new Set};return me.set(t,r),t!==Ht&&pn(_e(t)).children.add(ke(t)),r}function Yu(){me.clear(),rl=0,ll=0,me.set(Ht,{kind:"dir",mtimeMs:0,mode:511,children:new Set})}function ol(e){for(let t of e){let n=Ue(t.path);pn(_e(n)).children.add(ke(n)),me.set(n,{kind:"file",size:t.size,mtimeMs:sl(),mode:438,bytes:t.bytes})}}function ts(e,t){let n=Ue(e),r=me.get(n);if(r&&r.kind==="file"){r.bytes=t,r.size=t.byteLength,r.mtimeMs=sl();return}ol([{path:n,size:t.byteLength,bytes:t}])}function Qu(e){let t=me.get(Ue(e));return!!t&&t.kind==="file"&&t.bytes!==void 0}function ef(){let e=0;for(let[t,n]of[...me]){if(n.kind!=="file"||n.bytes!==void 0)continue;me.delete(t);let r=me.get(_e(t));r&&r.kind==="dir"&&r.children.delete(ke(t)),e++}return e}function tf(){let e=0;for(let t of me.values())t.kind==="file"&&t.bytes&&(e+=t.bytes.byteLength);return e}function nf(e,t,n){return{name:e,parentPath:t,path:t,isFile:()=>n==="file",isDirectory:()=>n==="dir",isSymbolicLink:ot,isBlockDevice:ot,isCharacterDevice:ot,isFIFO:ot,isSocket:ot}}function rf(e){return{size:e.kind==="file"?e.size:0,mode:e.mode,mtimeMs:e.mtimeMs,mtime:new Date(e.mtimeMs),isFile:()=>e.kind==="file",isDirectory:()=>e.kind==="dir",isSymbolicLink:ot,isBlockDevice:ot,isCharacterDevice:ot,isFIFO:ot,isSocket:ot}}function H(e){return me.has(Ue(e))}function Ee(e){let t=me.get(Ue(e));if(!t)throw Ct(e,"stat");return rf(t)}function gn(e){let t=Ue(e);if(!me.has(t))throw Ct(e,"realpath");return t}function _n(e,t){let n=Ue(e),r=me.get(n);if(!r)throw Ct(e,"scandir");if(r.kind!=="dir")throw il(e,"scandir");let s=[...r.children];return t?.withFileTypes?s.map(o=>{let a=me.get(n===Ht?`/${o}`:`${n}/${o}`);return nf(o,n,a?.kind==="dir"?"dir":"file")}):s}function te(e,t){let n=me.get(Ue(e));if(!n)throw Ct(e,"open");if(n.kind!=="file"){let s=new Error("EISDIR: illegal operation on a directory, read");throw s.code="EISDIR",s}if(!n.bytes)throw Ct(e,"open");let r=T.from(n.bytes);return t?r.toString(typeof t=="string"?t:t.encoding):r}function Re(e,t){let n=typeof t=="string"?new TextEncoder().encode(t):t;ts(e,n)}function ns(e,t){let n=me.get(Ue(e));if(!n)throw Ct(e,"chmod");n.mode=t}function gt(e,t){pn(e)}function Ln(e){let t=`${e}${ll++}`;return pn(t),t}function qe(e,t){let n=Ue(e),r=me.get(n);if(!r){if(t?.force)return;throw Ct(e,"unlink")}if(r.kind==="dir")for(let o of[...r.children])qe(n===Ht?`/${o}`:`${n}/${o}`,t);me.delete(n);let s=me.get(_e(n));s&&s.kind==="dir"&&s.children.delete(ke(n))}function Dn(e,t){let n=Ue(e),r=me.get(n);if(!r)throw Ct(e,"rename");let s=Ue(t);if(r.kind==="dir"){pn(s);for(let o of[...r.children])Dn(n===Ht?`/${o}`:`${n}/${o}`,s===Ht?`/${o}`:`${s}/${o}`)}else pn(_e(s)).children.add(ke(s)),me.set(s,r);qe(n,{force:!0})}function cl(){throw new Error("recursive filesystem watching is unavailable in the browser VFS")}var Ht,me,rl,ot,al,ll,xe=F(()=>{"use strict";k();oe();Ht="/",me=new Map([[Ht,{kind:"dir",mtimeMs:0,mode:511,children:new Set}]]),rl=0;ot=()=>!1;al=Ee;ll=0});function dl(e,t,n){let r=new Error(`spawnSync ${e} ENOENT`);return r.code="ENOENT",r.errno=-2,r.syscall=`spawnSync ${e}`,r.path=e,{pid:0,output:[],stdout:"",stderr:"",status:null,signal:null,error:r}}function ul(e,t,n){let r=new Map,s={pid:void 0,stdin:null,stdout:null,stderr:null,on(a,l){let c=r.get(a)??[];return c.push(l),r.set(a,c),s},kill:()=>!1},o=new Error(`spawn ${e} ENOENT`);return o.code="ENOENT",o.syscall=`spawn ${e}`,o.path=e,Promise.resolve().then(()=>{for(let a of r.get("error")??[])a(o);for(let a of r.get("close")??[])a(null)}),s}var Fi=F(()=>{k()});function pe(e,t,n={}){let r=dl(e,t,{cwd:n.cwd,input:n.input,encoding:"utf8",timeout:n.timeoutMs??12e4,maxBuffer:67108864,env:n.env??R.env}),s=!!r.error&&r.error.code==="ENOENT";return{ok:!r.error&&r.status===0,status:r.status,stdout:r.stdout??"",stderr:r.stderr??(r.error?String(r.error.message):""),missing:s}}function at(e){let t=fl.get(e);if(t!==void 0)return t;let n=pe(R.platform==="win32"?"where":"which",[e]),r=n.ok&&n.stdout.trim().length>0;return fl.set(e,r),r}function Pi(e){return e.toLowerCase().replace(/^https?:\/\//,"").replace(/^git@/,"").replace(/\.git$/,"").replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,120)}function sf(e,t){return e.length<=t?e:e.slice(0,t)+` +\u2026 [truncated ${e.length-t} chars]`}function of(e,t){let n=e.replace(/\s+/g," ").trim();if(n.length<=t)return n;let r=n.slice(0,t).replace(/\s+\S*$/,"");return r||(r=n.slice(0,t)),(r.match(/`/g)?.length??0)%2===1&&(r=r.replace(/`[^`]*$/,"")),r.lastIndexOf("[")>r.lastIndexOf("]")&&(r=r.slice(0,r.lastIndexOf("["))),r.replace(/\s+$/,"")+"\u2026"}function Ge(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function _t(e){return e.normalize("NFKD").replace(/[̀-ͯ]/g,"")}function rs(e){let t=new Set,n=[];for(let r of _t(e).split(/[^A-Za-z0-9_]+/)){if(!r)continue;let s=r.toLowerCase();r.length<2||ml.has(s)||t.has(s)||(t.add(s),n.push(r))}return n}function ss(e){let t=[];for(let n of _t(e).split(/[^A-Za-z0-9_]+/))n&&(n.length<2||ml.has(n.toLowerCase()))&&t.push(n);return t}function af(e){let t=rs(e),n=r=>{let s=0;return/\d/.test(r)&&(s+=3),/[A-Z]/.test(r)&&!/^[A-Z0-9]+$/.test(r)&&(s+=2),/_/.test(r)&&(s+=2),r.length>=8?s+=1.5:r.length>=5&&(s+=.5),s};return t.map((r,s)=>({k:r,s:n(r),i:s})).sort((r,s)=>s.s-r.s||r.i-s.i).map(r=>r.k)}function $i(e,t,n=60){let r=new Map;for(let s of e)s.forEach((o,a)=>{let l=t(o);r.set(l,(r.get(l)??0)+1/(n+a+1))});return r}function ht(e){let t=_t(e).replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1 $2"),n=[],r=new Set,s=o=>{o.length<2||r.has(o)||(r.add(o),n.push(o))};/\s/.test(e.trim())||s(_t(e).toLowerCase().replace(/[^a-z0-9_]+/g,""));for(let o of t.split(/[^A-Za-z0-9]+/))s(o.toLowerCase());return n}function Li(e){if(e.length<4)return e;let t=e;return t.endsWith("ies")&&t.length>4?t=t.slice(0,-3)+"y":t.endsWith("sses")?t=t.slice(0,-2):(t.endsWith("ses")&&t.length>4||t.endsWith("s")&&!t.endsWith("ss")&&!t.endsWith("us")&&!t.endsWith("is"))&&(t=t.slice(0,-1)),t.endsWith("ying")&&t.length>5?t=t.slice(0,-4)+"y":t.endsWith("ing")&&t.length>5?t=t.slice(0,-3):t.endsWith("ed")&&t.length>4&&(t=t.slice(0,-2)),t.endsWith("e")&&t.length>3&&(t=t.slice(0,-1)),t}var fl,ml,Ce=F(()=>{"use strict";k();Fi();fl=new Map;ml=new Set(["the","a","an","is","are","was","were","be","been","being","do","does","did","how","what","why","when","where","which","who","whom","this","that","these","those","of","in","on","to","for","with","and","or","but","if","then","else","than","as","at","by","from","into","about","it","its","i","you","we","they","he","she","there","here","can","could","should","would","will","shall","may","might","must","have","has","had","not","no","yes","so","such","only","any","some","all","get","set","use","used","using","work","works","working","handle","handled","happen","happens","default","value","values","please","explain","tell","me","my","our"])});function lf(e){let t="";for(let n=0;n{"use strict";k();Ce()});function pl(e,t){return t.has(e)||e.startsWith(".codeindex-edit-")}function Fe(e,t={}){let n=t.maxFileBytes??1048576,r=t.maxFiles??1/0,s=t.gitignore!==!1,o=t.ignoreDirs?new Set(t.ignoreDirs):qt,a=[],l=!1,c=0,d;try{d=gn(e)}catch{return{files:a,capped:l,excluded:c}}let f=p=>p===d||p.startsWith(d+"/"),u=[{dir:e,rel:"",rules:[]}],m=new Set;e:for(;u.length;){let p=u.pop(),g;try{g=gn(p.dir)}catch{continue}if(m.has(g)||(m.add(g),!f(g)))continue;let y;try{y=_n(p.dir,{withFileTypes:!0}).sort((S,_)=>S.name<_.name?-1:S.name>_.name?1:0)}catch{continue}let h=p.rules;if(s&&y.some(S=>S.name===".gitignore")){let S=Di(G(I(p.dir,".gitignore")),p.rel);S.length&&(h=[...h,...S])}for(let S of y){let _=S.name,E=I(p.dir,_),b=p.rel?`${p.rel}/${_}`:_,x=S.isSymbolicLink();if(S.isDirectory()&&pl(_,o))continue;let v;try{v=x?Ee(E):al(E)}catch{continue}if(v.isDirectory()){if(pl(_,o)||x||s&&h.length&&is(h,b,!0))continue;u.push({dir:E,rel:b,rules:h});continue}if(!v.isFile())continue;if(v.size>n){c++;continue}if(Wi.has(_.toLowerCase())){c++;continue}let A=es(_).toLowerCase();if(Ui.has(A)){c++;continue}if(_.endsWith(".min.js")||_.endsWith(".min.css")){c++;continue}if(s&&h.length&&is(h,b,!1)){c++;continue}if(x)try{if(!f(gn(E)))continue}catch{continue}if(a.length>=r){l=!0;break e}a.push({rel:b.split("/").join("/"),abs:E,size:v.size,ext:A,mtimeMs:v.mtimeMs})}}return{files:a,capped:l,excluded:c}}function G(e){try{let t=te(e);if(t.length>=2&&t[0]===255&&t[1]===254)return t.subarray(2,2+(t.length-2&-2)).toString("utf16le");if(t.length>=2&&t[0]===254&&t[1]===255){let r=T.from(t.subarray(2,2+(t.length-2&-2)));return r.swap16(),r.toString("utf16le")}if(t.length>=3&&t[0]===239&&t[1]===187&&t[2]===191)return t.subarray(3).toString("utf8");if(t.includes(0))return"";let n=t.toString("utf8");return n.includes("\uFFFD")?t.toString("latin1"):n}catch{return""}}var qt,Wi,Ui,cf,Ae=F(()=>{"use strict";k();xe();oe();ji();qt=new Set([".git","node_modules",".pnpm","bower_components","vendor","dist","build","out","target",".next",".nuxt",".svelte-kit",".turbo","coverage","__pycache__",".venv","venv",".tox",".mypy_cache",".pytest_cache",".gradle",".idea",".vscode",".cache","tmp",".ultraindex",".codeindex","Pods","DerivedData",".terraform","elm-stuff",".dart_tool"]);Wi=new Set(["package-lock.json","npm-shrinkwrap.json","yarn.lock","pnpm-lock.yaml","bun.lockb","composer.lock","cargo.lock","poetry.lock","pipfile.lock","gemfile.lock","go.sum","flake.lock","packages.lock.json","podfile.lock","mix.lock"]),Ui=new Set([".png",".jpg",".jpeg",".gif",".webp",".bmp",".ico",".icns",".svg",".pdf",".zip",".gz",".tar",".tgz",".bz2",".xz",".7z",".rar",".jar",".war",".class",".so",".dylib",".dll",".exe",".bin",".o",".a",".wasm",".woff",".woff2",".ttf",".otf",".eot",".mp3",".mp4",".mov",".avi",".webm",".wav",".flac",".ogg",".lock",".min.js",".map"]),cf=2e4});function as(e){let t=pe("git",["-C",e,"rev-parse","--short","HEAD"]);return t.ok?t.stdout.trim():void 0}function zi(e){return pe("git",["-C",e,"rev-parse","--is-inside-work-tree"]).ok}function Hi(e,t){let n=l=>pe("git",[...lt(e),"rev-parse","--verify","--quiet",`${l}^{commit}`]).ok,r=l=>{let c=pe("git",[...lt(e),"merge-base",l,"HEAD"]);return c.ok?c.stdout.trim():void 0};if(t){if(!n(t))return{error:`base ref "${t}" not found (tried git rev-parse --verify)`};let l=r(t);return l?{ref:t,mergeBase:l}:{error:`no merge-base between "${t}" and HEAD`}}let s=pe("git",[...lt(e),"symbolic-ref","--quiet","refs/remotes/origin/HEAD"]),o=[...s.ok?[s.stdout.trim().replace("refs/remotes/","")]:[],"origin/main","origin/master","main","master"];for(let l of o){if(!n(l))continue;let c=r(l);if(c)return{ref:l,mergeBase:c}}let a=pe("git",[...lt(e),"rev-parse","HEAD"]);return a.ok?{ref:"HEAD",mergeBase:a.stdout.trim(),note:"base: HEAD (no default branch found \u2014 reviewing uncommitted work)"}:{error:"cannot resolve HEAD \u2014 empty repository?"}}function qi(e,t){let n=[],r=pe("git",[...lt(e),"diff","-z","-M","--name-status",...Bi(t)]);if(r.ok){let a=r.stdout.split("\0"),l=0;for(;l[a.path,a])),o=pe("git",[...lt(e),"diff","-z","-M","--numstat",...Bi(t)]);if(o.ok){let a=o.stdout.split("\0"),l=0;for(;ln.length>0):[]}function Ze(e,t={}){let n=new Map,r=t.since?[`${t.since}..HEAD`]:[],s=pe("git",[...lt(e),"log",...r,"--pretty=format:","--name-only","-z"]);if(!s.ok)return{churn:n,ok:!1};for(let o of s.stdout.split("\0")){let a=o.replace(/^\n+/,"").trim();a&&n.set(a,(n.get(a)??0)+1)}return{churn:n,ok:!0}}function df(e,t){let n=new Set,r=pe("git",[...lt(e),"diff","-z","--name-only",t,"--"]);if(r.ok)for(let s of r.stdout.split("\0"))s&&n.add(s);for(let s of ls(e))n.add(s);return n}var lt,Bi,Gt=F(()=>{"use strict";k();Ce();lt=e=>["-C",e,"-c","core.quotePath=false"],Bi=e=>e.staged?["--cached"]:[e.mergeBase]});function uf(e){return typeof e=="string"?new TextEncoder().encode(e):e}function ff(e,t){if(e.length===1)return e[0];let n=new Uint8Array(t),r=0;for(let s of e)n.set(s,r),r+=s.byteLength;return n}function _l(e){let t=Math.floor(e.byteLength/536870912|0),n=e.byteLength<<3>>>0,r=Math.ceil((e.byteLength+9)/64),s=new Uint8Array(r*64);s.set(e),s[e.byteLength]=128;let o=new DataView(s.buffer);return o.setUint32(s.byteLength-8,t,!1),o.setUint32(s.byteLength-4,n,!1),o}function Vi(e,t){return(e<>>32-t)>>>0}function ct(e,t){return(e>>>t|e<<32-t)>>>0}function mf(e){let t=_l(e),n=1732584193,r=4023233417,s=2562383102,o=271733878,a=3285377520,l=new Uint32Array(80);for(let f=0;f>>0;y=g,g=p,p=Vi(m,30),m=u,u=E}n=n+u>>>0,r=r+m>>>0,s=s+p>>>0,o=o+g>>>0,a=a+y>>>0}let c=new Uint8Array(20),d=new DataView(c.buffer);return[n,r,s,o,a].forEach((f,u)=>d.setUint32(u*4,f,!1)),c}function gf(e){let t=_l(e),n=1779033703,r=3144134277,s=1013904242,o=2773480762,a=1359893119,l=2600822924,c=528734635,d=1541459225,f=new Uint32Array(64);for(let p=0;p>>3,U=ct(O,17)^ct(O,19)^O>>>10;f[v]=f[v-16]+N+f[v-7]+U>>>0}let g=n,y=r,h=s,S=o,_=a,E=l,b=c,x=d;for(let v=0;v<64;v++){let A=ct(_,6)^ct(_,11)^ct(_,25),O=_&E^~_&b,N=x+A+O+pf[v]+f[v]>>>0,U=ct(g,2)^ct(g,13)^ct(g,22),le=g&y^g&h^y&h,V=U+le>>>0;x=b,b=E,E=_,_=S+N>>>0,S=h,h=y,y=g,g=N+V>>>0}n=n+g>>>0,r=r+y>>>0,s=s+h>>>0,o=o+S>>>0,a=a+_>>>0,l=l+E>>>0,c=c+b>>>0,d=d+x>>>0}let u=new Uint8Array(32),m=new DataView(u.buffer);return[n,r,s,o,a,l,c,d].forEach((p,g)=>m.setUint32(g*4,p,!1)),u}function _f(e){let t="";for(let n of e)t+=gl[n>>4]+gl[n&15];return t}function hf(e){let t="";for(let n of e)t+=String.fromCharCode(n);return btoa(t)}function hn(e){let t=e.toLowerCase().replace("-","");if(t!=="sha1"&&t!=="sha256")throw new Error(`createHash: unsupported algorithm "${e}" in the browser build (sha1, sha256)`);let n=[],r=0,s={update(o){let a=uf(o);return n.push(a),r+=a.byteLength,s},digest(o){let a=r===0?new Uint8Array(0):ff(n,r),l=t==="sha1"?mf(a):gf(a);return o==="hex"?_f(l):o==="base64"?hf(l):l}};return s}var pf,gl,cs=F(()=>{k();pf=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]);gl="0123456789abcdef"});function Me(e){return hn("sha1").update(e).digest("hex")}function yf(e,t=8){return Me(e).slice(0,t)}var At=F(()=>{"use strict";k();cs()});function ne(e,t,n,r){let s=[],o=t.split(/\r?\n/);for(let a=0;at.slice(0,p).split(/\r?\n/).length,l=new Map;for(let p of n)l.has(p.name)||l.set(p.name,p);let c=of(t),d=/export\s*\{([\s\S]*?)\}\s*(?:from\s*['"]([^'"]+)['"])?\s*;?/g,u;for(;(u=d.exec(c))&&s.length{"use strict";S();rf={".ts":"typescript",".tsx":"typescript",".mts":"typescript",".cts":"typescript",".js":"javascript",".jsx":"javascript",".mjs":"javascript",".cjs":"javascript",".py":"python",".pyi":"python",".go":"go",".rb":"ruby",".rake":"ruby",".java":"java",".rs":"rust",".c":"c",".h":"c",".cc":"cpp",".cpp":"cpp",".cxx":"cpp",".hpp":"cpp",".cs":"csharp",".php":"php",".swift":"swift",".kt":"kotlin",".kts":"kotlin",".scala":"scala",".sc":"scala",".clj":"clojure",".ex":"elixir",".exs":"elixir",".erl":"erlang",".hs":"haskell",".dart":"dart",".lua":"lua",".sh":"shell",".bash":"shell",".zsh":"shell",".ksh":"shell",".fish":"shell",".hh":"cpp",".m":"objective-c",".mm":"objective-c",".sql":"sql",".graphql":"graphql",".gql":"graphql",".proto":"protobuf",".md":"markdown",".mdx":"markdown",".rst":"restructuredtext",".txt":"text",".json":"json",".yaml":"yaml",".yml":"yaml",".toml":"toml",".ini":"ini",".html":"html",".css":"css",".scss":"scss",".vue":"vue",".svelte":"svelte",".astro":"astro",".zig":"zig",".hcl":"hcl",".tf":"terraform",".tfvars":"terraform",".sol":"solidity"};sf=new Set([".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs"]);is=400});function df(e){return(e.split("/").pop()??"").replace(/\.[^.]+$/,"")}function uf(e,t){let n=o=>{if(!(!o||o==="default"))for(let a of t)a.name===o&&(a.exported=!0)},r=(o,a)=>{for(let l of o.split(",")){let c=l.trim().replace(/^type\s+/,"");if(!c)continue;let d=/^([\w$]+)\s+as\s+([\w$]+)$/.exec(c);if(d){d[2]!=="default"&&n(d[1]);continue}if(a){let u=/^([\w$]+)\s*:\s*([\w$]+)$/.exec(c);if(u){n(u[1]),n(u[2]);continue}}n(/^([\w$]+)/.exec(c)?.[1])}},s;for(rl.lastIndex=0;s=rl.exec(e);)s[2]||r(s[1]??"",!1);for(sl.lastIndex=0;s=sl.exec(e);)r(s[1]??"",!0);for(il.lastIndex=0;s=il.exec(e);)n(s[2])}var af,lf,cf,rl,sl,il,ol,al=O(()=>{"use strict";S();Ee();af=[{re:/^\s*export\s+(?:async\s+)?function\s+(?[\w$]+)/,kind:"function",exported:!0},{re:/^\s*export\s+default\s+(?:async\s+)?function\s+(?[\w$]+)/,kind:"function",exported:!0},{re:/^\s*export\s+default\s+(?:abstract\s+)?class\s+(?!extends\b)(?[\w$]+)/,kind:"class",exported:!0},{re:/^\s*(?:async\s+)?function\s+(?[\w$]+)/,kind:"function",exported:!1},{re:/^\s*export\s+(?:abstract\s+)?class\s+(?[\w$]+)/,kind:"class",exported:!0},{re:/^\s*(?:abstract\s+)?class\s+(?[\w$]+)/,kind:"class",exported:!1},{re:/^\s*export\s+interface\s+(?[\w$]+)/,kind:"interface",exported:!0},{re:/^\s*interface\s+(?[\w$]+)/,kind:"interface",exported:!1},{re:/^\s*export\s+type\s+(?[\w$]+)/,kind:"type",exported:!0},{re:/^\s*type\s+(?[\w$]+)\s*[=<]/,kind:"type",exported:!1},{re:/^\s*export\s+enum\s+(?[\w$]+)/,kind:"enum",exported:!0},{re:/^\s*export\s+const\s+enum\s+(?[\w$]+)/,kind:"enum",exported:!0},{re:/^\s*export\s+(?:const|let|var)\s+(?[\w$]+)\s*[:=]/,kind:"const",exported:!0},{re:/^\s*exports\.(?[\w$]+)\s*=/,kind:"const",exported:!0},{re:/^\s*module\.exports\.(?[\w$]+)\s*=/,kind:"const",exported:!0},{re:/^\s*(?:const|let)\s+(?[\w$]+)\s*=\s*(?:async\s*)?\([^)]*\)\s*(?::[^=]+)?=>/,kind:"const",exported:!1},{re:/^(?:const|let|var)\s+(?[\w$]+)\s*[:=]/,kind:"const",exported:!1},{re:/^\s*export\s+default\s+(?[A-Za-z_$][\w$]*)\s*;?\s*$/,kind:"default",exported:!0}],lf=/^\s*export\s+default\s+(?:async\s+)?(?:function|class)?\s*(?:\(|\{|extends\b)/,cf=/^\s*export\s+default\s+(?:async\s+)?(?:function|class)\s+(?!extends\b)[\w$]+/;rl=/export\s*\{([^}]*)\}\s*(from\b)?/g,sl=/module\.exports\s*=\s*\{([^}]*)\}/g,il=/(^|\n)\s*export\s+default\s+([A-Za-z_$][\w$]*)\s*;?\s*(?=\n|$)/g;ol={lang:"javascript/typescript",exts:[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs"],extract(e,t){let n=e.match(/\.(ts|tsx|mts|cts)$/)?"typescript":"javascript",r=ne(e,t,n,af),s=t.split(/\r?\n/);for(let o=0;o{"use strict";S();Ee();as=e=>!e.startsWith("_")||e.startsWith("__"),ff=[{re:/^(?:async\s+)?def\s+(?[\w]+)\s*\(/,kind:"function",exported:e=>as(e.groups.name)},{re:/^\s+(?:async\s+)?def\s+(?[\w]+)\s*\(/,kind:"method",exported:e=>as(e.groups.name)},{re:/^class\s+(?[\w]+)/,kind:"class",exported:e=>as(e.groups.name)},{re:/^\s+class\s+(?[\w]+)/,kind:"class",exported:e=>as(e.groups.name)}],ll={lang:"python",exts:[".py",".pyi"],extract(e,t){return ne(e,t,"python",ff)}}});var $n,mf,dl,ul=O(()=>{"use strict";S();Ee();$n=e=>/^[A-Z]/.test(e),mf=[{re:/^func\s+\([^)]*\)\s+(?[\w]+)\s*\(/,kind:"method",exported:e=>$n(e.groups.name)},{re:/^func\s+(?[\w]+)\s*\(/,kind:"function",exported:e=>$n(e.groups.name)},{re:/^type\s+(?[\w]+)\s+struct\b/,kind:"struct",exported:e=>$n(e.groups.name)},{re:/^type\s+(?[\w]+)\s+interface\b/,kind:"interface",exported:e=>$n(e.groups.name)},{re:/^type\s+(?[\w]+)\s+/,kind:"type",exported:e=>$n(e.groups.name)}],dl={lang:"go",exts:[".go"],extract(e,t){return ne(e,t,"go",mf)}}});var pf,fl,ml=O(()=>{"use strict";S();Ee();pf=[{re:/^\s*def\s+(?:self\.)?(?[\w?!=]+)/,kind:"method",exported:!0},{re:/^\s*class\s+(?[\w:]+)/,kind:"class",exported:!0},{re:/^\s*module\s+(?[\w:]+)/,kind:"module",exported:!0}],fl={lang:"ruby",exts:[".rb",".rake"],extract(e,t){return ne(e,t,"ruby",pf)}}});var gf,pl,gl=O(()=>{"use strict";S();Ee();gf=[{re:/^\s*(?:public|protected|private)?\s*(?:abstract\s+|final\s+)?class\s+(?[\w]+)/,kind:"class",exported:(e,t)=>/\bpublic\b/.test(t)},{re:/^\s*(?:public|protected|private)?\s*interface\s+(?[\w]+)/,kind:"interface",exported:(e,t)=>/\bpublic\b/.test(t)},{re:/^\s*(?:public|protected|private)?\s*enum\s+(?[\w]+)/,kind:"enum",exported:(e,t)=>/\bpublic\b/.test(t)},{re:/^\s*(?:public|protected|private)\s+(?:static\s+|final\s+|abstract\s+|synchronized\s+)*[\w<>\[\],.?\s]+\s+(?[\w]+)\s*\(/,kind:"method",exported:(e,t)=>/\bpublic\b/.test(t)}],pl={lang:"java",exts:[".java"],extract(e,t){return ne(e,t,"java",gf)}}});var Dn,_f,_l,hl=O(()=>{"use strict";S();Ee();Dn=(e,t)=>/^\s*pub\b/.test(t),_f=[{re:/^\s*(?:pub(?:\([^)]*\))?\s+)?(?:async\s+)?(?:unsafe\s+)?fn\s+(?[\w]+)/,kind:"function",exported:Dn},{re:/^\s*(?:pub(?:\([^)]*\))?\s+)?struct\s+(?[\w]+)/,kind:"struct",exported:Dn},{re:/^\s*(?:pub(?:\([^)]*\))?\s+)?enum\s+(?[\w]+)/,kind:"enum",exported:Dn},{re:/^\s*(?:pub(?:\([^)]*\))?\s+)?trait\s+(?[\w]+)/,kind:"trait",exported:Dn},{re:/^\s*(?:pub(?:\([^)]*\))?\s+)?type\s+(?[\w]+)/,kind:"type",exported:Dn}],_l={lang:"rust",exts:[".rs"],extract(e,t){return ne(e,t,"rust",_f)}}});var Ln,hf,yl,bl=O(()=>{"use strict";S();Ee();Ln=(e,t)=>/\b(public|internal)\b/.test(t),hf=[{re:/^\s*(?:public|internal|protected|private)?\s*(?:static\s+|sealed\s+|abstract\s+|partial\s+)*(?:class|record)\s+(?\w+)/,kind:"class",exported:Ln},{re:/^\s*(?:public|internal|protected|private)?\s*(?:partial\s+)?interface\s+(?\w+)/,kind:"interface",exported:Ln},{re:/^\s*(?:public|internal|protected|private)?\s*(?:readonly\s+)?(?:ref\s+)?struct\s+(?\w+)/,kind:"struct",exported:Ln},{re:/^\s*(?:public|internal|protected|private)?\s*enum\s+(?\w+)/,kind:"enum",exported:Ln},{re:/^\s*(?:public|internal|protected|private)\s+(?:static\s+|virtual\s+|override\s+|async\s+|sealed\s+|abstract\s+|new\s+)*[\w<>\[\],.?]+\s+(?\w+)\s*(?:<[^>]*>)?\s*\(/,kind:"method",exported:Ln}],yl={lang:"csharp",exts:[".cs"],extract(e,t){return ne(e,t,"csharp",hf)}}});var yf,wl,xl=O(()=>{"use strict";S();Ee();yf=[{re:/^\s*(?:abstract\s+|final\s+)*class\s+(?\w+)/,kind:"class",exported:!0},{re:/^\s*interface\s+(?\w+)/,kind:"interface",exported:!0},{re:/^\s*trait\s+(?\w+)/,kind:"trait",exported:!0},{re:/^\s*enum\s+(?\w+)/,kind:"enum",exported:!0},{re:/^\s*(?:public\s+|protected\s+|private\s+|static\s+|abstract\s+|final\s+)*function\s+(?\w+)\s*\(/,kind:"function",exported:(e,t)=>!/\b(private|protected)\b/.test(t)}],wl={lang:"php",exts:[".php"],extract(e,t){return ne(e,t,"php",yf)}}});var jn,ls,bf,Sl,kl=O(()=>{"use strict";S();Ee();jn=(e,t)=>!/\b(private|fileprivate)\b/.test(t),ls="(?:public\\s+|open\\s+|internal\\s+|private\\s+|fileprivate\\s+)?(?:final\\s+)?",bf=[{re:new RegExp(`^\\s*${ls}class\\s+(?\\w+)`),kind:"class",exported:jn},{re:new RegExp(`^\\s*${ls}struct\\s+(?\\w+)`),kind:"struct",exported:jn},{re:new RegExp(`^\\s*${ls}enum\\s+(?\\w+)`),kind:"enum",exported:jn},{re:new RegExp(`^\\s*${ls}protocol\\s+(?\\w+)`),kind:"protocol",exported:jn},{re:/^\s*(?:public\s+|open\s+|internal\s+|private\s+|fileprivate\s+)?(?:static\s+|class\s+|final\s+|override\s+|mutating\s+|@\w+\s+)*func\s+(?\w+)/,kind:"function",exported:jn}],Sl={lang:"swift",exts:[".swift"],extract(e,t){return ne(e,t,"swift",bf)}}});var cs,wf,El,vl=O(()=>{"use strict";S();Ee();cs=(e,t)=>!/\b(private|internal)\b/.test(t),wf=[{re:/^\s*(?:public\s+|internal\s+|private\s+|abstract\s+|sealed\s+|open\s+|final\s+|data\s+)*class\s+(?\w+)/,kind:"class",exported:cs},{re:/^\s*(?:public\s+|internal\s+|private\s+|fun\s+)?interface\s+(?\w+)/,kind:"interface",exported:cs},{re:/^\s*(?:public\s+|internal\s+|private\s+|companion\s+)?object\s+(?\w+)/,kind:"object",exported:cs},{re:/^\s*(?:public\s+|internal\s+|private\s+|protected\s+|override\s+|open\s+|abstract\s+|suspend\s+|inline\s+|operator\s+)*fun\s+(?:<[^>]*>\s+)?(?\w+)\s*\(/,kind:"function",exported:cs}],El={lang:"kotlin",exts:[".kt",".kts"],extract(e,t){return ne(e,t,"kotlin",wf)}}});var xf,Sf,Rl,Ml=O(()=>{"use strict";S();Ee();xf="(?!\\s*(?:if|for|while|switch|return|else|do|sizeof|typedef)\\b)",Sf=[{re:/^\s*(?:class|struct)\s+(?[A-Za-z_]\w+)\s*(?:[:{]|$)/,kind:"class",exported:!0},{re:/^\s*namespace\s+(?[A-Za-z_]\w+)/,kind:"namespace",exported:!0},{re:/^\s*(?:typedef\s+)?(?:struct|enum|union)\s+(?[A-Za-z_]\w+)\s*\{/,kind:"struct",exported:!0},{re:new RegExp(`^${xf}[A-Za-z_][\\w\\s\\*&<>:,]*?\\b(?[A-Za-z_]\\w+)\\s*\\([^;{]*\\)\\s*(?:const)?\\s*\\{?\\s*$`),kind:"function",exported:!0}],Rl={lang:"c/cpp",exts:[".c",".h",".cc",".cpp",".cxx",".hpp",".hh"],extract(e,t){return ne(e,t,e.match(/\.(c|h)$/)?"c":"cpp",Sf)}}});var kf,Cl,Al=O(()=>{"use strict";S();Ee();kf=[{re:/^\s*local\s+function\s+(?[\w.:]+)\s*\(/,kind:"function",exported:!1},{re:/^\s*function\s+(?[\w.:]+)\s*\(/,kind:"function",exported:!0},{re:/^\s*(?:local\s+)?(?[\w.]+)\s*=\s*function\s*\(/,kind:"function",exported:!0}],Cl={lang:"lua",exts:[".lua"],extract(e,t){return ne(e,t,"lua",kf)}}});var Ef,Tl,Il=O(()=>{"use strict";S();Ee();Ef=[{re:/^\s*function\s+(?[\w:-]+)\s*(?:\(\))?\s*\{?/,kind:"function",exported:!0},{re:/^\s*(?[A-Za-z_][\w:-]*)\s*\(\)\s*\{?/,kind:"function",exported:!0}],Tl={lang:"shell",exts:[".sh",".bash",".zsh",".ksh"],extract(e,t){return ne(e,t,"shell",Ef)}}});var vf,Nl,Ol=O(()=>{"use strict";S();Ee();vf=[{re:/^\s*defmodule\s+(?[\w.]+)/,kind:"module",exported:!0},{re:/^\s*defp\s+(?[\w?!]+)/,kind:"function",exported:!1},{re:/^\s*def\s+(?[\w?!]+)/,kind:"function",exported:!0},{re:/^\s*defmacrop?\s+(?[\w?!]+)/,kind:"macro",exported:!0}],Nl={lang:"elixir",exts:[".ex",".exs"],extract(e,t){return ne(e,t,"elixir",vf)}}});var Rf,Fl,Pl=O(()=>{"use strict";S();Ee();Rf=[{re:/^\s*(?:final\s+|sealed\s+|abstract\s+|implicit\s+)*(?:case\s+)?class\s+(?\w+)/,kind:"class",exported:!0},{re:/^\s*(?:sealed\s+)?trait\s+(?\w+)/,kind:"trait",exported:!0},{re:/^\s*(?:case\s+)?object\s+(?\w+)/,kind:"object",exported:!0},{re:/^\s*(?:override\s+|final\s+|private\s+|protected\s+|implicit\s+)*def\s+(?\w+)/,kind:"def",exported:(e,t)=>!/\b(private|protected)\b/.test(t)}],Fl={lang:"scala",exts:[".scala",".sc"],extract(e,t){return ne(e,t,"scala",Rf)}}});var Mt,Mf,$l,Dl=O(()=>{"use strict";S();Ee();Mt=e=>!(e.groups?.name??"").startsWith("_"),Mf=[{re:/^\s*(?:abstract\s+|base\s+|final\s+|sealed\s+|interface\s+)*class\s+(?\w+)/,kind:"class",exported:Mt},{re:/^\s*mixin\s+(?\w+)/,kind:"mixin",exported:Mt},{re:/^\s*extension\s+(?\w+)/,kind:"extension",exported:Mt},{re:/^\s*enum\s+(?\w+)/,kind:"enum",exported:Mt},{re:/^\s*typedef\s+(?\w+)/,kind:"type",exported:Mt},{re:/^\s*(?:@\w+\s+)*(?:static\s+|final\s+|const\s+|external\s+|abstract\s+)*(?:[\w<>,?\[\]. ]+\s+)?(?\w+)\s*\([^)]*\)\s*(?:async\s*\*?\s*)?(?:=>|\{|;)/,kind:"function",exported:Mt},{re:/^\s*(?:static\s+)?[\w<>,?\[\]. ]+\s+get\s+(?\w+)/,kind:"getter",exported:Mt},{re:/^\s*(?:static\s+)?set\s+(?\w+)\s*\(/,kind:"setter",exported:Mt}],$l={lang:"dart",exts:[".dart"],extract(e,t){return ne(e,t,"dart",Mf)}}});function Li(e,t,n){let r=Di.get(t),s;if(!r)s=[];else try{s=r.extract(e,n)}catch{s=[]}let o=new Set(s.map(l=>l.name)),a=os(e,n,s).filter(l=>!o.has(l.name));return a.length?[...s,...a]:s}function ji(e){return Di.get(e)?.lang??qt(e)}var Cf,Di,_n=O(()=>{"use strict";S();Ee();al();cl();ul();ml();gl();hl();bl();xl();kl();vl();Ml();Al();Il();Ol();Pl();Dl();Cf=[ol,ll,dl,fl,pl,_l,yl,wl,Sl,El,Rl,Cl,Tl,Nl,Fl,$l],Di=new Map;for(let e of Cf)for(let t of e.exts)Di.set(t,e)});function Ll(e,t){let n=e.split("/").pop().toLowerCase();return Tf.has(t)||Af.test(n)||If.test(e)}function Ff(e,t){let n=e.split("/").pop().toLowerCase();return Nf.has(n)||Of.has(t)}function jl(e){return!Pf.has(ji(e))}function Wi(e,t){return jl(t)?"code":Ll(e,t)?"doc":Ff(e,t)?"config":"other"}var Af,Tf,If,Nf,Of,Ui,Pf,Bi=O(()=>{"use strict";S();_n();Af=/^(readme|changelog|contributing|history|news|authors|notice|security|code_of_conduct|faq|getting[-_]?started|usage|guide|tutorial)\b/i,Tf=new Set([".md",".mdx",".rst",".adoc",".txt"]),If=/^(docs?|documentation|wiki|guides?|website|site|book)\//i,Nf=new Set(["package.json","pnpm-workspace.yaml","tsconfig.json","jsconfig.json","pyproject.toml","setup.py","setup.cfg","requirements.txt","pipfile","go.mod","cargo.toml","gemfile","pom.xml","build.gradle","build.gradle.kts","composer.json","mix.exs","pubspec.yaml","build.sbt","dockerfile","docker-compose.yml","docker-compose.yaml","makefile",".env.example","manifest.json"]),Of=new Set([".json",".yaml",".yml",".toml",".ini",".cfg"]),Ui=new Set([".md",".mdx"]);Pf=new Set(["markdown","restructuredtext","text","json","yaml","toml","ini","other","html","css","scss"])});function $f(e){let t="";for(let n=0;nt.some(r=>r.test(n))}function Ul(e){if(!e||e.length===0)return null;let t=gt(e.filter(r=>!r.startsWith("!"))),n=gt(e.filter(r=>r.startsWith("!")).map(r=>r.slice(1)));return r=>(!t||t(r))&&!n?.(r)}var Un=O(()=>{"use strict";S();Me()});function R(e,t){return et?1:0}function Hi(e){return(t,n)=>R(e(t),e(n))}var K=O(()=>{"use strict";S()});function Df(e){let t=e.split(/\r?\n/),n=[],r=null;for(let s of t){let o=/^\s*(```+|~~~+)/.exec(s);if(r){o&&s.trim().startsWith(r[0][0].repeat(3).slice(0,3))&&(r=null),n.push("");continue}if(o){r=o[1],n.push("");continue}n.push(s)}return n.join(` -`)}function Lf(e){return!e||e.startsWith("#")||e.startsWith("//")?!0:/^[a-z][a-z0-9+.-]*:/i.test(e)}function Wl(e){return e.replace(/!\[[^\]]*\]\([^)]*\)/g,"").replace(/`([^`]*)`/g,"$1").replace(/\*\*([^*]+)\*\*/g,"$1").replace(/\*([^*]+)\*/g,"$1").replace(/\[([^\]]*)\]\([^)]*\)/g,"$1").replace(/[#>*_~-]+/g," ").replace(/\s+/g," ").trim()}function jf(e){return/[A-Za-zÀ-ɏ]{3,}/.test(e)}function Uf(e){return/^(all notable changes to this project|in the interest of fostering|this project adheres to|we as members and leaders|table of contents)\b/i.test(e)}function zi(e){let t=e,n,r=/^---\r?\n([\s\S]*?)\r?\n---\r?\n?/.exec(t);if(r){let _=/(^|\n)title:\s*["']?(.+?)["']?\s*(\n|$)/i.exec(r[1]);_&&(n=_[2].trim()),t=t.slice(r[0].length)}let s=Df(t),o=s.split(/\r?\n/),a=[],l=n,c,d=!1;for(let _ of o){let y=/^(#{1,6})\s+(.+?)\s*#*\s*$/.exec(_);if(y){let x=Wl(y[2]);a.push(x),!l&&y[1].length===1&&(l=x),!c&&y[1].length>=2&&(d=!0);continue}if(!c&&!d){let x=_.trim();if(x&&!/^([-*+]|\d+\.)\s/.test(x)&&!x.startsWith("|")&&!x.startsWith("<")){let E=Wl(x);E.length>=8&&jf(E)&&!E.endsWith(":")&&!Uf(E)&&(c=E.slice(0,200))}}}let u=[],f=new Set,p=_=>{let y=_.trim();y=y.replace(/\s+["'(].*$/,"").trim(),y=y.replace(/^<|>$/g,""),!Lf(y)&&(f.has(y)||(f.add(y),u.push({kind:"doc-link",spec:y})))},m=/!?\[[^\]]*\]\(([^)]+)\)/g,g;for(;g=m.exec(s);)p(g[1]);let h=/^\s*\[[^\]]+\]:\s+(\S+)/gm;for(;g=h.exec(s);)p(g[1]);return{title:l,summary:c,headings:a,refs:u}}var Gi=O(()=>{"use strict";S()});function Gf(e){return e.lengthBl?!1:zf.test(e)}function qf(e){let t=e.trim();return!t||t.length>Bl||Hf.has(t)?!1:Number.isFinite(Number(t))}function Vf(e){let t=e,n=/^(?:[rRbBuUfF]{1,2}|@|\$)?(?:#*)?(['"`])/.exec(t);if(n){let r=n[1],s=t.indexOf(r),o=t.lastIndexOf(r);o>s&&(t=t.slice(s+1,o))}return t}var Bl,Wf,Bf,Hf,zf,Ct,ds=O(()=>{"use strict";S();K();Bl=80,Wf=2,Bf=256,Hf=new Set(["0","1","-1","2","-2"]),zf=/[\p{L}\p{N}]/u;Ct=class{seen=new Set;out=[];get full(){return this.out.length>=Bf}add(t,n,r){if(this.full||t==="string"&&!Gf(n)||t==="number"&&!qf(n)||t==="regex"&&!n)return;let s=`${t}\0${n}\0${r}`;this.seen.has(s)||(this.seen.add(s),this.out.push({value:n,line:r,kind:t}))}addString(t,n){this.add("string",Vf(t),n)}result(){if(this.out.length)return this.out.sort((t,n)=>R(t.value,n.value)||t.line-n.line||R(t.kind,n.kind))}}});function Hl(){return"/home"}function zl(){return typeof navigator<"u"&&navigator?.hardwareConcurrency?navigator.hardwareConcurrency:1}var qi=O(()=>{S()});function us(e){let t=typeof e=="string"?e:e.href;try{return decodeURIComponent(new URL(t).pathname)}catch{return t}}function Wn(e){return new URL(`file://${e.startsWith("/")?"":"/"}${e}`)}var ms=O(()=>{S()});var Vi={};xi(Vi,{createRequire:()=>Jf,default:()=>Kf});var Jf,Kf,Ji=O(()=>{S();Jf=()=>{throw new Error("node-only API in the browser build")},Kf={}});function hn(e){if(e!==At)throw new Error("Illegal constructor")}function Hn(e){return!!e&&typeof e.row=="number"&&typeof e.column=="number"}function Vl(e){b=e}function eo(e,t,n,r){let s=n-t,o=e.textCallback(t,r);if(o){for(t+=o.length;t0)t+=a.length,o+=a;else break}t>n&&(o=o.slice(0,s))}return o??""}function Qi(e,t,n,r,s){for(let o=0,a=s.length;o>>0,column:b.getValue(e+U,"i32")>>>0}}function Kl(e,t){ze(e,t.startPosition),e+=lt,ze(e,t.endPosition),e+=lt,b.setValue(e,t.startIndex,"i32"),e+=U,b.setValue(e,t.endIndex,"i32"),e+=U}function ps(e){let t={};return t.startPosition=Vt(e),e+=lt,t.endPosition=Vt(e),e+=lt,t.startIndex=b.getValue(e,"i32")>>>0,e+=U,t.endIndex=b.getValue(e,"i32")>>>0,t}function Xl(e,t=j){ze(t,e.startPosition),t+=lt,ze(t,e.oldEndPosition),t+=lt,ze(t,e.newEndPosition),t+=lt,b.setValue(t,e.startIndex,"i32"),t+=U,b.setValue(t,e.oldEndIndex,"i32"),t+=U,b.setValue(t,e.newEndIndex,"i32"),t+=U}function Zl(e){let t=b.getValue(e,"i32"),n=b.getValue(e+=U,"i32"),r=b.getValue(e+=U,"i32");return{major_version:t,minor_version:n,patch_version:r}}async function Ql(moduleArg={}){var moduleRtn,Module=moduleArg,ENVIRONMENT_IS_WEB=typeof window=="object",ENVIRONMENT_IS_WORKER=typeof WorkerGlobalScope<"u",ENVIRONMENT_IS_NODE=typeof v=="object"&&v.versions?.node&&v.type!="renderer";if(ENVIRONMENT_IS_NODE){let{createRequire:e}=await Promise.resolve().then(()=>(Ji(),Vi));var require=e(import.meta.url)}Module.currentQueryProgressCallback=null,Module.currentProgressCallback=null,Module.currentLogCallback=null,Module.currentParseCallback=null;var arguments_=[],thisProgram="./this.program",quit_=M((e,t)=>{throw t},"quit_"),_scriptName=import.meta.url,scriptDirectory="";function locateFile(e){return Module.locateFile?Module.locateFile(e,scriptDirectory):scriptDirectory+e}M(locateFile,"locateFile");var readAsync,readBinary;if(ENVIRONMENT_IS_NODE){var fs=require("fs");_scriptName.startsWith("file:")&&(scriptDirectory=require("path").dirname(require("url").fileURLToPath(_scriptName))+"/"),readBinary=M(e=>{e=isFileURI(e)?new URL(e):e;var t=fs.readFileSync(e);return t},"readBinary"),readAsync=M(async(e,t=!0)=>{e=isFileURI(e)?new URL(e):e;var n=fs.readFileSync(e,t?void 0:"utf8");return n},"readAsync"),v.argv.length>1&&(thisProgram=v.argv[1].replace(/\\/g,"/")),arguments_=v.argv.slice(2),quit_=M((e,t)=>{throw v.exitCode=e,t},"quit_")}else if(ENVIRONMENT_IS_WEB||ENVIRONMENT_IS_WORKER){try{scriptDirectory=new URL(".",_scriptName).href}catch{}ENVIRONMENT_IS_WORKER&&(readBinary=M(e=>{var t=new XMLHttpRequest;return t.open("GET",e,!1),t.responseType="arraybuffer",t.send(null),new Uint8Array(t.response)},"readBinary")),readAsync=M(async e=>{if(isFileURI(e))return new Promise((n,r)=>{var s=new XMLHttpRequest;s.open("GET",e,!0),s.responseType="arraybuffer",s.onload=()=>{if(s.status==200||s.status==0&&s.response){n(s.response);return}r(s.status)},s.onerror=r,s.send(null)});var t=await fetch(e,{credentials:"same-origin"});if(t.ok)return t.arrayBuffer();throw new Error(t.status+" : "+t.url)},"readAsync")}var out=console.log.bind(console),err=console.error.bind(console),dynamicLibraries=[],wasmBinary,ABORT=!1,EXITSTATUS,isFileURI=M(e=>e.startsWith("file://"),"isFileURI"),readyPromiseResolve,readyPromiseReject,wasmMemory,HEAP8,HEAPU8,HEAP16,HEAPU16,HEAP32,HEAPU32,HEAPF32,HEAPF64,HEAP64,HEAPU64,HEAP_DATA_VIEW,runtimeInitialized=!1;function updateMemoryViews(){var e=wasmMemory.buffer;Module.HEAP8=HEAP8=new Int8Array(e),Module.HEAP16=HEAP16=new Int16Array(e),Module.HEAPU8=HEAPU8=new Uint8Array(e),Module.HEAPU16=HEAPU16=new Uint16Array(e),Module.HEAP32=HEAP32=new Int32Array(e),Module.HEAPU32=HEAPU32=new Uint32Array(e),Module.HEAPF32=HEAPF32=new Float32Array(e),Module.HEAPF64=HEAPF64=new Float64Array(e),Module.HEAP64=HEAP64=new BigInt64Array(e),Module.HEAPU64=HEAPU64=new BigUint64Array(e),Module.HEAP_DATA_VIEW=HEAP_DATA_VIEW=new DataView(e),LE_HEAP_UPDATE()}M(updateMemoryViews,"updateMemoryViews");function initMemory(){if(Module.wasmMemory)wasmMemory=Module.wasmMemory;else{var e=Module.INITIAL_MEMORY||33554432;wasmMemory=new WebAssembly.Memory({initial:e/65536,maximum:32768})}updateMemoryViews()}M(initMemory,"initMemory");var __RELOC_FUNCS__=[];function preRun(){if(Module.preRun)for(typeof Module.preRun=="function"&&(Module.preRun=[Module.preRun]);Module.preRun.length;)addOnPreRun(Module.preRun.shift());callRuntimeCallbacks(onPreRuns)}M(preRun,"preRun");function initRuntime(){runtimeInitialized=!0,callRuntimeCallbacks(__RELOC_FUNCS__),wasmExports.__wasm_call_ctors(),callRuntimeCallbacks(onPostCtors)}M(initRuntime,"initRuntime");function preMain(){}M(preMain,"preMain");function postRun(){if(Module.postRun)for(typeof Module.postRun=="function"&&(Module.postRun=[Module.postRun]);Module.postRun.length;)addOnPostRun(Module.postRun.shift());callRuntimeCallbacks(onPostRuns)}M(postRun,"postRun");function abort(e){Module.onAbort?.(e),e="Aborted("+e+")",err(e),ABORT=!0,e+=". Build with -sASSERTIONS for more info.";var t=new WebAssembly.RuntimeError(e);throw readyPromiseReject?.(t),t}M(abort,"abort");var wasmBinaryFile;function findWasmBinary(){return Module.locateFile?locateFile("web-tree-sitter.wasm"):new URL("web-tree-sitter.wasm",import.meta.url).href}M(findWasmBinary,"findWasmBinary");function getBinarySync(e){if(e==wasmBinaryFile&&wasmBinary)return new Uint8Array(wasmBinary);if(readBinary)return readBinary(e);throw"both async and sync fetching of the wasm failed"}M(getBinarySync,"getBinarySync");async function getWasmBinary(e){if(!wasmBinary)try{var t=await readAsync(e);return new Uint8Array(t)}catch{}return getBinarySync(e)}M(getWasmBinary,"getWasmBinary");async function instantiateArrayBuffer(e,t){try{var n=await getWasmBinary(e),r=await WebAssembly.instantiate(n,t);return r}catch(s){err(`failed to asynchronously prepare wasm: ${s}`),abort(s)}}M(instantiateArrayBuffer,"instantiateArrayBuffer");async function instantiateAsync(e,t,n){if(!e&&!isFileURI(t)&&!ENVIRONMENT_IS_NODE)try{var r=fetch(t,{credentials:"same-origin"}),s=await WebAssembly.instantiateStreaming(r,n);return s}catch(o){err(`wasm streaming compile failed: ${o}`),err("falling back to ArrayBuffer instantiation")}return instantiateArrayBuffer(t,n)}M(instantiateAsync,"instantiateAsync");function getWasmImports(){return{env:wasmImports,wasi_snapshot_preview1:wasmImports,"GOT.mem":new Proxy(wasmImports,GOTHandler),"GOT.func":new Proxy(wasmImports,GOTHandler)}}M(getWasmImports,"getWasmImports");async function createWasm(){function e(o,a){wasmExports=o.exports,wasmExports=relocateExports(wasmExports,1024);var l=getDylinkMetadata(a);return l.neededDynlibs&&(dynamicLibraries=l.neededDynlibs.concat(dynamicLibraries)),mergeLibSymbols(wasmExports,"main"),LDSO.init(),loadDylibs(),__RELOC_FUNCS__.push(wasmExports.__wasm_apply_data_relocs),assignWasmExports(wasmExports),wasmExports}M(e,"receiveInstance");function t(o){return e(o.instance,o.module)}M(t,"receiveInstantiationResult");var n=getWasmImports();if(Module.instantiateWasm)return new Promise((o,a)=>{Module.instantiateWasm(n,(l,c)=>{o(e(l,c))})});wasmBinaryFile??=findWasmBinary();var r=await instantiateAsync(wasmBinary,wasmBinaryFile,n),s=t(r);return s}M(createWasm,"createWasm");class ExitStatus{static{M(this,"ExitStatus")}name="ExitStatus";constructor(t){this.message=`Program terminated with exit(${t})`,this.status=t}}var GOT={},currentModuleWeakSymbols=new Set([]),GOTHandler={get(e,t){var n=GOT[t];return n||(n=GOT[t]=new WebAssembly.Global({value:"i32",mutable:!0})),currentModuleWeakSymbols.has(t)||(n.required=!0),n}},LE_ATOMICS_NATIVE_BYTE_ORDER=[],LE_HEAP_LOAD_F32=M(e=>HEAP_DATA_VIEW.getFloat32(e,!0),"LE_HEAP_LOAD_F32"),LE_HEAP_LOAD_F64=M(e=>HEAP_DATA_VIEW.getFloat64(e,!0),"LE_HEAP_LOAD_F64"),LE_HEAP_LOAD_I16=M(e=>HEAP_DATA_VIEW.getInt16(e,!0),"LE_HEAP_LOAD_I16"),LE_HEAP_LOAD_I32=M(e=>HEAP_DATA_VIEW.getInt32(e,!0),"LE_HEAP_LOAD_I32"),LE_HEAP_LOAD_I64=M(e=>HEAP_DATA_VIEW.getBigInt64(e,!0),"LE_HEAP_LOAD_I64"),LE_HEAP_LOAD_U32=M(e=>HEAP_DATA_VIEW.getUint32(e,!0),"LE_HEAP_LOAD_U32"),LE_HEAP_STORE_F32=M((e,t)=>HEAP_DATA_VIEW.setFloat32(e,t,!0),"LE_HEAP_STORE_F32"),LE_HEAP_STORE_F64=M((e,t)=>HEAP_DATA_VIEW.setFloat64(e,t,!0),"LE_HEAP_STORE_F64"),LE_HEAP_STORE_I16=M((e,t)=>HEAP_DATA_VIEW.setInt16(e,t,!0),"LE_HEAP_STORE_I16"),LE_HEAP_STORE_I32=M((e,t)=>HEAP_DATA_VIEW.setInt32(e,t,!0),"LE_HEAP_STORE_I32"),LE_HEAP_STORE_I64=M((e,t)=>HEAP_DATA_VIEW.setBigInt64(e,t,!0),"LE_HEAP_STORE_I64"),LE_HEAP_STORE_U32=M((e,t)=>HEAP_DATA_VIEW.setUint32(e,t,!0),"LE_HEAP_STORE_U32"),callRuntimeCallbacks=M(e=>{for(;e.length>0;)e.shift()(Module)},"callRuntimeCallbacks"),onPostRuns=[],addOnPostRun=M(e=>onPostRuns.push(e),"addOnPostRun"),onPreRuns=[],addOnPreRun=M(e=>onPreRuns.push(e),"addOnPreRun"),UTF8Decoder=typeof TextDecoder<"u"?new TextDecoder:void 0,findStringEnd=M((e,t,n,r)=>{var s=t+n;if(r)return s;for(;e[t]&&!(t>=s);)++t;return t},"findStringEnd"),UTF8ArrayToString=M((e,t=0,n,r)=>{var s=findStringEnd(e,t,n,r);if(s-t>16&&e.buffer&&UTF8Decoder)return UTF8Decoder.decode(e.subarray(t,s));for(var o="";t>10,56320|d&1023)}}return o},"UTF8ArrayToString"),getDylinkMetadata=M(e=>{var t=0,n=0;function r(){return e[t++]}M(r,"getU8");function s(){for(var X=0,B=1;;){var P=e[t++];if(X+=(P&127)*B,B*=128,!(P&128))break}return X}M(s,"getLEB");function o(){var X=s();return t+=X,UTF8ArrayToString(e,t-X,X)}M(o,"getString");function a(){for(var X=s(),B=[];X--;)B.push(o());return B}M(a,"getStringList");function l(X,B){if(X)throw new Error(B)}if(M(l,"failIf"),e instanceof WebAssembly.Module){var c=WebAssembly.Module.customSections(e,"dylink.0");l(c.length===0,"need dylink section"),e=new Uint8Array(c[0]),n=e.length}else{var d=new Uint32Array(new Uint8Array(e.subarray(0,24)).buffer),u=d[0]==1836278016||d[0]==6386541;l(!u,"need to see wasm magic number"),l(e[8]!==0,"need the dylink section to be first"),t=9;var f=s();n=t+f;var p=o();l(p!=="dylink.0")}for(var m={neededDynlibs:[],tlsExports:new Set,weakImports:new Set,runtimePaths:[]},g=1,h=2,_=3,y=4,x=5,E=256,w=3,k=1;t>1)*2);case"i32":return LE_HEAP_LOAD_I32((e>>2)*4);case"i64":return LE_HEAP_LOAD_I64((e>>3)*8);case"float":return LE_HEAP_LOAD_F32((e>>2)*4);case"double":return LE_HEAP_LOAD_F64((e>>3)*8);case"*":return LE_HEAP_LOAD_U32((e>>2)*4);default:abort(`invalid type for getValue: ${t}`)}}M(getValue,"getValue");var newDSO=M((e,t,n)=>{var r={refcount:1/0,name:e,exports:n,global:!0};return LDSO.loadedLibsByName[e]=r,t!=null&&(LDSO.loadedLibsByHandle[t]=r),r},"newDSO"),LDSO={loadedLibsByName:{},loadedLibsByHandle:{},init(){newDSO("__main__",0,wasmImports)}},___heap_base=78240,alignMemory=M((e,t)=>Math.ceil(e/t)*t,"alignMemory"),getMemory=M(e=>{if(runtimeInitialized)return _calloc(e,1);var t=___heap_base,n=t+alignMemory(e,16);return ___heap_base=n,GOT.__heap_base.value=n,t},"getMemory"),isInternalSym=M(e=>["__cpp_exception","__c_longjmp","__wasm_apply_data_relocs","__dso_handle","__tls_size","__tls_align","__set_stack_limits","_emscripten_tls_init","__wasm_init_tls","__wasm_call_ctors","__start_em_asm","__stop_em_asm","__start_em_js","__stop_em_js"].includes(e)||e.startsWith("__em_js__"),"isInternalSym"),uleb128EncodeWithLen=M(e=>{let t=e.length;return[t%128|128,t>>7,...e]},"uleb128EncodeWithLen"),wasmTypeCodes={i:127,p:127,j:126,f:125,d:124,e:111},generateTypePack=M(e=>uleb128EncodeWithLen(Array.from(e,t=>{var n=wasmTypeCodes[t];return n})),"generateTypePack"),convertJsFunctionToWasm=M((e,t)=>{var n=Uint8Array.of(0,97,115,109,1,0,0,0,1,...uleb128EncodeWithLen([1,96,...generateTypePack(t.slice(1)),...generateTypePack(t[0]==="v"?"":t[0])]),2,7,1,1,101,1,102,0,0,7,5,1,1,102,0,0),r=new WebAssembly.Module(n),s=new WebAssembly.Instance(r,{e:{f:e}}),o=s.exports.f;return o},"convertJsFunctionToWasm"),wasmTableMirror=[],wasmTable=new WebAssembly.Table({initial:31,element:"anyfunc"}),getWasmTableEntry=M(e=>{var t=wasmTableMirror[e];return t||(wasmTableMirror[e]=t=wasmTable.get(e)),t},"getWasmTableEntry"),updateTableMap=M((e,t)=>{if(functionsInTableMap)for(var n=e;n(functionsInTableMap||(functionsInTableMap=new WeakMap,updateTableMap(0,wasmTable.length)),functionsInTableMap.get(e)||0),"getFunctionAddress"),freeTableIndexes=[],getEmptyTableSlot=M(()=>freeTableIndexes.length?freeTableIndexes.pop():wasmTable.grow(1),"getEmptyTableSlot"),setWasmTableEntry=M((e,t)=>{wasmTable.set(e,t),wasmTableMirror[e]=wasmTable.get(e)},"setWasmTableEntry"),addFunction=M((e,t)=>{var n=getFunctionAddress(e);if(n)return n;var r=getEmptyTableSlot();try{setWasmTableEntry(r,e)}catch(o){if(!(o instanceof TypeError))throw o;var s=convertJsFunctionToWasm(e,t);setWasmTableEntry(r,s)}return functionsInTableMap.set(e,r),r},"addFunction"),updateGOT=M((e,t)=>{for(var n in e)if(!isInternalSym(n)){var r=e[n];GOT[n]||=new WebAssembly.Global({value:"i32",mutable:!0}),(t||GOT[n].value==0)&&(typeof r=="function"?GOT[n].value=addFunction(r):typeof r=="number"?GOT[n].value=r:err(`unhandled export type for '${n}': ${typeof r}`))}},"updateGOT"),relocateExports=M((e,t,n)=>{var r={};for(var s in e){var o=e[s];typeof o=="object"&&(o=o.value),typeof o=="number"&&(o+=t),r[s]=o}return updateGOT(r,n),r},"relocateExports"),isSymbolDefined=M(e=>{var t=wasmImports[e];return!(!t||t.stub)},"isSymbolDefined"),dynCall=M((e,t,n=[],r=!1)=>{var s=getWasmTableEntry(t),o=s(...n);function a(l){return l}return M(a,"convert"),o},"dynCall"),stackSave=M(()=>_emscripten_stack_get_current(),"stackSave"),stackRestore=M(e=>__emscripten_stack_restore(e),"stackRestore"),createInvokeFunction=M(e=>(t,...n)=>{var r=stackSave();try{return dynCall(e,t,n)}catch(s){if(stackRestore(r),s!==s+0)throw s;if(_setThrew(1,0),e[0]=="j")return 0n}},"createInvokeFunction"),resolveGlobalSymbol=M((e,t=!1)=>{var n;return isSymbolDefined(e)?n=wasmImports[e]:e.startsWith("invoke_")&&(n=wasmImports[e]=createInvokeFunction(e.split("_")[1])),{sym:n,name:e}},"resolveGlobalSymbol"),onPostCtors=[],addOnPostCtor=M(e=>onPostCtors.push(e),"addOnPostCtor"),UTF8ToString=M((e,t,n)=>e?UTF8ArrayToString(HEAPU8,e,t,n):"","UTF8ToString"),loadWebAssemblyModule=M((binary,flags,libName,localScope,handle)=>{var metadata=getDylinkMetadata(binary);function loadModule(){var memAlign=Math.pow(2,metadata.memoryAlign),memoryBase=metadata.memorySize?alignMemory(getMemory(metadata.memorySize+memAlign),memAlign):0,tableBase=metadata.tableSize?wasmTable.length:0;handle&&(HEAP8[handle+8]=1,LE_HEAP_STORE_U32((handle+12>>2)*4,memoryBase),LE_HEAP_STORE_I32((handle+16>>2)*4,metadata.memorySize),LE_HEAP_STORE_U32((handle+20>>2)*4,tableBase),LE_HEAP_STORE_I32((handle+24>>2)*4,metadata.tableSize)),metadata.tableSize&&wasmTable.grow(metadata.tableSize);var moduleExports;function resolveSymbol(e){var t=resolveGlobalSymbol(e).sym;return!t&&localScope&&(t=localScope[e]),t||(t=moduleExports[e]),t}M(resolveSymbol,"resolveSymbol");var proxyHandler={get(e,t){switch(t){case"__memory_base":return memoryBase;case"__table_base":return tableBase}if(t in wasmImports&&!wasmImports[t].stub){var n=wasmImports[t];return n}if(!(t in e)){var r;e[t]=(...s)=>(r||=resolveSymbol(t),r(...s))}return e[t]}},proxy=new Proxy({},proxyHandler);currentModuleWeakSymbols=metadata.weakImports;var info={"GOT.mem":new Proxy({},GOTHandler),"GOT.func":new Proxy({},GOTHandler),env:proxy,wasi_snapshot_preview1:proxy};function postInstantiation(module,instance){updateTableMap(tableBase,metadata.tableSize),moduleExports=relocateExports(instance.exports,memoryBase),flags.allowUndefined||reportUndefinedSymbols();function addEmAsm(addr,body){for(var args=[],arity=0;arity<16&&body.indexOf("$"+arity)!=-1;arity++)args.push("$"+arity);args=args.join(",");var func=`(${args}) => { ${body} };`;ASM_CONSTS[start]=eval(func)}if(M(addEmAsm,"addEmAsm"),"__start_em_asm"in moduleExports)for(var start=moduleExports.__start_em_asm,stop=moduleExports.__stop_em_asm;start ${body};`;moduleExports[name]=eval(func)}M(addEmJs,"addEmJs");for(var name in moduleExports)if(name.startsWith("__em_js__")){var start=moduleExports[name],jsString=UTF8ToString(start),parts=jsString.split("<::>");addEmJs(name.replace("__em_js__",""),parts[0],parts[1]),delete moduleExports[name]}var applyRelocs=moduleExports.__wasm_apply_data_relocs;applyRelocs&&(runtimeInitialized?applyRelocs():__RELOC_FUNCS__.push(applyRelocs));var init=moduleExports.__wasm_call_ctors;return init&&(runtimeInitialized?init():addOnPostCtor(init)),moduleExports}if(M(postInstantiation,"postInstantiation"),flags.loadAsync)return(async()=>{var e;return binary instanceof WebAssembly.Module?e=new WebAssembly.Instance(binary,info):{module:binary,instance:e}=await WebAssembly.instantiate(binary,info),postInstantiation(binary,e)})();var module=binary instanceof WebAssembly.Module?binary:new WebAssembly.Module(binary),instance=new WebAssembly.Instance(module,info);return postInstantiation(module,instance)}return M(loadModule,"loadModule"),flags={...flags,rpath:{parentLibPath:libName,paths:metadata.runtimePaths}},flags.loadAsync?metadata.neededDynlibs.reduce((e,t)=>e.then(()=>loadDynamicLibrary(t,flags,localScope)),Promise.resolve()).then(loadModule):(metadata.neededDynlibs.forEach(e=>loadDynamicLibrary(e,flags,localScope)),loadModule())},"loadWebAssemblyModule"),mergeLibSymbols=M((e,t)=>{for(var[n,r]of Object.entries(e)){let s=M(a=>{isSymbolDefined(a)||(wasmImports[a]=r)},"setImport");s(n);let o="__main_argc_argv";n=="main"&&s(o),n==o&&s("main")}},"mergeLibSymbols"),asyncLoad=M(async e=>{var t=await readAsync(e);return new Uint8Array(t)},"asyncLoad");function loadDynamicLibrary(e,t={global:!0,nodelete:!0},n,r){var s=LDSO.loadedLibsByName[e];if(s)return t.global?s.global||(s.global=!0,mergeLibSymbols(s.exports,e)):n&&Object.assign(n,s.exports),t.nodelete&&s.refcount!==1/0&&(s.refcount=1/0),s.refcount++,r&&(LDSO.loadedLibsByHandle[r]=s),t.loadAsync?Promise.resolve(!0):!0;s=newDSO(e,r,"loading"),s.refcount=t.nodelete?1/0:1,s.global=t.global;function o(){if(r){var c=LE_HEAP_LOAD_U32((r+28>>2)*4),d=LE_HEAP_LOAD_U32((r+32>>2)*4);if(c&&d){var u=HEAP8.slice(c,c+d);return t.loadAsync?Promise.resolve(u):u}}var f=locateFile(e);if(t.loadAsync)return asyncLoad(f);if(!readBinary)throw new Error(`${f}: file not found, and synchronous loading of external files is not available`);return readBinary(f)}M(o,"loadLibData");function a(){return t.loadAsync?o().then(c=>loadWebAssemblyModule(c,t,e,n,r)):loadWebAssemblyModule(o(),t,e,n,r)}M(a,"getExports");function l(c){s.global?mergeLibSymbols(c,e):n&&Object.assign(n,c),s.exports=c}return M(l,"moduleLoaded"),t.loadAsync?a().then(c=>(l(c),!0)):(l(a()),!0)}M(loadDynamicLibrary,"loadDynamicLibrary");var reportUndefinedSymbols=M(()=>{for(var[e,t]of Object.entries(GOT))if(t.value==0){var n=resolveGlobalSymbol(e,!0).sym;if(!n&&!t.required)continue;if(typeof n=="function")t.value=addFunction(n,n.sig);else if(typeof n=="number")t.value=n;else throw new Error(`bad export type for '${e}': ${typeof n}`)}},"reportUndefinedSymbols"),runDependencies=0,dependenciesFulfilled=null,removeRunDependency=M(e=>{if(runDependencies--,Module.monitorRunDependencies?.(runDependencies),runDependencies==0&&dependenciesFulfilled){var t=dependenciesFulfilled;dependenciesFulfilled=null,t()}},"removeRunDependency"),addRunDependency=M(e=>{runDependencies++,Module.monitorRunDependencies?.(runDependencies)},"addRunDependency"),loadDylibs=M(async()=>{if(!dynamicLibraries.length){reportUndefinedSymbols();return}addRunDependency("loadDylibs");for(var e of dynamicLibraries)await loadDynamicLibrary(e,{loadAsync:!0,global:!0,nodelete:!0,allowUndefined:!0});reportUndefinedSymbols(),removeRunDependency("loadDylibs")},"loadDylibs"),noExitRuntime=!0;function setValue(e,t,n="i8"){switch(n.endsWith("*")&&(n="*"),n){case"i1":HEAP8[e]=t;break;case"i8":HEAP8[e]=t;break;case"i16":LE_HEAP_STORE_I16((e>>1)*2,t);break;case"i32":LE_HEAP_STORE_I32((e>>2)*4,t);break;case"i64":LE_HEAP_STORE_I64((e>>3)*8,BigInt(t));break;case"float":LE_HEAP_STORE_F32((e>>2)*4,t);break;case"double":LE_HEAP_STORE_F64((e>>3)*8,t);break;case"*":LE_HEAP_STORE_U32((e>>2)*4,t);break;default:abort(`invalid type for setValue: ${n}`)}}M(setValue,"setValue");var ___memory_base=new WebAssembly.Global({value:"i32",mutable:!1},1024),___stack_high=78240,___stack_low=12704,___stack_pointer=new WebAssembly.Global({value:"i32",mutable:!0},78240),___table_base=new WebAssembly.Global({value:"i32",mutable:!1},1),__abort_js=M(()=>abort(""),"__abort_js");__abort_js.sig="v";var getHeapMax=M(()=>2147483648,"getHeapMax"),growMemory=M(e=>{var t=wasmMemory.buffer.byteLength,n=(e-t+65535)/65536|0;try{return wasmMemory.grow(n),updateMemoryViews(),1}catch{}},"growMemory"),_emscripten_resize_heap=M(e=>{var t=HEAPU8.length;e>>>=0;var n=getHeapMax();if(e>n)return!1;for(var r=1;r<=4;r*=2){var s=t*(1+.2/r);s=Math.min(s,e+100663296);var o=Math.min(n,alignMemory(Math.max(e,s),65536)),a=growMemory(o);if(a)return!0}return!1},"_emscripten_resize_heap");_emscripten_resize_heap.sig="ip";var _fd_close=M(e=>52,"_fd_close");_fd_close.sig="ii";var INT53_MAX=9007199254740992,INT53_MIN=-9007199254740992,bigintToI53Checked=M(e=>eINT53_MAX?NaN:Number(e),"bigintToI53Checked");function _fd_seek(e,t,n,r){return t=bigintToI53Checked(t),70}M(_fd_seek,"_fd_seek"),_fd_seek.sig="iijip";var printCharBuffers=[null,[],[]],printChar=M((e,t)=>{var n=printCharBuffers[e];t===0||t===10?((e===1?out:err)(UTF8ArrayToString(n)),n.length=0):n.push(t)},"printChar"),_fd_write=M((e,t,n,r)=>{for(var s=0,o=0;o>2)*4),l=LE_HEAP_LOAD_U32((t+4>>2)*4);t+=8;for(var c=0;c>2)*4,s),0},"_fd_write");_fd_write.sig="iippp";function _tree_sitter_log_callback(e,t){if(Module.currentLogCallback){let n=UTF8ToString(t);Module.currentLogCallback(n,e!==0)}}M(_tree_sitter_log_callback,"_tree_sitter_log_callback");function _tree_sitter_parse_callback(e,t,n,r,s){let a=Module.currentParseCallback(t,{row:n,column:r});typeof a=="string"?(setValue(s,a.length,"i32"),stringToUTF16(a,e,10240)):setValue(s,0,"i32")}M(_tree_sitter_parse_callback,"_tree_sitter_parse_callback");function _tree_sitter_progress_callback(e,t){return Module.currentProgressCallback?Module.currentProgressCallback({currentOffset:e,hasError:t}):!1}M(_tree_sitter_progress_callback,"_tree_sitter_progress_callback");function _tree_sitter_query_progress_callback(e){return Module.currentQueryProgressCallback?Module.currentQueryProgressCallback({currentOffset:e}):!1}M(_tree_sitter_query_progress_callback,"_tree_sitter_query_progress_callback");var runtimeKeepaliveCounter=0,keepRuntimeAlive=M(()=>noExitRuntime||runtimeKeepaliveCounter>0,"keepRuntimeAlive"),_proc_exit=M(e=>{EXITSTATUS=e,keepRuntimeAlive()||(Module.onExit?.(e),ABORT=!0),quit_(e,new ExitStatus(e))},"_proc_exit");_proc_exit.sig="vi";var exitJS=M((e,t)=>{EXITSTATUS=e,_proc_exit(e)},"exitJS"),handleException=M(e=>{if(e instanceof ExitStatus||e=="unwind")return EXITSTATUS;quit_(1,e)},"handleException"),lengthBytesUTF8=M(e=>{for(var t=0,n=0;n=55296&&r<=57343?(t+=4,++n):t+=3}return t},"lengthBytesUTF8"),stringToUTF8Array=M((e,t,n,r)=>{if(!(r>0))return 0;for(var s=n,o=n+r-1,a=0;a=o)break;t[n++]=l}else if(l<=2047){if(n+1>=o)break;t[n++]=192|l>>6,t[n++]=128|l&63}else if(l<=65535){if(n+2>=o)break;t[n++]=224|l>>12,t[n++]=128|l>>6&63,t[n++]=128|l&63}else{if(n+3>=o)break;t[n++]=240|l>>18,t[n++]=128|l>>12&63,t[n++]=128|l>>6&63,t[n++]=128|l&63,a++}}return t[n]=0,n-s},"stringToUTF8Array"),stringToUTF8=M((e,t,n)=>stringToUTF8Array(e,HEAPU8,t,n),"stringToUTF8"),stackAlloc=M(e=>__emscripten_stack_alloc(e),"stackAlloc"),stringToUTF8OnStack=M(e=>{var t=lengthBytesUTF8(e)+1,n=stackAlloc(t);return stringToUTF8(e,n,t),n},"stringToUTF8OnStack"),AsciiToString=M(e=>{for(var t="";;){var n=HEAPU8[e++];if(!n)return t;t+=String.fromCharCode(n)}},"AsciiToString"),stringToUTF16=M((e,t,n)=>{if(n??=2147483647,n<2)return 0;n-=2;for(var r=t,s=n>1)*2,a),t+=2}return LE_HEAP_STORE_I16((t>>1)*2,0),t-r},"stringToUTF16");LE_ATOMICS_NATIVE_BYTE_ORDER=new Int8Array(new Int16Array([1]).buffer)[0]===1?[(e=>e),(e=>e),void 0,(e=>e)]:[(e=>e),(e=>((e&65280)<<8|(e&255)<<24)>>16),void 0,(e=>e>>24&255|e>>8&65280|(e&65280)<<8|(e&255)<<24)];function LE_HEAP_UPDATE(){HEAPU16.unsigned=(e=>e&65535),HEAPU32.unsigned=(e=>e>>>0)}if(M(LE_HEAP_UPDATE,"LE_HEAP_UPDATE"),initMemory(),Module.noExitRuntime&&(noExitRuntime=Module.noExitRuntime),Module.print&&(out=Module.print),Module.printErr&&(err=Module.printErr),Module.dynamicLibraries&&(dynamicLibraries=Module.dynamicLibraries),Module.wasmBinary&&(wasmBinary=Module.wasmBinary),Module.arguments&&(arguments_=Module.arguments),Module.thisProgram&&(thisProgram=Module.thisProgram),Module.preInit)for(typeof Module.preInit=="function"&&(Module.preInit=[Module.preInit]);Module.preInit.length>0;)Module.preInit.shift()();Module.setValue=setValue,Module.getValue=getValue,Module.UTF8ToString=UTF8ToString,Module.stringToUTF8=stringToUTF8,Module.lengthBytesUTF8=lengthBytesUTF8,Module.AsciiToString=AsciiToString,Module.stringToUTF16=stringToUTF16,Module.loadWebAssemblyModule=loadWebAssemblyModule,Module.LE_HEAP_STORE_I64=LE_HEAP_STORE_I64;var ASM_CONSTS={},_malloc,_calloc,_realloc,_free,_ts_range_edit,_memcmp,_ts_language_symbol_count,_ts_language_state_count,_ts_language_abi_version,_ts_language_name,_ts_language_field_count,_ts_language_next_state,_ts_language_symbol_name,_ts_language_symbol_for_name,_strncmp,_ts_language_symbol_type,_ts_language_field_name_for_id,_ts_lookahead_iterator_new,_ts_lookahead_iterator_delete,_ts_lookahead_iterator_reset_state,_ts_lookahead_iterator_reset,_ts_lookahead_iterator_next,_ts_lookahead_iterator_current_symbol,_ts_point_edit,_ts_parser_delete,_ts_parser_reset,_ts_parser_set_language,_ts_parser_set_included_ranges,_ts_query_new,_ts_query_delete,_iswspace,_iswalnum,_ts_query_pattern_count,_ts_query_capture_count,_ts_query_string_count,_ts_query_capture_name_for_id,_ts_query_capture_quantifier_for_id,_ts_query_string_value_for_id,_ts_query_predicates_for_pattern,_ts_query_start_byte_for_pattern,_ts_query_end_byte_for_pattern,_ts_query_is_pattern_rooted,_ts_query_is_pattern_non_local,_ts_query_is_pattern_guaranteed_at_step,_ts_query_disable_capture,_ts_query_disable_pattern,_ts_tree_copy,_ts_tree_delete,_ts_init,_ts_parser_new_wasm,_ts_parser_enable_logger_wasm,_ts_parser_parse_wasm,_ts_parser_included_ranges_wasm,_ts_language_type_is_named_wasm,_ts_language_type_is_visible_wasm,_ts_language_metadata_wasm,_ts_language_supertypes_wasm,_ts_language_subtypes_wasm,_ts_tree_root_node_wasm,_ts_tree_root_node_with_offset_wasm,_ts_tree_edit_wasm,_ts_tree_included_ranges_wasm,_ts_tree_get_changed_ranges_wasm,_ts_tree_cursor_new_wasm,_ts_tree_cursor_copy_wasm,_ts_tree_cursor_delete_wasm,_ts_tree_cursor_reset_wasm,_ts_tree_cursor_reset_to_wasm,_ts_tree_cursor_goto_first_child_wasm,_ts_tree_cursor_goto_last_child_wasm,_ts_tree_cursor_goto_first_child_for_index_wasm,_ts_tree_cursor_goto_first_child_for_position_wasm,_ts_tree_cursor_goto_next_sibling_wasm,_ts_tree_cursor_goto_previous_sibling_wasm,_ts_tree_cursor_goto_descendant_wasm,_ts_tree_cursor_goto_parent_wasm,_ts_tree_cursor_current_node_type_id_wasm,_ts_tree_cursor_current_node_state_id_wasm,_ts_tree_cursor_current_node_is_named_wasm,_ts_tree_cursor_current_node_is_missing_wasm,_ts_tree_cursor_current_node_id_wasm,_ts_tree_cursor_start_position_wasm,_ts_tree_cursor_end_position_wasm,_ts_tree_cursor_start_index_wasm,_ts_tree_cursor_end_index_wasm,_ts_tree_cursor_current_field_id_wasm,_ts_tree_cursor_current_depth_wasm,_ts_tree_cursor_current_descendant_index_wasm,_ts_tree_cursor_current_node_wasm,_ts_node_symbol_wasm,_ts_node_field_name_for_child_wasm,_ts_node_field_name_for_named_child_wasm,_ts_node_children_by_field_id_wasm,_ts_node_first_child_for_byte_wasm,_ts_node_first_named_child_for_byte_wasm,_ts_node_grammar_symbol_wasm,_ts_node_child_count_wasm,_ts_node_named_child_count_wasm,_ts_node_child_wasm,_ts_node_named_child_wasm,_ts_node_child_by_field_id_wasm,_ts_node_next_sibling_wasm,_ts_node_prev_sibling_wasm,_ts_node_next_named_sibling_wasm,_ts_node_prev_named_sibling_wasm,_ts_node_descendant_count_wasm,_ts_node_parent_wasm,_ts_node_child_with_descendant_wasm,_ts_node_descendant_for_index_wasm,_ts_node_named_descendant_for_index_wasm,_ts_node_descendant_for_position_wasm,_ts_node_named_descendant_for_position_wasm,_ts_node_start_point_wasm,_ts_node_end_point_wasm,_ts_node_start_index_wasm,_ts_node_end_index_wasm,_ts_node_to_string_wasm,_ts_node_children_wasm,_ts_node_named_children_wasm,_ts_node_descendants_of_type_wasm,_ts_node_is_named_wasm,_ts_node_has_changes_wasm,_ts_node_has_error_wasm,_ts_node_is_error_wasm,_ts_node_is_missing_wasm,_ts_node_is_extra_wasm,_ts_node_parse_state_wasm,_ts_node_next_parse_state_wasm,_ts_query_matches_wasm,_ts_query_captures_wasm,_memset,_memcpy,_memmove,_iswalpha,_iswblank,_iswdigit,_iswlower,_iswupper,_iswxdigit,_memchr,_strlen,_strcmp,_strncat,_strncpy,_towlower,_towupper,_setThrew,__emscripten_stack_restore,__emscripten_stack_alloc,_emscripten_stack_get_current,___wasm_apply_data_relocs;function assignWasmExports(e){Module._malloc=_malloc=e.malloc,Module._calloc=_calloc=e.calloc,Module._realloc=_realloc=e.realloc,Module._free=_free=e.free,Module._ts_range_edit=_ts_range_edit=e.ts_range_edit,Module._memcmp=_memcmp=e.memcmp,Module._ts_language_symbol_count=_ts_language_symbol_count=e.ts_language_symbol_count,Module._ts_language_state_count=_ts_language_state_count=e.ts_language_state_count,Module._ts_language_abi_version=_ts_language_abi_version=e.ts_language_abi_version,Module._ts_language_name=_ts_language_name=e.ts_language_name,Module._ts_language_field_count=_ts_language_field_count=e.ts_language_field_count,Module._ts_language_next_state=_ts_language_next_state=e.ts_language_next_state,Module._ts_language_symbol_name=_ts_language_symbol_name=e.ts_language_symbol_name,Module._ts_language_symbol_for_name=_ts_language_symbol_for_name=e.ts_language_symbol_for_name,Module._strncmp=_strncmp=e.strncmp,Module._ts_language_symbol_type=_ts_language_symbol_type=e.ts_language_symbol_type,Module._ts_language_field_name_for_id=_ts_language_field_name_for_id=e.ts_language_field_name_for_id,Module._ts_lookahead_iterator_new=_ts_lookahead_iterator_new=e.ts_lookahead_iterator_new,Module._ts_lookahead_iterator_delete=_ts_lookahead_iterator_delete=e.ts_lookahead_iterator_delete,Module._ts_lookahead_iterator_reset_state=_ts_lookahead_iterator_reset_state=e.ts_lookahead_iterator_reset_state,Module._ts_lookahead_iterator_reset=_ts_lookahead_iterator_reset=e.ts_lookahead_iterator_reset,Module._ts_lookahead_iterator_next=_ts_lookahead_iterator_next=e.ts_lookahead_iterator_next,Module._ts_lookahead_iterator_current_symbol=_ts_lookahead_iterator_current_symbol=e.ts_lookahead_iterator_current_symbol,Module._ts_point_edit=_ts_point_edit=e.ts_point_edit,Module._ts_parser_delete=_ts_parser_delete=e.ts_parser_delete,Module._ts_parser_reset=_ts_parser_reset=e.ts_parser_reset,Module._ts_parser_set_language=_ts_parser_set_language=e.ts_parser_set_language,Module._ts_parser_set_included_ranges=_ts_parser_set_included_ranges=e.ts_parser_set_included_ranges,Module._ts_query_new=_ts_query_new=e.ts_query_new,Module._ts_query_delete=_ts_query_delete=e.ts_query_delete,Module._iswspace=_iswspace=e.iswspace,Module._iswalnum=_iswalnum=e.iswalnum,Module._ts_query_pattern_count=_ts_query_pattern_count=e.ts_query_pattern_count,Module._ts_query_capture_count=_ts_query_capture_count=e.ts_query_capture_count,Module._ts_query_string_count=_ts_query_string_count=e.ts_query_string_count,Module._ts_query_capture_name_for_id=_ts_query_capture_name_for_id=e.ts_query_capture_name_for_id,Module._ts_query_capture_quantifier_for_id=_ts_query_capture_quantifier_for_id=e.ts_query_capture_quantifier_for_id,Module._ts_query_string_value_for_id=_ts_query_string_value_for_id=e.ts_query_string_value_for_id,Module._ts_query_predicates_for_pattern=_ts_query_predicates_for_pattern=e.ts_query_predicates_for_pattern,Module._ts_query_start_byte_for_pattern=_ts_query_start_byte_for_pattern=e.ts_query_start_byte_for_pattern,Module._ts_query_end_byte_for_pattern=_ts_query_end_byte_for_pattern=e.ts_query_end_byte_for_pattern,Module._ts_query_is_pattern_rooted=_ts_query_is_pattern_rooted=e.ts_query_is_pattern_rooted,Module._ts_query_is_pattern_non_local=_ts_query_is_pattern_non_local=e.ts_query_is_pattern_non_local,Module._ts_query_is_pattern_guaranteed_at_step=_ts_query_is_pattern_guaranteed_at_step=e.ts_query_is_pattern_guaranteed_at_step,Module._ts_query_disable_capture=_ts_query_disable_capture=e.ts_query_disable_capture,Module._ts_query_disable_pattern=_ts_query_disable_pattern=e.ts_query_disable_pattern,Module._ts_tree_copy=_ts_tree_copy=e.ts_tree_copy,Module._ts_tree_delete=_ts_tree_delete=e.ts_tree_delete,Module._ts_init=_ts_init=e.ts_init,Module._ts_parser_new_wasm=_ts_parser_new_wasm=e.ts_parser_new_wasm,Module._ts_parser_enable_logger_wasm=_ts_parser_enable_logger_wasm=e.ts_parser_enable_logger_wasm,Module._ts_parser_parse_wasm=_ts_parser_parse_wasm=e.ts_parser_parse_wasm,Module._ts_parser_included_ranges_wasm=_ts_parser_included_ranges_wasm=e.ts_parser_included_ranges_wasm,Module._ts_language_type_is_named_wasm=_ts_language_type_is_named_wasm=e.ts_language_type_is_named_wasm,Module._ts_language_type_is_visible_wasm=_ts_language_type_is_visible_wasm=e.ts_language_type_is_visible_wasm,Module._ts_language_metadata_wasm=_ts_language_metadata_wasm=e.ts_language_metadata_wasm,Module._ts_language_supertypes_wasm=_ts_language_supertypes_wasm=e.ts_language_supertypes_wasm,Module._ts_language_subtypes_wasm=_ts_language_subtypes_wasm=e.ts_language_subtypes_wasm,Module._ts_tree_root_node_wasm=_ts_tree_root_node_wasm=e.ts_tree_root_node_wasm,Module._ts_tree_root_node_with_offset_wasm=_ts_tree_root_node_with_offset_wasm=e.ts_tree_root_node_with_offset_wasm,Module._ts_tree_edit_wasm=_ts_tree_edit_wasm=e.ts_tree_edit_wasm,Module._ts_tree_included_ranges_wasm=_ts_tree_included_ranges_wasm=e.ts_tree_included_ranges_wasm,Module._ts_tree_get_changed_ranges_wasm=_ts_tree_get_changed_ranges_wasm=e.ts_tree_get_changed_ranges_wasm,Module._ts_tree_cursor_new_wasm=_ts_tree_cursor_new_wasm=e.ts_tree_cursor_new_wasm,Module._ts_tree_cursor_copy_wasm=_ts_tree_cursor_copy_wasm=e.ts_tree_cursor_copy_wasm,Module._ts_tree_cursor_delete_wasm=_ts_tree_cursor_delete_wasm=e.ts_tree_cursor_delete_wasm,Module._ts_tree_cursor_reset_wasm=_ts_tree_cursor_reset_wasm=e.ts_tree_cursor_reset_wasm,Module._ts_tree_cursor_reset_to_wasm=_ts_tree_cursor_reset_to_wasm=e.ts_tree_cursor_reset_to_wasm,Module._ts_tree_cursor_goto_first_child_wasm=_ts_tree_cursor_goto_first_child_wasm=e.ts_tree_cursor_goto_first_child_wasm,Module._ts_tree_cursor_goto_last_child_wasm=_ts_tree_cursor_goto_last_child_wasm=e.ts_tree_cursor_goto_last_child_wasm,Module._ts_tree_cursor_goto_first_child_for_index_wasm=_ts_tree_cursor_goto_first_child_for_index_wasm=e.ts_tree_cursor_goto_first_child_for_index_wasm,Module._ts_tree_cursor_goto_first_child_for_position_wasm=_ts_tree_cursor_goto_first_child_for_position_wasm=e.ts_tree_cursor_goto_first_child_for_position_wasm,Module._ts_tree_cursor_goto_next_sibling_wasm=_ts_tree_cursor_goto_next_sibling_wasm=e.ts_tree_cursor_goto_next_sibling_wasm,Module._ts_tree_cursor_goto_previous_sibling_wasm=_ts_tree_cursor_goto_previous_sibling_wasm=e.ts_tree_cursor_goto_previous_sibling_wasm,Module._ts_tree_cursor_goto_descendant_wasm=_ts_tree_cursor_goto_descendant_wasm=e.ts_tree_cursor_goto_descendant_wasm,Module._ts_tree_cursor_goto_parent_wasm=_ts_tree_cursor_goto_parent_wasm=e.ts_tree_cursor_goto_parent_wasm,Module._ts_tree_cursor_current_node_type_id_wasm=_ts_tree_cursor_current_node_type_id_wasm=e.ts_tree_cursor_current_node_type_id_wasm,Module._ts_tree_cursor_current_node_state_id_wasm=_ts_tree_cursor_current_node_state_id_wasm=e.ts_tree_cursor_current_node_state_id_wasm,Module._ts_tree_cursor_current_node_is_named_wasm=_ts_tree_cursor_current_node_is_named_wasm=e.ts_tree_cursor_current_node_is_named_wasm,Module._ts_tree_cursor_current_node_is_missing_wasm=_ts_tree_cursor_current_node_is_missing_wasm=e.ts_tree_cursor_current_node_is_missing_wasm,Module._ts_tree_cursor_current_node_id_wasm=_ts_tree_cursor_current_node_id_wasm=e.ts_tree_cursor_current_node_id_wasm,Module._ts_tree_cursor_start_position_wasm=_ts_tree_cursor_start_position_wasm=e.ts_tree_cursor_start_position_wasm,Module._ts_tree_cursor_end_position_wasm=_ts_tree_cursor_end_position_wasm=e.ts_tree_cursor_end_position_wasm,Module._ts_tree_cursor_start_index_wasm=_ts_tree_cursor_start_index_wasm=e.ts_tree_cursor_start_index_wasm,Module._ts_tree_cursor_end_index_wasm=_ts_tree_cursor_end_index_wasm=e.ts_tree_cursor_end_index_wasm,Module._ts_tree_cursor_current_field_id_wasm=_ts_tree_cursor_current_field_id_wasm=e.ts_tree_cursor_current_field_id_wasm,Module._ts_tree_cursor_current_depth_wasm=_ts_tree_cursor_current_depth_wasm=e.ts_tree_cursor_current_depth_wasm,Module._ts_tree_cursor_current_descendant_index_wasm=_ts_tree_cursor_current_descendant_index_wasm=e.ts_tree_cursor_current_descendant_index_wasm,Module._ts_tree_cursor_current_node_wasm=_ts_tree_cursor_current_node_wasm=e.ts_tree_cursor_current_node_wasm,Module._ts_node_symbol_wasm=_ts_node_symbol_wasm=e.ts_node_symbol_wasm,Module._ts_node_field_name_for_child_wasm=_ts_node_field_name_for_child_wasm=e.ts_node_field_name_for_child_wasm,Module._ts_node_field_name_for_named_child_wasm=_ts_node_field_name_for_named_child_wasm=e.ts_node_field_name_for_named_child_wasm,Module._ts_node_children_by_field_id_wasm=_ts_node_children_by_field_id_wasm=e.ts_node_children_by_field_id_wasm,Module._ts_node_first_child_for_byte_wasm=_ts_node_first_child_for_byte_wasm=e.ts_node_first_child_for_byte_wasm,Module._ts_node_first_named_child_for_byte_wasm=_ts_node_first_named_child_for_byte_wasm=e.ts_node_first_named_child_for_byte_wasm,Module._ts_node_grammar_symbol_wasm=_ts_node_grammar_symbol_wasm=e.ts_node_grammar_symbol_wasm,Module._ts_node_child_count_wasm=_ts_node_child_count_wasm=e.ts_node_child_count_wasm,Module._ts_node_named_child_count_wasm=_ts_node_named_child_count_wasm=e.ts_node_named_child_count_wasm,Module._ts_node_child_wasm=_ts_node_child_wasm=e.ts_node_child_wasm,Module._ts_node_named_child_wasm=_ts_node_named_child_wasm=e.ts_node_named_child_wasm,Module._ts_node_child_by_field_id_wasm=_ts_node_child_by_field_id_wasm=e.ts_node_child_by_field_id_wasm,Module._ts_node_next_sibling_wasm=_ts_node_next_sibling_wasm=e.ts_node_next_sibling_wasm,Module._ts_node_prev_sibling_wasm=_ts_node_prev_sibling_wasm=e.ts_node_prev_sibling_wasm,Module._ts_node_next_named_sibling_wasm=_ts_node_next_named_sibling_wasm=e.ts_node_next_named_sibling_wasm,Module._ts_node_prev_named_sibling_wasm=_ts_node_prev_named_sibling_wasm=e.ts_node_prev_named_sibling_wasm,Module._ts_node_descendant_count_wasm=_ts_node_descendant_count_wasm=e.ts_node_descendant_count_wasm,Module._ts_node_parent_wasm=_ts_node_parent_wasm=e.ts_node_parent_wasm,Module._ts_node_child_with_descendant_wasm=_ts_node_child_with_descendant_wasm=e.ts_node_child_with_descendant_wasm,Module._ts_node_descendant_for_index_wasm=_ts_node_descendant_for_index_wasm=e.ts_node_descendant_for_index_wasm,Module._ts_node_named_descendant_for_index_wasm=_ts_node_named_descendant_for_index_wasm=e.ts_node_named_descendant_for_index_wasm,Module._ts_node_descendant_for_position_wasm=_ts_node_descendant_for_position_wasm=e.ts_node_descendant_for_position_wasm,Module._ts_node_named_descendant_for_position_wasm=_ts_node_named_descendant_for_position_wasm=e.ts_node_named_descendant_for_position_wasm,Module._ts_node_start_point_wasm=_ts_node_start_point_wasm=e.ts_node_start_point_wasm,Module._ts_node_end_point_wasm=_ts_node_end_point_wasm=e.ts_node_end_point_wasm,Module._ts_node_start_index_wasm=_ts_node_start_index_wasm=e.ts_node_start_index_wasm,Module._ts_node_end_index_wasm=_ts_node_end_index_wasm=e.ts_node_end_index_wasm,Module._ts_node_to_string_wasm=_ts_node_to_string_wasm=e.ts_node_to_string_wasm,Module._ts_node_children_wasm=_ts_node_children_wasm=e.ts_node_children_wasm,Module._ts_node_named_children_wasm=_ts_node_named_children_wasm=e.ts_node_named_children_wasm,Module._ts_node_descendants_of_type_wasm=_ts_node_descendants_of_type_wasm=e.ts_node_descendants_of_type_wasm,Module._ts_node_is_named_wasm=_ts_node_is_named_wasm=e.ts_node_is_named_wasm,Module._ts_node_has_changes_wasm=_ts_node_has_changes_wasm=e.ts_node_has_changes_wasm,Module._ts_node_has_error_wasm=_ts_node_has_error_wasm=e.ts_node_has_error_wasm,Module._ts_node_is_error_wasm=_ts_node_is_error_wasm=e.ts_node_is_error_wasm,Module._ts_node_is_missing_wasm=_ts_node_is_missing_wasm=e.ts_node_is_missing_wasm,Module._ts_node_is_extra_wasm=_ts_node_is_extra_wasm=e.ts_node_is_extra_wasm,Module._ts_node_parse_state_wasm=_ts_node_parse_state_wasm=e.ts_node_parse_state_wasm,Module._ts_node_next_parse_state_wasm=_ts_node_next_parse_state_wasm=e.ts_node_next_parse_state_wasm,Module._ts_query_matches_wasm=_ts_query_matches_wasm=e.ts_query_matches_wasm,Module._ts_query_captures_wasm=_ts_query_captures_wasm=e.ts_query_captures_wasm,Module._memset=_memset=e.memset,Module._memcpy=_memcpy=e.memcpy,Module._memmove=_memmove=e.memmove,Module._iswalpha=_iswalpha=e.iswalpha,Module._iswblank=_iswblank=e.iswblank,Module._iswdigit=_iswdigit=e.iswdigit,Module._iswlower=_iswlower=e.iswlower,Module._iswupper=_iswupper=e.iswupper,Module._iswxdigit=_iswxdigit=e.iswxdigit,Module._memchr=_memchr=e.memchr,Module._strlen=_strlen=e.strlen,Module._strcmp=_strcmp=e.strcmp,Module._strncat=_strncat=e.strncat,Module._strncpy=_strncpy=e.strncpy,Module._towlower=_towlower=e.towlower,Module._towupper=_towupper=e.towupper,_setThrew=e.setThrew,__emscripten_stack_restore=e._emscripten_stack_restore,__emscripten_stack_alloc=e._emscripten_stack_alloc,_emscripten_stack_get_current=e.emscripten_stack_get_current,___wasm_apply_data_relocs=e.__wasm_apply_data_relocs}M(assignWasmExports,"assignWasmExports");var wasmImports={__heap_base:___heap_base,__indirect_function_table:wasmTable,__memory_base:___memory_base,__stack_high:___stack_high,__stack_low:___stack_low,__stack_pointer:___stack_pointer,__table_base:___table_base,_abort_js:__abort_js,emscripten_resize_heap:_emscripten_resize_heap,fd_close:_fd_close,fd_seek:_fd_seek,fd_write:_fd_write,memory:wasmMemory,tree_sitter_log_callback:_tree_sitter_log_callback,tree_sitter_parse_callback:_tree_sitter_parse_callback,tree_sitter_progress_callback:_tree_sitter_progress_callback,tree_sitter_query_progress_callback:_tree_sitter_query_progress_callback};function callMain(e=[]){var t=resolveGlobalSymbol("main").sym;if(t){e.unshift(thisProgram);var n=e.length,r=stackAlloc((n+1)*4),s=r;e.forEach(a=>{LE_HEAP_STORE_U32((s>>2)*4,stringToUTF8OnStack(a)),s+=4}),LE_HEAP_STORE_U32((s>>2)*4,0);try{var o=t(n,r);return exitJS(o,!0),o}catch(a){return handleException(a)}}}M(callMain,"callMain");function run(e=arguments_){if(runDependencies>0){dependenciesFulfilled=run;return}if(preRun(),runDependencies>0){dependenciesFulfilled=run;return}function t(){if(Module.calledRun=!0,!ABORT){initRuntime(),readyPromiseResolve?.(Module),Module.onRuntimeInitialized?.();var n=Module.noInitialRun||!1;n||callMain(e),postRun()}}M(t,"doRun"),Module.setStatus?(Module.setStatus("Running..."),setTimeout(()=>{setTimeout(()=>Module.setStatus(""),1),t()},1)):t()}M(run,"run");var wasmExports;return wasmExports=await createWasm(),run(),runtimeInitialized?moduleRtn=Module:moduleRtn=new Promise((e,t)=>{readyPromiseResolve=e,readyPromiseReject=t}),moduleRtn}async function tc(e){return ec??=await nm(e)}function nc(){return!!ec}function sc(e,t,n,r){if(e.length!==3)throw new Error(`Wrong number of arguments to \`#${n}\` predicate. Expected 2, got ${e.length-1}`);if(!ql(e[1]))throw new Error(`First argument of \`#${n}\` predicate must be a capture. Got "${e[1].value}"`);let s=n==="eq?"||n==="any-eq?",o=!n.startsWith("any-");if(ql(e[2])){let a=e[1].name,l=e[2].name;r[t].push(c=>{let d=[],u=[];for(let p of c)p.name===a&&d.push(p.node),p.name===l&&u.push(p.node);let f=M((p,m,g)=>g?p.text===m.text:p.text!==m.text,"compare");return o?d.every(p=>u.some(m=>f(p,m,s))):d.some(p=>u.some(m=>f(p,m,s)))})}else{let a=e[1].name,l=e[2].value,c=M(u=>u.text===l,"matches"),d=M(u=>u.text!==l,"doesNotMatch");r[t].push(u=>{let f=[];for(let m of u)m.name===a&&f.push(m.node);let p=s?c:d;return o?f.every(p):f.some(p)})}}function ic(e,t,n,r){if(e.length!==3)throw new Error(`Wrong number of arguments to \`#${n}\` predicate. Expected 2, got ${e.length-1}.`);if(e[1].type!=="capture")throw new Error(`First argument of \`#${n}\` predicate must be a capture. Got "${e[1].value}".`);if(e[2].type!=="string")throw new Error(`Second argument of \`#${n}\` predicate must be a string. Got @${e[2].name}.`);let s=n==="match?"||n==="any-match?",o=!n.startsWith("any-"),a=e[1].name,l=new RegExp(e[2].value);r[t].push(c=>{let d=[];for(let f of c)f.name===a&&d.push(f.node.text);let u=M((f,p)=>p?l.test(f):!l.test(f),"test");return d.length===0?!s:o?d.every(f=>u(f,s)):d.some(f=>u(f,s))})}function oc(e,t,n,r){if(e.length<2)throw new Error(`Wrong number of arguments to \`#${n}\` predicate. Expected at least 1. Got ${e.length-1}.`);if(e[1].type!=="capture")throw new Error(`First argument of \`#${n}\` predicate must be a capture. Got "${e[1].value}".`);let s=n==="any-of?",o=e[1].name,a=e.slice(2);if(!a.every(ro))throw new Error(`Arguments to \`#${n}\` predicate must be strings.".`);let l=a.map(c=>c.value);r[t].push(c=>{let d=[];for(let u of c)u.name===o&&d.push(u.node.text);return d.length===0?!s:d.every(u=>l.includes(u))===s})}function ac(e,t,n,r,s){if(e.length<2||e.length>3)throw new Error(`Wrong number of arguments to \`#${n}\` predicate. Expected 1 or 2. Got ${e.length-1}.`);if(!e.every(ro))throw new Error(`Arguments to \`#${n}\` predicate must be strings.".`);let o=n==="is?"?r:s;o[t]||(o[t]={}),o[t][e[1].value]=e[2]?.value??null}function lc(e,t,n){if(e.length<2||e.length>3)throw new Error(`Wrong number of arguments to \`#set!\` predicate. Expected 1 or 2. Got ${e.length-1}.`);if(!e.every(ro))throw new Error('Arguments to `#set!` predicate must be strings.".');n[t]||(n[t]={}),n[t][e[1].value]=e[2]?.value??null}function cc(e,t,n,r,s,o,a,l,c,d,u){if(t===rm){let f=r[n];o.push({type:"capture",name:f})}else if(t===sm)o.push({type:"string",value:s[n]});else if(o.length>0){if(o[0].type!=="string")throw new Error("Predicates must begin with a literal value");let f=o[0].value;switch(f){case"any-not-eq?":case"not-eq?":case"any-eq?":case"eq?":sc(o,e,f,a);break;case"any-not-match?":case"not-match?":case"any-match?":case"match?":ic(o,e,f,a);break;case"not-any-of?":case"any-of?":oc(o,e,f,a);break;case"is?":case"is-not?":ac(o,e,f,d,u);break;case"set!":lc(o,e,c);break;default:l[e].push({operator:f,operands:o.slice(1)})}o.length=0}}var Xf,M,Tw,Gl,U,Ki,Fe,lt,zn,Oe,At,b,Zf,Yf,Qf,em,tm,to,nm,ec,j,Xi,Zi,no,rm,sm,im,Iw,ql,ro,Ke,Bn,dc,so=O(()=>{S();Xf=Object.defineProperty,M=(e,t)=>Xf(e,"name",{value:t,configurable:!0}),Tw=class{static{M(this,"Edit")}startPosition;oldEndPosition;newEndPosition;startIndex;oldEndIndex;newEndIndex;constructor({startIndex:e,oldEndIndex:t,newEndIndex:n,startPosition:r,oldEndPosition:s,newEndPosition:o}){this.startIndex=e>>>0,this.oldEndIndex=t>>>0,this.newEndIndex=n>>>0,this.startPosition=r,this.oldEndPosition=s,this.newEndPosition=o}editPoint(e,t){let n=t,r={...e};if(t>=this.oldEndIndex){n=this.newEndIndex+(t-this.oldEndIndex);let s=e.row;r.row=this.newEndPosition.row+(e.row-this.oldEndPosition.row),r.column=s===this.oldEndPosition.row?this.newEndPosition.column+(e.column-this.oldEndPosition.column):e.column}else t>this.startIndex&&(n=this.newEndIndex,r.row=this.newEndPosition.row,r.column=this.newEndPosition.column);return{point:r,index:n}}editRange(e){let t={startIndex:e.startIndex,startPosition:{...e.startPosition},endIndex:e.endIndex,endPosition:{...e.endPosition}};return e.endIndex>=this.oldEndIndex?e.endIndex!==Number.MAX_SAFE_INTEGER&&(t.endIndex=this.newEndIndex+(e.endIndex-this.oldEndIndex),t.endPosition={row:this.newEndPosition.row+(e.endPosition.row-this.oldEndPosition.row),column:e.endPosition.row===this.oldEndPosition.row?this.newEndPosition.column+(e.endPosition.column-this.oldEndPosition.column):e.endPosition.column},t.endIndexthis.startIndex&&(t.endIndex=this.startIndex,t.endPosition={...this.startPosition}),e.startIndex>=this.oldEndIndex?(t.startIndex=this.newEndIndex+(e.startIndex-this.oldEndIndex),t.startPosition={row:this.newEndPosition.row+(e.startPosition.row-this.oldEndPosition.row),column:e.startPosition.row===this.oldEndPosition.row?this.newEndPosition.column+(e.startPosition.column-this.oldEndPosition.column):e.startPosition.column},t.startIndexthis.startIndex&&(t.startIndex=this.startIndex,t.startPosition={...this.startPosition}),t}},Gl=2,U=4,Ki=4*U,Fe=5*U,lt=2*U,zn=2*U+2*lt,Oe={row:0,column:0},At=Symbol("INTERNAL");M(hn,"assertInternal");M(Hn,"isPoint");M(Vl,"setModule");Zf=class{static{M(this,"LookaheadIterator")}0=0;language;constructor(e,t,n){hn(e),this[0]=t,this.language=n}get currentTypeId(){return b._ts_lookahead_iterator_current_symbol(this[0])}get currentType(){return this.language.types[this.currentTypeId]||"ERROR"}delete(){b._ts_lookahead_iterator_delete(this[0]),this[0]=0}reset(e,t){return b._ts_lookahead_iterator_reset(this[0],e[0],t)?(this.language=e,!0):!1}resetState(e){return!!b._ts_lookahead_iterator_reset_state(this[0],e)}[Symbol.iterator](){return{next:M(()=>b._ts_lookahead_iterator_next(this[0])?{done:!1,value:this.currentType}:{done:!0,value:""},"next")}}};M(eo,"getText");Yf=class Yi{static{M(this,"Tree")}0=0;textCallback;language;constructor(t,n,r,s){hn(t),this[0]=n,this.language=r,this.textCallback=s}copy(){let t=b._ts_tree_copy(this[0]);return new Yi(At,t,this.language,this.textCallback)}delete(){b._ts_tree_delete(this[0]),this[0]=0}get rootNode(){return b._ts_tree_root_node_wasm(this[0]),ue(this)}rootNodeWithOffset(t,n){let r=j+Fe;return b.setValue(r,t,"i32"),ze(r+U,n),b._ts_tree_root_node_with_offset_wasm(this[0]),ue(this)}edit(t){Xl(t),b._ts_tree_edit_wasm(this[0])}walk(){return this.rootNode.walk()}getChangedRanges(t){if(!(t instanceof Yi))throw new TypeError("Argument must be a Tree");b._ts_tree_get_changed_ranges_wasm(this[0],t[0]);let n=b.getValue(j,"i32"),r=b.getValue(j+U,"i32"),s=new Array(n);if(n>0){let o=r;for(let a=0;a0){let s=n;for(let o=0;o0){let s=n;for(let o=0;o0){let n=t;for(let r=0;r0){let n=t;for(let r=0;r0){let d=l;for(let u=0;u=e.oldEndIndex){this.startIndex=e.newEndIndex+(this.startIndex-e.oldEndIndex);let t,n;this.startPosition.row>e.oldEndPosition.row?(t=this.startPosition.row-e.oldEndPosition.row,n=this.startPosition.column):(t=0,n=this.startPosition.column,this.startPosition.column>=e.oldEndPosition.column&&(n=this.startPosition.column-e.oldEndPosition.column)),t>0?(this.startPosition.row+=t,this.startPosition.column=n):this.startPosition.column+=n}else this.startIndex>e.startIndex&&(this.startIndex=e.newEndIndex,this.startPosition.row=e.newEndPosition.row,this.startPosition.column=e.newEndPosition.column)}toString(){H(this);let e=b._ts_node_to_string_wasm(this.tree[0]),t=b.AsciiToString(e);return b._free(e),t}};M(Qi,"unmarshalCaptures");M(H,"marshalNode");M(ue,"unmarshalNode");M(ae,"marshalTreeCursor");M(je,"unmarshalTreeCursor");M(ze,"marshalPoint");M(Vt,"unmarshalPoint");M(Kl,"marshalRange");M(ps,"unmarshalRange");M(Xl,"marshalEdit");M(Zl,"unmarshalLanguageMetadata");tm=/^tree_sitter_\w+$/,to=class Yl{static{M(this,"Language")}0=0;types;fields;constructor(t,n){hn(t),this[0]=n,this.types=new Array(b._ts_language_symbol_count(this[0]));for(let r=0,s=this.types.length;r0){let s=n;for(let o=0;o0){let o=r;for(let a=0;a(Ji(),Vi))).readFile(t);else{let l=await fetch(t);if(!l.ok){let d=await l.text();throw new Error(`Language.load failed with status ${l.status}. +`&&(t[n]=" "),n++;nt.slice(0,m).split(/\r?\n/).length,l=new Map;for(let m of n)l.has(m.name)||l.set(m.name,m);let c=xf(t),d=/export\s*\{([\s\S]*?)\}\s*(?:from\s*['"]([^'"]+)['"])?\s*;?/g,f;for(;(f=d.exec(c))&&s.length{"use strict";k();bf={".ts":"typescript",".tsx":"typescript",".mts":"typescript",".cts":"typescript",".js":"javascript",".jsx":"javascript",".mjs":"javascript",".cjs":"javascript",".py":"python",".pyi":"python",".go":"go",".rb":"ruby",".rake":"ruby",".java":"java",".rs":"rust",".c":"c",".h":"c",".cc":"cpp",".cpp":"cpp",".cxx":"cpp",".hpp":"cpp",".cs":"csharp",".php":"php",".swift":"swift",".kt":"kotlin",".kts":"kotlin",".scala":"scala",".sc":"scala",".clj":"clojure",".ex":"elixir",".exs":"elixir",".erl":"erlang",".hs":"haskell",".dart":"dart",".lua":"lua",".sh":"shell",".bash":"shell",".zsh":"shell",".ksh":"shell",".fish":"shell",".hh":"cpp",".m":"objective-c",".mm":"objective-c",".sql":"sql",".graphql":"graphql",".gql":"graphql",".proto":"protobuf",".md":"markdown",".mdx":"markdown",".rst":"restructuredtext",".txt":"text",".json":"json",".yaml":"yaml",".yml":"yaml",".toml":"toml",".ini":"ini",".html":"html",".css":"css",".scss":"scss",".vue":"vue",".svelte":"svelte",".astro":"astro",".zig":"zig",".hcl":"hcl",".tf":"terraform",".tfvars":"terraform",".sol":"solidity"};wf=new Set([".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs"]);ds=400});function vf(e){return(e.split("/").pop()??"").replace(/\.[^.]+$/,"")}function Rf(e,t){let n=o=>{if(!(!o||o==="default"))for(let a of t)a.name===o&&(a.exported=!0)},r=(o,a)=>{for(let l of o.split(",")){let c=l.trim().replace(/^type\s+/,"");if(!c)continue;let d=/^([\w$]+)\s+as\s+([\w$]+)$/.exec(c);if(d){d[2]!=="default"&&n(d[1]);continue}if(a){let f=/^([\w$]+)\s*:\s*([\w$]+)$/.exec(c);if(f){n(f[1]),n(f[2]);continue}}n(/^([\w$]+)/.exec(c)?.[1])}},s;for(hl.lastIndex=0;s=hl.exec(e);)s[2]||r(s[1]??"",!1);for(yl.lastIndex=0;s=yl.exec(e);)r(s[1]??"",!0);for(bl.lastIndex=0;s=bl.exec(e);)n(s[2])}var Sf,kf,Ef,hl,yl,bl,wl,xl=F(()=>{"use strict";k();ve();Sf=[{re:/^\s*export\s+(?:async\s+)?function\s+(?[\w$]+)/,kind:"function",exported:!0},{re:/^\s*export\s+default\s+(?:async\s+)?function\s+(?[\w$]+)/,kind:"function",exported:!0},{re:/^\s*export\s+default\s+(?:abstract\s+)?class\s+(?!extends\b)(?[\w$]+)/,kind:"class",exported:!0},{re:/^\s*(?:async\s+)?function\s+(?[\w$]+)/,kind:"function",exported:!1},{re:/^\s*export\s+(?:abstract\s+)?class\s+(?[\w$]+)/,kind:"class",exported:!0},{re:/^\s*(?:abstract\s+)?class\s+(?[\w$]+)/,kind:"class",exported:!1},{re:/^\s*export\s+interface\s+(?[\w$]+)/,kind:"interface",exported:!0},{re:/^\s*interface\s+(?[\w$]+)/,kind:"interface",exported:!1},{re:/^\s*export\s+type\s+(?[\w$]+)/,kind:"type",exported:!0},{re:/^\s*type\s+(?[\w$]+)\s*[=<]/,kind:"type",exported:!1},{re:/^\s*export\s+enum\s+(?[\w$]+)/,kind:"enum",exported:!0},{re:/^\s*export\s+const\s+enum\s+(?[\w$]+)/,kind:"enum",exported:!0},{re:/^\s*export\s+(?:const|let|var)\s+(?[\w$]+)\s*[:=]/,kind:"const",exported:!0},{re:/^\s*exports\.(?[\w$]+)\s*=/,kind:"const",exported:!0},{re:/^\s*module\.exports\.(?[\w$]+)\s*=/,kind:"const",exported:!0},{re:/^\s*(?:const|let)\s+(?[\w$]+)\s*=\s*(?:async\s*)?\([^)]*\)\s*(?::[^=]+)?=>/,kind:"const",exported:!1},{re:/^(?:const|let|var)\s+(?[\w$]+)\s*[:=]/,kind:"const",exported:!1},{re:/^\s*export\s+default\s+(?[A-Za-z_$][\w$]*)\s*;?\s*$/,kind:"default",exported:!0}],kf=/^\s*export\s+default\s+(?:async\s+)?(?:function|class)?\s*(?:\(|\{|extends\b)/,Ef=/^\s*export\s+default\s+(?:async\s+)?(?:function|class)\s+(?!extends\b)[\w$]+/;hl=/export\s*\{([^}]*)\}\s*(from\b)?/g,yl=/module\.exports\s*=\s*\{([^}]*)\}/g,bl=/(^|\n)\s*export\s+default\s+([A-Za-z_$][\w$]*)\s*;?\s*(?=\n|$)/g;wl={lang:"javascript/typescript",exts:[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs"],extract(e,t){let n=e.match(/\.(ts|tsx|mts|cts)$/)?"typescript":"javascript",r=ne(e,t,n,Sf),s=t.split(/\r?\n/);for(let o=0;o{"use strict";k();ve();ms=e=>!e.startsWith("_")||e.startsWith("__"),Mf=[{re:/^(?:async\s+)?def\s+(?[\w]+)\s*\(/,kind:"function",exported:e=>ms(e.groups.name)},{re:/^\s+(?:async\s+)?def\s+(?[\w]+)\s*\(/,kind:"method",exported:e=>ms(e.groups.name)},{re:/^class\s+(?[\w]+)/,kind:"class",exported:e=>ms(e.groups.name)},{re:/^\s+class\s+(?[\w]+)/,kind:"class",exported:e=>ms(e.groups.name)}],Sl={lang:"python",exts:[".py",".pyi"],extract(e,t){return ne(e,t,"python",Mf)}}});var jn,Cf,El,vl=F(()=>{"use strict";k();ve();jn=e=>/^[A-Z]/.test(e),Cf=[{re:/^func\s+\([^)]*\)\s+(?[\w]+)\s*\(/,kind:"method",exported:e=>jn(e.groups.name)},{re:/^func\s+(?[\w]+)\s*\(/,kind:"function",exported:e=>jn(e.groups.name)},{re:/^type\s+(?[\w]+)\s+struct\b/,kind:"struct",exported:e=>jn(e.groups.name)},{re:/^type\s+(?[\w]+)\s+interface\b/,kind:"interface",exported:e=>jn(e.groups.name)},{re:/^type\s+(?[\w]+)\s+/,kind:"type",exported:e=>jn(e.groups.name)}],El={lang:"go",exts:[".go"],extract(e,t){return ne(e,t,"go",Cf)}}});var Af,Rl,Ml=F(()=>{"use strict";k();ve();Af=[{re:/^\s*def\s+(?:self\.)?(?[\w?!=]+)/,kind:"method",exported:!0},{re:/^\s*class\s+(?[\w:]+)/,kind:"class",exported:!0},{re:/^\s*module\s+(?[\w:]+)/,kind:"module",exported:!0}],Rl={lang:"ruby",exts:[".rb",".rake"],extract(e,t){return ne(e,t,"ruby",Af)}}});var Tf,Cl,Al=F(()=>{"use strict";k();ve();Tf=[{re:/^\s*(?:public|protected|private)?\s*(?:abstract\s+|final\s+)?class\s+(?[\w]+)/,kind:"class",exported:(e,t)=>/\bpublic\b/.test(t)},{re:/^\s*(?:public|protected|private)?\s*interface\s+(?[\w]+)/,kind:"interface",exported:(e,t)=>/\bpublic\b/.test(t)},{re:/^\s*(?:public|protected|private)?\s*enum\s+(?[\w]+)/,kind:"enum",exported:(e,t)=>/\bpublic\b/.test(t)},{re:/^\s*(?:public|protected|private)\s+(?:static\s+|final\s+|abstract\s+|synchronized\s+)*[\w<>\[\],.?\s]+\s+(?[\w]+)\s*\(/,kind:"method",exported:(e,t)=>/\bpublic\b/.test(t)}],Cl={lang:"java",exts:[".java"],extract(e,t){return ne(e,t,"java",Tf)}}});var Wn,If,Tl,Il=F(()=>{"use strict";k();ve();Wn=(e,t)=>/^\s*pub\b/.test(t),If=[{re:/^\s*(?:pub(?:\([^)]*\))?\s+)?(?:async\s+)?(?:unsafe\s+)?fn\s+(?[\w]+)/,kind:"function",exported:Wn},{re:/^\s*(?:pub(?:\([^)]*\))?\s+)?struct\s+(?[\w]+)/,kind:"struct",exported:Wn},{re:/^\s*(?:pub(?:\([^)]*\))?\s+)?enum\s+(?[\w]+)/,kind:"enum",exported:Wn},{re:/^\s*(?:pub(?:\([^)]*\))?\s+)?trait\s+(?[\w]+)/,kind:"trait",exported:Wn},{re:/^\s*(?:pub(?:\([^)]*\))?\s+)?type\s+(?[\w]+)/,kind:"type",exported:Wn}],Tl={lang:"rust",exts:[".rs"],extract(e,t){return ne(e,t,"rust",If)}}});var Un,Nf,Nl,Ol=F(()=>{"use strict";k();ve();Un=(e,t)=>/\b(public|internal)\b/.test(t),Nf=[{re:/^\s*(?:public|internal|protected|private)?\s*(?:static\s+|sealed\s+|abstract\s+|partial\s+)*(?:class|record)\s+(?\w+)/,kind:"class",exported:Un},{re:/^\s*(?:public|internal|protected|private)?\s*(?:partial\s+)?interface\s+(?\w+)/,kind:"interface",exported:Un},{re:/^\s*(?:public|internal|protected|private)?\s*(?:readonly\s+)?(?:ref\s+)?struct\s+(?\w+)/,kind:"struct",exported:Un},{re:/^\s*(?:public|internal|protected|private)?\s*enum\s+(?\w+)/,kind:"enum",exported:Un},{re:/^\s*(?:public|internal|protected|private)\s+(?:static\s+|virtual\s+|override\s+|async\s+|sealed\s+|abstract\s+|new\s+)*[\w<>\[\],.?]+\s+(?\w+)\s*(?:<[^>]*>)?\s*\(/,kind:"method",exported:Un}],Nl={lang:"csharp",exts:[".cs"],extract(e,t){return ne(e,t,"csharp",Nf)}}});var Of,Fl,Pl=F(()=>{"use strict";k();ve();Of=[{re:/^\s*(?:abstract\s+|final\s+)*class\s+(?\w+)/,kind:"class",exported:!0},{re:/^\s*interface\s+(?\w+)/,kind:"interface",exported:!0},{re:/^\s*trait\s+(?\w+)/,kind:"trait",exported:!0},{re:/^\s*enum\s+(?\w+)/,kind:"enum",exported:!0},{re:/^\s*(?:public\s+|protected\s+|private\s+|static\s+|abstract\s+|final\s+)*function\s+(?\w+)\s*\(/,kind:"function",exported:(e,t)=>!/\b(private|protected)\b/.test(t)}],Fl={lang:"php",exts:[".php"],extract(e,t){return ne(e,t,"php",Of)}}});var Bn,ps,Ff,$l,Ll=F(()=>{"use strict";k();ve();Bn=(e,t)=>!/\b(private|fileprivate)\b/.test(t),ps="(?:public\\s+|open\\s+|internal\\s+|private\\s+|fileprivate\\s+)?(?:final\\s+)?",Ff=[{re:new RegExp(`^\\s*${ps}class\\s+(?\\w+)`),kind:"class",exported:Bn},{re:new RegExp(`^\\s*${ps}struct\\s+(?\\w+)`),kind:"struct",exported:Bn},{re:new RegExp(`^\\s*${ps}enum\\s+(?\\w+)`),kind:"enum",exported:Bn},{re:new RegExp(`^\\s*${ps}protocol\\s+(?\\w+)`),kind:"protocol",exported:Bn},{re:/^\s*(?:public\s+|open\s+|internal\s+|private\s+|fileprivate\s+)?(?:static\s+|class\s+|final\s+|override\s+|mutating\s+|@\w+\s+)*func\s+(?\w+)/,kind:"function",exported:Bn}],$l={lang:"swift",exts:[".swift"],extract(e,t){return ne(e,t,"swift",Ff)}}});var gs,Pf,Dl,jl=F(()=>{"use strict";k();ve();gs=(e,t)=>!/\b(private|internal)\b/.test(t),Pf=[{re:/^\s*(?:public\s+|internal\s+|private\s+|abstract\s+|sealed\s+|open\s+|final\s+|data\s+)*class\s+(?\w+)/,kind:"class",exported:gs},{re:/^\s*(?:public\s+|internal\s+|private\s+|fun\s+)?interface\s+(?\w+)/,kind:"interface",exported:gs},{re:/^\s*(?:public\s+|internal\s+|private\s+|companion\s+)?object\s+(?\w+)/,kind:"object",exported:gs},{re:/^\s*(?:public\s+|internal\s+|private\s+|protected\s+|override\s+|open\s+|abstract\s+|suspend\s+|inline\s+|operator\s+)*fun\s+(?:<[^>]*>\s+)?(?\w+)\s*\(/,kind:"function",exported:gs}],Dl={lang:"kotlin",exts:[".kt",".kts"],extract(e,t){return ne(e,t,"kotlin",Pf)}}});var $f,Lf,Wl,Ul=F(()=>{"use strict";k();ve();$f="(?!\\s*(?:if|for|while|switch|return|else|do|sizeof|typedef)\\b)",Lf=[{re:/^\s*(?:class|struct)\s+(?[A-Za-z_]\w+)\s*(?:[:{]|$)/,kind:"class",exported:!0},{re:/^\s*namespace\s+(?[A-Za-z_]\w+)/,kind:"namespace",exported:!0},{re:/^\s*(?:typedef\s+)?(?:struct|enum|union)\s+(?[A-Za-z_]\w+)\s*\{/,kind:"struct",exported:!0},{re:new RegExp(`^${$f}[A-Za-z_][\\w\\s\\*&<>:,]*?\\b(?[A-Za-z_]\\w+)\\s*\\([^;{]*\\)\\s*(?:const)?\\s*\\{?\\s*$`),kind:"function",exported:!0}],Wl={lang:"c/cpp",exts:[".c",".h",".cc",".cpp",".cxx",".hpp",".hh"],extract(e,t){return ne(e,t,e.match(/\.(c|h)$/)?"c":"cpp",Lf)}}});var Df,Bl,zl=F(()=>{"use strict";k();ve();Df=[{re:/^\s*local\s+function\s+(?[\w.:]+)\s*\(/,kind:"function",exported:!1},{re:/^\s*function\s+(?[\w.:]+)\s*\(/,kind:"function",exported:!0},{re:/^\s*(?:local\s+)?(?[\w.]+)\s*=\s*function\s*\(/,kind:"function",exported:!0}],Bl={lang:"lua",exts:[".lua"],extract(e,t){return ne(e,t,"lua",Df)}}});var jf,Hl,ql=F(()=>{"use strict";k();ve();jf=[{re:/^\s*function\s+(?[\w:-]+)\s*(?:\(\))?\s*\{?/,kind:"function",exported:!0},{re:/^\s*(?[A-Za-z_][\w:-]*)\s*\(\)\s*\{?/,kind:"function",exported:!0}],Hl={lang:"shell",exts:[".sh",".bash",".zsh",".ksh"],extract(e,t){return ne(e,t,"shell",jf)}}});var Wf,Gl,Vl=F(()=>{"use strict";k();ve();Wf=[{re:/^\s*defmodule\s+(?[\w.]+)/,kind:"module",exported:!0},{re:/^\s*defp\s+(?[\w?!]+)/,kind:"function",exported:!1},{re:/^\s*def\s+(?[\w?!]+)/,kind:"function",exported:!0},{re:/^\s*defmacrop?\s+(?[\w?!]+)/,kind:"macro",exported:!0}],Gl={lang:"elixir",exts:[".ex",".exs"],extract(e,t){return ne(e,t,"elixir",Wf)}}});var Uf,Jl,Kl=F(()=>{"use strict";k();ve();Uf=[{re:/^\s*(?:final\s+|sealed\s+|abstract\s+|implicit\s+)*(?:case\s+)?class\s+(?\w+)/,kind:"class",exported:!0},{re:/^\s*(?:sealed\s+)?trait\s+(?\w+)/,kind:"trait",exported:!0},{re:/^\s*(?:case\s+)?object\s+(?\w+)/,kind:"object",exported:!0},{re:/^\s*(?:override\s+|final\s+|private\s+|protected\s+|implicit\s+)*def\s+(?\w+)/,kind:"def",exported:(e,t)=>!/\b(private|protected)\b/.test(t)}],Jl={lang:"scala",exts:[".scala",".sc"],extract(e,t){return ne(e,t,"scala",Uf)}}});var Tt,Bf,Xl,Zl=F(()=>{"use strict";k();ve();Tt=e=>!(e.groups?.name??"").startsWith("_"),Bf=[{re:/^\s*(?:abstract\s+|base\s+|final\s+|sealed\s+|interface\s+)*class\s+(?\w+)/,kind:"class",exported:Tt},{re:/^\s*mixin\s+(?\w+)/,kind:"mixin",exported:Tt},{re:/^\s*extension\s+(?\w+)/,kind:"extension",exported:Tt},{re:/^\s*enum\s+(?\w+)/,kind:"enum",exported:Tt},{re:/^\s*typedef\s+(?\w+)/,kind:"type",exported:Tt},{re:/^\s*(?:@\w+\s+)*(?:static\s+|final\s+|const\s+|external\s+|abstract\s+)*(?:[\w<>,?\[\]. ]+\s+)?(?\w+)\s*\([^)]*\)\s*(?:async\s*\*?\s*)?(?:=>|\{|;)/,kind:"function",exported:Tt},{re:/^\s*(?:static\s+)?[\w<>,?\[\]. ]+\s+get\s+(?\w+)/,kind:"getter",exported:Tt},{re:/^\s*(?:static\s+)?set\s+(?\w+)\s*\(/,kind:"setter",exported:Tt}],Xl={lang:"dart",exts:[".dart"],extract(e,t){return ne(e,t,"dart",Bf)}}});function Ki(e,t,n){let r=Ji.get(t),s;if(!r)s=[];else try{s=r.extract(e,n)}catch{s=[]}let o=new Set(s.map(l=>l.name)),a=us(e,n,s).filter(l=>!o.has(l.name));return a.length?[...s,...a]:s}function Xi(e){return Ji.get(e)?.lang??Vt(e)}var zf,Ji,yn=F(()=>{"use strict";k();ve();xl();kl();vl();Ml();Al();Il();Ol();Pl();Ll();jl();Ul();zl();ql();Vl();Kl();Zl();zf=[wl,Sl,El,Rl,Cl,Tl,Nl,Fl,$l,Dl,Wl,Bl,Hl,Gl,Jl,Xl],Ji=new Map;for(let e of zf)for(let t of e.exts)Ji.set(t,e)});function Yl(e,t){let n=e.split("/").pop().toLowerCase();return qf.has(t)||Hf.test(n)||Gf.test(e)}function Kf(e,t){let n=e.split("/").pop().toLowerCase();return Vf.has(n)||Jf.has(t)}function Ql(e){return!Xf.has(Xi(e))}function zn(e,t){return Ql(t)?"code":Yl(e,t)?"doc":Kf(e,t)?"config":"other"}var Hf,qf,Gf,Vf,Jf,Zi,Xf,_s=F(()=>{"use strict";k();yn();Hf=/^(readme|changelog|contributing|history|news|authors|notice|security|code_of_conduct|faq|getting[-_]?started|usage|guide|tutorial)\b/i,qf=new Set([".md",".mdx",".rst",".adoc",".txt"]),Gf=/^(docs?|documentation|wiki|guides?|website|site|book)\//i,Vf=new Set(["package.json","pnpm-workspace.yaml","tsconfig.json","jsconfig.json","pyproject.toml","setup.py","setup.cfg","requirements.txt","pipfile","go.mod","cargo.toml","gemfile","pom.xml","build.gradle","build.gradle.kts","composer.json","mix.exs","pubspec.yaml","build.sbt","dockerfile","docker-compose.yml","docker-compose.yaml","makefile",".env.example","manifest.json"]),Jf=new Set([".json",".yaml",".yml",".toml",".ini",".cfg"]),Zi=new Set([".md",".mdx"]);Xf=new Set(["markdown","restructuredtext","text","json","yaml","toml","ini","other","html","css","scss"])});function Zf(e){let t="";for(let n=0;nt.some(r=>r.test(n))}function ec(e){if(!e||e.length===0)return null;let t=yt(e.filter(r=>!r.startsWith("!"))),n=yt(e.filter(r=>r.startsWith("!")).map(r=>r.slice(1)));return r=>(!t||t(r))&&!n?.(r)}var Hn=F(()=>{"use strict";k();Ce()});function M(e,t){return et?1:0}function Yi(e){return(t,n)=>M(e(t),e(n))}var Y=F(()=>{"use strict";k()});function Yf(e){let t=e.split(/\r?\n/),n=[],r=null;for(let s of t){let o=/^\s*(```+|~~~+)/.exec(s);if(r){o&&s.trim().startsWith(r[0][0].repeat(3).slice(0,3))&&(r=null),n.push("");continue}if(o){r=o[1],n.push("");continue}n.push(s)}return n.join(` +`)}function Qf(e){return!e||e.startsWith("#")||e.startsWith("//")?!0:/^[a-z][a-z0-9+.-]*:/i.test(e)}function tc(e){return e.replace(/!\[[^\]]*\]\([^)]*\)/g,"").replace(/`([^`]*)`/g,"$1").replace(/\*\*([^*]+)\*\*/g,"$1").replace(/\*([^*]+)\*/g,"$1").replace(/\[([^\]]*)\]\([^)]*\)/g,"$1").replace(/[#>*_~-]+/g," ").replace(/\s+/g," ").trim()}function em(e){return/[A-Za-zÀ-ɏ]{3,}/.test(e)}function tm(e){return/^(all notable changes to this project|in the interest of fostering|this project adheres to|we as members and leaders|table of contents)\b/i.test(e)}function Qi(e){let t=e,n,r=/^---\r?\n([\s\S]*?)\r?\n---\r?\n?/.exec(t);if(r){let h=/(^|\n)title:\s*["']?(.+?)["']?\s*(\n|$)/i.exec(r[1]);h&&(n=h[2].trim()),t=t.slice(r[0].length)}let s=Yf(t),o=s.split(/\r?\n/),a=[],l=n,c,d=!1;for(let h of o){let S=/^(#{1,6})\s+(.+?)\s*#*\s*$/.exec(h);if(S){let _=tc(S[2]);a.push(_),!l&&S[1].length===1&&(l=_),!c&&S[1].length>=2&&(d=!0);continue}if(!c&&!d){let _=h.trim();if(_&&!/^([-*+]|\d+\.)\s/.test(_)&&!_.startsWith("|")&&!_.startsWith("<")){let E=tc(_);E.length>=8&&em(E)&&!E.endsWith(":")&&!tm(E)&&(c=E.slice(0,200))}}}let f=[],u=new Set,m=h=>{let S=h.trim();S=S.replace(/\s+["'(].*$/,"").trim(),S=S.replace(/^<|>$/g,""),!Qf(S)&&(u.has(S)||(u.add(S),f.push({kind:"doc-link",spec:S})))},p=/!?\[[^\]]*\]\(([^)]+)\)/g,g;for(;g=p.exec(s);)m(g[1]);let y=/^\s*\[[^\]]+\]:\s+(\S+)/gm;for(;g=y.exec(s);)m(g[1]);return{title:l,summary:c,headings:a,refs:f}}var eo=F(()=>{"use strict";k()});function om(e){return e.lengthnc?!1:im.test(e)}function am(e){let t=e.trim();return!t||t.length>nc||sm.has(t)?!1:Number.isFinite(Number(t))}function lm(e){let t=e,n=/^(?:[rRbBuUfF]{1,2}|@|\$)?(?:#*)?(['"`])/.exec(t);if(n){let r=n[1],s=t.indexOf(r),o=t.lastIndexOf(r);o>s&&(t=t.slice(s+1,o))}return t}var nc,nm,rm,sm,im,It,hs=F(()=>{"use strict";k();Y();nc=80,nm=2,rm=256,sm=new Set(["0","1","-1","2","-2"]),im=/[\p{L}\p{N}]/u;It=class{seen=new Set;out=[];get full(){return this.out.length>=rm}add(t,n,r){if(this.full||t==="string"&&!om(n)||t==="number"&&!am(n)||t==="regex"&&!n)return;let s=`${t}\0${n}\0${r}`;this.seen.has(s)||(this.seen.add(s),this.out.push({value:n,line:r,kind:t}))}addString(t,n){this.add("string",lm(t),n)}result(){if(this.out.length)return this.out.sort((t,n)=>M(t.value,n.value)||t.line-n.line||M(t.kind,n.kind))}}});function rc(){return"/home"}function ys(){return typeof navigator<"u"&&navigator?.hardwareConcurrency?navigator.hardwareConcurrency:1}function sc(){return Array.from({length:ys()},()=>({model:"browser",speed:0,times:{user:0,nice:0,sys:0,idle:0,irq:0}}))}var to=F(()=>{k()});function bs(e){let t=typeof e=="string"?e:e.href;try{return decodeURIComponent(new URL(t).pathname)}catch{return t}}function qn(e){return new URL(`file://${e.startsWith("/")?"":"/"}${e}`)}var ws=F(()=>{k()});var no={};Oi(no,{createRequire:()=>dm,default:()=>um});var dm,um,ro=F(()=>{k();dm=()=>{throw new Error("node-only API in the browser build")},um={}});function bn(e){if(e!==Nt)throw new Error("Illegal constructor")}function Vn(e){return!!e&&typeof e.row=="number"&&typeof e.column=="number"}function ac(e){w=e}function co(e,t,n,r){let s=n-t,o=e.textCallback(t,r);if(o){for(t+=o.length;t0)t+=a.length,o+=a;else break}t>n&&(o=o.slice(0,s))}return o??""}function lo(e,t,n,r,s){for(let o=0,a=s.length;o>>0,column:w.getValue(e+W,"i32")>>>0}}function cc(e,t){Ve(e,t.startPosition),e+=dt,Ve(e,t.endPosition),e+=dt,w.setValue(e,t.startIndex,"i32"),e+=W,w.setValue(e,t.endIndex,"i32"),e+=W}function xs(e){let t={};return t.startPosition=Jt(e),e+=dt,t.endPosition=Jt(e),e+=dt,t.startIndex=w.getValue(e,"i32")>>>0,e+=W,t.endIndex=w.getValue(e,"i32")>>>0,t}function dc(e,t=D){Ve(t,e.startPosition),t+=dt,Ve(t,e.oldEndPosition),t+=dt,Ve(t,e.newEndPosition),t+=dt,w.setValue(t,e.startIndex,"i32"),t+=W,w.setValue(t,e.oldEndIndex,"i32"),t+=W,w.setValue(t,e.newEndIndex,"i32"),t+=W}function uc(e){let t=w.getValue(e,"i32"),n=w.getValue(e+=W,"i32"),r=w.getValue(e+=W,"i32");return{major_version:t,minor_version:n,patch_version:r}}async function mc(moduleArg={}){var moduleRtn,Module=moduleArg,ENVIRONMENT_IS_WEB=typeof window=="object",ENVIRONMENT_IS_WORKER=typeof WorkerGlobalScope<"u",ENVIRONMENT_IS_NODE=typeof R=="object"&&R.versions?.node&&R.type!="renderer";if(ENVIRONMENT_IS_NODE){let{createRequire:e}=await Promise.resolve().then(()=>(ro(),no));var require=e(import.meta.url)}Module.currentQueryProgressCallback=null,Module.currentProgressCallback=null,Module.currentLogCallback=null,Module.currentParseCallback=null;var arguments_=[],thisProgram="./this.program",quit_=C((e,t)=>{throw t},"quit_"),_scriptName=import.meta.url,scriptDirectory="";function locateFile(e){return Module.locateFile?Module.locateFile(e,scriptDirectory):scriptDirectory+e}C(locateFile,"locateFile");var readAsync,readBinary;if(ENVIRONMENT_IS_NODE){var fs=require("fs");_scriptName.startsWith("file:")&&(scriptDirectory=require("path").dirname(require("url").fileURLToPath(_scriptName))+"/"),readBinary=C(e=>{e=isFileURI(e)?new URL(e):e;var t=fs.readFileSync(e);return t},"readBinary"),readAsync=C(async(e,t=!0)=>{e=isFileURI(e)?new URL(e):e;var n=fs.readFileSync(e,t?void 0:"utf8");return n},"readAsync"),R.argv.length>1&&(thisProgram=R.argv[1].replace(/\\/g,"/")),arguments_=R.argv.slice(2),quit_=C((e,t)=>{throw R.exitCode=e,t},"quit_")}else if(ENVIRONMENT_IS_WEB||ENVIRONMENT_IS_WORKER){try{scriptDirectory=new URL(".",_scriptName).href}catch{}ENVIRONMENT_IS_WORKER&&(readBinary=C(e=>{var t=new XMLHttpRequest;return t.open("GET",e,!1),t.responseType="arraybuffer",t.send(null),new Uint8Array(t.response)},"readBinary")),readAsync=C(async e=>{if(isFileURI(e))return new Promise((n,r)=>{var s=new XMLHttpRequest;s.open("GET",e,!0),s.responseType="arraybuffer",s.onload=()=>{if(s.status==200||s.status==0&&s.response){n(s.response);return}r(s.status)},s.onerror=r,s.send(null)});var t=await fetch(e,{credentials:"same-origin"});if(t.ok)return t.arrayBuffer();throw new Error(t.status+" : "+t.url)},"readAsync")}var out=console.log.bind(console),err=console.error.bind(console),dynamicLibraries=[],wasmBinary,ABORT=!1,EXITSTATUS,isFileURI=C(e=>e.startsWith("file://"),"isFileURI"),readyPromiseResolve,readyPromiseReject,wasmMemory,HEAP8,HEAPU8,HEAP16,HEAPU16,HEAP32,HEAPU32,HEAPF32,HEAPF64,HEAP64,HEAPU64,HEAP_DATA_VIEW,runtimeInitialized=!1;function updateMemoryViews(){var e=wasmMemory.buffer;Module.HEAP8=HEAP8=new Int8Array(e),Module.HEAP16=HEAP16=new Int16Array(e),Module.HEAPU8=HEAPU8=new Uint8Array(e),Module.HEAPU16=HEAPU16=new Uint16Array(e),Module.HEAP32=HEAP32=new Int32Array(e),Module.HEAPU32=HEAPU32=new Uint32Array(e),Module.HEAPF32=HEAPF32=new Float32Array(e),Module.HEAPF64=HEAPF64=new Float64Array(e),Module.HEAP64=HEAP64=new BigInt64Array(e),Module.HEAPU64=HEAPU64=new BigUint64Array(e),Module.HEAP_DATA_VIEW=HEAP_DATA_VIEW=new DataView(e),LE_HEAP_UPDATE()}C(updateMemoryViews,"updateMemoryViews");function initMemory(){if(Module.wasmMemory)wasmMemory=Module.wasmMemory;else{var e=Module.INITIAL_MEMORY||33554432;wasmMemory=new WebAssembly.Memory({initial:e/65536,maximum:32768})}updateMemoryViews()}C(initMemory,"initMemory");var __RELOC_FUNCS__=[];function preRun(){if(Module.preRun)for(typeof Module.preRun=="function"&&(Module.preRun=[Module.preRun]);Module.preRun.length;)addOnPreRun(Module.preRun.shift());callRuntimeCallbacks(onPreRuns)}C(preRun,"preRun");function initRuntime(){runtimeInitialized=!0,callRuntimeCallbacks(__RELOC_FUNCS__),wasmExports.__wasm_call_ctors(),callRuntimeCallbacks(onPostCtors)}C(initRuntime,"initRuntime");function preMain(){}C(preMain,"preMain");function postRun(){if(Module.postRun)for(typeof Module.postRun=="function"&&(Module.postRun=[Module.postRun]);Module.postRun.length;)addOnPostRun(Module.postRun.shift());callRuntimeCallbacks(onPostRuns)}C(postRun,"postRun");function abort(e){Module.onAbort?.(e),e="Aborted("+e+")",err(e),ABORT=!0,e+=". Build with -sASSERTIONS for more info.";var t=new WebAssembly.RuntimeError(e);throw readyPromiseReject?.(t),t}C(abort,"abort");var wasmBinaryFile;function findWasmBinary(){return Module.locateFile?locateFile("web-tree-sitter.wasm"):new URL("web-tree-sitter.wasm",import.meta.url).href}C(findWasmBinary,"findWasmBinary");function getBinarySync(e){if(e==wasmBinaryFile&&wasmBinary)return new Uint8Array(wasmBinary);if(readBinary)return readBinary(e);throw"both async and sync fetching of the wasm failed"}C(getBinarySync,"getBinarySync");async function getWasmBinary(e){if(!wasmBinary)try{var t=await readAsync(e);return new Uint8Array(t)}catch{}return getBinarySync(e)}C(getWasmBinary,"getWasmBinary");async function instantiateArrayBuffer(e,t){try{var n=await getWasmBinary(e),r=await WebAssembly.instantiate(n,t);return r}catch(s){err(`failed to asynchronously prepare wasm: ${s}`),abort(s)}}C(instantiateArrayBuffer,"instantiateArrayBuffer");async function instantiateAsync(e,t,n){if(!e&&!isFileURI(t)&&!ENVIRONMENT_IS_NODE)try{var r=fetch(t,{credentials:"same-origin"}),s=await WebAssembly.instantiateStreaming(r,n);return s}catch(o){err(`wasm streaming compile failed: ${o}`),err("falling back to ArrayBuffer instantiation")}return instantiateArrayBuffer(t,n)}C(instantiateAsync,"instantiateAsync");function getWasmImports(){return{env:wasmImports,wasi_snapshot_preview1:wasmImports,"GOT.mem":new Proxy(wasmImports,GOTHandler),"GOT.func":new Proxy(wasmImports,GOTHandler)}}C(getWasmImports,"getWasmImports");async function createWasm(){function e(o,a){wasmExports=o.exports,wasmExports=relocateExports(wasmExports,1024);var l=getDylinkMetadata(a);return l.neededDynlibs&&(dynamicLibraries=l.neededDynlibs.concat(dynamicLibraries)),mergeLibSymbols(wasmExports,"main"),LDSO.init(),loadDylibs(),__RELOC_FUNCS__.push(wasmExports.__wasm_apply_data_relocs),assignWasmExports(wasmExports),wasmExports}C(e,"receiveInstance");function t(o){return e(o.instance,o.module)}C(t,"receiveInstantiationResult");var n=getWasmImports();if(Module.instantiateWasm)return new Promise((o,a)=>{Module.instantiateWasm(n,(l,c)=>{o(e(l,c))})});wasmBinaryFile??=findWasmBinary();var r=await instantiateAsync(wasmBinary,wasmBinaryFile,n),s=t(r);return s}C(createWasm,"createWasm");class ExitStatus{static{C(this,"ExitStatus")}name="ExitStatus";constructor(t){this.message=`Program terminated with exit(${t})`,this.status=t}}var GOT={},currentModuleWeakSymbols=new Set([]),GOTHandler={get(e,t){var n=GOT[t];return n||(n=GOT[t]=new WebAssembly.Global({value:"i32",mutable:!0})),currentModuleWeakSymbols.has(t)||(n.required=!0),n}},LE_ATOMICS_NATIVE_BYTE_ORDER=[],LE_HEAP_LOAD_F32=C(e=>HEAP_DATA_VIEW.getFloat32(e,!0),"LE_HEAP_LOAD_F32"),LE_HEAP_LOAD_F64=C(e=>HEAP_DATA_VIEW.getFloat64(e,!0),"LE_HEAP_LOAD_F64"),LE_HEAP_LOAD_I16=C(e=>HEAP_DATA_VIEW.getInt16(e,!0),"LE_HEAP_LOAD_I16"),LE_HEAP_LOAD_I32=C(e=>HEAP_DATA_VIEW.getInt32(e,!0),"LE_HEAP_LOAD_I32"),LE_HEAP_LOAD_I64=C(e=>HEAP_DATA_VIEW.getBigInt64(e,!0),"LE_HEAP_LOAD_I64"),LE_HEAP_LOAD_U32=C(e=>HEAP_DATA_VIEW.getUint32(e,!0),"LE_HEAP_LOAD_U32"),LE_HEAP_STORE_F32=C((e,t)=>HEAP_DATA_VIEW.setFloat32(e,t,!0),"LE_HEAP_STORE_F32"),LE_HEAP_STORE_F64=C((e,t)=>HEAP_DATA_VIEW.setFloat64(e,t,!0),"LE_HEAP_STORE_F64"),LE_HEAP_STORE_I16=C((e,t)=>HEAP_DATA_VIEW.setInt16(e,t,!0),"LE_HEAP_STORE_I16"),LE_HEAP_STORE_I32=C((e,t)=>HEAP_DATA_VIEW.setInt32(e,t,!0),"LE_HEAP_STORE_I32"),LE_HEAP_STORE_I64=C((e,t)=>HEAP_DATA_VIEW.setBigInt64(e,t,!0),"LE_HEAP_STORE_I64"),LE_HEAP_STORE_U32=C((e,t)=>HEAP_DATA_VIEW.setUint32(e,t,!0),"LE_HEAP_STORE_U32"),callRuntimeCallbacks=C(e=>{for(;e.length>0;)e.shift()(Module)},"callRuntimeCallbacks"),onPostRuns=[],addOnPostRun=C(e=>onPostRuns.push(e),"addOnPostRun"),onPreRuns=[],addOnPreRun=C(e=>onPreRuns.push(e),"addOnPreRun"),UTF8Decoder=typeof TextDecoder<"u"?new TextDecoder:void 0,findStringEnd=C((e,t,n,r)=>{var s=t+n;if(r)return s;for(;e[t]&&!(t>=s);)++t;return t},"findStringEnd"),UTF8ArrayToString=C((e,t=0,n,r)=>{var s=findStringEnd(e,t,n,r);if(s-t>16&&e.buffer&&UTF8Decoder)return UTF8Decoder.decode(e.subarray(t,s));for(var o="";t>10,56320|d&1023)}}return o},"UTF8ArrayToString"),getDylinkMetadata=C(e=>{var t=0,n=0;function r(){return e[t++]}C(r,"getU8");function s(){for(var V=0,z=1;;){var P=e[t++];if(V+=(P&127)*z,z*=128,!(P&128))break}return V}C(s,"getLEB");function o(){var V=s();return t+=V,UTF8ArrayToString(e,t-V,V)}C(o,"getString");function a(){for(var V=s(),z=[];V--;)z.push(o());return z}C(a,"getStringList");function l(V,z){if(V)throw new Error(z)}if(C(l,"failIf"),e instanceof WebAssembly.Module){var c=WebAssembly.Module.customSections(e,"dylink.0");l(c.length===0,"need dylink section"),e=new Uint8Array(c[0]),n=e.length}else{var d=new Uint32Array(new Uint8Array(e.subarray(0,24)).buffer),f=d[0]==1836278016||d[0]==6386541;l(!f,"need to see wasm magic number"),l(e[8]!==0,"need the dylink section to be first"),t=9;var u=s();n=t+u;var m=o();l(m!=="dylink.0")}for(var p={neededDynlibs:[],tlsExports:new Set,weakImports:new Set,runtimePaths:[]},g=1,y=2,h=3,S=4,_=5,E=256,b=3,x=1;t>1)*2);case"i32":return LE_HEAP_LOAD_I32((e>>2)*4);case"i64":return LE_HEAP_LOAD_I64((e>>3)*8);case"float":return LE_HEAP_LOAD_F32((e>>2)*4);case"double":return LE_HEAP_LOAD_F64((e>>3)*8);case"*":return LE_HEAP_LOAD_U32((e>>2)*4);default:abort(`invalid type for getValue: ${t}`)}}C(getValue,"getValue");var newDSO=C((e,t,n)=>{var r={refcount:1/0,name:e,exports:n,global:!0};return LDSO.loadedLibsByName[e]=r,t!=null&&(LDSO.loadedLibsByHandle[t]=r),r},"newDSO"),LDSO={loadedLibsByName:{},loadedLibsByHandle:{},init(){newDSO("__main__",0,wasmImports)}},___heap_base=78240,alignMemory=C((e,t)=>Math.ceil(e/t)*t,"alignMemory"),getMemory=C(e=>{if(runtimeInitialized)return _calloc(e,1);var t=___heap_base,n=t+alignMemory(e,16);return ___heap_base=n,GOT.__heap_base.value=n,t},"getMemory"),isInternalSym=C(e=>["__cpp_exception","__c_longjmp","__wasm_apply_data_relocs","__dso_handle","__tls_size","__tls_align","__set_stack_limits","_emscripten_tls_init","__wasm_init_tls","__wasm_call_ctors","__start_em_asm","__stop_em_asm","__start_em_js","__stop_em_js"].includes(e)||e.startsWith("__em_js__"),"isInternalSym"),uleb128EncodeWithLen=C(e=>{let t=e.length;return[t%128|128,t>>7,...e]},"uleb128EncodeWithLen"),wasmTypeCodes={i:127,p:127,j:126,f:125,d:124,e:111},generateTypePack=C(e=>uleb128EncodeWithLen(Array.from(e,t=>{var n=wasmTypeCodes[t];return n})),"generateTypePack"),convertJsFunctionToWasm=C((e,t)=>{var n=Uint8Array.of(0,97,115,109,1,0,0,0,1,...uleb128EncodeWithLen([1,96,...generateTypePack(t.slice(1)),...generateTypePack(t[0]==="v"?"":t[0])]),2,7,1,1,101,1,102,0,0,7,5,1,1,102,0,0),r=new WebAssembly.Module(n),s=new WebAssembly.Instance(r,{e:{f:e}}),o=s.exports.f;return o},"convertJsFunctionToWasm"),wasmTableMirror=[],wasmTable=new WebAssembly.Table({initial:31,element:"anyfunc"}),getWasmTableEntry=C(e=>{var t=wasmTableMirror[e];return t||(wasmTableMirror[e]=t=wasmTable.get(e)),t},"getWasmTableEntry"),updateTableMap=C((e,t)=>{if(functionsInTableMap)for(var n=e;n(functionsInTableMap||(functionsInTableMap=new WeakMap,updateTableMap(0,wasmTable.length)),functionsInTableMap.get(e)||0),"getFunctionAddress"),freeTableIndexes=[],getEmptyTableSlot=C(()=>freeTableIndexes.length?freeTableIndexes.pop():wasmTable.grow(1),"getEmptyTableSlot"),setWasmTableEntry=C((e,t)=>{wasmTable.set(e,t),wasmTableMirror[e]=wasmTable.get(e)},"setWasmTableEntry"),addFunction=C((e,t)=>{var n=getFunctionAddress(e);if(n)return n;var r=getEmptyTableSlot();try{setWasmTableEntry(r,e)}catch(o){if(!(o instanceof TypeError))throw o;var s=convertJsFunctionToWasm(e,t);setWasmTableEntry(r,s)}return functionsInTableMap.set(e,r),r},"addFunction"),updateGOT=C((e,t)=>{for(var n in e)if(!isInternalSym(n)){var r=e[n];GOT[n]||=new WebAssembly.Global({value:"i32",mutable:!0}),(t||GOT[n].value==0)&&(typeof r=="function"?GOT[n].value=addFunction(r):typeof r=="number"?GOT[n].value=r:err(`unhandled export type for '${n}': ${typeof r}`))}},"updateGOT"),relocateExports=C((e,t,n)=>{var r={};for(var s in e){var o=e[s];typeof o=="object"&&(o=o.value),typeof o=="number"&&(o+=t),r[s]=o}return updateGOT(r,n),r},"relocateExports"),isSymbolDefined=C(e=>{var t=wasmImports[e];return!(!t||t.stub)},"isSymbolDefined"),dynCall=C((e,t,n=[],r=!1)=>{var s=getWasmTableEntry(t),o=s(...n);function a(l){return l}return C(a,"convert"),o},"dynCall"),stackSave=C(()=>_emscripten_stack_get_current(),"stackSave"),stackRestore=C(e=>__emscripten_stack_restore(e),"stackRestore"),createInvokeFunction=C(e=>(t,...n)=>{var r=stackSave();try{return dynCall(e,t,n)}catch(s){if(stackRestore(r),s!==s+0)throw s;if(_setThrew(1,0),e[0]=="j")return 0n}},"createInvokeFunction"),resolveGlobalSymbol=C((e,t=!1)=>{var n;return isSymbolDefined(e)?n=wasmImports[e]:e.startsWith("invoke_")&&(n=wasmImports[e]=createInvokeFunction(e.split("_")[1])),{sym:n,name:e}},"resolveGlobalSymbol"),onPostCtors=[],addOnPostCtor=C(e=>onPostCtors.push(e),"addOnPostCtor"),UTF8ToString=C((e,t,n)=>e?UTF8ArrayToString(HEAPU8,e,t,n):"","UTF8ToString"),loadWebAssemblyModule=C((binary,flags,libName,localScope,handle)=>{var metadata=getDylinkMetadata(binary);function loadModule(){var memAlign=Math.pow(2,metadata.memoryAlign),memoryBase=metadata.memorySize?alignMemory(getMemory(metadata.memorySize+memAlign),memAlign):0,tableBase=metadata.tableSize?wasmTable.length:0;handle&&(HEAP8[handle+8]=1,LE_HEAP_STORE_U32((handle+12>>2)*4,memoryBase),LE_HEAP_STORE_I32((handle+16>>2)*4,metadata.memorySize),LE_HEAP_STORE_U32((handle+20>>2)*4,tableBase),LE_HEAP_STORE_I32((handle+24>>2)*4,metadata.tableSize)),metadata.tableSize&&wasmTable.grow(metadata.tableSize);var moduleExports;function resolveSymbol(e){var t=resolveGlobalSymbol(e).sym;return!t&&localScope&&(t=localScope[e]),t||(t=moduleExports[e]),t}C(resolveSymbol,"resolveSymbol");var proxyHandler={get(e,t){switch(t){case"__memory_base":return memoryBase;case"__table_base":return tableBase}if(t in wasmImports&&!wasmImports[t].stub){var n=wasmImports[t];return n}if(!(t in e)){var r;e[t]=(...s)=>(r||=resolveSymbol(t),r(...s))}return e[t]}},proxy=new Proxy({},proxyHandler);currentModuleWeakSymbols=metadata.weakImports;var info={"GOT.mem":new Proxy({},GOTHandler),"GOT.func":new Proxy({},GOTHandler),env:proxy,wasi_snapshot_preview1:proxy};function postInstantiation(module,instance){updateTableMap(tableBase,metadata.tableSize),moduleExports=relocateExports(instance.exports,memoryBase),flags.allowUndefined||reportUndefinedSymbols();function addEmAsm(addr,body){for(var args=[],arity=0;arity<16&&body.indexOf("$"+arity)!=-1;arity++)args.push("$"+arity);args=args.join(",");var func=`(${args}) => { ${body} };`;ASM_CONSTS[start]=eval(func)}if(C(addEmAsm,"addEmAsm"),"__start_em_asm"in moduleExports)for(var start=moduleExports.__start_em_asm,stop=moduleExports.__stop_em_asm;start ${body};`;moduleExports[name]=eval(func)}C(addEmJs,"addEmJs");for(var name in moduleExports)if(name.startsWith("__em_js__")){var start=moduleExports[name],jsString=UTF8ToString(start),parts=jsString.split("<::>");addEmJs(name.replace("__em_js__",""),parts[0],parts[1]),delete moduleExports[name]}var applyRelocs=moduleExports.__wasm_apply_data_relocs;applyRelocs&&(runtimeInitialized?applyRelocs():__RELOC_FUNCS__.push(applyRelocs));var init=moduleExports.__wasm_call_ctors;return init&&(runtimeInitialized?init():addOnPostCtor(init)),moduleExports}if(C(postInstantiation,"postInstantiation"),flags.loadAsync)return(async()=>{var e;return binary instanceof WebAssembly.Module?e=new WebAssembly.Instance(binary,info):{module:binary,instance:e}=await WebAssembly.instantiate(binary,info),postInstantiation(binary,e)})();var module=binary instanceof WebAssembly.Module?binary:new WebAssembly.Module(binary),instance=new WebAssembly.Instance(module,info);return postInstantiation(module,instance)}return C(loadModule,"loadModule"),flags={...flags,rpath:{parentLibPath:libName,paths:metadata.runtimePaths}},flags.loadAsync?metadata.neededDynlibs.reduce((e,t)=>e.then(()=>loadDynamicLibrary(t,flags,localScope)),Promise.resolve()).then(loadModule):(metadata.neededDynlibs.forEach(e=>loadDynamicLibrary(e,flags,localScope)),loadModule())},"loadWebAssemblyModule"),mergeLibSymbols=C((e,t)=>{for(var[n,r]of Object.entries(e)){let s=C(a=>{isSymbolDefined(a)||(wasmImports[a]=r)},"setImport");s(n);let o="__main_argc_argv";n=="main"&&s(o),n==o&&s("main")}},"mergeLibSymbols"),asyncLoad=C(async e=>{var t=await readAsync(e);return new Uint8Array(t)},"asyncLoad");function loadDynamicLibrary(e,t={global:!0,nodelete:!0},n,r){var s=LDSO.loadedLibsByName[e];if(s)return t.global?s.global||(s.global=!0,mergeLibSymbols(s.exports,e)):n&&Object.assign(n,s.exports),t.nodelete&&s.refcount!==1/0&&(s.refcount=1/0),s.refcount++,r&&(LDSO.loadedLibsByHandle[r]=s),t.loadAsync?Promise.resolve(!0):!0;s=newDSO(e,r,"loading"),s.refcount=t.nodelete?1/0:1,s.global=t.global;function o(){if(r){var c=LE_HEAP_LOAD_U32((r+28>>2)*4),d=LE_HEAP_LOAD_U32((r+32>>2)*4);if(c&&d){var f=HEAP8.slice(c,c+d);return t.loadAsync?Promise.resolve(f):f}}var u=locateFile(e);if(t.loadAsync)return asyncLoad(u);if(!readBinary)throw new Error(`${u}: file not found, and synchronous loading of external files is not available`);return readBinary(u)}C(o,"loadLibData");function a(){return t.loadAsync?o().then(c=>loadWebAssemblyModule(c,t,e,n,r)):loadWebAssemblyModule(o(),t,e,n,r)}C(a,"getExports");function l(c){s.global?mergeLibSymbols(c,e):n&&Object.assign(n,c),s.exports=c}return C(l,"moduleLoaded"),t.loadAsync?a().then(c=>(l(c),!0)):(l(a()),!0)}C(loadDynamicLibrary,"loadDynamicLibrary");var reportUndefinedSymbols=C(()=>{for(var[e,t]of Object.entries(GOT))if(t.value==0){var n=resolveGlobalSymbol(e,!0).sym;if(!n&&!t.required)continue;if(typeof n=="function")t.value=addFunction(n,n.sig);else if(typeof n=="number")t.value=n;else throw new Error(`bad export type for '${e}': ${typeof n}`)}},"reportUndefinedSymbols"),runDependencies=0,dependenciesFulfilled=null,removeRunDependency=C(e=>{if(runDependencies--,Module.monitorRunDependencies?.(runDependencies),runDependencies==0&&dependenciesFulfilled){var t=dependenciesFulfilled;dependenciesFulfilled=null,t()}},"removeRunDependency"),addRunDependency=C(e=>{runDependencies++,Module.monitorRunDependencies?.(runDependencies)},"addRunDependency"),loadDylibs=C(async()=>{if(!dynamicLibraries.length){reportUndefinedSymbols();return}addRunDependency("loadDylibs");for(var e of dynamicLibraries)await loadDynamicLibrary(e,{loadAsync:!0,global:!0,nodelete:!0,allowUndefined:!0});reportUndefinedSymbols(),removeRunDependency("loadDylibs")},"loadDylibs"),noExitRuntime=!0;function setValue(e,t,n="i8"){switch(n.endsWith("*")&&(n="*"),n){case"i1":HEAP8[e]=t;break;case"i8":HEAP8[e]=t;break;case"i16":LE_HEAP_STORE_I16((e>>1)*2,t);break;case"i32":LE_HEAP_STORE_I32((e>>2)*4,t);break;case"i64":LE_HEAP_STORE_I64((e>>3)*8,BigInt(t));break;case"float":LE_HEAP_STORE_F32((e>>2)*4,t);break;case"double":LE_HEAP_STORE_F64((e>>3)*8,t);break;case"*":LE_HEAP_STORE_U32((e>>2)*4,t);break;default:abort(`invalid type for setValue: ${n}`)}}C(setValue,"setValue");var ___memory_base=new WebAssembly.Global({value:"i32",mutable:!1},1024),___stack_high=78240,___stack_low=12704,___stack_pointer=new WebAssembly.Global({value:"i32",mutable:!0},78240),___table_base=new WebAssembly.Global({value:"i32",mutable:!1},1),__abort_js=C(()=>abort(""),"__abort_js");__abort_js.sig="v";var getHeapMax=C(()=>2147483648,"getHeapMax"),growMemory=C(e=>{var t=wasmMemory.buffer.byteLength,n=(e-t+65535)/65536|0;try{return wasmMemory.grow(n),updateMemoryViews(),1}catch{}},"growMemory"),_emscripten_resize_heap=C(e=>{var t=HEAPU8.length;e>>>=0;var n=getHeapMax();if(e>n)return!1;for(var r=1;r<=4;r*=2){var s=t*(1+.2/r);s=Math.min(s,e+100663296);var o=Math.min(n,alignMemory(Math.max(e,s),65536)),a=growMemory(o);if(a)return!0}return!1},"_emscripten_resize_heap");_emscripten_resize_heap.sig="ip";var _fd_close=C(e=>52,"_fd_close");_fd_close.sig="ii";var INT53_MAX=9007199254740992,INT53_MIN=-9007199254740992,bigintToI53Checked=C(e=>eINT53_MAX?NaN:Number(e),"bigintToI53Checked");function _fd_seek(e,t,n,r){return t=bigintToI53Checked(t),70}C(_fd_seek,"_fd_seek"),_fd_seek.sig="iijip";var printCharBuffers=[null,[],[]],printChar=C((e,t)=>{var n=printCharBuffers[e];t===0||t===10?((e===1?out:err)(UTF8ArrayToString(n)),n.length=0):n.push(t)},"printChar"),_fd_write=C((e,t,n,r)=>{for(var s=0,o=0;o>2)*4),l=LE_HEAP_LOAD_U32((t+4>>2)*4);t+=8;for(var c=0;c>2)*4,s),0},"_fd_write");_fd_write.sig="iippp";function _tree_sitter_log_callback(e,t){if(Module.currentLogCallback){let n=UTF8ToString(t);Module.currentLogCallback(n,e!==0)}}C(_tree_sitter_log_callback,"_tree_sitter_log_callback");function _tree_sitter_parse_callback(e,t,n,r,s){let a=Module.currentParseCallback(t,{row:n,column:r});typeof a=="string"?(setValue(s,a.length,"i32"),stringToUTF16(a,e,10240)):setValue(s,0,"i32")}C(_tree_sitter_parse_callback,"_tree_sitter_parse_callback");function _tree_sitter_progress_callback(e,t){return Module.currentProgressCallback?Module.currentProgressCallback({currentOffset:e,hasError:t}):!1}C(_tree_sitter_progress_callback,"_tree_sitter_progress_callback");function _tree_sitter_query_progress_callback(e){return Module.currentQueryProgressCallback?Module.currentQueryProgressCallback({currentOffset:e}):!1}C(_tree_sitter_query_progress_callback,"_tree_sitter_query_progress_callback");var runtimeKeepaliveCounter=0,keepRuntimeAlive=C(()=>noExitRuntime||runtimeKeepaliveCounter>0,"keepRuntimeAlive"),_proc_exit=C(e=>{EXITSTATUS=e,keepRuntimeAlive()||(Module.onExit?.(e),ABORT=!0),quit_(e,new ExitStatus(e))},"_proc_exit");_proc_exit.sig="vi";var exitJS=C((e,t)=>{EXITSTATUS=e,_proc_exit(e)},"exitJS"),handleException=C(e=>{if(e instanceof ExitStatus||e=="unwind")return EXITSTATUS;quit_(1,e)},"handleException"),lengthBytesUTF8=C(e=>{for(var t=0,n=0;n=55296&&r<=57343?(t+=4,++n):t+=3}return t},"lengthBytesUTF8"),stringToUTF8Array=C((e,t,n,r)=>{if(!(r>0))return 0;for(var s=n,o=n+r-1,a=0;a=o)break;t[n++]=l}else if(l<=2047){if(n+1>=o)break;t[n++]=192|l>>6,t[n++]=128|l&63}else if(l<=65535){if(n+2>=o)break;t[n++]=224|l>>12,t[n++]=128|l>>6&63,t[n++]=128|l&63}else{if(n+3>=o)break;t[n++]=240|l>>18,t[n++]=128|l>>12&63,t[n++]=128|l>>6&63,t[n++]=128|l&63,a++}}return t[n]=0,n-s},"stringToUTF8Array"),stringToUTF8=C((e,t,n)=>stringToUTF8Array(e,HEAPU8,t,n),"stringToUTF8"),stackAlloc=C(e=>__emscripten_stack_alloc(e),"stackAlloc"),stringToUTF8OnStack=C(e=>{var t=lengthBytesUTF8(e)+1,n=stackAlloc(t);return stringToUTF8(e,n,t),n},"stringToUTF8OnStack"),AsciiToString=C(e=>{for(var t="";;){var n=HEAPU8[e++];if(!n)return t;t+=String.fromCharCode(n)}},"AsciiToString"),stringToUTF16=C((e,t,n)=>{if(n??=2147483647,n<2)return 0;n-=2;for(var r=t,s=n>1)*2,a),t+=2}return LE_HEAP_STORE_I16((t>>1)*2,0),t-r},"stringToUTF16");LE_ATOMICS_NATIVE_BYTE_ORDER=new Int8Array(new Int16Array([1]).buffer)[0]===1?[(e=>e),(e=>e),void 0,(e=>e)]:[(e=>e),(e=>((e&65280)<<8|(e&255)<<24)>>16),void 0,(e=>e>>24&255|e>>8&65280|(e&65280)<<8|(e&255)<<24)];function LE_HEAP_UPDATE(){HEAPU16.unsigned=(e=>e&65535),HEAPU32.unsigned=(e=>e>>>0)}if(C(LE_HEAP_UPDATE,"LE_HEAP_UPDATE"),initMemory(),Module.noExitRuntime&&(noExitRuntime=Module.noExitRuntime),Module.print&&(out=Module.print),Module.printErr&&(err=Module.printErr),Module.dynamicLibraries&&(dynamicLibraries=Module.dynamicLibraries),Module.wasmBinary&&(wasmBinary=Module.wasmBinary),Module.arguments&&(arguments_=Module.arguments),Module.thisProgram&&(thisProgram=Module.thisProgram),Module.preInit)for(typeof Module.preInit=="function"&&(Module.preInit=[Module.preInit]);Module.preInit.length>0;)Module.preInit.shift()();Module.setValue=setValue,Module.getValue=getValue,Module.UTF8ToString=UTF8ToString,Module.stringToUTF8=stringToUTF8,Module.lengthBytesUTF8=lengthBytesUTF8,Module.AsciiToString=AsciiToString,Module.stringToUTF16=stringToUTF16,Module.loadWebAssemblyModule=loadWebAssemblyModule,Module.LE_HEAP_STORE_I64=LE_HEAP_STORE_I64;var ASM_CONSTS={},_malloc,_calloc,_realloc,_free,_ts_range_edit,_memcmp,_ts_language_symbol_count,_ts_language_state_count,_ts_language_abi_version,_ts_language_name,_ts_language_field_count,_ts_language_next_state,_ts_language_symbol_name,_ts_language_symbol_for_name,_strncmp,_ts_language_symbol_type,_ts_language_field_name_for_id,_ts_lookahead_iterator_new,_ts_lookahead_iterator_delete,_ts_lookahead_iterator_reset_state,_ts_lookahead_iterator_reset,_ts_lookahead_iterator_next,_ts_lookahead_iterator_current_symbol,_ts_point_edit,_ts_parser_delete,_ts_parser_reset,_ts_parser_set_language,_ts_parser_set_included_ranges,_ts_query_new,_ts_query_delete,_iswspace,_iswalnum,_ts_query_pattern_count,_ts_query_capture_count,_ts_query_string_count,_ts_query_capture_name_for_id,_ts_query_capture_quantifier_for_id,_ts_query_string_value_for_id,_ts_query_predicates_for_pattern,_ts_query_start_byte_for_pattern,_ts_query_end_byte_for_pattern,_ts_query_is_pattern_rooted,_ts_query_is_pattern_non_local,_ts_query_is_pattern_guaranteed_at_step,_ts_query_disable_capture,_ts_query_disable_pattern,_ts_tree_copy,_ts_tree_delete,_ts_init,_ts_parser_new_wasm,_ts_parser_enable_logger_wasm,_ts_parser_parse_wasm,_ts_parser_included_ranges_wasm,_ts_language_type_is_named_wasm,_ts_language_type_is_visible_wasm,_ts_language_metadata_wasm,_ts_language_supertypes_wasm,_ts_language_subtypes_wasm,_ts_tree_root_node_wasm,_ts_tree_root_node_with_offset_wasm,_ts_tree_edit_wasm,_ts_tree_included_ranges_wasm,_ts_tree_get_changed_ranges_wasm,_ts_tree_cursor_new_wasm,_ts_tree_cursor_copy_wasm,_ts_tree_cursor_delete_wasm,_ts_tree_cursor_reset_wasm,_ts_tree_cursor_reset_to_wasm,_ts_tree_cursor_goto_first_child_wasm,_ts_tree_cursor_goto_last_child_wasm,_ts_tree_cursor_goto_first_child_for_index_wasm,_ts_tree_cursor_goto_first_child_for_position_wasm,_ts_tree_cursor_goto_next_sibling_wasm,_ts_tree_cursor_goto_previous_sibling_wasm,_ts_tree_cursor_goto_descendant_wasm,_ts_tree_cursor_goto_parent_wasm,_ts_tree_cursor_current_node_type_id_wasm,_ts_tree_cursor_current_node_state_id_wasm,_ts_tree_cursor_current_node_is_named_wasm,_ts_tree_cursor_current_node_is_missing_wasm,_ts_tree_cursor_current_node_id_wasm,_ts_tree_cursor_start_position_wasm,_ts_tree_cursor_end_position_wasm,_ts_tree_cursor_start_index_wasm,_ts_tree_cursor_end_index_wasm,_ts_tree_cursor_current_field_id_wasm,_ts_tree_cursor_current_depth_wasm,_ts_tree_cursor_current_descendant_index_wasm,_ts_tree_cursor_current_node_wasm,_ts_node_symbol_wasm,_ts_node_field_name_for_child_wasm,_ts_node_field_name_for_named_child_wasm,_ts_node_children_by_field_id_wasm,_ts_node_first_child_for_byte_wasm,_ts_node_first_named_child_for_byte_wasm,_ts_node_grammar_symbol_wasm,_ts_node_child_count_wasm,_ts_node_named_child_count_wasm,_ts_node_child_wasm,_ts_node_named_child_wasm,_ts_node_child_by_field_id_wasm,_ts_node_next_sibling_wasm,_ts_node_prev_sibling_wasm,_ts_node_next_named_sibling_wasm,_ts_node_prev_named_sibling_wasm,_ts_node_descendant_count_wasm,_ts_node_parent_wasm,_ts_node_child_with_descendant_wasm,_ts_node_descendant_for_index_wasm,_ts_node_named_descendant_for_index_wasm,_ts_node_descendant_for_position_wasm,_ts_node_named_descendant_for_position_wasm,_ts_node_start_point_wasm,_ts_node_end_point_wasm,_ts_node_start_index_wasm,_ts_node_end_index_wasm,_ts_node_to_string_wasm,_ts_node_children_wasm,_ts_node_named_children_wasm,_ts_node_descendants_of_type_wasm,_ts_node_is_named_wasm,_ts_node_has_changes_wasm,_ts_node_has_error_wasm,_ts_node_is_error_wasm,_ts_node_is_missing_wasm,_ts_node_is_extra_wasm,_ts_node_parse_state_wasm,_ts_node_next_parse_state_wasm,_ts_query_matches_wasm,_ts_query_captures_wasm,_memset,_memcpy,_memmove,_iswalpha,_iswblank,_iswdigit,_iswlower,_iswupper,_iswxdigit,_memchr,_strlen,_strcmp,_strncat,_strncpy,_towlower,_towupper,_setThrew,__emscripten_stack_restore,__emscripten_stack_alloc,_emscripten_stack_get_current,___wasm_apply_data_relocs;function assignWasmExports(e){Module._malloc=_malloc=e.malloc,Module._calloc=_calloc=e.calloc,Module._realloc=_realloc=e.realloc,Module._free=_free=e.free,Module._ts_range_edit=_ts_range_edit=e.ts_range_edit,Module._memcmp=_memcmp=e.memcmp,Module._ts_language_symbol_count=_ts_language_symbol_count=e.ts_language_symbol_count,Module._ts_language_state_count=_ts_language_state_count=e.ts_language_state_count,Module._ts_language_abi_version=_ts_language_abi_version=e.ts_language_abi_version,Module._ts_language_name=_ts_language_name=e.ts_language_name,Module._ts_language_field_count=_ts_language_field_count=e.ts_language_field_count,Module._ts_language_next_state=_ts_language_next_state=e.ts_language_next_state,Module._ts_language_symbol_name=_ts_language_symbol_name=e.ts_language_symbol_name,Module._ts_language_symbol_for_name=_ts_language_symbol_for_name=e.ts_language_symbol_for_name,Module._strncmp=_strncmp=e.strncmp,Module._ts_language_symbol_type=_ts_language_symbol_type=e.ts_language_symbol_type,Module._ts_language_field_name_for_id=_ts_language_field_name_for_id=e.ts_language_field_name_for_id,Module._ts_lookahead_iterator_new=_ts_lookahead_iterator_new=e.ts_lookahead_iterator_new,Module._ts_lookahead_iterator_delete=_ts_lookahead_iterator_delete=e.ts_lookahead_iterator_delete,Module._ts_lookahead_iterator_reset_state=_ts_lookahead_iterator_reset_state=e.ts_lookahead_iterator_reset_state,Module._ts_lookahead_iterator_reset=_ts_lookahead_iterator_reset=e.ts_lookahead_iterator_reset,Module._ts_lookahead_iterator_next=_ts_lookahead_iterator_next=e.ts_lookahead_iterator_next,Module._ts_lookahead_iterator_current_symbol=_ts_lookahead_iterator_current_symbol=e.ts_lookahead_iterator_current_symbol,Module._ts_point_edit=_ts_point_edit=e.ts_point_edit,Module._ts_parser_delete=_ts_parser_delete=e.ts_parser_delete,Module._ts_parser_reset=_ts_parser_reset=e.ts_parser_reset,Module._ts_parser_set_language=_ts_parser_set_language=e.ts_parser_set_language,Module._ts_parser_set_included_ranges=_ts_parser_set_included_ranges=e.ts_parser_set_included_ranges,Module._ts_query_new=_ts_query_new=e.ts_query_new,Module._ts_query_delete=_ts_query_delete=e.ts_query_delete,Module._iswspace=_iswspace=e.iswspace,Module._iswalnum=_iswalnum=e.iswalnum,Module._ts_query_pattern_count=_ts_query_pattern_count=e.ts_query_pattern_count,Module._ts_query_capture_count=_ts_query_capture_count=e.ts_query_capture_count,Module._ts_query_string_count=_ts_query_string_count=e.ts_query_string_count,Module._ts_query_capture_name_for_id=_ts_query_capture_name_for_id=e.ts_query_capture_name_for_id,Module._ts_query_capture_quantifier_for_id=_ts_query_capture_quantifier_for_id=e.ts_query_capture_quantifier_for_id,Module._ts_query_string_value_for_id=_ts_query_string_value_for_id=e.ts_query_string_value_for_id,Module._ts_query_predicates_for_pattern=_ts_query_predicates_for_pattern=e.ts_query_predicates_for_pattern,Module._ts_query_start_byte_for_pattern=_ts_query_start_byte_for_pattern=e.ts_query_start_byte_for_pattern,Module._ts_query_end_byte_for_pattern=_ts_query_end_byte_for_pattern=e.ts_query_end_byte_for_pattern,Module._ts_query_is_pattern_rooted=_ts_query_is_pattern_rooted=e.ts_query_is_pattern_rooted,Module._ts_query_is_pattern_non_local=_ts_query_is_pattern_non_local=e.ts_query_is_pattern_non_local,Module._ts_query_is_pattern_guaranteed_at_step=_ts_query_is_pattern_guaranteed_at_step=e.ts_query_is_pattern_guaranteed_at_step,Module._ts_query_disable_capture=_ts_query_disable_capture=e.ts_query_disable_capture,Module._ts_query_disable_pattern=_ts_query_disable_pattern=e.ts_query_disable_pattern,Module._ts_tree_copy=_ts_tree_copy=e.ts_tree_copy,Module._ts_tree_delete=_ts_tree_delete=e.ts_tree_delete,Module._ts_init=_ts_init=e.ts_init,Module._ts_parser_new_wasm=_ts_parser_new_wasm=e.ts_parser_new_wasm,Module._ts_parser_enable_logger_wasm=_ts_parser_enable_logger_wasm=e.ts_parser_enable_logger_wasm,Module._ts_parser_parse_wasm=_ts_parser_parse_wasm=e.ts_parser_parse_wasm,Module._ts_parser_included_ranges_wasm=_ts_parser_included_ranges_wasm=e.ts_parser_included_ranges_wasm,Module._ts_language_type_is_named_wasm=_ts_language_type_is_named_wasm=e.ts_language_type_is_named_wasm,Module._ts_language_type_is_visible_wasm=_ts_language_type_is_visible_wasm=e.ts_language_type_is_visible_wasm,Module._ts_language_metadata_wasm=_ts_language_metadata_wasm=e.ts_language_metadata_wasm,Module._ts_language_supertypes_wasm=_ts_language_supertypes_wasm=e.ts_language_supertypes_wasm,Module._ts_language_subtypes_wasm=_ts_language_subtypes_wasm=e.ts_language_subtypes_wasm,Module._ts_tree_root_node_wasm=_ts_tree_root_node_wasm=e.ts_tree_root_node_wasm,Module._ts_tree_root_node_with_offset_wasm=_ts_tree_root_node_with_offset_wasm=e.ts_tree_root_node_with_offset_wasm,Module._ts_tree_edit_wasm=_ts_tree_edit_wasm=e.ts_tree_edit_wasm,Module._ts_tree_included_ranges_wasm=_ts_tree_included_ranges_wasm=e.ts_tree_included_ranges_wasm,Module._ts_tree_get_changed_ranges_wasm=_ts_tree_get_changed_ranges_wasm=e.ts_tree_get_changed_ranges_wasm,Module._ts_tree_cursor_new_wasm=_ts_tree_cursor_new_wasm=e.ts_tree_cursor_new_wasm,Module._ts_tree_cursor_copy_wasm=_ts_tree_cursor_copy_wasm=e.ts_tree_cursor_copy_wasm,Module._ts_tree_cursor_delete_wasm=_ts_tree_cursor_delete_wasm=e.ts_tree_cursor_delete_wasm,Module._ts_tree_cursor_reset_wasm=_ts_tree_cursor_reset_wasm=e.ts_tree_cursor_reset_wasm,Module._ts_tree_cursor_reset_to_wasm=_ts_tree_cursor_reset_to_wasm=e.ts_tree_cursor_reset_to_wasm,Module._ts_tree_cursor_goto_first_child_wasm=_ts_tree_cursor_goto_first_child_wasm=e.ts_tree_cursor_goto_first_child_wasm,Module._ts_tree_cursor_goto_last_child_wasm=_ts_tree_cursor_goto_last_child_wasm=e.ts_tree_cursor_goto_last_child_wasm,Module._ts_tree_cursor_goto_first_child_for_index_wasm=_ts_tree_cursor_goto_first_child_for_index_wasm=e.ts_tree_cursor_goto_first_child_for_index_wasm,Module._ts_tree_cursor_goto_first_child_for_position_wasm=_ts_tree_cursor_goto_first_child_for_position_wasm=e.ts_tree_cursor_goto_first_child_for_position_wasm,Module._ts_tree_cursor_goto_next_sibling_wasm=_ts_tree_cursor_goto_next_sibling_wasm=e.ts_tree_cursor_goto_next_sibling_wasm,Module._ts_tree_cursor_goto_previous_sibling_wasm=_ts_tree_cursor_goto_previous_sibling_wasm=e.ts_tree_cursor_goto_previous_sibling_wasm,Module._ts_tree_cursor_goto_descendant_wasm=_ts_tree_cursor_goto_descendant_wasm=e.ts_tree_cursor_goto_descendant_wasm,Module._ts_tree_cursor_goto_parent_wasm=_ts_tree_cursor_goto_parent_wasm=e.ts_tree_cursor_goto_parent_wasm,Module._ts_tree_cursor_current_node_type_id_wasm=_ts_tree_cursor_current_node_type_id_wasm=e.ts_tree_cursor_current_node_type_id_wasm,Module._ts_tree_cursor_current_node_state_id_wasm=_ts_tree_cursor_current_node_state_id_wasm=e.ts_tree_cursor_current_node_state_id_wasm,Module._ts_tree_cursor_current_node_is_named_wasm=_ts_tree_cursor_current_node_is_named_wasm=e.ts_tree_cursor_current_node_is_named_wasm,Module._ts_tree_cursor_current_node_is_missing_wasm=_ts_tree_cursor_current_node_is_missing_wasm=e.ts_tree_cursor_current_node_is_missing_wasm,Module._ts_tree_cursor_current_node_id_wasm=_ts_tree_cursor_current_node_id_wasm=e.ts_tree_cursor_current_node_id_wasm,Module._ts_tree_cursor_start_position_wasm=_ts_tree_cursor_start_position_wasm=e.ts_tree_cursor_start_position_wasm,Module._ts_tree_cursor_end_position_wasm=_ts_tree_cursor_end_position_wasm=e.ts_tree_cursor_end_position_wasm,Module._ts_tree_cursor_start_index_wasm=_ts_tree_cursor_start_index_wasm=e.ts_tree_cursor_start_index_wasm,Module._ts_tree_cursor_end_index_wasm=_ts_tree_cursor_end_index_wasm=e.ts_tree_cursor_end_index_wasm,Module._ts_tree_cursor_current_field_id_wasm=_ts_tree_cursor_current_field_id_wasm=e.ts_tree_cursor_current_field_id_wasm,Module._ts_tree_cursor_current_depth_wasm=_ts_tree_cursor_current_depth_wasm=e.ts_tree_cursor_current_depth_wasm,Module._ts_tree_cursor_current_descendant_index_wasm=_ts_tree_cursor_current_descendant_index_wasm=e.ts_tree_cursor_current_descendant_index_wasm,Module._ts_tree_cursor_current_node_wasm=_ts_tree_cursor_current_node_wasm=e.ts_tree_cursor_current_node_wasm,Module._ts_node_symbol_wasm=_ts_node_symbol_wasm=e.ts_node_symbol_wasm,Module._ts_node_field_name_for_child_wasm=_ts_node_field_name_for_child_wasm=e.ts_node_field_name_for_child_wasm,Module._ts_node_field_name_for_named_child_wasm=_ts_node_field_name_for_named_child_wasm=e.ts_node_field_name_for_named_child_wasm,Module._ts_node_children_by_field_id_wasm=_ts_node_children_by_field_id_wasm=e.ts_node_children_by_field_id_wasm,Module._ts_node_first_child_for_byte_wasm=_ts_node_first_child_for_byte_wasm=e.ts_node_first_child_for_byte_wasm,Module._ts_node_first_named_child_for_byte_wasm=_ts_node_first_named_child_for_byte_wasm=e.ts_node_first_named_child_for_byte_wasm,Module._ts_node_grammar_symbol_wasm=_ts_node_grammar_symbol_wasm=e.ts_node_grammar_symbol_wasm,Module._ts_node_child_count_wasm=_ts_node_child_count_wasm=e.ts_node_child_count_wasm,Module._ts_node_named_child_count_wasm=_ts_node_named_child_count_wasm=e.ts_node_named_child_count_wasm,Module._ts_node_child_wasm=_ts_node_child_wasm=e.ts_node_child_wasm,Module._ts_node_named_child_wasm=_ts_node_named_child_wasm=e.ts_node_named_child_wasm,Module._ts_node_child_by_field_id_wasm=_ts_node_child_by_field_id_wasm=e.ts_node_child_by_field_id_wasm,Module._ts_node_next_sibling_wasm=_ts_node_next_sibling_wasm=e.ts_node_next_sibling_wasm,Module._ts_node_prev_sibling_wasm=_ts_node_prev_sibling_wasm=e.ts_node_prev_sibling_wasm,Module._ts_node_next_named_sibling_wasm=_ts_node_next_named_sibling_wasm=e.ts_node_next_named_sibling_wasm,Module._ts_node_prev_named_sibling_wasm=_ts_node_prev_named_sibling_wasm=e.ts_node_prev_named_sibling_wasm,Module._ts_node_descendant_count_wasm=_ts_node_descendant_count_wasm=e.ts_node_descendant_count_wasm,Module._ts_node_parent_wasm=_ts_node_parent_wasm=e.ts_node_parent_wasm,Module._ts_node_child_with_descendant_wasm=_ts_node_child_with_descendant_wasm=e.ts_node_child_with_descendant_wasm,Module._ts_node_descendant_for_index_wasm=_ts_node_descendant_for_index_wasm=e.ts_node_descendant_for_index_wasm,Module._ts_node_named_descendant_for_index_wasm=_ts_node_named_descendant_for_index_wasm=e.ts_node_named_descendant_for_index_wasm,Module._ts_node_descendant_for_position_wasm=_ts_node_descendant_for_position_wasm=e.ts_node_descendant_for_position_wasm,Module._ts_node_named_descendant_for_position_wasm=_ts_node_named_descendant_for_position_wasm=e.ts_node_named_descendant_for_position_wasm,Module._ts_node_start_point_wasm=_ts_node_start_point_wasm=e.ts_node_start_point_wasm,Module._ts_node_end_point_wasm=_ts_node_end_point_wasm=e.ts_node_end_point_wasm,Module._ts_node_start_index_wasm=_ts_node_start_index_wasm=e.ts_node_start_index_wasm,Module._ts_node_end_index_wasm=_ts_node_end_index_wasm=e.ts_node_end_index_wasm,Module._ts_node_to_string_wasm=_ts_node_to_string_wasm=e.ts_node_to_string_wasm,Module._ts_node_children_wasm=_ts_node_children_wasm=e.ts_node_children_wasm,Module._ts_node_named_children_wasm=_ts_node_named_children_wasm=e.ts_node_named_children_wasm,Module._ts_node_descendants_of_type_wasm=_ts_node_descendants_of_type_wasm=e.ts_node_descendants_of_type_wasm,Module._ts_node_is_named_wasm=_ts_node_is_named_wasm=e.ts_node_is_named_wasm,Module._ts_node_has_changes_wasm=_ts_node_has_changes_wasm=e.ts_node_has_changes_wasm,Module._ts_node_has_error_wasm=_ts_node_has_error_wasm=e.ts_node_has_error_wasm,Module._ts_node_is_error_wasm=_ts_node_is_error_wasm=e.ts_node_is_error_wasm,Module._ts_node_is_missing_wasm=_ts_node_is_missing_wasm=e.ts_node_is_missing_wasm,Module._ts_node_is_extra_wasm=_ts_node_is_extra_wasm=e.ts_node_is_extra_wasm,Module._ts_node_parse_state_wasm=_ts_node_parse_state_wasm=e.ts_node_parse_state_wasm,Module._ts_node_next_parse_state_wasm=_ts_node_next_parse_state_wasm=e.ts_node_next_parse_state_wasm,Module._ts_query_matches_wasm=_ts_query_matches_wasm=e.ts_query_matches_wasm,Module._ts_query_captures_wasm=_ts_query_captures_wasm=e.ts_query_captures_wasm,Module._memset=_memset=e.memset,Module._memcpy=_memcpy=e.memcpy,Module._memmove=_memmove=e.memmove,Module._iswalpha=_iswalpha=e.iswalpha,Module._iswblank=_iswblank=e.iswblank,Module._iswdigit=_iswdigit=e.iswdigit,Module._iswlower=_iswlower=e.iswlower,Module._iswupper=_iswupper=e.iswupper,Module._iswxdigit=_iswxdigit=e.iswxdigit,Module._memchr=_memchr=e.memchr,Module._strlen=_strlen=e.strlen,Module._strcmp=_strcmp=e.strcmp,Module._strncat=_strncat=e.strncat,Module._strncpy=_strncpy=e.strncpy,Module._towlower=_towlower=e.towlower,Module._towupper=_towupper=e.towupper,_setThrew=e.setThrew,__emscripten_stack_restore=e._emscripten_stack_restore,__emscripten_stack_alloc=e._emscripten_stack_alloc,_emscripten_stack_get_current=e.emscripten_stack_get_current,___wasm_apply_data_relocs=e.__wasm_apply_data_relocs}C(assignWasmExports,"assignWasmExports");var wasmImports={__heap_base:___heap_base,__indirect_function_table:wasmTable,__memory_base:___memory_base,__stack_high:___stack_high,__stack_low:___stack_low,__stack_pointer:___stack_pointer,__table_base:___table_base,_abort_js:__abort_js,emscripten_resize_heap:_emscripten_resize_heap,fd_close:_fd_close,fd_seek:_fd_seek,fd_write:_fd_write,memory:wasmMemory,tree_sitter_log_callback:_tree_sitter_log_callback,tree_sitter_parse_callback:_tree_sitter_parse_callback,tree_sitter_progress_callback:_tree_sitter_progress_callback,tree_sitter_query_progress_callback:_tree_sitter_query_progress_callback};function callMain(e=[]){var t=resolveGlobalSymbol("main").sym;if(t){e.unshift(thisProgram);var n=e.length,r=stackAlloc((n+1)*4),s=r;e.forEach(a=>{LE_HEAP_STORE_U32((s>>2)*4,stringToUTF8OnStack(a)),s+=4}),LE_HEAP_STORE_U32((s>>2)*4,0);try{var o=t(n,r);return exitJS(o,!0),o}catch(a){return handleException(a)}}}C(callMain,"callMain");function run(e=arguments_){if(runDependencies>0){dependenciesFulfilled=run;return}if(preRun(),runDependencies>0){dependenciesFulfilled=run;return}function t(){if(Module.calledRun=!0,!ABORT){initRuntime(),readyPromiseResolve?.(Module),Module.onRuntimeInitialized?.();var n=Module.noInitialRun||!1;n||callMain(e),postRun()}}C(t,"doRun"),Module.setStatus?(Module.setStatus("Running..."),setTimeout(()=>{setTimeout(()=>Module.setStatus(""),1),t()},1)):t()}C(run,"run");var wasmExports;return wasmExports=await createWasm(),run(),runtimeInitialized?moduleRtn=Module:moduleRtn=new Promise((e,t)=>{readyPromiseResolve=e,readyPromiseReject=t}),moduleRtn}async function gc(e){return pc??=await ym(e)}function _c(){return!!pc}function yc(e,t,n,r){if(e.length!==3)throw new Error(`Wrong number of arguments to \`#${n}\` predicate. Expected 2, got ${e.length-1}`);if(!oc(e[1]))throw new Error(`First argument of \`#${n}\` predicate must be a capture. Got "${e[1].value}"`);let s=n==="eq?"||n==="any-eq?",o=!n.startsWith("any-");if(oc(e[2])){let a=e[1].name,l=e[2].name;r[t].push(c=>{let d=[],f=[];for(let m of c)m.name===a&&d.push(m.node),m.name===l&&f.push(m.node);let u=C((m,p,g)=>g?m.text===p.text:m.text!==p.text,"compare");return o?d.every(m=>f.some(p=>u(m,p,s))):d.some(m=>f.some(p=>u(m,p,s)))})}else{let a=e[1].name,l=e[2].value,c=C(f=>f.text===l,"matches"),d=C(f=>f.text!==l,"doesNotMatch");r[t].push(f=>{let u=[];for(let p of f)p.name===a&&u.push(p.node);let m=s?c:d;return o?u.every(m):u.some(m)})}}function bc(e,t,n,r){if(e.length!==3)throw new Error(`Wrong number of arguments to \`#${n}\` predicate. Expected 2, got ${e.length-1}.`);if(e[1].type!=="capture")throw new Error(`First argument of \`#${n}\` predicate must be a capture. Got "${e[1].value}".`);if(e[2].type!=="string")throw new Error(`Second argument of \`#${n}\` predicate must be a string. Got @${e[2].name}.`);let s=n==="match?"||n==="any-match?",o=!n.startsWith("any-"),a=e[1].name,l=new RegExp(e[2].value);r[t].push(c=>{let d=[];for(let u of c)u.name===a&&d.push(u.node.text);let f=C((u,m)=>m?l.test(u):!l.test(u),"test");return d.length===0?!s:o?d.every(u=>f(u,s)):d.some(u=>f(u,s))})}function wc(e,t,n,r){if(e.length<2)throw new Error(`Wrong number of arguments to \`#${n}\` predicate. Expected at least 1. Got ${e.length-1}.`);if(e[1].type!=="capture")throw new Error(`First argument of \`#${n}\` predicate must be a capture. Got "${e[1].value}".`);let s=n==="any-of?",o=e[1].name,a=e.slice(2);if(!a.every(mo))throw new Error(`Arguments to \`#${n}\` predicate must be strings.".`);let l=a.map(c=>c.value);r[t].push(c=>{let d=[];for(let f of c)f.name===o&&d.push(f.node.text);return d.length===0?!s:d.every(f=>l.includes(f))===s})}function xc(e,t,n,r,s){if(e.length<2||e.length>3)throw new Error(`Wrong number of arguments to \`#${n}\` predicate. Expected 1 or 2. Got ${e.length-1}.`);if(!e.every(mo))throw new Error(`Arguments to \`#${n}\` predicate must be strings.".`);let o=n==="is?"?r:s;o[t]||(o[t]={}),o[t][e[1].value]=e[2]?.value??null}function Sc(e,t,n){if(e.length<2||e.length>3)throw new Error(`Wrong number of arguments to \`#set!\` predicate. Expected 1 or 2. Got ${e.length-1}.`);if(!e.every(mo))throw new Error('Arguments to `#set!` predicate must be strings.".');n[t]||(n[t]={}),n[t][e[1].value]=e[2]?.value??null}function kc(e,t,n,r,s,o,a,l,c,d,f){if(t===bm){let u=r[n];o.push({type:"capture",name:u})}else if(t===wm)o.push({type:"string",value:s[n]});else if(o.length>0){if(o[0].type!=="string")throw new Error("Predicates must begin with a literal value");let u=o[0].value;switch(u){case"any-not-eq?":case"not-eq?":case"any-eq?":case"eq?":yc(o,e,u,a);break;case"any-not-match?":case"not-match?":case"any-match?":case"match?":bc(o,e,u,a);break;case"not-any-of?":case"any-of?":wc(o,e,u,a);break;case"is?":case"is-not?":xc(o,e,u,d,f);break;case"set!":Sc(o,e,c);break;default:l[e].push({operator:u,operands:o.slice(1)})}o.length=0}}var fm,C,Zw,ic,W,so,Le,dt,Jn,$e,Nt,w,mm,pm,gm,_m,hm,uo,ym,pc,D,io,oo,fo,bm,wm,xm,Yw,oc,mo,Ye,Gn,Ec,po=F(()=>{k();fm=Object.defineProperty,C=(e,t)=>fm(e,"name",{value:t,configurable:!0}),Zw=class{static{C(this,"Edit")}startPosition;oldEndPosition;newEndPosition;startIndex;oldEndIndex;newEndIndex;constructor({startIndex:e,oldEndIndex:t,newEndIndex:n,startPosition:r,oldEndPosition:s,newEndPosition:o}){this.startIndex=e>>>0,this.oldEndIndex=t>>>0,this.newEndIndex=n>>>0,this.startPosition=r,this.oldEndPosition=s,this.newEndPosition=o}editPoint(e,t){let n=t,r={...e};if(t>=this.oldEndIndex){n=this.newEndIndex+(t-this.oldEndIndex);let s=e.row;r.row=this.newEndPosition.row+(e.row-this.oldEndPosition.row),r.column=s===this.oldEndPosition.row?this.newEndPosition.column+(e.column-this.oldEndPosition.column):e.column}else t>this.startIndex&&(n=this.newEndIndex,r.row=this.newEndPosition.row,r.column=this.newEndPosition.column);return{point:r,index:n}}editRange(e){let t={startIndex:e.startIndex,startPosition:{...e.startPosition},endIndex:e.endIndex,endPosition:{...e.endPosition}};return e.endIndex>=this.oldEndIndex?e.endIndex!==Number.MAX_SAFE_INTEGER&&(t.endIndex=this.newEndIndex+(e.endIndex-this.oldEndIndex),t.endPosition={row:this.newEndPosition.row+(e.endPosition.row-this.oldEndPosition.row),column:e.endPosition.row===this.oldEndPosition.row?this.newEndPosition.column+(e.endPosition.column-this.oldEndPosition.column):e.endPosition.column},t.endIndexthis.startIndex&&(t.endIndex=this.startIndex,t.endPosition={...this.startPosition}),e.startIndex>=this.oldEndIndex?(t.startIndex=this.newEndIndex+(e.startIndex-this.oldEndIndex),t.startPosition={row:this.newEndPosition.row+(e.startPosition.row-this.oldEndPosition.row),column:e.startPosition.row===this.oldEndPosition.row?this.newEndPosition.column+(e.startPosition.column-this.oldEndPosition.column):e.startPosition.column},t.startIndexthis.startIndex&&(t.startIndex=this.startIndex,t.startPosition={...this.startPosition}),t}},ic=2,W=4,so=4*W,Le=5*W,dt=2*W,Jn=2*W+2*dt,$e={row:0,column:0},Nt=Symbol("INTERNAL");C(bn,"assertInternal");C(Vn,"isPoint");C(ac,"setModule");mm=class{static{C(this,"LookaheadIterator")}0=0;language;constructor(e,t,n){bn(e),this[0]=t,this.language=n}get currentTypeId(){return w._ts_lookahead_iterator_current_symbol(this[0])}get currentType(){return this.language.types[this.currentTypeId]||"ERROR"}delete(){w._ts_lookahead_iterator_delete(this[0]),this[0]=0}reset(e,t){return w._ts_lookahead_iterator_reset(this[0],e[0],t)?(this.language=e,!0):!1}resetState(e){return!!w._ts_lookahead_iterator_reset_state(this[0],e)}[Symbol.iterator](){return{next:C(()=>w._ts_lookahead_iterator_next(this[0])?{done:!1,value:this.currentType}:{done:!0,value:""},"next")}}};C(co,"getText");pm=class ao{static{C(this,"Tree")}0=0;textCallback;language;constructor(t,n,r,s){bn(t),this[0]=n,this.language=r,this.textCallback=s}copy(){let t=w._ts_tree_copy(this[0]);return new ao(Nt,t,this.language,this.textCallback)}delete(){w._ts_tree_delete(this[0]),this[0]=0}get rootNode(){return w._ts_tree_root_node_wasm(this[0]),ue(this)}rootNodeWithOffset(t,n){let r=D+Le;return w.setValue(r,t,"i32"),Ve(r+W,n),w._ts_tree_root_node_with_offset_wasm(this[0]),ue(this)}edit(t){dc(t),w._ts_tree_edit_wasm(this[0])}walk(){return this.rootNode.walk()}getChangedRanges(t){if(!(t instanceof ao))throw new TypeError("Argument must be a Tree");w._ts_tree_get_changed_ranges_wasm(this[0],t[0]);let n=w.getValue(D,"i32"),r=w.getValue(D+W,"i32"),s=new Array(n);if(n>0){let o=r;for(let a=0;a0){let s=n;for(let o=0;o0){let s=n;for(let o=0;o0){let n=t;for(let r=0;r0){let n=t;for(let r=0;r0){let d=l;for(let f=0;f=e.oldEndIndex){this.startIndex=e.newEndIndex+(this.startIndex-e.oldEndIndex);let t,n;this.startPosition.row>e.oldEndPosition.row?(t=this.startPosition.row-e.oldEndPosition.row,n=this.startPosition.column):(t=0,n=this.startPosition.column,this.startPosition.column>=e.oldEndPosition.column&&(n=this.startPosition.column-e.oldEndPosition.column)),t>0?(this.startPosition.row+=t,this.startPosition.column=n):this.startPosition.column+=n}else this.startIndex>e.startIndex&&(this.startIndex=e.newEndIndex,this.startPosition.row=e.newEndPosition.row,this.startPosition.column=e.newEndPosition.column)}toString(){q(this);let e=w._ts_node_to_string_wasm(this.tree[0]),t=w.AsciiToString(e);return w._free(e),t}};C(lo,"unmarshalCaptures");C(q,"marshalNode");C(ue,"unmarshalNode");C(ae,"marshalTreeCursor");C(Be,"unmarshalTreeCursor");C(Ve,"marshalPoint");C(Jt,"unmarshalPoint");C(cc,"marshalRange");C(xs,"unmarshalRange");C(dc,"marshalEdit");C(uc,"unmarshalLanguageMetadata");hm=/^tree_sitter_\w+$/,uo=class fc{static{C(this,"Language")}0=0;types;fields;constructor(t,n){bn(t),this[0]=n,this.types=new Array(w._ts_language_symbol_count(this[0]));for(let r=0,s=this.types.length;r0){let s=n;for(let o=0;o0){let o=r;for(let a=0;a(ro(),no))).readFile(t);else{let l=await fetch(t);if(!l.ok){let d=await l.text();throw new Error(`Language.load failed with status ${l.status}. -${d}`)}let c=l.clone();try{n=await WebAssembly.compileStreaming(l)}catch(d){console.error("wasm streaming compile failed:",d),console.error("falling back to ArrayBuffer instantiation"),n=new Uint8Array(await c.arrayBuffer())}}let r=await b.loadWebAssemblyModule(n,{loadAsync:!0}),s=Object.keys(r),o=s.find(l=>tm.test(l)&&!l.includes("external_scanner_"));if(!o)throw console.log(`Couldn't find language function in Wasm file. Symbols: -${JSON.stringify(s,null,2)}`),new Error("Language.load failed: no language function found in Wasm file");let a=r[o]();return new Yl(At,a)}};M(Ql,"Module");nm=Ql,ec=null;M(tc,"initializeBinding");M(nc,"checkModule");no=class{static{M(this,"Parser")}0=0;1=0;logCallback=null;language=null;static async init(e){Vl(await tc(e)),j=b._ts_init(),Xi=b.getValue(j,"i32"),Zi=b.getValue(j+U,"i32")}constructor(){this.initialize()}initialize(){if(!nc())throw new Error("cannot construct a Parser before calling `init()`");b._ts_parser_new_wasm(),this[0]=b.getValue(j,"i32"),this[1]=b.getValue(j+U,"i32")}delete(){b._ts_parser_delete(this[0]),b._free(this[1]),this[0]=0,this[1]=0}setLanguage(e){let t;if(!e)t=0,this.language=null;else if(e.constructor===to){t=e[0];let n=b._ts_language_abi_version(t);if(ne.slice(l);else if(typeof e=="function")b.currentParseCallback=e;else throw new Error("Argument must be a string or a function");n?.progressCallback?b.currentProgressCallback=n.progressCallback:b.currentProgressCallback=null,this.logCallback?(b.currentLogCallback=this.logCallback,b._ts_parser_enable_logger_wasm(this[0],1)):(b.currentLogCallback=null,b._ts_parser_enable_logger_wasm(this[0],0));let r=0,s=0;if(n?.includedRanges){r=n.includedRanges.length,s=b._calloc(r,zn);let l=s;for(let c=0;c0){let r=t;for(let s=0;se.type==="capture","isCaptureStep"),ro=M(e=>e.type==="string","isStringStep"),Ke={Syntax:1,NodeName:2,FieldName:3,CaptureName:4,PatternStructure:5},Bn=class rc extends Error{constructor(t,n,r,s){super(rc.formatMessage(t,n)),this.kind=t,this.info=n,this.index=r,this.length=s,this.name="QueryError"}static{M(this,"QueryError")}static formatMessage(t,n){switch(t){case Ke.NodeName:return`Bad node name '${n.word}'`;case Ke.FieldName:return`Bad field name '${n.word}'`;case Ke.CaptureName:return`Bad capture name @${n.word}`;case Ke.PatternStructure:return`Bad pattern structure at offset ${n.suffix}`;case Ke.Syntax:return`Bad syntax at offset ${n.suffix}`}}};M(sc,"parseAnyPredicate");M(ic,"parseMatchPredicate");M(oc,"parseAnyOfPredicate");M(ac,"parseIsPredicate");M(lc,"parseSetDirective");M(cc,"parsePattern");dc=class{static{M(this,"Query")}0=0;exceededMatchLimit;textPredicates;captureNames;captureQuantifiers;predicates;setProperties;assertedProperties;refutedProperties;matchLimit;constructor(e,t){let n=b.lengthBytesUTF8(t),r=b._malloc(n+1);b.stringToUTF8(t,r,n+1);let s=b._ts_query_new(e[0],r,n,j,j+U);if(!s){let _=b.getValue(j+U,"i32"),y=b.getValue(j,"i32"),x=b.UTF8ToString(r,y).length,E=t.slice(x,x+100).split(` -`)[0],w=E.match(im)?.[0]??"";switch(b._free(r),_){case Ke.Syntax:throw new Bn(Ke.Syntax,{suffix:`${x}: '${E}'...`},x,0);case Ke.NodeName:throw new Bn(_,{word:w},x,w.length);case Ke.FieldName:throw new Bn(_,{word:w},x,w.length);case Ke.CaptureName:throw new Bn(_,{word:w},x,w.length);case Ke.PatternStructure:throw new Bn(_,{suffix:`${x}: '${E}'...`},x,0)}}let o=b._ts_query_string_count(s),a=b._ts_query_capture_count(s),l=b._ts_query_pattern_count(s),c=new Array(a),d=new Array(l),u=new Array(o);for(let _=0;_o)throw new Error("`startIndex` cannot be greater than `endIndex`");if(r!==Oe&&(n.row>r.row||n.row===r.row&&n.column>r.column))throw new Error("`startPosition` cannot be greater than `endPosition`");if(d!==0&&c>d)throw new Error("`startContainingIndex` cannot be greater than `endContainingIndex`");if(l!==Oe&&(a.row>l.row||a.row===l.row&&a.column>l.column))throw new Error("`startContainingPosition` cannot be greater than `endContainingPosition`");p&&(b.currentQueryProgressCallback=p),H(e),b._ts_query_matches_wasm(this[0],e.tree[0],n.row,n.column,r.row,r.column,s,o,a.row,a.column,l.row,l.column,c,d,u,f);let m=b.getValue(j,"i32"),g=b.getValue(j+U,"i32"),h=b.getValue(j+2*U,"i32"),_=new Array(m);this.exceededMatchLimit=!!h;let y=0,x=g;for(let E=0;EA(C))){_[y]={patternIndex:w,captures:C};let A=this.setProperties[w];_[y].setProperties=A;let F=this.assertedProperties[w];_[y].assertedProperties=F;let N=this.refutedProperties[w];_[y].refutedProperties=N,y++}}return _.length=y,b._free(g),b.currentQueryProgressCallback=null,_}captures(e,t={}){let n=t.startPosition??Oe,r=t.endPosition??Oe,s=t.startIndex??0,o=t.endIndex??0,a=t.startContainingPosition??Oe,l=t.endContainingPosition??Oe,c=t.startContainingIndex??0,d=t.endContainingIndex??0,u=t.matchLimit??4294967295,f=t.maxStartDepth??4294967295,p=t.progressCallback;if(typeof u!="number")throw new Error("Arguments must be numbers");if(this.matchLimit=u,o!==0&&s>o)throw new Error("`startIndex` cannot be greater than `endIndex`");if(r!==Oe&&(n.row>r.row||n.row===r.row&&n.column>r.column))throw new Error("`startPosition` cannot be greater than `endPosition`");if(d!==0&&c>d)throw new Error("`startContainingIndex` cannot be greater than `endContainingIndex`");if(l!==Oe&&(a.row>l.row||a.row===l.row&&a.column>l.column))throw new Error("`startContainingPosition` cannot be greater than `endContainingPosition`");p&&(b.currentQueryProgressCallback=p),H(e),b._ts_query_captures_wasm(this[0],e.tree[0],n.row,n.column,r.row,r.column,s,o,a.row,a.column,l.row,l.column,c,d,u,f);let m=b.getValue(j,"i32"),g=b.getValue(j+U,"i32"),h=b.getValue(j+2*U,"i32"),_=new Array;this.exceededMatchLimit=!!h;let y=new Array,x=g;for(let E=0;EA(y))){let A=y[C],F=this.setProperties[w];A.setProperties=F;let N=this.assertedProperties[w];A.assertedProperties=N;let W=this.refutedProperties[w];A.refutedProperties=W,_.push(A)}}return b._free(g),b.currentQueryProgressCallback=null,_}predicatesForPattern(e){return this.predicates[e]}disableCapture(e){let t=b.lengthBytesUTF8(e),n=b._malloc(t+1);b.stringToUTF8(e,n,t+1),b._ts_query_disable_capture(this[0],n,t),b._free(n)}disablePattern(e){if(e>=this.predicates.length)throw new Error(`Pattern index is ${e} but the pattern count is ${this.predicates.length}`);b._ts_query_disable_pattern(this[0],e)}didExceedMatchLimit(){return this.exceededMatchLimit}startIndexForPattern(e){if(e>=this.predicates.length)throw new Error(`Pattern index is ${e} but the pattern count is ${this.predicates.length}`);return b._ts_query_start_byte_for_pattern(this[0],e)}endIndexForPattern(e){if(e>=this.predicates.length)throw new Error(`Pattern index is ${e} but the pattern count is ${this.predicates.length}`);return b._ts_query_end_byte_for_pattern(this[0],e)}patternCount(){return b._ts_query_pattern_count(this[0])}captureIndexForName(e){return this.captureNames.indexOf(e)}isPatternRooted(e){return b._ts_query_is_pattern_rooted(this[0],e)===1}isPatternNonLocal(e){return b._ts_query_is_pattern_non_local(this[0],e)===1}isPatternGuaranteedAtStep(e){return b._ts_query_is_pattern_guaranteed_at_step(this[0],e)===1}}});function Jn(e){return _s[e]}function yn(){let e=v.env.XDG_CACHE_HOME,t=e&&e.trim()?e.trim():I(Hl(),".cache");return I(t,"codeindex","grammars",fe)}function Xe(e={}){let t=yn(),n=(l,c)=>({tier:l,dir:c,cacheDir:t,dirs:[c,...z(I(c,"..",uc))?[I(c,"..",uc)]:[]]}),r=v.env.CODEINDEX_GRAMMAR_DIR??v.env.ULTRAINDEX_GRAMMAR_DIR;if(r&&r.trim()&&z(r))return n("env",r);let s=e.moduleDir??Se(us(import.meta.url)),o=[I(s,"grammars"),I(s,"..","..","scripts","grammars"),I(s,"..","scripts","grammars")];for(let l of o)if(z(l))return n("adjacent",l);let a=v.env.CODEINDEX_GRAMMARS_DIR;return a&&a.trim()&&z(a)?n("env",a):z(t)?n("cache",t):{tier:"none",cacheDir:t,dirs:[]}}function om(e){return Xe(e).dir}async function Ze(e){let{dirs:t}=Xe();if(!t.length)return;let n=r=>{for(let s of t){let o=I(s,r);if(z(o))return o}};if(!fc){let r=n("web-tree-sitter.wasm");if(!r)return;await no.init({wasmBinary:te(r)}),fc=!0,gs=new no}for(let r of new Set(e)){if(Gn.has(r)||io.has(r))continue;let s=n(`${r}.wasm`);if(!s){io.add(r);continue}try{Gn.set(r,await to.load(new Uint8Array(te(s))))}catch{io.add(r)}}}function oo(){return[...new Set(Object.values(_s))]}function _t(e){let t=new Set;for(let n of e){let r=_s[n];r!==void 0&&t.add(r)}return[...t].sort()}function Ye(e){return Gn.has(e)}function ao(e){return Gn.get(e)}function hs(e){let t=Gn.get(e);return!gs||!t?null:(gs.setLanguage(t),gs)}var qn,Vn,_s,uc,fc,gs,Gn,io,Qe=O(()=>{"use strict";S();we();qi();ie();ms();so();qe();qn=new Set(["typescript","tsx","javascript","python","go","rust","java","ruby","c","cpp","c_sharp","php","scala","bash","lua"]),Vn=new Set(["kotlin","elixir","zig","hcl","terraform","solidity"]),_s={".ts":"typescript",".mts":"typescript",".cts":"typescript",".tsx":"tsx",".js":"javascript",".jsx":"javascript",".mjs":"javascript",".cjs":"javascript",".py":"python",".pyi":"python",".go":"go",".rs":"rust",".java":"java",".rb":"ruby",".rake":"ruby",".c":"c",".h":"c",".cc":"cpp",".cpp":"cpp",".cxx":"cpp",".hpp":"cpp",".hh":"cpp",".cs":"c_sharp",".php":"php",".scala":"scala",".sc":"scala",".sh":"bash",".bash":"bash",".lua":"lua",".kt":"kotlin",".kts":"kotlin",".ex":"elixir",".exs":"elixir",".zig":"zig",".hcl":"hcl",".tf":"terraform",".tfvars":"terraform",".sol":"solidity"};uc="grammars-extended";fc=!1,gs=null,Gn=new Map,io=new Set});function Ce(e,t){for(let n of e.namedChildren){if(t(n))return n;let r=Ce(n,t);if(r)return r}}function Kn(e){let t=e.childForFieldName("name");if(t?.text)return t.text;let n=e.childForFieldName("declarator");for(;n;){let o=n.childForFieldName("name");if(o?.text)return o.text;if(n.namedChildren.length===0&&/(^|_)identifier$/.test(n.type))return n.text;let a=n.childForFieldName("declarator");if(!a||a===n)break;n=a}let s=Ce(e,o=>o.type==="variable_declarator")?.childForFieldName("name");if(s?.text)return s.text;for(let o of e.namedChildren)if(/(^|_)(identifier|name|constant)$/.test(o.type))return o.text}function Jt(e){if(!e)return;let t=e.namedChildren;if(t.length===0)return ys.test(e.type)?e.text:void 0;let n=e.childForFieldName("name")??e.childForFieldName("property")??e.childForFieldName("attribute")??e.childForFieldName("field")??e.childForFieldName("function");if(n)return Jt(n);let r=t[t.length-1];return r&&r!==e?Jt(r):void 0}function Xn(e){if(!e||e.namedChildren.length===0)return;let t=e.childForFieldName("object")??e.childForFieldName("operand")??e.childForFieldName("value")??e.childForFieldName("path")??e.childForFieldName("expression")??e.childForFieldName("argument")??e.childForFieldName("receiver")??e.childForFieldName("table"),n=t?Jt(t):void 0;return n&&/^[A-Za-z_]\w*$/.test(n)?n:void 0}function Ue(e){if(!e)return;let t=e.childForFieldName("type")??e.childForFieldName("name");if(t&&/generic|qualified|scoped|nested/.test(e.type))return Ue(t);if(e.namedChildren.length===0)return mc.test(e.type)?e.text:void 0;let n,r=s=>{if(s.namedChildren.length===0){mc.test(s.type)&&(n=s.text);return}if(!/arguments|parameters/.test(s.type))for(let o of s.namedChildren)r(o)};return r(e),n}var ys,mc,lo=O(()=>{"use strict";S();ys=/(^|_)(identifier|name|constant|word)$/;mc=/identifier|constant|(^|_)name$/});function Ie(e){if(!e)return[];let t=[];for(let n of e.namedChildren){if(/arguments|parameters/.test(n.type))continue;let r=Ue(n);r&&t.push(r)}return t}function pc(e,t){if(!t.self)return[];let n=_e(e,"class_heritage");if(!n)return[];let r=[];for(let s of Ie(_e(n,"extends_clause")))r.push(pe("extends",t.self,s,e));for(let s of Ie(_e(n,"implements_clause")))r.push(pe("implements",t.self,s,e));return r}function Zn(e,t,n){return Ie(e).map((s,o)=>pe(o===0?"extends":"implements",t,s,n))}var _e,pe,wc,fo,ws,gc,co,am,_c,hc,lm,Yn,cm,bs,yc,dm,bc,uo,xc,Sc=O(()=>{"use strict";S();lo();_e=(e,t)=>e.namedChildren.find(n=>n.type===t),pe=(e,t,n,r)=>({kind:e,from:t,to:n,line:r.startPosition.row+1});wc=new Set(["interface","trait","enum","protocol","annotation"]),fo=new Set(["function","method","def","constructor","operator"]),ws=new Set(["function","function_expression","arrow_function","generator_function","class","function_definition","lambda"]),gc=e=>/\b(public|internal)\b/.test(e),co=e=>!/\b(private|protected)\b/.test(e),am=e=>!/^local\b/.test(e),_c=e=>/\bpub\b/.test(e),hc=(e,t)=>/^[A-Z]/.test(t),lm=(e,t)=>!t.startsWith("_")||/^__\w+__$/.test(t),Yn=()=>!0,cm=()=>!1,bs=e=>Ce(e,t=>t.type==="function_declarator")!==void 0,yc={defmodule:"module",defprotocol:"protocol",defimpl:"impl",defstruct:"struct",defexception:"exception",def:"function",defp:"function",defmacro:"macro",defmacrop:"macro",defguard:"guard",defguardp:"guard",defdelegate:"function"},dm=new Set(["resource","data","variable","output","module","provider","locals","terraform"]),bc={lang:"terraform",defs:{block:"block"},containers:new Set(["config_file","body"]),exported:Yn,kindFrom:{block:e=>{let t=e.namedChildren.find(n=>n.type==="identifier")?.text;return t&&dm.has(t)?t:void 0}},nameFrom:{block:e=>{let t=e.namedChildren.filter(n=>n.type==="string_lit").map(n=>n.text.replace(/^"|"$/g,""));return t.length?t.join("."):e.namedChildren.find(n=>n.type==="identifier")?.text}}},uo={lang:"typescript",defs:{function_declaration:"function",generator_function_declaration:"function",function_signature:"function",class_declaration:"class",abstract_class_declaration:"class",interface_declaration:"interface",type_alias_declaration:"type",enum_declaration:"enum",enum_assignment:"enum-member",method_definition:"method",method_signature:"method",abstract_method_signature:"method",property_signature:"property",public_field_definition:"property",call_signature:"call-signature",construct_signature:"construct-signature",index_signature:"index-signature",internal_module:"namespace",module:"namespace",variable_declarator:"const"},containers:new Set(["class_body","export_statement","ambient_declaration","program","lexical_declaration","variable_declaration","interface_body","object_type","enum_body","statement_block","try_statement","catch_clause","finally_clause","if_statement","else_clause","for_statement","for_in_statement","while_statement","do_statement","switch_statement","switch_body","switch_case","switch_default","labeled_statement","return_statement","expression_statement","call_expression","arguments","arrow_function","function_expression","function","parenthesized_expression"]),exported:cm,exportMarkers:new Set(["export_statement","ambient_declaration"]),bareMembers:{enum_body:"enum-member"},nameFrom:{call_signature:()=>"(call)",construct_signature:()=>"(construct)",index_signature:e=>`[${e.namedChildren.find(t=>t.type==="identifier")?.text??"key"}]`},privateMember:e=>{for(let t of e.namedChildren)if(t.type==="accessibility_modifier"&&/^(private|protected)/.test(t.text)||t.type==="private_property_identifier")return!0;return!1},imports:{import_statement:"string"},calls:{call_expression:"function",new_expression:"constructor"},assignments:!0,relationsFrom:{class_declaration:pc,abstract_class_declaration:pc,interface_declaration:(e,t)=>t.self?Ie(_e(e,"extends_type_clause")).map(n=>pe("extends",t.self,n,e)):[]}},xc={typescript:uo,tsx:{...uo,lang:"typescript"},javascript:{...uo,lang:"javascript",defs:{function_declaration:"function",generator_function_declaration:"function",class_declaration:"class",method_definition:"method",field_definition:"property",variable_declarator:"const"}},python:{lang:"python",defs:{function_definition:"function",class_definition:"class"},containers:new Set(["block","decorated_definition","module"]),exported:lm,imports:{import_statement:"path",import_from_statement:"path"},calls:{call:"function"},docstring:!0,relationsFrom:{class_definition:(e,t)=>t.self?Ie(e.childForFieldName("superclasses")).map(n=>pe("extends",t.self,n,e)):[]},extraMembers:(e,t)=>{if(t.inFunctionBody)return[];if(e.type==="import_from_statement"){let s=[];for(let o of e.namedChildren){if(o.type!=="aliased_import")continue;let a=o.namedChildren[0]?.text,l=o.childForFieldName("alias")?.text;a&&l&&a===l&&s.push({name:l,kind:"reexport"})}return s}if(e.type!=="expression_statement")return[];let n=e.namedChildren[0];if(!n||n.type!=="assignment")return[];let r=n.childForFieldName("left");return!r||r.type!=="identifier"?[]:[{name:r.text,kind:t.ownerKind==="class"?"field":"const"}]}},go:{lang:"go",defs:{function_declaration:"function",method_declaration:"method",type_spec:"type",const_spec:"const",var_spec:"var",field_declaration:"field",method_spec:"method",method_elem:"method",package_clause:"package"},containers:new Set(["type_declaration","const_declaration","var_declaration","var_spec_list","source_file","struct_type","interface_type","field_declaration_list"]),exported:hc,imports:{import_declaration:"string"},calls:{call_expression:"function"},parentFrom:{method_declaration:e=>Ue(e.childForFieldName("receiver"))},nameFrom:{field_declaration:e=>e.childForFieldName("name")?.text},relationsFrom:{field_declaration:(e,t)=>{if(!t.self||e.childForFieldName("name"))return[];let n=Ue(e.childForFieldName("type"));return n?[pe("extends",t.self,n,e)]:[]}}},ruby:{lang:"ruby",defs:{method:"def",singleton_method:"def",class:"class",module:"module"},containers:new Set(["class","module","body_statement","program"]),exported:Yn,calls:{call:"function"},sectionVisibility:e=>(e.type==="identifier"||e.type==="call")&&/^(private|protected)$/.test(e.text)?!1:e.type==="identifier"&&e.text==="public"?!0:void 0,relationsFrom:{class:(e,t)=>{if(!t.self)return[];let n=Ue(e.childForFieldName("superclass"));return n?[pe("extends",t.self,n,e)]:[]},call:(e,t)=>{let n=e.childForFieldName("method");if(!t.self||!n||!/^(include|prepend|extend)$/.test(n.text))return[];let r=[];for(let s of e.childForFieldName("arguments")?.namedChildren??[]){let o=Ue(s);o&&r.push(pe("implements",t.self,o,e))}return r}},extraMembers:(e,t)=>{if(t.inFunctionBody)return[];if(e.type==="assignment"){let n=e.childForFieldName("left");return n?.type==="constant"?[{name:n.text,kind:"const"}]:[]}if(e.type==="call"){let n=e.childForFieldName("method");if(!n||!/^attr_(reader|writer|accessor)$/.test(n.text))return[];let r=e.childForFieldName("arguments"),s=[];for(let o of r?.namedChildren??[])o.type==="simple_symbol"&&s.push({name:o.text.replace(/^:/,""),kind:"attr"});return s}return[]}},java:{lang:"java",defs:{class_declaration:"class",interface_declaration:"interface",annotation_type_declaration:"annotation",enum_declaration:"enum",enum_constant:"enum-member",record_declaration:"record",method_declaration:"method",constructor_declaration:"constructor",compact_constructor_declaration:"constructor",field_declaration:"field",constant_declaration:"field",annotation_type_element_declaration:"method"},containers:new Set(["class_body","interface_body","enum_body","enum_body_declarations","annotation_type_body","program","formal_parameters"]),exported:gc,imports:{import_declaration:"path"},calls:{method_invocation:"function",object_creation_expression:"constructor"},kindFrom:{formal_parameter:e=>e.parent?.parent?.type==="record_declaration"?"field":void 0},publicMember:e=>e.parent?.parent?.type==="record_declaration",nameFrom:{field_declaration:e=>Ce(e,t=>t.type==="variable_declarator")?.childForFieldName("name")?.text,constant_declaration:e=>Ce(e,t=>t.type==="variable_declarator")?.childForFieldName("name")?.text},relationsFrom:{class_declaration:(e,t)=>{if(!t.self)return[];let n=[];for(let s of Ie(e.childForFieldName("superclass")))n.push(pe("extends",t.self,s,e));let r=e.childForFieldName("interfaces");for(let s of Ie(_e(r??e,"type_list")??r))n.push(pe("implements",t.self,s,e));return n},interface_declaration:(e,t)=>{let n=e.childForFieldName("interfaces")??_e(e,"extends_interfaces");return t.self?Ie(_e(n??e,"type_list")??n).map(r=>pe("extends",t.self,r,e)):[]},record_declaration:(e,t)=>{let n=e.childForFieldName("interfaces");return t.self?Ie(_e(n??e,"type_list")??n).map(r=>pe("implements",t.self,r,e)):[]}}},rust:{lang:"rust",defs:{function_item:"function",function_signature_item:"function",struct_item:"struct",enum_item:"enum",enum_variant:"enum-member",field_declaration:"field",trait_item:"trait",type_item:"type",associated_type:"type",mod_item:"mod",const_item:"const",static_item:"static",union_item:"union",macro_definition:"macro"},containers:new Set(["impl_item","declaration_list","source_file","field_declaration_list","enum_variant_list","foreign_mod_item","block"]),exported:_c,calls:{call_expression:"function"},parentFrom:{impl_item:e=>Ue(e.childForFieldName("type"))},nestedDefs:new Set(["const_item","static_item"]),publicMembersIn:{impl_item:e=>e.childForFieldName("trait")!==null},relationsFrom:{impl_item:(e,t)=>{let n=Ue(e.childForFieldName("trait"));return t.self&&n?[pe("implements",t.self,n,e)]:[]}}},c_sharp:{lang:"csharp",defs:{class_declaration:"class",interface_declaration:"interface",struct_declaration:"struct",enum_declaration:"enum",enum_member_declaration:"enum-member",record_declaration:"record",delegate_declaration:"delegate",method_declaration:"method",constructor_declaration:"constructor",property_declaration:"property",indexer_declaration:"indexer",operator_declaration:"operator",field_declaration:"field",event_declaration:"event",event_field_declaration:"event",conversion_operator_declaration:"operator",destructor_declaration:"destructor"},containers:new Set(["namespace_declaration","declaration_list","compilation_unit","file_scoped_namespace_declaration","enum_member_declaration_list","parameter_list"]),exported:gc,calls:{invocation_expression:"function",object_creation_expression:"constructor"},kindFrom:{parameter:e=>e.parent?.parent?.type==="record_declaration"?"field":void 0},publicMember:e=>e.parent?.parent?.type==="record_declaration",nameFrom:{field_declaration:e=>Ce(e,t=>t.type==="variable_declarator")?.childForFieldName("name")?.text,event_field_declaration:e=>Ce(e,t=>t.type==="variable_declarator")?.childForFieldName("name")?.text,conversion_operator_declaration:e=>e.childForFieldName("type")?.text},relationsFrom:{class_declaration:(e,t)=>t.self?Zn(_e(e,"base_list"),t.self,e):[],struct_declaration:(e,t)=>t.self?Zn(_e(e,"base_list"),t.self,e):[],record_declaration:(e,t)=>t.self?Zn(_e(e,"base_list"),t.self,e):[],interface_declaration:(e,t)=>t.self?Ie(_e(e,"base_list")).map(n=>pe("extends",t.self,n,e)):[]}},php:{lang:"php",defs:{function_definition:"function",class_declaration:"class",interface_declaration:"interface",trait_declaration:"trait",enum_declaration:"enum",enum_case:"enum-member",method_declaration:"method",property_declaration:"property",const_declaration:"const",namespace_definition:"namespace"},containers:new Set(["declaration_list","enum_declaration_list","program"]),exported:co,calls:{function_call_expression:"function",member_call_expression:"member",object_creation_expression:"constructor"},nameFrom:{property_declaration:e=>Ce(e,t=>t.type==="variable_name")?.text.replace(/^\$/,""),const_declaration:e=>Ce(e,t=>t.type==="const_element")?.namedChildren[0]?.text},relationsFrom:{class_declaration:(e,t)=>{if(!t.self)return[];let n=[];for(let r of Ie(_e(e,"base_clause")))n.push(pe("extends",t.self,r,e));for(let r of Ie(_e(e,"class_interface_clause")))n.push(pe("implements",t.self,r,e));return n},interface_declaration:(e,t)=>t.self?Ie(_e(e,"base_clause")).map(n=>pe("extends",t.self,n,e)):[]}},c:{lang:"c",defs:{function_definition:"function",struct_specifier:"struct",enum_specifier:"enum",enumerator:"enum-member",union_specifier:"union",type_definition:"type",field_declaration:"field",declaration:"const"},containers:new Set(["translation_unit","declaration_list","field_declaration_list","enumerator_list","linkage_specification","preproc_ifdef","preproc_if"]),exported:Yn,calls:{call_expression:"function"},kindFrom:{field_declaration:e=>bs(e)?"method":"field",declaration:e=>bs(e)?"function":"const"}},cpp:{lang:"cpp",defs:{function_definition:"function",class_specifier:"class",struct_specifier:"struct",enum_specifier:"enum",enumerator:"enum-member",union_specifier:"union",type_definition:"type",alias_declaration:"type",concept_definition:"concept",namespace_definition:"namespace",namespace_alias_definition:"namespace",field_declaration:"field",declaration:"const",using_declaration:"using",friend_declaration:"friend"},containers:new Set(["translation_unit","declaration_list","field_declaration_list","enumerator_list","template_declaration","linkage_specification","preproc_ifdef","preproc_if"]),exported:Yn,calls:{call_expression:"function",new_expression:"constructor"},kindFrom:{field_declaration:e=>bs(e)?"method":"field",declaration:e=>bs(e)?"function":"const"},sectionVisibility:e=>e.type==="access_specifier"?!/^(private|protected)/.test(e.text):void 0,nameFrom:{friend_declaration:e=>Kn(e)??(e.namedChildren[0]?Kn(e.namedChildren[0]):void 0)},relationsFrom:{class_specifier:(e,t)=>t.self?Ie(_e(e,"base_class_clause")).map(n=>pe("extends",t.self,n,e)):[],struct_specifier:(e,t)=>t.self?Ie(_e(e,"base_class_clause")).map(n=>pe("extends",t.self,n,e)):[]}},scala:{lang:"scala",defs:{class_definition:"class",object_definition:"object",trait_definition:"trait",enum_definition:"enum",function_definition:"def",function_declaration:"def",val_definition:"val",val_declaration:"val",var_definition:"var",type_definition:"type",given_definition:"given",package_clause:"package"},containers:new Set(["compilation_unit","package_clause","template_body","class_parameters","parameters","extension_definition"]),parentFrom:{extension_definition:e=>Ue(_e(e,"parameters")?.namedChildren[0]?.childForFieldName("type")??null)},exported:co,kindFrom:{class_parameter:e=>/^\s*(?:val|var)\b/.test(e.text)?/^\s*var\b/.test(e.text)?"var":"val":e.parent?.parent?.type==="class_definition"&&/\bcase\s+class\b/.test(e.parent.parent.text.slice(0,80))?"val":void 0},calls:{call_expression:"function",instance_expression:"constructor"},relationsFrom:{class_definition:(e,t)=>t.self?Zn(_e(e,"extends_clause"),t.self,e):[],object_definition:(e,t)=>t.self?Zn(_e(e,"extends_clause"),t.self,e):[],trait_definition:(e,t)=>t.self?Ie(_e(e,"extends_clause")).map(n=>pe("extends",t.self,n,e)):[]}},bash:{lang:"shell",defs:{function_definition:"function",declaration_command:"const"},containers:new Set(["program","if_statement","compound_statement"]),exported:Yn,calls:{command:"function"},nameFrom:{declaration_command:e=>/^\s*local\b/.test(e.text)?void 0:Ce(e,t=>t.type==="variable_name")?.text}},kotlin:{lang:"kotlin",defs:{class_declaration:"class",object_declaration:"object",function_declaration:"function",property_declaration:"property",enum_entry:"enum-member",type_alias:"type",class_parameter:"property"},containers:new Set(["source_file","class_body","enum_class_body","companion_object","object_declaration","primary_constructor","class_parameters"]),exported:co,calls:{call_expression:"function"},kindFrom:{class_parameter:e=>/^\s*(?:val|var)\b/.test(e.text)||/\bdata\s+class\b/.test(e.parent?.parent?.parent?.text.slice(0,80)??"")?"property":void 0,class_declaration:e=>{let t=e.text.slice(0,80);return/\binterface\b/.test(t)?"interface":/\benum\s+class\b/.test(t)?"enum":/\bannotation\s+class\b/.test(t)?"annotation":"class"}},nameFrom:{property_declaration:e=>Ce(e,t=>t.type==="variable_declaration")?.namedChildren[0]?.text??e.namedChildren.find(t=>t.type==="identifier")?.text},relationsFrom:{class_declaration:(e,t)=>{if(!t.self)return[];let n=[];for(let r of _e(e,"delegation_specifiers")?.namedChildren??[]){let s=Ue(r);s&&n.push(pe(Ce(r,o=>o.type==="constructor_invocation")?"extends":"implements",t.self,s,e))}return n}}},elixir:{lang:"elixir",defs:{},containers:new Set(["source","do_block","call","stab_clause"]),exported:e=>!/^\s*defp?macrop\b|^\s*defp\b/.test(e),calls:{call:"function"},kindFrom:{call:e=>yc[e.childForFieldName("target")?.text??e.namedChildren[0]?.text??""]},skipCall:e=>{if(e.parent?.type==="unary_operator")return!0;if(e.parent?.type!=="arguments")return!1;let t=e.parent.parent,n=t?.childForFieldName("target")??t?.namedChildren[0];return n!==void 0&&yc[n.text]!==void 0},docFrom:e=>{let t=e.previousNamedSibling;for(;t&&t.type==="unary_operator";){let n=t.namedChildren[0],r=n?.childForFieldName("target")??n?.namedChildren[0];if(r&&/^(doc|moduledoc)$/.test(r.text)){let s=Ce(t,o=>o.type==="string");if(s)return s.text.replace(/^"""|"""$/g,"").replace(/^"|"$/g,"").trim()||void 0}t=t.previousNamedSibling}},nameFrom:{call:e=>{let n=(e.childForFieldName("arguments")??e.namedChildren.find(s=>s.type==="arguments"))?.namedChildren[0];if(!n)return;if(n.type==="alias"||n.type==="identifier")return n.text;let r=n.childForFieldName("target")??n.namedChildren[0];return r&&/identifier|alias/.test(r.type)?r.text:void 0}}},zig:{lang:"zig",defs:{function_declaration:"function",variable_declaration:"const",container_field:"field",test_declaration:"test"},containers:new Set(["source_file","variable_declaration","struct_declaration","enum_declaration","union_declaration","error_set_declaration","opaque_declaration","block"]),exported:_c,calls:{call_expression:"function"},kindFrom:{variable_declaration:e=>{let t=e.namedChildren.find(n=>n.type==="builtin_function");if(!(t&&/^@(import|cImport)\b/.test(t.text))){for(let n of e.namedChildren){if(n.type==="struct_declaration")return"struct";if(n.type==="enum_declaration")return"enum";if(n.type==="union_declaration")return"union";if(n.type==="error_set_declaration")return"error";if(n.type==="opaque_declaration")return"opaque"}return/^\s*(?:pub\s+)?var\b/.test(e.text.slice(0,24))?"var":"const"}},container_field:e=>e.parent?.type==="enum_declaration"?"enum-member":"field"}},solidity:{lang:"solidity",defs:{contract_declaration:"contract",interface_declaration:"interface",library_declaration:"library",function_definition:"function",constructor_definition:"constructor",modifier_definition:"modifier",event_definition:"event",error_declaration:"error",struct_declaration:"struct",struct_member:"field",enum_declaration:"enum",enum_value:"enum-member",state_variable_declaration:"field",constant_variable_declaration:"const",user_defined_type_definition:"type",fallback_receive_definition:"function"},containers:new Set(["source_file","contract_body","struct_declaration","enum_declaration","enum_body"]),exported:(e,t)=>/\b(public|external)\b/.test(e)?!0:/\b(internal|private)\b/.test(e)?!1:hc(e,t)||!0,calls:{call_expression:"function"},nameFrom:{state_variable_declaration:e=>e.namedChildren.find(t=>t.type==="identifier")?.text,fallback_receive_definition:e=>/^\s*receive\b/.test(e.text)?"receive":"fallback",enum_value:e=>e.text},relationsFrom:{contract_declaration:(e,t)=>t.self?e.namedChildren.filter(n=>n.type==="inheritance_specifier").map(n=>Ue(n)).filter(n=>n!==void 0).map(n=>pe("extends",t.self,n,e)):[],interface_declaration:(e,t)=>t.self?e.namedChildren.filter(n=>n.type==="inheritance_specifier").map(n=>Ue(n)).filter(n=>n!==void 0).map(n=>pe("extends",t.self,n,e)):[]}},terraform:bc,hcl:{...bc,lang:"hcl"},lua:{lang:"lua",defs:{function_declaration:"function"},containers:new Set(["chunk","variable_declaration"]),exported:am,calls:{function_call:"function"},assignments:!0}}});function mm(e){let t=e.childForFieldName("body"),n=t&&t.startIndex>e.startIndex?t.startIndex:void 0,r=s=>{um.has(s.type)&&s.startIndex>e.startIndex&&(n===void 0||s.startIndex|=)$/,"").trim().slice(0,fm)}var um,fm,kc=O(()=>{"use strict";S();um=new Set(["block","statement_block","class_body","declaration_list","field_declaration_list","template_body","compound_statement","body_statement","enum_body","enum_body_declarations","enum_variant_list","enum_member_declaration_list","enumerator_list","interface_body","object_type","do_block","struct_declaration","enum_declaration","union_declaration","error_set_declaration","opaque_declaration","contract_body","enum_class_body"]),fm=400});function mo(e){return pm.test(e.trim())}function po(e){return gm.test(e.trim())}function ht(e){return e.replace(/\*+\/\s*$/,"").replace(/^\s*\/\*+!?/,"").replace(/^\s*\/\/[/!]?/,"").replace(/^\s*--+/,"").replace(/^\s*#+/,"").replace(/^\s*\*+/,"").replace(/^\s*(?:"""|''')/,"").replace(/(?:"""|''')\s*$/,"").replace(/[-=~_]{3,}/g," ").trim()}function _m(e){return e.replace(/<\/?[A-Za-z][^>]*>/g," ").replace(/\s+/g," ").trim()}function go(e,t=hm){let n=[];for(let o of e){let a=o.trim();if(!(!a||mo(a)||po(a))){if(/^@[a-z]/i.test(a))break;n.push(a)}}let r=_m(n.join(" "));if(r.length<3)return;let s=/^(.*?[.!?])(\s|$)/.exec(r);return(s?s[1]:r).slice(0,t)}var pm,gm,hm,xs=O(()=>{"use strict";S();pm=/^(eslint\b|eslint-|prettier\b|prettier-|tslint\b|jshint\b|jslint\b|globals?\b|istanbul\b|c8\s|v8\s|@ts-|ts-|@flow\b|@jsx\b|@jsxRuntime\b|@jest-environment\b|@vitest-environment\b|@license\b|@preserve\b|@copyright\b|copyright\b|spdx-|1);)t.push(n),r=n.startPosition.row,n=n.previousNamedSibling;if(!t.length)return[];t.reverse();let s=[];for(let o of t)for(let a of o.text.split(/\r?\n/))s.push(ht(a));return s}function bn(e){let t=e;for(;t;){let n=wm(t);if(n.length){let o=go(n);if(o)return o}let r=t.parent;if(!r||!bm.has(r.type))return;let s=t.previousNamedSibling;if(s&&!xm.test(s.type))return;t=r}}function Ec(e){let n=e.childForFieldName("body")?.namedChildren[0];if(!n)return;let r=n.type==="string"?n:n.type==="expression_statement"?n.namedChildren[0]:void 0;if(!(!r||r.type!=="string"))return go(r.text.split(/\r?\n/).map(ht))}var ym,bm,xm,vc=O(()=>{"use strict";S();xs();ym=/(^|_)comment$/,bm=new Set(["export_statement","ambient_declaration","decorated_definition","template_declaration","labeled_statement","lexical_declaration","variable_declaration","type_declaration","const_declaration","var_declaration","body_statement","body"]);xm=/decorator|annotation|modifiers/});function Lm(e){return e.namedChildren.every(t=>Dm.test(t.type))}function jm(e,t,n,r,s){let o=new Set,a=t.calls!==void 0,l=[],c=new Set,d=(w,k,C)=>{if(!w||w.length<2||!/^[A-Za-z_]\w*$/.test(w))return;let A=k.startPosition.row+1,F=`${w} ${A}`;c.has(F)||(c.add(F),l.push(C?{name:w,line:A,receiver:C}:{name:w,line:A}))},u=new Set,f=w=>{if(!(u.size>=Rc))for(let k of pt(w)){if(u.size>=Rc)return;u.add(k)}},p=new Ct,m=t.imports?.import_statement!==void 0,g=new Set,h=s&&t.imports!==void 0,_=[],y=new Set,x=w=>{let k=w.trim();k&&!y.has(k)&&(y.add(k),_.push({kind:"import",spec:k}))},E=w=>{let k=w.type,C=w.namedChildren;if(C.length===0&&Nm.test(k)){let A=w.text;Om.test(A)&&!n.has(A)&&o.add(A)}if(Fm.test(k))for(let A of w.text.split(/\r?\n/))f(ht(A));else C.length===0&&Mc.test(k)&&w.endIndex-w.startIndex<=Mm&&f(w.text.replace(/^['"`]+|['"`]+$/g,""));if(!p.full){let A=w.startPosition.row+1;Mc.test(k)&&Lm(w)?p.addString(w.text,A):C.length===0&&Pm.test(k)?p.add("number",w.text.trim(),A):$m.test(k)&&p.add("regex",w.text,A)}if(a&&!(t.kindFrom?.[k]&&t.kindFrom[k](w))&&!t.skipCall?.(w)){let A=t.calls[k];if(A==="function"){let F=w.childForFieldName("function")??w.childForFieldName("callee")??w.childForFieldName("method")??w.childForFieldName("name")??w.childForFieldName("target")??C[0]??null;d(Jt(F),w,Xn(F)??Xn(w))}else if(A==="member")d(Jt(w.childForFieldName("name")),w,Xn(w));else if(A==="constructor"){let F=w.childForFieldName("constructor")??w.childForFieldName("type")??w.childForFieldName("name");for(let N=0;!F&&N/string/.test(N.type));F&&x(F.text.replace(/^['"]|['"]$/g,""))}else if(A==="path"){let F=w.childForFieldName("name")??w.childForFieldName("module_name");x((F??w).text.replace(/^(import|from)\s+/,"").split(/\s+/)[0])}}for(let A of C)E(A)};return E(e),l.sort((w,k)=>R(w.name,k.name)||w.line-k.line),{refs:_,idents:[...o].sort().slice(0,Sm),calls:l.slice(0,r),importedNames:[...g].sort(R).slice(0,Em),terms:[...u].sort(R),literals:p.result()??[]}}function Um(e){let t=[],n=r=>{if(/^(shorthand_property_identifier_pattern|identifier)$/.test(r.type)){t.includes(r.text)||t.push(r.text);return}if(r.type==="pair_pattern"){let s=r.childForFieldName("value");s&&n(s);return}for(let s of r.namedChildren)n(s)};for(let r of e.namedChildren)n(r);return t}function _o(e,t,n,r={}){let s=Jn(t);if(!s||!Ye(s))return;let o=xc[s];if(!o)return;let a=hs(s);if(!a)return;let l=null;try{if(l=a.parse(n),!l)return;let c=r.maxSymbols??vm,d=[],u=l.rootNode,f=(e.split("/").pop()??"").replace(/\.[^.]+$/,""),p=new Set,m=P=>{d.length{let V=o.relationsFrom?.[P.type];if(V)for(let oe of V(P,{self:$})){if(oe.from===oe.to)continue;let ee=`${oe.kind} ${oe.from} ${oe.to}`;h.has(ee)||g.length>=Rm||(h.add(ee),g.push(oe))}},y=(P,$,V,oe)=>oe.inFunctionBody||o.privateMember?.(P)===!0?!1:o.publicMember?.(P)===!0?!0:oe.sectionPublic?oe.forcePublic?!0:oe.exported||o.exported($,V):!1,x=P=>o.docFrom?.(P)??(o.docstring?Ec(P):void 0)??bn(P),E=(P,$)=>{let V=$.sectionPublic,oe=o.bareMembers?.[P.type];for(let ee of P.namedChildren){if(o.sectionVisibility){let Ne=o.sectionVisibility(ee);if(Ne!==void 0){V=Ne;continue}}let le=V===$.sectionPublic?$:{...$,sectionPublic:V};if(oe&&ee.namedChildren.length===0&&ys.test(ee.type)){m({name:ee.text,kind:oe,file:e,line:ee.startPosition.row+1,endLine:ee.endPosition.row+1,...le.parent?{parent:le.parent}:{},exported:le.forcePublic||le.exported,lang:o.lang});continue}for(let Ne of o.extraMembers?.(ee,{ownerKind:le.ownerKind,inFunctionBody:le.inFunctionBody})??[]){let De=Tt(ee,n),Z=bn(ee);m({name:Ne.name,kind:Ne.kind,file:e,line:ee.startPosition.row+1,endLine:ee.endPosition.row+1,...le.parent?{parent:le.parent}:{},...le.parentPath&&le.parentPath!==le.parent?{parentPath:le.parentPath}:{},signature:De,...Z?{doc:Z}:{},exported:y(ee,De,Ne.name,le),lang:o.lang})}k(ee,le)}},w=(P,$)=>{let V=!1;for(let oe of P.namedChildren)o.containers.has(oe.type)&&(V=!0,E(oe,$));!V&&o.containers.has(P.type)&&E(P,$)},k=(P,$)=>{if($.funcDepth>Cm)return;let V=P.type,oe=o.exportMarkers?.has(V)===!0,ee=$.exported||oe;if(V==="export_statement"){for(let Z of P.namedChildren)if(Z.type==="identifier")p.add(Z.text);else if(Z.type==="export_clause")for(let Y of Z.namedChildren){let L=Y.childForFieldName("name")??Y.namedChildren[0];L?.text&&p.add(L.text)}if(f&&P.children.some(Z=>Z.type==="default"))for(let Z of P.namedChildren){let Y=Tm.has(Z.type),L=Im.has(Z.type);if((Y||L)&&!Z.childForFieldName("name")){let de=bn(P);m({name:f,kind:L?"class":"function",file:e,line:P.startPosition.row+1,endLine:P.endPosition.row+1,signature:Tt(P,n),...de?{doc:de}:{},exported:!0,lang:o.lang});break}}}if(o.assignments&&V==="expression_statement"){let Z=P.namedChildren[0];if(Z?.type==="assignment_expression"){let Y=Z.childForFieldName("left"),L=Z.childForFieldName("right");if(Y?.type==="member_expression"&&Y.text==="module.exports"&&L){if(L.type==="object"){for(let J of L.namedChildren)if(J.type==="shorthand_property_identifier")p.add(J.text);else if(J.type==="pair"){let ce=J.childForFieldName("key"),be=J.childForFieldName("value");ce?.type==="property_identifier"&&p.add(ce.text),be?.type==="identifier"&&p.add(be.text)}return}if(L.type==="identifier"){p.add(L.text);return}}let de=L&&ws.has(L.type);if(Y&&L&&de){let J,ce=!1;if(Y.type==="member_expression"){let be=Y.childForFieldName("property");if(be?.type==="property_identifier"){J=be.text;let ut=Y.text.slice(0,Y.text.length-be.text.length-1);ce=ut==="exports"||ut==="module.exports"}}else Y.type==="identifier"&&(J=Y.text);if(J){let be=bn(P);m({name:J,kind:L.type==="class"?"class":"function",file:e,line:Z.startPosition.row+1,endLine:Z.endPosition.row+1,...$.parent?{parent:$.parent}:{},signature:Tt(Z,n),...be?{doc:be}:{},exported:!$.inFunctionBody&&(ee||ce),lang:o.lang});return}}else if(Y?.type==="member_expression"&&L){let J=Y.childForFieldName("property");if(J?.type==="property_identifier"){let ce=Y.text.slice(0,Y.text.length-J.text.length-1);if(ce==="exports"||ce==="module.exports"){L.type==="identifier"&&p.add(L.text),(L.type!=="identifier"||L.text!==J.text)&&m({name:J.text,kind:"const",file:e,line:Z.startPosition.row+1,endLine:Z.endPosition.row+1,...$.parent?{parent:$.parent}:{},signature:Tt(Z,n),exported:!0,lang:o.lang});return}}}}}if(o.assignments&&V==="assignment_statement"){let Z=P.children.find(ce=>ce.type==="variable_list"),Y=P.children.find(ce=>ce.type==="expression_list"),L=Z?.namedChildren??[],de=Y?.namedChildren??[],J=Math.min(L.length,de.length);for(let ce=0;ceJ.type==="object_pattern"||J.type==="array_pattern");if(L&&!$.inFunctionBody){let J=Tt(P,n),ce=x(P);for(let be of Um(L))m({name:be,kind:De,file:e,line:P.startPosition.row+1,endLine:P.endPosition.row+1,...$.parent?{parent:$.parent}:{},signature:J,...ce?{doc:ce}:{},exported:y(P,J,be,{...$,exported:ee}),lang:o.lang});return}let de=fo.has(De)||Am.has(De)||o.nestedDefs?.has(V)===!0||ws.has(P.childForFieldName("value")?.type??"");if(Y&&(!$.inFunctionBody||de)){let J=Tt(P,n),ce=x(P),be=le??$.parent,ut=le??$.parentPath;m({name:Y,kind:De,file:e,line:P.startPosition.row+1,endLine:P.endPosition.row+1,...be?{parent:be}:{},...ut&&ut!==be?{parentPath:ut}:{},signature:J,...ce?{doc:ce}:{},exported:y(P,J,Y,{...$,exported:ee}),lang:o.lang}),_(P,Y);let Fn=fo.has(De);w(P,{parent:Y,parentPath:ut?`${ut}/${Y}`:Y,ownerKind:De,exported:ee,forcePublic:wc.has(De),inFunctionBody:$.inFunctionBody||Fn,funcDepth:$.funcDepth+(Fn?1:0),sectionPublic:!0});return}}if(_(P,le??$.parent),o.containers.has(V)){let Z=$.forcePublic||o.publicMembersIn?.[V]?.(P)===!0,Y=ws.has(V);E(P,{...$,exported:ee,forcePublic:Z,inFunctionBody:$.inFunctionBody||Y,funcDepth:$.funcDepth+(Y?1:0),...le?{parent:le,parentPath:le,ownerKind:"type"}:{}})}};if(E(u,{exported:!1,forcePublic:!1,inFunctionBody:!1,funcDepth:0,sectionPublic:!0}),p.size)for(let P of d)!P.exported&&p.has(P.name)&&(P.exported=!0);let C=r.imports!==!1,{refs:A,idents:F,calls:N,importedNames:W,terms:q,literals:X}=jm(u,o,new Set(d.map(P=>P.name)),r.maxCalls??km,C),B;if(C&&o.lang==="java"){let P=Ce(u,$=>$.type==="package_declaration");P&&(B=P.text.replace(/^package\s+/,"").replace(/;.*$/,"").trim())}return g.sort((P,$)=>R(P.from,$.from)||R(P.kind,$.kind)||R(P.to,$.to)),{symbols:d,refs:A,pkg:B,idents:F,calls:N,importedNames:W,relations:g,terms:q,literals:X,...d.length>=c?{truncated:!0}:{}}}catch{return}finally{l?.delete()}}var Sm,km,Em,vm,Rm,Rc,Mm,Cm,Am,Tm,Im,Nm,Om,Fm,Mc,Pm,$m,Dm,ho=O(()=>{"use strict";S();ds();K();Qe();lo();Sc();kc();vc();xs();Me();Sm=512,km=512,Em=256,vm=2e3,Rm=256,Rc=512,Mm=80,Cm=2,Am=new Set(["class","struct","enum","interface","trait","type","record","union"]),Tm=new Set(["function","function_expression","function_declaration","generator_function","generator_function_declaration","arrow_function"]),Im=new Set(["class","class_declaration","abstract_class_declaration"]),Nm=/identifier|constant|(^|_)name$/,Om=/^[A-Za-z_]\w{4,}$/,Fm=/(^|_)comment$/,Mc=/(^|_)string(_literal)?$/,Pm=/(^|_)(integer|float|number|decimal|numeric)(_literal)?$/,$m=/(^|_)(regex|regular_expression)(_pattern|_literal)?$/,Dm=/(^|_)(fragment|content|escape_sequence|character)$/});function Gm(e){let t=e.split(/\r?\n/),n=[],r=null;for(let a=0;aa&&!mo(a)&&!po(a)).join(" ").replace(/\s+/g," ").trim();if(s.length<8)return;let o=/^(.*?[.!?])(\s|$)/.exec(s);return(o?o[1]:s).slice(0,200)}function bo(e,t=[]){if(t.length>=qm)return t;let n=e.indexOf("{");if(n===-1){let c=e.replace(/\s+as\s+\w+\s*$/,"").replace(/::\s*\*\s*$/,"").replace(/^::/,"").trim();return c&&t.push(c),t}let r=e.slice(0,n),s=0,o=-1;for(let c=n;c({kind:"import",spec:s}))}function Km(e,t=[],n=512){let r=new Map,s=new Set(t.map(l=>`${l.name} ${l.line}`)),o=e.split(` -`),a=/(?:\bnew\s+)?(?:([A-Za-z_$][\w$]*)\s*\.\s*)?([A-Za-z_$][\w$]*)\s*\(/g;for(let l=0;ll.namec.name?1:l.line-c.line)}function Zm(e){let t=new Set,n=s=>{if(!(t.size>=yo))for(let o of pt(s)){if(t.size>=yo)return;t.add(o)}},r=!1;for(let s of e.split(` -`)){if(t.size>=yo)break;let o=s;if(r){let c=o.indexOf("*/");if(n(ht(c===-1?o:o.slice(0,c))),c===-1)continue;r=!1,o=o.slice(c+2)}let a=o.indexOf("/*");if(a!==-1){let c=o.indexOf("*/",a+2);n(ht(o.slice(a,c===-1?void 0:c))),c===-1?(r=!0,o=o.slice(0,a)):o=o.slice(0,a)+o.slice(c+2)}let l=/(^|\s)(\/\/|#|--)(.*)$/.exec(o);l&&(n(ht(l[2]+l[3])),o=o.slice(0,l.index));for(let c of o.matchAll(/(['"`])((?:\\.|(?!\1)[^\\])*)\1/g)){let d=c[2];d.length&&d.length<=Xm&&n(d)}}return[...t].sort()}function Ym(e){let t=new Ct,n=!1,r=0;for(let s of e.split(` -`)){if(r++,t.full)break;let o=s;if(n){let c=o.indexOf("*/");if(c===-1)continue;n=!1,o=o.slice(c+2)}let a=o.indexOf("/*");if(a!==-1){let c=o.indexOf("*/",a+2);c===-1?(n=!0,o=o.slice(0,a)):o=o.slice(0,a)+o.slice(c+2)}let l=/(^|\s)(\/\/|#|--)(.*)$/.exec(o);l&&(o=o.slice(0,l.index));for(let c of o.matchAll(/(['"`])((?:\\.|(?!\1)[^\\])*)\1/g))t.add("string",c[2],r);for(let c of o.replace(/(['"`])(?:\\.|(?!\1)[^\\])*\1/g," ").matchAll(/(?p.name)),c=os(e,n,a).filter(p=>!l.has(p.name)),d=Vm(t,n),u=new Set(d.map(p=>p.spec)),f=(s?s.literals.length?s.literals:void 0:Ym(n))?.filter(p=>!(p.kind==="string"&&u.has(p.value)));return{symbols:[...a,...c],...s?.truncated||o.length>a.length||c.length>=is?{truncated:!0}:{},summary:Gm(n),refs:d,pkg:t===".java"?/^\s*package\s+([\w.]+)\s*;/m.exec(n)?.[1]:t===".cs"?/^\s*(?:file-scoped\s+)?namespace\s+([\w.]+)/m.exec(n)?.[1]:void 0,idents:s?.idents,calls:s?s.calls:Km(n,a,r.maxCallsPerFile),importedNames:s?.importedNames,relations:s?.relations?.length?s.relations:void 0,terms:s?s.terms:Zm(n),literals:f?.length?f:void 0}}var Wm,Bm,Hm,zm,qm,Jm,Cc,yo,Xm,wo=O(()=>{"use strict";S();ds();_n();ho();Ee();xs();Me();Wm=2e3,Bm=new Set([".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs"]),Hm=new Set([".py",".pyi"]),zm=new Set([".c",".h",".cc",".cpp",".cxx",".hpp",".hh"]);qm=16;Jm=new Set(["if","else","elif","for","while","do","switch","case","match","when","unless","until","catch","except","return","throw","raise","yield","await","typeof","instanceof","sizeof","delete","void","in","of","not","and","or","assert","defer","select","with","loop"]),Cc=/(?:\bfunction|\bdef|\bfunc|\bfun|\bfn|\bclass|\bsub|\bmacro|\bproc)\s*[*]?\s*$/;yo=512,Xm=80});function Tc(e){let t=new Ct,n=0;for(let r of e.split(` -`)){if(n++,t.full)break;let s=np(r);for(let a of s.matchAll(Ac))t.add("string",a[2],n);let o=tp.exec(s);if(o){let a=o[1].trim();a&&!/^[[{|>&*-]/.test(a)&&!Qm.test(a)&&t.add("string",a,n)}for(let a of s.replace(Ac," ").matchAll(ep))t.add("number",a[0].replace(/_/g,""),n)}return t.result()}function np(e){let t;for(let n=0;n{"use strict";S();ds();Ac=/(['"])((?:\\.|(?!\1)[^\\])*)\1/g,Qm=/(['"])((?:\\.|(?!\1)[^\\])*)\1/,ep=/(?f.rel)),a!==void 0&&n.length!==a.size&&(l=!1,c=!0),{root:e,commit:ns(e),files:n,languages:r,docText:s,mtimes:o,capped:u.value.capped,excluded:u.value.excluded,contentUnchanged:l,cacheDirty:c}}var It=O(()=>{"use strict";S();ie();Te();Gt();Rt();Bi();_n();Un();K();Gi();wo();Ic()});function Nt(e){let t=new Map;for(let n of e.files)t.set(n.rel,{hash:n.hash,record:n,size:n.size,mtimeMs:e.mtimes.get(n.rel)});return t}function Oc(e,t=yt){let n;try{n=JSON.parse(te(I(e,t,"cache.json"),"utf8"))}catch{return}if(!(!n||n.schemaVersion!==5||n.extractorVersion!==13||!n.files))return{cacheMap:new Map(Object.entries(n.files)),meta:{engineVersion:n.engineVersion,commit:n.commit,graphSha1:n.graphSha1,symbolsSha1:n.symbolsSha1}}}function Fc(e,t,n,r=yt){if(!t.contentUnchanged||n.engineVersion!==fe||n.commit!==t.commit||n.graphSha1===void 0||n.symbolsSha1===void 0)return;let s=I(e,r),o,a;try{o=te(I(s,"graph.json")),a=te(I(s,"symbols.json"))}catch{return}if(!(ve(o)!==n.graphSha1||ve(a)!==n.symbolsSha1))try{let l=JSON.parse(o.toString("utf8")),c=JSON.parse(a.toString("utf8"));return l.schemaVersion!==5||c.schemaVersion!==5?void 0:{scan:t,graph:l,symbols:c}}catch{return}}function er(e,t,n=yt){let r=Oc(e,n);if(!r)return;let s=Pe(e,{...t,cache:r.cacheMap});return{scan:s,cacheMap:Nt(s),arts:Fc(e,s,r.meta,n)}}var yt,tr=O(()=>{"use strict";S();we();ie();qe();It();Rt();yt=".codeindex"});function Tp(e){let t=xe(e).split("/").filter(s=>s!=="."),n=[],r=0;for(;rt?1:0)}function Ao(e){let t="",n=!1;for(let s=0;shm.test(l)&&!l.includes("external_scanner_"));if(!o)throw console.log(`Couldn't find language function in Wasm file. Symbols: +${JSON.stringify(s,null,2)}`),new Error("Language.load failed: no language function found in Wasm file");let a=r[o]();return new fc(Nt,a)}};C(mc,"Module");ym=mc,pc=null;C(gc,"initializeBinding");C(_c,"checkModule");fo=class{static{C(this,"Parser")}0=0;1=0;logCallback=null;language=null;static async init(e){ac(await gc(e)),D=w._ts_init(),io=w.getValue(D,"i32"),oo=w.getValue(D+W,"i32")}constructor(){this.initialize()}initialize(){if(!_c())throw new Error("cannot construct a Parser before calling `init()`");w._ts_parser_new_wasm(),this[0]=w.getValue(D,"i32"),this[1]=w.getValue(D+W,"i32")}delete(){w._ts_parser_delete(this[0]),w._free(this[1]),this[0]=0,this[1]=0}setLanguage(e){let t;if(!e)t=0,this.language=null;else if(e.constructor===uo){t=e[0];let n=w._ts_language_abi_version(t);if(ne.slice(l);else if(typeof e=="function")w.currentParseCallback=e;else throw new Error("Argument must be a string or a function");n?.progressCallback?w.currentProgressCallback=n.progressCallback:w.currentProgressCallback=null,this.logCallback?(w.currentLogCallback=this.logCallback,w._ts_parser_enable_logger_wasm(this[0],1)):(w.currentLogCallback=null,w._ts_parser_enable_logger_wasm(this[0],0));let r=0,s=0;if(n?.includedRanges){r=n.includedRanges.length,s=w._calloc(r,Jn);let l=s;for(let c=0;c0){let r=t;for(let s=0;se.type==="capture","isCaptureStep"),mo=C(e=>e.type==="string","isStringStep"),Ye={Syntax:1,NodeName:2,FieldName:3,CaptureName:4,PatternStructure:5},Gn=class hc extends Error{constructor(t,n,r,s){super(hc.formatMessage(t,n)),this.kind=t,this.info=n,this.index=r,this.length=s,this.name="QueryError"}static{C(this,"QueryError")}static formatMessage(t,n){switch(t){case Ye.NodeName:return`Bad node name '${n.word}'`;case Ye.FieldName:return`Bad field name '${n.word}'`;case Ye.CaptureName:return`Bad capture name @${n.word}`;case Ye.PatternStructure:return`Bad pattern structure at offset ${n.suffix}`;case Ye.Syntax:return`Bad syntax at offset ${n.suffix}`}}};C(yc,"parseAnyPredicate");C(bc,"parseMatchPredicate");C(wc,"parseAnyOfPredicate");C(xc,"parseIsPredicate");C(Sc,"parseSetDirective");C(kc,"parsePattern");Ec=class{static{C(this,"Query")}0=0;exceededMatchLimit;textPredicates;captureNames;captureQuantifiers;predicates;setProperties;assertedProperties;refutedProperties;matchLimit;constructor(e,t){let n=w.lengthBytesUTF8(t),r=w._malloc(n+1);w.stringToUTF8(t,r,n+1);let s=w._ts_query_new(e[0],r,n,D,D+W);if(!s){let h=w.getValue(D+W,"i32"),S=w.getValue(D,"i32"),_=w.UTF8ToString(r,S).length,E=t.slice(_,_+100).split(` +`)[0],b=E.match(xm)?.[0]??"";switch(w._free(r),h){case Ye.Syntax:throw new Gn(Ye.Syntax,{suffix:`${_}: '${E}'...`},_,0);case Ye.NodeName:throw new Gn(h,{word:b},_,b.length);case Ye.FieldName:throw new Gn(h,{word:b},_,b.length);case Ye.CaptureName:throw new Gn(h,{word:b},_,b.length);case Ye.PatternStructure:throw new Gn(h,{suffix:`${_}: '${E}'...`},_,0)}}let o=w._ts_query_string_count(s),a=w._ts_query_capture_count(s),l=w._ts_query_pattern_count(s),c=new Array(a),d=new Array(l),f=new Array(o);for(let h=0;ho)throw new Error("`startIndex` cannot be greater than `endIndex`");if(r!==$e&&(n.row>r.row||n.row===r.row&&n.column>r.column))throw new Error("`startPosition` cannot be greater than `endPosition`");if(d!==0&&c>d)throw new Error("`startContainingIndex` cannot be greater than `endContainingIndex`");if(l!==$e&&(a.row>l.row||a.row===l.row&&a.column>l.column))throw new Error("`startContainingPosition` cannot be greater than `endContainingPosition`");m&&(w.currentQueryProgressCallback=m),q(e),w._ts_query_matches_wasm(this[0],e.tree[0],n.row,n.column,r.row,r.column,s,o,a.row,a.column,l.row,l.column,c,d,f,u);let p=w.getValue(D,"i32"),g=w.getValue(D+W,"i32"),y=w.getValue(D+2*W,"i32"),h=new Array(p);this.exceededMatchLimit=!!y;let S=0,_=g;for(let E=0;EA(v))){h[S]={patternIndex:b,captures:v};let A=this.setProperties[b];h[S].setProperties=A;let O=this.assertedProperties[b];h[S].assertedProperties=O;let N=this.refutedProperties[b];h[S].refutedProperties=N,S++}}return h.length=S,w._free(g),w.currentQueryProgressCallback=null,h}captures(e,t={}){let n=t.startPosition??$e,r=t.endPosition??$e,s=t.startIndex??0,o=t.endIndex??0,a=t.startContainingPosition??$e,l=t.endContainingPosition??$e,c=t.startContainingIndex??0,d=t.endContainingIndex??0,f=t.matchLimit??4294967295,u=t.maxStartDepth??4294967295,m=t.progressCallback;if(typeof f!="number")throw new Error("Arguments must be numbers");if(this.matchLimit=f,o!==0&&s>o)throw new Error("`startIndex` cannot be greater than `endIndex`");if(r!==$e&&(n.row>r.row||n.row===r.row&&n.column>r.column))throw new Error("`startPosition` cannot be greater than `endPosition`");if(d!==0&&c>d)throw new Error("`startContainingIndex` cannot be greater than `endContainingIndex`");if(l!==$e&&(a.row>l.row||a.row===l.row&&a.column>l.column))throw new Error("`startContainingPosition` cannot be greater than `endContainingPosition`");m&&(w.currentQueryProgressCallback=m),q(e),w._ts_query_captures_wasm(this[0],e.tree[0],n.row,n.column,r.row,r.column,s,o,a.row,a.column,l.row,l.column,c,d,f,u);let p=w.getValue(D,"i32"),g=w.getValue(D+W,"i32"),y=w.getValue(D+2*W,"i32"),h=new Array;this.exceededMatchLimit=!!y;let S=new Array,_=g;for(let E=0;EA(S))){let A=S[v],O=this.setProperties[b];A.setProperties=O;let N=this.assertedProperties[b];A.assertedProperties=N;let U=this.refutedProperties[b];A.refutedProperties=U,h.push(A)}}return w._free(g),w.currentQueryProgressCallback=null,h}predicatesForPattern(e){return this.predicates[e]}disableCapture(e){let t=w.lengthBytesUTF8(e),n=w._malloc(t+1);w.stringToUTF8(e,n,t+1),w._ts_query_disable_capture(this[0],n,t),w._free(n)}disablePattern(e){if(e>=this.predicates.length)throw new Error(`Pattern index is ${e} but the pattern count is ${this.predicates.length}`);w._ts_query_disable_pattern(this[0],e)}didExceedMatchLimit(){return this.exceededMatchLimit}startIndexForPattern(e){if(e>=this.predicates.length)throw new Error(`Pattern index is ${e} but the pattern count is ${this.predicates.length}`);return w._ts_query_start_byte_for_pattern(this[0],e)}endIndexForPattern(e){if(e>=this.predicates.length)throw new Error(`Pattern index is ${e} but the pattern count is ${this.predicates.length}`);return w._ts_query_end_byte_for_pattern(this[0],e)}patternCount(){return w._ts_query_pattern_count(this[0])}captureIndexForName(e){return this.captureNames.indexOf(e)}isPatternRooted(e){return w._ts_query_is_pattern_rooted(this[0],e)===1}isPatternNonLocal(e){return w._ts_query_is_pattern_non_local(this[0],e)===1}isPatternGuaranteedAtStep(e){return w._ts_query_is_pattern_guaranteed_at_step(this[0],e)===1}}});function Yn(e){return Es[e]}function wn(){let e=R.env.XDG_CACHE_HOME,t=e&&e.trim()?e.trim():I(rc(),".cache");return I(t,"codeindex","grammars",fe)}function Qe(e={}){let t=wn(),n=(l,c)=>({tier:l,dir:c,cacheDir:t,dirs:[c,...H(I(c,"..",vc))?[I(c,"..",vc)]:[]]}),r=R.env.CODEINDEX_GRAMMAR_DIR??R.env.ULTRAINDEX_GRAMMAR_DIR;if(r&&r.trim()&&H(r))return n("env",r);let s=e.moduleDir??_e(bs(import.meta.url)),o=[I(s,"grammars"),I(s,"..","..","scripts","grammars"),I(s,"..","scripts","grammars")];for(let l of o)if(H(l))return n("adjacent",l);let a=R.env.CODEINDEX_GRAMMARS_DIR;return a&&a.trim()&&H(a)?n("env",a):H(t)?n("cache",t):{tier:"none",cacheDir:t,dirs:[]}}function Sm(e){return Qe(e).dir}async function et(e){let{dirs:t}=Qe();if(!t.length)return;let n=r=>{for(let s of t){let o=I(s,r);if(H(o))return o}};if(!Rc){let r=n("web-tree-sitter.wasm");if(!r)return;await fo.init({wasmBinary:te(r)}),Rc=!0,ks=new fo}for(let r of new Set(e)){if(Kn.has(r))continue;let s=n(`${r}.wasm`),o=s?(()=>{try{let a=Ee(s);return`${s}:${a.size}:${a.mtimeMs}`}catch{return`${s}:unreadable`}})():`missing:${t.join("|")}`;if(Ss.get(r)!==o){if(!s){Ss.set(r,o);continue}try{Kn.set(r,await uo.load(new Uint8Array(te(s)))),Ss.delete(r)}catch{Ss.set(r,o)}}}}function go(){return[...new Set(Object.values(Es))]}function bt(e){let t=new Set;for(let n of e){let r=Es[n];r!==void 0&&t.add(r)}return[...t].sort()}function tt(e){return Kn.has(e)}function _o(e){return Kn.get(e)}function vs(e){let t=Kn.get(e);return!ks||!t?null:(ks.setLanguage(t),ks)}var Xn,Zn,Es,vc,Rc,ks,Kn,Ss,nt=F(()=>{"use strict";k();xe();to();oe();ws();po();Xe();Xn=new Set(["typescript","tsx","javascript","python","go","rust","java","ruby","c","cpp","c_sharp","php","scala","bash","lua"]),Zn=new Set(["kotlin","elixir","zig","hcl","terraform","solidity"]),Es={".ts":"typescript",".mts":"typescript",".cts":"typescript",".tsx":"tsx",".js":"javascript",".jsx":"javascript",".mjs":"javascript",".cjs":"javascript",".py":"python",".pyi":"python",".go":"go",".rs":"rust",".java":"java",".rb":"ruby",".rake":"ruby",".c":"c",".h":"c",".cc":"cpp",".cpp":"cpp",".cxx":"cpp",".hpp":"cpp",".hh":"cpp",".cs":"c_sharp",".php":"php",".scala":"scala",".sc":"scala",".sh":"bash",".bash":"bash",".lua":"lua",".kt":"kotlin",".kts":"kotlin",".ex":"elixir",".exs":"elixir",".zig":"zig",".hcl":"hcl",".tf":"terraform",".tfvars":"terraform",".sol":"solidity"};vc="grammars-extended";Rc=!1,ks=null,Kn=new Map,Ss=new Map});function Te(e,t){for(let n of e.namedChildren){if(t(n))return n;let r=Te(n,t);if(r)return r}}function Qn(e){let t=e.childForFieldName("name");if(t?.text)return t.text;let n=e.childForFieldName("declarator");for(;n;){let o=n.childForFieldName("name");if(o?.text)return o.text;if(n.namedChildren.length===0&&/(^|_)identifier$/.test(n.type))return n.text;let a=n.childForFieldName("declarator");if(!a||a===n)break;n=a}let s=Te(e,o=>o.type==="variable_declarator")?.childForFieldName("name");if(s?.text)return s.text;for(let o of e.namedChildren)if(/(^|_)(identifier|name|constant)$/.test(o.type))return o.text}function Kt(e){if(!e)return;let t=e.namedChildren;if(t.length===0)return Rs.test(e.type)?e.text:void 0;let n=e.childForFieldName("name")??e.childForFieldName("property")??e.childForFieldName("attribute")??e.childForFieldName("field")??e.childForFieldName("function");if(n)return Kt(n);let r=t[t.length-1];return r&&r!==e?Kt(r):void 0}function er(e){if(!e||e.namedChildren.length===0)return;let t=e.childForFieldName("object")??e.childForFieldName("operand")??e.childForFieldName("value")??e.childForFieldName("path")??e.childForFieldName("expression")??e.childForFieldName("argument")??e.childForFieldName("receiver")??e.childForFieldName("table"),n=t?Kt(t):void 0;return n&&/^[A-Za-z_]\w*$/.test(n)?n:void 0}function ze(e){if(!e)return;let t=e.childForFieldName("type")??e.childForFieldName("name");if(t&&/generic|qualified|scoped|nested/.test(e.type))return ze(t);if(e.namedChildren.length===0)return Mc.test(e.type)?e.text:void 0;let n,r=s=>{if(s.namedChildren.length===0){Mc.test(s.type)&&(n=s.text);return}if(!/arguments|parameters/.test(s.type))for(let o of s.namedChildren)r(o)};return r(e),n}var Rs,Mc,ho=F(()=>{"use strict";k();Rs=/(^|_)(identifier|name|constant|word)$/;Mc=/identifier|constant|(^|_)name$/});function Oe(e){if(!e)return[];let t=[];for(let n of e.namedChildren){if(/arguments|parameters/.test(n.type))continue;let r=ze(n);r&&t.push(r)}return t}function Cc(e,t){if(!t.self)return[];let n=he(e,"class_heritage");if(!n)return[];let r=[];for(let s of Oe(he(n,"extends_clause")))r.push(ge("extends",t.self,s,e));for(let s of Oe(he(n,"implements_clause")))r.push(ge("implements",t.self,s,e));return r}function tr(e,t,n){return Oe(e).map((s,o)=>ge(o===0?"extends":"implements",t,s,n))}var he,ge,Fc,wo,Cs,Ac,yo,km,Tc,Ic,Em,nr,vm,Ms,Nc,Rm,Oc,bo,Pc,$c=F(()=>{"use strict";k();ho();he=(e,t)=>e.namedChildren.find(n=>n.type===t),ge=(e,t,n,r)=>({kind:e,from:t,to:n,line:r.startPosition.row+1});Fc=new Set(["interface","trait","enum","protocol","annotation"]),wo=new Set(["function","method","def","constructor","operator"]),Cs=new Set(["function","function_expression","arrow_function","generator_function","class","function_definition","lambda"]),Ac=e=>/\b(public|internal)\b/.test(e),yo=e=>!/\b(private|protected)\b/.test(e),km=e=>!/^local\b/.test(e),Tc=e=>/\bpub\b/.test(e),Ic=(e,t)=>/^[A-Z]/.test(t),Em=(e,t)=>!t.startsWith("_")||/^__\w+__$/.test(t),nr=()=>!0,vm=()=>!1,Ms=e=>Te(e,t=>t.type==="function_declarator")!==void 0,Nc={defmodule:"module",defprotocol:"protocol",defimpl:"impl",defstruct:"struct",defexception:"exception",def:"function",defp:"function",defmacro:"macro",defmacrop:"macro",defguard:"guard",defguardp:"guard",defdelegate:"function"},Rm=new Set(["resource","data","variable","output","module","provider","locals","terraform"]),Oc={lang:"terraform",defs:{block:"block"},containers:new Set(["config_file","body"]),exported:nr,kindFrom:{block:e=>{let t=e.namedChildren.find(n=>n.type==="identifier")?.text;return t&&Rm.has(t)?t:void 0}},nameFrom:{block:e=>{let t=e.namedChildren.filter(n=>n.type==="string_lit").map(n=>n.text.replace(/^"|"$/g,""));return t.length?t.join("."):e.namedChildren.find(n=>n.type==="identifier")?.text}}},bo={lang:"typescript",defs:{function_declaration:"function",generator_function_declaration:"function",function_signature:"function",class_declaration:"class",abstract_class_declaration:"class",interface_declaration:"interface",type_alias_declaration:"type",enum_declaration:"enum",enum_assignment:"enum-member",method_definition:"method",method_signature:"method",abstract_method_signature:"method",property_signature:"property",public_field_definition:"property",call_signature:"call-signature",construct_signature:"construct-signature",index_signature:"index-signature",internal_module:"namespace",module:"namespace",variable_declarator:"const"},containers:new Set(["class_body","export_statement","ambient_declaration","program","lexical_declaration","variable_declaration","interface_body","object_type","enum_body","statement_block","try_statement","catch_clause","finally_clause","if_statement","else_clause","for_statement","for_in_statement","while_statement","do_statement","switch_statement","switch_body","switch_case","switch_default","labeled_statement","return_statement","expression_statement","call_expression","arguments","arrow_function","function_expression","function","parenthesized_expression"]),exported:vm,exportMarkers:new Set(["export_statement","ambient_declaration"]),bareMembers:{enum_body:"enum-member"},nameFrom:{call_signature:()=>"(call)",construct_signature:()=>"(construct)",index_signature:e=>`[${e.namedChildren.find(t=>t.type==="identifier")?.text??"key"}]`},privateMember:e=>{for(let t of e.namedChildren)if(t.type==="accessibility_modifier"&&/^(private|protected)/.test(t.text)||t.type==="private_property_identifier")return!0;return!1},imports:{import_statement:"string"},calls:{call_expression:"function",new_expression:"constructor"},assignments:!0,relationsFrom:{class_declaration:Cc,abstract_class_declaration:Cc,interface_declaration:(e,t)=>t.self?Oe(he(e,"extends_type_clause")).map(n=>ge("extends",t.self,n,e)):[]}},Pc={typescript:bo,tsx:{...bo,lang:"typescript"},javascript:{...bo,lang:"javascript",defs:{function_declaration:"function",generator_function_declaration:"function",class_declaration:"class",method_definition:"method",field_definition:"property",variable_declarator:"const"}},python:{lang:"python",defs:{function_definition:"function",class_definition:"class"},containers:new Set(["block","decorated_definition","module"]),exported:Em,imports:{import_statement:"path",import_from_statement:"path"},calls:{call:"function"},docstring:!0,relationsFrom:{class_definition:(e,t)=>t.self?Oe(e.childForFieldName("superclasses")).map(n=>ge("extends",t.self,n,e)):[]},extraMembers:(e,t)=>{if(t.inFunctionBody)return[];if(e.type==="import_from_statement"){let s=[];for(let o of e.namedChildren){if(o.type!=="aliased_import")continue;let a=o.namedChildren[0]?.text,l=o.childForFieldName("alias")?.text;a&&l&&a===l&&s.push({name:l,kind:"reexport"})}return s}if(e.type!=="expression_statement")return[];let n=e.namedChildren[0];if(!n||n.type!=="assignment")return[];let r=n.childForFieldName("left");return!r||r.type!=="identifier"?[]:[{name:r.text,kind:t.ownerKind==="class"?"field":"const"}]}},go:{lang:"go",defs:{function_declaration:"function",method_declaration:"method",type_spec:"type",const_spec:"const",var_spec:"var",field_declaration:"field",method_spec:"method",method_elem:"method",package_clause:"package"},containers:new Set(["type_declaration","const_declaration","var_declaration","var_spec_list","source_file","struct_type","interface_type","field_declaration_list"]),exported:Ic,imports:{import_declaration:"string"},calls:{call_expression:"function"},parentFrom:{method_declaration:e=>ze(e.childForFieldName("receiver"))},nameFrom:{field_declaration:e=>e.childForFieldName("name")?.text},relationsFrom:{field_declaration:(e,t)=>{if(!t.self||e.childForFieldName("name"))return[];let n=ze(e.childForFieldName("type"));return n?[ge("extends",t.self,n,e)]:[]}}},ruby:{lang:"ruby",defs:{method:"def",singleton_method:"def",class:"class",module:"module"},containers:new Set(["class","module","body_statement","program"]),exported:nr,calls:{call:"function"},sectionVisibility:e=>(e.type==="identifier"||e.type==="call")&&/^(private|protected)$/.test(e.text)?!1:e.type==="identifier"&&e.text==="public"?!0:void 0,relationsFrom:{class:(e,t)=>{if(!t.self)return[];let n=ze(e.childForFieldName("superclass"));return n?[ge("extends",t.self,n,e)]:[]},call:(e,t)=>{let n=e.childForFieldName("method");if(!t.self||!n||!/^(include|prepend|extend)$/.test(n.text))return[];let r=[];for(let s of e.childForFieldName("arguments")?.namedChildren??[]){let o=ze(s);o&&r.push(ge("implements",t.self,o,e))}return r}},extraMembers:(e,t)=>{if(t.inFunctionBody)return[];if(e.type==="assignment"){let n=e.childForFieldName("left");return n?.type==="constant"?[{name:n.text,kind:"const"}]:[]}if(e.type==="call"){let n=e.childForFieldName("method");if(!n||!/^attr_(reader|writer|accessor)$/.test(n.text))return[];let r=e.childForFieldName("arguments"),s=[];for(let o of r?.namedChildren??[])o.type==="simple_symbol"&&s.push({name:o.text.replace(/^:/,""),kind:"attr"});return s}return[]}},java:{lang:"java",defs:{class_declaration:"class",interface_declaration:"interface",annotation_type_declaration:"annotation",enum_declaration:"enum",enum_constant:"enum-member",record_declaration:"record",method_declaration:"method",constructor_declaration:"constructor",compact_constructor_declaration:"constructor",field_declaration:"field",constant_declaration:"field",annotation_type_element_declaration:"method"},containers:new Set(["class_body","interface_body","enum_body","enum_body_declarations","annotation_type_body","program","formal_parameters"]),exported:Ac,imports:{import_declaration:"path"},calls:{method_invocation:"function",object_creation_expression:"constructor"},kindFrom:{formal_parameter:e=>e.parent?.parent?.type==="record_declaration"?"field":void 0},publicMember:e=>e.parent?.parent?.type==="record_declaration",nameFrom:{field_declaration:e=>Te(e,t=>t.type==="variable_declarator")?.childForFieldName("name")?.text,constant_declaration:e=>Te(e,t=>t.type==="variable_declarator")?.childForFieldName("name")?.text},relationsFrom:{class_declaration:(e,t)=>{if(!t.self)return[];let n=[];for(let s of Oe(e.childForFieldName("superclass")))n.push(ge("extends",t.self,s,e));let r=e.childForFieldName("interfaces");for(let s of Oe(he(r??e,"type_list")??r))n.push(ge("implements",t.self,s,e));return n},interface_declaration:(e,t)=>{let n=e.childForFieldName("interfaces")??he(e,"extends_interfaces");return t.self?Oe(he(n??e,"type_list")??n).map(r=>ge("extends",t.self,r,e)):[]},record_declaration:(e,t)=>{let n=e.childForFieldName("interfaces");return t.self?Oe(he(n??e,"type_list")??n).map(r=>ge("implements",t.self,r,e)):[]}}},rust:{lang:"rust",defs:{function_item:"function",function_signature_item:"function",struct_item:"struct",enum_item:"enum",enum_variant:"enum-member",field_declaration:"field",trait_item:"trait",type_item:"type",associated_type:"type",mod_item:"mod",const_item:"const",static_item:"static",union_item:"union",macro_definition:"macro"},containers:new Set(["impl_item","declaration_list","source_file","field_declaration_list","enum_variant_list","foreign_mod_item","block"]),exported:Tc,calls:{call_expression:"function"},parentFrom:{impl_item:e=>ze(e.childForFieldName("type"))},nestedDefs:new Set(["const_item","static_item"]),publicMembersIn:{impl_item:e=>e.childForFieldName("trait")!==null},relationsFrom:{impl_item:(e,t)=>{let n=ze(e.childForFieldName("trait"));return t.self&&n?[ge("implements",t.self,n,e)]:[]}}},c_sharp:{lang:"csharp",defs:{class_declaration:"class",interface_declaration:"interface",struct_declaration:"struct",enum_declaration:"enum",enum_member_declaration:"enum-member",record_declaration:"record",delegate_declaration:"delegate",method_declaration:"method",constructor_declaration:"constructor",property_declaration:"property",indexer_declaration:"indexer",operator_declaration:"operator",field_declaration:"field",event_declaration:"event",event_field_declaration:"event",conversion_operator_declaration:"operator",destructor_declaration:"destructor"},containers:new Set(["namespace_declaration","declaration_list","compilation_unit","file_scoped_namespace_declaration","enum_member_declaration_list","parameter_list"]),exported:Ac,calls:{invocation_expression:"function",object_creation_expression:"constructor"},kindFrom:{parameter:e=>e.parent?.parent?.type==="record_declaration"?"field":void 0},publicMember:e=>e.parent?.parent?.type==="record_declaration",nameFrom:{field_declaration:e=>Te(e,t=>t.type==="variable_declarator")?.childForFieldName("name")?.text,event_field_declaration:e=>Te(e,t=>t.type==="variable_declarator")?.childForFieldName("name")?.text,conversion_operator_declaration:e=>e.childForFieldName("type")?.text},relationsFrom:{class_declaration:(e,t)=>t.self?tr(he(e,"base_list"),t.self,e):[],struct_declaration:(e,t)=>t.self?tr(he(e,"base_list"),t.self,e):[],record_declaration:(e,t)=>t.self?tr(he(e,"base_list"),t.self,e):[],interface_declaration:(e,t)=>t.self?Oe(he(e,"base_list")).map(n=>ge("extends",t.self,n,e)):[]}},php:{lang:"php",defs:{function_definition:"function",class_declaration:"class",interface_declaration:"interface",trait_declaration:"trait",enum_declaration:"enum",enum_case:"enum-member",method_declaration:"method",property_declaration:"property",const_declaration:"const",namespace_definition:"namespace"},containers:new Set(["declaration_list","enum_declaration_list","program"]),exported:yo,calls:{function_call_expression:"function",member_call_expression:"member",object_creation_expression:"constructor"},nameFrom:{property_declaration:e=>Te(e,t=>t.type==="variable_name")?.text.replace(/^\$/,""),const_declaration:e=>Te(e,t=>t.type==="const_element")?.namedChildren[0]?.text},relationsFrom:{class_declaration:(e,t)=>{if(!t.self)return[];let n=[];for(let r of Oe(he(e,"base_clause")))n.push(ge("extends",t.self,r,e));for(let r of Oe(he(e,"class_interface_clause")))n.push(ge("implements",t.self,r,e));return n},interface_declaration:(e,t)=>t.self?Oe(he(e,"base_clause")).map(n=>ge("extends",t.self,n,e)):[]}},c:{lang:"c",defs:{function_definition:"function",struct_specifier:"struct",enum_specifier:"enum",enumerator:"enum-member",union_specifier:"union",type_definition:"type",field_declaration:"field",declaration:"const"},containers:new Set(["translation_unit","declaration_list","field_declaration_list","enumerator_list","linkage_specification","preproc_ifdef","preproc_if"]),exported:nr,calls:{call_expression:"function"},kindFrom:{field_declaration:e=>Ms(e)?"method":"field",declaration:e=>Ms(e)?"function":"const"}},cpp:{lang:"cpp",defs:{function_definition:"function",class_specifier:"class",struct_specifier:"struct",enum_specifier:"enum",enumerator:"enum-member",union_specifier:"union",type_definition:"type",alias_declaration:"type",concept_definition:"concept",namespace_definition:"namespace",namespace_alias_definition:"namespace",field_declaration:"field",declaration:"const",using_declaration:"using",friend_declaration:"friend"},containers:new Set(["translation_unit","declaration_list","field_declaration_list","enumerator_list","template_declaration","linkage_specification","preproc_ifdef","preproc_if"]),exported:nr,calls:{call_expression:"function",new_expression:"constructor"},kindFrom:{field_declaration:e=>Ms(e)?"method":"field",declaration:e=>Ms(e)?"function":"const"},sectionVisibility:e=>e.type==="access_specifier"?!/^(private|protected)/.test(e.text):void 0,nameFrom:{friend_declaration:e=>Qn(e)??(e.namedChildren[0]?Qn(e.namedChildren[0]):void 0)},relationsFrom:{class_specifier:(e,t)=>t.self?Oe(he(e,"base_class_clause")).map(n=>ge("extends",t.self,n,e)):[],struct_specifier:(e,t)=>t.self?Oe(he(e,"base_class_clause")).map(n=>ge("extends",t.self,n,e)):[]}},scala:{lang:"scala",defs:{class_definition:"class",object_definition:"object",trait_definition:"trait",enum_definition:"enum",function_definition:"def",function_declaration:"def",val_definition:"val",val_declaration:"val",var_definition:"var",type_definition:"type",given_definition:"given",package_clause:"package"},containers:new Set(["compilation_unit","package_clause","template_body","class_parameters","parameters","extension_definition"]),parentFrom:{extension_definition:e=>ze(he(e,"parameters")?.namedChildren[0]?.childForFieldName("type")??null)},exported:yo,kindFrom:{class_parameter:e=>/^\s*(?:val|var)\b/.test(e.text)?/^\s*var\b/.test(e.text)?"var":"val":e.parent?.parent?.type==="class_definition"&&/\bcase\s+class\b/.test(e.parent.parent.text.slice(0,80))?"val":void 0},calls:{call_expression:"function",instance_expression:"constructor"},relationsFrom:{class_definition:(e,t)=>t.self?tr(he(e,"extends_clause"),t.self,e):[],object_definition:(e,t)=>t.self?tr(he(e,"extends_clause"),t.self,e):[],trait_definition:(e,t)=>t.self?Oe(he(e,"extends_clause")).map(n=>ge("extends",t.self,n,e)):[]}},bash:{lang:"shell",defs:{function_definition:"function",declaration_command:"const"},containers:new Set(["program","if_statement","compound_statement"]),exported:nr,calls:{command:"function"},nameFrom:{declaration_command:e=>/^\s*local\b/.test(e.text)?void 0:Te(e,t=>t.type==="variable_name")?.text}},kotlin:{lang:"kotlin",defs:{class_declaration:"class",object_declaration:"object",function_declaration:"function",property_declaration:"property",enum_entry:"enum-member",type_alias:"type",class_parameter:"property"},containers:new Set(["source_file","class_body","enum_class_body","companion_object","object_declaration","primary_constructor","class_parameters"]),exported:yo,calls:{call_expression:"function"},kindFrom:{class_parameter:e=>/^\s*(?:val|var)\b/.test(e.text)||/\bdata\s+class\b/.test(e.parent?.parent?.parent?.text.slice(0,80)??"")?"property":void 0,class_declaration:e=>{let t=e.text.slice(0,80);return/\binterface\b/.test(t)?"interface":/\benum\s+class\b/.test(t)?"enum":/\bannotation\s+class\b/.test(t)?"annotation":"class"}},nameFrom:{property_declaration:e=>Te(e,t=>t.type==="variable_declaration")?.namedChildren[0]?.text??e.namedChildren.find(t=>t.type==="identifier")?.text},relationsFrom:{class_declaration:(e,t)=>{if(!t.self)return[];let n=[];for(let r of he(e,"delegation_specifiers")?.namedChildren??[]){let s=ze(r);s&&n.push(ge(Te(r,o=>o.type==="constructor_invocation")?"extends":"implements",t.self,s,e))}return n}}},elixir:{lang:"elixir",defs:{},containers:new Set(["source","do_block","call","stab_clause"]),exported:e=>!/^\s*defp?macrop\b|^\s*defp\b/.test(e),calls:{call:"function"},kindFrom:{call:e=>Nc[e.childForFieldName("target")?.text??e.namedChildren[0]?.text??""]},skipCall:e=>{if(e.parent?.type==="unary_operator")return!0;if(e.parent?.type!=="arguments")return!1;let t=e.parent.parent,n=t?.childForFieldName("target")??t?.namedChildren[0];return n!==void 0&&Nc[n.text]!==void 0},docFrom:e=>{let t=e.previousNamedSibling;for(;t&&t.type==="unary_operator";){let n=t.namedChildren[0],r=n?.childForFieldName("target")??n?.namedChildren[0];if(r&&/^(doc|moduledoc)$/.test(r.text)){let s=Te(t,o=>o.type==="string");if(s)return s.text.replace(/^"""|"""$/g,"").replace(/^"|"$/g,"").trim()||void 0}t=t.previousNamedSibling}},nameFrom:{call:e=>{let n=(e.childForFieldName("arguments")??e.namedChildren.find(s=>s.type==="arguments"))?.namedChildren[0];if(!n)return;if(n.type==="alias"||n.type==="identifier")return n.text;let r=n.childForFieldName("target")??n.namedChildren[0];return r&&/identifier|alias/.test(r.type)?r.text:void 0}}},zig:{lang:"zig",defs:{function_declaration:"function",variable_declaration:"const",container_field:"field",test_declaration:"test"},containers:new Set(["source_file","variable_declaration","struct_declaration","enum_declaration","union_declaration","error_set_declaration","opaque_declaration","block"]),exported:Tc,calls:{call_expression:"function"},kindFrom:{variable_declaration:e=>{let t=e.namedChildren.find(n=>n.type==="builtin_function");if(!(t&&/^@(import|cImport)\b/.test(t.text))){for(let n of e.namedChildren){if(n.type==="struct_declaration")return"struct";if(n.type==="enum_declaration")return"enum";if(n.type==="union_declaration")return"union";if(n.type==="error_set_declaration")return"error";if(n.type==="opaque_declaration")return"opaque"}return/^\s*(?:pub\s+)?var\b/.test(e.text.slice(0,24))?"var":"const"}},container_field:e=>e.parent?.type==="enum_declaration"?"enum-member":"field"}},solidity:{lang:"solidity",defs:{contract_declaration:"contract",interface_declaration:"interface",library_declaration:"library",function_definition:"function",constructor_definition:"constructor",modifier_definition:"modifier",event_definition:"event",error_declaration:"error",struct_declaration:"struct",struct_member:"field",enum_declaration:"enum",enum_value:"enum-member",state_variable_declaration:"field",constant_variable_declaration:"const",user_defined_type_definition:"type",fallback_receive_definition:"function"},containers:new Set(["source_file","contract_body","struct_declaration","enum_declaration","enum_body"]),exported:(e,t)=>/\b(public|external)\b/.test(e)?!0:/\b(internal|private)\b/.test(e)?!1:Ic(e,t)||!0,calls:{call_expression:"function"},nameFrom:{state_variable_declaration:e=>e.namedChildren.find(t=>t.type==="identifier")?.text,fallback_receive_definition:e=>/^\s*receive\b/.test(e.text)?"receive":"fallback",enum_value:e=>e.text},relationsFrom:{contract_declaration:(e,t)=>t.self?e.namedChildren.filter(n=>n.type==="inheritance_specifier").map(n=>ze(n)).filter(n=>n!==void 0).map(n=>ge("extends",t.self,n,e)):[],interface_declaration:(e,t)=>t.self?e.namedChildren.filter(n=>n.type==="inheritance_specifier").map(n=>ze(n)).filter(n=>n!==void 0).map(n=>ge("extends",t.self,n,e)):[]}},terraform:Oc,hcl:{...Oc,lang:"hcl"},lua:{lang:"lua",defs:{function_declaration:"function"},containers:new Set(["chunk","variable_declaration"]),exported:km,calls:{function_call:"function"},assignments:!0}}});function Am(e){let t=e.childForFieldName("body"),n=t&&t.startIndex>e.startIndex?t.startIndex:void 0,r=s=>{Mm.has(s.type)&&s.startIndex>e.startIndex&&(n===void 0||s.startIndex|=)$/,"").trim().slice(0,Cm)}var Mm,Cm,Lc=F(()=>{"use strict";k();Mm=new Set(["block","statement_block","class_body","declaration_list","field_declaration_list","template_body","compound_statement","body_statement","enum_body","enum_body_declarations","enum_variant_list","enum_member_declaration_list","enumerator_list","interface_body","object_type","do_block","struct_declaration","enum_declaration","union_declaration","error_set_declaration","opaque_declaration","contract_body","enum_class_body"]),Cm=400});function xo(e){return Tm.test(e.trim())}function So(e){return Im.test(e.trim())}function wt(e){return e.replace(/\*+\/\s*$/,"").replace(/^\s*\/\*+!?/,"").replace(/^\s*\/\/[/!]?/,"").replace(/^\s*--+/,"").replace(/^\s*#+/,"").replace(/^\s*\*+/,"").replace(/^\s*(?:"""|''')/,"").replace(/(?:"""|''')\s*$/,"").replace(/[-=~_]{3,}/g," ").trim()}function Nm(e){return e.replace(/<\/?[A-Za-z][^>]*>/g," ").replace(/\s+/g," ").trim()}function ko(e,t=Om){let n=[];for(let o of e){let a=o.trim();if(!(!a||xo(a)||So(a))){if(/^@[a-z]/i.test(a))break;n.push(a)}}let r=Nm(n.join(" "));if(r.length<3)return;let s=/^(.*?[.!?])(\s|$)/.exec(r);return(s?s[1]:r).slice(0,t)}var Tm,Im,Om,As=F(()=>{"use strict";k();Tm=/^(eslint\b|eslint-|prettier\b|prettier-|tslint\b|jshint\b|jslint\b|globals?\b|istanbul\b|c8\s|v8\s|@ts-|ts-|@flow\b|@jsx\b|@jsxRuntime\b|@jest-environment\b|@vitest-environment\b|@license\b|@preserve\b|@copyright\b|copyright\b|spdx-|1);)t.push(n),r=n.startPosition.row,n=n.previousNamedSibling;if(!t.length)return[];t.reverse();let s=[];for(let o of t)for(let a of o.text.split(/\r?\n/))s.push(wt(a));return s}function xn(e){let t=e;for(;t;){let n=$m(t);if(n.length){let o=ko(n);if(o)return o}let r=t.parent;if(!r||!Pm.has(r.type))return;let s=t.previousNamedSibling;if(s&&!Lm.test(s.type))return;t=r}}function Dc(e){let n=e.childForFieldName("body")?.namedChildren[0];if(!n)return;let r=n.type==="string"?n:n.type==="expression_statement"?n.namedChildren[0]:void 0;if(!(!r||r.type!=="string"))return ko(r.text.split(/\r?\n/).map(wt))}var Fm,Pm,Lm,jc=F(()=>{"use strict";k();As();Fm=/(^|_)comment$/,Pm=new Set(["export_statement","ambient_declaration","decorated_definition","template_declaration","labeled_statement","lexical_declaration","variable_declaration","type_declaration","const_declaration","var_declaration","body_statement","body"]);Lm=/decorator|annotation|modifiers/});function ep(e){return e.namedChildren.every(t=>Qm.test(t.type))}function tp(e,t,n,r,s){let o=new Set,a=t.calls!==void 0,l=[],c=new Set,d=(b,x,v)=>{if(!b||b.length<2||!/^[A-Za-z_]\w*$/.test(b))return;let A=x.startPosition.row+1,O=`${b} ${A}`;c.has(O)||(c.add(O),l.push(v?{name:b,line:A,receiver:v}:{name:b,line:A}))},f=new Set,u=b=>{if(!(f.size>=Wc))for(let x of ht(b)){if(f.size>=Wc)return;f.add(x)}},m=new It,p=t.imports?.import_statement!==void 0,g=new Set,y=s&&t.imports!==void 0,h=[],S=new Set,_=b=>{let x=b.trim();x&&!S.has(x)&&(S.add(x),h.push({kind:"import",spec:x}))},E=b=>{let x=b.type,v=b.namedChildren;if(v.length===0&&Jm.test(x)){let A=b.text;Km.test(A)&&!n.has(A)&&o.add(A)}if(Xm.test(x))for(let A of b.text.split(/\r?\n/))u(wt(A));else v.length===0&&Uc.test(x)&&b.endIndex-b.startIndex<=zm&&u(b.text.replace(/^['"`]+|['"`]+$/g,""));if(!m.full){let A=b.startPosition.row+1;Uc.test(x)&&ep(b)?m.addString(b.text,A):v.length===0&&Zm.test(x)?m.add("number",b.text.trim(),A):Ym.test(x)&&m.add("regex",b.text,A)}if(a&&!(t.kindFrom?.[x]&&t.kindFrom[x](b))&&!t.skipCall?.(b)){let A=t.calls[x];if(A==="function"){let O=b.childForFieldName("function")??b.childForFieldName("callee")??b.childForFieldName("method")??b.childForFieldName("name")??b.childForFieldName("target")??v[0]??null;d(Kt(O),b,er(O)??er(b))}else if(A==="member")d(Kt(b.childForFieldName("name")),b,er(b));else if(A==="constructor"){let O=b.childForFieldName("constructor")??b.childForFieldName("type")??b.childForFieldName("name");for(let N=0;!O&&N/string/.test(N.type));O&&_(O.text.replace(/^['"]|['"]$/g,""))}else if(A==="path"){let O=b.childForFieldName("name")??b.childForFieldName("module_name");_((O??b).text.replace(/^(import|from)\s+/,"").split(/\s+/)[0])}}for(let A of v)E(A)};return E(e),l.sort((b,x)=>M(b.name,x.name)||b.line-x.line),{refs:h,idents:[...o].sort().slice(0,Dm),calls:l.slice(0,r),importedNames:[...g].sort(M).slice(0,Wm),terms:[...f].sort(M),literals:m.result()??[]}}function np(e){let t=[],n=r=>{if(/^(shorthand_property_identifier_pattern|identifier)$/.test(r.type)){t.includes(r.text)||t.push(r.text);return}if(r.type==="pair_pattern"){let s=r.childForFieldName("value");s&&n(s);return}for(let s of r.namedChildren)n(s)};for(let r of e.namedChildren)n(r);return t}function Eo(e,t,n,r={}){let s=Yn(t);if(!s||!tt(s))return;let o=Pc[s];if(!o)return;let a=vs(s);if(!a)return;let l=null;try{if(l=a.parse(n),!l)return;let c=r.maxSymbols??Um,d=[],f=l.rootNode,u=(e.split("/").pop()??"").replace(/\.[^.]+$/,""),m=new Set,p=P=>{d.length{let B=o.relationsFrom?.[P.type];if(B)for(let re of B(P,{self:j})){if(re.from===re.to)continue;let J=`${re.kind} ${re.from} ${re.to}`;y.has(J)||g.length>=Bm||(y.add(J),g.push(re))}},S=(P,j,B,re)=>re.inFunctionBody||o.privateMember?.(P)===!0?!1:o.publicMember?.(P)===!0?!0:re.sectionPublic?re.forcePublic?!0:re.exported||o.exported(j,B):!1,_=P=>o.docFrom?.(P)??(o.docstring?Dc(P):void 0)??xn(P),E=(P,j)=>{let B=j.sectionPublic,re=o.bareMembers?.[P.type];for(let J of P.namedChildren){if(o.sectionVisibility){let be=o.sectionVisibility(J);if(be!==void 0){B=be;continue}}let ee=B===j.sectionPublic?j:{...j,sectionPublic:B};if(re&&J.namedChildren.length===0&&Rs.test(J.type)){p({name:J.text,kind:re,file:e,line:J.startPosition.row+1,endLine:J.endPosition.row+1,...ee.parent?{parent:ee.parent}:{},exported:ee.forcePublic||ee.exported,lang:o.lang});continue}for(let be of o.extraMembers?.(J,{ownerKind:ee.ownerKind,inFunctionBody:ee.inFunctionBody})??[]){let Ie=Ot(J,n),X=xn(J);p({name:be.name,kind:be.kind,file:e,line:J.startPosition.row+1,endLine:J.endPosition.row+1,...ee.parent?{parent:ee.parent}:{},...ee.parentPath&&ee.parentPath!==ee.parent?{parentPath:ee.parentPath}:{},signature:Ie,...X?{doc:X}:{},exported:S(J,Ie,be.name,ee),lang:o.lang})}x(J,ee)}},b=(P,j)=>{let B=!1;for(let re of P.namedChildren)o.containers.has(re.type)&&(B=!0,E(re,j));!B&&o.containers.has(P.type)&&E(P,j)},x=(P,j)=>{if(j.funcDepth>Hm)return;let B=P.type,re=o.exportMarkers?.has(B)===!0,J=j.exported||re;if(B==="export_statement"){for(let X of P.namedChildren)if(X.type==="identifier")m.add(X.text);else if(X.type==="export_clause")for(let Z of X.namedChildren){let L=Z.childForFieldName("name")??Z.namedChildren[0];L?.text&&m.add(L.text)}if(u&&P.children.some(X=>X.type==="default"))for(let X of P.namedChildren){let Z=Gm.has(X.type),L=Vm.has(X.type);if((Z||L)&&!X.childForFieldName("name")){let de=xn(P);p({name:u,kind:L?"class":"function",file:e,line:P.startPosition.row+1,endLine:P.endPosition.row+1,signature:Ot(P,n),...de?{doc:de}:{},exported:!0,lang:o.lang});break}}}if(o.assignments&&B==="expression_statement"){let X=P.namedChildren[0];if(X?.type==="assignment_expression"){let Z=X.childForFieldName("left"),L=X.childForFieldName("right");if(Z?.type==="member_expression"&&Z.text==="module.exports"&&L){if(L.type==="object"){for(let K of L.namedChildren)if(K.type==="shorthand_property_identifier")m.add(K.text);else if(K.type==="pair"){let ce=K.childForFieldName("key"),we=K.childForFieldName("value");ce?.type==="property_identifier"&&m.add(ce.text),we?.type==="identifier"&&m.add(we.text)}return}if(L.type==="identifier"){m.add(L.text);return}}let de=L&&Cs.has(L.type);if(Z&&L&&de){let K,ce=!1;if(Z.type==="member_expression"){let we=Z.childForFieldName("property");if(we?.type==="property_identifier"){K=we.text;let pt=Z.text.slice(0,Z.text.length-we.text.length-1);ce=pt==="exports"||pt==="module.exports"}}else Z.type==="identifier"&&(K=Z.text);if(K){let we=xn(P);p({name:K,kind:L.type==="class"?"class":"function",file:e,line:X.startPosition.row+1,endLine:X.endPosition.row+1,...j.parent?{parent:j.parent}:{},signature:Ot(X,n),...we?{doc:we}:{},exported:!j.inFunctionBody&&(J||ce),lang:o.lang});return}}else if(Z?.type==="member_expression"&&L){let K=Z.childForFieldName("property");if(K?.type==="property_identifier"){let ce=Z.text.slice(0,Z.text.length-K.text.length-1);if(ce==="exports"||ce==="module.exports"){L.type==="identifier"&&m.add(L.text),(L.type!=="identifier"||L.text!==K.text)&&p({name:K.text,kind:"const",file:e,line:X.startPosition.row+1,endLine:X.endPosition.row+1,...j.parent?{parent:j.parent}:{},signature:Ot(X,n),exported:!0,lang:o.lang});return}}}}}if(o.assignments&&B==="assignment_statement"){let X=P.children.find(ce=>ce.type==="variable_list"),Z=P.children.find(ce=>ce.type==="expression_list"),L=X?.namedChildren??[],de=Z?.namedChildren??[],K=Math.min(L.length,de.length);for(let ce=0;ceK.type==="object_pattern"||K.type==="array_pattern");if(L&&!j.inFunctionBody){let K=Ot(P,n),ce=_(P);for(let we of np(L))p({name:we,kind:Ie,file:e,line:P.startPosition.row+1,endLine:P.endPosition.row+1,...j.parent?{parent:j.parent}:{},signature:K,...ce?{doc:ce}:{},exported:S(P,K,we,{...j,exported:J}),lang:o.lang});return}let de=wo.has(Ie)||qm.has(Ie)||o.nestedDefs?.has(B)===!0||Cs.has(P.childForFieldName("value")?.type??"");if(Z&&(!j.inFunctionBody||de)){let K=Ot(P,n),ce=_(P),we=ee??j.parent,pt=ee??j.parentPath;p({name:Z,kind:Ie,file:e,line:P.startPosition.row+1,endLine:P.endPosition.row+1,...we?{parent:we}:{},...pt&&pt!==we?{parentPath:pt}:{},signature:K,...ce?{doc:ce}:{},exported:S(P,K,Z,{...j,exported:J}),lang:o.lang}),h(P,Z);let $n=wo.has(Ie);b(P,{parent:Z,parentPath:pt?`${pt}/${Z}`:Z,ownerKind:Ie,exported:J,forcePublic:Fc.has(Ie),inFunctionBody:j.inFunctionBody||$n,funcDepth:j.funcDepth+($n?1:0),sectionPublic:!0});return}}if(h(P,ee??j.parent),o.containers.has(B)){let X=j.forcePublic||o.publicMembersIn?.[B]?.(P)===!0,Z=Cs.has(B);E(P,{...j,exported:J,forcePublic:X,inFunctionBody:j.inFunctionBody||Z,funcDepth:j.funcDepth+(Z?1:0),...ee?{parent:ee,parentPath:ee,ownerKind:"type"}:{}})}};if(E(f,{exported:!1,forcePublic:!1,inFunctionBody:!1,funcDepth:0,sectionPublic:!0}),m.size)for(let P of d)!P.exported&&m.has(P.name)&&(P.exported=!0);let v=r.imports!==!1,{refs:A,idents:O,calls:N,importedNames:U,terms:le,literals:V}=tp(f,o,new Set(d.map(P=>P.name)),r.maxCalls??jm,v),z;if(v&&o.lang==="java"){let P=Te(f,j=>j.type==="package_declaration");P&&(z=P.text.replace(/^package\s+/,"").replace(/;.*$/,"").trim())}return g.sort((P,j)=>M(P.from,j.from)||M(P.kind,j.kind)||M(P.to,j.to)),{symbols:d,refs:A,pkg:z,idents:O,calls:N,importedNames:U,relations:g,terms:le,literals:V,...d.length>=c?{truncated:!0}:{}}}catch{return}finally{l?.delete()}}var Dm,jm,Wm,Um,Bm,Wc,zm,Hm,qm,Gm,Vm,Jm,Km,Xm,Uc,Zm,Ym,Qm,vo=F(()=>{"use strict";k();hs();Y();nt();ho();$c();Lc();jc();As();Ce();Dm=512,jm=512,Wm=256,Um=2e3,Bm=256,Wc=512,zm=80,Hm=2,qm=new Set(["class","struct","enum","interface","trait","type","record","union"]),Gm=new Set(["function","function_expression","function_declaration","generator_function","generator_function_declaration","arrow_function"]),Vm=new Set(["class","class_declaration","abstract_class_declaration"]),Jm=/identifier|constant|(^|_)name$/,Km=/^[A-Za-z_]\w{4,}$/,Xm=/(^|_)comment$/,Uc=/(^|_)string(_literal)?$/,Zm=/(^|_)(integer|float|number|decimal|numeric)(_literal)?$/,Ym=/(^|_)(regex|regular_expression)(_pattern|_literal)?$/,Qm=/(^|_)(fragment|content|escape_sequence|character)$/});function ap(e){let t=e.split(/\r?\n/),n=[],r=null;for(let a=0;aa&&!xo(a)&&!So(a)).join(" ").replace(/\s+/g," ").trim();if(s.length<8)return;let o=/^(.*?[.!?])(\s|$)/.exec(s);return(o?o[1]:s).slice(0,200)}function Mo(e,t=[]){if(t.length>=lp)return t;let n=e.indexOf("{");if(n===-1){let c=e.replace(/\s+as\s+\w+\s*$/,"").replace(/::\s*\*\s*$/,"").replace(/^::/,"").trim();return c&&t.push(c),t}let r=e.slice(0,n),s=0,o=-1;for(let c=n;c({kind:"import",spec:s}))}function up(e,t=[],n=512){let r=new Map,s=new Set(t.map(l=>`${l.name} ${l.line}`)),o=e.split(` +`),a=/(?:\bnew\s+)?(?:([A-Za-z_$][\w$]*)\s*\.\s*)?([A-Za-z_$][\w$]*)\s*\(/g;for(let l=0;ll.namec.name?1:l.line-c.line)}function mp(e){let t=new Set,n=s=>{if(!(t.size>=Ro))for(let o of ht(s)){if(t.size>=Ro)return;t.add(o)}},r=!1;for(let s of e.split(` +`)){if(t.size>=Ro)break;let o=s;if(r){let c=o.indexOf("*/");if(n(wt(c===-1?o:o.slice(0,c))),c===-1)continue;r=!1,o=o.slice(c+2)}let a=o.indexOf("/*");if(a!==-1){let c=o.indexOf("*/",a+2);n(wt(o.slice(a,c===-1?void 0:c))),c===-1?(r=!0,o=o.slice(0,a)):o=o.slice(0,a)+o.slice(c+2)}let l=/(^|\s)(\/\/|#|--)(.*)$/.exec(o);l&&(n(wt(l[2]+l[3])),o=o.slice(0,l.index));for(let c of o.matchAll(/(['"`])((?:\\.|(?!\1)[^\\])*)\1/g)){let d=c[2];d.length&&d.length<=fp&&n(d)}}return[...t].sort()}function pp(e){let t=new It,n=!1,r=0;for(let s of e.split(` +`)){if(r++,t.full)break;let o=s;if(n){let c=o.indexOf("*/");if(c===-1)continue;n=!1,o=o.slice(c+2)}let a=o.indexOf("/*");if(a!==-1){let c=o.indexOf("*/",a+2);c===-1?(n=!0,o=o.slice(0,a)):o=o.slice(0,a)+o.slice(c+2)}let l=/(^|\s)(\/\/|#|--)(.*)$/.exec(o);l&&(o=o.slice(0,l.index));for(let c of o.matchAll(/(['"`])((?:\\.|(?!\1)[^\\])*)\1/g))t.add("string",c[2],r);for(let c of o.replace(/(['"`])(?:\\.|(?!\1)[^\\])*\1/g," ").matchAll(/(?m.name)),c=us(e,n,a).filter(m=>!l.has(m.name)),d=cp(t,n),f=new Set(d.map(m=>m.spec)),u=(s?s.literals.length?s.literals:void 0:pp(n))?.filter(m=>!(m.kind==="string"&&f.has(m.value)));return{symbols:[...a,...c],...s?.truncated||o.length>a.length||c.length>=ds?{truncated:!0}:{},summary:ap(n),refs:d,pkg:t===".java"?/^\s*package\s+([\w.]+)\s*;/m.exec(n)?.[1]:t===".cs"?/^\s*(?:file-scoped\s+)?namespace\s+([\w.]+)/m.exec(n)?.[1]:void 0,idents:s?.idents,calls:s?s.calls:up(n,a,r.maxCallsPerFile),importedNames:s?.importedNames,relations:s?.relations?.length?s.relations:void 0,terms:s?s.terms:mp(n),literals:u?.length?u:void 0}}var rp,sp,ip,op,lp,dp,Bc,Ro,fp,Ao=F(()=>{"use strict";k();hs();yn();vo();ve();As();Ce();rp=2e3,sp=new Set([".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs"]),ip=new Set([".py",".pyi"]),op=new Set([".c",".h",".cc",".cpp",".cxx",".hpp",".hh"]);lp=16;dp=new Set(["if","else","elif","for","while","do","switch","case","match","when","unless","until","catch","except","return","throw","raise","yield","await","typeof","instanceof","sizeof","delete","void","in","of","not","and","or","assert","defer","select","with","loop"]),Bc=/(?:\bfunction|\bdef|\bfunc|\bfun|\bfn|\bclass|\bsub|\bmacro|\bproc)\s*[*]?\s*$/;Ro=512,fp=80});function Hc(e){let t=new It,n=0;for(let r of e.split(` +`)){if(n++,t.full)break;let s=yp(r);for(let a of s.matchAll(zc))t.add("string",a[2],n);let o=hp.exec(s);if(o){let a=o[1].trim();a&&!/^[[{|>&*-]/.test(a)&&!gp.test(a)&&t.add("string",a,n)}for(let a of s.replace(zc," ").matchAll(_p))t.add("number",a[0].replace(/_/g,""),n)}return t.result()}function yp(e){let t;for(let n=0;n{"use strict";k();hs();zc=/(['"])((?:\\.|(?!\1)[^\\])*)\1/g,gp=/(['"])((?:\\.|(?!\1)[^\\])*)\1/,_p=/(?u.rel)),a!==void 0&&n.length!==a.size&&(l=!1,c=!0),{root:e,commit:as(e),files:n,languages:r,docText:s,mtimes:o,capped:f.value.capped,excluded:f.value.excluded,contentUnchanged:l,cacheDirty:c}}var Ft=F(()=>{"use strict";k();oe();Ae();Gt();At();_s();yn();Hn();Y();eo();Ao();qc()});function De(e){let t=new Map;for(let n of e.files)t.set(n.rel,{hash:n.hash,record:n,size:n.size,mtimeMs:e.mtimes.get(n.rel)});return t}function No(e,t,n=!1){let r=e.files.filter(s=>zn(s.rel,s.ext)==="code");return n&&r.length>0||r.some(s=>{let o=t.get(s.rel);return!o||o.size!==s.size||o.mtimeMs!==s.mtimeMs})}function Oo(e,t=ut){let n;try{n=JSON.parse(te(I(e,t,"cache.json"),"utf8"))}catch{return}if(!(!n||n.schemaVersion!==5||n.extractorVersion!==14||!n.files))return{cacheMap:new Map(Object.entries(n.files)),meta:{engineVersion:n.engineVersion,commit:n.commit,graphSha1:n.graphSha1,symbolsSha1:n.symbolsSha1}}}function Fo(e,t,n,r=ut){if(!t.contentUnchanged||n.engineVersion!==fe||n.commit!==t.commit||n.graphSha1===void 0||n.symbolsSha1===void 0)return;let s=I(e,r),o,a;try{o=te(I(s,"graph.json")),a=te(I(s,"symbols.json"))}catch{return}if(!(Me(o)!==n.graphSha1||Me(a)!==n.symbolsSha1))try{let l=JSON.parse(o.toString("utf8")),c=JSON.parse(a.toString("utf8"));return l.schemaVersion!==5||c.schemaVersion!==5?void 0:{scan:t,graph:l,symbols:c}}catch{return}}function Po(e,t,n=ut){let r=Oo(e,n);if(!r)return;let s=Pe(e,{...t,cache:r.cacheMap});return{scan:s,cacheMap:De(s),arts:Fo(e,s,r.meta,n)}}async function Is(e,t,n,r=ut){let s=Oo(e,r);if(!s)return;let o=t.precomputedWalk??Fe(e,{maxFileBytes:t.maxBytes,maxFiles:t.maxFiles,gitignore:t.gitignore,ignoreDirs:t.ignoreDirs});No(o,s.cacheMap,t.fullHash)&&await n();let l=Pe(e,{...t,cache:s.cacheMap,precomputedWalk:o}),c=!1,d;return{scan:l,cacheMap:De(l),loadArtifacts:()=>(c||(c=!0,d=Fo(e,l,s.meta,r)),d)}}var ut,sr=F(()=>{"use strict";k();xe();oe();Xe();Ft();At();Ae();_s();ut=".codeindex"});var Ns,Vc=F(()=>{k();Ns=class{constructor(){throw new Error("worker_threads is not available in the browser build (the engine runs single-threaded here)")}}});function bp(){try{let e=bs(import.meta.url);if(e.endsWith("engine.mjs"))return qn(e).href;let t=I(_e(e),"engine.mjs");return H(t)?qn(t).href:void 0}catch{return}}function Jc(e){let t=R.env.CODEINDEX_WORKERS,n=e??(t!==void 0&&t!==""?Number(t):void 0);if(n!==void 0)return Number.isFinite(n)&&n>0?Math.floor(n):0;let r=1;try{r=typeof ys=="function"?ys():sc().length}catch{r=1}return Math.max(0,Math.min(r-1,8))}async function Sp(e,t){await et(e.grammarKeys);let n=e.grammarKeys.filter(s=>tt(s)),r=[];for(let s of e.jobs){let o,a;try{let d=Ee(s.abs);o=d.size,a=d.mtimeMs}catch{continue}let l=G(s.abs),c=Ts(s.rel,s.ext,o,l,Me(l),Vt(s.ext),{maxCallsPerFile:e.maxCallsPerFile});r.push({rel:s.rel,size:o,mtimeMs:a,record:c})}t({ready:n,records:r})}async function Kc(e,t,n,r={}){if(n<2||e.length===0)return;let s=bp();if(!s)return;let o=t.filter(c=>tt(c)).sort(),a=Array.from({length:Math.min(n,e.length)},()=>[]);e.forEach((c,d)=>a[d%a.length].push(c));let l=`import { runExtractWorker } from ${JSON.stringify(s)}; +import { parentPort, workerData } from "node:worker_threads"; +runExtractWorker(workerData.input, (o) => parentPort.postMessage(o)).catch((e) => parentPort.postMessage({ error: String(e) })); +`;try{let c=await Promise.all(a.map(f=>new Promise((u,m)=>{let p=new Ns(l,{eval:!0,workerData:{input:{jobs:f,grammarKeys:o,maxCallsPerFile:r.maxCallsPerFile}}}),g=setTimeout(()=>{m(new Error("extraction worker timed out")),p.terminate()},wp),y=h=>{clearTimeout(g),h()};p.once("message",h=>{y(()=>u(h)),p.terminate()}),p.once("error",h=>y(()=>m(h))),p.once("exit",h=>{h!==0&&y(()=>m(new Error(`extraction worker exited with ${h}`)))})}))),d=new Map;for(let f of c){if("error"in f||f.ready.slice().sort().join(",")!==o.join(","))return;for(let u of f.records)d.set(u.rel,{size:u.size,mtimeMs:u.mtimeMs,record:u.record})}return d}catch{return}}async function Pt(e,t={}){let n=Jc(t.workers);if(n<2)return Pe(e,t);let r=t.precomputedWalk??Fe(e,{maxFileBytes:t.maxBytes,maxFiles:t.maxFiles,gitignore:t.gitignore,ignoreDirs:t.ignoreDirs}),s={...t,precomputedWalk:r},o=[];for(let{f:d}of Io(e,s)){let f=t.cache?.get(d.rel);!t.fullHash&&f&&f.size!==void 0&&f.mtimeMs!==void 0&&f.size===d.size&&f.mtimeMs===d.mtimeMs||o.push({abs:d.abs,rel:d.rel,ext:d.ext})}if(o.length===0)return Pe(e,s);if(!(t.workers!==void 0||(R.env.CODEINDEX_WORKERS??"")!=="")&&o.lengthd.ext)),c=await Kc(o,l,n,{maxCallsPerFile:t.maxCallsPerFile});return Pe(e,c?{...s,extracted:c}:s)}var wp,xp,Os=F(()=>{"use strict";k();xe();to();oe();ws();Vc();At();Ae();yn();nt();Ft();wp=600*1e3,xp=200});function Jp(e){let t=Se(e).split("/").filter(s=>s!=="."),n=[],r=0;for(;rt?1:0)}function Wo(e){let t="",n=!1;for(let s=0;s=Op)){if(typeof e=="string")t.includes(e)||t.push(e);else if(Array.isArray(e))for(let n of e)To(n,t);else if(e!==null&&typeof e=="object"){let n=Object.keys(e).sort((r,s)=>Gc(r)-Gc(s)||(rs?1:0));for(let r of n)To(e[r],t)}}}function Fp(e){if(e==null)return[];let t=[],n=(r,s)=>{let o=[];To(s,o),o.length&&t.push({key:r,star:r.includes("*"),targets:o})};if(typeof e=="string"||Array.isArray(e))n(".",e);else if(typeof e=="object"){let r=Object.keys(e);if(r.every(s=>s==="."||s.startsWith("./")))for(let s of r)n(s,e[s]);else n(".",e)}return t.sort((r,s)=>Number(r.star)-Number(s.star)||s.key.length-r.key.length||(r.key{let o=/^\s*([^\s=]+)(?:\s+v\S+)?\s*=>\s*(\S+)(?:\s+v\S+)?\s*$/.exec(s);if(!o)return;let a=o[2];if(!/^\.\.?\//.test(a))return;let l=xe(D.join(t,a));l.startsWith("..")||n.push({from:o[1],toDir:l})};for(let s of e.matchAll(/^[ \t]*replace[ \t]+([^(\r\n][^\r\n]*)$/gm))r(s[1]);for(let s of e.matchAll(/^[ \t]*replace[ \t]*\(([\s\S]*?)\)/gm))for(let o of s[1].split(/\r?\n/))r(o);return n}function Io(e){let t=new Set(e.files.map(h=>h.rel)),n=new Map,r=new Set;for(let h of e.files){let _=h.rel.includes("/")?D.dirname(h.rel):"",y=n.get(_);y||n.set(_,y=[]),y.push(h.rel);let x=_;for(;x&&!r.has(x);)r.add(x),x=x.includes("/")?D.dirname(x):""}let s=[],o=[];for(let h of t){let _=h.slice(h.lastIndexOf("/")+1);if(_!=="tsconfig.json"&&_!=="jsconfig.json"&&!(h==="tsconfig.base.json"))continue;let x=h.includes("/")?D.dirname(h):"",E=qc(e.root,t,h,s,new Set);if(!E?.paths)continue;let w=[];for(let[C,A]of Object.entries(E.paths)){if(!Array.isArray(A))continue;let F=C.endsWith("*");w.push({prefix:F?C.slice(0,-1):C,star:F,targets:A})}if(!w.length)continue;let k=E.baseUrl!==void 0?xe(D.join(E.baseUrlDir,E.baseUrl)).replace(/^\.$/,""):E.pathsDir;o.push({dir:x,baseUrl:k,paths:w})}o.sort((h,_)=>_.dir.length-h.dir.length);let a=[];for(let h of t){if(h!=="go.mod"&&!h.endsWith("/go.mod"))continue;let _=G(I(e.root,h)),y=/^\s*module\s+(\S+)/m.exec(_);if(!y)continue;let x=h.includes("/")?D.dirname(h):"";a.push({module:y[1],dir:x,replaces:Pp(_,x)})}a.sort((h,_)=>_.dir.length-h.dir.length||(h.dir<_.dir?-1:1));let l=[];for(let h of t){if(h!=="Cargo.toml"&&!h.endsWith("/Cargo.toml"))continue;let _=G(I(e.root,h)),y=/\[package\][^[]*?^\s*name\s*=\s*"([^"]+)"/ms.exec(_);if(!y)continue;let x=h.includes("/")?D.dirname(h):"",E=xe(D.join(x,"src")).replace(/^\.$/,""),w=Ip(t,[D.join(E,"lib.rs"),D.join(E,"main.rs")]);l.push({name:y[1].replace(/-/g,"_"),dir:x,srcDir:E,rootFile:w})}l.sort((h,_)=>_.dir.length-h.dir.length||(h.dir<_.dir?-1:1));let c=new Set;for(let h of e.files){if(h.ext!==".java"||!h.pkg)continue;let _=h.rel.includes("/")?D.dirname(h.rel):"",y=h.pkg.replace(/\./g,"/");_===y?c.add(""):_.endsWith("/"+y)&&c.add(_.slice(0,-y.length-1))}let d=new Set([""]);for(let h of t){let _=h.split("/").pop();(_==="__init__.py"||_==="pyproject.toml"||_==="setup.py")&&d.add(h.includes("/")?D.dirname(h):"")}let u=[];for(let h of t){if(h!=="package.json"&&!h.endsWith("/package.json"))continue;let _=Ao(G(I(e.root,h)));if(_===void 0){s.push(`unparseable ${h} \u2014 skipped for workspace resolution`);continue}if(typeof _.name!="string")continue;let y=[_.source,_.main,_.module,_.types].filter(x=>typeof x=="string");u.push({name:_.name,dir:h.includes("/")?D.dirname(h):"",exportEntries:Fp(_.exports),mainCandidates:y})}u.sort((h,_)=>_.name.length-h.name.length);let f=new Set([""]);for(let h of r){let _=h.slice(h.lastIndexOf("/")+1);(_==="include"||_==="inc"||_==="src")&&f.add(h)}let p=new Set([""]);for(let h of r)h.slice(h.lastIndexOf("/")+1)==="lib"&&p.add(h);let m=[];for(let h of t){if(h!=="composer.json"&&!h.endsWith("/composer.json"))continue;let _=Ao(G(I(e.root,h)));if(!_){s.push(`unparseable ${h} \u2014 skipped for PHP PSR-4 resolution`);continue}let y=h.includes("/")?D.dirname(h):"";for(let x of[_.autoload?.["psr-4"],_["autoload-dev"]?.["psr-4"]])if(x)for(let[E,w]of Object.entries(x))for(let k of Array.isArray(w)?w:[w])typeof k=="string"&&m.push({prefix:E.replace(/\\+$/,""),dir:xe(D.join(y,k)).replace(/^\.$/,"")})}m.sort((h,_)=>_.prefix.length-h.prefix.length);let g=new Map;for(let h of e.files){if(h.ext!==".cs"||!h.pkg)continue;let _=g.get(h.pkg);_||g.set(h.pkg,_=[]),_.push(h.rel)}for(let h of g.values())h.sort(R);return{fileSet:t,dirSet:r,filesByDir:n,tsConfigs:o,goModules:a,rustCrates:l,javaRoots:[...c].sort(Mo),pyRoots:[...d],workspacePackages:u,cIncludeRoots:[...f].sort(Mo),rubyLibRoots:[...p].sort(Mo),phpPsr4:m,csharpNamespaces:g,warnings:s}}function ct(e,t){for(let n of t){let r=xe(n);if(r&&!r.startsWith("..")&&e.fileSet.has(r))return r}}function No(e,t,n){let r=t.split("#")[0].split("?")[0];if(!r)return{kind:"external"};if(r.startsWith("//")||/^[a-z][a-z0-9+.-]*:/i.test(r))return{kind:"external"};let s=e.includes("/")?D.dirname(e):"",o=xe(D.join(s,r));if(o.startsWith(".."))return{kind:"dangling",reason:"escapes-repo-root"};let a=ct(n,[o,o+".md",o+".mdx",D.join(o,"README.md"),D.join(o,"readme.md"),D.join(o,"index.md"),D.join(o,"index.mdx")]);return a?{kind:"resolved",target:a}:n.dirSet.has(o)?{kind:"external"}:{kind:"dangling",reason:"missing-target"}}function $p(e,t,n){let r=a=>ct(n,[...kp.map(l=>a+l),...Ep.map(l=>D.join(a,l))]),s=a=>{let l=r(a);if(l)return l;let c=a.replace(/\.(js|jsx|mjs|cjs)$/,"");return c!==a?r(c):void 0};if(t.startsWith(".")){let a=e.includes("/")?D.dirname(e):"",l=xe(D.join(a,t));if(l.startsWith(".."))return{kind:"dangling",reason:"escapes-repo-root"};let c=s(l);return c?{kind:"resolved",target:c}:{kind:"dangling",reason:"missing-module"}}let o;for(let a of n.tsConfigs){if(a.dir&&e!==a.dir&&!e.startsWith(a.dir+"/"))continue;let l=!1;for(let c of a.paths){if(!(c.star?t.startsWith(c.prefix):t===c.prefix))continue;l=!0;let d=c.star?t.slice(c.prefix.length):"",u=!1;for(let f of c.targets){let p=c.star?f.replace(/\*/,d):f,m=xe(D.join(a.baseUrl,p)),g=s(m);if(g)return{kind:"resolved",target:g};let h=m.includes("/")?D.dirname(m):"";(n.dirSet.has(h)||n.fileSet.has(m))&&(u=!0)}o=u?{kind:"dangling",reason:"alias-unresolved"}:{kind:"external"};break}if(l)break}for(let a of n.workspacePackages){if(t!==a.name&&!t.startsWith(a.name+"/"))continue;let l=t.slice(a.name.length).replace(/^\//,""),c=f=>{for(let p of[f,...Tp(f)]){let m=s(xe(D.join(a.dir,p)));if(m)return m}},d=l?"./"+l:".";for(let f of a.exportEntries){let p;if(f.star){let m=f.key.indexOf("*"),g=f.key.slice(0,m),h=f.key.slice(m+1);if(!d.startsWith(g)||!d.endsWith(h)||d.length{let a=o?o.replace(/\./g,"/"):"",l=xe(D.join(s,a));return ct(n,[l+".py",l+".pyi",D.join(l,"__init__.py")])};if(t.startsWith(".")){let s=/^\.+/.exec(t)[0].length,o=t.slice(s),l=e.includes("/")?D.dirname(e):"";for(let d=1;d{let l=xe(a).replace(/^\.$/,""),c=(n.filesByDir.get(l)??[]).filter(d=>d.endsWith(".go")).sort();return c.length?{kind:"resolved",target:c[0]}:{kind:"dangling",reason:"missing-package"}},s=n.goModules.find(a=>!a.dir||e===a.dir||e.startsWith(a.dir+"/"));if(s)for(let a of s.replaces){if(t!==a.from&&!t.startsWith(a.from+"/"))continue;let l=t.slice(a.from.length).replace(/^\//,"");return r(D.join(a.toDir,l))}let o=s?[s,...n.goModules.filter(a=>a!==s)]:n.goModules;for(let a of o){if(t!==a.module&&!t.startsWith(a.module+"/"))continue;let l=t.slice(a.module.length).replace(/^\//,"");return r(D.join(a.dir,l))}return{kind:"external"}}function jp(e,t,n){if(!n.rustCrates.length)return{kind:"external"};let r=(x,E)=>ct(n,[D.join(x,E+".rs"),D.join(x,E,"mod.rs")]),s=(x,E)=>{for(let w=E.length;w>=1;w--){let k=xe(D.join(x,...E.slice(0,w-1))),C=r(k,E[w-1]);if(C)return C}},o=e.includes("/")?D.dirname(e):"",a=e.slice(e.lastIndexOf("/")+1).replace(/\.rs$/,""),l=a==="mod"||a==="lib"||a==="main",c=l?o:D.join(o,a);if(t.startsWith("mod ")){let x=t.slice(4),E=r(c,x)??(l?void 0:r(o,x));return E?{kind:"resolved",target:E}:{kind:"dangling",reason:"missing-module"}}let d=t.split("::").map(x=>x.trim()).filter(Boolean);if(!d.length)return{kind:"external"};let u=d[0],f=n.rustCrates.find(x=>!x.dir||e===x.dir||e.startsWith(x.dir+"/")),p,m=[];if(u==="crate"&&f)p=f.srcDir,m=d.slice(1);else if(u==="self")p=c,m=d.slice(1);else if(u==="super"){let x=l?o.includes("/")?D.dirname(o):"":o,E=1;for(;EE.name===u);if(x){let E=s(x.srcDir,d.slice(1));if(E)return{kind:"resolved",target:E};if(x.rootFile)return{kind:"resolved",target:x.rootFile}}return{kind:"external"}}if(!m.length)return{kind:"external"};let g=s(p,m);if(g)return{kind:"resolved",target:g};if(f&&p===f.srcDir&&f.rootFile)return{kind:"resolved",target:f.rootFile};let h=p.includes("/")?D.dirname(p):"",_=p.slice(p.lastIndexOf("/")+1),y=_?r(h,_):void 0;return y&&y!==e?{kind:"resolved",target:y}:{kind:"external"}}function Up(e,t){if(!t.javaRoots.length)return{kind:"external"};let n=o=>{for(let a of t.javaRoots){let l=xe(D.join(a,o));if(l.endsWith("/*")||l==="*"){let c=l==="*"?"":l.slice(0,-2),d=(t.filesByDir.get(c)??[]).filter(u=>u.endsWith(".java")).sort();if(d.length)return d[0];continue}if(t.fileSet.has(l+".java"))return l+".java"}},r=e.replace(/\./g,"/"),s=n(r);if(!s&&!e.endsWith(".*")){let o=r.split("/");for(let a=o.length-1;a>=2&&!s;a--)s=n(o.slice(0,a).join("/"))}return s?{kind:"resolved",target:s}:{kind:"external"}}function Wp(e,t,n){let r=e.includes("/")?D.dirname(e):"",s=ct(n,[D.join(r,t),...n.cIncludeRoots.map(o=>D.join(o,t))]);return s?{kind:"resolved",target:s}:{kind:"dangling",reason:"missing-include"}}function Bp(e,t,n){if(t.startsWith(".")){let r=e.includes("/")?D.dirname(e):"",s=xe(D.join(r,t)),o=ct(n,[s+".rb",D.join(s,"index.rb")]);return o?{kind:"resolved",target:o}:{kind:"dangling",reason:"missing-module"}}for(let r of n.rubyLibRoots){let s=ct(n,[D.join(r,t+".rb")]);if(s)return{kind:"resolved",target:s}}return{kind:"external"}}function Hp(e,t,n){if(t.startsWith(".")){let s=e.includes("/")?D.dirname(e):"",o=xe(D.join(s,t)),a=ct(n,[o,o+".php"]);return a?{kind:"resolved",target:a}:{kind:"dangling",reason:"missing-module"}}let r=t.replace(/^\\+/,"");for(let{prefix:s,dir:o}of n.phpPsr4){if(s&&r!==s&&!r.startsWith(s+"\\"))continue;let a=s?r.slice(s.length).replace(/^\\+/,""):r,l=ct(n,[D.join(o,a.replace(/\\/g,"/"))+".php"]);if(l)return{kind:"resolved",target:l}}return{kind:"external"}}function zp(e,t){let n=t.csharpNamespaces.get(e);if(n?.length)return{kind:"resolved",target:n[0]};let r;for(let[s,o]of t.csharpNamespaces)if(s===e||s.startsWith(e+".")){let a=o[0];(r===void 0||R(a,r)<0)&&(r=a)}return r?{kind:"resolved",target:r}:{kind:"external"}}function rr(e,t,n,r){let s=n.lastIndexOf(".");return s!==-1&&Sp.has(n.slice(s).toLowerCase().replace(/[?#].*$/,""))?{kind:"external"}:vp.has(t)||Rp.has(t)?$p(e,n,r):Mp.has(t)?Dp(e,n,r):t===".go"?Lp(e,n,r):t===".rs"?jp(e,n,r):t===".java"?Up(n,r):Cp.has(t)?Wp(e,n,r):t===".rb"||t===".rake"?Bp(e,n,r):t===".php"?Hp(e,n,r):t===".cs"?zp(n,r):{kind:"external"}}var Sp,kp,Ep,vp,Rp,Mp,Cp,Ap,Co,Op,vs=O(()=>{"use strict";S();ie();ie();Te();K();Sp=new Set([".svg",".png",".jpg",".jpeg",".gif",".webp",".bmp",".ico",".icns",".pdf",".woff",".woff2",".ttf",".otf",".eot",".mp3",".mp4",".mov",".avi",".webm",".wav",".flac",".ogg",".map"]),kp=["",".ts",".tsx",".d.ts",".mts",".cts",".js",".jsx",".mjs",".cjs",".vue",".svelte",".astro",".html",".htm"],Ep=["index.ts","index.tsx","index.js","index.jsx","index.mjs","index.cjs"],vp=new Set([".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs"]),Rp=new Set([".vue",".svelte",".astro",".html",".htm"]),Mp=new Set([".py",".pyi"]),Cp=new Set([".c",".h",".cc",".cpp",".cxx",".hpp",".hh"]),Ap=new Set(["dist","build","lib","out","output","esm","cjs","umd"]);Co=["source","ts","import","module","require","node","default"],Op=8});function Ms(e){return Jp.test(e.split("/").pop())}function Kp(e){return e.includes("/")?D.dirname(e):Rs}function Vc(e){return e===Rs?0:qp.test(e)||Vp.test(e)?2:Gp.test(e)?0:null}function Xp(e,t){let n=Vc(e);return n!==null?n:t.every(r=>r.kind==="doc"||r.kind==="config"||Ms(r.rel))?2:1}function Zp(e,t){let n=t.find(a=>/^(readme|index)\.(md|mdx)$/i.test(a.rel.split("/").pop()));if(n?.summary)return n.summary;if(n?.title)return n.title;let r=t.filter(a=>a.summary).sort((a,l)=>(l.summary?.length??0)-(a.summary?.length??0));if(r[0]?.summary)return r[0].summary;let s=[...new Set(t.map(a=>a.lang))].filter(a=>a!=="other"),o=e===Rs?"the repository root":`\`${e}/\``;return`${t.length} file(s) in ${o}${s.length?` (${s.slice(0,3).join(", ")})`:""}.`}function Oo(e){let t=new Map;for(let c of e.files){let d=Kp(c.rel),u=t.get(d);u||t.set(d,u=[]),u.push(c)}let n=[...t.keys()].sort(R),r=new Map,s=new Map;for(let c of n){let d=c===Rs?"root":Ei(c);r.set(c,d),s.set(d,(s.get(d)??0)+1)}let o=c=>{let d=r.get(c);return d&&s.get(d)===1?d:`${d||"module"}-${ve(c).slice(0,8)}`},a=[],l=new Map;for(let c of n){let d=t.get(c).slice().sort((p,m)=>R(p.rel,m.rel)),u=o(c),f={slug:u,path:c,title:c,tier:Xp(c,d),members:d.map(p=>p.rel),summary:Zp(c,d)};a.push(f);for(let p of d)l.set(p.rel,u)}return a.sort((c,d)=>R(c.slug,d.slug)),{modules:a,moduleOf:l}}var Rs,Gp,qp,Vp,Jp,Cs=O(()=>{"use strict";S();ie();Me();Rt();K();Rs="(root)",Gp=/(^|\/)(types?|util|utils|lib|libs|common|core|config|configs|constants|shared|helpers|internal)$/i,qp=/(^|\/)(tests?|__tests?__|__mocks?__|__snapshots?__|spec|specs|e2e|examples?|example|benchmark|benchmarks|fixtures?|docs?|documentation|\.github)(\/|$)/i,Vp=/(^|\/)(scripts?|bin|\.storybook)$/i,Jp=/\.(test|spec|e2e|stories|story)\.[cm]?[jt]sx?$/i});function tt(e){return e==="typescript"||e==="javascript"?"js":e==="c"||e==="cpp"?"c":e}function Qp(e,t){let n=e.split("/"),r=t.split("/"),s=0;for(;sr?(r=a,n=o,s=!1):a===r&&(s=!0)}return s?void 0:n}function Fo(e,t){let n=new Map,r=new Set;for(let o of e.files)for(let a of o.symbols){if(!a.exported||Yp.has(a.kind))continue;let l=`${a.name} ${a.file}`;if(r.has(l))continue;r.add(l);let c=n.get(a.name);c||n.set(a.name,c=[]),c.push({file:a.file,lang:a.lang})}let s=new Map;for(let o of e.files){if(!o.calls?.length)continue;let a=tt(o.lang),l=new Set(o.symbols.map(d=>d.name)),c=new Map;for(let d of o.calls)c.set(d.name,(c.get(d.name)??0)+1);for(let[d,u]of c){if(l.has(d))continue;let f=(n.get(d)??[]).filter(y=>tt(y.lang)===a&&y.file!==o.rel);if(!f.length)continue;let p=f.filter(y=>t.has(`${o.rel}|${y.file}`)),m,g;if(a==="js"){if(!p.length)continue;m=et(o.rel,p),g="extracted"}else p.length?(m=et(o.rel,p),g="extracted"):(m=et(o.rel,f),g="inferred");if(!m)continue;let h=`${o.rel}|${m.file}`,_=s.get(h);_?(_.weight+=u,g==="extracted"&&(_.confidence="extracted")):s.set(h,{from:o.rel,to:m.file,weight:u,confidence:g})}}return[...s.values()].map(o=>({from:o.from,to:o.to,kind:"call",weight:Math.min(o.weight,5),confidence:o.confidence})).sort((o,a)=>R(o.from,a.from)||R(o.to,a.to))}var Yp,wn=O(()=>{"use strict";S();K();Yp=new Set(["reexport","reexport-all","default"])});function Jc(e){let t=new Map,n=new Set;for(let r of e.files)for(let s of r.symbols){if(!tg.has(s.kind))continue;let o=`${s.name} ${s.file}`;if(n.has(o))continue;n.add(o);let a=t.get(s.name);a||t.set(s.name,a=[]),a.push({name:s.name,file:s.file,kind:s.kind,lang:s.lang,line:s.line})}return t}function sr(e,t){let n=Jc(e),r=[];for(let s of e.files){if(!s.relations?.length)continue;let o=tt(s.lang);for(let a of s.relations){let l=(n.get(a.to)??[]).filter(p=>tt(p.lang)===o);if(!l.length)continue;let c=l.filter(p=>t.has(`${s.rel}|${p.file}`)||p.file===s.rel),d=c.length?c:l,u=et(s.rel,d.map(p=>({file:p.file,lang:p.lang})));if(!u)continue;let f=d.find(p=>p.file===u.file);r.push({kind:eg.has(f.kind)?"implements":a.kind,from:a.from,fromFile:s.rel,fromLine:a.line,to:f.name,toFile:f.file,toKind:f.kind})}}return r.sort((s,o)=>R(s.fromFile,o.fromFile)||R(s.from,o.from)||R(s.kind,o.kind)||R(s.to,o.to))}function Po(e,t){let n=new Map;for(let r of sr(e,t)){if(r.toFile===r.fromFile)continue;let s=`${r.fromFile}${$e}${r.toFile}${$e}${r.kind}`,o=n.get(s);o?o.weight=Math.min(o.weight+1,5):n.set(s,{from:r.fromFile,to:r.toFile,kind:r.kind,weight:1})}return[...n.values()].sort((r,s)=>R(r.from,s.from)||R(r.to,s.to)||R(r.kind,s.kind))}function xn(e,t){let n=Jc(e),r=sr(e,t),s=new Map,o=(f,p)=>`${f}${$e}${p}`;for(let f of n.values())for(let p of f)s.set(o(p.name,p.file),{name:p.name,file:p.file,line:p.line,kind:p.kind,extends:[],implements:[],extendedBy:[],implementedBy:[],unresolved:[]});let a=f=>({name:f.name,file:f.file,line:f.line,kind:f.kind});for(let f of r){let p=s.get(o(f.from,f.fromFile)),m=s.get(o(f.to,f.toFile));m&&(p?((f.kind==="extends"?p.extends:p.implements).push(a(m)),(f.kind==="extends"?m.extendedBy:m.implementedBy).push(a(p))):(f.kind==="extends"?m.extendedBy:m.implementedBy).push({name:f.from,file:f.fromFile,line:f.fromLine,kind:"unknown"}))}let l=new Set(r.map(f=>`${f.fromFile}${$e}${f.from}${$e}${f.kind}${$e}${f.to}`));for(let f of e.files)for(let p of f.relations??[]){if(l.has(`${f.rel}${$e}${p.from}${$e}${p.kind}${$e}${p.to}`))continue;let m=p.kind==="extends"?"implements":"extends";l.has(`${f.rel}${$e}${p.from}${$e}${m}${$e}${p.to}`)||s.get(o(p.from,f.rel))?.unresolved.push({kind:p.kind,to:p.to})}let c=(f,p)=>R(f.name,p.name)||R(f.file,p.file),d=new Map,u=[...s.keys()].sort(R);for(let f of u){let p=s.get(f);p.extends.sort(c),p.implements.sort(c),p.extendedBy.sort(c),p.implementedBy.sort(c),p.unresolved.sort((m,g)=>R(m.kind,g.kind)||R(m.to,g.to)),d.has(p.name)?d.set(`${p.name}@${p.file}`,p):d.set(p.name,p)}return d}function ir(e,t){let n=e.get(t);if(!n)return[];let r=new Set([`${n.name}${$e}${n.file}`]),s=[],o=[n];for(;o.length;){let a=[];for(let l of o)for(let c of[...l.implementedBy,...l.extendedBy]){let d=`${c.name}${$e}${c.file}`;if(r.has(d))continue;r.add(d),s.push(c);let u=e.get(c.name)??e.get(`${c.name}@${c.file}`);u&&u.file===c.file&&a.push(u)}o=a}return s.sort((a,l)=>R(a.name,l.name)||R(a.file,l.file))}function ng(e,t){return e.get(t)}var $e,eg,tg,Kt=O(()=>{"use strict";S();wn();K();$e="\0",eg=new Set(["interface","trait","protocol"]),tg=new Set(["class","interface","trait","struct","type","enum","record","object","protocol","module","mod","union","annotation"])});function $o(e){let t=Sn(e),n=new Map;if(!t.size)return n;let r=(s,o)=>{let a=n.get(s);a||n.set(s,a=new Set),a.add(o)};for(let s of e.files)if(s.kind==="code"&&s.idents)for(let o of s.idents){let a=t.get(o);a&&a!==s.rel&&r(o,s.rel)}else if(s.kind==="doc"){let o=e.docText.get(s.rel);if(!o)continue;for(let a of o.split(/[^A-Za-z0-9_]+/)){let l=t.get(a);l&&l!==s.rel&&r(a,s.rel)}}return n}function Do(e,t=new Map,n=5){let r=new Map;for(let a of e.files)for(let l of a.symbols){let c=r.get(l.name);c||r.set(l.name,c=[]),c.push({file:l.file,line:l.line,...l.endLine!==void 0?{endLine:l.endLine}:{},kind:l.kind,exported:l.exported,lang:l.lang,...l.parent?{parent:l.parent}:{}})}let s={};for(let a of[...r.keys()].sort(R))s[a]=r.get(a).slice().sort((l,c)=>R(l.file,c.file)||l.line-c.line||R(l.kind,c.kind));let o={};for(let a of[...t.keys()].sort(R)){let l=[...t.get(a)].sort(R);l.length&&(o[a]=l)}return{schemaVersion:n,defs:s,refs:o}}function As(e){return JSON.stringify(e,null,2)+` -`}var or=O(()=>{"use strict";S();qe();K();dt()});function ar(e){return new Set(Yt(e))}function Xt(e,t,n={}){let r=t??Yt(e),s=n.recall===!0,o=new Map;for(let f of e.files){let p=new Set;for(let m of f.symbols){if(!m.exported||Ts.has(m.kind)||p.has(m.name))continue;p.add(m.name);let g=o.get(m.name);g||o.set(m.name,g=[]),g.push(m)}}let a=new Map;for(let f of e.files){let p=new Map;for(let m of f.symbols)!Ts.has(m.kind)&&!p.has(m.name)&&p.set(m.name,m);a.set(f.rel,p)}let l=new Map,c=(f,p)=>{let m=l.get(f.name+"\0"+f.file);m||l.set(f.name+"\0"+f.file,m={def:f,callers:[]}),m.callers.push(p)};for(let f of e.files){if(!f.calls?.length)continue;let p=tt(f.lang),m=a.get(f.rel);for(let g of f.calls){let h=m.get(g.name);if(h){h.line!==g.line&&c(h,s?{file:f.rel,line:g.line,confidence:"corroborated"}:{file:f.rel,line:g.line});continue}let _=(o.get(g.name)??[]).filter(w=>tt(w.lang)===p&&w.file!==f.rel).map(w=>({file:w.file,lang:w.lang}));if(!_.length)continue;let y=_.filter(w=>r.has(`${f.rel}|${w.file}`)),x=p==="js"?y.length?et(f.rel,y):s&&_.length===1?_[0]:void 0:y.length?et(f.rel,y):et(f.rel,_);if(!x)continue;let E=o.get(g.name).find(w=>w.file===x.file);c(E,s?{file:f.rel,line:g.line,confidence:y.length?"corroborated":"unique-name"}:{file:f.rel,line:g.line})}}let d=new Map,u=[...l.keys()].sort(R);for(let f of u){let{def:p,callers:m}=l.get(f);m.sort((g,h)=>R(g.file,h.file)||g.line-h.line),d.has(p.name)?d.set(`${p.name}@${p.file}`,{def:p,callers:m}):d.set(p.name,{def:p,callers:m})}return d}function rg(e,t,n){let r=e.files.find(s=>s.rel===t);if(r?.symbols.length)return Is(r.symbols,n)}function Is(e,t){let n;for(let r of e)Ts.has(r.kind)||r.line>t||r.endLine!==void 0&&t>r.endLine||(!n||r.line>n.line||r.line===n.line&&(r.endLine??1/0)<=(n.endLine??1/0))&&(n=r);return n}function sg(e){let t=new Map;for(let r of e.files){if(!r.calls?.length)continue;let s=r.symbols.filter(o=>!Ts.has(o.kind));for(let o of r.calls){let a={file:r.rel,line:o.line};o.receiver!==void 0&&(a.receiver=o.receiver);let l=Is(s,o.line);l&&(a.enclosingSymbol=l);let c=t.get(o.name);c||t.set(o.name,c=[]),c.push(a)}}let n=new Map;for(let r of[...t.keys()].sort(R)){let s=t.get(r);s.sort((o,a)=>R(o.file,a.file)||o.line-a.line),n.set(r,s)}return n}var Ts,Zt=O(()=>{"use strict";S();wn();dt();K();Ts=new Set(["reexport","reexport-all","default"])});function Qt(e){return e.parent?`${e.file}#${e.parent}/${e.name}`:`${e.file}#${e.name}`}function og(e){return{id:Qt(e),name:e.name,kind:e.kind,file:e.file,line:e.line,...e.endLine!==void 0?{endLine:e.endLine}:{},exported:e.exported,...e.doc?{doc:e.doc}:{},...e.signature?{signature:e.signature}:{}}}function lr(e,t){let n=new Map,r=new Map,s=new Map,o=new Set;for(let m of e.files){let g=[];for(let h of m.symbols){if(ig.has(h.kind)||(g.push(h),n.set(Qt(h),og(h)),!h.exported))continue;let _=`${h.name} ${h.file}`;if(o.has(_))continue;o.add(_);let y=s.get(h.name);y||s.set(h.name,y=[]),y.push(h)}r.set(m.rel,g)}let a=new Map,l=(m,g,h)=>{if(m===g)return;let _=`${m}${Ns}${g}${Ns}${h}`,y=a.get(_);y?y.weight+=1:a.set(_,{from:m,to:g,kind:h,weight:1})};for(let m of e.files){if(!m.calls?.length)continue;let g=tt(m.lang),h=r.get(m.rel)??[],_=new Map;for(let y of h)_.has(y.name)||_.set(y.name,y);for(let y of m.calls){let x=Is(h,y.line);if(!x)continue;let E=_.get(y.name);if(E){E.line!==y.line&&l(Qt(x),Qt(E),"calls");continue}let w=(s.get(y.name)??[]).filter(N=>tt(N.lang)===g&&N.file!==m.rel);if(!w.length)continue;let k=w.filter(N=>t.has(`${m.rel}|${N.file}`)),C=k.length?k:g==="js"?[]:w;if(!C.length)continue;let A=et(m.rel,C.map(N=>({file:N.file,lang:N.lang})));if(!A)continue;let F=C.find(N=>N.file===A.file);l(Qt(x),Qt(F),"calls")}}let c=new Map;for(let m of n.values())c.set(`${m.name} ${m.file}`,m.id);for(let m of sr(e,t)){let g=c.get(`${m.from} ${m.fromFile}`),h=c.get(`${m.to} ${m.toFile}`);g&&h&&l(g,h,m.kind)}let d=[...a.values()].sort((m,g)=>R(m.from,g.from)||R(m.kind,g.kind)||R(m.to,g.to)),u=new Map,f=new Map;for(let m of d)(u.get(m.from)??u.set(m.from,[]).get(m.from)).push(m),(f.get(m.to)??f.set(m.to,[]).get(m.to)).push(m);let p=new Map;for(let m of[...n.keys()].sort(R)){let g=n.get(m);(p.get(g.name)??p.set(g.name,[]).get(g.name)).push(m)}return{nodes:n,edges:d,out:u,in:f,byName:p}}function cr(e,t,n={}){let r=Math.max(1,Math.min(n.depth??2,ag)),s=n.direction??"both",o=e.nodes.has(t)?[t]:e.byName.get(t)??[...e.nodes.keys()].filter(m=>m.endsWith(`#${t}`)),a=o.map(m=>e.nodes.get(m)).filter(Boolean);if(!a.length)return{root:[],nodes:[],edges:[]};let l=new Map;for(let m of o)l.set(m,0);let c=new Map,d=[...o],u=!1;for(let m=1;m<=r&&d.length;m++){let g=[];for(let h of d){let _=(y,x)=>{for(let E of y??[]){c.set(`${E.from}${Ns}${E.to}${Ns}${E.kind}`,E);let w=x(E);if(!l.has(w)){if(l.size>=lg){u=!0;continue}l.set(w,m),g.push(w)}}};s!=="in"&&_(e.out.get(h),y=>y.to),s!=="out"&&_(e.in.get(h),y=>y.from)}d=g}let f=[...l.entries()].map(([m,g])=>({...e.nodes.get(m),depth:g})).sort((m,g)=>m.depth-g.depth||R(m.file,g.file)||R(m.name,g.name)),p=[...c.values()].filter(m=>l.has(m.from)&&l.has(m.to)).sort((m,g)=>R(m.from,g.from)||R(m.kind,g.kind)||R(m.to,g.to));return{root:a,nodes:f,edges:p,...u?{truncated:!0}:{}}}var Ns,ig,ag,lg,dr=O(()=>{"use strict";S();wn();Zt();Kt();K();Ns="\0",ig=new Set(["reexport","reexport-all","default"]);ag=5,lg=400});function Ot(e){if(dg.test(e)||Ms(e))return!0;let t=e.split("/").pop();return cg.some(n=>n.test(t))}function ur(e){let t=new Set,n=new Map;for(let a of e.files)n.set(a.rel,a.module),a.fileKind==="code"&&Ot(a.rel)&&t.add(a.rel);let r=new Map,s=new Map;for(let a of e.fileEdges){if(a.dangling||a.kind!=="import"&&a.kind!=="use"&&a.kind!=="call"||!t.has(a.from)||t.has(a.to))continue;let l=r.get(a.to);l||r.set(a.to,l=new Set),l.add(a.from);let c=n.get(a.to);if(c!==void 0){let d=s.get(c);d||s.set(c,d=new Set),d.add(a.from)}}let o=a=>{let l=new Map;for(let c of[...a.keys()].sort(R))l.set(c,[...a.get(c)].sort(R));return l};return{testFiles:t,testedByFile:o(r),testedByModule:o(s)}}function ug(e,t){let n=e.modules.find(r=>r.slug===t);return n?.testedBy?n.testedBy:ur(e).testedByModule.get(t)??[]}function fg(e){let t=ur(e),n=new Map;for(let r of e.files)r.fileKind!=="code"||t.testFiles.has(r.rel)||n.set(r.module,(n.get(r.module)??0)+1);return e.modules.filter(r=>r.tier<=1&&r.symbols>0&&(n.get(r.slug)??0)>0&&!t.testedByModule.has(r.slug))}var cg,dg,kn=O(()=>{"use strict";S();Cs();K();cg=[/^test_.*\.py$/i,/_test\.py$/i,/_test\.go$/,/(Test|Tests|IT)\.java$/,/(Test|Tests)\.kt$/,/_spec\.rb$/,/_test\.rb$/,/Test\.php$/,/(Test|Tests)\.cs$/,/_test\.exs$/],dg=/(^|\/)(tests?|__tests?__|spec|specs|e2e)(\/|$)/i});function En(e,t,n){let r=e.fields[t];for(let s of pt(n))r.tf.set(s,(r.tf.get(s)??0)+1),r.len++,e.all.add(s)}function xg(){let e={};for(let t of Os)e[t]={tf:new Map,len:0};return e}function Fs(e){let t=[];for(let n of e.files){let r={file:n.rel,fields:xg(),all:new Set,symbols:[],decls:[],exactNames:new Set,isTest:Ot(n.rel)},s=new Set;for(let o of n.symbols)En(r,"name",o.name),o.doc&&En(r,"doc",o.doc),r.exactNames.add(mt(o.name).toLowerCase()),s.has(o.name)||(s.add(o.name),r.symbols.push(o.name),r.decls.push({name:o.name,kind:o.kind,line:o.line}));for(let o of n.rel.split("/"))En(r,"path",o);for(let o of n.headings)En(r,"heading",o);n.summary&&En(r,"summary",n.summary);for(let o of n.terms??[])En(r,"body",o);t.push(r)}return t}function Qc(e){let t=`^^${e}$$`,n=new Set;for(let r=0;r+3<=t.length;r++)n.add(t.slice(r,r+3));return n}function Sg(e,t){if(!e.size||!t.size)return 0;let n=0;for(let r of e)t.has(r)&&n++;return 2*n/(e.size+t.size)}function ed(e){let t=new Set,n=new Map;for(let r of e)for(let s of r.all){if(t.has(s))continue;t.add(s);let o=Ri(s);if(o===s)continue;let a=n.get(o);a||n.set(o,a=[]),a.push(s)}for(let r of n.values())r.sort(R);return n}function td(e){let t=new Map;for(let n of e)for(let r of n.all)t.has(r)||t.set(r,Qc(r));return t}function Ft(e,t,n={}){return nd(e,t,n).results}function en(e,t,n={}){return nd(e,t,n)}function Zc(e,t,n){return{results:[],explain:{query:e,terms:[],droppedStopwords:Qr(e),unresolvedTerms:[],verdict:t,note:n,bridgedOnlyResults:0,resultCount:0}}}function nd(e,t,n={}){let r=[],s=new Set;for(let x of Yr(t))for(let E of pt(x))s.has(E)||(s.add(E),r.push(E));if(!r.length){let x=Qr(t);return Zc(t,"none",x.length?`Nothing was searched for: every token in this query (${x.join(", ")}) is a stopword or too short to index. Search with the identifiers or domain words you are actually looking for.`:"Nothing was searched for: the query carried no indexable token.")}let o=r.some(x=>wg.test(x)),a=rd(e),l=a.length;if(!l)return Zc(t,"none","This index contains no files.");let c={};for(let x of Os){let E=0;for(let w of a)E+=w.fields[x].len;c[x]=E/l||1}let d=new Map;for(let x of r){let E=0;for(let w of a)w.all.has(x)&&E++;d.set(x,E)}let u=n.fuzzy??!0,f=new Map;if(u){let x=r.filter(E=>d.get(E)===0);if(x.length){let E=od(e),w=[];for(let k of x){let C=(E.get(Ri(k))??[]).filter(A=>A!==k);C.length?f.set(k,C.slice(0,Xc).map(A=>({term:A,dice:Yc}))):w.push(k)}if(w.length){let k=sd(e);for(let C of w){let A=Qc(C),F=[];for(let[N,W]of k){let q=Sg(A,W);q>=gg&&F.push({term:N,dice:q})}F.sort((N,W)=>W.dice-N.dice||R(N.term,W.term)),f.set(C,F.slice(0,Xc))}}}}let p=new Map,m=x=>{let E=d.get(x)??p.get(x);if(E!==void 0)return E;let w=0;for(let k of a)k.all.has(x)&&w++;return p.set(x,w),w},g=x=>Math.log(1+(l-x+.5)/(x+.5)),h=n.rank==="graph"?id(e):void 0,_=[];for(let x of a){let E=0,w=[],k=new Set,C=new Set,A=new Set,F=!1,N=B=>{let P=0;for(let $ of Os){let V=x.fields[$],oe=V.tf.get(B);if(!oe)continue;k.add($);let ee=hg[$];P+=_g[$]*oe/(1-ee+ee*V.len/c[$])}return P};for(let B of r){let P=N(B);if(P>0){w.push(B),C.add(B),x.exactNames.has(B)&&(F=!0),E+=g(d.get(B))*(P/(Kc+P));continue}for(let $ of f.get(B)??[]){let V=N($.term);V&&(E+=g(m($.term))*(V/(Kc+V))*$.dice,C.add($.term),A.add(B))}}if(!w.length&&!A.size)continue;F&&(E*=yg),x.isTest&&!o&&(E*=bg),h&&(E*=1+.35*Math.log1p(h.get(x.file)??0));let q=x.decls.map(B=>{let P=new Set(pt(B.name)),$=0;for(let V of C)P.has(V)&&$++;return{decl:B,hits:$}}).filter(B=>B.hits>0).sort((B,P)=>P.hits-B.hits||R(B.decl.name,P.decl.name)).slice(0,pg).map(B=>B.decl),X={file:x.file,score:Number(E.toFixed(4)),matchedTerms:w.sort(R),topSymbols:q.map(B=>B.name)};k.size&&(X.matchedFields=Os.filter(B=>k.has(B))),q.length&&(X.symbolHits=q,X.line=Math.min(...q.map(B=>B.line))),A.size&&(X.fuzzyTerms=[...A].sort(R)),w.length||(X.bridgedOnly=!0),_.push(X)}_.sort((x,E)=>E.score-x.score||R(x.file,E.file));let y=(n.exact?_.filter(x=>!x.bridgedOnly):_).slice(0,n.limit??mg);return{results:y,explain:kg(t,r,d,f,y)}}function kg(e,t,n,r,s){let o=t.map(g=>{let h=n.get(g)??0,_=h===0?r.get(g)??[]:[];if(!_.length)return{term:g,df:h};let y=_[0].dice===Yc?"stem":"trigram";return{term:g,df:h,bridge:{via:y,to:_.map(x=>x.term),dice:_[0].dice}}}),a=o.filter(g=>g.df===0&&!g.bridge).map(g=>g.term).sort(R),l=!/\s/.test(e.trim())&&t.length?{term:t[0],df:n.get(t[0])??0}:void 0,c=s.filter(g=>g.bridgedOnly).length,d=s.length>0&&c===s.length,u=l?.df===0,f=s.length?u||d?"weak":"match":"none",p={query:e,terms:o,droppedStopwords:Qr(e),unresolvedTerms:a,...l?{wholeIdentifier:l}:{},verdict:f,bridgedOnlyResults:c,resultCount:s.length},m=Eg(p,u,d);return m&&(p.note=m),p}function Eg(e,t,n){let{verdict:r,wholeIdentifier:s,resultCount:o,terms:a}=e;if(r!=="match"){if(!o)return e.unresolvedTerms.length?`No file matches. ${e.unresolvedTerms.length===1?"The term":"The terms"} ${e.unresolvedTerms.join(", ")} appear nowhere in this index.`:"No file matches this query.";if(t&&s){let l=a.filter(f=>f.term!==s.term&&f.df>0).map(f=>f.term).join(", "),c=a.find(f=>f.term===s.term)?.bridge?.to??[],d=l?` The ${o} result${o===1?"":"s"} below match only its parts (${l}).`:"",u=c.length?` Closest indexed name${c.length===1?"":"s"}: ${c.join(", ")}.`:"";return`No file in this index defines or mentions "${s.term}".${d}${u} If you expected it here, check you are indexing the right branch or commit.`}if(n)return`Nothing matched verbatim. Every result below came from a near match: ${a.filter(d=>d.bridge).map(d=>`"${d.term}" \u2192 ${d.bridge.to.join(", ")}`).join("; ")}. Re-run with --exact to see only literal matches.`}}var Kc,mg,pg,gg,Xc,Yc,Os,_g,hg,yg,bg,wg,vn=O(()=>{"use strict";S();dt();Me();kn();K();Kc=1.2,mg=20,pg=5,gg=.6,Xc=3,Yc=.9,Os=["name","path","heading","summary","doc","body"],_g={name:3,path:2,heading:1.5,summary:1.5,doc:1.6,body:.7},hg={name:.75,path:.75,heading:.75,summary:.75,doc:.75,body:.4},yg=1.35,bg=.65,wg=/^(test|tests|spec|specs|fixture|fixtures|mock|mocks|stub|stubs)$/});function fr(e,t,n=.85){let r=new Map,s=e.length;if(s===0)return r;let o=new Map(e.map((d,u)=>[d,u])),a=Array.from({length:s},()=>[]),l=new Array(s).fill(0);for(let d of t){if(d.dangling)continue;let u=o.get(d.from),f=o.get(d.to);u===void 0||f===void 0||u===f||(a[u].push([f,d.weight]),l[u]+=d.weight)}let c=new Array(s).fill(1/s);for(let d=0;d<100;d++){let u=0;for(let g=0;gr.set(d,c[u])),r}function ad(e,t){let n=new Map;for(let d of e)n.set(d,0);let r=e.length;if(r<3)return n;let s=new Map(e.map((d,u)=>[d,u])),o=Array.from({length:r},()=>new Set);for(let d of t){if(d.dangling)continue;let u=s.get(d.from),f=s.get(d.to);u===void 0||f===void 0||u===f||(o[u].add(f),o[f].add(u))}let a=o.map(d=>[...d].sort((u,f)=>u-f)),l=new Array(r).fill(0);for(let d=0;d[]),p=new Array(r).fill(0),m=new Array(r).fill(-1);p[d]=1,m[d]=0;let g=[d];for(let _=0;_=0;_--){let y=u[_];for(let x of f[y])h[x]+=p[x]/p[y]*(1+h[y]);y!==d&&(l[y]+=h[y])}}let c=(r-1)*(r-2)/2;return e.forEach((d,u)=>n.set(d,l[u]/2/c)),n}function Lo(e){let t=[],n=e.modules.length;if(n>0){let s=e.modules.map(a=>a.id),o=fr(s,e.moduleEdges);for(let a of e.modules)a.pagerank=Number(((o.get(a.id)??0)*n).toFixed(4));if(n>3e3)t.push(`betweenness skipped (${n} modules > 3000)`);else{let a=ad(s,e.moduleEdges);for(let l of e.modules)l.betweenness=Number((a.get(l.id)??0).toFixed(6))}}let r=e.files.length;if(r>0){let s=e.files.map(a=>a.id),o=fr(s,e.fileEdges);for(let a of e.files)a.pagerank=Number(((o.get(a.id)??0)*r).toFixed(4))}return t}var Ps=O(()=>{"use strict";S()});function $s(e){return 1+(e.match(vg)??[]).length}function mr(e,t,n=50){let r=[];for(let s of e.files){if(s.kind!=="code"||t&&s.rel!==t||!s.symbols.length)continue;let o=G(I(e.root,s.rel)).split(` +`||t[a]==="\r");)a++;if(t[a]==="}"||t[a]==="]")continue}r+=o}try{return JSON.parse(r)}catch{return}}function Xp(e,t,n){let r=Se($.join(t,n)),s=n.endsWith(".json")?[r]:[r+".json",$.join(r,"tsconfig.json")];for(let o of s)if(e.has(o))return o}function id(e,t,n,r,s){if(s.has(n))return;s.add(n);let o=Wo(G(I(e,n)));if(o===void 0){r.push(`unparseable ${n} \u2014 its path aliases were ignored`);return}let a=n.includes("/")?$.dirname(n):"",l={baseUrlDir:"",pathsDir:""},c=o.extends===void 0?[]:Array.isArray(o.extends)?o.extends:[o.extends];for(let f of c){if(typeof f!="string")continue;let u=Xp(t,a,f);if(!u){/^\.\.?\//.test(f)&&r.push(`${n} extends "${f}" which is missing \u2014 its path aliases were ignored`);continue}let m=id(e,t,u,r,s);m?.baseUrl!==void 0&&(l.baseUrl=m.baseUrl,l.baseUrlDir=m.baseUrlDir),m?.paths&&(l.paths=m.paths,l.pathsDir=m.pathsDir)}let d=o.compilerOptions;return d?.baseUrl!==void 0&&(l.baseUrl=d.baseUrl,l.baseUrlDir=a),d?.paths&&(l.paths=d.paths,l.pathsDir=a),l}function sd(e){let t=jo.indexOf(e);return t!==-1?t:e==="types"?jo.length+1:jo.length}function Uo(e,t){if(!(t.length>=Zp)){if(typeof e=="string")t.includes(e)||t.push(e);else if(Array.isArray(e))for(let n of e)Uo(n,t);else if(e!==null&&typeof e=="object"){let n=Object.keys(e).sort((r,s)=>sd(r)-sd(s)||(rs?1:0));for(let r of n)Uo(e[r],t)}}}function Yp(e){if(e==null)return[];let t=[],n=(r,s)=>{let o=[];Uo(s,o),o.length&&t.push({key:r,star:r.includes("*"),targets:o})};if(typeof e=="string"||Array.isArray(e))n(".",e);else if(typeof e=="object"){let r=Object.keys(e);if(r.every(s=>s==="."||s.startsWith("./")))for(let s of r)n(s,e[s]);else n(".",e)}return t.sort((r,s)=>Number(r.star)-Number(s.star)||s.key.length-r.key.length||(r.key{let o=/^\s*([^\s=]+)(?:\s+v\S+)?\s*=>\s*(\S+)(?:\s+v\S+)?\s*$/.exec(s);if(!o)return;let a=o[2];if(!/^\.\.?\//.test(a))return;let l=Se($.join(t,a));l.startsWith("..")||n.push({from:o[1],toDir:l})};for(let s of e.matchAll(/^[ \t]*replace[ \t]+([^(\r\n][^\r\n]*)$/gm))r(s[1]);for(let s of e.matchAll(/^[ \t]*replace[ \t]*\(([\s\S]*?)\)/gm))for(let o of s[1].split(/\r?\n/))r(o);return n}function Bo(e){let t=new Set(e.files.map(y=>y.rel)),n=new Map,r=new Set;for(let y of e.files){let h=y.rel.includes("/")?$.dirname(y.rel):"",S=n.get(h);S||n.set(h,S=[]),S.push(y.rel);let _=h;for(;_&&!r.has(_);)r.add(_),_=_.includes("/")?$.dirname(_):""}let s=[],o=[];for(let y of t){let h=y.slice(y.lastIndexOf("/")+1);if(h!=="tsconfig.json"&&h!=="jsconfig.json"&&!(y==="tsconfig.base.json"))continue;let _=y.includes("/")?$.dirname(y):"",E=id(e.root,t,y,s,new Set);if(!E?.paths)continue;let b=[];for(let[v,A]of Object.entries(E.paths)){if(!Array.isArray(A))continue;let O=v.endsWith("*");b.push({prefix:O?v.slice(0,-1):v,star:O,targets:A})}if(!b.length)continue;let x=E.baseUrl!==void 0?Se($.join(E.baseUrlDir,E.baseUrl)).replace(/^\.$/,""):E.pathsDir;o.push({dir:_,baseUrl:x,paths:b})}o.sort((y,h)=>h.dir.length-y.dir.length);let a=[];for(let y of t){if(y!=="go.mod"&&!y.endsWith("/go.mod"))continue;let h=G(I(e.root,y)),S=/^\s*module\s+(\S+)/m.exec(h);if(!S)continue;let _=y.includes("/")?$.dirname(y):"";a.push({module:S[1],dir:_,replaces:Qp(h,_)})}a.sort((y,h)=>h.dir.length-y.dir.length||(y.dirh.dir.length-y.dir.length||(y.dirtypeof _=="string");f.push({name:h.name,dir:y.includes("/")?$.dirname(y):"",exportEntries:Yp(h.exports),mainCandidates:S})}f.sort((y,h)=>h.name.length-y.name.length);let u=new Set([""]);for(let y of r){let h=y.slice(y.lastIndexOf("/")+1);(h==="include"||h==="inc"||h==="src")&&u.add(y)}let m=new Set([""]);for(let y of r)y.slice(y.lastIndexOf("/")+1)==="lib"&&m.add(y);let p=[];for(let y of t){if(y!=="composer.json"&&!y.endsWith("/composer.json"))continue;let h=Wo(G(I(e.root,y)));if(!h){s.push(`unparseable ${y} \u2014 skipped for PHP PSR-4 resolution`);continue}let S=y.includes("/")?$.dirname(y):"";for(let _ of[h.autoload?.["psr-4"],h["autoload-dev"]?.["psr-4"]])if(_)for(let[E,b]of Object.entries(_))for(let x of Array.isArray(b)?b:[b])typeof x=="string"&&p.push({prefix:E.replace(/\\+$/,""),dir:Se($.join(S,x)).replace(/^\.$/,"")})}p.sort((y,h)=>h.prefix.length-y.prefix.length);let g=new Map;for(let y of e.files){if(y.ext!==".cs"||!y.pkg)continue;let h=g.get(y.pkg);h||g.set(y.pkg,h=[]),h.push(y.rel)}for(let y of g.values())y.sort(M);return{fileSet:t,dirSet:r,filesByDir:n,tsConfigs:o,goModules:a,rustCrates:l,javaRoots:[...c].sort(Do),pyRoots:[...d],workspacePackages:f,cIncludeRoots:[...u].sort(Do),rubyLibRoots:[...m].sort(Do),phpPsr4:p,csharpNamespaces:g,warnings:s}}function ft(e,t){for(let n of t){let r=Se(n);if(r&&!r.startsWith("..")&&e.fileSet.has(r))return r}}function zo(e,t,n){let r=t.split("#")[0].split("?")[0];if(!r)return{kind:"external"};if(r.startsWith("//")||/^[a-z][a-z0-9+.-]*:/i.test(r))return{kind:"external"};let s=e.includes("/")?$.dirname(e):"",o=Se($.join(s,r));if(o.startsWith(".."))return{kind:"dangling",reason:"escapes-repo-root"};let a=ft(n,[o,o+".md",o+".mdx",$.join(o,"README.md"),$.join(o,"readme.md"),$.join(o,"index.md"),$.join(o,"index.mdx")]);return a?{kind:"resolved",target:a}:n.dirSet.has(o)?{kind:"external"}:{kind:"dangling",reason:"missing-target"}}function eg(e,t,n){let r=a=>ft(n,[...Up.map(l=>a+l),...Bp.map(l=>$.join(a,l))]),s=a=>{let l=r(a);if(l)return l;let c=a.replace(/\.(js|jsx|mjs|cjs)$/,"");return c!==a?r(c):void 0};if(t.startsWith(".")){let a=e.includes("/")?$.dirname(e):"",l=Se($.join(a,t));if(l.startsWith(".."))return{kind:"dangling",reason:"escapes-repo-root"};let c=s(l);return c?{kind:"resolved",target:c}:{kind:"dangling",reason:"missing-module"}}let o;for(let a of n.tsConfigs){if(a.dir&&e!==a.dir&&!e.startsWith(a.dir+"/"))continue;let l=!1;for(let c of a.paths){if(!(c.star?t.startsWith(c.prefix):t===c.prefix))continue;l=!0;let d=c.star?t.slice(c.prefix.length):"",f=!1;for(let u of c.targets){let m=c.star?u.replace(/\*/,d):u,p=Se($.join(a.baseUrl,m)),g=s(p);if(g)return{kind:"resolved",target:g};let y=p.includes("/")?$.dirname(p):"";(n.dirSet.has(y)||n.fileSet.has(p))&&(f=!0)}o=f?{kind:"dangling",reason:"alias-unresolved"}:{kind:"external"};break}if(l)break}for(let a of n.workspacePackages){if(t!==a.name&&!t.startsWith(a.name+"/"))continue;let l=t.slice(a.name.length).replace(/^\//,""),c=u=>{for(let m of[u,...Jp(u)]){let p=s(Se($.join(a.dir,m)));if(p)return p}},d=l?"./"+l:".";for(let u of a.exportEntries){let m;if(u.star){let p=u.key.indexOf("*"),g=u.key.slice(0,p),y=u.key.slice(p+1);if(!d.startsWith(g)||!d.endsWith(y)||d.length{let a=o?o.replace(/\./g,"/"):"",l=Se($.join(s,a));return ft(n,[l+".py",l+".pyi",$.join(l,"__init__.py")])};if(t.startsWith(".")){let s=/^\.+/.exec(t)[0].length,o=t.slice(s),l=e.includes("/")?$.dirname(e):"";for(let d=1;d{let l=Se(a).replace(/^\.$/,""),c=(n.filesByDir.get(l)??[]).filter(d=>d.endsWith(".go")).sort();return c.length?{kind:"resolved",target:c[0]}:{kind:"dangling",reason:"missing-package"}},s=n.goModules.find(a=>!a.dir||e===a.dir||e.startsWith(a.dir+"/"));if(s)for(let a of s.replaces){if(t!==a.from&&!t.startsWith(a.from+"/"))continue;let l=t.slice(a.from.length).replace(/^\//,"");return r($.join(a.toDir,l))}let o=s?[s,...n.goModules.filter(a=>a!==s)]:n.goModules;for(let a of o){if(t!==a.module&&!t.startsWith(a.module+"/"))continue;let l=t.slice(a.module.length).replace(/^\//,"");return r($.join(a.dir,l))}return{kind:"external"}}function rg(e,t,n){if(!n.rustCrates.length)return{kind:"external"};let r=(_,E)=>ft(n,[$.join(_,E+".rs"),$.join(_,E,"mod.rs")]),s=(_,E)=>{for(let b=E.length;b>=1;b--){let x=Se($.join(_,...E.slice(0,b-1))),v=r(x,E[b-1]);if(v)return v}},o=e.includes("/")?$.dirname(e):"",a=e.slice(e.lastIndexOf("/")+1).replace(/\.rs$/,""),l=a==="mod"||a==="lib"||a==="main",c=l?o:$.join(o,a);if(t.startsWith("mod ")){let _=t.slice(4),E=r(c,_)??(l?void 0:r(o,_));return E?{kind:"resolved",target:E}:{kind:"dangling",reason:"missing-module"}}let d=t.split("::").map(_=>_.trim()).filter(Boolean);if(!d.length)return{kind:"external"};let f=d[0],u=n.rustCrates.find(_=>!_.dir||e===_.dir||e.startsWith(_.dir+"/")),m,p=[];if(f==="crate"&&u)m=u.srcDir,p=d.slice(1);else if(f==="self")m=c,p=d.slice(1);else if(f==="super"){let _=l?o.includes("/")?$.dirname(o):"":o,E=1;for(;EE.name===f);if(_){let E=s(_.srcDir,d.slice(1));if(E)return{kind:"resolved",target:E};if(_.rootFile)return{kind:"resolved",target:_.rootFile}}return{kind:"external"}}if(!p.length)return{kind:"external"};let g=s(m,p);if(g)return{kind:"resolved",target:g};if(u&&m===u.srcDir&&u.rootFile)return{kind:"resolved",target:u.rootFile};let y=m.includes("/")?$.dirname(m):"",h=m.slice(m.lastIndexOf("/")+1),S=h?r(y,h):void 0;return S&&S!==e?{kind:"resolved",target:S}:{kind:"external"}}function sg(e,t){if(!t.javaRoots.length)return{kind:"external"};let n=o=>{for(let a of t.javaRoots){let l=Se($.join(a,o));if(l.endsWith("/*")||l==="*"){let c=l==="*"?"":l.slice(0,-2),d=(t.filesByDir.get(c)??[]).filter(f=>f.endsWith(".java")).sort();if(d.length)return d[0];continue}if(t.fileSet.has(l+".java"))return l+".java"}},r=e.replace(/\./g,"/"),s=n(r);if(!s&&!e.endsWith(".*")){let o=r.split("/");for(let a=o.length-1;a>=2&&!s;a--)s=n(o.slice(0,a).join("/"))}return s?{kind:"resolved",target:s}:{kind:"external"}}function ig(e,t,n){let r=e.includes("/")?$.dirname(e):"",s=ft(n,[$.join(r,t),...n.cIncludeRoots.map(o=>$.join(o,t))]);return s?{kind:"resolved",target:s}:{kind:"dangling",reason:"missing-include"}}function og(e,t,n){if(t.startsWith(".")){let r=e.includes("/")?$.dirname(e):"",s=Se($.join(r,t)),o=ft(n,[s+".rb",$.join(s,"index.rb")]);return o?{kind:"resolved",target:o}:{kind:"dangling",reason:"missing-module"}}for(let r of n.rubyLibRoots){let s=ft(n,[$.join(r,t+".rb")]);if(s)return{kind:"resolved",target:s}}return{kind:"external"}}function ag(e,t,n){if(t.startsWith(".")){let s=e.includes("/")?$.dirname(e):"",o=Se($.join(s,t)),a=ft(n,[o,o+".php"]);return a?{kind:"resolved",target:a}:{kind:"dangling",reason:"missing-module"}}let r=t.replace(/^\\+/,"");for(let{prefix:s,dir:o}of n.phpPsr4){if(s&&r!==s&&!r.startsWith(s+"\\"))continue;let a=s?r.slice(s.length).replace(/^\\+/,""):r,l=ft(n,[$.join(o,a.replace(/\\/g,"/"))+".php"]);if(l)return{kind:"resolved",target:l}}return{kind:"external"}}function lg(e,t){let n=t.csharpNamespaces.get(e);if(n?.length)return{kind:"resolved",target:n[0]};let r;for(let[s,o]of t.csharpNamespaces)if(s===e||s.startsWith(e+".")){let a=o[0];(r===void 0||M(a,r)<0)&&(r=a)}return r?{kind:"resolved",target:r}:{kind:"external"}}function or(e,t,n,r){let s=n.lastIndexOf(".");return s!==-1&&Wp.has(n.slice(s).toLowerCase().replace(/[?#].*$/,""))?{kind:"external"}:zp.has(t)||Hp.has(t)?eg(e,n,r):qp.has(t)?tg(e,n,r):t===".go"?ng(e,n,r):t===".rs"?rg(e,n,r):t===".java"?sg(n,r):Gp.has(t)?ig(e,n,r):t===".rb"||t===".rake"?og(e,n,r):t===".php"?ag(e,n,r):t===".cs"?lg(n,r):{kind:"external"}}var Wp,Up,Bp,zp,Hp,qp,Gp,Vp,jo,Zp,Ps=F(()=>{"use strict";k();oe();oe();Ae();Y();Wp=new Set([".svg",".png",".jpg",".jpeg",".gif",".webp",".bmp",".ico",".icns",".pdf",".woff",".woff2",".ttf",".otf",".eot",".mp3",".mp4",".mov",".avi",".webm",".wav",".flac",".ogg",".map"]),Up=["",".ts",".tsx",".d.ts",".mts",".cts",".js",".jsx",".mjs",".cjs",".vue",".svelte",".astro",".html",".htm"],Bp=["index.ts","index.tsx","index.js","index.jsx","index.mjs","index.cjs"],zp=new Set([".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs"]),Hp=new Set([".vue",".svelte",".astro",".html",".htm"]),qp=new Set([".py",".pyi"]),Gp=new Set([".c",".h",".cc",".cpp",".cxx",".hpp",".hh"]),Vp=new Set(["dist","build","lib","out","output","esm","cjs","umd"]);jo=["source","ts","import","module","require","node","default"],Zp=8});function Ls(e){return fg.test(e.split("/").pop())}function mg(e){return e.includes("/")?$.dirname(e):$s}function od(e){return e===$s?0:dg.test(e)||ug.test(e)?2:cg.test(e)?0:null}function pg(e,t){let n=od(e);return n!==null?n:t.every(r=>r.kind==="doc"||r.kind==="config"||Ls(r.rel))?2:1}function gg(e,t){let n=t.find(a=>/^(readme|index)\.(md|mdx)$/i.test(a.rel.split("/").pop()));if(n?.summary)return n.summary;if(n?.title)return n.title;let r=t.filter(a=>a.summary).sort((a,l)=>(l.summary?.length??0)-(a.summary?.length??0));if(r[0]?.summary)return r[0].summary;let s=[...new Set(t.map(a=>a.lang))].filter(a=>a!=="other"),o=e===$s?"the repository root":`\`${e}/\``;return`${t.length} file(s) in ${o}${s.length?` (${s.slice(0,3).join(", ")})`:""}.`}function Ho(e){let t=new Map;for(let c of e.files){let d=mg(c.rel),f=t.get(d);f||t.set(d,f=[]),f.push(c)}let n=[...t.keys()].sort(M),r=new Map,s=new Map;for(let c of n){let d=c===$s?"root":Pi(c);r.set(c,d),s.set(d,(s.get(d)??0)+1)}let o=c=>{let d=r.get(c);return d&&s.get(d)===1?d:`${d||"module"}-${Me(c).slice(0,8)}`},a=[],l=new Map;for(let c of n){let d=t.get(c).slice().sort((m,p)=>M(m.rel,p.rel)),f=o(c),u={slug:f,path:c,title:c,tier:pg(c,d),members:d.map(m=>m.rel),summary:gg(c,d)};a.push(u);for(let m of d)l.set(m.rel,f)}return a.sort((c,d)=>M(c.slug,d.slug)),{modules:a,moduleOf:l}}var $s,cg,dg,ug,fg,Ds=F(()=>{"use strict";k();oe();Ce();At();Y();$s="(root)",cg=/(^|\/)(types?|util|utils|lib|libs|common|core|config|configs|constants|shared|helpers|internal)$/i,dg=/(^|\/)(tests?|__tests?__|__mocks?__|__snapshots?__|spec|specs|e2e|examples?|example|benchmark|benchmarks|fixtures?|docs?|documentation|\.github)(\/|$)/i,ug=/(^|\/)(scripts?|bin|\.storybook)$/i,fg=/\.(test|spec|e2e|stories|story)\.[cm]?[jt]sx?$/i});function st(e){return e==="typescript"||e==="javascript"?"js":e==="c"||e==="cpp"?"c":e}function hg(e,t){let n=e.split("/"),r=t.split("/"),s=0;for(;sr?(r=a,n=o,s=!1):a===r&&(s=!0)}return s?void 0:n}function qo(e,t){let n=new Map,r=new Set;for(let o of e.files)for(let a of o.symbols){if(!a.exported||_g.has(a.kind))continue;let l=`${a.name} ${a.file}`;if(r.has(l))continue;r.add(l);let c=n.get(a.name);c||n.set(a.name,c=[]),c.push({file:a.file,lang:a.lang})}let s=new Map;for(let o of e.files){if(!o.calls?.length)continue;let a=st(o.lang),l=new Set(o.symbols.map(d=>d.name)),c=new Map;for(let d of o.calls)c.set(d.name,(c.get(d.name)??0)+1);for(let[d,f]of c){if(l.has(d))continue;let u=(n.get(d)??[]).filter(S=>st(S.lang)===a&&S.file!==o.rel);if(!u.length)continue;let m=u.filter(S=>t.has(`${o.rel}|${S.file}`)),p,g;if(a==="js"){if(!m.length)continue;p=rt(o.rel,m),g="extracted"}else m.length?(p=rt(o.rel,m),g="extracted"):(p=rt(o.rel,u),g="inferred");if(!p)continue;let y=`${o.rel}|${p.file}`,h=s.get(y);h?(h.weight+=f,g==="extracted"&&(h.confidence="extracted")):s.set(y,{from:o.rel,to:p.file,weight:f,confidence:g})}}return[...s.values()].map(o=>({from:o.from,to:o.to,kind:"call",weight:Math.min(o.weight,5),confidence:o.confidence})).sort((o,a)=>M(o.from,a.from)||M(o.to,a.to))}var _g,Sn=F(()=>{"use strict";k();Y();_g=new Set(["reexport","reexport-all","default"])});function ad(e){let t=new Map,n=new Set;for(let r of e.files)for(let s of r.symbols){if(!bg.has(s.kind))continue;let o=`${s.name} ${s.file}`;if(n.has(o))continue;n.add(o);let a=t.get(s.name);a||t.set(s.name,a=[]),a.push({name:s.name,file:s.file,kind:s.kind,lang:s.lang,line:s.line})}return t}function ar(e,t){let n=ad(e),r=[];for(let s of e.files){if(!s.relations?.length)continue;let o=st(s.lang);for(let a of s.relations){let l=(n.get(a.to)??[]).filter(m=>st(m.lang)===o);if(!l.length)continue;let c=l.filter(m=>t.has(`${s.rel}|${m.file}`)||m.file===s.rel),d=c.length?c:l,f=rt(s.rel,d.map(m=>({file:m.file,lang:m.lang})));if(!f)continue;let u=d.find(m=>m.file===f.file);r.push({kind:yg.has(u.kind)?"implements":a.kind,from:a.from,fromFile:s.rel,fromLine:a.line,to:u.name,toFile:u.file,toKind:u.kind})}}return r.sort((s,o)=>M(s.fromFile,o.fromFile)||M(s.from,o.from)||M(s.kind,o.kind)||M(s.to,o.to))}function Go(e,t){let n=new Map;for(let r of ar(e,t)){if(r.toFile===r.fromFile)continue;let s=`${r.fromFile}${je}${r.toFile}${je}${r.kind}`,o=n.get(s);o?o.weight=Math.min(o.weight+1,5):n.set(s,{from:r.fromFile,to:r.toFile,kind:r.kind,weight:1})}return[...n.values()].sort((r,s)=>M(r.from,s.from)||M(r.to,s.to)||M(r.kind,s.kind))}function kn(e,t){let n=ad(e),r=ar(e,t),s=new Map,o=(u,m)=>`${u}${je}${m}`;for(let u of n.values())for(let m of u)s.set(o(m.name,m.file),{name:m.name,file:m.file,line:m.line,kind:m.kind,extends:[],implements:[],extendedBy:[],implementedBy:[],unresolved:[]});let a=u=>({name:u.name,file:u.file,line:u.line,kind:u.kind});for(let u of r){let m=s.get(o(u.from,u.fromFile)),p=s.get(o(u.to,u.toFile));p&&(m?((u.kind==="extends"?m.extends:m.implements).push(a(p)),(u.kind==="extends"?p.extendedBy:p.implementedBy).push(a(m))):(u.kind==="extends"?p.extendedBy:p.implementedBy).push({name:u.from,file:u.fromFile,line:u.fromLine,kind:"unknown"}))}let l=new Set(r.map(u=>`${u.fromFile}${je}${u.from}${je}${u.kind}${je}${u.to}`));for(let u of e.files)for(let m of u.relations??[]){if(l.has(`${u.rel}${je}${m.from}${je}${m.kind}${je}${m.to}`))continue;let p=m.kind==="extends"?"implements":"extends";l.has(`${u.rel}${je}${m.from}${je}${p}${je}${m.to}`)||s.get(o(m.from,u.rel))?.unresolved.push({kind:m.kind,to:m.to})}let c=(u,m)=>M(u.name,m.name)||M(u.file,m.file),d=new Map,f=[...s.keys()].sort(M);for(let u of f){let m=s.get(u);m.extends.sort(c),m.implements.sort(c),m.extendedBy.sort(c),m.implementedBy.sort(c),m.unresolved.sort((p,g)=>M(p.kind,g.kind)||M(p.to,g.to)),d.has(m.name)?d.set(`${m.name}@${m.file}`,m):d.set(m.name,m)}return d}function lr(e,t){let n=e.get(t);if(!n)return[];let r=new Set([`${n.name}${je}${n.file}`]),s=[],o=[n];for(;o.length;){let a=[];for(let l of o)for(let c of[...l.implementedBy,...l.extendedBy]){let d=`${c.name}${je}${c.file}`;if(r.has(d))continue;r.add(d),s.push(c);let f=e.get(c.name)??e.get(`${c.name}@${c.file}`);f&&f.file===c.file&&a.push(f)}o=a}return s.sort((a,l)=>M(a.name,l.name)||M(a.file,l.file))}function wg(e,t){return e.get(t)}var je,yg,bg,Xt=F(()=>{"use strict";k();Sn();Y();je="\0",yg=new Set(["interface","trait","protocol"]),bg=new Set(["class","interface","trait","struct","type","enum","record","object","protocol","module","mod","union","annotation"])});function Vo(e){let t=En(e),n=new Map;if(!t.size)return n;let r=(s,o)=>{let a=n.get(s);a||n.set(s,a=new Set),a.add(o)};for(let s of e.files)if(s.kind==="code"&&s.idents)for(let o of s.idents){let a=t.get(o);a&&a!==s.rel&&r(o,s.rel)}else if(s.kind==="doc"){let o=e.docText.get(s.rel);if(!o)continue;for(let a of o.split(/[^A-Za-z0-9_]+/)){let l=t.get(a);l&&l!==s.rel&&r(a,s.rel)}}return n}function Jo(e,t=new Map,n=5){let r=new Map;for(let a of e.files)for(let l of a.symbols){let c=r.get(l.name);c||r.set(l.name,c=[]),c.push({file:l.file,line:l.line,...l.endLine!==void 0?{endLine:l.endLine}:{},kind:l.kind,exported:l.exported,lang:l.lang,...l.parent?{parent:l.parent}:{}})}let s={};for(let a of[...r.keys()].sort(M))s[a]=r.get(a).slice().sort((l,c)=>M(l.file,c.file)||l.line-c.line||M(l.kind,c.kind));let o={};for(let a of[...t.keys()].sort(M)){let l=[...t.get(a)].sort(M);l.length&&(o[a]=l)}return{schemaVersion:n,defs:s,refs:o}}function js(e){return JSON.stringify(e,null,2)+` +`}var cr=F(()=>{"use strict";k();Xe();Y();mt()});function dr(e){return new Set(Qt(e))}function Zt(e,t,n={}){let r=t??Qt(e),s=n.recall===!0,o=new Map;for(let m of e.files){let p=new Set;for(let g of m.symbols){if(!g.exported||Ws.has(g.kind)||p.has(g.name))continue;p.add(g.name);let y=o.get(g.name);y||o.set(g.name,y=[]),y.push(g)}}let a=new Map;for(let[m,p]of o){let g=new Map;for(let y of p){let h=st(y.lang),S=g.get(h);S||g.set(h,S=[]),S.push(y)}a.set(m,g)}let l=new Map;for(let m of e.files){let p=new Map;for(let g of m.symbols)!Ws.has(g.kind)&&!p.has(g.name)&&p.set(g.name,g);l.set(m.rel,p)}let c=new Map,d=(m,p)=>{let g=c.get(m.name+"\0"+m.file);g||c.set(m.name+"\0"+m.file,g={def:m,callers:[]}),g.callers.push(p)};for(let m of e.files){if(!m.calls?.length)continue;let p=st(m.lang),g=l.get(m.rel);for(let y of m.calls){let h=g.get(y.name);if(h){h.line!==y.line&&d(h,s?{file:m.rel,line:y.line,confidence:"corroborated"}:{file:m.rel,line:y.line});continue}let S=(a.get(y.name)?.get(p)??[]).filter(x=>x.file!==m.rel);if(!S.length)continue;let _=S.filter(x=>r.has(`${m.rel}|${x.file}`)),E=p==="js"?_.length?rt(m.rel,_):s&&S.length===1?S[0]:void 0:_.length?rt(m.rel,_):rt(m.rel,S);if(!E)continue;d(E,s?{file:m.rel,line:y.line,confidence:_.length?"corroborated":"unique-name"}:{file:m.rel,line:y.line})}}let f=new Map,u=[...c.keys()].sort(M);for(let m of u){let{def:p,callers:g}=c.get(m);g.sort((y,h)=>M(y.file,h.file)||y.line-h.line),f.has(p.name)?f.set(`${p.name}@${p.file}`,{def:p,callers:g}):f.set(p.name,{def:p,callers:g})}return f}function xg(e,t,n){let r=e.files.find(s=>s.rel===t);if(r?.symbols.length)return Us(r.symbols,n)}function Us(e,t){let n;for(let r of e)Ws.has(r.kind)||r.line>t||r.endLine!==void 0&&t>r.endLine||(!n||r.line>n.line||r.line===n.line&&(r.endLine??1/0)<=(n.endLine??1/0))&&(n=r);return n}function Sg(e){let t=new Map;for(let r of e.files){if(!r.calls?.length)continue;let s=r.symbols.filter(o=>!Ws.has(o.kind));for(let o of r.calls){let a={file:r.rel,line:o.line};o.receiver!==void 0&&(a.receiver=o.receiver);let l=Us(s,o.line);l&&(a.enclosingSymbol=l);let c=t.get(o.name);c||t.set(o.name,c=[]),c.push(a)}}let n=new Map;for(let r of[...t.keys()].sort(M)){let s=t.get(r);s.sort((o,a)=>M(o.file,a.file)||o.line-a.line),n.set(r,s)}return n}var Ws,Yt=F(()=>{"use strict";k();Sn();mt();Y();Ws=new Set(["reexport","reexport-all","default"])});function en(e){return e.parent?`${e.file}#${e.parent}/${e.name}`:`${e.file}#${e.name}`}function Eg(e){return{id:en(e),name:e.name,kind:e.kind,file:e.file,line:e.line,...e.endLine!==void 0?{endLine:e.endLine}:{},exported:e.exported,...e.doc?{doc:e.doc}:{},...e.signature?{signature:e.signature}:{}}}function ur(e,t){let n=new Map,r=new Map,s=new Map,o=new Set;for(let p of e.files){let g=[];for(let y of p.symbols){if(kg.has(y.kind)||(g.push(y),n.set(en(y),Eg(y)),!y.exported))continue;let h=`${y.name} ${y.file}`;if(o.has(h))continue;o.add(h);let S=s.get(y.name);S||s.set(y.name,S=[]),S.push(y)}r.set(p.rel,g)}let a=new Map,l=(p,g,y)=>{if(p===g)return;let h=`${p}${Bs}${g}${Bs}${y}`,S=a.get(h);S?S.weight+=1:a.set(h,{from:p,to:g,kind:y,weight:1})};for(let p of e.files){if(!p.calls?.length)continue;let g=st(p.lang),y=r.get(p.rel)??[],h=new Map;for(let S of y)h.has(S.name)||h.set(S.name,S);for(let S of p.calls){let _=Us(y,S.line);if(!_)continue;let E=h.get(S.name);if(E){E.line!==S.line&&l(en(_),en(E),"calls");continue}let b=(s.get(S.name)??[]).filter(N=>st(N.lang)===g&&N.file!==p.rel);if(!b.length)continue;let x=b.filter(N=>t.has(`${p.rel}|${N.file}`)),v=x.length?x:g==="js"?[]:b;if(!v.length)continue;let A=rt(p.rel,v.map(N=>({file:N.file,lang:N.lang})));if(!A)continue;let O=v.find(N=>N.file===A.file);l(en(_),en(O),"calls")}}let c=new Map;for(let p of n.values())c.set(`${p.name} ${p.file}`,p.id);for(let p of ar(e,t)){let g=c.get(`${p.from} ${p.fromFile}`),y=c.get(`${p.to} ${p.toFile}`);g&&y&&l(g,y,p.kind)}let d=[...a.values()].sort((p,g)=>M(p.from,g.from)||M(p.kind,g.kind)||M(p.to,g.to)),f=new Map,u=new Map;for(let p of d)(f.get(p.from)??f.set(p.from,[]).get(p.from)).push(p),(u.get(p.to)??u.set(p.to,[]).get(p.to)).push(p);let m=new Map;for(let p of[...n.keys()].sort(M)){let g=n.get(p);(m.get(g.name)??m.set(g.name,[]).get(g.name)).push(p)}return{nodes:n,edges:d,out:f,in:u,byName:m}}function fr(e,t,n={}){let r=Math.max(1,Math.min(n.depth??2,vg)),s=n.direction??"both",o=e.nodes.has(t)?[t]:e.byName.get(t)??[...e.nodes.keys()].filter(p=>p.endsWith(`#${t}`)),a=o.map(p=>e.nodes.get(p)).filter(Boolean);if(!a.length)return{root:[],nodes:[],edges:[]};let l=new Map;for(let p of o)l.set(p,0);let c=new Map,d=[...o],f=!1;for(let p=1;p<=r&&d.length;p++){let g=[];for(let y of d){let h=(S,_)=>{for(let E of S??[]){c.set(`${E.from}${Bs}${E.to}${Bs}${E.kind}`,E);let b=_(E);if(!l.has(b)){if(l.size>=Rg){f=!0;continue}l.set(b,p),g.push(b)}}};s!=="in"&&h(e.out.get(y),S=>S.to),s!=="out"&&h(e.in.get(y),S=>S.from)}d=g}let u=[...l.entries()].map(([p,g])=>({...e.nodes.get(p),depth:g})).sort((p,g)=>p.depth-g.depth||M(p.file,g.file)||M(p.name,g.name)),m=[...c.values()].filter(p=>l.has(p.from)&&l.has(p.to)).sort((p,g)=>M(p.from,g.from)||M(p.kind,g.kind)||M(p.to,g.to));return{root:a,nodes:u,edges:m,...f?{truncated:!0}:{}}}var Bs,kg,vg,Rg,mr=F(()=>{"use strict";k();Sn();Yt();Xt();Y();Bs="\0",kg=new Set(["reexport","reexport-all","default"]);vg=5,Rg=400});function $t(e){if(Cg.test(e)||Ls(e))return!0;let t=e.split("/").pop();return Mg.some(n=>n.test(t))}function pr(e){let t=new Set,n=new Map;for(let a of e.files)n.set(a.rel,a.module),a.fileKind==="code"&&$t(a.rel)&&t.add(a.rel);let r=new Map,s=new Map;for(let a of e.fileEdges){if(a.dangling||a.kind!=="import"&&a.kind!=="use"&&a.kind!=="call"||!t.has(a.from)||t.has(a.to))continue;let l=r.get(a.to);l||r.set(a.to,l=new Set),l.add(a.from);let c=n.get(a.to);if(c!==void 0){let d=s.get(c);d||s.set(c,d=new Set),d.add(a.from)}}let o=a=>{let l=new Map;for(let c of[...a.keys()].sort(M))l.set(c,[...a.get(c)].sort(M));return l};return{testFiles:t,testedByFile:o(r),testedByModule:o(s)}}function Ag(e,t){let n=e.modules.find(r=>r.slug===t);return n?.testedBy?n.testedBy:pr(e).testedByModule.get(t)??[]}function Tg(e){let t=pr(e),n=new Map;for(let r of e.files)r.fileKind!=="code"||t.testFiles.has(r.rel)||n.set(r.module,(n.get(r.module)??0)+1);return e.modules.filter(r=>r.tier<=1&&r.symbols>0&&(n.get(r.slug)??0)>0&&!t.testedByModule.has(r.slug))}var Mg,Cg,vn=F(()=>{"use strict";k();Ds();Y();Mg=[/^test_.*\.py$/i,/_test\.py$/i,/_test\.go$/,/(Test|Tests|IT)\.java$/,/(Test|Tests)\.kt$/,/_spec\.rb$/,/_test\.rb$/,/Test\.php$/,/(Test|Tests)\.cs$/,/_test\.exs$/],Cg=/(^|\/)(tests?|__tests?__|spec|specs|e2e)(\/|$)/i});function Rn(e,t,n){let r=e.fields[t];for(let s of ht(n))r.tf.set(s,(r.tf.get(s)??0)+1),r.len++,e.all.add(s)}function jg(){let e={};for(let t of zs)e[t]={tf:new Map,len:0};return e}function Hs(e){let t=[];for(let n of e.files){let r={file:n.rel,fields:jg(),all:new Set,symbols:[],decls:[],exactNames:new Set,isTest:$t(n.rel)},s=new Set;for(let o of n.symbols)Rn(r,"name",o.name),o.doc&&Rn(r,"doc",o.doc),r.exactNames.add(_t(o.name).toLowerCase()),s.has(o.name)||(s.add(o.name),r.symbols.push(o.name),r.decls.push({name:o.name,kind:o.kind,line:o.line}));for(let o of n.rel.split("/"))Rn(r,"path",o);for(let o of n.headings)Rn(r,"heading",o);n.summary&&Rn(r,"summary",n.summary);for(let o of n.terms??[])Rn(r,"body",o);t.push(r)}return t}function fd(e){let t=`^^${e}$$`,n=new Set;for(let r=0;r+3<=t.length;r++)n.add(t.slice(r,r+3));return n}function Wg(e,t){if(!e.size||!t.size)return 0;let n=0;for(let r of e)t.has(r)&&n++;return 2*n/(e.size+t.size)}function md(e){let t=new Set,n=new Map;for(let r of e)for(let s of r.all){if(t.has(s))continue;t.add(s);let o=Li(s);if(o===s)continue;let a=n.get(o);a||n.set(o,a=[]),a.push(s)}for(let r of n.values())r.sort(M);return n}function pd(e){let t=new Map;for(let n of e)for(let r of n.all)t.has(r)||t.set(r,fd(r));return t}function Lt(e,t,n={}){return gd(e,t,n).results}function tn(e,t,n={}){return gd(e,t,n)}function dd(e,t,n){return{results:[],explain:{query:e,terms:[],droppedStopwords:ss(e),unresolvedTerms:[],verdict:t,note:n,bridgedOnlyResults:0,resultCount:0}}}function gd(e,t,n={}){let r=[],s=new Set;for(let _ of rs(t))for(let E of ht(_))s.has(E)||(s.add(E),r.push(E));if(!r.length){let _=ss(t);return dd(t,"none",_.length?`Nothing was searched for: every token in this query (${_.join(", ")}) is a stopword or too short to index. Search with the identifiers or domain words you are actually looking for.`:"Nothing was searched for: the query carried no indexable token.")}let o=r.some(_=>Dg.test(_)),a=_d(e),l=a.length;if(!l)return dd(t,"none","This index contains no files.");let c={};for(let _ of zs){let E=0;for(let b of a)E+=b.fields[_].len;c[_]=E/l||1}let d=new Map;for(let _ of r){let E=0;for(let b of a)b.all.has(_)&&E++;d.set(_,E)}let f=n.fuzzy??!0,u=new Map;if(f){let _=r.filter(E=>d.get(E)===0);if(_.length){let E=bd(e),b=[];for(let x of _){let v=(E.get(Li(x))??[]).filter(A=>A!==x);v.length?u.set(x,v.slice(0,cd).map(A=>({term:A,dice:ud}))):b.push(x)}if(b.length){let x=hd(e);for(let v of b){let A=fd(v),O=[];for(let[N,U]of x){let le=Wg(A,U);le>=Og&&O.push({term:N,dice:le})}O.sort((N,U)=>U.dice-N.dice||M(N.term,U.term)),u.set(v,O.slice(0,cd))}}}}let m=new Map,p=_=>{let E=d.get(_)??m.get(_);if(E!==void 0)return E;let b=0;for(let x of a)x.all.has(_)&&b++;return m.set(_,b),b},g=_=>Math.log(1+(l-_+.5)/(_+.5)),y=n.rank==="graph"?yd(e):void 0,h=[];for(let _ of a){let E=0,b=[],x=new Set,v=new Set,A=new Set,O=!1,N=z=>{let P=0;for(let j of zs){let B=_.fields[j],re=B.tf.get(z);if(!re)continue;x.add(j);let J=Pg[j];P+=Fg[j]*re/(1-J+J*B.len/c[j])}return P};for(let z of r){let P=N(z);if(P>0){b.push(z),v.add(z),_.exactNames.has(z)&&(O=!0),E+=g(d.get(z))*(P/(ld+P));continue}for(let j of u.get(z)??[]){let B=N(j.term);B&&(E+=g(p(j.term))*(B/(ld+B))*j.dice,v.add(j.term),A.add(z))}}if(!b.length&&!A.size)continue;O&&(E*=$g),_.isTest&&!o&&(E*=Lg),y&&(E*=1+.35*Math.log1p(y.get(_.file)??0));let le=_.decls.map(z=>{let P=new Set(ht(z.name)),j=0;for(let B of v)P.has(B)&&j++;return{decl:z,hits:j}}).filter(z=>z.hits>0).sort((z,P)=>P.hits-z.hits||M(z.decl.name,P.decl.name)).slice(0,Ng).map(z=>z.decl),V={file:_.file,score:Number(E.toFixed(4)),matchedTerms:b.sort(M),topSymbols:le.map(z=>z.name)};x.size&&(V.matchedFields=zs.filter(z=>x.has(z))),le.length&&(V.symbolHits=le,V.line=Math.min(...le.map(z=>z.line))),A.size&&(V.fuzzyTerms=[...A].sort(M)),b.length||(V.bridgedOnly=!0),h.push(V)}h.sort((_,E)=>E.score-_.score||M(_.file,E.file));let S=(n.exact?h.filter(_=>!_.bridgedOnly):h).slice(0,n.limit??Ig);return{results:S,explain:Ug(t,r,d,u,S)}}function Ug(e,t,n,r,s){let o=t.map(g=>{let y=n.get(g)??0,h=y===0?r.get(g)??[]:[];if(!h.length)return{term:g,df:y};let S=h[0].dice===ud?"stem":"trigram";return{term:g,df:y,bridge:{via:S,to:h.map(_=>_.term),dice:h[0].dice}}}),a=o.filter(g=>g.df===0&&!g.bridge).map(g=>g.term).sort(M),l=!/\s/.test(e.trim())&&t.length?{term:t[0],df:n.get(t[0])??0}:void 0,c=s.filter(g=>g.bridgedOnly).length,d=s.length>0&&c===s.length,f=l?.df===0,u=s.length?f||d?"weak":"match":"none",m={query:e,terms:o,droppedStopwords:ss(e),unresolvedTerms:a,...l?{wholeIdentifier:l}:{},verdict:u,bridgedOnlyResults:c,resultCount:s.length},p=Bg(m,f,d);return p&&(m.note=p),m}function Bg(e,t,n){let{verdict:r,wholeIdentifier:s,resultCount:o,terms:a}=e;if(r!=="match"){if(!o)return e.unresolvedTerms.length?`No file matches. ${e.unresolvedTerms.length===1?"The term":"The terms"} ${e.unresolvedTerms.join(", ")} appear nowhere in this index.`:"No file matches this query.";if(t&&s){let l=a.filter(u=>u.term!==s.term&&u.df>0).map(u=>u.term).join(", "),c=a.find(u=>u.term===s.term)?.bridge?.to??[],d=l?` The ${o} result${o===1?"":"s"} below match only its parts (${l}).`:"",f=c.length?` Closest indexed name${c.length===1?"":"s"}: ${c.join(", ")}.`:"";return`No file in this index defines or mentions "${s.term}".${d}${f} If you expected it here, check you are indexing the right branch or commit.`}if(n)return`Nothing matched verbatim. Every result below came from a near match: ${a.filter(d=>d.bridge).map(d=>`"${d.term}" \u2192 ${d.bridge.to.join(", ")}`).join("; ")}. Re-run with --exact to see only literal matches.`}}var ld,Ig,Ng,Og,cd,ud,zs,Fg,Pg,$g,Lg,Dg,Mn=F(()=>{"use strict";k();mt();Ce();vn();Y();ld=1.2,Ig=20,Ng=5,Og=.6,cd=3,ud=.9,zs=["name","path","heading","summary","doc","body"],Fg={name:3,path:2,heading:1.5,summary:1.5,doc:1.6,body:.7},Pg={name:.75,path:.75,heading:.75,summary:.75,doc:.75,body:.4},$g=1.35,Lg=.65,Dg=/^(test|tests|spec|specs|fixture|fixtures|mock|mocks|stub|stubs)$/});function gr(e,t,n=.85){let r=new Map,s=e.length;if(s===0)return r;let o=new Map(e.map((d,f)=>[d,f])),a=Array.from({length:s},()=>[]),l=new Array(s).fill(0);for(let d of t){if(d.dangling)continue;let f=o.get(d.from),u=o.get(d.to);f===void 0||u===void 0||f===u||(a[f].push([u,d.weight]),l[f]+=d.weight)}let c=new Array(s).fill(1/s);for(let d=0;d<100;d++){let f=0;for(let g=0;gr.set(d,c[f])),r}function wd(e,t){let n=new Map;for(let d of e)n.set(d,0);let r=e.length;if(r<3)return n;let s=new Map(e.map((d,f)=>[d,f])),o=Array.from({length:r},()=>new Set);for(let d of t){if(d.dangling)continue;let f=s.get(d.from),u=s.get(d.to);f===void 0||u===void 0||f===u||(o[f].add(u),o[u].add(f))}let a=o.map(d=>[...d].sort((f,u)=>f-u)),l=new Array(r).fill(0);for(let d=0;d[]),m=new Array(r).fill(0),p=new Array(r).fill(-1);m[d]=1,p[d]=0;let g=[d];for(let h=0;h=0;h--){let S=f[h];for(let _ of u[S])y[_]+=m[_]/m[S]*(1+y[S]);S!==d&&(l[S]+=y[S])}}let c=(r-1)*(r-2)/2;return e.forEach((d,f)=>n.set(d,l[f]/2/c)),n}function Ko(e){let t=[],n=e.modules.length;if(n>0){let s=e.modules.map(a=>a.id),o=gr(s,e.moduleEdges);for(let a of e.modules)a.pagerank=Number(((o.get(a.id)??0)*n).toFixed(4));if(n>3e3)t.push(`betweenness skipped (${n} modules > 3000)`);else{let a=wd(s,e.moduleEdges);for(let l of e.modules)l.betweenness=Number((a.get(l.id)??0).toFixed(6))}}let r=e.files.length;if(r>0){let s=e.files.map(a=>a.id),o=gr(s,e.fileEdges);for(let a of e.files)a.pagerank=Number(((o.get(a.id)??0)*r).toFixed(4))}return t}var qs=F(()=>{"use strict";k()});function Gs(e){return 1+(e.match(zg)??[]).length}function _r(e,t,n=50){let r=[];for(let s of e.files){if(s.kind!=="code"||t&&s.rel!==t||!s.symbols.length)continue;let o=G(I(e.root,s.rel)).split(` `);for(let a of s.symbols){if(a.kind==="reexport"||a.kind==="reexport-all")continue;let l=a.endLine??a.line,c=o.slice(a.line-1,l).join(` -`),d={file:s.rel,name:a.name,line:a.line,complexity:$s(c)};a.endLine!==void 0&&(d.endLine=a.endLine),r.push(d)}}return r.sort((s,o)=>o.complexity-s.complexity||R(s.file,o.file)||s.line-o.line),r.slice(0,n)}function pr(e,t,n=20){let r=ld(e),s=e.files.filter(o=>o.kind==="code").map(o=>{let a=r.get(o.rel),l=t.get(o.rel)??0;return{file:o.rel,complexity:a,commits:l,score:(l+1)*a}});return s.sort((o,a)=>a.score-o.score||R(o.file,a.file)),s.slice(0,n)}var vg,gr=O(()=>{"use strict";S();ie();dt();Te();K();vg=/\b(if|elif|elsif|else\s+if|for|foreach|while|until|unless|case|when|match|catch|rescue|except)\b|&&|\|\||(?s.rel),r=[];for(let s of Yt(e)){let o=s.indexOf("|");r.push({from:s.slice(0,o),to:s.slice(o+1),kind:"import",weight:1})}t.importPagerank=fr(n,r)}return t.importPagerank}function od(e){let t=Ge(e),n=t.bm25??={docs:Fs(e)};return n.stems??=ed(n.docs)}function ld(e){let t=Ge(e);if(!t.fileComplexity){let n=new Map;for(let r of e.files)r.kind==="code"&&n.set(r.rel,$s(G(I(e.root,r.rel))));t.fileComplexity=n}return t.fileComplexity}var jo,dt=O(()=>{"use strict";S();ie();vs();Ls();or();Zt();Kt();dr();vn();Ps();gr();Te();jo=new WeakMap});function Rg(e){return e.length<5?!1:/[a-z][A-Z]/.test(e)||/[A-Z]{2}/.test(e)||e.includes("_")||/\d/.test(e)}function Bo(e){let t=new Map;for(let r of e.files)for(let s of r.symbols){if(!s.exported||Mg.has(s.kind)||!Rg(s.name))continue;let o=t.get(s.name);o||t.set(s.name,o=new Set),o.add(r.rel)}let n=new Map;for(let[r,s]of t)s.size===1&&n.set(r,[...s][0]);return n}function Pt(e,t){let n=Cg(t.from,t.to,t.kind),r=e.get(n);if(r){r.weight+=t.weight;return}e.set(n,{...t})}function zo(e,t,n,r,s){let o=new Map,a=new Set;for(let k of e.files)for(let C of k.refs)if(C.kind==="doc-link"){let A=No(k.rel,C.spec,t);if(A.kind==="external")continue;A.kind==="dangling"?Pt(o,{from:k.rel,to:C.spec,kind:"doc-link",weight:1,dangling:!0,reason:A.reason}):A.target!==k.rel&&Pt(o,{from:k.rel,to:A.target,kind:"doc-link",weight:1})}else{let A=rr(k.rel,k.ext,C.spec,t);if(A.kind==="external")continue;A.kind==="dangling"?Pt(o,{from:k.rel,to:C.spec,kind:"import",weight:1,dangling:!0,reason:A.reason}):A.target!==k.rel&&(Pt(o,{from:k.rel,to:A.target,kind:"import",weight:1}),a.add(`${k.rel}|${A.target}`))}let l=new Set;for(let k of Fo(e,a))Pt(o,k),l.add(`${k.from}|${k.to}`);for(let k of Po(e,a))Pt(o,k),l.add(`${k.from}|${k.to}`);cd(e,t,a);let c=Sn(e);if(c.size)for(let k of e.files){if(k.kind!=="code"||!k.idents?.length)continue;let C=new Map;for(let A of k.idents){let F=c.get(A);!F||F===k.rel||C.set(F,(C.get(F)??0)+1)}for(let[A,F]of C){let N=`${k.rel}|${A}`;a.has(N)||l.has(N)||Pt(o,{from:k.rel,to:A,kind:"use",weight:Math.min(F,5)})}}if(c.size)for(let k of e.files){if(k.kind!=="doc")continue;let C=e.docText.get(k.rel)??G(I(e.root,k.rel));if(!C)continue;let A=new Map;for(let F of C.split(/[^A-Za-z0-9_]+/))c.has(F)&&A.set(F,(A.get(F)??0)+1);for(let[F,N]of A){let W=c.get(F);W!==k.rel&&Pt(o,{from:k.rel,to:W,kind:"mention",weight:Math.min(N,5)})}}let d=[...o.values()].sort((k,C)=>R(k.from,C.from)||R(k.to,C.to)||R(k.kind,C.kind)),u=new Map,f=new Map,p=new Set(e.files.map(k=>k.rel));for(let k of d)k.dangling||!p.has(k.to)||(f.set(k.from,(f.get(k.from)??0)+1),u.set(k.to,(u.get(k.to)??0)+1));let m={import:7,extends:6,implements:5,call:4,use:3,"doc-link":2,mention:1,contains:0},g=new Map;for(let k of d){if(k.dangling||!p.has(k.to))continue;let C=r.get(k.from),A=r.get(k.to);if(!C||!A||C===A)continue;let F=`${C}${Ho}${A}`,N=g.get(F);N?(N.weight+=k.weight,(m[k.kind]??0)>(m[N.kind]??0)&&(N.kind=k.kind)):g.set(F,{from:C,to:A,kind:k.kind,weight:k.weight})}let h=[...g.values()].sort((k,C)=>R(k.from,C.from)||R(k.to,C.to)),_=new Map,y=new Map;for(let k of h)y.set(k.from,(y.get(k.from)??0)+1),_.set(k.to,(_.get(k.to)??0)+1);let x=e.files.map(k=>({id:k.rel,kind:"file",rel:k.rel,fileKind:k.kind,lang:k.lang,module:r.get(k.rel)??"root",title:k.title,summary:k.summary,symbols:k.symbols.length,lines:k.lines,degIn:u.get(k.rel)??0,degOut:f.get(k.rel)??0})).sort((k,C)=>R(k.rel,C.rel)),E=new Map;for(let k of e.files){let C=r.get(k.rel)??"root";E.set(C,(E.get(C)??0)+k.symbols.length)}let w=n.map(k=>({id:k.slug,kind:"module",slug:k.slug,path:k.path,title:k.title,summary:k.summary,tier:k.tier,members:k.members,symbols:E.get(k.slug)??0,degIn:_.get(k.slug)??0,degOut:y.get(k.slug)??0})).sort((k,C)=>R(k.slug,C.slug));return{schemaVersion:s?.schemaVersion??5,version:s?.version??fe,commit:e.commit,fileCount:e.files.length,languages:e.languages,files:x,modules:w,fileEdges:d,moduleEdges:h}}var Mg,Ho,Cg,Ls=O(()=>{"use strict";S();ie();qe();vs();wn();Kt();dt();Te();K();Mg=new Set(["reexport","reexport-all","default"]);Ho="\0",Cg=(e,t,n)=>`${e}${Ho}${t}${Ho}${n}`});function qo(e,t){let n=e.files.find(r=>r.rel===t);return n?[...n.symbols].filter(r=>!Go.has(r.kind)).sort((r,s)=>r.line-s.line||R(r.name,s.name)):[]}function Mn(e,t,n={}){let r=t.split("/").filter(Boolean);if(!r.length)return[];let s=r[r.length-1],o=r.slice(0,-1),a=(d,u)=>n.substring?d.toLowerCase().includes(u.toLowerCase()):d===u,l=[];for(let d of e.files)for(let u of d.symbols)if(!Go.has(u.kind)&&a(u.name,s)){if(o.length){let f=o[o.length-1];if(!u.parent||u.parent!==f)continue}l.push({...u})}l.sort((d,u)=>+(u.name===s)-+(d.name===s)||R(d.file,u.file)||d.line-u.line);let c=l.slice(0,n.maxResults??50);if(n.includeBody)for(let d of c){let u=d.endLine??d.line,f=G(I(e.root,d.file));f&&(d.body=f.split(` -`).slice(d.line-1,u).join(` -`))}return n.concise?c.map(d=>({name:d.name,kind:d.kind,file:d.file,line:d.line,...d.body!==void 0?{body:d.body}:{}})):c}function Vo(e,t){let n=[];for(let d of e.files)for(let u of d.symbols)u.name===t&&!Go.has(u.kind)&&n.push(u);n.sort((d,u)=>R(d.file,u.file)||d.line-u.line);let s=Rn(e).get(t),o=s?[...s.callers]:[],a=new Set,c=Sn(e).get(t);for(let d of e.files)if(d.rel!==c){if(d.kind==="code"&&d.idents?.includes(t))a.add(d.rel);else if(d.kind==="doc"){let u=e.docText.get(d.rel);u&&new RegExp(`\\b${t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}\\b`).test(u)&&a.add(d.rel)}}for(let d of o)a.add(d.file);return{defs:n,callSites:o,referencingFiles:[...a].sort(R)}}var Go,js=O(()=>{"use strict";S();ie();Te();dt();K();Go=new Set(["reexport","reexport-all","default"])});function Us(e,t,n){let r=Mn(e,t);if(n&&(r=r.filter(o=>o.file===n)),r.length===1)return r[0];if(r.length===0){let o=Mn(e,t,{substring:!0,maxResults:5}).map(a=>`${a.file}:${a.line} ${a.parent?a.parent+"/":""}${a.name}`).join(", ");throw new Error(`no symbol matches "${t}"${n?` in ${n}`:""}${o?` \u2014 near matches: ${o}`:""}`)}let s=r.map(o=>`${o.file}:${o.line}`).join(", ");throw new Error(`"${t}" is ambiguous (${r.length} matches: ${s}) \u2014 qualify with \`file\` or a Parent/name path`)}function ud(e){return te(e,"utf8").split(` -`)}function Jo(e,t,n,r){let s=Us(e,t,r),o=s.endLine??s.line,a=I(e.root,s.file),l=ud(a),c=n.replace(/^\n+|\n+$/g,"").split(` -`);return l.splice(s.line-1,o-s.line+1,...c),Re(a,l.join(` -`)),{file:s.file,startLine:s.line,endLine:s.line+c.length-1,lines:c.length}}function fd(e,t,n,r,s,o){let a=I(e.root,t.file),l=ud(a),c=Ag.has(t.kind)?1:0,d=n.replace(/^\n+|\n+$/g,"").split(` -`),u=[];return s&&c&&l[r-1]?.trim()!==""&&u.push(""),u.push(...d),o&&c&&l[r]?.trim()!==""&&u.push(""),l.splice(r,0,...u),Re(a,l.join(` -`)),{file:t.file,startLine:r+1,endLine:r+u.length,lines:u.length}}function Ko(e,t,n,r){let s=Us(e,t,r),o=s.endLine??s.line;return fd(e,s,n,o,!0,!0)}function Xo(e,t,n,r){let s=Us(e,t,r);return fd(e,s,n,s.line-1,!0,!0)}var Ag,Zo=O(()=>{"use strict";S();we();ie();js();Ag=new Set(["function","method","class","interface","struct","trait","enum","def"])});function pd(e){let t=e.replace(/^mem:/,"").replace(/\.md$/,"");if(!t)throw new Error("memory name is empty");let n=t.split("/");for(let r of n){if(!r||r==="."||r===".."||r.includes("\\"))throw new Error(`invalid memory name: "${e}"`);if(!/^[\w][\w.-]*$/.test(r))throw new Error(`invalid memory name segment: "${r}"`)}return t}function Yo(e,t){return I(e,...md,`${pd(t)}.md`)}function _r(e,t,n){let r=Yo(e,t);return ft(Se(r),{recursive:!0}),Re(r,n.endsWith(` +`),d={file:s.rel,name:a.name,line:a.line,complexity:Gs(c)};a.endLine!==void 0&&(d.endLine=a.endLine),r.push(d)}}return r.sort((s,o)=>o.complexity-s.complexity||M(s.file,o.file)||s.line-o.line),r.slice(0,n)}function hr(e,t,n=20){let r=xd(e),s=e.files.filter(o=>o.kind==="code").map(o=>{let a=r.get(o.rel),l=t.get(o.rel)??0;return{file:o.rel,complexity:a,commits:l,score:(l+1)*a}});return s.sort((o,a)=>a.score-o.score||M(o.file,a.file)),s.slice(0,n)}var zg,yr=F(()=>{"use strict";k();oe();mt();Ae();Y();zg=/\b(if|elif|elsif|else\s+if|for|foreach|while|until|unless|case|when|match|catch|rescue|except)\b|&&|\|\||(?[n.rel,n]))}function kd(e){let t=We(e);if(!t.symbolsByName){let n=new Map;for(let r of e.files)for(let s of r.symbols){let o=n.get(s.name);o?o.push(s):n.set(s.name,[s])}t.symbolsByName=n}return t.symbolsByName}function Zo(e){let t=We(e);return t.resolveCtx??=Bo(e)}function Qt(e){let t=We(e);if(!t.importPairs){let n=Zo(e),r=new Set;for(let s of e.files)for(let o of s.refs){if(o.kind!=="import")continue;let a=or(s.rel,s.ext,o.spec,n);a.kind==="resolved"&&a.target!==s.rel&&r.add(`${s.rel}|${a.target}`)}t.importPairs=r}return t.importPairs}function Ed(e,t,n){let r=Xo.get(e);!r||r.resolveCtx!==t||r.importPairs||(r.importPairs=n)}function En(e){let t=We(e);return t.uniqueDefs??=Qo(e)}function Vs(e){let t=We(e);return t.symbolRefs??=Vo(e)}function Cn(e){let t=We(e);return t.callerIndex??=Zt(e,Qt(e))}function Yo(e){let t=We(e);return t.hierarchy??=kn(e,Qt(e))}function vd(e){let t=We(e);return t.symbolGraph??=ur(e,Qt(e))}function _d(e){let t=We(e);return(t.bm25??={docs:Hs(e)}).docs}function hd(e){let t=We(e),n=t.bm25??={docs:Hs(e)};return n.trigrams??=pd(n.docs)}function yd(e){let t=We(e);if(!t.importPagerank){let n=e.files.map(s=>s.rel),r=[];for(let s of Qt(e)){let o=s.indexOf("|");r.push({from:s.slice(0,o),to:s.slice(o+1),kind:"import",weight:1})}t.importPagerank=gr(n,r)}return t.importPagerank}function bd(e){let t=We(e),n=t.bm25??={docs:Hs(e)};return n.stems??=md(n.docs)}function xd(e){let t=We(e);if(!t.fileComplexity){let n=new Map;for(let r of e.files)r.kind==="code"&&n.set(r.rel,Gs(G(I(e.root,r.rel))));t.fileComplexity=n}return t.fileComplexity}var Xo,mt=F(()=>{"use strict";k();oe();Ps();Js();cr();Yt();Xt();mr();Mn();qs();yr();Ae();Xo=new WeakMap});function Hg(e){return e.length<5?!1:/[a-z][A-Z]/.test(e)||/[A-Z]{2}/.test(e)||e.includes("_")||/\d/.test(e)}function Qo(e){let t=new Map;for(let r of e.files)for(let s of r.symbols){if(!s.exported||qg.has(s.kind)||!Hg(s.name))continue;let o=t.get(s.name);o||t.set(s.name,o=new Set),o.add(r.rel)}let n=new Map;for(let[r,s]of t)s.size===1&&n.set(r,[...s][0]);return n}function Dt(e,t){let n=Gg(t.from,t.to,t.kind),r=e.get(n);if(r){r.weight+=t.weight;return}e.set(n,{...t})}function ta(e,t,n,r,s){let o=new Map,a=new Set;for(let x of e.files)for(let v of x.refs)if(v.kind==="doc-link"){let A=zo(x.rel,v.spec,t);if(A.kind==="external")continue;A.kind==="dangling"?Dt(o,{from:x.rel,to:v.spec,kind:"doc-link",weight:1,dangling:!0,reason:A.reason}):A.target!==x.rel&&Dt(o,{from:x.rel,to:A.target,kind:"doc-link",weight:1})}else{let A=or(x.rel,x.ext,v.spec,t);if(A.kind==="external")continue;A.kind==="dangling"?Dt(o,{from:x.rel,to:v.spec,kind:"import",weight:1,dangling:!0,reason:A.reason}):A.target!==x.rel&&(Dt(o,{from:x.rel,to:A.target,kind:"import",weight:1}),a.add(`${x.rel}|${A.target}`))}let l=new Set;for(let x of qo(e,a))Dt(o,x),l.add(`${x.from}|${x.to}`);for(let x of Go(e,a))Dt(o,x),l.add(`${x.from}|${x.to}`);Ed(e,t,a);let c=En(e);if(c.size)for(let x of e.files){if(x.kind!=="code"||!x.idents?.length)continue;let v=new Map;for(let A of x.idents){let O=c.get(A);!O||O===x.rel||v.set(O,(v.get(O)??0)+1)}for(let[A,O]of v){let N=`${x.rel}|${A}`;a.has(N)||l.has(N)||Dt(o,{from:x.rel,to:A,kind:"use",weight:Math.min(O,5)})}}if(c.size)for(let x of e.files){if(x.kind!=="doc")continue;let v=e.docText.get(x.rel)??G(I(e.root,x.rel));if(!v)continue;let A=new Map;for(let O of v.split(/[^A-Za-z0-9_]+/))c.has(O)&&A.set(O,(A.get(O)??0)+1);for(let[O,N]of A){let U=c.get(O);U!==x.rel&&Dt(o,{from:x.rel,to:U,kind:"mention",weight:Math.min(N,5)})}}let d=[...o.values()].sort((x,v)=>M(x.from,v.from)||M(x.to,v.to)||M(x.kind,v.kind)),f=new Map,u=new Map,m=new Set(e.files.map(x=>x.rel));for(let x of d)x.dangling||!m.has(x.to)||(u.set(x.from,(u.get(x.from)??0)+1),f.set(x.to,(f.get(x.to)??0)+1));let p={import:7,extends:6,implements:5,call:4,use:3,"doc-link":2,mention:1,contains:0},g=new Map;for(let x of d){if(x.dangling||!m.has(x.to))continue;let v=r.get(x.from),A=r.get(x.to);if(!v||!A||v===A)continue;let O=`${v}${ea}${A}`,N=g.get(O);N?(N.weight+=x.weight,(p[x.kind]??0)>(p[N.kind]??0)&&(N.kind=x.kind)):g.set(O,{from:v,to:A,kind:x.kind,weight:x.weight})}let y=[...g.values()].sort((x,v)=>M(x.from,v.from)||M(x.to,v.to)),h=new Map,S=new Map;for(let x of y)S.set(x.from,(S.get(x.from)??0)+1),h.set(x.to,(h.get(x.to)??0)+1);let _=e.files.map(x=>({id:x.rel,kind:"file",rel:x.rel,fileKind:x.kind,lang:x.lang,module:r.get(x.rel)??"root",title:x.title,summary:x.summary,symbols:x.symbols.length,lines:x.lines,degIn:f.get(x.rel)??0,degOut:u.get(x.rel)??0})).sort((x,v)=>M(x.rel,v.rel)),E=new Map;for(let x of e.files){let v=r.get(x.rel)??"root";E.set(v,(E.get(v)??0)+x.symbols.length)}let b=n.map(x=>({id:x.slug,kind:"module",slug:x.slug,path:x.path,title:x.title,summary:x.summary,tier:x.tier,members:x.members,symbols:E.get(x.slug)??0,degIn:h.get(x.slug)??0,degOut:S.get(x.slug)??0})).sort((x,v)=>M(x.slug,v.slug));return{schemaVersion:s?.schemaVersion??5,version:s?.version??fe,commit:e.commit,fileCount:e.files.length,languages:e.languages,files:_,modules:b,fileEdges:d,moduleEdges:y}}var qg,ea,Gg,Js=F(()=>{"use strict";k();oe();Xe();Ps();Sn();Xt();mt();Ae();Y();qg=new Set(["reexport","reexport-all","default"]);ea="\0",Gg=(e,t,n)=>`${e}${ea}${t}${ea}${n}`});function*Vg(e){for(let t of e.files)yield*t.symbols}function ra(e,t){let n=Sd(e).get(t);return n?[...n.symbols].filter(r=>!na.has(r.kind)).sort((r,s)=>r.line-s.line||M(r.name,s.name)):[]}function An(e,t,n={}){let r=t.split("/").filter(Boolean);if(!r.length)return[];let s=r[r.length-1],o=r.slice(0,-1),a=(f,u)=>n.substring?f.toLowerCase().includes(u.toLowerCase()):f===u,l=[],c=n.substring?Vg(e):kd(e).get(s)??[];for(let f of c)if(!na.has(f.kind)&&a(f.name,s)){if(o.length){let u=o[o.length-1];if(!f.parent||f.parent!==u)continue}l.push({...f})}l.sort((f,u)=>+(u.name===s)-+(f.name===s)||M(f.file,u.file)||f.line-u.line);let d=l.slice(0,n.maxResults??50);if(n.includeBody){let f=new Map,u=new Set;for(let m of d){let p=m.endLine??m.line;if(u.has(m.file))continue;let g=f.get(m.file);if(!g){let y=G(I(e.root,m.file));if(!y){u.add(m.file);continue}g=y.split(` +`),f.set(m.file,g)}m.body=g.slice(m.line-1,p).join(` +`)}}return n.concise?d.map(f=>({name:f.name,kind:f.kind,file:f.file,line:f.line,...f.body!==void 0?{body:f.body}:{}})):d}function sa(e,t){let n=[];for(let d of e.files)for(let f of d.symbols)f.name===t&&!na.has(f.kind)&&n.push(f);n.sort((d,f)=>M(d.file,f.file)||d.line-f.line);let s=Cn(e).get(t),o=s?[...s.callers]:[],a=new Set,c=En(e).get(t);for(let d of e.files)if(d.rel!==c){if(d.kind==="code"&&d.idents?.includes(t))a.add(d.rel);else if(d.kind==="doc"){let f=e.docText.get(d.rel);f&&new RegExp(`\\b${t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}\\b`).test(f)&&a.add(d.rel)}}for(let d of o)a.add(d.file);return{defs:n,callSites:o,referencingFiles:[...a].sort(M)}}var na,Ks=F(()=>{"use strict";k();oe();Ae();mt();Y();na=new Set(["reexport","reexport-all","default"])});function Xs(e,t,n){let r=An(e,t);if(n&&(r=r.filter(o=>o.file===n)),r.length===1)return r[0];if(r.length===0){let o=An(e,t,{substring:!0,maxResults:5}).map(a=>`${a.file}:${a.line} ${a.parent?a.parent+"/":""}${a.name}`).join(", ");throw new Error(`no symbol matches "${t}"${n?` in ${n}`:""}${o?` \u2014 near matches: ${o}`:""}`)}let s=r.map(o=>`${o.file}:${o.line}`).join(", ");throw new Error(`"${t}" is ambiguous (${r.length} matches: ${s}) \u2014 qualify with \`file\` or a Parent/name path`)}function Rd(e){return te(e,"utf8").split(` +`)}function Md(e,t,n=qe){let r=gn(e),s=Ee(r).mode,o;try{o=Ln(I(_e(r),".codeindex-edit-"))}catch{Re(r,t),ns(r,s);return}let a=I(o,ke(r));try{Re(a,t),ns(a,s);try{Dn(a,r)}catch{Re(r,t),ns(r,s)}}finally{try{n(o,{recursive:!0,force:!0})}catch{}}}function ia(e,t,n,r){let s=Xs(e,t,r),o=s.endLine??s.line,a=I(e.root,s.file),l=Rd(a),c=n.replace(/^\n+|\n+$/g,"").split(` +`);return l.splice(s.line-1,o-s.line+1,...c),Md(a,l.join(` +`)),{file:s.file,startLine:s.line,endLine:s.line+c.length-1,lines:c.length}}function Cd(e,t,n,r,s,o){let a=I(e.root,t.file),l=Rd(a),c=Jg.has(t.kind)?1:0,d=n.replace(/^\n+|\n+$/g,"").split(` +`),f=[];return s&&c&&l[r-1]?.trim()!==""&&f.push(""),f.push(...d),o&&c&&l[r]?.trim()!==""&&f.push(""),l.splice(r,0,...f),Md(a,l.join(` +`)),{file:t.file,startLine:r+1,endLine:r+f.length,lines:f.length}}function oa(e,t,n,r){let s=Xs(e,t,r),o=s.endLine??s.line;return Cd(e,s,n,o,!0,!0)}function aa(e,t,n,r){let s=Xs(e,t,r);return Cd(e,s,n,s.line-1,!0,!0)}var Jg,la=F(()=>{"use strict";k();xe();oe();Ks();Jg=new Set(["function","method","class","interface","struct","trait","enum","def"])});function Td(e){let t=e.replace(/^mem:/,"").replace(/\.md$/,"");if(!t)throw new Error("memory name is empty");let n=t.split("/");for(let r of n){if(!r||r==="."||r===".."||r.includes("\\"))throw new Error(`invalid memory name: "${e}"`);if(!/^[\w][\w.-]*$/.test(r))throw new Error(`invalid memory name segment: "${r}"`)}return t}function ca(e,t){return I(e,...Ad,`${Td(t)}.md`)}function br(e,t,n){let r=ca(e,t);return gt(_e(r),{recursive:!0}),Re(r,n.endsWith(` `)?n:n+` -`),pd(t)}function Qo(e,t){try{return te(Yo(e,t),"utf8")}catch{return}}function ea(e,t){let n=Yo(e,t);try{Ve(n)}catch{return!1}return zt(n),!0}function ta(e){let t=I(e,...md),n=[],r=(s,o)=>{let a;try{a=pn(s,{withFileTypes:!0})}catch{return}for(let l of a)l.isDirectory()?r(I(s,l.name),o?`${o}/${l.name}`:l.name):l.name.endsWith(".md")&&n.push(o?`${o}/${l.name.slice(0,-3)}`:l.name.slice(0,-3))};return r(t,""),n.sort()}var md,Ws=O(()=>{"use strict";S();we();ie();md=[".codeindex","memories"]});function bt(e,t,n){let r=G(e);if(r)try{let s=JSON.parse(r);if(s&&typeof s=="object")return s;t&&n&&n.push(`malformed ${t}: not a JSON object`);return}catch(s){if(t&&n){let o=String(s instanceof Error?s.message:s).split(` -`)[0];n.push(`malformed ${t}: ${o}`)}return}}function $t(e,t){let n=new RegExp(`^\\[${He(t)}\\]\\s*$([\\s\\S]*?)(?=^\\[|$(?![\\s\\S]))`,"m"),r=e.match(n);return r?r[1]:null}function hr(e,t){let n=e.match(new RegExp(`${He(t)}\\s*=\\s*\\[([^\\]]*)\\]`));return n?n[1].split(/\r?\n/).map(r=>r.replace(/#.*$/,"")).join(` -`).split(",").map(r=>r.trim().replace(/^["']|["']$/g,"")).filter(Boolean):[]}function Cn(e,t){return e?.match(new RegExp(`^\\s*${He(t)}\\s*=\\s*["']([^"']+)["']`,"m"))?.[1]}function na(e){let t="";for(let n=0;nNg(e,t,n,r),o=()=>Og(e,t),a=()=>Fg(e,t),l=()=>Pg(e,t),c=()=>$g(e,t),d=()=>Dg(e,t,r),u=()=>Lg(e,t,r),p=n==="go"?[a,s,o,l,c,d,u]:n==="uv"?[c,s,o,a,l,d,u]:n==="composer"?[d,s,c,o,a,l,u]:n==="gradle"?[s,l,o,a,c,d,u,()=>jg(e,t)]:[s,o,a,l,c,d,u];for(let m of p){let g=m();if(g)return g}}function Wg(e){return e.replace(/[\s\S]*?<\/parent>/g,"").replace(/[\s\S]*?<\/dependencies>/g,"").match(/\s*([^<]+?)\s*<\/artifactId>/)?.[1]}function yr(e,t,n,r,s){let o=t.replace(/^\.\//,"").replace(/\/+$/,"");if(!o||o==="."||n.has(o)||o.split("/").includes(".."))return;let a=Ug(e,o,r,s);a&&n.set(o,a)}function Bg(e,t){try{return Ve(I(e,t)).isDirectory()}catch{return!1}}function gd(e,t){let n;try{n=pn(t?I(e,t):e,{withFileTypes:!0})}catch{return[]}return n.filter(r=>r.isDirectory()&&!r.name.startsWith(".")&&!Tg.has(r.name)).map(r=>t?`${t}/${r.name}`:r.name).sort(R)}function _d(e,t,n,r){if(!(n>Ig))for(let s of gd(e,t))r.push(s),_d(e,s,n+1,r)}function Hg(e,t){let n=t.split("/").filter(s=>s&&s!==".");if(n.includes(".."))return[];let r=[""];for(let s of n){let o=new Set;if(s==="**")for(let a of r){a&&o.add(a);let l=[];_d(e,a,0,l);for(let c of l)o.add(c)}else if(s.includes("*")){let a=new RegExp(`^${s.split("*").map(He).join("[^/]*")}$`);for(let l of r)for(let c of gd(e,l))a.test(c.split("/").pop())&&o.add(c)}else for(let a of r){let l=a?`${a}/${s}`:s;Bg(e,l)&&o.add(l)}if(r=[...o],!r.length)return[]}return r.filter(Boolean)}function Bs(e,t,n,r,s){let o=t.replace(/^\.\//,"").replace(/\/+$/,"");if(o){if(!o.includes("*")){yr(e,o,n,r,s);return}for(let a of Hg(e,o))yr(e,a,n,r,s)}}function zg(e,t){let n=[],r=[],s=(d,u)=>{let f=d.trim();f&&(f.startsWith("!")?r.push(f.slice(1)):n.push({pattern:f,kind:u}))},a=bt(I(e,"package.json"),"package.json",t)?.workspaces;if(Array.isArray(a))for(let d of a)typeof d=="string"&&s(d,"npm");else if(a&&typeof a=="object"&&Array.isArray(a.packages))for(let d of a.packages)typeof d=="string"&&s(d,"npm");let l=G(I(e,"pnpm-workspace.yaml")),c=!1;for(let d of l.split(/\r?\n/)){if(/^\S/.test(d)){c=/^packages\s*:/.test(d);continue}if(!c)continue;let u=d.match(/^\s*-\s*['"]?([^'"#]+?)['"]?\s*(?:#.*)?$/);u&&s(u[1].trim(),"pnpm")}return{positives:n,negations:r}}function Gg(e,t){let n=bt(I(e,"lerna.json"),"lerna.json",t);if(n&&Array.isArray(n.packages))return n.packages.filter(s=>typeof s=="string").map(s=>({pattern:s,kind:"lerna"}));let r=bt(I(e,"nx.json"),"nx.json",t);if(r){let s=r.workspaceLayout??{},o=typeof s.appsDir=="string"?s.appsDir:"apps",a=typeof s.libsDir=="string"?s.libsDir:"libs";return[...new Set([o,a])].map(l=>({pattern:`${l}/*`,kind:"nx"}))}return[]}function qg(e,t,n){let r=G(I(e,"Cargo.toml"));if(!r)return;let s=$t(r,"workspace");if(!s)return;let o=hr(s,"members");if(!o.length)return;let a=hr(s,"exclude").map(na),l=new Map;for(let c of o)Bs(e,c,l,"cargo",n);for(let[c,d]of l)a.some(u=>u.test(c))||t.has(c)||t.set(c,d)}function Vg(e,t,n){let r=G(I(e,"go.work"));if(!r)return;let s=[];for(let o of r.matchAll(/^use\s*\(([\s\S]*?)\)/gm))for(let a of o[1].split(/\r?\n/)){let l=a.replace(/\/\/.*$/,"").trim();l&&s.push(l)}for(let o of r.matchAll(/^use\s+([^\s(]+)/gm))s.push(o[1]);for(let o of s)o==="."||o==="./"||yr(e,o,t,"go",n)}function Jg(e,t,n){let r=G(I(e,"pom.xml"));if(!r)return;let s=r.match(/([\s\S]*?)<\/modules>/)?.[1];if(s)for(let o of s.matchAll(/\s*([^<]+?)\s*<\/module>/g))yr(e,o[1],t,"maven",n)}function Kg(e,t,n){let r=G(I(e,"pyproject.toml"));if(!r)return;let s=$t(r,"tool.uv.workspace");if(!s)return;let o=hr(s,"members");if(!o.length)return;let a=hr(s,"exclude").map(na),l=new Map;for(let c of o)Bs(e,c,l,"uv",n);for(let[c,d]of l)a.some(u=>u.test(c))||t.has(c)||t.set(c,d)}function Xg(e,t,n){let s=bt(I(e,"composer.json"),"composer.json",n)?.repositories;if(Array.isArray(s))for(let o of s){if(!o||typeof o!="object")continue;let{type:a,url:l}=o;a==="path"&&typeof l=="string"&&l&&Bs(e,l,t,"composer",n)}}function Zg(e,t,n){for(let r of["settings.gradle","settings.gradle.kts"]){let s=G(I(e,r));if(s){for(let o of s.split(/\r?\n/))if(/^\s*include[\s(]/.test(o))for(let a of o.matchAll(/["']([^"']+)["']/g)){let l=a[1].replace(/^:/,"").replace(/:/g,"/");l&&yr(e,l,t,"gradle",n)}}}}function Yg(e,t,n,r){let s=bt(I(e,t.dir,"package.json"),`${t.dir}/package.json`,r);if(!s)return[];let o=new Set;for(let a of["dependencies","devDependencies","peerDependencies"]){let l=s[a];if(!(!l||typeof l!="object"))for(let c of Object.keys(l))c!==t.name&&n.has(c)&&o.add(c)}return[...o]}function hd(e,t){let n=`${e}/${t}`.split("/"),r=[];for(let s of n)!s||s==="."||(s===".."?r.pop():r.push(s));return r.join("/")}function Qg(e,t,n,r){let s=G(I(e,t.dir,"Cargo.toml"));if(!s)return[];let o=new Set;for(let a of["dependencies","dev-dependencies","build-dependencies"]){let l=$t(s,a);if(l)for(let c of l.split(/\r?\n/)){let d=c.match(/^\s*([A-Za-z0-9_-]+)\s*=\s*(.+)$/);if(!d)continue;let u=d[1];if(u!==t.name&&n.has(u)){o.add(u);continue}let f=d[2].match(/path\s*=\s*["']([^"']+)["']/);if(f){let p=r.get(hd(t.dir,f[1]));p&&p!==t.name&&o.add(p)}}}return[...o]}function e_(e,t,n,r){let s=G(I(e,t.dir,"go.mod"));if(!s)return[];let o=new Set;for(let a of s.matchAll(/^\s*(?:require\s+)?([^\s/(][^\s]*)\s+v[^\s]+/gm)){let l=a[1];l!==t.name&&n.has(l)&&o.add(l)}for(let a of s.matchAll(/^\s*(?:replace\s+)?(\S+)(?:\s+\S+)?\s*=>\s*(\.\.?\/\S+)/gm)){let l=r.get(hd(t.dir,a[2]));l&&l!==t.name&&o.add(l)}return[...o]}function t_(e,t,n){let r=G(I(e,t.dir,"pom.xml"));if(!r)return[];let s=new Set;for(let o of r.replace(/[\s\S]*?<\/parent>/g,"").matchAll(/([\s\S]*?)<\/dependency>/g)){let a=o[1].match(/\s*([^<]+?)\s*<\/artifactId>/)?.[1];a&&a!==t.name&&n.has(a)&&s.add(a)}return[...s]}function n_(e,t,n){let r=G(I(e,t.dir,"pyproject.toml"));if(!r)return[];let s=new Set,o=$t(r,"project");if(o)for(let l of hr(o,"dependencies")){let c=l.match(/^[A-Za-z0-9_.-]+/)?.[0];c&&c!==t.name&&n.has(c)&&s.add(c)}let a=$t(r,"tool.uv.sources");if(a)for(let l of a.split(/\r?\n/)){let c=l.match(/^\s*([A-Za-z0-9_.-]+)\s*=\s*\{[^}]*workspace\s*=\s*true/);c&&c[1]!==t.name&&n.has(c[1])&&s.add(c[1])}return[...s]}function r_(e,t,n,r){let s=bt(I(e,t.dir,"composer.json"),`${t.dir}/composer.json`,r);if(!s)return[];let o=new Set;for(let a of["require","require-dev"]){let l=s[a];if(!(!l||typeof l!="object"))for(let c of Object.keys(l))c!==t.name&&n.has(c)&&o.add(c)}return[...o]}function s_(e,t,n,r){for(let s of["build.gradle","build.gradle.kts"]){let o=G(I(e,t.dir,s));if(!o)continue;let a=new Set;for(let l of o.matchAll(/project\s*\(\s*["']:?([^"']+)["']\s*\)/g)){let c=l[1].replace(/:/g,"/"),d=r.get(c)??(n.has(c)?c:void 0);d&&d!==t.name&&a.add(d)}return[...a]}return[]}function i_(e,t,n,r,s){switch(t.kind){case"cargo":return Qg(e,t,n,r);case"go":return e_(e,t,n,r);case"maven":return t_(e,t,n);case"uv":return n_(e,t,n);case"composer":return r_(e,t,n,s);case"gradle":return s_(e,t,n,r);default:return Yg(e,t,n,s)}}function o_(e){let t=new Map(e.map(o=>[o.name,[...o.dependsOn??[]].sort(R)])),n=new Map,r=[],s=o=>{n.set(o,"visiting"),r.push(o);for(let a of t.get(o)??[])if(t.has(a)){if(n.get(a)==="visiting")return[...r.slice(r.indexOf(a)),a];if(!n.has(a)){let l=s(a);if(l)return l}}return r.pop(),n.set(o,"done"),null};for(let o of[...t.keys()].sort(R))if(!n.has(o)){let a=s(o);if(a)return a}}function a_(e){let t=new Map(e.map(r=>[r.name,new Set(r.dependsOn??[])])),n=[];for(;t.size>0;){let r=[...t.entries()].filter(([,s])=>[...s].every(o=>!t.has(o))).map(([s])=>s).sort(R);if(!r.length){n.push(...[...t.keys()].sort(R));break}for(let s of r)n.push(s),t.delete(s)}return n}function tn(e){let t=[],n=new Map,{positives:r,negations:s}=zg(e,t),o=r.length?r:Gg(e,t);if(o.length){let u=new Map;for(let{pattern:p,kind:m}of o)Bs(e,p,u,m,t);let f=s.map(na);for(let[p,m]of u)f.some(g=>g.test(p))||n.set(p,m)}qg(e,n,t),Vg(e,n,t),Jg(e,n,t),Kg(e,n,t),Xg(e,n,t),Zg(e,n,t);let a=[...n.values()].sort((u,f)=>R(u.dir,f.dir)),l=new Set(a.map(u=>u.name)),c=new Map(a.map(u=>[u.dir,u.name]));for(let u of a){let f=i_(e,u,l,c,t);f.length&&(u.dependsOn=f.sort(R))}let d=[...a].sort((u,f)=>f.dir.length-u.dir.length);return{packages:a,cycle:o_(a),topoOrder:a_(a),warnings:[...new Set(t)].sort(R),packageOf:u=>d.find(f=>u===f.dir||u.startsWith(f.dir+"/"))}}var Tg,Ig,br=O(()=>{"use strict";S();we();ie();Te();K();Me();Tg=new Set(["node_modules",".git","dist","build","target","coverage"]),Ig=4});function l_(e,t){return e.modules.find(n=>n.slug===t)?.community}function p_(e,t){let n=e.length,r=new Map(e.map((l,c)=>[l,c])),s=Array.from({length:n},()=>new Map);for(let l of t){if(l.dangling)continue;let c=r.get(l.from),d=r.get(l.to);c===void 0||d===void 0||c===d||(s[c].set(d,(s[c].get(d)??0)+l.weight),s[d].set(c,(s[d].get(c)??0)+l.weight))}let o=s.map(l=>{let c=0;for(let d of l.values())c+=d;return c}),a=o.reduce((l,c)=>l+c,0);return{n,adj:s,k:o,twoM:a}}function ra(e){let t=new Map,n=new Array(e.length);for(let r=0;ru);if(s===0)return ra(o);let a=r.slice(),l=!0,c=0;for(;l&&ch-_)){if(g===u)continue;let h=f.get(g)-yd*r[d]*a[g]/s;h>m+u_&&(m=h,p=g)}a[p]+=r[d],p!==u&&(o[d]=p,l=!0)}}return ra(o)}function __(e,t,n){let r=Array.from({length:n},()=>new Map);for(let a=0;a{let l=0;for(let c of a.values())l+=c;return l}),o=s.reduce((a,l)=>a+l,0);return{n,adj:r,k:s,twoM:o}}function bd(e){if(e.n===0)return[];let t=e,n=Array.from({length:e.n},(r,s)=>s);for(let r=0;rn&&n.length>0)}function h_(e,t){let n=t.length,r=new Map;t.forEach((c,d)=>r.set(c,d));let s=Array.from({length:n},()=>new Map);for(let c=0;c{let d=0;for(let u of c.values())d+=u;return d}),a=o.reduce((c,d)=>c+d,0),l=bd({n,adj:s,k:o,twoM:a});return wd(l).map(c=>c.map(d=>t[d]))}function y_(e,t,n){let r=[];for(let s of e){if(s.length>f_*n&&s.length>=m_){let o=h_(t,s);if(o.length>1){r.push(...o);continue}}r.push(s)}return r}function b_(e,t){if(e.length!==t.length)return t.length-e.length;for(let n=0;n({id:Number(f),set:new Set(p)})),o=[];e.forEach((f,p)=>{for(let m of s){let g=0;for(let h of f)m.set.has(h)&&g++;g>0&&o.push({ni:p,prevId:m.id,inter:g})}}),o.sort((f,p)=>p.inter-f.inter||f.ni-p.ni||f.prevId-p.prevId);let a=new Map,l=new Set;for(let f of o)a.has(f.ni)||l.has(f.prevId)||(a.set(f.ni,f.prevId),l.add(f.prevId));let c=new Set;for(let f=0;f=0&&pu.slug).sort(R),o=p_(s,t),a=bd(o),c=y_(wd(a),o,s.length).map(u=>u.map(f=>s[f]).sort(R));c.sort(b_);let d=w_(c,n);return c.forEach((u,f)=>{for(let p of u)r.set(p,d[f])}),r}var yd,c_,d_,u_,f_,m_,ia=O(()=>{"use strict";S();K();yd=1,c_=20,d_=10,u_=1e-12,f_=.25,m_=10});function Hs(e){let t=new Map,n=new Map;for(let a of e.modules)a.community!==void 0&&t.set(a.slug,a.community),n.set(a.slug,a.tier);let r=new Map,s=(a,l)=>ar.get(s(a.comms[0],a.comms[1]))<=S_).map(a=>({from:a.edge.from,to:a.edge.to,kind:a.edge.kind,weight:a.edge.weight,communities:a.comms,pairEdges:r.get(s(a.comms[0],a.comms[1]))})).sort((a,l)=>a.pairEdges-l.pairEdges||R(a.from,l.from)||R(a.to,l.to)).slice(0,x_)}function E_(e,t,n){return(e.surprises??Hs(e)).some(s=>s.from===t&&s.to===n)}var x_,S_,k_,oa=O(()=>{"use strict";S();K();x_=24,S_=2,k_=new Set(["import","call","use"])});function v_(e){let t={};for(let n of Object.keys(e).sort(R))t[n]=e[n];return t}function An(e){let t={...e,languages:v_(e.languages)};return JSON.stringify(t,null,2)+` -`}var zs=O(()=>{"use strict";S();K()});function dh(e,t){return t!=="string"?!0:e.length>=lh||ch.test(e)}function gh(e){if(!e)return!1;for(let t=0;t")&&!"=!<>+-*/%&|^".includes(e[t-1]??""))return ph.test(e.slice(t+1));return!1}function _h(e,t){let n;for(let r of e){if(!oh.has(r.kind)||gh(r.signature))continue;let s=r.endLine??r.line;s-r.line>ah||ts||(!n||r.line>n.line)&&(n=r)}return n}function nn(e,t={}){let n=t.minFiles??Ad.minFiles,r=t.minCount??Ad.minCount,s=new Map;for(let a of e.files)if(a.literals?.length&&!(!t.includeTests&&Ot(a.rel)))for(let l of a.literals){if(t.kinds&&!t.kinds.has(l.kind)||!dh(l.value,l.kind))continue;let c=`${l.kind}\0${l.value}`,d=s.get(c);d||s.set(c,d={value:l.value,kind:l.kind,sites:[]});let u=_h(a.symbols,l.line);d.sites.push(u?{file:a.rel,line:l.line,holder:u.name,holderExported:u.exported}:{file:a.rel,line:l.line})}let o=[];for(let a of s.values()){let l=new Set(a.sites.map(m=>m.file));if(l.sizem.holder),d=a.sites.filter(m=>!m.holder),u=new Set(c.map(m=>m.holder)),p=new Set(c.map(m=>`${m.file}\0${m.holder}`)).size>=2?"competing":c.length>0?"bypassed":"uncentralized";if(a.kind==="number"){if(u.size!==1||d.length===0)continue;p="bypassed"}p==="bypassed"&&d.length===0||o.push({value:a.value,kind:a.kind,tier:p,holders:c.sort(Td),literals:d.sort(Td),files:l.size,count:a.sites.length})}return o.sort((a,l)=>Id(a.tier)-Id(l.tier)||l.files-a.files||l.count-a.count||R(a.value,l.value)),{duplications:o,families:hh(o)}}function Td(e,t){return R(e.file,t.file)||e.line-t.line}function Id(e){return e==="competing"?0:e==="bypassed"?1:2}function hh(e){let t=new Map;for(let r of e){if(r.kind!=="string"||!uh.test(r.value))continue;let s=yh(r.value);if(!s)continue;let o=t.get(s);o?o.push(r):t.set(s,[r])}let n=[];for(let[r,s]of t){if(s.lengths.files-r.files||s.count-r.count||R(r.prefix,s.prefix)),n}function yh(e){let t=e.startsWith("/")?e.slice(1):e,n=t.search(/[/:]/);if(n<=0)return;let r=(e.startsWith("/")?"/":"")+t.slice(0,n);return r.length>=mh?r:void 0}var Nd,Ad,oh,ah,lh,ch,uh,fh,mh,ph,wr=O(()=>{"use strict";S();kn();K();Nd=24,Ad={minFiles:2,minCount:3},oh=new Set(["const","constant","variable","enum","enumerator","property","field","static"]),ah=12,lh=6,ch=/[/:._-]/;uh=/^[/@a-z0-9][\w./:@-]*$/i,fh=2,mh=4,ph=/^\s*(?:async\b|function\b|\(|[A-Za-z_$][\w$]*\s*=>)/});function la(e,t={}){return Dt(Pe(e,t),t)}function Dt(e,t={}){let n=Uo(e),{modules:r,moduleOf:s}=Oo(e),o=zo(e,n,r,s,t.meta),a=sa(o.modules,o.moduleEdges,t.previousCommunities);for(let f of o.modules){let p=a.get(f.slug);p!==void 0&&(f.community=p)}Lo(o);let l=ur(o);for(let f of o.files)l.testFiles.has(f.rel)&&(f.testFile=!0);for(let f of o.modules){let p=l.testedByModule.get(f.slug);p?.length&&(f.testedBy=p)}let c=Hs(o);c.length&&(o.surprises=c);let{duplications:d}=nn(e);d.length&&(o.literalDuplications=d.slice(0,Nd));let u=Do(e,Ds(e),t.meta?.schemaVersion);return{scan:e,graph:o,symbols:u}}var Vs=O(()=>{"use strict";S();It();dt();Cs();Ls();ia();Ps();kn();oa();wr();or()});function wh(e){return e.sort((t,n)=>R(t.file,n.file)||t.line-n.line)}function xh(e,t,n){let r=["--no-heading","--line-number","--null","--color=never","--no-messages","--hidden","--no-require-git","--no-ignore-global","--no-ignore-exclude","--no-ignore-parent","--no-ignore-dot","--max-filesize","1M"];for(let c of Pn)r.push("--glob",`!**/${c}/**`);for(let c of Ai)r.push("--iglob",`!**/${c}`);for(let c of Ti)r.push("--iglob",`!**/*${c}`);r.push("--glob","!*.min.js","--glob","!*.min.css"),n.ignoreCase&&r.push("--ignore-case");let s=n.globs??[],o=c=>c.startsWith("/")?c:`/${c}`;for(let c of s.filter(d=>!d.startsWith("!")))r.push("--glob",o(c));for(let c of s.filter(d=>d.startsWith("!")))r.push("--glob",`!${o(c.slice(1))}`);r.push("--regexp",t,"./");let a=me("rg",r,{cwd:e});if(a.missing||!a.ok&&a.status!==1)return;let l=[];for(let c of a.stdout.split(` -`)){if(!c)continue;let d=c.indexOf("\0");if(d===-1)continue;let u=c.slice(0,d).replace(/^\.\//,""),f=c.slice(d+1),p=f.indexOf(":");p!==-1&&l.push({file:u,line:Number(f.slice(0,p)),text:f.slice(p+1)})}return l}function Sh(e,t,n){let r=Ul(n.globs?.map(o=>o.replace(/^(!?)\//,"$1"))),s=[];for(let o of Le(e).files){if(r&&!r(o.rel))continue;let a=G(o.abs);if(!a)continue;let l=a.split(` -`);for(let c=0;c{"use strict";S();Te();Un();Me();K();bh=200});function St(e){let t=v.env.CODEINDEX_EMBED_DIR,n=[];t&&n.push(t),e&&n.push(I(e,".codeindex",Od)),n.push(I(v.cwd(),".codeindex",Od));for(let r of n)if(z(I(r,"model.json")))return r}function vh(e){return St(e)!==void 0}function ca(e,t){let{modelId:n,dim:r,vocab:s,weights:o,unk:a}=e??{};if(typeof n!="string"||!n)throw new Error(`embed model: missing modelId in ${t}`);if(!Number.isInteger(r)||r<=0)throw new Error(`embed model: bad dim ${r} in ${t}`);if(!Array.isArray(s)||!Array.isArray(o)||s.length!==o.length)throw new Error(`embed model: vocab/weights length mismatch in ${t}`);let l=s.length,c=new Float64Array(l*r),d=new Map;for(let p=0;p{"use strict";S();ss();we();ie();nt=1,Od="models",kh="https://github.com/maxgfr/codeindex/releases/download/embed-model-v1/model.json",Eh="163ad053eab4e9a80d421ed4164f32292c83290f02fbbe6fe4b9b1cd6ea18d34"});function Pd(e){let t=mt(e).replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1 $2"),n=[];for(let r of t.toLowerCase().split(/[^a-z0-9]+/))r&&n.push(r);return n}function $d(e,t){if(!e)return[];let n=[],r=0,s=e.length;for(;rr;){let l=r===0?e.slice(r,o):"##"+e.slice(r,o),c=t.vocab.get(l);if(c!==void 0){a=c;break}o--}if(a===-1)return t.unkId>=0?[t.unkId]:[];n.push(a),r=o}return n}function Dd(e,t){let n=[];for(let r of Pd(e))for(let s of $d(r,t))n.push(s);return n}function Ld(e){let t=Math.floor(e),n=e-t;return n<.5?t:n>.5?t+1:t%2===0?t:t+1}function kr(e){let t=e.length,n=new Int8Array(t),r=0;for(let o=0;oSr?a=Sr:a<-Sr&&(a=-Sr),n[o]=a}return n}function Er(e,t){let{dim:n,weights:r}=e,s=Dd(t,e);if(s.length===0)return new Int8Array(n);let o=new Float64Array(n);for(let l of s){let c=l*n;for(let d=0;d{"use strict";S();Me();Sr=127});function Rh(e,t,n,r){return[t,n??"",r??"",e.replace(/\//g," ")].join(` -`)}function Mh(e,t,n,r){return[t??"",n??"",...r,e.replace(/\//g," ")].join(` -`)}function Ks(e){let t=[];for(let n of e.files){let r=new Set,s=!1;for(let o of n.symbols)r.has(o.name)||(r.add(o.name),s=!0,t.push({file:n.rel,symbol:o.name,line:o.line,text:Rh(n.rel,o.name,o.signature,n.summary)}));if(!s){let o=Mh(n.rel,n.title,n.summary,n.headings);o.replace(/\s+/g,"")&&t.push({file:n.rel,text:o})}}return t}function sn(e,t){let n=Ks(e).map(r=>{let s={file:r.file,vec:Er(t,r.text)};return r.symbol!==void 0&&(s.symbol=r.symbol),r.line!==void 0&&(s.line=r.line),s});return{embedVersion:nt,modelId:t.modelId,dim:t.dim,records:n}}function Xs(e){let t=JSON.stringify({embedVersion:e.embedVersion,modelId:e.modelId,dim:e.dim,count:e.records.length,records:e.records.map(a=>({file:a.file,symbol:a.symbol??"",line:a.line??0}))}),n=T.from(t,"utf8"),r=T.alloc(e.records.length*e.dim),s=0;for(let a of e.records)for(let l=0;l{let d=new Int8Array(o);for(let f=0;f{"use strict";S();vr();rn();jd="CIE1"});function on(e,t,n,r={}){let s=r.limit??Ah,o=Ft(e,t,{limit:Math.max(s,50),fuzzy:r.fuzzy}),a=r.queryVec??(r.model?Er(r.model,t):void 0);if(!a||!n||n.records.length===0)return o.slice(0,s);let l=new Map;for(let m of n.records){let g=ua(a,m.vec),h=l.get(m.file);(!h||g>h.score)&&l.set(m.file,{score:g,symbol:m.symbol})}let c=[...l.entries()].filter(([,m])=>m.score>0).sort((m,g)=>g[1].score-m[1].score||R(m[0],g[0])).map(([m])=>m),d=o.map(m=>m.file),u=vi([d,c],m=>m,r.rrfK??Th),f=new Map(o.map(m=>[m.file,m]));return[...u.entries()].sort((m,g)=>g[1]-m[1]||R(m[0],g[0])).map(([m,g])=>{let h=f.get(m),_={file:m,score:Number(g.toFixed(4)),matchedTerms:h?.matchedTerms??[],topSymbols:h?.topSymbols??[]},y=l.get(m);return y?.symbol&&(_.semanticSymbol=y.symbol),h?.fuzzyTerms&&(_.fuzzyTerms=h.fuzzyTerms),_}).slice(0,s)}var Ah,Th,Zs=O(()=>{"use strict";S();Me();K();vn();vr();Ah=20,Th=60});function jt(e={}){let t=e.url??v.env.CODEINDEX_EMBED_ENDPOINT;return t&&t.trim()?t.trim():void 0}function Ud(e){return e.replace(/\/+$/,"")}function Wd(e){let t=Ud(e);return t.endsWith("/embed")?t:t+"/embed"}function Bd(e){return Ud(e).replace(/\/embed$/,"")+"/healthz"}function Hd(e){if(typeof e.timeoutMs=="number")return e.timeoutMs;let t=Number(v.env.CODEINDEX_EMBED_TIMEOUT_MS);return Number.isFinite(t)&&t>0?t:3e4}async function fa(e,t={}){let n=jt(t);if(!n)throw new Error("no embedding endpoint configured (set CODEINDEX_EMBED_ENDPOINT or pass opts.url)");let r=Wd(n),s=new AbortController,o=setTimeout(()=>s.abort(),Hd(t));try{let a=await fetch(r,{method:"POST",headers:{"content-type":"application/json",...t.headers??{}},body:JSON.stringify({texts:e}),signal:s.signal});if(!a.ok)throw new Error(`embedding endpoint ${r} returned HTTP ${a.status}`);let c=(await a.json()).vectors;if(!Array.isArray(c)||!c.every(d=>Array.isArray(d)&&d.every(u=>typeof u=="number")))throw new Error(`embedding endpoint ${r} returned a malformed { vectors } payload`);return c}finally{clearTimeout(o)}}async function Rr(e,t={}){let n=new AbortController,r=setTimeout(()=>n.abort(),Hd(t));try{return(await fetch(Bd(e),{signal:n.signal,headers:t.headers})).ok}catch{return!1}finally{clearTimeout(r)}}async function Mr(e,t={}){let[n]=await fa([e],t);if(!n)throw new Error("embedding endpoint returned no vector for the query");return kr(n)}async function Cr(e,t={}){let n=Ks(e),r=t.batchSize&&t.batchSize>0?t.batchSize:64,s=[],o=0;for(let a=0;ad.text),t);if(c.length!==l.length)throw new Error(`embedding endpoint returned ${c.length} vectors for ${l.length} texts`);for(let d=0;do&&(o=f.length);let p={file:u.file,vec:f};u.symbol!==void 0&&(p.symbol=u.symbol),u.line!==void 0&&(p.line=u.line),s.push(p)}}return{embedVersion:nt,modelId:"endpoint",dim:o,records:s}}var Ys=O(()=>{"use strict";S();vr();rn();In()});function an(e,t,n={}){let r=(n.budgetTokens??1024)*zd,s=n.maxSymbolsPerFile??8,o=[...t.files].filter(u=>u.fileKind==="code").sort((u,f)=>(f.pagerank??0)-(u.pagerank??0)||f.symbols-u.symbols||R(u.rel,f.rel)),a=new Map(e.files.map(u=>[u.rel,u])),c=`# repo map \u2014 ${t.fileCount} files -`,d=0;for(let u of o){let f=a.get(u.rel);if(!f)continue;let p=[...f.symbols].filter(g=>g.kind!=="reexport"&&g.kind!=="reexport-all").sort((g,h)=>Number(h.exported)-Number(g.exported)||g.line-h.line).slice(0,s),m=` -${u.rel}: -`;for(let g of p){let h=(g.signature??`${g.kind} ${g.name}`).replace(/\s+/g," ").trim().slice(0,120);m+=` ${g.line}: ${h} -`}if(c.length+m.length>r)break;c+=m,d++}return`${c} -(${d} of ${o.length} code files shown, ~${Math.ceil(c.length/zd)} tokens) -`}var zd,Ar=O(()=>{"use strict";S();K();zd=4});function Tr(e,t={}){let n=t.maxCommitFiles??30,r=t.minTogether??3,s=t.maxPairs??100,o=t.since?[`${t.since}..HEAD`]:[],a=me("git",["-C",e,"-c","core.quotePath=false","log",...o,"--pretty=format:%x1e","--name-only"]);if(!a.ok)return{ok:!1,couplings:[]};let l=new Map,c=new Map;for(let u of a.stdout.split("")){let f=u.split(` -`).map(m=>m.trim()).filter(Boolean);if(!f.length||f.length>n)continue;let p=[...new Set(f)].sort(R);for(let m of p)l.set(m,(l.get(m)??0)+1);for(let m=0;mf.strength-u.strength||f.together-u.together||R(u.a,f.a)||R(u.b,f.b)),{ok:!0,couplings:d.slice(0,s)}}function ln(e,t,n=20){let r=e.files.filter(s=>s.kind==="code").map(s=>{let o=t.get(s.rel)??0;return{rel:s.rel,lines:s.lines,commits:o,score:Number((o*Math.log2(s.lines+1)).toFixed(2))}});return r.sort((s,o)=>o.score-s.score||o.lines-s.lines||R(s.rel,o.rel)),r.slice(0,n)}var Gd,Ir=O(()=>{"use strict";S();Me();K();Gd="\0"});function Nh(e){for(let t of Ih){let n=I(e,t);if(!z(n))continue;let r;try{r=te(n,"utf8")}catch{continue}for(let s of r.split(/\n\s*\n/)){let o=s.trim();if(!o||o.startsWith("#")||o.startsWith("<")||/^(\[!\[|!\[|\[)/.test(o)&&!/[.:]\s/.test(o))continue;let a=o.replace(/\[([^\]]*)\]\([^)]*\)/g,"$1").replace(/[*_`]/g,"").replace(/\s+/g," ").trim();if(a.length>20)return a.slice(0,400)}break}}function ma(e,t,n={}){let r=[],s=Ae(e.root).replace(/\/+$/,"").split("/").pop()||"repository";r.push(`# ${s}`,"");let o=Nh(e.root);o&&r.push(o,"");let a=Object.entries(t.languages).sort((p,m)=>m[1]-p[1]||R(p[0],m[0])).slice(0,6).map(([p,m])=>`${p} ${m}`).join(", ");r.push(`**${t.fileCount} indexed files** \xB7 ${a}`,"");let l=tn(e.root);if(l.packages.length>1){r.push(`## Layout \u2014 monorepo, ${l.packages.length} packages`,"");for(let p of l.packages.slice(0,20))r.push(`- \`${p.dir}\` \u2014 ${p.name}`);l.packages.length>20&&r.push(`- \u2026and ${l.packages.length-20} more`),l.cycle?.length&&r.push("",`\u26A0 dependency cycle: ${l.cycle.join(" \u2192 ")}`),r.push("")}r.push("## Key files","",an(e,t,{budgetTokens:n.budgetTokens??900}).trim(),"");let{churn:c,ok:d}=Je(e.root);if(d&&c.size){let p=ln(e,c,8);if(p.length){r.push("## Where work concentrates","","Files ranked by commits \xD7 size \u2014 where changes and defects cluster.","");for(let m of p)r.push(`- \`${m.rel}\` \u2014 ${m.commits} commits, ${m.lines} lines`);r.push("")}}r.push("## Next","","- `search ` \u2014 BM25 over names, paths, doc comments and prose; `explain_search` says whether it really matched","- `find_symbol ` / `symbols_overview ` \u2014 read structure without reading files","- `find_references ` \u2014 three labelled tiers; add `lsp: true` when a language server is configured","");let u=r.join(` -`);if(n.remember===!1)return{brief:u};let f=n.memoryName??"onboarding";return _r(e.root,f,u),{brief:u,memory:f}}var Ih,pa=O(()=>{"use strict";S();we();ie();Ar();br();Ir();Gt();Ws();K();Ih=["README.md","README.markdown","README.rst","README.txt","README"]});function Qs(e){let t=JSON.stringify(e);return`Content-Length: ${Fh(t)}${Oh}${t}`}function Fh(e){return new TextEncoder().encode(e).byteLength}function ga(){let e=new TextEncoder,t=new TextDecoder,n=new Uint8Array(0),r=o=>{let a=new Uint8Array(n.length+o.length);a.set(n),a.set(o,n.length),n=a},s=()=>{for(let o=0;o+3qd){n=n.subarray(l+4);continue}let f=l+4;if(n.lengtha===0?o:encodeURIComponent(o)).join("/")}function Vd(e,t){if(!t.startsWith("file://"))return;let n=decodeURIComponent(t.slice(7));/^\/[A-Za-z]:/.test(n)&&(n=n.slice(1));let r=e.replace(/\/+$/,"");if(n===r)return"";if(n.startsWith(`${r}/`))return n.slice(r.length+1)}function ei(e,t){let n=Array.isArray(t)?t:t&&typeof t=="object"?[t]:[],r=new Set,s=[];for(let o of n){if(!o||typeof o!="object")continue;let a=o.uri??o.targetUri;if(!a)continue;let l=Vd(e,a);if(l===void 0||l==="")continue;let c=(o.range??o.targetSelectionRange??o.targetRange)?.start,d=typeof c?.line=="number"?c.line+1:1,u=typeof c?.character=="number"?c.character:void 0,f=`${l}:${d}:${u??""}`;r.has(f)||(r.add(f),s.push(u===void 0?{file:l,line:d}:{file:l,line:d,character:u}))}return s.sort((o,a)=>R(o.file,a.file)||o.line-a.line||(o.character??0)-(a.character??0))}var qd,Oh,_a=O(()=>{"use strict";S();K();qd=32*1024*1024,Oh=`\r +`),Td(t)}function da(e,t){try{return te(ca(e,t),"utf8")}catch{return}}function ua(e,t){let n=ca(e,t);try{Ee(n)}catch{return!1}return qe(n),!0}function fa(e){let t=I(e,...Ad),n=[],r=(s,o)=>{let a;try{a=_n(s,{withFileTypes:!0})}catch{return}for(let l of a)l.isDirectory()?r(I(s,l.name),o?`${o}/${l.name}`:l.name):l.name.endsWith(".md")&&n.push(o?`${o}/${l.name.slice(0,-3)}`:l.name.slice(0,-3))};return r(t,""),n.sort()}var Ad,Zs=F(()=>{"use strict";k();xe();oe();Ad=[".codeindex","memories"]});function xt(e,t,n){let r=G(e);if(r)try{let s=JSON.parse(r);if(s&&typeof s=="object")return s;t&&n&&n.push(`malformed ${t}: not a JSON object`);return}catch(s){if(t&&n){let o=String(s instanceof Error?s.message:s).split(` +`)[0];n.push(`malformed ${t}: ${o}`)}return}}function jt(e,t){let n=new RegExp(`^\\[${Ge(t)}\\]\\s*$([\\s\\S]*?)(?=^\\[|$(?![\\s\\S]))`,"m"),r=e.match(n);return r?r[1]:null}function wr(e,t){let n=e.match(new RegExp(`${Ge(t)}\\s*=\\s*\\[([^\\]]*)\\]`));return n?n[1].split(/\r?\n/).map(r=>r.replace(/#.*$/,"")).join(` +`).split(",").map(r=>r.trim().replace(/^["']|["']$/g,"")).filter(Boolean):[]}function Tn(e,t){return e?.match(new RegExp(`^\\s*${Ge(t)}\\s*=\\s*["']([^"']+)["']`,"m"))?.[1]}function ma(e){let t="";for(let n=0;nZg(e,t,n,r),o=()=>Yg(e,t),a=()=>Qg(e,t),l=()=>e_(e,t),c=()=>t_(e,t),d=()=>n_(e,t,r),f=()=>r_(e,t,r),m=n==="go"?[a,s,o,l,c,d,f]:n==="uv"?[c,s,o,a,l,d,f]:n==="composer"?[d,s,c,o,a,l,f]:n==="gradle"?[s,l,o,a,c,d,f,()=>s_(e,t)]:[s,o,a,l,c,d,f];for(let p of m){let g=p();if(g)return g}}function o_(e){return e.replace(/[\s\S]*?<\/parent>/g,"").replace(/[\s\S]*?<\/dependencies>/g,"").match(/\s*([^<]+?)\s*<\/artifactId>/)?.[1]}function xr(e,t,n,r,s){let o=t.replace(/^\.\//,"").replace(/\/+$/,"");if(!o||o==="."||n.has(o)||o.split("/").includes(".."))return;let a=i_(e,o,r,s);a&&n.set(o,a)}function a_(e,t){try{return Ee(I(e,t)).isDirectory()}catch{return!1}}function Id(e,t){let n;try{n=_n(t?I(e,t):e,{withFileTypes:!0})}catch{return[]}return n.filter(r=>r.isDirectory()&&!r.name.startsWith(".")&&!Kg.has(r.name)).map(r=>t?`${t}/${r.name}`:r.name).sort(M)}function Nd(e,t,n,r){if(!(n>Xg))for(let s of Id(e,t))r.push(s),Nd(e,s,n+1,r)}function l_(e,t){let n=t.split("/").filter(s=>s&&s!==".");if(n.includes(".."))return[];let r=[""];for(let s of n){let o=new Set;if(s==="**")for(let a of r){a&&o.add(a);let l=[];Nd(e,a,0,l);for(let c of l)o.add(c)}else if(s.includes("*")){let a=new RegExp(`^${s.split("*").map(Ge).join("[^/]*")}$`);for(let l of r)for(let c of Id(e,l))a.test(c.split("/").pop())&&o.add(c)}else for(let a of r){let l=a?`${a}/${s}`:s;a_(e,l)&&o.add(l)}if(r=[...o],!r.length)return[]}return r.filter(Boolean)}function Ys(e,t,n,r,s){let o=t.replace(/^\.\//,"").replace(/\/+$/,"");if(o){if(!o.includes("*")){xr(e,o,n,r,s);return}for(let a of l_(e,o))xr(e,a,n,r,s)}}function c_(e,t){let n=[],r=[],s=(d,f)=>{let u=d.trim();u&&(u.startsWith("!")?r.push(u.slice(1)):n.push({pattern:u,kind:f}))},a=xt(I(e,"package.json"),"package.json",t)?.workspaces;if(Array.isArray(a))for(let d of a)typeof d=="string"&&s(d,"npm");else if(a&&typeof a=="object"&&Array.isArray(a.packages))for(let d of a.packages)typeof d=="string"&&s(d,"npm");let l=G(I(e,"pnpm-workspace.yaml")),c=!1;for(let d of l.split(/\r?\n/)){if(/^\S/.test(d)){c=/^packages\s*:/.test(d);continue}if(!c)continue;let f=d.match(/^\s*-\s*['"]?([^'"#]+?)['"]?\s*(?:#.*)?$/);f&&s(f[1].trim(),"pnpm")}return{positives:n,negations:r}}function d_(e,t){let n=xt(I(e,"lerna.json"),"lerna.json",t);if(n&&Array.isArray(n.packages))return n.packages.filter(s=>typeof s=="string").map(s=>({pattern:s,kind:"lerna"}));let r=xt(I(e,"nx.json"),"nx.json",t);if(r){let s=r.workspaceLayout??{},o=typeof s.appsDir=="string"?s.appsDir:"apps",a=typeof s.libsDir=="string"?s.libsDir:"libs";return[...new Set([o,a])].map(l=>({pattern:`${l}/*`,kind:"nx"}))}return[]}function u_(e,t,n){let r=G(I(e,"Cargo.toml"));if(!r)return;let s=jt(r,"workspace");if(!s)return;let o=wr(s,"members");if(!o.length)return;let a=wr(s,"exclude").map(ma),l=new Map;for(let c of o)Ys(e,c,l,"cargo",n);for(let[c,d]of l)a.some(f=>f.test(c))||t.has(c)||t.set(c,d)}function f_(e,t,n){let r=G(I(e,"go.work"));if(!r)return;let s=[];for(let o of r.matchAll(/^use\s*\(([\s\S]*?)\)/gm))for(let a of o[1].split(/\r?\n/)){let l=a.replace(/\/\/.*$/,"").trim();l&&s.push(l)}for(let o of r.matchAll(/^use\s+([^\s(]+)/gm))s.push(o[1]);for(let o of s)o==="."||o==="./"||xr(e,o,t,"go",n)}function m_(e,t,n){let r=G(I(e,"pom.xml"));if(!r)return;let s=r.match(/([\s\S]*?)<\/modules>/)?.[1];if(s)for(let o of s.matchAll(/\s*([^<]+?)\s*<\/module>/g))xr(e,o[1],t,"maven",n)}function p_(e,t,n){let r=G(I(e,"pyproject.toml"));if(!r)return;let s=jt(r,"tool.uv.workspace");if(!s)return;let o=wr(s,"members");if(!o.length)return;let a=wr(s,"exclude").map(ma),l=new Map;for(let c of o)Ys(e,c,l,"uv",n);for(let[c,d]of l)a.some(f=>f.test(c))||t.has(c)||t.set(c,d)}function g_(e,t,n){let s=xt(I(e,"composer.json"),"composer.json",n)?.repositories;if(Array.isArray(s))for(let o of s){if(!o||typeof o!="object")continue;let{type:a,url:l}=o;a==="path"&&typeof l=="string"&&l&&Ys(e,l,t,"composer",n)}}function __(e,t,n){for(let r of["settings.gradle","settings.gradle.kts"]){let s=G(I(e,r));if(s){for(let o of s.split(/\r?\n/))if(/^\s*include[\s(]/.test(o))for(let a of o.matchAll(/["']([^"']+)["']/g)){let l=a[1].replace(/^:/,"").replace(/:/g,"/");l&&xr(e,l,t,"gradle",n)}}}}function h_(e,t,n,r){let s=xt(I(e,t.dir,"package.json"),`${t.dir}/package.json`,r);if(!s)return[];let o=new Set;for(let a of["dependencies","devDependencies","peerDependencies"]){let l=s[a];if(!(!l||typeof l!="object"))for(let c of Object.keys(l))c!==t.name&&n.has(c)&&o.add(c)}return[...o]}function Od(e,t){let n=`${e}/${t}`.split("/"),r=[];for(let s of n)!s||s==="."||(s===".."?r.pop():r.push(s));return r.join("/")}function y_(e,t,n,r){let s=G(I(e,t.dir,"Cargo.toml"));if(!s)return[];let o=new Set;for(let a of["dependencies","dev-dependencies","build-dependencies"]){let l=jt(s,a);if(l)for(let c of l.split(/\r?\n/)){let d=c.match(/^\s*([A-Za-z0-9_-]+)\s*=\s*(.+)$/);if(!d)continue;let f=d[1];if(f!==t.name&&n.has(f)){o.add(f);continue}let u=d[2].match(/path\s*=\s*["']([^"']+)["']/);if(u){let m=r.get(Od(t.dir,u[1]));m&&m!==t.name&&o.add(m)}}}return[...o]}function b_(e,t,n,r){let s=G(I(e,t.dir,"go.mod"));if(!s)return[];let o=new Set;for(let a of s.matchAll(/^\s*(?:require\s+)?([^\s/(][^\s]*)\s+v[^\s]+/gm)){let l=a[1];l!==t.name&&n.has(l)&&o.add(l)}for(let a of s.matchAll(/^\s*(?:replace\s+)?(\S+)(?:\s+\S+)?\s*=>\s*(\.\.?\/\S+)/gm)){let l=r.get(Od(t.dir,a[2]));l&&l!==t.name&&o.add(l)}return[...o]}function w_(e,t,n){let r=G(I(e,t.dir,"pom.xml"));if(!r)return[];let s=new Set;for(let o of r.replace(/[\s\S]*?<\/parent>/g,"").matchAll(/([\s\S]*?)<\/dependency>/g)){let a=o[1].match(/\s*([^<]+?)\s*<\/artifactId>/)?.[1];a&&a!==t.name&&n.has(a)&&s.add(a)}return[...s]}function x_(e,t,n){let r=G(I(e,t.dir,"pyproject.toml"));if(!r)return[];let s=new Set,o=jt(r,"project");if(o)for(let l of wr(o,"dependencies")){let c=l.match(/^[A-Za-z0-9_.-]+/)?.[0];c&&c!==t.name&&n.has(c)&&s.add(c)}let a=jt(r,"tool.uv.sources");if(a)for(let l of a.split(/\r?\n/)){let c=l.match(/^\s*([A-Za-z0-9_.-]+)\s*=\s*\{[^}]*workspace\s*=\s*true/);c&&c[1]!==t.name&&n.has(c[1])&&s.add(c[1])}return[...s]}function S_(e,t,n,r){let s=xt(I(e,t.dir,"composer.json"),`${t.dir}/composer.json`,r);if(!s)return[];let o=new Set;for(let a of["require","require-dev"]){let l=s[a];if(!(!l||typeof l!="object"))for(let c of Object.keys(l))c!==t.name&&n.has(c)&&o.add(c)}return[...o]}function k_(e,t,n,r){for(let s of["build.gradle","build.gradle.kts"]){let o=G(I(e,t.dir,s));if(!o)continue;let a=new Set;for(let l of o.matchAll(/project\s*\(\s*["']:?([^"']+)["']\s*\)/g)){let c=l[1].replace(/:/g,"/"),d=r.get(c)??(n.has(c)?c:void 0);d&&d!==t.name&&a.add(d)}return[...a]}return[]}function E_(e,t,n,r,s){switch(t.kind){case"cargo":return y_(e,t,n,r);case"go":return b_(e,t,n,r);case"maven":return w_(e,t,n);case"uv":return x_(e,t,n);case"composer":return S_(e,t,n,s);case"gradle":return k_(e,t,n,r);default:return h_(e,t,n,s)}}function v_(e){let t=new Map(e.map(o=>[o.name,[...o.dependsOn??[]].sort(M)])),n=new Map,r=[],s=o=>{n.set(o,"visiting"),r.push(o);for(let a of t.get(o)??[])if(t.has(a)){if(n.get(a)==="visiting")return[...r.slice(r.indexOf(a)),a];if(!n.has(a)){let l=s(a);if(l)return l}}return r.pop(),n.set(o,"done"),null};for(let o of[...t.keys()].sort(M))if(!n.has(o)){let a=s(o);if(a)return a}}function R_(e){let t=new Map(e.map(r=>[r.name,new Set(r.dependsOn??[])])),n=[];for(;t.size>0;){let r=[...t.entries()].filter(([,s])=>[...s].every(o=>!t.has(o))).map(([s])=>s).sort(M);if(!r.length){n.push(...[...t.keys()].sort(M));break}for(let s of r)n.push(s),t.delete(s)}return n}function nn(e){let t=[],n=new Map,{positives:r,negations:s}=c_(e,t),o=r.length?r:d_(e,t);if(o.length){let f=new Map;for(let{pattern:m,kind:p}of o)Ys(e,m,f,p,t);let u=s.map(ma);for(let[m,p]of f)u.some(g=>g.test(m))||n.set(m,p)}u_(e,n,t),f_(e,n,t),m_(e,n,t),p_(e,n,t),g_(e,n,t),__(e,n,t);let a=[...n.values()].sort((f,u)=>M(f.dir,u.dir)),l=new Set(a.map(f=>f.name)),c=new Map(a.map(f=>[f.dir,f.name]));for(let f of a){let u=E_(e,f,l,c,t);u.length&&(f.dependsOn=u.sort(M))}let d=[...a].sort((f,u)=>u.dir.length-f.dir.length);return{packages:a,cycle:v_(a),topoOrder:R_(a),warnings:[...new Set(t)].sort(M),packageOf:f=>d.find(u=>f===u.dir||f.startsWith(u.dir+"/"))}}var Kg,Xg,Sr=F(()=>{"use strict";k();xe();oe();Ae();Y();Ce();Kg=new Set(["node_modules",".git","dist","build","target","coverage"]),Xg=4});function M_(e,t){return e.modules.find(n=>n.slug===t)?.community}function O_(e,t){let n=e.length,r=new Map(e.map((l,c)=>[l,c])),s=Array.from({length:n},()=>new Map);for(let l of t){if(l.dangling)continue;let c=r.get(l.from),d=r.get(l.to);c===void 0||d===void 0||c===d||(s[c].set(d,(s[c].get(d)??0)+l.weight),s[d].set(c,(s[d].get(c)??0)+l.weight))}let o=s.map(l=>{let c=0;for(let d of l.values())c+=d;return c}),a=o.reduce((l,c)=>l+c,0);return{n,adj:s,k:o,twoM:a}}function pa(e){let t=new Map,n=new Array(e.length);for(let r=0;rf);if(s===0)return pa(o);let a=r.slice(),l=!0,c=0;for(;l&&cy-h)){if(g===f)continue;let y=u.get(g)-Fd*r[d]*a[g]/s;y>p+T_&&(p=y,m=g)}a[m]+=r[d],m!==f&&(o[d]=m,l=!0)}}return pa(o)}function P_(e,t,n){let r=Array.from({length:n},()=>new Map);for(let a=0;a{let l=0;for(let c of a.values())l+=c;return l}),o=s.reduce((a,l)=>a+l,0);return{n,adj:r,k:s,twoM:o}}function Pd(e){if(e.n===0)return[];let t=e,n=Array.from({length:e.n},(r,s)=>s);for(let r=0;rn&&n.length>0)}function $_(e,t){let n=t.length,r=new Map;t.forEach((c,d)=>r.set(c,d));let s=Array.from({length:n},()=>new Map);for(let c=0;c{let d=0;for(let f of c.values())d+=f;return d}),a=o.reduce((c,d)=>c+d,0),l=Pd({n,adj:s,k:o,twoM:a});return $d(l).map(c=>c.map(d=>t[d]))}function L_(e,t,n){let r=[];for(let s of e){if(s.length>I_*n&&s.length>=N_){let o=$_(t,s);if(o.length>1){r.push(...o);continue}}r.push(s)}return r}function D_(e,t){if(e.length!==t.length)return t.length-e.length;for(let n=0;n({id:Number(u),set:new Set(m)})),o=[];e.forEach((u,m)=>{for(let p of s){let g=0;for(let y of u)p.set.has(y)&&g++;g>0&&o.push({ni:m,prevId:p.id,inter:g})}}),o.sort((u,m)=>m.inter-u.inter||u.ni-m.ni||u.prevId-m.prevId);let a=new Map,l=new Set;for(let u of o)a.has(u.ni)||l.has(u.prevId)||(a.set(u.ni,u.prevId),l.add(u.prevId));let c=new Set;for(let u=0;u=0&&mf.slug).sort(M),o=O_(s,t),a=Pd(o),c=L_($d(a),o,s.length).map(f=>f.map(u=>s[u]).sort(M));c.sort(D_);let d=j_(c,n);return c.forEach((f,u)=>{for(let m of f)r.set(m,d[u])}),r}var Fd,C_,A_,T_,I_,N_,_a=F(()=>{"use strict";k();Y();Fd=1,C_=20,A_=10,T_=1e-12,I_=.25,N_=10});function Qs(e){let t=new Map,n=new Map;for(let a of e.modules)a.community!==void 0&&t.set(a.slug,a.community),n.set(a.slug,a.tier);let r=new Map,s=(a,l)=>ar.get(s(a.comms[0],a.comms[1]))<=U_).map(a=>({from:a.edge.from,to:a.edge.to,kind:a.edge.kind,weight:a.edge.weight,communities:a.comms,pairEdges:r.get(s(a.comms[0],a.comms[1]))})).sort((a,l)=>a.pairEdges-l.pairEdges||M(a.from,l.from)||M(a.to,l.to)).slice(0,W_)}function z_(e,t,n){return(e.surprises??Qs(e)).some(s=>s.from===t&&s.to===n)}var W_,U_,B_,ha=F(()=>{"use strict";k();Y();W_=24,U_=2,B_=new Set(["import","call","use"])});function H_(e){let t={};for(let n of Object.keys(e).sort(M))t[n]=e[n];return t}function In(e){let t={...e,languages:H_(e.languages)};return JSON.stringify(t,null,2)+` +`}var ei=F(()=>{"use strict";k();Y()});function Ah(e,t){return t!=="string"?!0:e.length>=Mh||Ch.test(e)}function Fh(e){if(!e)return!1;for(let t=0;t")&&!"=!<>+-*/%&|^".includes(e[t-1]??""))return Oh.test(e.slice(t+1));return!1}function Ph(e,t){let n;for(let r of e){if(!vh.has(r.kind)||Fh(r.signature))continue;let s=r.endLine??r.line;s-r.line>Rh||ts||(!n||r.line>n.line)&&(n=r)}return n}function rn(e,t={}){let n=t.minFiles??qd.minFiles,r=t.minCount??qd.minCount,s=new Map;for(let a of e.files)if(a.literals?.length&&!(!t.includeTests&&$t(a.rel)))for(let l of a.literals){if(t.kinds&&!t.kinds.has(l.kind)||!Ah(l.value,l.kind))continue;let c=`${l.kind}\0${l.value}`,d=s.get(c);d||s.set(c,d={value:l.value,kind:l.kind,sites:[]});let f=Ph(a.symbols,l.line);d.sites.push(f?{file:a.rel,line:l.line,holder:f.name,holderExported:f.exported}:{file:a.rel,line:l.line})}let o=[];for(let a of s.values()){let l=new Set(a.sites.map(p=>p.file));if(l.sizep.holder),d=a.sites.filter(p=>!p.holder),f=new Set(c.map(p=>p.holder)),m=new Set(c.map(p=>`${p.file}\0${p.holder}`)).size>=2?"competing":c.length>0?"bypassed":"uncentralized";if(a.kind==="number"){if(f.size!==1||d.length===0)continue;m="bypassed"}m==="bypassed"&&d.length===0||o.push({value:a.value,kind:a.kind,tier:m,holders:c.sort(Gd),literals:d.sort(Gd),files:l.size,count:a.sites.length})}return o.sort((a,l)=>Vd(a.tier)-Vd(l.tier)||l.files-a.files||l.count-a.count||M(a.value,l.value)),{duplications:o,families:$h(o)}}function Gd(e,t){return M(e.file,t.file)||e.line-t.line}function Vd(e){return e==="competing"?0:e==="bypassed"?1:2}function $h(e){let t=new Map;for(let r of e){if(r.kind!=="string"||!Th.test(r.value))continue;let s=Lh(r.value);if(!s)continue;let o=t.get(s);o?o.push(r):t.set(s,[r])}let n=[];for(let[r,s]of t){if(s.lengths.files-r.files||s.count-r.count||M(r.prefix,s.prefix)),n}function Lh(e){let t=e.startsWith("/")?e.slice(1):e,n=t.search(/[/:]/);if(n<=0)return;let r=(e.startsWith("/")?"/":"")+t.slice(0,n);return r.length>=Nh?r:void 0}var Jd,qd,vh,Rh,Mh,Ch,Th,Ih,Nh,Oh,kr=F(()=>{"use strict";k();vn();Y();Jd=24,qd={minFiles:2,minCount:3},vh=new Set(["const","constant","variable","enum","enumerator","property","field","static"]),Rh=12,Mh=6,Ch=/[/:._-]/;Th=/^[/@a-z0-9][\w./:@-]*$/i,Ih=2,Nh=4,Oh=/^\s*(?:async\b|function\b|\(|[A-Za-z_$][\w$]*\s*=>)/});function Dh(e,t={}){return Et(Pe(e,t),t)}function Et(e,t={}){let n=Zo(e),{modules:r,moduleOf:s}=Ho(e),o=ta(e,n,r,s,t.meta),a=ga(o.modules,o.moduleEdges,t.previousCommunities);for(let u of o.modules){let m=a.get(u.slug);m!==void 0&&(u.community=m)}Ko(o);let l=pr(o);for(let u of o.files)l.testFiles.has(u.rel)&&(u.testFile=!0);for(let u of o.modules){let m=l.testedByModule.get(u.slug);m?.length&&(u.testedBy=m)}let c=Qs(o);c.length&&(o.surprises=c);let{duplications:d}=rn(e);d.length&&(o.literalDuplications=d.slice(0,Jd));let f=Jo(e,Vs(e),t.meta?.schemaVersion);return{scan:e,graph:o,symbols:f}}var ri=F(()=>{"use strict";k();Ft();mt();Ds();Js();_a();qs();vn();ha();kr();cr()});function Wh(e){return e.sort((t,n)=>M(t.file,n.file)||t.line-n.line)}function Uh(e,t,n){let r=["--no-heading","--line-number","--null","--color=never","--no-messages","--hidden","--no-require-git","--no-ignore-global","--no-ignore-exclude","--no-ignore-parent","--no-ignore-dot","--max-filesize","1M"];for(let c of qt)r.push("--glob",`!**/${c}/**`);for(let c of Wi)r.push("--iglob",`!**/${c}`);for(let c of Ui)r.push("--iglob",`!**/*${c}`);r.push("--glob","!*.min.js","--glob","!*.min.css"),n.ignoreCase&&r.push("--ignore-case");let s=n.globs??[],o=c=>c.startsWith("/")?c:`/${c}`;for(let c of s.filter(d=>!d.startsWith("!")))r.push("--glob",o(c));for(let c of s.filter(d=>d.startsWith("!")))r.push("--glob",`!${o(c.slice(1))}`);r.push("--regexp",t,"./");let a=pe("rg",r,{cwd:e});if(a.missing||!a.ok&&a.status!==1)return;let l=[];for(let c of a.stdout.split(` +`)){if(!c)continue;let d=c.indexOf("\0");if(d===-1)continue;let f=c.slice(0,d).replace(/^\.\//,""),u=c.slice(d+1),m=u.indexOf(":");m!==-1&&l.push({file:f,line:Number(u.slice(0,m)),text:u.slice(m+1)})}return l}function Bh(e,t,n){let r=ec(n.globs?.map(o=>o.replace(/^(!?)\//,"$1"))),s=[];for(let o of Fe(e).files){if(r&&!r(o.rel))continue;let a=G(o.abs);if(!a)continue;let l=a.split(` +`);for(let c=0;c{"use strict";k();Ae();Hn();Ce();Y();jh=200});function vt(e){let t=R.env.CODEINDEX_EMBED_DIR,n=[];t&&n.push(t),e&&n.push(I(e,".codeindex",Kd)),n.push(I(R.cwd(),".codeindex",Kd));for(let r of n)if(H(I(r,"model.json")))return r}function qh(e){return vt(e)!==void 0}function ba(e,t){let{modelId:n,dim:r,vocab:s,weights:o,unk:a}=e??{};if(typeof n!="string"||!n)throw new Error(`embed model: missing modelId in ${t}`);if(!Number.isInteger(r)||r<=0)throw new Error(`embed model: bad dim ${r} in ${t}`);if(!Array.isArray(s)||!Array.isArray(o)||s.length!==o.length)throw new Error(`embed model: vocab/weights length mismatch in ${t}`);let l=s.length,c=new Float64Array(l*r),d=new Map;for(let m=0;m{"use strict";k();cs();xe();oe();it=1,Kd="models",zh="https://github.com/maxgfr/codeindex/releases/download/embed-model-v1/model.json",Hh="163ad053eab4e9a80d421ed4164f32292c83290f02fbbe6fe4b9b1cd6ea18d34"});function Zd(e){let t=_t(e).replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1 $2"),n=[];for(let r of t.toLowerCase().split(/[^a-z0-9]+/))r&&n.push(r);return n}function Yd(e,t){if(!e)return[];let n=[],r=0,s=e.length;for(;rr;){let l=r===0?e.slice(r,o):"##"+e.slice(r,o),c=t.vocab.get(l);if(c!==void 0){a=c;break}o--}if(a===-1)return t.unkId>=0?[t.unkId]:[];n.push(a),r=o}return n}function Qd(e,t){let n=[];for(let r of Zd(e))for(let s of Yd(r,t))n.push(s);return n}function eu(e){let t=Math.floor(e),n=e-t;return n<.5?t:n>.5?t+1:t%2===0?t:t+1}function Rr(e){let t=e.length,n=new Int8Array(t),r=0;for(let o=0;ovr?a=vr:a<-vr&&(a=-vr),n[o]=a}return n}function Mr(e,t){let{dim:n,weights:r}=e,s=Qd(t,e);if(s.length===0)return new Int8Array(n);let o=new Float64Array(n);for(let l of s){let c=l*n;for(let d=0;d{"use strict";k();Ce();vr=127});function Gh(e,t,n,r){return[t,n??"",r??"",e.replace(/\//g," ")].join(` +`)}function Vh(e,t,n,r){return[t??"",n??"",...r,e.replace(/\//g," ")].join(` +`)}function ii(e){let t=[];for(let n of e.files){let r=new Set,s=!1;for(let o of n.symbols)r.has(o.name)||(r.add(o.name),s=!0,t.push({file:n.rel,symbol:o.name,line:o.line,text:Gh(n.rel,o.name,o.signature,n.summary)}));if(!s){let o=Vh(n.rel,n.title,n.summary,n.headings);o.replace(/\s+/g,"")&&t.push({file:n.rel,text:o})}}return t}function on(e,t){let n=ii(e).map(r=>{let s={file:r.file,vec:Mr(t,r.text)};return r.symbol!==void 0&&(s.symbol=r.symbol),r.line!==void 0&&(s.line=r.line),s});return{embedVersion:it,modelId:t.modelId,dim:t.dim,records:n}}function oi(e){let t=JSON.stringify({embedVersion:e.embedVersion,modelId:e.modelId,dim:e.dim,count:e.records.length,records:e.records.map(a=>({file:a.file,symbol:a.symbol??"",line:a.line??0}))}),n=new TextEncoder().encode(t),r=e.records.length*e.dim,s=new Uint8Array(8+n.length+r);s.set([67,73,69,49],0),new DataView(s.buffer,s.byteOffset,s.byteLength).setUint32(4,n.length,!0),s.set(n,8);let o=8+n.length;for(let a of e.records)for(let l=0;le.byteLength)throw new Error("embeddings.bin: truncated header");let r=JSON.parse(new TextDecoder().decode(e.subarray(8,8+n))),s=8+n,{dim:o}=r;if(s+r.records.length*o>e.byteLength)throw new Error("embeddings.bin: truncated body");let a=r.records.map((l,c)=>{let d=new Int8Array(e.buffer.slice(e.byteOffset+s+c*o,e.byteOffset+s+(c+1)*o)),f={file:l.file,vec:d};return l.symbol&&(f.symbol=l.symbol),l.line&&(f.line=l.line),f});return{embedVersion:r.embedVersion,modelId:r.modelId,dim:o,records:a}}var Jh,On=F(()=>{"use strict";k();Cr();sn();Jh="CIE1"});function an(e,t,n,r={}){let s=r.limit??Xh,o=Lt(e,t,{limit:Math.max(s,50),fuzzy:r.fuzzy}),a=r.queryVec??(r.model?Mr(r.model,t):void 0);if(!a||!n||n.records.length===0)return o.slice(0,s);let l=new Map;for(let p of n.records){let g=xa(a,p.vec),y=l.get(p.file);(!y||g>y.score)&&l.set(p.file,{score:g,symbol:p.symbol})}let c=[...l.entries()].filter(([,p])=>p.score>0).sort((p,g)=>g[1].score-p[1].score||M(p[0],g[0])).map(([p])=>p),d=o.map(p=>p.file),f=$i([d,c],p=>p,r.rrfK??Zh),u=new Map(o.map(p=>[p.file,p]));return[...f.entries()].sort((p,g)=>g[1]-p[1]||M(p[0],g[0])).map(([p,g])=>{let y=u.get(p),h={file:p,score:Number(g.toFixed(4)),matchedTerms:y?.matchedTerms??[],topSymbols:y?.topSymbols??[]},S=l.get(p);return S?.symbol&&(h.semanticSymbol=S.symbol),y?.fuzzyTerms&&(h.fuzzyTerms=y.fuzzyTerms),h}).slice(0,s)}var Xh,Zh,ai=F(()=>{"use strict";k();Ce();Y();Mn();Cr();Xh=20,Zh=60});function Ut(e={}){let t=e.url??R.env.CODEINDEX_EMBED_ENDPOINT;return t&&t.trim()?t.trim():void 0}function tu(e){return e.replace(/\/+$/,"")}function nu(e){let t=tu(e);return t.endsWith("/embed")?t:t+"/embed"}function ru(e){return tu(e).replace(/\/embed$/,"")+"/healthz"}function su(e){if(typeof e.timeoutMs=="number")return e.timeoutMs;let t=Number(R.env.CODEINDEX_EMBED_TIMEOUT_MS);return Number.isFinite(t)&&t>0?t:3e4}async function Sa(e,t={}){let n=Ut(t);if(!n)throw new Error("no embedding endpoint configured (set CODEINDEX_EMBED_ENDPOINT or pass opts.url)");let r=nu(n),s=new AbortController,o=setTimeout(()=>s.abort(),su(t));try{let a=await fetch(r,{method:"POST",headers:{"content-type":"application/json",...t.headers??{}},body:JSON.stringify({texts:e}),signal:s.signal});if(!a.ok)throw new Error(`embedding endpoint ${r} returned HTTP ${a.status}`);let c=(await a.json()).vectors;if(!Array.isArray(c)||!c.every(d=>Array.isArray(d)&&d.every(f=>typeof f=="number")))throw new Error(`embedding endpoint ${r} returned a malformed { vectors } payload`);return c}finally{clearTimeout(o)}}async function Ar(e,t={}){let n=new AbortController,r=setTimeout(()=>n.abort(),su(t));try{return(await fetch(ru(e),{signal:n.signal,headers:t.headers})).ok}catch{return!1}finally{clearTimeout(r)}}async function Tr(e,t={}){let[n]=await Sa([e],t);if(!n)throw new Error("embedding endpoint returned no vector for the query");return Rr(n)}async function Ir(e,t={}){let n=ii(e),r=t.batchSize&&t.batchSize>0?t.batchSize:64,s=[],o=0;for(let a=0;ad.text),t);if(c.length!==l.length)throw new Error(`embedding endpoint returned ${c.length} vectors for ${l.length} texts`);for(let d=0;do&&(o=u.length);let m={file:f.file,vec:u};f.symbol!==void 0&&(m.symbol=f.symbol),f.line!==void 0&&(m.line=f.line),s.push(m)}}return{embedVersion:it,modelId:"endpoint",dim:o,records:s}}var li=F(()=>{"use strict";k();Cr();sn();On()});function ln(e,t,n={}){let r=(n.budgetTokens??1024)*iu,s=n.maxSymbolsPerFile??8,o=[...t.files].filter(f=>f.fileKind==="code").sort((f,u)=>(u.pagerank??0)-(f.pagerank??0)||u.symbols-f.symbols||M(f.rel,u.rel)),a=new Map(e.files.map(f=>[f.rel,f])),c=`# repo map \u2014 ${t.fileCount} files +`,d=0;for(let f of o){let u=a.get(f.rel);if(!u)continue;let m=[...u.symbols].filter(g=>g.kind!=="reexport"&&g.kind!=="reexport-all").sort((g,y)=>Number(y.exported)-Number(g.exported)||g.line-y.line).slice(0,s),p=` +${f.rel}: +`;for(let g of m){let y=(g.signature??`${g.kind} ${g.name}`).replace(/\s+/g," ").trim().slice(0,120);p+=` ${g.line}: ${y} +`}if(c.length+p.length>r)break;c+=p,d++}return`${c} +(${d} of ${o.length} code files shown, ~${Math.ceil(c.length/iu)} tokens) +`}var iu,Nr=F(()=>{"use strict";k();Y();iu=4});function Or(e,t={}){let n=t.maxCommitFiles??30,r=t.minTogether??3,s=t.maxPairs??100,o=t.since?[`${t.since}..HEAD`]:[],a=pe("git",["-C",e,"-c","core.quotePath=false","log",...o,"--pretty=format:%x1e","--name-only"]);if(!a.ok)return{ok:!1,couplings:[]};let l=new Map,c=new Map;for(let f of a.stdout.split("")){let u=f.split(` +`).map(p=>p.trim()).filter(Boolean);if(!u.length||u.length>n)continue;let m=[...new Set(u)].sort(M);for(let p of m)l.set(p,(l.get(p)??0)+1);for(let p=0;pu.strength-f.strength||u.together-f.together||M(f.a,u.a)||M(f.b,u.b)),{ok:!0,couplings:d.slice(0,s)}}function cn(e,t,n=20){let r=e.files.filter(s=>s.kind==="code").map(s=>{let o=t.get(s.rel)??0;return{rel:s.rel,lines:s.lines,commits:o,score:Number((o*Math.log2(s.lines+1)).toFixed(2))}});return r.sort((s,o)=>o.score-s.score||o.lines-s.lines||M(s.rel,o.rel)),r.slice(0,n)}var ou,Fr=F(()=>{"use strict";k();Ce();Y();ou="\0"});function Qh(e){for(let t of Yh){let n=I(e,t);if(!H(n))continue;let r;try{r=te(n,"utf8")}catch{continue}for(let s of r.split(/\n\s*\n/)){let o=s.trim();if(!o||o.startsWith("#")||o.startsWith("<")||/^(\[!\[|!\[|\[)/.test(o)&&!/[.:]\s/.test(o))continue;let a=o.replace(/\[([^\]]*)\]\([^)]*\)/g,"$1").replace(/[*_`]/g,"").replace(/\s+/g," ").trim();if(a.length>20)return a.slice(0,400)}break}}function ka(e,t,n={}){let r=[],s=Ne(e.root).replace(/\/+$/,"").split("/").pop()||"repository";r.push(`# ${s}`,"");let o=Qh(e.root);o&&r.push(o,"");let a=Object.entries(t.languages).sort((m,p)=>p[1]-m[1]||M(m[0],p[0])).slice(0,6).map(([m,p])=>`${m} ${p}`).join(", ");r.push(`**${t.fileCount} indexed files** \xB7 ${a}`,"");let l=nn(e.root);if(l.packages.length>1){r.push(`## Layout \u2014 monorepo, ${l.packages.length} packages`,"");for(let m of l.packages.slice(0,20))r.push(`- \`${m.dir}\` \u2014 ${m.name}`);l.packages.length>20&&r.push(`- \u2026and ${l.packages.length-20} more`),l.cycle?.length&&r.push("",`\u26A0 dependency cycle: ${l.cycle.join(" \u2192 ")}`),r.push("")}r.push("## Key files","",ln(e,t,{budgetTokens:n.budgetTokens??900}).trim(),"");let{churn:c,ok:d}=Ze(e.root);if(d&&c.size){let m=cn(e,c,8);if(m.length){r.push("## Where work concentrates","","Files ranked by commits \xD7 size \u2014 where changes and defects cluster.","");for(let p of m)r.push(`- \`${p.rel}\` \u2014 ${p.commits} commits, ${p.lines} lines`);r.push("")}}r.push("## Next","","- `search ` \u2014 BM25 over names, paths, doc comments and prose; `explain_search` says whether it really matched","- `find_symbol ` / `symbols_overview ` \u2014 read structure without reading files","- `find_references ` \u2014 three labelled tiers; add `lsp: true` when a language server is configured","");let f=r.join(` +`);if(n.remember===!1)return{brief:f};let u=n.memoryName??"onboarding";return br(e.root,u,f),{brief:f,memory:u}}var Yh,Ea=F(()=>{"use strict";k();xe();oe();Nr();Sr();Fr();Gt();Zs();Y();Yh=["README.md","README.markdown","README.rst","README.txt","README"]});function ci(e){let t=JSON.stringify(e);return`Content-Length: ${ty(t)}${ey}${t}`}function ty(e){return new TextEncoder().encode(e).byteLength}function va(){let e=new TextEncoder,t=new TextDecoder,n=new Uint8Array(0),r=o=>{let a=new Uint8Array(n.length+o.length);a.set(n),a.set(o,n.length),n=a},s=()=>{for(let o=0;o+3au){n=n.subarray(l+4);continue}let u=l+4;if(n.lengthc===0||c===1&&/^[A-Za-z]:$/.test(l)?l:encodeURIComponent(l)).join("/")}function lu(e,t){if(!t.startsWith("file://"))return;let n;try{let l=t.slice(7);n=decodeURIComponent(l.startsWith("/")?l:`//${l}`).replace(/\\/g,"/")}catch{return}/^\/[A-Za-z]:/.test(n)&&(n=n.slice(1));let r=e.replace(/\\/g,"/").replace(/\/+$/,""),s=/^[A-Za-z]:/.test(r)||r.startsWith("//"),o=s?n.toLowerCase():n,a=s?r.toLowerCase():r;if(o===a)return"";if(o.startsWith(`${a}/`))return n.slice(r.length+1)}function di(e,t){let n=Array.isArray(t)?t:t&&typeof t=="object"?[t]:[],r=new Set,s=[];for(let o of n){if(!o||typeof o!="object")continue;let a=o.uri??o.targetUri;if(!a)continue;let l=lu(e,a);if(l===void 0||l==="")continue;let c=(o.range??o.targetSelectionRange??o.targetRange)?.start,d=typeof c?.line=="number"?c.line+1:1,f=typeof c?.character=="number"?c.character:void 0,u=`${l}:${d}:${f??""}`;r.has(u)||(r.add(u),s.push(f===void 0?{file:l,line:d}:{file:l,line:d,character:f}))}return s.sort((o,a)=>M(o.file,a.file)||o.line-a.line||(o.character??0)-(a.character??0))}var au,ey,Ra=F(()=>{"use strict";k();Y();au=32*1024*1024,ey=`\r \r -`});async function ha(e,t){let n=t.timeoutMs??Ph,r=t.startupTimeoutMs??$h,s=ga(),o=new Map,a=new Set,l=1,c,d=_=>{c=_;for(let[,y]of o)clearTimeout(y.timer),y.reject(_);o.clear()};e.onData(_=>{for(let y of s.push(_)){if(typeof y.id!="number")continue;let x=o.get(y.id);x&&(o.delete(y.id),clearTimeout(x.timer),y.error?x.reject(new Error(`${y.error.message} (code ${y.error.code})`)):x.resolve(y.result))}}),e.onExit(_=>d(new Error(`language server exited (code ${_??"unknown"})`)));let u=(_,y)=>{c||e.write(Qs({jsonrpc:"2.0",method:_,params:y}))},f=(_,y,x=n)=>{if(c)return Promise.reject(c);let E=l++;return new Promise((w,k)=>{let C=setTimeout(()=>{o.delete(E),k(new ti(_,x))},x);C.unref?.(),o.set(E,{resolve:w,reject:k,timer:C}),e.write(Qs({jsonrpc:"2.0",id:E,method:_,params:y}))})},p=await f("initialize",{processId:null,rootUri:cn(t.root,""),workspaceFolders:[{uri:cn(t.root,""),name:"repo"}],capabilities:{textDocument:{references:{dynamicRegistration:!1},definition:{dynamicRegistration:!1,linkSupport:!0},implementation:{dynamicRegistration:!1,linkSupport:!0}}},...t.initializationOptions!==void 0?{initializationOptions:t.initializationOptions}:{}},r);u("initialized",{});let m=_=>{let y=p?.capabilities?.[_];return y===!0||typeof y=="object"&&y!==null},g={references:m("referencesProvider"),definition:m("definitionProvider"),implementation:m("implementationProvider"),typeHierarchy:m("typeHierarchyProvider")},h=(_,y,x)=>({textDocument:{uri:cn(t.root,_)},position:{line:Math.max(0,y-1),character:x}});return{capabilities:g,didOpen(_,y,x){a.has(_)||(a.add(_),u("textDocument/didOpen",{textDocument:{uri:cn(t.root,_),languageId:x,version:1,text:y}}))},async references(_,y,x){if(!g.references)return[];let E=await f("textDocument/references",{...h(_,y,x),context:{includeDeclaration:!0}});return ei(t.root,E)},async definition(_,y,x){return g.definition?ei(t.root,await f("textDocument/definition",h(_,y,x))):[]},async shutdown(){try{for(let _ of a)u("textDocument/didClose",{textDocument:{uri:cn(t.root,_)}});a.clear(),await f("shutdown",null,Math.min(n,2e3)),u("exit",void 0)}catch{}finally{d(new Error("session closed")),e.close()}}}}var ti,Ph,$h,ya=O(()=>{"use strict";S();_a();ti=class extends Error{constructor(t,n){super(`${t} exceeded ${n}ms`),this.name="LspTimeout"}},Ph=5e3,$h=15e3});function ni(e){let t=v.env.CODEINDEX_LSP_CONFIG;if(t!==void 0){let s=t.trim();return!s||s==="0"||s.toLowerCase()==="off"?{path:void 0,source:"none"}:{path:Ae(s),source:"env"}}let n=I(e,Kd,Jd);if(z(n))return{path:n,source:"repo"};let r=I(v.cwd(),Kd,Jd);return r!==n&&z(r)?{path:r,source:"cwd"}:{path:void 0,source:"none"}}function Xd(e){if(!e||typeof e!="object")throw new Error("lsp.json must be a JSON object");let t=e;if(t.version!==1)throw new Error(`lsp.json: unsupported version ${JSON.stringify(t.version)} (expected 1)`);if(!Array.isArray(t.servers))throw new Error("lsp.json: `servers` must be an array");let n=new Set;return{version:1,servers:t.servers.map((s,o)=>{if(!s||typeof s!="object")throw new Error(`lsp.json: servers[${o}] must be an object`);let a=s,l=typeof a.id=="string"&&a.id.trim()?a.id.trim():void 0;if(!l)throw new Error(`lsp.json: servers[${o}].id must be a non-empty string`);if(n.has(l))throw new Error(`lsp.json: duplicate server id ${JSON.stringify(l)}`);if(n.add(l),typeof a.command!="string"||!a.command.trim())throw new Error(`lsp.json: servers[${o}].command must be a non-empty string`);if(!Array.isArray(a.languages)||!a.languages.length||a.languages.some(c=>typeof c!="string"))throw new Error(`lsp.json: servers[${o}].languages must be a non-empty array of strings`);if(a.args!==void 0&&(!Array.isArray(a.args)||a.args.some(c=>typeof c!="string")))throw new Error(`lsp.json: servers[${o}].args must be an array of strings`);return{id:l,languages:a.languages,...typeof a.languageId=="string"?{languageId:a.languageId}:{},command:a.command,...Array.isArray(a.args)?{args:a.args}:{},...a.env&&typeof a.env=="object"?{env:a.env}:{},...a.initializationOptions!==void 0?{initializationOptions:a.initializationOptions}:{},...typeof a.timeoutMs=="number"?{timeoutMs:a.timeoutMs}:{},...typeof a.startupTimeoutMs=="number"?{startupTimeoutMs:a.startupTimeoutMs}:{}}})}}function ri(e){let{path:t}=ni(e);if(!t||!z(t))return;let n;try{n=JSON.parse(te(t,"utf8"))}catch(r){throw new Error(`${t}: ${r instanceof Error?r.message:String(r)}`)}return Xd(n)}function ba(e,t){return e.servers.find(n=>n.languages.includes(t))}function Zd(e){return Qd("CODEINDEX_LSP_TIMEOUT_MS")??e.timeoutMs??Dh}function Yd(e){return Qd("CODEINDEX_LSP_STARTUP_TIMEOUT_MS")??e.startupTimeoutMs??Lh}function Qd(e){let t=v.env[e];if(t===void 0)return;let n=Number(t);return Number.isFinite(n)&&n>0?n:void 0}var Jd,Kd,Dh,Lh,wa=O(()=>{"use strict";S();we();ie();Jd="lsp.json",Kd=".codeindex";Dh=5e3,Lh=15e3});function Ut(e,t){return{server:e,ok:!1,reason:t,refs:[],agreement:{both:[],lspOnly:[],staticOnly:[]}}}function tu(e,t,n,r){try{let o=te(I(e,t),"utf8").split(/\r?\n/)[n-1]?.indexOf(r)??-1;return o<0?0:o}catch{return 0}}function xa(e,t){let n=new Set(e.map(l=>l.file)),r=new Set([...t.callSites.map(l=>l.file),...t.referencingFiles,...t.defs.map(l=>l.file)]),s=[],o=[],a=[];for(let l of n)(r.has(l)?s:o).push(l);for(let l of r)n.has(l)||a.push(l);return{both:s.sort(R),lspOnly:o.sort(R),staticOnly:a.sort(R)}}async function nu(e,t,n,r,s,o){if(!r.capabilities.references)return{...n,lsp:Ut(s,"server does not provide textDocument/references")};if(!n.defs.length)return{...n,lsp:Ut(s,`no declaration of ${t} to anchor a request on`)};let a=new Set,l=[];try{for(let c of n.defs){let d=jh(e.root,c.file);if(!d)continue;r.didOpen(c.file,d,o);let u=tu(e.root,c.file,c.line,t);for(let f of await r.references(c.file,c.line,u)){let p=`${f.file}:${f.line}:${f.character??""}`;a.has(p)||(a.add(p),l.push(f))}}}catch(c){return{...n,lsp:{server:s,ok:!1,reason:c instanceof Error?c.message:String(c),refs:l.sort(eu),agreement:xa(l,n)}}}return l.sort(eu),{...n,lsp:{server:s,ok:!0,refs:l,agreement:xa(l,n)}}}function eu(e,t){return R(e.file,t.file)||e.line-t.line||(e.character??0)-(t.character??0)}function jh(e,t){try{return te(I(e,t),"utf8")}catch{return""}}var Sa=O(()=>{"use strict";S();we();ie();K()});function ka(e,t){let n;try{n=Ya(e.command,e.args??[],{cwd:t,stdio:["pipe","pipe","pipe"],...e.env?{env:{...v.env,...e.env}}:{}})}catch{return}let r=!1,s=[],o=[],a=l=>{if(!r){r=!0;for(let c of o)c(l)}};return n.on("error",()=>a(null)),n.on("close",l=>a(l)),n.stdout?.on("data",l=>{for(let c of s)c(l)}),n.stderr?.on("data",()=>{}),{write(l){if(!r)try{n.stdin?.write(l)}catch{a(null)}},onData(l){s.push(l)},onExit(l){r?l(null):o.push(l)},close(){try{n.stdin?.end()}catch{}let l=setTimeout(()=>{try{n.kill("SIGKILL")}catch{}},2e3);l.unref?.(),n.on("close",()=>clearTimeout(l))}}}var Ea=O(()=>{"use strict";S();ki()});async function Nr(e,t,n=!1){let{path:r,source:s}=ni(t),o=ri(t);if(!o)return{lspVersion:1,mode:"none",configPath:r??null,source:s,servers:[],unmappedLanguages:[]};let a=new Map;for(let u of e.files)a.set(u.lang,(a.get(u.lang)??0)+1);let l=[];for(let u of o.servers){let f={id:u.id,languages:u.languages,command:u.command,onPath:it(u.command),filesInRepo:u.languages.reduce((p,m)=>p+(a.get(m)??0),0)};if(n){let p=await ru(u,e.root);p.ok?(f.reachable=!0,f.capabilities=p.session.capabilities,await p.session.shutdown()):(f.reachable=!1,f.error=p.reason)}l.push(f)}let c=new Set(o.servers.flatMap(u=>u.languages)),d=[...a.keys()].filter(u=>!c.has(u)&&u!=="other").sort();return{lspVersion:1,mode:"configured",configPath:r??null,source:s,servers:l,unmappedLanguages:d}}async function ru(e,t){if(!it(e.command))return{ok:!1,reason:`${e.command} is not on PATH`};let n=ka(e,t);if(!n)return{ok:!1,reason:`could not start ${e.command}`};try{return{ok:!0,session:await ha(n,{root:t,timeoutMs:Zd(e),startupTimeoutMs:Yd(e),...e.initializationOptions!==void 0?{initializationOptions:e.initializationOptions}:{}})}}catch(r){return n.close(),{ok:!1,reason:r instanceof Error?r.message:String(r)}}}async function va(e,t,n,r){let s;try{s=ri(t)}catch(c){return{...r,lsp:Ut("(config)",c instanceof Error?c.message:String(c))}}if(!s)return r;let o=r.defs[0]?.lang;if(!o)return{...r,lsp:Ut("(none)",`no declaration of ${n} to anchor a request on`)};let a=ba(s,o);if(!a)return{...r,lsp:Ut("(none)",`no server configured for ${o}`)};let l=await ru(a,e.root);if(!l.ok)return{...r,lsp:Ut(a.id,l.reason)};try{return await nu(e,n,r,l.session,a.id,a.languageId??a.languages[0])}finally{await l.session.shutdown()}}var si=O(()=>{"use strict";S();Me();ya();wa();Sa();Ea()});function zh(e){let n=e.split("/").pop().split(".")[0].toLowerCase();return Hh.has(n)}function iu(e){return Array.isArray(e)?e:[e]}function Or(e){let t=Array.isArray(e)?e:e?.rules;if(!Array.isArray(t))throw new Error("rules config must be an array (or an object with a `rules` array)");return t.map((n,r)=>{let s=`rules[${r}]`;if(typeof n!="object"||n===null)throw new Error(`${s}: must be an object`);let o=n;if(typeof o.name!="string"||!o.name)throw new Error(`${s}: \`name\` (non-empty string) is required`);if(o.severity!==void 0&&!Uh.has(o.severity))throw new Error(`${s} (${o.name}): \`severity\` must be "error" or "warn"`);if(o.comment!==void 0&&typeof o.comment!="string")throw new Error(`${s} (${o.name}): \`comment\` must be a string`);if(o.builtin!==void 0){if(!Wh.has(o.builtin))throw new Error(`${s} (${o.name}): \`builtin\` must be "cycles", "orphans" or "literals"`);return{name:o.name,builtin:o.builtin,severity:o.severity,comment:o.comment,...o.tiers!==void 0?{tiers:o.tiers}:{}}}let a=d=>{let u=o[d];if(!(typeof u=="string"?u.length>0:Array.isArray(u)&&u.length>0&&u.every(p=>typeof p=="string"&&p)))throw new Error(`${s} (${o.name}): \`${d}\` must be a glob or a non-empty array of globs`);return u},l=a("from"),c=a("to");if(o.kind!==void 0&&!(Array.isArray(o.kind)&&o.kind.every(u=>su.has(u))))throw new Error(`${s} (${o.name}): \`kind\` must be an array of edge kinds (${[...su].join(", ")})`);return{name:o.name,from:l,to:c,kind:o.kind,severity:o.severity,comment:o.comment}})}function Gh(e){let t=new Map;for(let u of e.moduleEdges){if(u.kind!=="import")continue;let f=t.get(u.from);f||t.set(u.from,f=[]),f.push(u.to)}for(let u of t.values())u.sort(R);let n=[...t.keys()].sort(R),r=new Map,s=new Map,o=new Set,a=[],l=[],c=0;for(let u of n){if(r.has(u))continue;let f=[{node:u,next:0}];for(;f.length;){let p=f[f.length-1],m=p.node;p.next===0&&(r.set(m,c),s.set(m,c),c++,a.push(m),o.add(m));let g=t.get(m)??[];if(p.next1&&l.push(_)}f.pop();let h=f[f.length-1];h&&s.set(h.node,Math.min(s.get(h.node),s.get(m)))}}}let d=[];for(let u of l){let f=new Set(u),p=[...u].sort(R)[0],m=new Map([[p,null]]),g=[p];for(let y=0;y(t.get(y)??[]).includes(p)&&y!==p)??p,_=[];for(let y=h;y!==null;y=m.get(y)??null)_.unshift(y);_.push(p),d.push({start:p,path:_})}return d}function Fr(e,t){let n=[],r=(o,a)=>{n.push({rule:o.name,...a,severity:o.severity??"error",...o.comment!==void 0?{comment:o.comment}:{}})},s=new Set(e.files.map(o=>o.rel));for(let o of t){if("builtin"in o){if(o.builtin==="cycles")for(let d of Gh(e))r(o,{from:d.start,to:d.path.join(" -> "),kind:"cycle"});else if(o.builtin==="literals"){let d=new Set(o.tiers?.length?o.tiers:Bh);for(let u of e.literalDuplications??[]){if(!d.has(u.tier))continue;let f=u.holders[0]??u.literals[0];r(o,{from:`${f.file}:${f.line}`,to:`${u.tier} ${JSON.stringify(u.value)} (${u.count} sites, ${u.files} files)`,kind:"literal"})}}else for(let d of e.files)d.fileKind!=="code"||d.degIn!==0||d.degOut!==0||zh(d.rel)||r(o,{from:d.rel,to:d.rel,kind:"orphan"});continue}let a=gt(iu(o.from)),l=gt(iu(o.to));if(!a||!l)continue;let c=o.kind?.length?new Set(o.kind):null;for(let d of e.fileEdges)d.dangling||!s.has(d.to)||c&&!c.has(d.kind)||!a(d.from)||!l(d.to)||r(o,{from:d.from,to:d.to,kind:d.kind})}return n.sort((o,a)=>R(o.rule,a.rule)||R(o.from,a.from)||R(o.to,a.to)||R(o.kind,a.kind)),n}var su,Uh,Wh,Bh,Hh,ii=O(()=>{"use strict";S();Un();K();su=new Set(["contains","doc-link","import","call","use","mention"]),Uh=new Set(["error","warn"]),Wh=new Set(["cycles","orphans","literals"]),Bh=["competing","bypassed"],Hh=new Set(["index","main","app","application","cli","server","entry","entrypoint","setup","conftest","__init__","__main__","mod","lib"])});function Pr(e){let t=Rn(e),n=Ds(e),r=[],s=o=>o.exported&&!qh.has(o.kind)&&!Ot(o.file)&&!Vh.test(o.file);for(let o of e.files)for(let a of o.symbols){if(!s(a))continue;let l=t.get(a.name)??t.get(`${a.name}@${a.file}`);if(!!l&&l.def.file===a.file&&l.callers.length>0)continue;let d=(n.get(a.name)?.size??0)>0;r.push({name:a.name,file:a.file,line:a.line,kind:a.kind,tier:d?"uncalled":"unreferenced"})}return r.sort((o,a)=>R(o.tier,a.tier)||R(o.file,a.file)||o.line-a.line)}var qh,Vh,oi=O(()=>{"use strict";S();dt();kn();K();qh=new Set(["reexport","reexport-all","default"]),Vh=/(^|\/)(index|main|cli|app|server|engine)\.[a-z]+$/});function $r(e,t={}){let n=t.maxEdges??80,r=[...e.moduleEdges].filter(l=>!l.dangling);t.module&&(r=r.filter(l=>l.from===t.module||l.to===t.module)),r.sort((l,c)=>c.weight-l.weight||R(l.from,c.from)||R(l.to,c.to));let s=Math.max(0,r.length-n);r=r.slice(0,n);let o=new Set;for(let l of r)o.add(l.from),o.add(l.to);t.module&&o.add(t.module);let a=["graph LR"];for(let l of[...e.modules].sort((c,d)=>R(c.slug,d.slug)))o.has(l.slug)&&a.push(` ${Ra(l.slug)}["${l.slug}${l.tier===0?" (core)":""}"]`);for(let l of r){let c=l.kind==="import"?"":`|${l.kind}|`;a.push(` ${Ra(l.from)} -->${c} ${Ra(l.to)}`)}return s&&a.push(` %% ${s} lighter edges omitted (maxEdges=${n})`),a.join(` +`});async function Ma(e,t){let n=t.timeoutMs??ny,r=t.startupTimeoutMs??ry,s=va(),o=new Map,a=new Set,l=1,c,d=h=>{c=h;for(let[,S]of o)clearTimeout(S.timer),S.reject(h);o.clear()};e.onData(h=>{for(let S of s.push(h)){if(typeof S.id!="number")continue;let _=o.get(S.id);_&&(o.delete(S.id),clearTimeout(_.timer),S.error?_.reject(new Error(`${S.error.message} (code ${S.error.code})`)):_.resolve(S.result))}}),e.onExit(h=>d(new Error(`language server exited (code ${h??"unknown"})`)));let f=(h,S)=>{c||e.write(ci({jsonrpc:"2.0",method:h,params:S}))},u=(h,S,_=n)=>{if(c)return Promise.reject(c);let E=l++;return new Promise((b,x)=>{let v=setTimeout(()=>{o.delete(E),x(new ui(h,_))},_);v.unref?.(),o.set(E,{resolve:b,reject:x,timer:v}),e.write(ci({jsonrpc:"2.0",id:E,method:h,params:S}))})},m=await u("initialize",{processId:null,rootUri:dn(t.root,""),workspaceFolders:[{uri:dn(t.root,""),name:"repo"}],capabilities:{textDocument:{references:{dynamicRegistration:!1},definition:{dynamicRegistration:!1,linkSupport:!0},implementation:{dynamicRegistration:!1,linkSupport:!0}}},...t.initializationOptions!==void 0?{initializationOptions:t.initializationOptions}:{}},r);f("initialized",{});let p=h=>{let S=m?.capabilities?.[h];return S===!0||typeof S=="object"&&S!==null},g={references:p("referencesProvider"),definition:p("definitionProvider"),implementation:p("implementationProvider"),typeHierarchy:p("typeHierarchyProvider")},y=(h,S,_)=>({textDocument:{uri:dn(t.root,h)},position:{line:Math.max(0,S-1),character:_}});return{capabilities:g,didOpen(h,S,_){a.has(h)||(a.add(h),f("textDocument/didOpen",{textDocument:{uri:dn(t.root,h),languageId:_,version:1,text:S}}))},async references(h,S,_){if(!g.references)return[];let E=await u("textDocument/references",{...y(h,S,_),context:{includeDeclaration:!0}});return di(t.root,E)},async definition(h,S,_){return g.definition?di(t.root,await u("textDocument/definition",y(h,S,_))):[]},async shutdown(){try{for(let h of a)f("textDocument/didClose",{textDocument:{uri:dn(t.root,h)}});a.clear(),await u("shutdown",null,Math.min(n,2e3)),f("exit",void 0)}catch{}finally{d(new Error("session closed")),e.close()}}}}var ui,ny,ry,Ca=F(()=>{"use strict";k();Ra();ui=class extends Error{constructor(t,n){super(`${t} exceeded ${n}ms`),this.name="LspTimeout"}},ny=5e3,ry=15e3});function fi(e){let t=R.env.CODEINDEX_LSP_CONFIG;if(t!==void 0){let s=t.trim();return!s||s==="0"||s.toLowerCase()==="off"?{path:void 0,source:"none"}:{path:Ne(s),source:"env"}}let n=I(e,du,cu);if(H(n))return{path:n,source:"repo"};let r=I(R.cwd(),du,cu);return r!==n&&H(r)?{path:r,source:"cwd"}:{path:void 0,source:"none"}}function uu(e){if(!e||typeof e!="object")throw new Error("lsp.json must be a JSON object");let t=e;if(t.version!==1)throw new Error(`lsp.json: unsupported version ${JSON.stringify(t.version)} (expected 1)`);if(!Array.isArray(t.servers))throw new Error("lsp.json: `servers` must be an array");let n=new Set;return{version:1,servers:t.servers.map((s,o)=>{if(!s||typeof s!="object")throw new Error(`lsp.json: servers[${o}] must be an object`);let a=s,l=typeof a.id=="string"&&a.id.trim()?a.id.trim():void 0;if(!l)throw new Error(`lsp.json: servers[${o}].id must be a non-empty string`);if(n.has(l))throw new Error(`lsp.json: duplicate server id ${JSON.stringify(l)}`);if(n.add(l),typeof a.command!="string"||!a.command.trim())throw new Error(`lsp.json: servers[${o}].command must be a non-empty string`);if(!Array.isArray(a.languages)||!a.languages.length||a.languages.some(c=>typeof c!="string"))throw new Error(`lsp.json: servers[${o}].languages must be a non-empty array of strings`);if(a.args!==void 0&&(!Array.isArray(a.args)||a.args.some(c=>typeof c!="string")))throw new Error(`lsp.json: servers[${o}].args must be an array of strings`);return{id:l,languages:a.languages,...typeof a.languageId=="string"?{languageId:a.languageId}:{},command:a.command,...Array.isArray(a.args)?{args:a.args}:{},...a.env&&typeof a.env=="object"?{env:a.env}:{},...a.initializationOptions!==void 0?{initializationOptions:a.initializationOptions}:{},...typeof a.timeoutMs=="number"?{timeoutMs:a.timeoutMs}:{},...typeof a.startupTimeoutMs=="number"?{startupTimeoutMs:a.startupTimeoutMs}:{}}})}}function mi(e){let{path:t}=fi(e);if(!t||!H(t))return;let n;try{n=JSON.parse(te(t,"utf8"))}catch(r){throw new Error(`${t}: ${r instanceof Error?r.message:String(r)}`)}return uu(n)}function Aa(e,t){return e.servers.find(n=>n.languages.includes(t))}function fu(e){return pu("CODEINDEX_LSP_TIMEOUT_MS")??e.timeoutMs??sy}function mu(e){return pu("CODEINDEX_LSP_STARTUP_TIMEOUT_MS")??e.startupTimeoutMs??iy}function pu(e){let t=R.env[e];if(t===void 0)return;let n=Number(t);return Number.isFinite(n)&&n>0?n:void 0}var cu,du,sy,iy,Ta=F(()=>{"use strict";k();xe();oe();cu="lsp.json",du=".codeindex";sy=5e3,iy=15e3});function Bt(e,t){return{server:e,ok:!1,reason:t,refs:[],agreement:{both:[],lspOnly:[],staticOnly:[]}}}function _u(e,t,n,r){try{let o=te(I(e,t),"utf8").split(/\r?\n/)[n-1]?.indexOf(r)??-1;return o<0?0:o}catch{return 0}}function Ia(e,t){let n=new Set(e.map(l=>l.file)),r=new Set([...t.callSites.map(l=>l.file),...t.referencingFiles,...t.defs.map(l=>l.file)]),s=[],o=[],a=[];for(let l of n)(r.has(l)?s:o).push(l);for(let l of r)n.has(l)||a.push(l);return{both:s.sort(M),lspOnly:o.sort(M),staticOnly:a.sort(M)}}async function hu(e,t,n,r,s,o){if(!r.capabilities.references)return{...n,lsp:Bt(s,"server does not provide textDocument/references")};if(!n.defs.length)return{...n,lsp:Bt(s,`no declaration of ${t} to anchor a request on`)};let a=new Set,l=[];try{for(let c of n.defs){let d=oy(e.root,c.file);if(!d)continue;r.didOpen(c.file,d,o);let f=_u(e.root,c.file,c.line,t);for(let u of await r.references(c.file,c.line,f)){let m=`${u.file}:${u.line}:${u.character??""}`;a.has(m)||(a.add(m),l.push(u))}}}catch(c){return{...n,lsp:{server:s,ok:!1,reason:c instanceof Error?c.message:String(c),refs:l.sort(gu),agreement:Ia(l,n)}}}return l.sort(gu),{...n,lsp:{server:s,ok:!0,refs:l,agreement:Ia(l,n)}}}function gu(e,t){return M(e.file,t.file)||e.line-t.line||(e.character??0)-(t.character??0)}function oy(e,t){try{return te(I(e,t),"utf8")}catch{return""}}var Na=F(()=>{"use strict";k();xe();oe();Y()});function Oa(e,t){let n;try{n=ul(e.command,e.args??[],{cwd:t,stdio:["pipe","pipe","pipe"],...e.env?{env:{...R.env,...e.env}}:{}})}catch{return}let r=!1,s=[],o=[],a=l=>{if(!r){r=!0;for(let c of o)c(l)}};return n.on("error",()=>a(null)),n.on("close",l=>a(l)),n.stdout?.on("data",l=>{for(let c of s)c(l)}),n.stderr?.on("data",()=>{}),{write(l){if(!r)try{n.stdin?.write(l)}catch{a(null)}},onData(l){s.push(l)},onExit(l){r?l(null):o.push(l)},close(){try{n.stdin?.end()}catch{}let l=setTimeout(()=>{try{n.kill("SIGKILL")}catch{}},2e3);l.unref?.(),n.on("close",()=>clearTimeout(l))}}}var Fa=F(()=>{"use strict";k();Fi()});async function Pr(e,t,n=!1){let{path:r,source:s}=fi(t),o=mi(t);if(!o)return{lspVersion:1,mode:"none",configPath:r??null,source:s,servers:[],unmappedLanguages:[]};let a=new Map;for(let f of e.files)a.set(f.lang,(a.get(f.lang)??0)+1);let l=[];for(let f of o.servers){let u={id:f.id,languages:f.languages,command:f.command,onPath:at(f.command),filesInRepo:f.languages.reduce((m,p)=>m+(a.get(p)??0),0)};if(n){let m=await yu(f,e.root);m.ok?(u.reachable=!0,u.capabilities=m.session.capabilities,await m.session.shutdown()):(u.reachable=!1,u.error=m.reason)}l.push(u)}let c=new Set(o.servers.flatMap(f=>f.languages)),d=[...a.keys()].filter(f=>!c.has(f)&&f!=="other").sort();return{lspVersion:1,mode:"configured",configPath:r??null,source:s,servers:l,unmappedLanguages:d}}async function yu(e,t){if(!at(e.command))return{ok:!1,reason:`${e.command} is not on PATH`};let n=Oa(e,t);if(!n)return{ok:!1,reason:`could not start ${e.command}`};try{return{ok:!0,session:await Ma(n,{root:t,timeoutMs:fu(e),startupTimeoutMs:mu(e),...e.initializationOptions!==void 0?{initializationOptions:e.initializationOptions}:{}})}}catch(r){return n.close(),{ok:!1,reason:r instanceof Error?r.message:String(r)}}}async function Pa(e,t,n,r){let s;try{s=mi(t)}catch(c){return{...r,lsp:Bt("(config)",c instanceof Error?c.message:String(c))}}if(!s)return r;let o=r.defs[0]?.lang;if(!o)return{...r,lsp:Bt("(none)",`no declaration of ${n} to anchor a request on`)};let a=Aa(s,o);if(!a)return{...r,lsp:Bt("(none)",`no server configured for ${o}`)};let l=await yu(a,e.root);if(!l.ok)return{...r,lsp:Bt(a.id,l.reason)};try{return await hu(e,n,r,l.session,a.id,a.languageId??a.languages[0])}finally{await l.session.shutdown()}}var pi=F(()=>{"use strict";k();Ce();Ca();Ta();Na();Fa()});function uy(e){let n=e.split("/").pop().split(".")[0].toLowerCase();return dy.has(n)}function wu(e){return Array.isArray(e)?e:[e]}function $r(e){let t=Array.isArray(e)?e:e?.rules;if(!Array.isArray(t))throw new Error("rules config must be an array (or an object with a `rules` array)");return t.map((n,r)=>{let s=`rules[${r}]`;if(typeof n!="object"||n===null)throw new Error(`${s}: must be an object`);let o=n;if(typeof o.name!="string"||!o.name)throw new Error(`${s}: \`name\` (non-empty string) is required`);if(o.severity!==void 0&&!ay.has(o.severity))throw new Error(`${s} (${o.name}): \`severity\` must be "error" or "warn"`);if(o.comment!==void 0&&typeof o.comment!="string")throw new Error(`${s} (${o.name}): \`comment\` must be a string`);if(o.builtin!==void 0){if(!ly.has(o.builtin))throw new Error(`${s} (${o.name}): \`builtin\` must be "cycles", "orphans" or "literals"`);return{name:o.name,builtin:o.builtin,severity:o.severity,comment:o.comment,...o.tiers!==void 0?{tiers:o.tiers}:{}}}let a=d=>{let f=o[d];if(!(typeof f=="string"?f.length>0:Array.isArray(f)&&f.length>0&&f.every(m=>typeof m=="string"&&m)))throw new Error(`${s} (${o.name}): \`${d}\` must be a glob or a non-empty array of globs`);return f},l=a("from"),c=a("to");if(o.kind!==void 0&&!(Array.isArray(o.kind)&&o.kind.every(f=>bu.has(f))))throw new Error(`${s} (${o.name}): \`kind\` must be an array of edge kinds (${[...bu].join(", ")})`);return{name:o.name,from:l,to:c,kind:o.kind,severity:o.severity,comment:o.comment}})}function fy(e){let t=new Map;for(let f of e.moduleEdges){if(f.kind!=="import")continue;let u=t.get(f.from);u||t.set(f.from,u=[]),u.push(f.to)}for(let f of t.values())f.sort(M);let n=[...t.keys()].sort(M),r=new Map,s=new Map,o=new Set,a=[],l=[],c=0;for(let f of n){if(r.has(f))continue;let u=[{node:f,next:0}];for(;u.length;){let m=u[u.length-1],p=m.node;m.next===0&&(r.set(p,c),s.set(p,c),c++,a.push(p),o.add(p));let g=t.get(p)??[];if(m.next1&&l.push(h)}u.pop();let y=u[u.length-1];y&&s.set(y.node,Math.min(s.get(y.node),s.get(p)))}}}let d=[];for(let f of l){let u=new Set(f),m=[...f].sort(M)[0],p=new Map([[m,null]]),g=[m];for(let S=0;S(t.get(S)??[]).includes(m)&&S!==m)??m,h=[];for(let S=y;S!==null;S=p.get(S)??null)h.unshift(S);h.push(m),d.push({start:m,path:h})}return d}function Lr(e,t){let n=[],r=(o,a)=>{n.push({rule:o.name,...a,severity:o.severity??"error",...o.comment!==void 0?{comment:o.comment}:{}})},s=new Set(e.files.map(o=>o.rel));for(let o of t){if("builtin"in o){if(o.builtin==="cycles")for(let d of fy(e))r(o,{from:d.start,to:d.path.join(" -> "),kind:"cycle"});else if(o.builtin==="literals"){let d=new Set(o.tiers?.length?o.tiers:cy);for(let f of e.literalDuplications??[]){if(!d.has(f.tier))continue;let u=f.holders[0]??f.literals[0];r(o,{from:`${u.file}:${u.line}`,to:`${f.tier} ${JSON.stringify(f.value)} (${f.count} sites, ${f.files} files)`,kind:"literal"})}}else for(let d of e.files)d.fileKind!=="code"||d.degIn!==0||d.degOut!==0||uy(d.rel)||r(o,{from:d.rel,to:d.rel,kind:"orphan"});continue}let a=yt(wu(o.from)),l=yt(wu(o.to));if(!a||!l)continue;let c=o.kind?.length?new Set(o.kind):null;for(let d of e.fileEdges)d.dangling||!s.has(d.to)||c&&!c.has(d.kind)||!a(d.from)||!l(d.to)||r(o,{from:d.from,to:d.to,kind:d.kind})}return n.sort((o,a)=>M(o.rule,a.rule)||M(o.from,a.from)||M(o.to,a.to)||M(o.kind,a.kind)),n}var bu,ay,ly,cy,dy,gi=F(()=>{"use strict";k();Hn();Y();bu=new Set(["contains","doc-link","import","call","use","mention"]),ay=new Set(["error","warn"]),ly=new Set(["cycles","orphans","literals"]),cy=["competing","bypassed"],dy=new Set(["index","main","app","application","cli","server","entry","entrypoint","setup","conftest","__init__","__main__","mod","lib"])});function Dr(e){let t=Cn(e),n=Vs(e),r=[],s=o=>o.exported&&!my.has(o.kind)&&!$t(o.file)&&!py.test(o.file);for(let o of e.files)for(let a of o.symbols){if(!s(a))continue;let l=t.get(a.name)??t.get(`${a.name}@${a.file}`);if(!!l&&l.def.file===a.file&&l.callers.length>0)continue;let d=(n.get(a.name)?.size??0)>0;r.push({name:a.name,file:a.file,line:a.line,kind:a.kind,tier:d?"uncalled":"unreferenced"})}return r.sort((o,a)=>M(o.tier,a.tier)||M(o.file,a.file)||o.line-a.line)}var my,py,_i=F(()=>{"use strict";k();mt();vn();Y();my=new Set(["reexport","reexport-all","default"]),py=/(^|\/)(index|main|cli|app|server|engine)\.[a-z]+$/});function jr(e,t={}){let n=t.maxEdges??80,r=[...e.moduleEdges].filter(l=>!l.dangling);t.module&&(r=r.filter(l=>l.from===t.module||l.to===t.module)),r.sort((l,c)=>c.weight-l.weight||M(l.from,c.from)||M(l.to,c.to));let s=Math.max(0,r.length-n);r=r.slice(0,n);let o=new Set;for(let l of r)o.add(l.from),o.add(l.to);t.module&&o.add(t.module);let a=["graph LR"];for(let l of[...e.modules].sort((c,d)=>M(c.slug,d.slug)))o.has(l.slug)&&a.push(` ${$a(l.slug)}["${l.slug}${l.tier===0?" (core)":""}"]`);for(let l of r){let c=l.kind==="import"?"":`|${l.kind}|`;a.push(` ${$a(l.from)} -->${c} ${$a(l.to)}`)}return s&&a.push(` %% ${s} lighter edges omitted (maxEdges=${n})`),a.join(` `)+` -`}function Ma(e){return"m_"+e.replace(/[^A-Za-z0-9_]/g,"_")}function Zh(e,t={}){let n=t.maxModules??Kh,r=t.maxEdges??Xh,o=e.modules.slice().sort((d,u)=>ou(u)-ou(d)||R(d.slug,u.slug)).slice(0,n),a=new Set(o.map(d=>d.slug)),l=e.moduleEdges.filter(d=>a.has(d.from)&&a.has(d.to)).sort((d,u)=>u.weight-d.weight||R(d.from,u.from)||R(d.to,u.to)).slice(0,r),c=[];c.push(`%% ${t.title??"module graph"} \u2014 ${o.length} of ${e.modules.length} modules, ${l.length} of ${e.moduleEdges.length} edges`),(o.lengthf.tier===d);if(u.length){c.push(` subgraph ${Jh[d]}`);for(let f of u)c.push(` ${Ma(f.slug)}["${f.path.replace(/"/g,"'")}"]`);c.push(" end")}}for(let d of l){let u=d.weight>1?`|${d.weight}| `:"";c.push(` ${Ma(d.from)} -->${u?" "+u:" "}${Ma(d.to)}`)}return{content:"```mermaid\n"+c.join(` -`)+"\n```\n",shownModules:o.length,totalModules:e.modules.length,shownEdges:l.length,totalEdges:e.moduleEdges.length}}var Ra,Jh,Kh,Xh,ou,ai=O(()=>{"use strict";S();K();Ra=e=>e.replace(/[^\w]/g,"_");Jh={0:"Foundations",1:"Features",2:"Tail"},Kh=40,Xh=80,ou=e=>e.degIn+e.degOut});function fu(){throw new Error("readline is not available in the browser build (the MCP stdio transport is Node-only)")}var mu=O(()=>{S()});function li(e,t){let n=e.properties??{};for(let[r,s]of Object.entries(t)){if(s==null)continue;let o=n[r];if(!o?.type)continue;let a=Array.isArray(s)?"array":typeof s;if(o.type==="number"){if(a==="number"||a==="string"&&Number.isFinite(Number(s))&&s.trim()!=="")continue;return`\`${r}\` must be a number, got ${a==="string"?JSON.stringify(s):a}`}if(o.type==="array"){if(a!=="array")return`\`${r}\` must be an array of strings, got ${a}`;if(o.items?.type==="string"&&!s.every(l=>typeof l=="string"))return`\`${r}\` must be an array of strings`;continue}if(a!==o.type)return`\`${r}\` must be a ${o.type}, got ${a}`}}function ci(e,t,n){if(t||!n)return;let r;try{r=JSON.parse(e)}catch{return}if(!(r===null||typeof r!="object"||Array.isArray(r)))return r}function di(e){return typeof e=="string"&&Et.includes(e)?e:ry}function fi(e,t,n,r){let s=T.byteLength(e,"utf8");if(s<=r)return e;let o=Na[t]?I(n,yt,Na[t]):void 0;return JSON.stringify({truncated:!0,tool:t,bytes:s,maxBytes:r,reason:"This response exceeds the configured limit and was withheld rather than sent as an unusable partial payload.",narrower:sy[t]??"narrow the request with `scope`, `include`/`exclude`, or a `limit`",...o&&z(o)?{artifact:o,artifactNote:"The full result is already on disk here \u2014 read it directly if you need all of it."}:o?{artifactNote:`Run \`codeindex index --repo ${n} --out ${I(n,yt)}\` to get this as a file.`}:{}},null,2)+` -`}function mi(e,t){let n=Na[t];if(!n)return;let r;try{r=JSON.parse(e)}catch{return}if(!(r.truncated!==!0||typeof r.artifact!="string"))return{type:"resource_link",uri:Wn(r.artifact).href,name:n,description:`The full ${t} result this call was too large to inline.`,mimeType:"application/json"}}var Et,ry,pu,Lr,ui,sy,Na,pi=O(()=>{"use strict";S();we();ie();ms();tr();Et=["2024-11-05","2025-03-26","2025-06-18","2025-11-25"],ry=Et[Et.length-1],pu="2025-03-26",Lr="2025-06-18";ui=1e6,sy={graph:"pass `scope` to a subdirectory, or use repo_map / mermaid for an overview",symbols:"pass `name` to look up one symbol, or use find_symbol / symbols_overview",callers:"pass `name` to look up one symbol's call sites",dead_code:"pass `scope` to a subdirectory",find_references:"the symbol is referenced very widely \u2014 narrow with `scope` on a graph query",check_rules:"narrow the rule set, or pass `scope` to a subdirectory"},Na={graph:"graph.json",symbols:"symbols.json"}});function Oa(e){let t=Ur[e];if(t)return{readOnlyHint:!t.write,...t.write?{destructiveHint:t.destructive===!0,idempotentHint:t.idempotent===!0}:{},openWorldHint:t.openWorld===!0}}function Wr(){return["all",...Object.keys(gi).sort()]}function Br(e){let t=e.split(",").map(r=>r.trim()).filter(Boolean),n=new Set;for(let r of t){if(r==="all")return new Set(jr.map(o=>o.name));let s=gi[r];if(!s)throw new Error(`unknown tool profile "${r}" \u2014 one of: ${Wr().join(", ")}`);for(let o of s)n.add(o)}return n}function Hr(e,t=Et[0],n){let r=t>=pu,s=t>=Lr,o=n?Br(n):void 0,a=o?jr.filter(l=>o.has(l.name)):jr;return!e&&!r&&!s?a:a.map(l=>({...l,...s&&Ur[l.name]?{title:Ur[l.name].title}:{},...s&&un[l.name]?{outputSchema:un[l.name]}:{},...r?{annotations:Oa(l.name)}:{},inputSchema:e?{...l.inputSchema,properties:{...l.inputSchema.properties,repo:{type:"string",description:`Absolute path to the repository root (optional \u2014 defaults to ${e})`}},required:l.inputSchema.required.filter(c=>c!=="repo")}:l.inputSchema}))}var Q,dn,jr,Nn,he,un,Ur,gi,_i=O(()=>{"use strict";S();pi();Q={repo:{type:"string",description:"Absolute path to the repository root"}},dn={scope:{type:"string",description:"Restrict to one directory (repo-relative)"},include:{type:"array",items:{type:"string"},description:"Include globs"},exclude:{type:"array",items:{type:"string"},description:"Exclude globs"}},jr=[{name:"scan_summary",description:"Deterministically scan a repository: file count, per-language file histogram, HEAD commit, and whether the walk was capped. Fast first look at any codebase.",inputSchema:{type:"object",properties:{...Q,...dn},required:["repo"]}},{name:"graph",description:"Build the full typed cross-file link-graph (import/call/use/doc-link/mention edges, module grouping, PageRank centrality, Louvain communities, tests-map). Returns graph.json. Large on big repos \u2014 prefer scan_summary/symbols/callers for targeted questions.",inputSchema:{type:"object",properties:{...Q,...dn},required:["repo"]}},{name:"symbols",description:"Where is a symbol defined and which files reference it? Returns the definition sites (file, line, kind, exported) and referencing files. Omit `name` for the full symbol index.",inputSchema:{type:"object",properties:{...Q,name:{type:"string",description:"Symbol name to look up"}},required:["repo"]}},{name:"callers",description:"Who calls a function? Per-symbol caller index: each defined symbol with the exact (file, line) call sites that bind to it. Omit `name` for the full index.",inputSchema:{type:"object",properties:{...Q,name:{type:"string",description:"Symbol name to look up"},recall:{type:"boolean",description:"Recall-oriented binding: relax the JS/TS import gate to unique repo-wide names, labelling each site corroborated|unique-name (default false = precision)"}},required:["repo"]}},{name:"workspaces",description:"Detect monorepo packages (npm/pnpm/yarn/lerna/nx/cargo/go.work/maven) with the workspace dependency graph, one cycle if present, and a topological build order.",inputSchema:{type:"object",properties:{...Q},required:["repo"]}},{name:"churn",description:"Per-file git commit counts (whole history, or since a ref) \u2014 the churn half of hotspot analysis.",inputSchema:{type:"object",properties:{...Q,since:{type:"string",description:"Only count commits after this ref"}},required:["repo"]}},{name:"symbols_overview",description:"All symbols declared in ONE file (name, kind, line span, exported, parent), in declaration order \u2014 the fastest way to understand a file without reading it.",inputSchema:{type:"object",properties:{...Q,file:{type:"string",description:"Repo-relative file path"}},required:["repo","file"]}},{name:"find_symbol",description:`Find symbol declarations by name or name path ('Class/method' matches a method inside Class). Each match carries its COMPLETE SIGNATURE (parameters and return type) by default, because "what shape is it" is the question that follows "where is it" almost every time and one round trip beats two. Options: substring matching, includeBody for the declaration's source, concise to drop everything but name/kind/file/line when you genuinely only want a location. Exact-name matches rank first.`,inputSchema:{type:"object",properties:{...Q,namePath:{type:"string",description:"Symbol name or Parent/child path"},substring:{type:"boolean"},includeBody:{type:"boolean"},concise:{type:"boolean",description:"Return only name/kind/file/line \u2014 drop the signature, line span, visibility and language. Roughly 2.5x smaller; use it when you are resolving a path and nothing more (default false)."},maxResults:{type:"number",description:"Cap matches (default 50)"}},required:["repo","namePath"]}},{name:"find_references",description:"Who references a symbol? Three labeled tiers: defs (declarations), callSites (line-precise, import-corroborated call bindings), referencingFiles (file-level identifier/doc mentions \u2014 may include homonyms). Confidence decreases across tiers; the labels let you decide what to trust.",inputSchema:{type:"object",properties:{...Q,name:{type:"string",description:"Symbol name"},lsp:{type:"boolean",description:"Also ask a configured language server (see lsp_status) and append an `lsp` block: its references plus an `agreement` matrix (both / lspOnly / staticOnly). The three static tiers are unchanged either way. `staticOnly` is where the homonyms are. No config, no binary, a crash or a timeout all degrade to the static answer with a stated reason (default false)."}},required:["repo","name"]}},{name:"lsp_status",description:"Is the optional LSP tier configured, and would it answer? Reports the config path and its source, each server with whether its command is on PATH and how many files in this repo it claims, and the languages no server covers. Opt-in by asset: the tier is active only when /.codeindex/lsp.json exists (or CODEINDEX_LSP_CONFIG points at one). `probe: true` additionally starts each server to read the capabilities it really advertises. The tier never touches graph.json/symbols.json \u2014 it annotates query answers only.",inputSchema:{type:"object",properties:{...Q,probe:{type:"boolean",description:"Start each server and read its real capabilities (default false: no spawn)"}},required:["repo"]}},{name:"onboard",description:"One call that says what this repository IS: its own tagline, size and language mix, monorepo layout when there is one, a token-budgeted map of the highest-PageRank files with their key signatures, and where git says work concentrates. Composes scan_summary + workspaces + repo_map + hotspots so the first four round trips of a session become one, and persists the result as the `onboarding` memory (read_memory) so the next session does not repeat them. Set remember:false to skip the write.",inputSchema:{type:"object",properties:{...Q,budgetTokens:{type:"number",description:"Token budget for the key-files section (default 900)"},remember:{type:"boolean",description:"Persist the brief as the `onboarding` memory (default true)"}},required:["repo"]}},{name:"repo_map",description:"Token-budgeted map of the repository: the highest-PageRank files with their key exported signatures, deterministically rendered to fit `budgetTokens` (default 1024). The densest single read to understand an unfamiliar codebase.",inputSchema:{type:"object",properties:{...Q,budgetTokens:{type:"number",description:"Approximate token budget (default 1024)"}},required:["repo"]}},{name:"hotspots",description:"Where does work concentrate? Files ranked by git churn \xD7 size (commits \xD7 log2 lines). High-scoring files are where changes and defects cluster.",inputSchema:{type:"object",properties:{...Q,since:{type:"string",description:"Only count commits after this ref"}},required:["repo"]}},{name:"coupling",description:"Change coupling: pairs of files that repeatedly change in the same commits \u2014 hidden dependencies no import shows. strength 1.0 = every change to one touched the other.",inputSchema:{type:"object",properties:{...Q,since:{type:"string",description:"Only mine commits after this ref"}},required:["repo"]}},{name:"replace_symbol_body",description:"WRITE: replace a symbol's whole declaration with `body` (verbatim, supply full indentation). The symbol is resolved by name path ('Class/method'); ambiguity errors list the candidates \u2014 qualify with `file`. Line spans come from the AST index.",inputSchema:{type:"object",properties:{...Q,namePath:{type:"string"},body:{type:"string"},file:{type:"string",description:"Disambiguate: repo-relative file containing the symbol"}},required:["repo","namePath","body"]}},{name:"insert_after_symbol",description:"WRITE: insert `body` after a symbol's declaration (blank-line separation preserved for definition-like kinds). Resolved like replace_symbol_body.",inputSchema:{type:"object",properties:{...Q,namePath:{type:"string"},body:{type:"string"},file:{type:"string"}},required:["repo","namePath","body"]}},{name:"insert_before_symbol",description:"WRITE: insert `body` before a symbol's declaration (blank-line separation preserved). Resolved like replace_symbol_body.",inputSchema:{type:"object",properties:{...Q,namePath:{type:"string"},body:{type:"string"},file:{type:"string"}},required:["repo","namePath","body"]}},{name:"write_memory",description:"Persist a named markdown note under /.codeindex/memories/ (names may use topic/name form). Write small, focused notes: project map, build commands, conventions.",inputSchema:{type:"object",properties:{...Q,name:{type:"string"},content:{type:"string"}},required:["repo","name","content"]}},{name:"read_memory",description:"Read one persisted memory by name.",inputSchema:{type:"object",properties:{...Q,name:{type:"string"}},required:["repo","name"]}},{name:"list_memories",description:"List persisted memory names \u2014 load this first, then read individual memories on relevance.",inputSchema:{type:"object",properties:{...Q},required:["repo"]}},{name:"delete_memory",description:"Delete one persisted memory by name.",inputSchema:{type:"object",properties:{...Q,name:{type:"string"}},required:["repo","name"]}},{name:"dead_code",description:"Dead-code candidates in two labeled tiers: 'unreferenced' (no call site binds AND nothing references the name) and 'uncalled' (referenced somewhere \u2014 re-export, type position \u2014 but never called). Exported symbols only; test files and entrypoint-looking files excluded as roots. On a large repo this list runs to thousands of entries \u2014 pass `limit`, or `scope` to one subdirectory.",inputSchema:{type:"object",properties:{...Q,...dn,limit:{type:"number",description:"Cap entries (default: all)"}},required:["repo"]}},{name:"duplicated_literals",description:"Values with no single source of truth: one literal written out across many files. Three labeled tiers \u2014 'competing' (two or more exported constants hold the same value), 'bypassed' (a constant holds it and other files rewrite it anyway), 'uncentralized' (nothing holds it). Path-like values are also grouped into namespace families, so a whole route space reports once instead of once per route. Covers config files (JSON/YAML/TOML) as well as code, which is where the dangerous cases live: a threshold declared in TypeScript and again in a rules JSON is checked by no compiler. Use it to answer 'what breaks if this value changes' and 'is there already a helper for this'.",inputSchema:{type:"object",properties:{...Q,...dn,minFiles:{type:"number",description:"Distinct files a value must span (default 2)"},minCount:{type:"number",description:"Total occurrences required (default 3)"},includeTests:{type:"boolean",description:"Count test files too (default false)"},limit:{type:"number",description:"Cap duplications (default: all)"}},required:["repo"]}},{name:"complexity",description:"Cyclomatic-complexity estimates (branch-token counting over AST line spans), most-complex first. Pass `file` for one file's symbols, omit for the repo-wide top. Combine with hotspots: the `risk` field of this tool's sibling ranks complexity \xD7 churn.",inputSchema:{type:"object",properties:{...Q,file:{type:"string"},risk:{type:"boolean",description:"Return complexity \xD7 git-churn risk ranking instead"}},required:["repo"]}},{name:"mermaid",description:"Mermaid diagram of the module graph (renders inline in Claude/GitHub \u2014 no graph database). Optionally scoped to one module's neighborhood.",inputSchema:{type:"object",properties:{...Q,module:{type:"string",description:"Module slug to focus on"}},required:["repo"]}},{name:"grep",description:"Search file contents (ripgrep when available, deterministic JS fallback otherwise). Returns sorted (file, line, text) hits.",inputSchema:{type:"object",properties:{...Q,pattern:{type:"string",description:"Regular expression to search for"},scope:{type:"string",description:"Restrict to one directory (repo-relative)"},globs:{type:"array",items:{type:"string"},description:"Restrict to matching paths"},ignoreCase:{type:"boolean"},maxHits:{type:"number"}},required:["repo","pattern"]}},{name:"search",description:'Natural-language-ish lexical search: BM25F ranking over SIX weighted fields \u2014 symbol names (camelCase/snake_case subtokens), path segments, markdown headings, the file summary, per-symbol DOC COMMENTS, and the prose body (comment + short-literal words). The last two are why "where is rate limiting handled" works: the phrase lives in a comment, not in a name. Results carry `matchedFields`, a `line` anchor and `symbolHits` (name/kind/line). NOT embeddings by default \u2014 deterministic, diacritic-folded, zero API keys. Answers "where is auth handled?"-style queries with ranked files, matched terms and top symbols. Query terms with zero document frequency get a deterministic trigram-fuzzy fallback (typo-tolerant) unless `fuzzy: false`. Set `semantic: true` to RRF-fuse an embedding tier (HTTP endpoint, else a local static model) with lexical \u2014 the response then wraps the ranked list as `{ results, tier, degradedReason? }`, `tier` being "endpoint"/"static" when fusion happened or "lexical" (with `degradedReason`) when it did not (see embed_status). Without `semantic`, the response is the bare ranked array, unchanged.',inputSchema:{type:"object",properties:{...Q,...dn,query:{type:"string",description:"Natural-language or identifier query"},limit:{type:"number",description:"Max results (default 20)"},fuzzy:{type:"boolean",description:'Fallback for query terms with zero document frequency: a morphological stem match first ("caching" finds "cache"), then trigram similarity for typos (default true)'},rank:{type:"string",description:`Structural prior: "graph" multiplies the lexical score by the file's PageRank over the resolved import graph; "lexical" (default) scores on text alone. Unproven on the judged corpus \u2014 see SearchOptions.rank.`},exact:{type:"boolean",description:"Drop results that carry no verbatim query-term match \u2014 the ones the stem/trigram bridge produced (default false)."},explain:{type:"boolean",description:"Wrap the response as `{ results, explain }` with the query verdict (default false = bare array). See explain_search."},semantic:{type:"boolean",description:'RRF-fuse an embedding tier with lexical (default false). Precedence: the HTTP endpoint (CODEINDEX_EMBED_ENDPOINT) if set, else a local static model. The response reports the effective tier as a top-level `tier` field ("endpoint"/"static" on success, "lexical" plus `degradedReason` when neither is available/reachable) instead of degrading silently \u2014 see embed_status.'}},required:["repo","query"]}},{name:"explain_search",description:'Search, and say whether the query actually found anything. Returns `{ results, explain }` where explain.verdict is "match" (a verbatim term matched), "weak" (results exist but rest on a near match, or the identifier you asked for has document frequency 0) or "none". Use this instead of `search` whenever an empty-feeling or surprising result matters: a query for an identifier that is NOT in the indexed tree still returns confident-looking rows built from its subtokens \u2014 searching "nullGipStep7" in a repo that only has "nullGipStep2" ranks files matching "null" and "gip" \u2014 and only the verdict distinguishes that from a real hit. Also names the terms dropped as stopwords, the terms that exist nowhere, and what each near match bridged to.',inputSchema:{type:"object",properties:{...Q,...dn,query:{type:"string",description:"Natural-language or identifier query"},limit:{type:"number",description:"Max results (default 20)"},fuzzy:{type:"boolean",description:"Stem/trigram fallback for zero-document-frequency terms (default true)"},exact:{type:"boolean",description:"Drop results carrying no verbatim term match (default false)"}},required:["repo","query"]}},{name:"embed_status",description:"Report the embedding tier: the effective mode (none/static/endpoint; endpoint > static model), the resolved model (opt-in, never shipped in the package) with its modelId/dim, EMBED_VERSION, and the configured HTTP endpoint with its reachability. Use to check whether `search` with semantic:true will fuse embeddings or degrade to lexical.",inputSchema:{type:"object",properties:{...Q},required:["repo"]}},{name:"type_hierarchy",description:"How do types relate? For one type: the base classes it extends, the interfaces/traits it implements, and \u2014 the reverse direction, which no other tool answers \u2014 what extends or implements IT, plus any declared supertype with no definition in this repo. Omit `name` for the whole hierarchy.",inputSchema:{type:"object",properties:{...Q,name:{type:"string",description:"Type name to look up"}},required:["repo"]}},{name:"implementations",description:"Who implements this interface (or extends this class)? Walks the hierarchy TRANSITIVELY, so a class implementing a sub-interface of the one asked about is included. The tool to reach for before changing an interface.",inputSchema:{type:"object",properties:{...Q,name:{type:"string",description:"Interface/trait/class name"}},required:["repo","name"]}},{name:"call_graph",description:"What does this symbol reach, and what reaches it? A bounded symbol-to-symbol neighborhood around `symbol` \u2014 `depth` hops (default 2) following `calls`/`extends`/`implements` edges, `direction` out (callees) | in (callers) | both. Answers impact questions the one-hop `callers` tool cannot.",inputSchema:{type:"object",properties:{...Q,symbol:{type:"string",description:"Symbol name to centre on"},depth:{type:"number",description:"Hops to follow (default 2, max 5)"},direction:{type:"string",description:"out | in | both (default both)"}},required:["repo","symbol"]}},{name:"check_rules",description:'Validate dependency-cruiser-style architecture rules against the link-graph. Rules (inline JSON array): forbidden edges {name, from, to, kind?, severity?, comment?} with glob paths, plus builtins {name, builtin: "cycles"|"orphans"} (module-level import cycles; edge-less code files). Returns deterministic violations with severity error|warn \u2014 a CI gate.',inputSchema:{type:"object",properties:{...Q,...dn,rules:{type:"array",description:"Rules array (inline JSON \u2014 see description)"},configPath:{type:"string",description:"Read the rules from this JSON file instead (repo-relative or absolute) \u2014 the CLI's --config. Ignored when `rules` is given."}},required:["repo"]}}],Nn={type:"array",items:{type:"string"}},he={type:"object"},un={call_graph:{type:"object",properties:{root:{type:"array",items:he},nodes:{type:"array",items:he},edges:{type:"array",items:he},truncated:{type:"boolean"}},required:["root","nodes","edges"]},scan_summary:{type:"object",properties:{engineVersion:{type:"string"},commit:{type:"string"},fileCount:{type:"integer"},languages:{type:"object",additionalProperties:{type:"integer"}},capped:{type:"boolean"}},required:["engineVersion","fileCount","languages","capped"]},graph:{type:"object",properties:{schemaVersion:{type:"integer"},version:{type:"string"},commit:{type:"string"},fileCount:{type:"integer"},languages:{type:"object",additionalProperties:{type:"integer"}},files:{type:"array",items:he},modules:{type:"array",items:he},fileEdges:{type:"array",items:he},moduleEdges:{type:"array",items:he}},required:["schemaVersion","files","fileEdges","modules","moduleEdges"]},symbols:{oneOf:[{type:"object",properties:{schemaVersion:{type:"integer"},defs:he,refs:he},required:["schemaVersion","defs"]},{type:"object",properties:{name:{type:"string"},defs:{type:"array",items:he},refs:Nn},required:["name","defs","refs"]}]},callers:{oneOf:[{type:"object",additionalProperties:he},{type:"object",properties:{error:{type:"string"}},required:["error"]}]},workspaces:{type:"object",properties:{packages:{type:"array",items:he},cycle:{type:["array","null"],items:{type:"string"}},topoOrder:Nn},required:["packages","topoOrder"]},churn:{type:"object",properties:{ok:{type:"boolean"},churn:{type:"object",additionalProperties:{type:"integer"}}},required:["ok","churn"]},find_references:{type:"object",properties:{defs:{type:"array",items:he},callSites:{type:"array",items:he},referencingFiles:Nn},required:["defs","callSites","referencingFiles"]},lsp_status:{type:"object",properties:{lspVersion:{type:"number"},mode:{type:"string",enum:["none","configured"]},configPath:{type:["string","null"]},source:{type:"string",enum:["env","repo","cwd","none"]},servers:{type:"array",items:he},unmappedLanguages:Nn},required:["lspVersion","mode","source","servers","unmappedLanguages"]},onboard:{type:"object",properties:{brief:{type:"string"},memory:{type:"string"}},required:["brief"]},explain_search:{type:"object",properties:{results:{type:"array",items:he},explain:{type:"object",properties:{query:{type:"string"},terms:{type:"array",items:he},droppedStopwords:Nn,unresolvedTerms:Nn,wholeIdentifier:he,verdict:{type:"string",enum:["match","weak","none"]},note:{type:"string"},bridgedOnlyResults:{type:"number"},resultCount:{type:"number"}},required:["query","terms","droppedStopwords","unresolvedTerms","verdict","bridgedOnlyResults","resultCount"]}},required:["results","explain"]},hotspots:{type:"object",properties:{churnOk:{type:"boolean"},hotspots:{type:"array",items:he}},required:["churnOk","hotspots"]},coupling:{type:"object",properties:{ok:{type:"boolean"},couplings:{type:"array",items:he}},required:["ok","couplings"]},duplicated_literals:{type:"object",properties:{duplications:{type:"array",items:he},families:{type:"array",items:he}},required:["duplications","families"]},embed_status:{type:"object",properties:{embedVersion:{type:"integer"},mode:{type:"string",enum:["none","static","endpoint"]},model:{},endpoint:{},endpointReachable:{type:"boolean"}},required:["embedVersion","mode"]},write_memory:{type:"object",properties:{written:{type:"string"}},required:["written"]},delete_memory:{type:"object",properties:{deleted:{type:"boolean"}},required:["deleted"]}};for(let e of["replace_symbol_body","insert_after_symbol","insert_before_symbol"])un[e]={type:"object",properties:{file:{type:"string"},symbol:{type:"string"},startLine:{type:"integer"},endLine:{type:"integer"}},required:["file"]};Ur={scan_summary:{title:"Scan summary"},graph:{title:"Link graph"},symbols:{title:"Symbol index"},callers:{title:"Caller index"},workspaces:{title:"Monorepo workspaces"},churn:{title:"Git churn"},symbols_overview:{title:"File symbol overview"},find_symbol:{title:"Find symbol"},find_references:{title:"Find references"},repo_map:{title:"Repository map"},onboard:{title:"Project brief",write:!0,destructive:!1,idempotent:!0},hotspots:{title:"Hotspots"},coupling:{title:"Change coupling"},replace_symbol_body:{title:"Replace symbol body",write:!0,destructive:!0,idempotent:!0},insert_after_symbol:{title:"Insert after symbol",write:!0,destructive:!1,idempotent:!1},insert_before_symbol:{title:"Insert before symbol",write:!0,destructive:!1,idempotent:!1},write_memory:{title:"Write memory",write:!0,destructive:!1,idempotent:!0},read_memory:{title:"Read memory"},list_memories:{title:"List memories"},delete_memory:{title:"Delete memory",write:!0,destructive:!0,idempotent:!0},dead_code:{title:"Dead-code candidates"},duplicated_literals:{title:"Values with no single source of truth"},complexity:{title:"Complexity"},mermaid:{title:"Mermaid module diagram"},grep:{title:"Grep file contents"},search:{title:"Lexical search",openWorld:!0},explain_search:{title:"Search with a verdict",openWorld:!0},lsp_status:{title:"LSP tier status",openWorld:!0},embed_status:{title:"Embedding tier status",openWorld:!0},type_hierarchy:{title:"Type hierarchy"},implementations:{title:"Implementations"},call_graph:{title:"Call graph neighborhood"},check_rules:{title:"Check architecture rules"}};gi={orient:["scan_summary","repo_map","onboard","workspaces","mermaid","read_memory","list_memories"],find:["search","explain_search","grep","find_symbol","symbols","symbols_overview"],impact:["find_references","callers","call_graph","dead_code","type_hierarchy","implementations","lsp_status"],edit:["find_symbol","symbols_overview","replace_symbol_body","insert_after_symbol","insert_before_symbol"],risk:["hotspots","churn","coupling","complexity","check_rules","duplicated_literals","dead_code"]}});function Pa(e){return ve(e.files.map(t=>`${t.rel}:${t.hash}`).join(` -`))}async function zr(e,t){let n=`${e.mode}:${e.identity}:${Pa(e.scan)}`;if(hi&&hi.key===n)return hi.index;let r=await t();return hi={key:n,index:r},r}function Gr(e){let t;try{t=Ve(I(e,"model.json"))}catch{return}let n=`${e}:${t.mtimeMs}:${t.size}`;if(yi&&yi.key===n)return yi.model;let r=Lt(e);return r&&(yi={key:n,model:r}),r}function oy(e){let t=rt.findIndex(r=>r.key===e);if(t<0)return;let[n]=rt.splice(t,1);return rt.unshift(n),n}function Fa(e){let t=rt.findIndex(n=>n.key===e.key);return t>=0&&rt.splice(t,1),rt.unshift(e),rt.length=Math.min(rt.length,iy),e}function gu(){rt.length=0}function _u(e,t){return e+"\0"+JSON.stringify({scope:t.scope,include:t.include,exclude:t.exclude,gitignore:t.gitignore,ignoreDirs:t.ignoreDirs,maxBytes:t.maxBytes,maxFiles:t.maxFiles,maxCallsPerFile:t.maxCallsPerFile,out:t.out,fullHash:t.fullHash})}function ye(e,t={},n){let r=_u(e,t),s=oy(r);if(s){let l=Pe(e,{...t,cache:s.cacheMap,precomputedWalk:n});return l.contentUnchanged?(l.cacheDirty&&(s.cacheMap=Nt(l)),s.scan.commit!==l.commit&&(s.scan.commit=l.commit),s.scan):(Fa({key:r,scan:l,cacheMap:Nt(l)}),l)}let o=er(e,{...t,precomputedWalk:n});if(o)return Fa({key:r,scan:o.scan,cacheMap:o.cacheMap,arts:o.arts}),o.scan;let a=Pe(e,{...t,precomputedWalk:n});return Fa({key:r,scan:a,cacheMap:Nt(a)}),a}function bi(e,t={},n){if(rt.some(r=>r.key===_u(e,t))){let r=ye(e,t,n);return{root:r.root,commit:r.commit,fileCount:r.files.length,languages:r.languages,capped:r.capped,excluded:r.excluded}}return Qn(e,{...t,precomputedWalk:n})}function vt(e,t={},n){let r=ye(e,t,n),s=rt.find(o=>o.scan===r);return s?s.arts??=Dt(r,t):Dt(r,t)}async function hu(e){await qr(Le(e,{}))}async function qr(e){await Ze(_t(e.files.map(t=>t.ext)))}var hi,yi,iy,rt,$a=O(()=>{"use strict";S();we();ie();Vs();It();tr();Te();Qe();rn();In();Rt();iy=4,rt=[]});var wu={};xi(wu,{DEFAULT_MAX_RESPONSE_BYTES:()=>ui,OUTPUT_SCHEMAS:()=>un,PROTOCOL_VERSIONS:()=>Et,TOOLS:()=>jr,TOOL_META:()=>Ur,TOOL_PROFILES:()=>gi,annotationsFor:()=>Oa,capResponse:()=>fi,getArtifacts:()=>vt,getScan:()=>ye,getScanSummary:()=>bi,memoizedEmbedModel:()=>Gr,memoizedEmbeddingIndex:()=>zr,negotiateProtocol:()=>di,profileNames:()=>Wr,resourceLinkFor:()=>mi,runMcpServer:()=>bu,scanFingerprint:()=>Pa,structuredContentFor:()=>ci,toCacheMap:()=>Nt,toolsFor:()=>Hr,toolsInProfiles:()=>Br,validateArgs:()=>li,warmGrammarsForRepo:()=>hu,warmGrammarsForWalk:()=>qr});function re(e){return typeof e=="string"&&e?e:void 0}function Da(e){return Array.isArray(e)&&e.every(t=>typeof t=="string")&&e.length?e:void 0}function Wt(e){let t=typeof e=="number"?e:typeof e=="string"&&e.trim()!==""?Number(e):NaN;return Number.isFinite(t)&&t>0?t:void 0}function yu(e){return e instanceof Error?e.message:String(e)}async function ly(e,t,n){let r=re(t.repo)??n;if(!r)throw new Error("`repo` is required (absolute path to the repository root)");let s={scope:re(t.scope),include:Da(t.include),exclude:Da(t.exclude)},o=re(t.rank),a=o==="graph"||o==="lexical"?{rank:o}:{},l;if(ay.has(e)||(l=Le(r,{}),await qr(l)),e==="scan_summary"){let c=bi(r,s,l);return JSON.stringify({engineVersion:fe,commit:c.commit,fileCount:c.fileCount,languages:c.languages,capped:c.capped},null,2)}if(e==="graph")return An(vt(r,s,l).graph);if(e==="symbols"){let{symbols:c}=vt(r,s,l),d=re(t.name);return JSON.stringify(d?{name:d,defs:c.defs[d]??[],refs:c.refs[d]??[]}:c,null,2)}if(e==="callers"){let c=ye(r,s,l),d=t.recall===!0?Xt(c,void 0,{recall:!0}):Rn(c),u=re(t.name);if(u){let p=d.get(u);return JSON.stringify(p??{error:`no tracked callers for "${u}"`},null,2)}let f={};for(let[p,m]of d)f[p]=m;return JSON.stringify(f,null,2)}if(e==="workspaces"){let c=tn(r);return JSON.stringify({packages:c.packages,cycle:c.cycle??null,topoOrder:c.topoOrder},null,2)}if(e==="churn"){let{churn:c,ok:d}=Je(r,{since:re(t.since)}),u={};for(let f of[...c.keys()].sort())u[f]=c.get(f);return JSON.stringify({ok:d,churn:u},null,2)}if(e==="symbols_overview"){let c=re(t.file);if(!c)throw new Error("`file` is required");return JSON.stringify(qo(ye(r,s,l),c),null,2)}if(e==="find_symbol"){let c=re(t.namePath);if(!c)throw new Error("`namePath` is required");let d=Mn(ye(r,s,l),c,{substring:t.substring===!0,includeBody:t.includeBody===!0,concise:t.concise===!0,maxResults:Wt(t.maxResults)});return JSON.stringify(d,null,2)}if(e==="find_references"){let c=re(t.name);if(!c)throw new Error("`name` is required");let d=ye(r,s,l),u=Vo(d,c);return t.lsp===!0?JSON.stringify(await va(d,r,c,u),null,2):JSON.stringify(u,null,2)}if(e==="lsp_status")return JSON.stringify(await Nr(ye(r,s,l),r,t.probe===!0),null,2);if(e==="replace_symbol_body"||e==="insert_after_symbol"||e==="insert_before_symbol"){let c=re(t.namePath),d=typeof t.body=="string"?t.body:void 0;if(!c||d===void 0)throw new Error("`namePath` and `body` are required");let u=ye(r,s,l),p=(e==="replace_symbol_body"?Jo:e==="insert_after_symbol"?Ko:Xo)(u,c,d,re(t.file));return gu(),JSON.stringify(p,null,2)}if(e==="write_memory"){let c=re(t.name),d=typeof t.content=="string"?t.content:void 0;if(!c||d===void 0)throw new Error("`name` and `content` are required");return JSON.stringify({written:_r(r,c,d)},null,2)}if(e==="read_memory"){let c=re(t.name);if(!c)throw new Error("`name` is required");let d=Qo(r,c);if(d===void 0)throw new Error(`no memory named "${c}" \u2014 see list_memories`);return d}if(e==="list_memories")return JSON.stringify(ta(r),null,2);if(e==="delete_memory"){let c=re(t.name);if(!c)throw new Error("`name` is required");return JSON.stringify({deleted:ea(r,c)},null,2)}if(e==="dead_code"){let c=Pr(ye(r,s,l)),d=Wt(t.limit);return d===void 0||c.length<=d?JSON.stringify(c,null,2):JSON.stringify({total:c.length,shown:d,truncated:!0,candidates:c.slice(0,d)},null,2)}if(e==="duplicated_literals"){let c=nn(ye(r,s,l),{minFiles:Wt(t.minFiles),minCount:Wt(t.minCount),includeTests:t.includeTests===!0}),d=Wt(t.limit);return d===void 0||c.duplications.length<=d?JSON.stringify(c,null,2):JSON.stringify({total:c.duplications.length,shown:d,truncated:!0,duplications:c.duplications.slice(0,d),families:c.families},null,2)}if(e==="complexity"){let c=ye(r,s,l);if(t.risk===!0){let{churn:d,ok:u}=Je(r,{since:re(t.since)});return JSON.stringify({churnOk:u,risks:pr(c,d,Wt(t.top))},null,2)}return JSON.stringify(mr(c,re(t.file),Wt(t.top)),null,2)}if(e==="mermaid"){let{graph:c}=vt(r,s,l);return $r(c,{module:re(t.module),maxEdges:Wt(t.maxEdges)})}if(e==="onboard"){let c=ye(r,s,l),{graph:d}=vt(r,s,l);return JSON.stringify(ma(c,d,{...typeof t.budgetTokens=="number"?{budgetTokens:t.budgetTokens}:{},...t.remember===!1?{remember:!1}:{}}),null,2)}if(e==="repo_map"){let{scan:c,graph:d}=vt(r,s,l);return an(c,d,{budgetTokens:typeof t.budgetTokens=="number"?t.budgetTokens:void 0})}if(e==="hotspots"){let c=ye(r,s,l),{churn:d,ok:u}=Je(r,{since:re(t.since)});return JSON.stringify({churnOk:u,hotspots:ln(c,d)},null,2)}if(e==="coupling"){let{ok:c,couplings:d}=Tr(r,{since:re(t.since)});return JSON.stringify({ok:c,couplings:d},null,2)}if(e==="grep"){let c=re(t.pattern);if(!c)throw new Error("`pattern` is required");let d=re(t.scope),u=Da(t.globs),f=xr(r,c,{globs:d?[...u??[],`${d.replace(/\/+$/,"")}/**`]:u,ignoreCase:t.ignoreCase===!0,maxHits:typeof t.maxHits=="number"?t.maxHits:void 0});return JSON.stringify(f,null,2)}if(e==="search"){let c=re(t.query);if(!c)throw new Error("`query` is required");let d=ye(r,s,l),u=typeof t.limit=="number"?t.limit:void 0,f=typeof t.fuzzy=="boolean"?t.fuzzy:void 0,p=t.exact===!0?{exact:!0}:{};if(t.semantic===!0){let h=jt();if(h)try{let E=await zr({mode:"endpoint",identity:h,scan:d},()=>Cr(d)),w=await Mr(c),k=on(d,c,E,{queryVec:w,limit:u,fuzzy:f});return JSON.stringify({results:k,tier:"endpoint"},null,2)}catch(E){let w=Ft(d,c,{limit:u,fuzzy:f,...a});return JSON.stringify({results:w,tier:"lexical",degradedReason:`embedding endpoint failed: ${yu(E)}`},null,2)}let _=St(r),y=_?Gr(_):void 0;if(y){let E=await zr({mode:"static",identity:`${_}#${y.modelId}`,scan:d},()=>sn(d,y)),w=on(d,c,E,{model:y,limit:u,fuzzy:f});return JSON.stringify({results:w,tier:"static"},null,2)}let x=Ft(d,c,{limit:u,fuzzy:f,...a});return JSON.stringify({results:x,tier:"lexical",degradedReason:"no embedding endpoint or static model configured \u2014 see embed_status"},null,2)}let{results:m,explain:g}=en(d,c,{limit:u,fuzzy:f,...p,...a});return JSON.stringify(t.explain===!0?{results:m,explain:g}:m,null,2)}if(e==="explain_search"){let c=re(t.query);if(!c)throw new Error("`query` is required");let d=ye(r,s,l),u=typeof t.limit=="number"?t.limit:void 0,f=typeof t.fuzzy=="boolean"?t.fuzzy:void 0,{results:p,explain:m}=en(d,c,{limit:u,fuzzy:f,...t.exact===!0?{exact:!0}:{},...a});return JSON.stringify({results:p,explain:m},null,2)}if(e==="embed_status"){let c=St(r),d=c?Gr(c):void 0,u=jt(),p={embedVersion:nt,mode:u?"endpoint":d?"static":"none",model:d?{present:!0,dir:c,modelId:d.modelId,dim:d.dim,vocabSize:d.vocabSize}:{present:!1},endpoint:u??null};return u&&(p.endpointReachable=await Rr(u)),JSON.stringify(p,null,2)}if(e==="type_hierarchy"){let c=Wo(ye(r,s,l)),d=re(t.name);if(!d){let f={};for(let[p,m]of c)f[p]=m;return JSON.stringify(f,null,2)}let u=c.get(d);return JSON.stringify(u||{error:`no type named ${d}`},null,2)}if(e==="implementations"){let c=re(t.name);if(!c)throw new Error("`name` is required");let d=Wo(ye(r,s,l));return d.has(c)?JSON.stringify({name:c,implementations:ir(d,c)},null,2):JSON.stringify({error:`no type named ${c}`},null,2)}if(e==="call_graph"){let c=re(t.symbol);if(!c)throw new Error("`symbol` is required");let d=re(t.direction),u=d==="out"||d==="in"?d:"both",f=cr(dd(ye(r,s,l)),c,{...typeof t.depth=="number"?{depth:t.depth}:{},direction:u});return f.root.length?JSON.stringify(f,null,2):JSON.stringify({error:`no symbol named ${c}`},null,2)}if(e==="check_rules"){let c=re(t.configPath),d=t.rules;if(d===void 0&&c){let p=Jr(c)?c:I(r,c);try{d=JSON.parse(te(p,"utf8"))}catch(m){throw new Error(`cannot read rules from ${p}: ${yu(m)}`)}}if(d===void 0)throw new Error("`rules` (or `configPath`) is required");let u=Or(d),{graph:f}=vt(r,s,l);return JSON.stringify(Fr(f,u),null,2)}throw new Error(`unknown tool: ${e}`)}async function bu(e={}){let t={name:e.serverInfo?.name??"codeindex",version:e.serverInfo?.version??fe},n=Et[0],r=Hr(e.defaultRepo,n,e.profile),s=l=>{v.stdout.write(JSON.stringify({jsonrpc:"2.0",...l})+` -`)},o=fu({input:v.stdin,terminal:!1});for await(let l of o){let c=l.trim();if(!c)continue;let d;try{d=JSON.parse(c)}catch{s({id:null,error:{code:-32700,message:"parse error"}});continue}let u=Array.isArray(d)?d:[d];for(let f of u)await a(f)}async function a(l){if(!(l.id===void 0||l.id===null))try{if(l.method==="initialize")n=di(l.params?.protocolVersion),r=Hr(e.defaultRepo,n,e.profile),s({id:l.id,result:{protocolVersion:n,capabilities:{tools:{}},serverInfo:t}});else if(l.method==="ping")s({id:l.id,result:{}});else if(l.method==="tools/list")s({id:l.id,result:{tools:r}});else if(l.method==="tools/call"){let c=l.params??{},d=re(c.name)??"",u=c.arguments??{};try{let f=r.find(E=>E.name===d),p=f?li(f.inputSchema,u):void 0;if(p)throw new Error(p);let m=await ly(d,u,e.defaultRepo),g=re(u.repo)??e.defaultRepo??"",h=fi(m,d,g,e.maxResponseBytes??ui),_=h!==m,y=_&&n>=Lr?mi(h,d):void 0,x=n>=Lr?ci(h,_,un[d]!==void 0):void 0;s({id:l.id,result:{content:y?[{type:"text",text:h},y]:[{type:"text",text:h}],...x?{structuredContent:x}:{}}})}catch(f){s({id:l.id,result:{content:[{type:"text",text:f instanceof Error?f.message:String(f)}],isError:!0}})}}else s({id:l.id,error:{code:-32601,message:`method not found: ${l.method}`}})}catch(c){s({id:l.id,error:{code:-32603,message:c instanceof Error?c.message:String(c)}})}}}var ay,La=O(()=>{"use strict";S();we();ie();mu();qe();zs();Zt();dt();Kt();dr();br();Gt();Js();Ir();Ar();oi();wr();gr();ai();js();si();pa();Zo();Ws();vn();ii();rn();In();Zs();Ys();Te();_i();pi();$a();_i();pi();$a();ay=new Set(["workspaces","churn","coupling","grep","write_memory","read_memory","list_memories","delete_memory","embed_status","scan_summary"])});var ku={};xi(ku,{rewriteCommand:()=>Su,shellQuote:()=>wi,tokenize:()=>xu});function xu(e){let t=[],n="",r,s=!1;for(let o=0;o2&&/^-[a-zA-Z]+$/.test(o)){let a=o.slice(1).split("").map(l=>`-${l}`);t.splice(s,1,...a),s--}else return}}if(n.pattern===void 0){let s=r.shift();if(s===void 0||s==="")return;n.pattern=s}if(!(r.length>1))return n.path=r[0],n}function Su(e,t="codeindex"){let n=e.trim();if(!n||cy.test(n))return;let r=xu(n);if(!r||r.length<2)return;let[s,...o]=r;if(s===void 0||!dy.has(s))return;let a=uy(s,o);if(!a||a.pattern===void 0)return;let l=a.pattern;if(!a.recursive)return;let c=a.path,d=[t,"grep",wi(l)];c&&c!=="."&&c!=="./"&&d.push("--scope",wi(c.replace(/\/+$/,""))),a.ignoreCase&&d.push("--ignore-case");for(let u of a.includes)d.push("--include",wi(u));return d.join(" ")}var cy,dy,ja=O(()=>{"use strict";S();cy=/[|&;<>`\n\r$(){}]/,dy=new Set(["grep","egrep","rg","ripgrep"])});S();S();qe();Te();It();It();tr();S();we();qi();ie();ms();S();var ks=class{constructor(){throw new Error("worker_threads is not available in the browser build (the engine runs single-threaded here)")}};Rt();Te();_n();Qe();It();function rp(){try{let e=us(import.meta.url);if(e.endsWith("engine.mjs"))return Wn(e).href;let t=I(Se(e),"engine.mjs");return z(t)?Wn(t).href:void 0}catch{return}}var sp=600*1e3;function Pc(e){let t=v.env.CODEINDEX_WORKERS,n=e??(t!==void 0&&t!==""?Number(t):void 0);if(n!==void 0)return Number.isFinite(n)&&n>0?Math.floor(n):0;let r=1;try{r=zl()}catch{r=1}return Math.max(0,Math.min(r-1,8))}async function ip(e,t){await Ze(e.grammarKeys);let n=e.grammarKeys.filter(s=>Ye(s)),r=[];for(let s of e.jobs){let o,a;try{let d=Ve(s.abs);o=d.size,a=d.mtimeMs}catch{continue}let l=G(s.abs),c=xo(s.rel,s.ext,o,l,ve(l),qt(s.ext),{maxCallsPerFile:e.maxCallsPerFile});r.push({rel:s.rel,size:o,mtimeMs:a,record:c})}t({ready:n,records:r})}async function $c(e,t,n,r={}){if(n<2||e.length===0)return;let s=rp();if(!s)return;let o=t.filter(c=>Ye(c)).sort(),a=Array.from({length:Math.min(n,e.length)},()=>[]);e.forEach((c,d)=>a[d%a.length].push(c));let l=`import { runExtractWorker } from ${JSON.stringify(s)}; -import { parentPort, workerData } from "node:worker_threads"; -runExtractWorker(workerData.input, (o) => parentPort.postMessage(o)).catch((e) => parentPort.postMessage({ error: String(e) })); -`;try{let c=await Promise.all(a.map(u=>new Promise((f,p)=>{let m=new ks(l,{eval:!0,workerData:{input:{jobs:u,grammarKeys:o,maxCallsPerFile:r.maxCallsPerFile}}}),g=setTimeout(()=>{p(new Error("extraction worker timed out")),m.terminate()},sp),h=_=>{clearTimeout(g),_()};m.once("message",_=>{h(()=>f(_)),m.terminate()}),m.once("error",_=>h(()=>p(_))),m.once("exit",_=>{_!==0&&h(()=>p(new Error(`extraction worker exited with ${_}`)))})}))),d=new Map;for(let u of c){if("error"in u||u.ready.slice().sort().join(",")!==o.join(","))return;for(let f of u.records)d.set(f.rel,{size:f.size,mtimeMs:f.mtimeMs,record:f.record})}return d}catch{return}}async function Eo(e,t={}){let n=Pc(t.workers);if(n<2)return Pe(e,t);let r=t.precomputedWalk??Le(e,{maxFileBytes:t.maxBytes,maxFiles:t.maxFiles,gitignore:t.gitignore,ignoreDirs:t.ignoreDirs}),s={...t,precomputedWalk:r},o=[];for(let{f:c}of ko(e,s)){let d=t.cache?.get(c.rel);!t.fullHash&&d&&d.size!==void 0&&d.mtimeMs!==void 0&&d.size===c.size&&d.mtimeMs===c.mtimeMs||o.push({abs:c.abs,rel:c.rel,ext:c.ext})}if(o.length===0)return Pe(e,s);let a=_t(r.files.map(c=>c.ext)),l=await $c(o,a,n,{maxCallsPerFile:t.maxCallsPerFile});return Pe(e,l?{...s,extracted:l}:s)}Un();Ci();Bi();S();ie();var op=new Set([".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs",".vue",".svelte",".astro",".py",".rb",".go",".rs",".java",".kt",".kts",".php",".c",".cc",".cpp",".h",".hpp",".cs",".swift",".scala",".clj",".ex",".exs",".dart",".lua",".sh",".bash",".zig",".elm",".hcl",".tf",".tfvars",".sol",".hh",".sc",".pyi",".rake",".cxx"]),ap=new Set([".css",".scss",".sass",".less",".styl",".pcss"]),lp=new Set([".md",".mdx",".rst",".adoc",".txt"]),cp=new Set([".json",".yaml",".yml",".toml",".csv",".xml",".env"]),dp=new Set([".png",".jpg",".jpeg",".gif",".webp",".avif",".ico",".bmp",".tiff",".svg",".pdf",".woff",".woff2",".ttf",".otf",".eot",".mp3",".mp4",".mov",".avi",".webm",".zip",".gz",".tar",".rar",".7z",".wasm",".so",".dylib",".dll",".exe",".bin",".class",".jar",".pyc",".node"]),up=["locales","locale","i18n","lang","langs","translations","messages"],fp=new Set([".json",".yaml",".yml",".po",".properties"]),mp=["__tests__","test","tests","spec","e2e","__mocks__"],pp=["migrations","entities","models"],gp=new Set(["package.json","tsconfig.json","dockerfile","makefile","pyproject.toml","cargo.toml","go.mod","requirements.txt","gemfile","composer.json","pubspec.yaml"]);function _p(e,t){let n=e.toLowerCase(),r=ke(n),s=n.split("/"),o=a=>a.some(l=>s.includes(l));return o(up)&&fp.has(t)?"i18n":t===".prisma"||t===".sql"||t===".graphql"||t===".gql"||r.startsWith("schema.")||r==="models.py"||o(pp)?"schema":n.includes(".test.")||n.includes(".spec.")||o(mp)?"test":gp.has(r)||r.endsWith(".config.js")||r.endsWith(".config.ts")||r.endsWith(".config.mjs")||r.startsWith(".eslintrc")||r.startsWith(".prettierrc")||r.startsWith(".env")||r.startsWith("docker-compose")?"config":lp.has(t)?"doc":ap.has(t)?"style":op.has(t)?"code":dp.has(t)?"asset":cp.has(t)?"data":"other"}_n();wo();Gi();Qe();ho();S();we();ie();so();Qe();K();var Dc=new Map;function Lc(e,t){let n=Dc.get(e);if(n!==void 0)return n;let r=null;for(let s of Xe().dirs){let o=I(s,`${e}.tags.scm`);if(z(o)){try{r=new dc(t,te(o,"utf8"))}catch{r=null}break}}return Dc.set(e,r),r}function hp(e){if(!Xe().dirs.some(r=>z(I(r,`${e}.tags.scm`))))return{present:!1,compiled:!1};let n=ao(e);return n?{present:!0,compiled:Lc(e,n)!==null}:{present:!0,compiled:!1}}function yp(e,t){let n=Jn(e);if(!n)return[];let r=ao(n),s=hs(n);if(!r||!s)return[];let o=Lc(n,r);if(!o)return[];let a=null;try{if(a=s.parse(t),!a)return[];let l=[],c=new Set;for(let d of o.matches(a.rootNode)){let u,f,p=0;for(let g of d.captures)g.name==="name"?(u=g.node.text,p=g.node.startPosition.row+1):g.name.startsWith("definition.")&&(f=g.name.slice(11));if(!u||!f)continue;let m=`${f} ${u} ${p}`;c.has(m)||(c.add(m),l.push({kind:f,name:u,line:p}))}return l.sort((d,u)=>d.line-u.line||R(d.name,u.name)||R(d.kind,u.kind))}catch{return[]}finally{a?.delete()}}Qe();Qe();S();ss();we();ie();S();function jc(){throw new Error("zlib.gunzipSync is not available in the browser build (use DecompressionStream at an async boundary)")}qe();var Ro=`https://github.com/maxgfr/codeindex/releases/download/v${fe}/grammars-${fe}.tar.gz`;function Es(){let e=v.env.CODEINDEX_GRAMMARS_URL;return e&&e.trim()?{url:e.trim()}:{url:Ro,sha256Url:`${Ro}.sha256`}}async function Uc(e,t){let n=await fetch(e);if(!n.ok)throw new Error(`HTTP ${n.status} from ${e}`);let r=T.from(await n.arrayBuffer());if(t){let s=gn("sha256").update(r).digest("hex");if(s!==t)throw new Error(`sha256 mismatch: expected ${t}, got ${s}`)}return r}function Wc(e){return T.isBuffer(e)?e:T.from(e.buffer,e.byteOffset,e.byteLength)}async function Bc(e){let t=await fetch(e);if(!t.ok)throw new Error(`HTTP ${t.status} from ${e}`);let r=((await t.text()).trim().split(/\s+/)[0]??"").toLowerCase();if(!/^[0-9a-f]{64}$/.test(r))throw new Error(`invalid sha256 sidecar at ${e}`);return r}function vo(e,t,n){let r=e.subarray(t,t+n),s=r.indexOf(0);return r.toString("utf8",0,s===-1?r.length:s)}function*bp(e){let t=0;for(;t+512<=e.length;){let n=e.subarray(t,t+512),r=!0;for(let u=0;u<512;u++)if(n[u]!==0){r=!1;break}if(r)break;let s=vo(n,0,100),o=vo(n,345,155),a=vo(n,124,12).trim(),l=a?parseInt(a,8):0,c=String.fromCharCode(n[156]??0);t+=512;let d=e.subarray(t,t+l);t+=Math.ceil(l/512)*512,yield{name:o?`${o}/${s}`:s,type:c,data:d}}}function wp(e){if(!e||e.includes("\0")||e.startsWith("/")||e.startsWith("\\")||/^[A-Za-z]:/.test(e))return null;let t=[];for(let n of e.split(/[/\\]/))if(!(n===""||n===".")){if(n==="..")return null;t.push(n)}return t.length?t.join("/"):null}function Hc(e,t){let n=Ae(t),r=[];for(let s of bp(Wc(e))){if(s.type!=="0"&&s.type!=="\0")continue;let o=wp(s.name);if(o===null)throw new Error(`refusing unsafe tar entry: ${s.name}`);let a=Ae(t,o);if(a!==n&&!a.startsWith(n+"/"))throw new Error(`tar entry escapes destination: ${s.name}`);ft(Se(a),{recursive:!0}),Re(a,s.data),r.push(o)}return r}function zc(e,t){let n=Wc(e),r=n.length>=2&&n[0]===31&&n[1]===139?jc(n):n;return Hc(r,t)}async function nr(e,t={}){let n=t.onNote??(()=>{}),r=Es(),s;if(r.sha256Url)try{s=await Bc(r.sha256Url)}catch(d){n(`codeindex: could not fetch checksum (${d instanceof Error?d.message:String(d)}) \u2014 proceeding unverified -`)}let o=I(e,"web-tree-sitter.wasm"),a=I(Se(e),`${fe}.sha256`);if(z(o)&&s&&z(a)){let d="";try{d=te(a,"utf8").trim()}catch{}if(d===s)return{ok:!0,status:"up-to-date",cacheDir:e,message:`codeindex: grammars already present at ${e} (up to date) +`}function La(e){return"m_"+e.replace(/[^A-Za-z0-9_]/g,"_")}function yy(e,t={}){let n=t.maxModules??_y,r=t.maxEdges??hy,o=e.modules.slice().sort((d,f)=>xu(f)-xu(d)||M(d.slug,f.slug)).slice(0,n),a=new Set(o.map(d=>d.slug)),l=e.moduleEdges.filter(d=>a.has(d.from)&&a.has(d.to)).sort((d,f)=>f.weight-d.weight||M(d.from,f.from)||M(d.to,f.to)).slice(0,r),c=[];c.push(`%% ${t.title??"module graph"} \u2014 ${o.length} of ${e.modules.length} modules, ${l.length} of ${e.moduleEdges.length} edges`),(o.lengthu.tier===d);if(f.length){c.push(` subgraph ${gy[d]}`);for(let u of f)c.push(` ${La(u.slug)}["${u.path.replace(/"/g,"'")}"]`);c.push(" end")}}for(let d of l){let f=d.weight>1?`|${d.weight}| `:"";c.push(` ${La(d.from)} -->${f?" "+f:" "}${La(d.to)}`)}return{content:"```mermaid\n"+c.join(` +`)+"\n```\n",shownModules:o.length,totalModules:e.modules.length,shownEdges:l.length,totalEdges:e.moduleEdges.length}}var $a,gy,_y,hy,xu,hi=F(()=>{"use strict";k();Y();$a=e=>e.replace(/[^\w]/g,"_");gy={0:"Foundations",1:"Features",2:"Tail"},_y=40,hy=80,xu=e=>e.degIn+e.degOut});function Mu(){throw new Error("readline is not available in the browser build (the MCP stdio transport is Node-only)")}var Cu=F(()=>{k()});function yi(e,t){let n=e.properties??{};for(let[r,s]of Object.entries(t)){if(s==null)continue;let o=n[r];if(!o?.type)continue;let a=Array.isArray(s)?"array":typeof s;if(o.type==="number"){let l=a==="number"?s:a==="string"&&s.trim()!==""?Number(s):NaN;if(!Number.isFinite(l))return`\`${r}\` must be a number, got ${a==="string"?JSON.stringify(s):a}`;if(o.minimum!==void 0&&lo.maximum)return`\`${r}\` must be at most ${o.maximum}`;continue}if(o.type==="array"){if(a!=="array")return`\`${r}\` must be an array of strings, got ${a}`;if(o.items?.type==="string"&&!s.every(l=>typeof l=="string"))return`\`${r}\` must be an array of strings`;continue}if(a!==o.type)return`\`${r}\` must be a ${o.type}, got ${a}`}}function bi(e,t,n){if(t||!n)return;let r;try{r=JSON.parse(e)}catch{return}if(!(r===null||typeof r!="object"||Array.isArray(r)))return r}function wi(e){return typeof e=="string"&&Mt.includes(e)?e:Ey}function Si(e,t,n,r){let s=T.byteLength(e,"utf8");if(s<=r)return e;let o=Ba[t]?I(n,ut,Ba[t]):void 0;return JSON.stringify({truncated:!0,tool:t,bytes:s,maxBytes:r,reason:"This response exceeds the configured limit and was withheld rather than sent as an unusable partial payload.",narrower:vy[t]??"narrow the request with `scope`, `include`/`exclude`, or a `limit`",...o&&H(o)?{artifact:o,artifactNote:"The full result is already on disk here \u2014 read it directly if you need all of it."}:o?{artifactNote:`Run \`codeindex index --repo ${n} --out ${I(n,ut)}\` to get this as a file.`}:{}},null,2)+` +`}function ki(e,t){let n=Ba[t];if(!n)return;let r;try{r=JSON.parse(e)}catch{return}if(!(r.truncated!==!0||typeof r.artifact!="string"))return{type:"resource_link",uri:qn(r.artifact).href,name:n,description:`The full ${t} result this call was too large to inline.`,mimeType:"application/json"}}var Mt,Ey,Au,Ur,xi,vy,Ba,Ei=F(()=>{"use strict";k();xe();oe();ws();sr();Mt=["2024-11-05","2025-03-26","2025-06-18","2025-11-25"],Ey=Mt[Mt.length-1],Au="2025-03-26",Ur="2025-06-18";xi=1e6,vy={graph:"pass `scope` to a subdirectory, or use repo_map / mermaid for an overview",symbols:"pass `name` to look up one symbol, or use find_symbol / symbols_overview",callers:"pass `name` to look up one symbol's call sites",dead_code:"pass `scope` to a subdirectory",find_references:"the symbol is referenced very widely \u2014 narrow with `scope` on a graph query",check_rules:"narrow the rule set, or pass `scope` to a subdirectory"},Ba={graph:"graph.json",symbols:"symbols.json"}});function za(e){let t=zr[e];if(t)return{readOnlyHint:!t.write,...t.write?{destructiveHint:t.destructive===!0,idempotentHint:t.idempotent===!0}:{},openWorldHint:t.openWorld===!0}}function Hr(){return["all",...Object.keys(vi).sort()]}function qr(e){let t=e.split(",").map(r=>r.trim()).filter(Boolean),n=new Set;for(let r of t){if(r==="all")return new Set(Br.map(o=>o.name));let s=vi[r];if(!s)throw new Error(`unknown tool profile "${r}" \u2014 one of: ${Hr().join(", ")}`);for(let o of s)n.add(o)}return n}function Gr(e,t=Mt[0],n){let r=t>=Au,s=t>=Ur,o=n?qr(n):void 0,a=o?Br.filter(l=>o.has(l.name)):Br;return!e&&!r&&!s?a:a.map(l=>({...l,...s&&zr[l.name]?{title:zr[l.name].title}:{},...s&&fn[l.name]?{outputSchema:fn[l.name]}:{},...r?{annotations:za(l.name)}:{},inputSchema:e?{...l.inputSchema,properties:{...l.inputSchema.properties,repo:{type:"string",description:`Absolute path to the repository root (optional \u2014 defaults to ${e})`}},required:l.inputSchema.required.filter(c=>c!=="repo")}:l.inputSchema}))}var Q,un,Br,Fn,ye,fn,zr,vi,Ri=F(()=>{"use strict";k();Ei();Q={repo:{type:"string",description:"Absolute path to the repository root"}},un={scope:{type:"string",description:"Restrict to one directory (repo-relative)"},include:{type:"array",items:{type:"string"},description:"Include globs"},exclude:{type:"array",items:{type:"string"},description:"Exclude globs"}},Br=[{name:"scan_summary",description:"Deterministically scan a repository: file count, per-language file histogram, HEAD commit, and whether the walk was capped. Fast first look at any codebase.",inputSchema:{type:"object",properties:{...Q,...un},required:["repo"]}},{name:"graph",description:"Build the full typed cross-file link-graph (import/call/use/doc-link/mention edges, module grouping, PageRank centrality, Louvain communities, tests-map). Returns graph.json. Large on big repos \u2014 prefer scan_summary/symbols/callers for targeted questions.",inputSchema:{type:"object",properties:{...Q,...un},required:["repo"]}},{name:"symbols",description:"Where is a symbol defined and which files reference it? Returns the definition sites (file, line, kind, exported) and referencing files. Omit `name` for the full symbol index.",inputSchema:{type:"object",properties:{...Q,name:{type:"string",description:"Symbol name to look up"}},required:["repo"]}},{name:"callers",description:"Who calls a function? Per-symbol caller index: each defined symbol with the exact (file, line) call sites that bind to it. Omit `name` for the full index.",inputSchema:{type:"object",properties:{...Q,name:{type:"string",description:"Symbol name to look up"},recall:{type:"boolean",description:"Recall-oriented binding: relax the JS/TS import gate to unique repo-wide names, labelling each site corroborated|unique-name (default false = precision)"}},required:["repo"]}},{name:"workspaces",description:"Detect monorepo packages (npm/pnpm/yarn/lerna/nx/cargo/go.work/maven) with the workspace dependency graph, one cycle if present, and a topological build order.",inputSchema:{type:"object",properties:{...Q},required:["repo"]}},{name:"churn",description:"Per-file git commit counts (whole history, or since a ref) \u2014 the churn half of hotspot analysis.",inputSchema:{type:"object",properties:{...Q,since:{type:"string",description:"Only count commits after this ref"}},required:["repo"]}},{name:"symbols_overview",description:"All symbols declared in ONE file (name, kind, line span, exported, parent), in declaration order \u2014 the fastest way to understand a file without reading it.",inputSchema:{type:"object",properties:{...Q,file:{type:"string",description:"Repo-relative file path"}},required:["repo","file"]}},{name:"find_symbol",description:`Find symbol declarations by name or name path ('Class/method' matches a method inside Class). Each match carries its COMPLETE SIGNATURE (parameters and return type) by default, because "what shape is it" is the question that follows "where is it" almost every time and one round trip beats two. Options: substring matching, includeBody for the declaration's source, concise to drop everything but name/kind/file/line when you genuinely only want a location. Exact-name matches rank first.`,inputSchema:{type:"object",properties:{...Q,namePath:{type:"string",description:"Symbol name or Parent/child path"},substring:{type:"boolean"},includeBody:{type:"boolean"},concise:{type:"boolean",description:"Return only name/kind/file/line \u2014 drop the signature, line span, visibility and language. Roughly 2.5x smaller; use it when you are resolving a path and nothing more (default false)."},maxResults:{type:"number",minimum:1,description:"Cap matches (default 50)"}},required:["repo","namePath"]}},{name:"find_references",description:"Who references a symbol? Three labeled tiers: defs (declarations), callSites (line-precise, import-corroborated call bindings), referencingFiles (file-level identifier/doc mentions \u2014 may include homonyms). Confidence decreases across tiers; the labels let you decide what to trust.",inputSchema:{type:"object",properties:{...Q,name:{type:"string",description:"Symbol name"},lsp:{type:"boolean",description:"Also ask a configured language server (see lsp_status) and append an `lsp` block: its references plus an `agreement` matrix (both / lspOnly / staticOnly). The three static tiers are unchanged either way. `staticOnly` is where the homonyms are. No config, no binary, a crash or a timeout all degrade to the static answer with a stated reason (default false)."}},required:["repo","name"]}},{name:"lsp_status",description:"Is the optional LSP tier configured, and would it answer? Reports the config path and its source, each server with whether its command is on PATH and how many files in this repo it claims, and the languages no server covers. Opt-in by asset: the tier is active only when /.codeindex/lsp.json exists (or CODEINDEX_LSP_CONFIG points at one). `probe: true` additionally starts each server to read the capabilities it really advertises. The tier never touches graph.json/symbols.json \u2014 it annotates query answers only.",inputSchema:{type:"object",properties:{...Q,probe:{type:"boolean",description:"Start each server and read its real capabilities (default false: no spawn)"}},required:["repo"]}},{name:"onboard",description:"One call that says what this repository IS: its own tagline, size and language mix, monorepo layout when there is one, a token-budgeted map of the highest-PageRank files with their key signatures, and where git says work concentrates. Composes scan_summary + workspaces + repo_map + hotspots so the first four round trips of a session become one, and persists the result as the `onboarding` memory (read_memory) so the next session does not repeat them. Set remember:false to skip the write.",inputSchema:{type:"object",properties:{...Q,budgetTokens:{type:"number",minimum:1,description:"Token budget for the key-files section (default 900)"},remember:{type:"boolean",description:"Persist the brief as the `onboarding` memory (default true)"}},required:["repo"]}},{name:"repo_map",description:"Token-budgeted map of the repository: the highest-PageRank files with their key exported signatures, deterministically rendered to fit `budgetTokens` (default 1024). The densest single read to understand an unfamiliar codebase.",inputSchema:{type:"object",properties:{...Q,budgetTokens:{type:"number",minimum:1,description:"Approximate token budget (default 1024)"}},required:["repo"]}},{name:"hotspots",description:"Where does work concentrate? Files ranked by git churn \xD7 size (commits \xD7 log2 lines). High-scoring files are where changes and defects cluster.",inputSchema:{type:"object",properties:{...Q,since:{type:"string",description:"Only count commits after this ref"}},required:["repo"]}},{name:"coupling",description:"Change coupling: pairs of files that repeatedly change in the same commits \u2014 hidden dependencies no import shows. strength 1.0 = every change to one touched the other.",inputSchema:{type:"object",properties:{...Q,since:{type:"string",description:"Only mine commits after this ref"}},required:["repo"]}},{name:"replace_symbol_body",description:"WRITE: replace a symbol's whole declaration with `body` (verbatim, supply full indentation). The symbol is resolved by name path ('Class/method'); ambiguity errors list the candidates \u2014 qualify with `file`. Line spans come from the AST index.",inputSchema:{type:"object",properties:{...Q,namePath:{type:"string"},body:{type:"string"},file:{type:"string",description:"Disambiguate: repo-relative file containing the symbol"}},required:["repo","namePath","body"]}},{name:"insert_after_symbol",description:"WRITE: insert `body` after a symbol's declaration (blank-line separation preserved for definition-like kinds). Resolved like replace_symbol_body.",inputSchema:{type:"object",properties:{...Q,namePath:{type:"string"},body:{type:"string"},file:{type:"string"}},required:["repo","namePath","body"]}},{name:"insert_before_symbol",description:"WRITE: insert `body` before a symbol's declaration (blank-line separation preserved). Resolved like replace_symbol_body.",inputSchema:{type:"object",properties:{...Q,namePath:{type:"string"},body:{type:"string"},file:{type:"string"}},required:["repo","namePath","body"]}},{name:"write_memory",description:"Persist a named markdown note under /.codeindex/memories/ (names may use topic/name form). Write small, focused notes: project map, build commands, conventions.",inputSchema:{type:"object",properties:{...Q,name:{type:"string"},content:{type:"string"}},required:["repo","name","content"]}},{name:"read_memory",description:"Read one persisted memory by name.",inputSchema:{type:"object",properties:{...Q,name:{type:"string"}},required:["repo","name"]}},{name:"list_memories",description:"List persisted memory names \u2014 load this first, then read individual memories on relevance.",inputSchema:{type:"object",properties:{...Q},required:["repo"]}},{name:"delete_memory",description:"Delete one persisted memory by name.",inputSchema:{type:"object",properties:{...Q,name:{type:"string"}},required:["repo","name"]}},{name:"dead_code",description:"Dead-code candidates in two labeled tiers: 'unreferenced' (no call site binds AND nothing references the name) and 'uncalled' (referenced somewhere \u2014 re-export, type position \u2014 but never called). Exported symbols only; test files and entrypoint-looking files excluded as roots. On a large repo this list runs to thousands of entries \u2014 pass `limit`, or `scope` to one subdirectory.",inputSchema:{type:"object",properties:{...Q,...un,limit:{type:"number",minimum:0,description:"Cap entries (default: all)"}},required:["repo"]}},{name:"duplicated_literals",description:"Values with no single source of truth: one literal written out across many files. Three labeled tiers \u2014 'competing' (two or more exported constants hold the same value), 'bypassed' (a constant holds it and other files rewrite it anyway), 'uncentralized' (nothing holds it). Path-like values are also grouped into namespace families, so a whole route space reports once instead of once per route. Covers config files (JSON/YAML/TOML) as well as code, which is where the dangerous cases live: a threshold declared in TypeScript and again in a rules JSON is checked by no compiler. Use it to answer 'what breaks if this value changes' and 'is there already a helper for this'.",inputSchema:{type:"object",properties:{...Q,...un,minFiles:{type:"number",minimum:1,description:"Distinct files a value must span (default 2)"},minCount:{type:"number",minimum:1,description:"Total occurrences required (default 3)"},includeTests:{type:"boolean",description:"Count test files too (default false)"},limit:{type:"number",minimum:0,description:"Cap duplications (default: all)"}},required:["repo"]}},{name:"complexity",description:"Cyclomatic-complexity estimates (branch-token counting over AST line spans), most-complex first. Pass `file` for one file's symbols, omit for the repo-wide top. Combine with hotspots: the `risk` field of this tool's sibling ranks complexity \xD7 churn.",inputSchema:{type:"object",properties:{...Q,file:{type:"string"},risk:{type:"boolean",description:"Return complexity \xD7 git-churn risk ranking instead"},since:{type:"string",description:"Only count risk churn after this ref"},top:{type:"number",minimum:1,description:"Cap ranked symbols"}},required:["repo"]}},{name:"mermaid",description:"Mermaid diagram of the module graph (renders inline in Claude/GitHub \u2014 no graph database). Optionally scoped to one module's neighborhood.",inputSchema:{type:"object",properties:{...Q,module:{type:"string",description:"Module slug to focus on"},maxEdges:{type:"number",minimum:1,description:"Cap rendered edges"}},required:["repo"]}},{name:"grep",description:"Search file contents (ripgrep when available, deterministic JS fallback otherwise). Returns sorted (file, line, text) hits.",inputSchema:{type:"object",properties:{...Q,pattern:{type:"string",description:"Regular expression to search for"},scope:{type:"string",description:"Restrict to one directory (repo-relative)"},globs:{type:"array",items:{type:"string"},description:"Restrict to matching paths"},ignoreCase:{type:"boolean"},maxHits:{type:"number",minimum:1}},required:["repo","pattern"]}},{name:"search",description:'Natural-language-ish lexical search: BM25F ranking over SIX weighted fields \u2014 symbol names (camelCase/snake_case subtokens), path segments, markdown headings, the file summary, per-symbol DOC COMMENTS, and the prose body (comment + short-literal words). The last two are why "where is rate limiting handled" works: the phrase lives in a comment, not in a name. Results carry `matchedFields`, a `line` anchor and `symbolHits` (name/kind/line). NOT embeddings by default \u2014 deterministic, diacritic-folded, zero API keys. Answers "where is auth handled?"-style queries with ranked files, matched terms and top symbols. Query terms with zero document frequency get a deterministic trigram-fuzzy fallback (typo-tolerant) unless `fuzzy: false`. Set `semantic: true` to RRF-fuse an embedding tier (HTTP endpoint, else a local static model) with lexical \u2014 the response then wraps the ranked list as `{ results, tier, degradedReason? }`, `tier` being "endpoint"/"static" when fusion happened or "lexical" (with `degradedReason`) when it did not (see embed_status). Without `semantic`, the response is the bare ranked array, unchanged.',inputSchema:{type:"object",properties:{...Q,...un,query:{type:"string",description:"Natural-language or identifier query"},limit:{type:"number",minimum:0,description:"Max results (default 20)"},fuzzy:{type:"boolean",description:'Fallback for query terms with zero document frequency: a morphological stem match first ("caching" finds "cache"), then trigram similarity for typos (default true)'},rank:{type:"string",description:`Structural prior: "graph" multiplies the lexical score by the file's PageRank over the resolved import graph; "lexical" (default) scores on text alone. Unproven on the judged corpus \u2014 see SearchOptions.rank.`},exact:{type:"boolean",description:"Drop results that carry no verbatim query-term match \u2014 the ones the stem/trigram bridge produced (default false)."},explain:{type:"boolean",description:"Wrap the response as `{ results, explain }` with the query verdict (default false = bare array). See explain_search."},semantic:{type:"boolean",description:'RRF-fuse an embedding tier with lexical (default false). Precedence: the HTTP endpoint (CODEINDEX_EMBED_ENDPOINT) if set, else a local static model. The response reports the effective tier as a top-level `tier` field ("endpoint"/"static" on success, "lexical" plus `degradedReason` when neither is available/reachable) instead of degrading silently \u2014 see embed_status.'}},required:["repo","query"]}},{name:"explain_search",description:'Search, and say whether the query actually found anything. Returns `{ results, explain }` where explain.verdict is "match" (a verbatim term matched), "weak" (results exist but rest on a near match, or the identifier you asked for has document frequency 0) or "none". Use this instead of `search` whenever an empty-feeling or surprising result matters: a query for an identifier that is NOT in the indexed tree still returns confident-looking rows built from its subtokens \u2014 searching "nullGipStep7" in a repo that only has "nullGipStep2" ranks files matching "null" and "gip" \u2014 and only the verdict distinguishes that from a real hit. Also names the terms dropped as stopwords, the terms that exist nowhere, and what each near match bridged to.',inputSchema:{type:"object",properties:{...Q,...un,query:{type:"string",description:"Natural-language or identifier query"},limit:{type:"number",minimum:0,description:"Max results (default 20)"},fuzzy:{type:"boolean",description:"Stem/trigram fallback for zero-document-frequency terms (default true)"},exact:{type:"boolean",description:"Drop results carrying no verbatim term match (default false)"}},required:["repo","query"]}},{name:"embed_status",description:"Report the embedding tier: the effective mode (none/static/endpoint; endpoint > static model), the resolved model (opt-in, never shipped in the package) with its modelId/dim, EMBED_VERSION, and the configured HTTP endpoint with its reachability. Use to check whether `search` with semantic:true will fuse embeddings or degrade to lexical.",inputSchema:{type:"object",properties:{...Q},required:["repo"]}},{name:"type_hierarchy",description:"How do types relate? For one type: the base classes it extends, the interfaces/traits it implements, and \u2014 the reverse direction, which no other tool answers \u2014 what extends or implements IT, plus any declared supertype with no definition in this repo. Omit `name` for the whole hierarchy.",inputSchema:{type:"object",properties:{...Q,name:{type:"string",description:"Type name to look up"}},required:["repo"]}},{name:"implementations",description:"Who implements this interface (or extends this class)? Walks the hierarchy TRANSITIVELY, so a class implementing a sub-interface of the one asked about is included. The tool to reach for before changing an interface.",inputSchema:{type:"object",properties:{...Q,name:{type:"string",description:"Interface/trait/class name"}},required:["repo","name"]}},{name:"call_graph",description:"What does this symbol reach, and what reaches it? A bounded symbol-to-symbol neighborhood around `symbol` \u2014 `depth` hops (default 2) following `calls`/`extends`/`implements` edges, `direction` out (callees) | in (callers) | both. Answers impact questions the one-hop `callers` tool cannot.",inputSchema:{type:"object",properties:{...Q,symbol:{type:"string",description:"Symbol name to centre on"},depth:{type:"number",minimum:1,maximum:5,description:"Hops to follow (default 2, max 5)"},direction:{type:"string",description:"out | in | both (default both)"}},required:["repo","symbol"]}},{name:"check_rules",description:'Validate dependency-cruiser-style architecture rules against the link-graph. Rules (inline JSON array): forbidden edges {name, from, to, kind?, severity?, comment?} with glob paths, plus builtins {name, builtin: "cycles"|"orphans"} (module-level import cycles; edge-less code files). Returns deterministic violations with severity error|warn \u2014 a CI gate.',inputSchema:{type:"object",properties:{...Q,...un,rules:{type:"array",description:"Rules array (inline JSON \u2014 see description)"},configPath:{type:"string",description:"Read the rules from this JSON file instead (repo-relative or absolute) \u2014 the CLI's --config. Ignored when `rules` is given."}},required:["repo"]}}],Fn={type:"array",items:{type:"string"}},ye={type:"object"},fn={call_graph:{type:"object",properties:{root:{type:"array",items:ye},nodes:{type:"array",items:ye},edges:{type:"array",items:ye},truncated:{type:"boolean"}},required:["root","nodes","edges"]},scan_summary:{type:"object",properties:{engineVersion:{type:"string"},commit:{type:"string"},fileCount:{type:"integer"},languages:{type:"object",additionalProperties:{type:"integer"}},capped:{type:"boolean"}},required:["engineVersion","fileCount","languages","capped"]},graph:{type:"object",properties:{schemaVersion:{type:"integer"},version:{type:"string"},commit:{type:"string"},fileCount:{type:"integer"},languages:{type:"object",additionalProperties:{type:"integer"}},files:{type:"array",items:ye},modules:{type:"array",items:ye},fileEdges:{type:"array",items:ye},moduleEdges:{type:"array",items:ye}},required:["schemaVersion","files","fileEdges","modules","moduleEdges"]},symbols:{oneOf:[{type:"object",properties:{schemaVersion:{type:"integer"},defs:ye,refs:ye},required:["schemaVersion","defs"]},{type:"object",properties:{name:{type:"string"},defs:{type:"array",items:ye},refs:Fn},required:["name","defs","refs"]}]},callers:{oneOf:[{type:"object",additionalProperties:ye},{type:"object",properties:{error:{type:"string"}},required:["error"]}]},workspaces:{type:"object",properties:{packages:{type:"array",items:ye},cycle:{type:["array","null"],items:{type:"string"}},topoOrder:Fn},required:["packages","topoOrder"]},churn:{type:"object",properties:{ok:{type:"boolean"},churn:{type:"object",additionalProperties:{type:"integer"}}},required:["ok","churn"]},find_references:{type:"object",properties:{defs:{type:"array",items:ye},callSites:{type:"array",items:ye},referencingFiles:Fn},required:["defs","callSites","referencingFiles"]},lsp_status:{type:"object",properties:{lspVersion:{type:"number"},mode:{type:"string",enum:["none","configured"]},configPath:{type:["string","null"]},source:{type:"string",enum:["env","repo","cwd","none"]},servers:{type:"array",items:ye},unmappedLanguages:Fn},required:["lspVersion","mode","source","servers","unmappedLanguages"]},onboard:{type:"object",properties:{brief:{type:"string"},memory:{type:"string"}},required:["brief"]},explain_search:{type:"object",properties:{results:{type:"array",items:ye},explain:{type:"object",properties:{query:{type:"string"},terms:{type:"array",items:ye},droppedStopwords:Fn,unresolvedTerms:Fn,wholeIdentifier:ye,verdict:{type:"string",enum:["match","weak","none"]},note:{type:"string"},bridgedOnlyResults:{type:"number"},resultCount:{type:"number"}},required:["query","terms","droppedStopwords","unresolvedTerms","verdict","bridgedOnlyResults","resultCount"]}},required:["results","explain"]},hotspots:{type:"object",properties:{churnOk:{type:"boolean"},hotspots:{type:"array",items:ye}},required:["churnOk","hotspots"]},coupling:{type:"object",properties:{ok:{type:"boolean"},couplings:{type:"array",items:ye}},required:["ok","couplings"]},duplicated_literals:{type:"object",properties:{duplications:{type:"array",items:ye},families:{type:"array",items:ye}},required:["duplications","families"]},embed_status:{type:"object",properties:{embedVersion:{type:"integer"},mode:{type:"string",enum:["none","static","endpoint"]},model:{},endpoint:{},endpointReachable:{type:"boolean"}},required:["embedVersion","mode"]},write_memory:{type:"object",properties:{written:{type:"string"}},required:["written"]},delete_memory:{type:"object",properties:{deleted:{type:"boolean"}},required:["deleted"]}};for(let e of["replace_symbol_body","insert_after_symbol","insert_before_symbol"])fn[e]={type:"object",properties:{file:{type:"string"},symbol:{type:"string"},startLine:{type:"integer"},endLine:{type:"integer"}},required:["file"]};zr={scan_summary:{title:"Scan summary"},graph:{title:"Link graph"},symbols:{title:"Symbol index"},callers:{title:"Caller index"},workspaces:{title:"Monorepo workspaces"},churn:{title:"Git churn"},symbols_overview:{title:"File symbol overview"},find_symbol:{title:"Find symbol"},find_references:{title:"Find references"},repo_map:{title:"Repository map"},onboard:{title:"Project brief",write:!0,destructive:!1,idempotent:!0},hotspots:{title:"Hotspots"},coupling:{title:"Change coupling"},replace_symbol_body:{title:"Replace symbol body",write:!0,destructive:!0,idempotent:!0},insert_after_symbol:{title:"Insert after symbol",write:!0,destructive:!1,idempotent:!1},insert_before_symbol:{title:"Insert before symbol",write:!0,destructive:!1,idempotent:!1},write_memory:{title:"Write memory",write:!0,destructive:!1,idempotent:!0},read_memory:{title:"Read memory"},list_memories:{title:"List memories"},delete_memory:{title:"Delete memory",write:!0,destructive:!0,idempotent:!0},dead_code:{title:"Dead-code candidates"},duplicated_literals:{title:"Values with no single source of truth"},complexity:{title:"Complexity"},mermaid:{title:"Mermaid module diagram"},grep:{title:"Grep file contents"},search:{title:"Lexical search",openWorld:!0},explain_search:{title:"Search with a verdict",openWorld:!0},lsp_status:{title:"LSP tier status",openWorld:!0},embed_status:{title:"Embedding tier status",openWorld:!0},type_hierarchy:{title:"Type hierarchy"},implementations:{title:"Implementations"},call_graph:{title:"Call graph neighborhood"},check_rules:{title:"Check architecture rules"}};vi={orient:["scan_summary","repo_map","onboard","workspaces","mermaid","read_memory","list_memories"],find:["search","explain_search","grep","find_symbol","symbols","symbols_overview"],impact:["find_references","callers","call_graph","dead_code","type_hierarchy","implementations","lsp_status"],edit:["find_symbol","symbols_overview","replace_symbol_body","insert_after_symbol","insert_before_symbol"],risk:["hotspots","churn","coupling","complexity","check_rules","duplicated_literals","dead_code"]}});function Ha(e){return Me(e.files.map(t=>`${t.rel}:${t.hash}`).join(` +`))}async function Vr(e,t){let n=`${e.mode}:${e.identity}:${Ha(e.scan)}`;if(Mi&&Mi.key===n)return Mi.index;let r=await t();return Mi={key:n,index:r},r}function Jr(e){let t;try{t=Ee(I(e,"model.json"))}catch{return}let n=`${e}:${t.mtimeMs}:${t.size}`;if(Ci&&Ci.key===n)return Ci.model;let r=Wt(e);return r&&(Ci={key:n,model:r}),r}function Tu(e){let t=Je.findIndex(r=>r.key===e);if(t<0)return;let[n]=Je.splice(t,1);return Je.unshift(n),n}function zt(e){let t=Je.findIndex(n=>n.key===e.key);return t>=0&&Je.splice(t,1),Je.unshift(e),Je.length=Math.min(Je.length,Ry),e}function Iu(){Je.length=0}function qa(e,t){let n=e+"\0";for(let r of Je)r.key.startsWith(n)&&(t?r.cacheMap.delete(t):r.cacheMap.clear())}function Nu(e,t){return e+"\0"+JSON.stringify({scope:t.scope,include:t.include,exclude:t.exclude,gitignore:t.gitignore,ignoreDirs:t.ignoreDirs,maxBytes:t.maxBytes,maxFiles:t.maxFiles,maxCallsPerFile:t.maxCallsPerFile,out:t.out,fullHash:t.fullHash})}function Kr(e,t={},n){let r=Nu(e,t),s=Tu(r);if(s){let l=Pe(e,{...t,cache:s.cacheMap,precomputedWalk:n});return l.contentUnchanged?(l.cacheDirty&&(s.cacheMap=De(l)),s.scan.commit!==l.commit&&(s.scan.commit=l.commit,s.arts=void 0,s.loadArtifacts=void 0),s.scan):(zt({key:r,scan:l,cacheMap:De(l)}),l)}let o=Po(e,{...t,precomputedWalk:n});if(o)return zt({key:r,scan:o.scan,cacheMap:o.cacheMap,arts:o.arts}),o.scan;let a=Pe(e,{...t,precomputedWalk:n});return zt({key:r,scan:a,cacheMap:De(a)}),a}async function Ai(e,t={},n,r=async()=>{}){let s=Nu(e,t),o=Je.find(c=>c.key===s);if(o){let c=o.cacheMap,d=m=>(m.cacheDirty&&(o.cacheMap=De(m)),o.scan.commit!==m.commit&&(o.scan.commit=m.commit,o.arts=void 0,o.loadArtifacts=void 0),Tu(s),o.scan);if(n&&No(n,c,t.fullHash)){await r();let m=await Pt(e,{...t,cache:c,precomputedWalk:n});return m.contentUnchanged?d(m):(zt({key:s,scan:m,cacheMap:De(m)}),m)}let f=Pe(e,{...t,cache:c,precomputedWalk:n});if(f.contentUnchanged)return d(f);if(n)return zt({key:s,scan:f,cacheMap:De(f)}),f;await r();let u=await Pt(e,{...t,cache:c,precomputedWalk:n});return zt({key:s,scan:u,cacheMap:De(u)}),u}let a=await Is(e,{...t,precomputedWalk:n},r);if(a)return zt({key:s,scan:a.scan,cacheMap:a.cacheMap,arts:a.arts,loadArtifacts:a.loadArtifacts}),a.scan;await r();let l=await Pt(e,{...t,precomputedWalk:n});return zt({key:s,scan:l,cacheMap:De(l)}),l}function Ti(e,t={},n){return rr(e,{...t,precomputedWalk:n})}function Ii(e,t={},n,r){let s=r??Kr(e,t,n),o=Je.find(a=>a.scan===s);return o?o.arts??=o.loadArtifacts?.()??Et(s,t):Et(s,t)}async function Ou(e){await Xr(Fe(e,{}))}async function Xr(e){await et(bt(e.files.map(t=>t.ext)))}var Mi,Ci,Ry,Je,Ga=F(()=>{"use strict";k();xe();oe();ri();Ft();Os();sr();Ae();nt();sn();On();At();Ry=4,Je=[]});var $u={};Oi($u,{DEFAULT_MAX_RESPONSE_BYTES:()=>xi,OUTPUT_SCHEMAS:()=>fn,PROTOCOL_VERSIONS:()=>Mt,TOOLS:()=>Br,TOOL_META:()=>zr,TOOL_PROFILES:()=>vi,annotationsFor:()=>za,capResponse:()=>Si,getArtifacts:()=>Ii,getScan:()=>Kr,getScanParallel:()=>Ai,getScanSummary:()=>Ti,memoizedEmbedModel:()=>Jr,memoizedEmbeddingIndex:()=>Vr,negotiateProtocol:()=>wi,profileNames:()=>Hr,resourceLinkFor:()=>ki,runMcpServer:()=>Pu,scanFingerprint:()=>Ha,structuredContentFor:()=>bi,toCacheMap:()=>De,toolsFor:()=>Gr,toolsInProfiles:()=>qr,validateArgs:()=>yi,warmGrammarsForRepo:()=>Ou,warmGrammarsForWalk:()=>Xr});function My(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;return t.jsonrpc!=="2.0"||typeof t.method!="string"?!1:t.id===void 0||t.id===null||typeof t.id=="number"||typeof t.id=="string"}function Cy(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;return t.jsonrpc==="2.0"&&typeof t.method!="string"&&("result"in t||"error"in t)}function se(e){return typeof e=="string"&&e?e:void 0}function Va(e){return Array.isArray(e)&&e.every(t=>typeof t=="string")&&e.length?e:void 0}function Zr(e){let t=typeof e=="number"?e:typeof e=="string"&&e.trim()!==""?Number(e):NaN;return Number.isFinite(t)&&t>=0?t:void 0}function Ke(e){let t=Zr(e);return t!==void 0&&t>0?t:void 0}function Fu(e){return e instanceof Error?e.message:String(e)}async function Ty(e,t,n){let r=se(t.repo)??n;if(!r)throw new Error("`repo` is required (absolute path to the repository root)");try{if(!Ee(r).isDirectory())throw new Error("not a directory")}catch{throw new Error(`repository root is not a readable directory: ${r}`)}let s={scope:se(t.scope),include:Va(t.include),exclude:Va(t.exclude)},o=se(t.rank),a=o==="graph"||o==="lexical"?{rank:o}:{},l,c;Ay.has(e)||(l=Fe(r,{}),c=await Ai(r,s,l,()=>l?Xr(l):Promise.resolve()));let d=()=>c??Kr(r,s,l),f=()=>Ii(r,s,l,c);if(e==="scan_summary"){let u=Ti(r,s,l);return JSON.stringify({engineVersion:fe,commit:u.commit,fileCount:u.fileCount,languages:u.languages,capped:u.capped},null,2)}if(e==="graph")return In(f().graph);if(e==="symbols"){let{symbols:u}=f(),m=se(t.name);return JSON.stringify(m?{name:m,defs:u.defs[m]??[],refs:u.refs[m]??[]}:u,null,2)}if(e==="callers"){let u=d(),m=t.recall===!0?Zt(u,void 0,{recall:!0}):Cn(u),p=se(t.name);if(p){let y=m.get(p);return JSON.stringify(y??{error:`no tracked callers for "${p}"`},null,2)}let g={};for(let[y,h]of m)g[y]=h;return JSON.stringify(g,null,2)}if(e==="workspaces"){let u=nn(r);return JSON.stringify({packages:u.packages,cycle:u.cycle??null,topoOrder:u.topoOrder},null,2)}if(e==="churn"){let{churn:u,ok:m}=Ze(r,{since:se(t.since)}),p={};for(let g of[...u.keys()].sort())p[g]=u.get(g);return JSON.stringify({ok:m,churn:p},null,2)}if(e==="symbols_overview"){let u=se(t.file);if(!u)throw new Error("`file` is required");return JSON.stringify(ra(d(),u),null,2)}if(e==="find_symbol"){let u=se(t.namePath);if(!u)throw new Error("`namePath` is required");let m=An(d(),u,{substring:t.substring===!0,includeBody:t.includeBody===!0,concise:t.concise===!0,maxResults:Ke(t.maxResults)});return JSON.stringify(m,null,2)}if(e==="find_references"){let u=se(t.name);if(!u)throw new Error("`name` is required");let m=d(),p=sa(m,u);return t.lsp===!0?JSON.stringify(await Pa(m,r,u,p),null,2):JSON.stringify(p,null,2)}if(e==="lsp_status")return JSON.stringify(await Pr(d(),r,t.probe===!0),null,2);if(e==="replace_symbol_body"||e==="insert_after_symbol"||e==="insert_before_symbol"){let u=se(t.namePath),m=typeof t.body=="string"?t.body:void 0;if(!u||m===void 0)throw new Error("`namePath` and `body` are required");let p=d(),y=(e==="replace_symbol_body"?ia:e==="insert_after_symbol"?oa:aa)(p,u,m,se(t.file));return Iu(),JSON.stringify(y,null,2)}if(e==="write_memory"){let u=se(t.name),m=typeof t.content=="string"?t.content:void 0;if(!u||m===void 0)throw new Error("`name` and `content` are required");return JSON.stringify({written:br(r,u,m)},null,2)}if(e==="read_memory"){let u=se(t.name);if(!u)throw new Error("`name` is required");let m=da(r,u);if(m===void 0)throw new Error(`no memory named "${u}" \u2014 see list_memories`);return m}if(e==="list_memories")return JSON.stringify(fa(r),null,2);if(e==="delete_memory"){let u=se(t.name);if(!u)throw new Error("`name` is required");return JSON.stringify({deleted:ua(r,u)},null,2)}if(e==="dead_code"){let u=Dr(d()),m=Zr(t.limit);return m===void 0||u.length<=m?JSON.stringify(u,null,2):JSON.stringify({total:u.length,shown:m,truncated:!0,candidates:u.slice(0,m)},null,2)}if(e==="duplicated_literals"){let u=rn(d(),{minFiles:Ke(t.minFiles),minCount:Ke(t.minCount),includeTests:t.includeTests===!0}),m=Zr(t.limit);return m===void 0||u.duplications.length<=m?JSON.stringify(u,null,2):JSON.stringify({total:u.duplications.length,shown:m,truncated:!0,duplications:u.duplications.slice(0,m),families:u.families},null,2)}if(e==="complexity"){let u=d();if(t.risk===!0){let{churn:m,ok:p}=Ze(r,{since:se(t.since)});return JSON.stringify({churnOk:p,risks:hr(u,m,Ke(t.top))},null,2)}return JSON.stringify(_r(u,se(t.file),Ke(t.top)),null,2)}if(e==="mermaid"){let{graph:u}=f();return jr(u,{module:se(t.module),maxEdges:Ke(t.maxEdges)})}if(e==="onboard"){let u=d(),{graph:m}=f();return JSON.stringify(ka(u,m,{...Ke(t.budgetTokens)!==void 0?{budgetTokens:Ke(t.budgetTokens)}:{},...t.remember===!1?{remember:!1}:{}}),null,2)}if(e==="repo_map"){let{scan:u,graph:m}=f();return ln(u,m,{budgetTokens:Ke(t.budgetTokens)})}if(e==="hotspots"){let u=d(),{churn:m,ok:p}=Ze(r,{since:se(t.since)});return JSON.stringify({churnOk:p,hotspots:cn(u,m)},null,2)}if(e==="coupling"){let{ok:u,couplings:m}=Or(r,{since:se(t.since)});return JSON.stringify({ok:u,couplings:m},null,2)}if(e==="grep"){let u=se(t.pattern);if(!u)throw new Error("`pattern` is required");let m=se(t.scope),p=Va(t.globs),g=Er(r,u,{globs:m?[...p??[],`${m.replace(/\/+$/,"")}/**`]:p,ignoreCase:t.ignoreCase===!0,maxHits:Ke(t.maxHits)});return JSON.stringify(g,null,2)}if(e==="search"){let u=se(t.query);if(!u)throw new Error("`query` is required");let m=d(),p=Zr(t.limit),g=typeof t.fuzzy=="boolean"?t.fuzzy:void 0,y=t.exact===!0?{exact:!0}:{};if(t.semantic===!0){let _=Ut();if(_)try{let v=await Vr({mode:"endpoint",identity:_,scan:m},()=>Ir(m)),A=await Tr(u),O=an(m,u,v,{queryVec:A,limit:p,fuzzy:g});return JSON.stringify({results:O,tier:"endpoint"},null,2)}catch(v){let A=Lt(m,u,{limit:p,fuzzy:g,...a});return JSON.stringify({results:A,tier:"lexical",degradedReason:`embedding endpoint failed: ${Fu(v)}`},null,2)}let E=vt(r),b=E?Jr(E):void 0;if(b){let v=await Vr({mode:"static",identity:`${E}#${b.modelId}`,scan:m},()=>on(m,b)),A=an(m,u,v,{model:b,limit:p,fuzzy:g});return JSON.stringify({results:A,tier:"static"},null,2)}let x=Lt(m,u,{limit:p,fuzzy:g,...a});return JSON.stringify({results:x,tier:"lexical",degradedReason:"no embedding endpoint or static model configured \u2014 see embed_status"},null,2)}let{results:h,explain:S}=tn(m,u,{limit:p,fuzzy:g,...y,...a});return JSON.stringify(t.explain===!0?{results:h,explain:S}:h,null,2)}if(e==="explain_search"){let u=se(t.query);if(!u)throw new Error("`query` is required");let m=d(),p=Zr(t.limit),g=typeof t.fuzzy=="boolean"?t.fuzzy:void 0,{results:y,explain:h}=tn(m,u,{limit:p,fuzzy:g,...t.exact===!0?{exact:!0}:{},...a});return JSON.stringify({results:y,explain:h},null,2)}if(e==="embed_status"){let u=vt(r),m=u?Jr(u):void 0,p=Ut(),y={embedVersion:it,mode:p?"endpoint":m?"static":"none",model:m?{present:!0,dir:u,modelId:m.modelId,dim:m.dim,vocabSize:m.vocabSize}:{present:!1},endpoint:p??null};return p&&(y.endpointReachable=await Ar(p)),JSON.stringify(y,null,2)}if(e==="type_hierarchy"){let u=Yo(d()),m=se(t.name);if(!m){let g={};for(let[y,h]of u)g[y]=h;return JSON.stringify(g,null,2)}let p=u.get(m);return JSON.stringify(p||{error:`no type named ${m}`},null,2)}if(e==="implementations"){let u=se(t.name);if(!u)throw new Error("`name` is required");let m=Yo(d());return m.has(u)?JSON.stringify({name:u,implementations:lr(m,u)},null,2):JSON.stringify({error:`no type named ${u}`},null,2)}if(e==="call_graph"){let u=se(t.symbol);if(!u)throw new Error("`symbol` is required");let m=se(t.direction),p=m==="out"||m==="in"?m:"both",g=fr(vd(d()),u,{...Ke(t.depth)!==void 0?{depth:Ke(t.depth)}:{},direction:p});return g.root.length?JSON.stringify(g,null,2):JSON.stringify({error:`no symbol named ${u}`},null,2)}if(e==="check_rules"){let u=se(t.configPath),m=t.rules;if(m===void 0&&u){let y=Qr(u)?u:I(r,u);try{m=JSON.parse(te(y,"utf8"))}catch(h){throw new Error(`cannot read rules from ${y}: ${Fu(h)}`)}}if(m===void 0)throw new Error("`rules` (or `configPath`) is required");let p=$r(m),{graph:g}=f();return JSON.stringify(Lr(g,p),null,2)}throw new Error(`unknown tool: ${e}`)}async function Pu(e={}){let t={name:e.serverInfo?.name??"codeindex",version:e.serverInfo?.version??fe},n=Mt[0],r=Gr(e.defaultRepo,n,e.profile),s;if(e.watch&&e.defaultRepo)try{s=cl(e.defaultRepo,{recursive:!0},(c,d)=>{let f=d?.toString().replaceAll("\\","/")??"";f.split("/").some(m=>qt.has(m)||m.startsWith(".codeindex-edit-"))||qa(e.defaultRepo,f||void 0)}),s.on("error",c=>{R.stderr.write(`codeindex: MCP watcher disabled (${c.message}); using freshness scans +`),s?.close(),s=void 0,qa(e.defaultRepo)})}catch(c){R.stderr.write(`codeindex: MCP watcher unavailable (${c instanceof Error?c.message:String(c)}); using freshness scans +`)}let o=c=>{let d=Array.isArray(c)?c.map(f=>({jsonrpc:"2.0",...f})):{jsonrpc:"2.0",...c};R.stdout.write(JSON.stringify(d)+` +`)},a=Mu({input:R.stdin,terminal:!1});try{for await(let c of a){let d=c.trim();if(!d)continue;let f;try{f=JSON.parse(d)}catch{o({id:null,error:{code:-32700,message:"parse error"}});continue}if(Array.isArray(f)&&f.length===0){o({id:null,error:{code:-32600,message:"invalid request"}});continue}let u=async m=>{if(!Cy(m))return My(m)?l(m):{id:null,error:{code:-32600,message:"invalid request"}}};if(Array.isArray(f)){let m=[];for(let p of f){let g=await u(p);g&&m.push(g)}m.length>0&&o(m)}else{let m=await u(f);m&&o(m)}}}finally{s?.close()}async function l(c){let d=!("id"in c),f=u=>d?void 0:{id:c.id??null,...u};try{if(c.method==="initialize")return n=wi(c.params?.protocolVersion),r=Gr(e.defaultRepo,n,e.profile),f({result:{protocolVersion:n,capabilities:{tools:{}},serverInfo:t}});if(c.method==="ping")return f({result:{}});if(c.method==="tools/list")return f({result:{tools:r}});if(c.method==="tools/call"){let u=c.params??{},m=se(u.name)??"",p=u.arguments??{};try{let g=r.find(v=>v.name===m),y=g?yi(g.inputSchema,p):void 0;if(y)throw new Error(y);let h=await Ty(m,p,e.defaultRepo),S=se(p.repo)??e.defaultRepo??"",_=Si(h,m,S,e.maxResponseBytes??xi),E=_!==h,b=E&&n>=Ur?ki(_,m):void 0,x=n>=Ur?bi(_,E,fn[m]!==void 0):void 0;return f({result:{content:b?[{type:"text",text:_},b]:[{type:"text",text:_}],...x?{structuredContent:x}:{}}})}catch(g){return f({result:{content:[{type:"text",text:g instanceof Error?g.message:String(g)}],isError:!0}})}}else return f({error:{code:-32601,message:`method not found: ${c.method}`}})}catch(u){return f({error:{code:-32603,message:u instanceof Error?u.message:String(u)}})}}}var Ay,Ja=F(()=>{"use strict";k();xe();oe();Cu();Xe();ei();Yt();mt();Xt();mr();Sr();Gt();si();Fr();Nr();_i();kr();yr();hi();Ks();pi();Ea();la();Zs();Mn();gi();sn();On();ai();li();Ae();Ri();Ei();Ga();Ri();Ei();Ga();Ay=new Set(["workspaces","churn","coupling","grep","write_memory","read_memory","list_memories","delete_memory","embed_status","scan_summary"])});var ju={};Oi(ju,{rewriteCommand:()=>Du,shellQuote:()=>Ni,tokenize:()=>Lu});function Lu(e){let t=[],n="",r,s=!1;for(let o=0;o2&&/^-[a-zA-Z]+$/.test(o)){let a=o.slice(1).split("").map(l=>`-${l}`);t.splice(s,1,...a),s--}else return}}if(n.pattern===void 0){let s=r.shift();if(s===void 0||s==="")return;n.pattern=s}if(!(r.length>1))return n.path=r[0],n}function Du(e,t="codeindex"){let n=e.trim();if(!n||Iy.test(n))return;let r=Lu(n);if(!r||r.length<2)return;let[s,...o]=r;if(s===void 0||!Ny.has(s))return;let a=Oy(s,o);if(!a||a.pattern===void 0)return;let l=a.pattern;if(!a.recursive)return;let c=a.path,d=[t,"grep",Ni(l)];c&&c!=="."&&c!=="./"&&d.push("--scope",Ni(c.replace(/\/+$/,""))),a.ignoreCase&&d.push("--ignore-case");for(let f of a.includes)d.push("--include",Ni(f));return d.join(" ")}var Iy,Ny,Ka=F(()=>{"use strict";k();Iy=/[|&;<>`\n\r$(){}]/,Ny=new Set(["grep","egrep","rg","ripgrep"])});k();k();Xe();Ae();Ft();Ft();sr();Os();Hn();ji();_s();k();oe();var kp=new Set([".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs",".vue",".svelte",".astro",".py",".rb",".go",".rs",".java",".kt",".kts",".php",".c",".cc",".cpp",".h",".hpp",".cs",".swift",".scala",".clj",".ex",".exs",".dart",".lua",".sh",".bash",".zig",".elm",".hcl",".tf",".tfvars",".sol",".hh",".sc",".pyi",".rake",".cxx"]),Ep=new Set([".css",".scss",".sass",".less",".styl",".pcss"]),vp=new Set([".md",".mdx",".rst",".adoc",".txt"]),Rp=new Set([".json",".yaml",".yml",".toml",".csv",".xml",".env"]),Mp=new Set([".png",".jpg",".jpeg",".gif",".webp",".avif",".ico",".bmp",".tiff",".svg",".pdf",".woff",".woff2",".ttf",".otf",".eot",".mp3",".mp4",".mov",".avi",".webm",".zip",".gz",".tar",".rar",".7z",".wasm",".so",".dylib",".dll",".exe",".bin",".class",".jar",".pyc",".node"]),Cp=["locales","locale","i18n","lang","langs","translations","messages"],Ap=new Set([".json",".yaml",".yml",".po",".properties"]),Tp=["__tests__","test","tests","spec","e2e","__mocks__"],Ip=["migrations","entities","models"],Np=new Set(["package.json","tsconfig.json","dockerfile","makefile","pyproject.toml","cargo.toml","go.mod","requirements.txt","gemfile","composer.json","pubspec.yaml"]);function Op(e,t){let n=e.toLowerCase(),r=ke(n),s=n.split("/"),o=a=>a.some(l=>s.includes(l));return o(Cp)&&Ap.has(t)?"i18n":t===".prisma"||t===".sql"||t===".graphql"||t===".gql"||r.startsWith("schema.")||r==="models.py"||o(Ip)?"schema":n.includes(".test.")||n.includes(".spec.")||o(Tp)?"test":Np.has(r)||r.endsWith(".config.js")||r.endsWith(".config.ts")||r.endsWith(".config.mjs")||r.startsWith(".eslintrc")||r.startsWith(".prettierrc")||r.startsWith(".env")||r.startsWith("docker-compose")?"config":vp.has(t)?"doc":Ep.has(t)?"style":kp.has(t)?"code":Mp.has(t)?"asset":Rp.has(t)?"data":"other"}yn();Ao();eo();nt();vo();k();xe();oe();po();nt();Y();var Xc=new Map;function Zc(e,t){let n=Xc.get(e);if(n!==void 0)return n;let r=null;for(let s of Qe().dirs){let o=I(s,`${e}.tags.scm`);if(H(o)){try{r=new Ec(t,te(o,"utf8"))}catch{r=null}break}}return Xc.set(e,r),r}function Fp(e){if(!Qe().dirs.some(r=>H(I(r,`${e}.tags.scm`))))return{present:!1,compiled:!1};let n=_o(e);return n?{present:!0,compiled:Zc(e,n)!==null}:{present:!0,compiled:!1}}function Pp(e,t){let n=Yn(e);if(!n)return[];let r=_o(n),s=vs(n);if(!r||!s)return[];let o=Zc(n,r);if(!o)return[];let a=null;try{if(a=s.parse(t),!a)return[];let l=[],c=new Set;for(let d of o.matches(a.rootNode)){let f,u,m=0;for(let g of d.captures)g.name==="name"?(f=g.node.text,m=g.node.startPosition.row+1):g.name.startsWith("definition.")&&(u=g.name.slice(11));if(!f||!u)continue;let p=`${u} ${f} ${m}`;c.has(p)||(c.add(p),l.push({kind:u,name:f,line:m}))}return l.sort((d,f)=>d.line-f.line||M(d.name,f.name)||M(d.kind,f.kind))}catch{return[]}finally{a?.delete()}}nt();nt();k();cs();xe();oe();k();function Yc(){throw new Error("zlib.gunzipSync is not available in the browser build (use DecompressionStream at an async boundary)")}Xe();var Lo=`https://github.com/maxgfr/codeindex/releases/download/v${fe}/grammars-${fe}.tar.gz`;function Fs(){let e=R.env.CODEINDEX_GRAMMARS_URL;return e&&e.trim()?{url:e.trim()}:{url:Lo,sha256Url:`${Lo}.sha256`}}async function Qc(e,t){let n=await fetch(e);if(!n.ok)throw new Error(`HTTP ${n.status} from ${e}`);let r=T.from(await n.arrayBuffer());if(t){let s=hn("sha256").update(r).digest("hex");if(s!==t)throw new Error(`sha256 mismatch: expected ${t}, got ${s}`)}return r}function ed(e){return T.isBuffer(e)?e:T.from(e.buffer,e.byteOffset,e.byteLength)}async function td(e){let t=await fetch(e);if(!t.ok)throw new Error(`HTTP ${t.status} from ${e}`);let r=((await t.text()).trim().split(/\s+/)[0]??"").toLowerCase();if(!/^[0-9a-f]{64}$/.test(r))throw new Error(`invalid sha256 sidecar at ${e}`);return r}function $o(e,t,n){let r=e.subarray(t,t+n),s=r.indexOf(0);return r.toString("utf8",0,s===-1?r.length:s)}function*$p(e){let t=0;for(;t+512<=e.length;){let n=e.subarray(t,t+512),r=!0;for(let f=0;f<512;f++)if(n[f]!==0){r=!1;break}if(r)break;let s=$o(n,0,100),o=$o(n,345,155),a=$o(n,124,12).trim(),l=a?parseInt(a,8):0,c=String.fromCharCode(n[156]??0);t+=512;let d=e.subarray(t,t+l);t+=Math.ceil(l/512)*512,yield{name:o?`${o}/${s}`:s,type:c,data:d}}}function Lp(e){if(!e||e.includes("\0")||e.startsWith("/")||e.startsWith("\\")||/^[A-Za-z]:/.test(e))return null;let t=[];for(let n of e.split(/[/\\]/))if(!(n===""||n===".")){if(n==="..")return null;t.push(n)}return t.length?t.join("/"):null}function nd(e,t){let n=Ne(t),r=[];for(let s of $p(ed(e))){if(s.type!=="0"&&s.type!=="\0")continue;let o=Lp(s.name);if(o===null)throw new Error(`refusing unsafe tar entry: ${s.name}`);let a=Ne(t,o);if(a!==n&&!a.startsWith(n+"/"))throw new Error(`tar entry escapes destination: ${s.name}`);gt(_e(a),{recursive:!0}),Re(a,s.data),r.push(o)}return r}function rd(e,t){let n=ed(e),r=n.length>=2&&n[0]===31&&n[1]===139?Yc(n):n;return nd(r,t)}function Dp(e,t,n,r,s=Dn,o=qe){let a=_e(t),l=Ln(I(a,".grammars-swap-")),c=I(l,"previous-cache"),d=I(l,"previous-marker"),f=I(l,"next-marker"),u=!1,m=!1,p=!1,g=!1;try{r&&Re(f,r+` +`),H(t)&&(s(t,c),u=!0),H(n)&&(s(n,d),m=!0),s(e,t),p=!0,r&&(s(f,n),g=!0)}catch(y){let h=[],S=_=>{try{_()}catch(E){h.push(E)}};if(g&&H(n)&&S(()=>qe(n,{force:!0})),p&&H(t)&&S(()=>qe(t,{recursive:!0,force:!0})),m&&H(d)&&S(()=>s(d,n)),u&&H(c)&&S(()=>s(c,t)),h.length===0)try{qe(l,{recursive:!0,force:!0})}catch{}if(h.length>0){let _=h[0];throw new Error(`${y instanceof Error?y.message:String(y)}; rollback failed: ${_ instanceof Error?_.message:String(_)} (backup preserved at ${l})`)}throw y}try{o(l,{recursive:!0,force:!0})}catch{}}async function ir(e,t={}){let n=t.onNote??(()=>{}),r=Fs(),s;if(r.sha256Url)try{s=await td(r.sha256Url)}catch(d){n(`codeindex: could not fetch checksum (${d instanceof Error?d.message:String(d)}) \u2014 proceeding unverified +`)}let o=I(e,"web-tree-sitter.wasm"),a=I(_e(e),`${fe}.sha256`);if(H(o)&&s&&H(a)){let d="";try{d=te(a,"utf8").trim()}catch{}if(d===s)return{ok:!0,status:"up-to-date",cacheDir:e,message:`codeindex: grammars already present at ${e} (up to date) `}}n(`codeindex: fetching grammars from ${r.url} \u2192 ${e} -`);let l;try{l=await Uc(r.url,s)}catch(d){return{ok:!1,status:"failed",cacheDir:e,message:`codeindex: pull failed \u2014 ${d instanceof Error?d.message:String(d)} (nothing written) -`}}let c;try{if(ft(Se(e),{recursive:!0}),c=Xa(I(Se(e),".grammars-tmp-")),zc(l,c),!z(I(c,"web-tree-sitter.wasm")))throw new Error("archive is missing web-tree-sitter.wasm");z(e)&&zt(e,{recursive:!0,force:!0}),Si(c,e),c=void 0,s&&Re(a,s+` -`)}catch(d){if(c)try{zt(c,{recursive:!0,force:!0})}catch{}return{ok:!1,status:"failed",cacheDir:e,message:`codeindex: pull failed \u2014 ${d instanceof Error?d.message:String(d)} (nothing written) +`);let l;try{l=await Qc(r.url,s)}catch(d){return{ok:!1,status:"failed",cacheDir:e,message:`codeindex: pull failed \u2014 ${d instanceof Error?d.message:String(d)} (nothing written) +`}}let c;try{if(gt(_e(e),{recursive:!0}),c=Ln(I(_e(e),".grammars-tmp-")),rd(l,c),!H(I(c,"web-tree-sitter.wasm")))throw new Error("archive is missing web-tree-sitter.wasm");Dp(c,e,a,s),c=void 0}catch(d){if(c)try{qe(c,{recursive:!0,force:!0})}catch{}return{ok:!1,status:"failed",cacheDir:e,message:`codeindex: pull failed \u2014 ${d instanceof Error?d.message:String(d)} (nothing written) `}}return{ok:!0,status:"pulled",cacheDir:e,message:`codeindex: grammars extracted \u2192 ${e} -`}}S();Qe();async function xp(e={}){let t=e.label??"codeindex",n=[],r=u=>{n.push(u),e.onNote?e.onNote(u):v.stderr.write(u)},s=v.env.CODEINDEX_NO_GRAMMARS_PULL,o=(e.pull??!0)&&!(s&&s.trim()&&s!=="0"),a=[...e.keys??oo()],l=!1;if(Xe().tier==="none"&&o){r(`${t}: tree-sitter grammars not found locally \u2014 pulling them into the shared cache (once per machine)\u2026 -`);let u=await nr(yn(),{onNote:r});r(u.message),l=u.ok&&u.status==="pulled"}await Ze(a);let c=Xe().tier,d=a.some(u=>Ye(u));return d||r(`${t}: no tree-sitter grammars available (offline?) \u2014 extracting with the regex tier, so symbols and call sites are less precise. Run \`codeindex grammars pull\` once online to enable AST precision. -`),{tier:c,ready:d,pulled:l,notes:n}}vs();Cs();Ls();wn();Kt();dr();Zt();js();Zo();Ws();br();Ps();ia();kn();oa();or();zs();S();ie();qe();Te();K();var xt=class{buf;len=0;constructor(t=64){this.buf=new Uint8Array(t)}get length(){return this.len}grow(t){if(this.len+t<=this.buf.length)return;let n=this.buf.length*2||64;for(;n127;)e.push(t&127|128),t=Math.floor(t/128);e.push(t&127)}function kd(e,t,n){qs(e,t*8+n)}function Gs(e,t,n){kd(e,t,0),qs(e,n)}function Ed(e,t,n){kd(e,t,2),qs(e,n.length),e.pushAll(n)}function Tn(e,t,n){Ed(e,t,n.view())}function wt(e,t,n){Ed(e,t,R_.encode(n))}function M_(e,t,n){let r=new xt(n.length*2);for(let s of n)qs(r,s);Tn(e,t,r)}var C_=1,A_=2,T_=2,I_=3,N_=4,O_=1,F_=2,P_=1,$_=2,D_=3,L_=4,j_=6,U_=1,W_=2,B_=3,H_=1,z_=5,G_=6,q_=8,V_=1,J_=1,K_=2,X_={function:17,method:26,class:7,interface:21,enum:11,struct:49,trait:53,type:54,const:8,var:61},vd="codeindex . . . ",Z_=/^[A-Za-z0-9_+\-$]+$/;function Rd(e){return Z_.test(e)?e:"`"+e.replace(/`/g,"``")+"`"}function Md(e){return"`"+e.replace(/`/g,"``")+"`/"}function Cd(e){return Rd(e)+"#"}var Y_=new Set(["class","interface","enum","struct","trait","type"]),Q_=new Set(["function","method","def"]);function eh(e){return Y_.has(e)?"#":Q_.has(e)?"().":"."}function th(e,t){let n=vd+Md(e);return t.parent&&(n+=Cd(t.parent)),n+Rd(t.name)+eh(t.kind)}function nh(e,t){return vd+Md(e)+Cd(t)}function rh(e,t,n){if(!n.has(e))return n.add(e),e;for(let r=0;;r++){let s=r===0?String(t):`${t}_${r}`,o=`${e}(${s})`;if(!n.has(o))return n.add(o),o}}function xd(e){return e==="typescript"||e==="javascript"?"js":e==="c"||e==="cpp"?"c":e}var sh=new Set(["reexport","reexport-all","default"]);function Sd(e){return e>=48&&e<=57||e>=65&&e<=90||e>=97&&e<=122||e===95||e===36}function ih(e,t){if(!t)return null;let n=/^[A-Za-z_$][\w$]*$/.test(t),r=0;for(;;){let s=e.indexOf(t,r);if(s<0)return null;if(!n)return[s,s+t.length];let o=s>0?e.charCodeAt(s-1):-1,a=s+t.length,l=am.kind==="code"&&m.symbols.length>0),o=new Map,a=new Map;for(let m of s){let g=new Set,h=[];for(let _ of m.symbols){let y=rh(th(m.rel,_),_.line,g);if(h.push({sym:_,symbolString:y}),_.exported&&!sh.has(_.kind)){let x=a.get(_.name);x||a.set(_.name,x=[]),x.push({symbolString:y,family:xd(_.lang)})}}o.set(m.rel,h)}let l=(m,g)=>{let h=a.get(m);if(!h||h.length!==1)return;let _=h[0];return _.family===g?_.symbolString:void 0},c=[];for(let m of s){let h=G(I(e.root,m.rel)).split(` -`).map(N=>N.endsWith("\r")?N.slice(0,-1):N),_=(N,W)=>{let q=h[N-1];if(q===void 0)return[N-1,0,0];let X=ih(q,W);return X?[N-1,X[0],X[1]]:[N-1,0,q.length]},y=o.get(m.rel),x=[];for(let{sym:N,symbolString:W}of y)x.push({range:_(N.line,N.name),symbol:W,roles:J_});let E=xd(m.lang);for(let N of m.calls??[]){let W=l(N.name,E);W&&x.push({range:_(N.line,N.name),symbol:W,roles:0})}x.sort((N,W)=>N.range[0]-W.range[0]||N.range[1]-W.range[1]||N.range[2]-W.range[2]||N.roles-W.roles||R(N.symbol,W.symbol));let w=new Set,k=y.map(({sym:N,symbolString:W})=>({symbol:W,displayName:N.name,kind:X_[N.kind],enclosing:N.parent?nh(m.rel,N.parent):void 0})).sort((N,W)=>R(N.symbol,W.symbol)),C=new xt(1024);wt(C,P_,m.rel);let A=new xt(64);for(let N of x){let W=`${N.range.join(",")} ${N.roles} ${N.symbol}`;w.has(W)||(w.add(W),A.reset(),M_(A,U_,N.range),wt(A,W_,N.symbol),N.roles!==0&&Gs(A,B_,N.roles),Tn(C,$_,A))}let F=new xt(64);for(let N of k)F.reset(),wt(F,H_,N.symbol),N.kind!==void 0&&Gs(F,z_,N.kind),wt(F,G_,N.displayName),N.enclosing&&wt(F,q_,N.enclosing),Tn(C,D_,F);wt(C,L_,m.lang),Gs(C,j_,K_),c.push(C)}let d=new xt;wt(d,O_,"codeindex"),wt(d,F_,r);let u=new xt;Tn(u,T_,d),wt(u,I_,n),Gs(u,N_,V_);let f=0;for(let m of c)f+=m.length;let p=new xt(f+u.length+16);Tn(p,C_,u);for(let m of c)Tn(p,A_,m);return p.toUint8Array()}Vs();Gt();Js();vn();rn();vr();In();Zs();Ys();pa();si();wa();ya();Ea();_a();Sa();ii();Ir();Ar();oi();wr();gr();ai();S();K();var Yh=new Set(["import","use","call"]);function lu(e){let t=e.slice().sort((s,o)=>s-o),n=t.length,r=n===0?0:t[Math.min(n-1,Math.floor(.99*n))];return Math.max(50,r)}function cu(e,t,n=1/0){let r=new Map;for(let l of e){if(l.dangling||!Yh.has(l.kind))continue;let c=r.get(l.to);c||r.set(l.to,c=[]),c.push(l)}let s=new Map,o=new Set(t),a=[...t];for(let l=1;l<=n&&a.length;l++){let c=[];for(let d of a)for(let u of(r.get(d)??[]).slice().sort((f,p)=>R(f.from,p.from)))o.has(u.from)||(o.add(u.from),s.set(u.from,l),c.push(u.from));a=c}return s}function Dr(e,t,n=1/0){let r=new Map(e.files.map(u=>[u.rel,u.module])),s=e.modules.find(u=>u.slug===t),o=s?void 0:e.files.find(u=>u.rel===t);if(!s&&!o)return;let a=s?s.members:[o.rel],c=[...cu(e.fileEdges,a,n).entries()].map(([u,f])=>({rel:u,module:r.get(u)??"root",depth:f})).sort((u,f)=>u.depth-f.depth||R(u.rel,f.rel)),d=[...new Set(c.map(u=>u.module).filter(u=>u!==t))].sort(R);return{target:t,scope:s?"module":"file",seeds:a,files:c,modules:d}}function au(e,t,n,r){let s=new Map,o=new Map,a=new Map;for(let f of e)f.dangling||r&&!r.has(f.kind)||((s.get(f.from)??s.set(f.from,[]).get(f.from)).push(f),(o.get(f.to)??o.set(f.to,[]).get(f.to)).push(f),a.set(f.from,(a.get(f.from)??0)+1),a.set(f.to,(a.get(f.to)??0)+1));let l=lu([...a.values()]),c=new Set([t]),d=[],u=[t];for(let f=1;f<=n;f++){let p=[];for(let m of u)if(!(m!==t&&(a.get(m)??0)>=l)){for(let g of(s.get(m)??[]).slice().sort((h,_)=>R(h.to,_.to)))c.has(g.to)||(d.push({node:g.to,direction:"out",kind:g.kind,weight:g.weight,depth:f,confidence:g.confidence}),c.add(g.to),p.push(g.to));for(let g of(o.get(m)??[]).slice().sort((h,_)=>R(h.from,_.from)))c.has(g.from)||(d.push({node:g.from,direction:"in",kind:g.kind,weight:g.weight,depth:f,confidence:g.confidence}),c.add(g.from),p.push(g.from))}u=p}return d}function Ca(e,t,n=1,r){let s=e.modules.find(a=>a.slug===t);if(s)return{target:t,scope:"module",links:au(e.moduleEdges,t,n,r),members:s.members};if(e.files.find(a=>a.rel===t))return{target:t,scope:"file",links:au(e.fileEdges,t,n,r)}}S();Gt();K();Te();Me();var kt={exportedChange:25,hubHigh:20,hubMed:10,blastHigh:20,blastMed:10,testGap:20,surprise:10,dangling:15},Qh=60,ey=30,ty=3,Aa=2;function du(e,t){let n=[],r=new Set,s=(a,l)=>{let c=`${a.name}:${a.line}`;r.has(c)||(r.add(c),n.push({name:a.name,kind:a.kind,exported:a.exported,line:a.line,...a.endLine!==void 0?{endLine:a.endLine}:{},...a.parent!==void 0?{parent:a.parent}:{},...l?{approx:!0}:{}}))},o=a=>(a.endLine??a.line)-a.line;for(let a of t){let l=e.filter(c=>c.line<=a.end&&(c.endLine??c.line)>=a.start);if(l.length){l.sort((c,d)=>o(c)-o(d)||d.line-c.line||R(c.name,d.name));for(let c of l)s(c,!1)}else{let c=e.filter(u=>u.line<=a.start&&u.endLine===void 0),d=c[c.length-1];d&&s(d,!0)}}return n}function ny(e,t){if(e.length<=1)return 0;let n=0;for(let r of e)r[w.rel,w])),a=new Map;if(t){for(let[w,k]of Object.entries(t.defs))for(let C of k){let A=a.get(C.file);A||a.set(C.file,A=[]),A.push({name:w,...C})}for(let w of a.values())w.sort((k,C)=>k.line-C.line||R(k.name,C.name))}let l=[],c=[],d=[];for(let w of[...n.files].sort((k,C)=>R(k.path,C.path))){let k={...w.oldPath!==void 0?{oldPath:w.oldPath}:{},...w.binary?{binary:!0}:{},...w.linesAdded!==void 0?{linesAdded:w.linesAdded}:{},...w.linesDeleted!==void 0?{linesDeleted:w.linesDeleted}:{}};if(w.status==="deleted"){l.push(w.path),d.push({path:w.path,status:w.status,...k,hunks:[],symbols:[]});continue}let C=o.get(w.path);if(!C){c.push(w.path);continue}let A=n.hunks.get(w.path)??[];!A.length&&w.status==="added"&&!w.binary&&(A=[{start:1,end:Math.max(C.lines,1)}]);let F=w.binary?[]:du(a.get(w.path)??[],A);d.push({path:w.path,status:w.status,...k,module:C.module,hunks:A.map(N=>({start:N.start,end:N.end})),symbols:F})}let u=new Set(d.filter(w=>w.status!=="deleted").map(w=>w.path)),f=e.fileEdges.filter(w=>w.dangling&&(w.kind==="import"||w.kind==="doc-link")&&u.has(w.from)).map(w=>({from:w.from,spec:w.to,reason:w.reason??"unknown"})).sort((w,k)=>R(w.from,k.from)||R(w.spec,k.spec)),p=(w,k)=>{if(!k.startsWith("."))return!1;let C=w.split("/").slice(0,-1);for(let A of k.split("/"))A==="."||A===""||(A===".."?C.pop():C.push(A));return C.some(A=>Pn.has(A))},m=new Map;for(let w of d){if(w.status==="deleted"||!w.module)continue;let k=m.get(w.module);k||m.set(w.module,k=[]),k.push(w)}let g=new Set;for(let w of e.files)w.fileKind==="code"&&!w.testFile&&g.add(w.module);let h=e.modules.some(w=>w.pagerank!==void 0),_=w=>h?w.pagerank??0:w.degIn+w.degOut,y=e.modules.map(_),x=h?"pagerank":"degree",E=[];for(let w of[...m.keys()].sort(R)){let k=e.modules.find(L=>L.slug===w);if(!k)continue;let C=m.get(w),A=[],F=0,N=[...new Set(C.flatMap(L=>L.symbols.filter(de=>de.exported).map(de=>de.name)))].sort(R);if(N.length){F+=kt.exportedChange;let L=N.slice(0,3).join(", ")+(N.length>3?", \u2026":"");A.push(N.length===1?`exported symbol ${L} changed`:`exported symbols ${L} changed`)}let W=ny(y,_(k));W>=.9?(F+=kt.hubHigh,A.push(`${x} p${Math.round(W*100)} hub`)):W>=.75&&(F+=kt.hubMed,A.push(`${x} p${Math.round(W*100)} hub`));let q=new Map,X=new Set;for(let L of C){let de=Dr(e,L.path,r);if(de){for(let J of de.files){let ce=q.get(J.rel);(ce===void 0||J.depthL===1).length,transitiveFiles:B,modules:[...X].sort(R)};B>=20||$.modules.length>=5?(F+=kt.blastHigh,A.push(`${B} dependent files across ${$.modules.length} modules (depth ${r})`)):B>=5&&(F+=kt.blastMed,A.push(`${B} dependent files across ${$.modules.length} modules (depth ${r})`));let V=k.tier<=1&&k.symbols>0&&g.has(w),oe=k.testedBy??[],ee=V?oe.length?{status:"covered",files:oe}:{status:"gap",files:[]}:{status:"n/a",files:[]};ee.status==="gap"&&(F+=kt.testGap,A.push("no test covers this module"));let le=(e.surprises??[]).find(L=>L.from===w||L.to===w);le&&(F+=kt.surprise,A.push(`cross-community edge to ${le.from===w?le.to:le.from} (surprising)`));let Ne=f.filter(L=>C.some(de=>de.path===L.from)&&!p(L.from,L.spec));if(Ne.length){F+=kt.dangling;let L=Ne[0],de=Ne.length>1?` (+${Ne.length-1} more)`:"";A.push(`dangling import "${L.spec}" in ${L.from}${de}`)}F=Math.min(100,F);let De=C.map(L=>L.path).sort(R),Z=C.flatMap(L=>L.symbols),Y=C.slice().sort((L,de)=>de.symbols.filter(J=>J.exported).length-L.symbols.filter(J=>J.exported).length||de.symbols.length-L.symbols.length||R(L.path,de.path)).slice(0,ty).map(L=>L.path);E.push({slug:w,path:k.path,score:F,bucket:F>=Qh?"HIGH":F>=ey?"MEDIUM":"LOW",reasons:A,changedFiles:De,changedSymbols:{total:new Set(Z.map(L=>`${L.name}:${L.line}`)).size,exported:new Set(Z.filter(L=>L.exported).map(L=>`${L.name}:${L.line}`)).size},impact:$,tests:ee,open:Y})}return E.sort((w,k)=>k.score-w.score||R(w.slug,k.slug)),{base:n.base,...e.commit!==void 0?{indexCommit:e.commit}:{},depth:r,changes:d,modules:E,dangling:f,deleted:l.sort(R),unindexed:c.sort(R),notes:s}}function Ta(e,t,n,r={}){if(!it("git"))return{error:"git is required for delta and was not found on PATH"};if(!Ni(e))return{error:`delta needs a git worktree \u2014 ${e} is not inside one`};let s=[],o;if(r.staged){let c=me("git",["-C",e,"rev-parse","HEAD"]);if(!c.ok)return{error:"cannot resolve HEAD \u2014 empty repository?"};o={ref:"HEAD",mergeBase:c.stdout.trim(),staged:!0}}else{let c=Oi(e,r.base);if("error"in c)return{error:c.error};c.note&&s.push(c.note),o={ref:c.ref,mergeBase:c.mergeBase,staged:!1}}let a=r.staged?{staged:!0}:{mergeBase:o.mergeBase},l=Fi(e,a);if(!r.staged){let c=new Set(l.map(d=>d.path));for(let d of rs(e))c.has(d)||l.push({path:d,status:"added"})}return uu(t,n,{files:l,hunks:Pi(e,a),base:o,notes:s},r.depth??Aa)}function Ia(e){let t=e.base.mergeBase.slice(0,7),n=`${e.base.staged?"staged vs ":""}${e.base.ref}`;if(!e.changes.length&&!e.unindexed.length)return`codeindex: no changes vs ${n} (merge-base ${t}) +`}}k();nt();async function jp(e={}){let t=e.label??"codeindex",n=[],r=f=>{n.push(f),e.onNote?e.onNote(f):R.stderr.write(f)},s=R.env.CODEINDEX_NO_GRAMMARS_PULL,o=(e.pull??!0)&&!(s&&s.trim()&&s!=="0"),a=[...e.keys??go()],l=!1;if(Qe().tier==="none"&&o){r(`${t}: tree-sitter grammars not found locally \u2014 pulling them into the shared cache (once per machine)\u2026 +`);let f=await ir(wn(),{onNote:r});r(f.message),l=f.ok&&f.status==="pulled"}await et(a);let c=Qe().tier,d=a.some(f=>tt(f));return d||r(`${t}: no tree-sitter grammars available (offline?) \u2014 extracting with the regex tier, so symbols and call sites are less precise. Run \`codeindex grammars pull\` once online to enable AST precision. +`),{tier:c,ready:d,pulled:l,notes:n}}Ps();Ds();Js();Sn();Xt();mr();Yt();Ks();la();Zs();Sr();qs();_a();vn();ha();cr();ei();k();oe();Xe();Ae();Y();var kt=class{buf;len=0;constructor(t=64){this.buf=new Uint8Array(t)}get length(){return this.len}grow(t){if(this.len+t<=this.buf.length)return;let n=this.buf.length*2||64;for(;n127;)e.push(t&127|128),t=Math.floor(t/128);e.push(t&127)}function jd(e,t,n){ni(e,t*8+n)}function ti(e,t,n){jd(e,t,0),ni(e,n)}function Wd(e,t,n){jd(e,t,2),ni(e,n.length),e.pushAll(n)}function Nn(e,t,n){Wd(e,t,n.view())}function St(e,t,n){Wd(e,t,q_.encode(n))}function G_(e,t,n){let r=new kt(n.length*2);for(let s of n)ni(r,s);Nn(e,t,r)}var V_=1,J_=2,K_=2,X_=3,Z_=4,Y_=1,Q_=2,eh=1,th=2,nh=3,rh=4,sh=6,ih=1,oh=2,ah=3,lh=1,ch=5,dh=6,uh=8,fh=1,mh=1,ph=2,gh={function:17,method:26,class:7,interface:21,enum:11,struct:49,trait:53,type:54,const:8,var:61},Ud="codeindex . . . ",_h=/^[A-Za-z0-9_+\-$]+$/;function Bd(e){return _h.test(e)?e:"`"+e.replace(/`/g,"``")+"`"}function zd(e){return"`"+e.replace(/`/g,"``")+"`/"}function Hd(e){return Bd(e)+"#"}var hh=new Set(["class","interface","enum","struct","trait","type"]),yh=new Set(["function","method","def"]);function bh(e){return hh.has(e)?"#":yh.has(e)?"().":"."}function wh(e,t){let n=Ud+zd(e);return t.parent&&(n+=Hd(t.parent)),n+Bd(t.name)+bh(t.kind)}function xh(e,t){return Ud+zd(e)+Hd(t)}function Sh(e,t,n){if(!n.has(e))return n.add(e),e;for(let r=0;;r++){let s=r===0?String(t):`${t}_${r}`,o=`${e}(${s})`;if(!n.has(o))return n.add(o),o}}function Ld(e){return e==="typescript"||e==="javascript"?"js":e==="c"||e==="cpp"?"c":e}var kh=new Set(["reexport","reexport-all","default"]);function Dd(e){return e>=48&&e<=57||e>=65&&e<=90||e>=97&&e<=122||e===95||e===36}function Eh(e,t){if(!t)return null;let n=/^[A-Za-z_$][\w$]*$/.test(t),r=0;for(;;){let s=e.indexOf(t,r);if(s<0)return null;if(!n)return[s,s+t.length];let o=s>0?e.charCodeAt(s-1):-1,a=s+t.length,l=ap.kind==="code"&&p.symbols.length>0),o=new Map,a=new Map;for(let p of s){let g=new Set,y=[];for(let h of p.symbols){let S=Sh(wh(p.rel,h),h.line,g);if(y.push({sym:h,symbolString:S}),h.exported&&!kh.has(h.kind)){let _=a.get(h.name);_||a.set(h.name,_=[]),_.push({symbolString:S,family:Ld(h.lang)})}}o.set(p.rel,y)}let l=(p,g)=>{let y=a.get(p);if(!y||y.length!==1)return;let h=y[0];return h.family===g?h.symbolString:void 0},c=[];for(let p of s){let y=G(I(e.root,p.rel)).split(` +`).map(N=>N.endsWith("\r")?N.slice(0,-1):N),h=(N,U)=>{let le=y[N-1];if(le===void 0)return[N-1,0,0];let V=Eh(le,U);return V?[N-1,V[0],V[1]]:[N-1,0,le.length]},S=o.get(p.rel),_=[];for(let{sym:N,symbolString:U}of S)_.push({range:h(N.line,N.name),symbol:U,roles:mh});let E=Ld(p.lang);for(let N of p.calls??[]){let U=l(N.name,E);U&&_.push({range:h(N.line,N.name),symbol:U,roles:0})}_.sort((N,U)=>N.range[0]-U.range[0]||N.range[1]-U.range[1]||N.range[2]-U.range[2]||N.roles-U.roles||M(N.symbol,U.symbol));let b=new Set,x=S.map(({sym:N,symbolString:U})=>({symbol:U,displayName:N.name,kind:gh[N.kind],enclosing:N.parent?xh(p.rel,N.parent):void 0})).sort((N,U)=>M(N.symbol,U.symbol)),v=new kt(1024);St(v,eh,p.rel);let A=new kt(64);for(let N of _){let U=`${N.range.join(",")} ${N.roles} ${N.symbol}`;b.has(U)||(b.add(U),A.reset(),G_(A,ih,N.range),St(A,oh,N.symbol),N.roles!==0&&ti(A,ah,N.roles),Nn(v,th,A))}let O=new kt(64);for(let N of x)O.reset(),St(O,lh,N.symbol),N.kind!==void 0&&ti(O,ch,N.kind),St(O,dh,N.displayName),N.enclosing&&St(O,uh,N.enclosing),Nn(v,nh,O);St(v,rh,p.lang),ti(v,sh,ph),c.push(v)}let d=new kt;St(d,Y_,"codeindex"),St(d,Q_,r);let f=new kt;Nn(f,K_,d),St(f,X_,n),ti(f,Z_,fh);let u=0;for(let p of c)u+=p.length;let m=new kt(u+f.length+16);Nn(m,V_,f);for(let p of c)Nn(m,J_,p);return m.toUint8Array()}ri();Gt();si();Mn();sn();Cr();On();ai();li();Ea();pi();Ta();Ca();Fa();Ra();Na();gi();Fr();Nr();_i();kr();yr();hi();k();Y();var by=new Set(["import","use","call"]);function ku(e){let t=e.slice().sort((s,o)=>s-o),n=t.length,r=n===0?0:t[Math.min(n-1,Math.floor(.99*n))];return Math.max(50,r)}function Eu(e,t,n=1/0){let r=new Map;for(let l of e){if(l.dangling||!by.has(l.kind))continue;let c=r.get(l.to);c||r.set(l.to,c=[]),c.push(l)}let s=new Map,o=new Set(t),a=[...t];for(let l=1;l<=n&&a.length;l++){let c=[];for(let d of a)for(let f of(r.get(d)??[]).slice().sort((u,m)=>M(u.from,m.from)))o.has(f.from)||(o.add(f.from),s.set(f.from,l),c.push(f.from));a=c}return s}function Wr(e,t,n=1/0){let r=new Map(e.files.map(f=>[f.rel,f.module])),s=e.modules.find(f=>f.slug===t),o=s?void 0:e.files.find(f=>f.rel===t);if(!s&&!o)return;let a=s?s.members:[o.rel],c=[...Eu(e.fileEdges,a,n).entries()].map(([f,u])=>({rel:f,module:r.get(f)??"root",depth:u})).sort((f,u)=>f.depth-u.depth||M(f.rel,u.rel)),d=[...new Set(c.map(f=>f.module).filter(f=>f!==t))].sort(M);return{target:t,scope:s?"module":"file",seeds:a,files:c,modules:d}}function Su(e,t,n,r){let s=new Map,o=new Map,a=new Map;for(let u of e)u.dangling||r&&!r.has(u.kind)||((s.get(u.from)??s.set(u.from,[]).get(u.from)).push(u),(o.get(u.to)??o.set(u.to,[]).get(u.to)).push(u),a.set(u.from,(a.get(u.from)??0)+1),a.set(u.to,(a.get(u.to)??0)+1));let l=ku([...a.values()]),c=new Set([t]),d=[],f=[t];for(let u=1;u<=n;u++){let m=[];for(let p of f)if(!(p!==t&&(a.get(p)??0)>=l)){for(let g of(s.get(p)??[]).slice().sort((y,h)=>M(y.to,h.to)))c.has(g.to)||(d.push({node:g.to,direction:"out",kind:g.kind,weight:g.weight,depth:u,confidence:g.confidence}),c.add(g.to),m.push(g.to));for(let g of(o.get(p)??[]).slice().sort((y,h)=>M(y.from,h.from)))c.has(g.from)||(d.push({node:g.from,direction:"in",kind:g.kind,weight:g.weight,depth:u,confidence:g.confidence}),c.add(g.from),m.push(g.from))}f=m}return d}function Da(e,t,n=1,r){let s=e.modules.find(a=>a.slug===t);if(s)return{target:t,scope:"module",links:Su(e.moduleEdges,t,n,r),members:s.members};if(e.files.find(a=>a.rel===t))return{target:t,scope:"file",links:Su(e.fileEdges,t,n,r)}}k();Gt();Y();Ae();Ce();var Rt={exportedChange:25,hubHigh:20,hubMed:10,blastHigh:20,blastMed:10,testGap:20,surprise:10,dangling:15},wy=60,xy=30,Sy=3,ja=2;function vu(e,t){let n=[],r=new Set,s=(a,l)=>{let c=`${a.name}:${a.line}`;r.has(c)||(r.add(c),n.push({name:a.name,kind:a.kind,exported:a.exported,line:a.line,...a.endLine!==void 0?{endLine:a.endLine}:{},...a.parent!==void 0?{parent:a.parent}:{},...l?{approx:!0}:{}}))},o=a=>(a.endLine??a.line)-a.line;for(let a of t){let l=e.filter(c=>c.line<=a.end&&(c.endLine??c.line)>=a.start);if(l.length){l.sort((c,d)=>o(c)-o(d)||d.line-c.line||M(c.name,d.name));for(let c of l)s(c,!1)}else{let c=e.filter(f=>f.line<=a.start&&f.endLine===void 0),d=c[c.length-1];d&&s(d,!0)}}return n}function ky(e,t){if(e.length<=1)return 0;let n=0;for(let r of e)r[b.rel,b])),a=new Map;if(t){for(let[b,x]of Object.entries(t.defs))for(let v of x){let A=a.get(v.file);A||a.set(v.file,A=[]),A.push({name:b,...v})}for(let b of a.values())b.sort((x,v)=>x.line-v.line||M(x.name,v.name))}let l=[],c=[],d=[];for(let b of[...n.files].sort((x,v)=>M(x.path,v.path))){let x={...b.oldPath!==void 0?{oldPath:b.oldPath}:{},...b.binary?{binary:!0}:{},...b.linesAdded!==void 0?{linesAdded:b.linesAdded}:{},...b.linesDeleted!==void 0?{linesDeleted:b.linesDeleted}:{}};if(b.status==="deleted"){l.push(b.path),d.push({path:b.path,status:b.status,...x,hunks:[],symbols:[]});continue}let v=o.get(b.path);if(!v){c.push(b.path);continue}let A=n.hunks.get(b.path)??[];!A.length&&b.status==="added"&&!b.binary&&(A=[{start:1,end:Math.max(v.lines,1)}]);let O=b.binary?[]:vu(a.get(b.path)??[],A);d.push({path:b.path,status:b.status,...x,module:v.module,hunks:A.map(N=>({start:N.start,end:N.end})),symbols:O})}let f=new Set(d.filter(b=>b.status!=="deleted").map(b=>b.path)),u=e.fileEdges.filter(b=>b.dangling&&(b.kind==="import"||b.kind==="doc-link")&&f.has(b.from)).map(b=>({from:b.from,spec:b.to,reason:b.reason??"unknown"})).sort((b,x)=>M(b.from,x.from)||M(b.spec,x.spec)),m=(b,x)=>{if(!x.startsWith("."))return!1;let v=b.split("/").slice(0,-1);for(let A of x.split("/"))A==="."||A===""||(A===".."?v.pop():v.push(A));return v.some(A=>qt.has(A))},p=new Map;for(let b of d){if(b.status==="deleted"||!b.module)continue;let x=p.get(b.module);x||p.set(b.module,x=[]),x.push(b)}let g=new Set;for(let b of e.files)b.fileKind==="code"&&!b.testFile&&g.add(b.module);let y=e.modules.some(b=>b.pagerank!==void 0),h=b=>y?b.pagerank??0:b.degIn+b.degOut,S=e.modules.map(h),_=y?"pagerank":"degree",E=[];for(let b of[...p.keys()].sort(M)){let x=e.modules.find(L=>L.slug===b);if(!x)continue;let v=p.get(b),A=[],O=0,N=[...new Set(v.flatMap(L=>L.symbols.filter(de=>de.exported).map(de=>de.name)))].sort(M);if(N.length){O+=Rt.exportedChange;let L=N.slice(0,3).join(", ")+(N.length>3?", \u2026":"");A.push(N.length===1?`exported symbol ${L} changed`:`exported symbols ${L} changed`)}let U=ky(S,h(x));U>=.9?(O+=Rt.hubHigh,A.push(`${_} p${Math.round(U*100)} hub`)):U>=.75&&(O+=Rt.hubMed,A.push(`${_} p${Math.round(U*100)} hub`));let le=new Map,V=new Set;for(let L of v){let de=Wr(e,L.path,r);if(de){for(let K of de.files){let ce=le.get(K.rel);(ce===void 0||K.depthL===1).length,transitiveFiles:z,modules:[...V].sort(M)};z>=20||j.modules.length>=5?(O+=Rt.blastHigh,A.push(`${z} dependent files across ${j.modules.length} modules (depth ${r})`)):z>=5&&(O+=Rt.blastMed,A.push(`${z} dependent files across ${j.modules.length} modules (depth ${r})`));let B=x.tier<=1&&x.symbols>0&&g.has(b),re=x.testedBy??[],J=B?re.length?{status:"covered",files:re}:{status:"gap",files:[]}:{status:"n/a",files:[]};J.status==="gap"&&(O+=Rt.testGap,A.push("no test covers this module"));let ee=(e.surprises??[]).find(L=>L.from===b||L.to===b);ee&&(O+=Rt.surprise,A.push(`cross-community edge to ${ee.from===b?ee.to:ee.from} (surprising)`));let be=u.filter(L=>v.some(de=>de.path===L.from)&&!m(L.from,L.spec));if(be.length){O+=Rt.dangling;let L=be[0],de=be.length>1?` (+${be.length-1} more)`:"";A.push(`dangling import "${L.spec}" in ${L.from}${de}`)}O=Math.min(100,O);let Ie=v.map(L=>L.path).sort(M),X=v.flatMap(L=>L.symbols),Z=v.slice().sort((L,de)=>de.symbols.filter(K=>K.exported).length-L.symbols.filter(K=>K.exported).length||de.symbols.length-L.symbols.length||M(L.path,de.path)).slice(0,Sy).map(L=>L.path);E.push({slug:b,path:x.path,score:O,bucket:O>=wy?"HIGH":O>=xy?"MEDIUM":"LOW",reasons:A,changedFiles:Ie,changedSymbols:{total:new Set(X.map(L=>`${L.name}:${L.line}`)).size,exported:new Set(X.filter(L=>L.exported).map(L=>`${L.name}:${L.line}`)).size},impact:j,tests:J,open:Z})}return E.sort((b,x)=>x.score-b.score||M(b.slug,x.slug)),{base:n.base,...e.commit!==void 0?{indexCommit:e.commit}:{},depth:r,changes:d,modules:E,dangling:u,deleted:l.sort(M),unindexed:c.sort(M),notes:s}}function Wa(e,t,n,r={}){if(!at("git"))return{error:"git is required for delta and was not found on PATH"};if(!zi(e))return{error:`delta needs a git worktree \u2014 ${e} is not inside one`};let s=[],o;if(r.staged){let c=pe("git",["-C",e,"rev-parse","HEAD"]);if(!c.ok)return{error:"cannot resolve HEAD \u2014 empty repository?"};o={ref:"HEAD",mergeBase:c.stdout.trim(),staged:!0}}else{let c=Hi(e,r.base);if("error"in c)return{error:c.error};c.note&&s.push(c.note),o={ref:c.ref,mergeBase:c.mergeBase,staged:!1}}let a=r.staged?{staged:!0}:{mergeBase:o.mergeBase},l=qi(e,a);if(!r.staged){let c=new Set(l.map(d=>d.path));for(let d of ls(e))c.has(d)||l.push({path:d,status:"added"})}return Ru(t,n,{files:l,hunks:Gi(e,a),base:o,notes:s},r.depth??ja)}function Ua(e){let t=e.base.mergeBase.slice(0,7),n=`${e.base.staged?"staged vs ":""}${e.base.ref}`;if(!e.changes.length&&!e.unindexed.length)return`codeindex: no changes vs ${n} (merge-base ${t}) `;let r=e.changes.length+e.unindexed.length,s=[`codeindex: delta vs ${n} (merge-base ${t}) \u2014 ${r} changed file(s), ${e.modules.length} module(s)${e.indexCommit?`, index @ ${e.indexCommit}`:""}`];for(let o of e.notes)s.push(` note: ${o}`);for(let o of e.modules){s.push(` ${o.bucket.padEnd(6)} ${o.slug} score ${o.score}${o.reasons.length?` \u2014 ${o.reasons.join("; ")}`:""}`);let a=o.tests.status==="gap"?"GAP":o.tests.status==="covered"?`covered (${o.tests.files.length})`:"n/a";s.push(` open: ${o.open.join(", ")||"\u2014"} \xB7 tests: ${a}`)}return e.dangling.length&&s.push(` dangling: ${e.dangling.map(o=>`${o.spec} (from ${o.from})`).join(" \xB7 ")}`),e.deleted.length&&s.push(` deleted: ${e.deleted.join(", ")}`),e.unindexed.length&&s.push(` unindexed: ${e.unindexed.join(", ")}`),s.join(` `)+` -`}La();ja();Rt();K();Me();S();we();ie();qe();qe();Qe();Vs();Rt();zs();or();It();tr();Te();Kt();Zt();dr();Zt();br();Gt();Js();Ir();Ar();oi();wr();gr();ai();vn();ii();rn();In();Zs();Ys();Me();si();_i();var Eu=`codeindex engine v${fe} \u2014 deterministic repo indexing +`}Ja();Ka();At();Y();Ce();k();xe();oe();Xe();Xe();nt();ri();At();ei();cr();Ft();Os();sr();Ae();Xt();Yt();mr();Yt();Sr();Gt();si();Fr();Nr();_i();kr();yr();hi();Mn();gi();sn();On();ai();li();Ce();pi();Ri();var Wu=`codeindex engine v${fe} \u2014 deterministic repo indexing Usage: engine.mjs [flags] @@ -167,7 +169,8 @@ Commands: advertises a named subset (all | orient | find | impact | edit | risk, default all) \u2014 every advertised tool's schema costs an agent context on EVERY turn, and a tool left out is still answerable - when called by name + when called by name; --watch enables proactive invalidation for a + pinned repo while retaining per-request freshness verification version Print the engine version Flags (accepted before OR after the subcommand: '--repo X scan' and @@ -221,54 +224,54 @@ Flags (accepted before OR after the subcommand: '--repo X scan' and --min-count \`literals\`: total occurrences required (default 3) --include-tests \`literals\`: count test files too. Off by default \u2014 a test restating a value is usually asserting it deliberately -`;function fy(e){let t={repo:v.cwd(),include:[],exclude:[],gitignore:!0,ignoreDirs:[],noAst:!1,fuzzy:!0,semantic:!1};for(let n=0;n{let a=e[++n];if(a===void 0)throw new Error(`missing value for ${r}`);return a},o=()=>{let a=s(),l=Number(a);if(!Number.isFinite(l)||l<=0)throw new Error(`${r} expects a positive number, got "${a}"`);return l};if(r==="--repo")t.repo=Ae(s());else if(r==="--out"){let a=s();t.out=a==="-"?"-":Ae(a)}else if(r==="--project-root")t.projectRoot=s();else if(r==="--include")t.include.push(s());else if(r==="--exclude")t.exclude.push(s());else if(r==="--scope")t.scope=s();else if(r==="--no-gitignore")t.gitignore=!1;else if(r==="--ignore-dir")t.ignoreDirs.push(s());else if(r==="--max-files")t.maxFiles=o();else if(r==="--max-bytes")t.maxBytes=o();else if(r==="--max-calls")t.maxCalls=o();else if(r==="--ignore-case")t.ignoreCase=!0;else if(r==="--max-hits")t.maxHits=o();else if(r==="--budget-tokens")t.budgetTokens=o();else if(r==="--min-files")t.minFiles=o();else if(r==="--min-count")t.minCount=o();else if(r==="--include-tests")t.includeTests=!0;else if(r==="--no-ast")t.noAst=!0;else if(r==="--index")t.indexDir=s();else if(r==="--no-index-cache")t.noIndexCache=!0;else if(r==="--workers"){let a=s(),l=Number(a);if(!Number.isInteger(l)||l<0)throw new Error(`--workers expects a non-negative integer, got "${a}"`);t.workers=l}else if(r==="--since")t.since=s();else if(r==="--config")t.config=Ae(s());else if(r==="--limit")t.limit=o();else if(r==="--no-fuzzy")t.fuzzy=!1;else if(r==="--exact")t.exact=!0;else if(r==="--explain")t.explain=!0;else if(r==="--semantic")t.semantic=!0;else if(r==="--recall")t.recall=!0;else if(r==="--run")t.run=!0;else if(r==="--probe")t.probe=!0;else if(r==="--base")t.base=s();else if(r==="--staged")t.staged=!0;else if(r==="--depth")t.depth=o();else if(r==="--kind")t.kind=s();else if(r==="--rank"){let a=s();if(a!=="graph"&&a!=="lexical")throw new Error(`--rank expects graph|lexical, got "${a}"`);t.rank=a}else if(r==="--direction"){let a=s();if(a!=="out"&&a!=="in"&&a!=="both")throw new Error(`--direction expects out|in|both, got "${a}"`);t.direction=a}else if(r==="--json")t.json=!0;else if(!r.startsWith("--")&&t.positional===void 0)t.positional=r;else throw new Error(`unknown flag: ${r}`)}return t}function se(e,t){t?Re(t,e):v.stdout.write(e)}function On(e,t){return{include:e.include.length?e.include:void 0,exclude:e.exclude.length?e.exclude:void 0,scope:e.scope,gitignore:e.gitignore,ignoreDirs:e.ignoreDirs.length?e.ignoreDirs:void 0,maxFiles:e.maxFiles,maxBytes:e.maxBytes,maxCallsPerFile:e.maxCalls,precomputedWalk:t}}var my=new Set(["grep","churn","coupling","workspaces","grammars"]);function py(e){let t,n,r,s;for(let o=0;o=e.length?e:[e[n],...t,...e.slice(n+1)]}async function hy(e){let t=_y(e),[n,...r]=t;if(!n||n==="help"||n==="--help"||n==="-h"){v.stdout.write(Eu);return}if(n==="version"||n==="--version"){v.stdout.write(fe+` -`);return}if(n==="rewrite"){let{rewriteCommand:m}=await Promise.resolve().then(()=>(ja(),ku)),g=m(r.join(" "));if(!g){v.exitCode=1;return}v.stdout.write(g+` -`);return}if(n==="mcp"){let{runMcpServer:m}=await Promise.resolve().then(()=>(La(),wu));await m(py(r));return}let s=fy(r);if(!z(s.repo))throw new Error(`--repo path does not exist: ${s.repo}`);let o=!my.has(n)&&!(n==="embed"&&s.positional!=="build"),a;o&&!s.noAst&&(a=Le(s.repo,{maxFileBytes:s.maxBytes,maxFiles:s.maxFiles,gitignore:s.gitignore,ignoreDirs:s.ignoreDirs.length?s.ignoreDirs:void 0}),await Ze(_t(a.files.map(m=>m.ext))));let l=s.indexDir??yt,c=!1,d,u=()=>{if(c)return d;if(c=!0,s.noIndexCache)return;let m=er(s.repo,On(s,a),l);return m&&(d={scan:m.scan,arts:m.arts}),d},f=()=>u()?.scan??Pe(s.repo,On(s,a)),p=()=>{let m=u();return m?.arts?m.arts:m?Dt(m.scan,On(s,a)):la(s.repo,On(s,a))};if(n==="index"){if(!s.out)throw new Error("index needs --out ");let m=s.out;ft(m,{recursive:!0});let g=I(m,"cache.json"),h,_={};try{let q=JSON.parse(te(g,"utf8"));q.schemaVersion===5&&q.extractorVersion===13&&(h=new Map(Object.entries(q.files)),_={engineVersion:q.engineVersion,commit:q.commit,graphSha1:q.graphSha1,symbolsSha1:q.symbolsSha1,embed:q.embed})}catch{}let y=await Eo(s.repo,{...On(s,a),cache:h,out:m,workers:s.workers}),x=St(s.repo),E=x?Lt(x):void 0,w=I(m,"graph.json"),k=I(m,"symbols.json"),C=I(m,"embeddings.bin"),A=q=>{try{return ve(te(q))}catch{return}},F=q=>{let X={};for(let B of y.files){let P={hash:B.hash,record:B,size:B.size},$=y.mtimes.get(B.rel);$!==void 0&&(P.mtimeMs=$),X[B.rel]=P}Re(g,JSON.stringify({schemaVersion:5,extractorVersion:13,engineVersion:fe,commit:y.commit,graphSha1:q.graphSha1,symbolsSha1:q.symbolsSha1,embed:q.embed,files:X})+` -`)},N=!E||_.embed!==void 0&&_.embed.embedVersion===nt&&_.embed.modelId===E.modelId&&_.embed.sha1!==void 0&&A(C)===_.embed.sha1;if(y.contentUnchanged&&_.engineVersion===fe&&_.commit===y.commit&&_.graphSha1!==void 0&&A(w)===_.graphSha1&&_.symbolsSha1!==void 0&&A(k)===_.symbolsSha1&&N)y.cacheDirty&&F(_),v.stderr.write(`codeindex: ${y.files.length} files \u2192 ${m}/graph.json + symbols.json${y.capped?" (capped)":""} (unchanged \u2014 artifacts reused) -`);else{let{graph:q,symbols:X}=Dt(y),B=An(q),P=As(X);Re(w,B),Re(k,P);let $="",V;if(E){let oe=sn(y,E),ee=Xs(oe);Re(C,ee),V={embedVersion:nt,modelId:E.modelId,sha1:ve(ee)},$=` + embeddings.bin (${oe.records.length} records, model ${E.modelId})`}F({graphSha1:ve(B),symbolsSha1:ve(P),embed:V}),v.stderr.write(`codeindex: ${y.files.length} files \u2192 ${m}/graph.json + symbols.json${$}${y.capped?" (capped)":""} -`)}}else if(n==="scan"){let m=Qn(s.repo,On(s,a)),g={engineVersion:fe,commit:m.commit,fileCount:m.fileCount,languages:m.languages,capped:m.capped};se(JSON.stringify(g,null,2)+` -`,s.out)}else if(n==="graph"){let{graph:m}=p();se(An(m),s.out)}else if(n==="symbols"){let{symbols:m}=p();se(As(m),s.out)}else if(n==="scip"){let m=f(),g=aa(m,{projectRoot:s.projectRoot}),h=s.out??Ae("index.scip");h==="-"?v.stdout.write(T.from(g)):(Re(h,g),v.stderr.write(`codeindex: SCIP index \u2192 ${h} (${g.length} bytes) -`))}else if(n==="callers"){let m=f(),g=Xt(m,void 0,{recall:s.recall}),h={};for(let[_,y]of g)h[_]=y;se(JSON.stringify(h,null,2)+` -`,s.out)}else if(n==="hierarchy"){let m=f(),g=xn(m,ar(m));if(s.positional){let h=g.get(s.positional);if(!h)throw new Error(`no type named ${s.positional}`);se(JSON.stringify(h,null,2)+` -`,s.out)}else{let h={};for(let[_,y]of g)h[_]=y;se(JSON.stringify(h,null,2)+` -`,s.out)}}else if(n==="implementations"){if(!s.positional)throw new Error("implementations needs a type name: cli.mjs implementations --repo ");let m=f(),g=xn(m,ar(m));if(!g.has(s.positional))throw new Error(`no type named ${s.positional}`);se(JSON.stringify({name:s.positional,implementations:ir(g,s.positional)},null,2)+` -`,s.out)}else if(n==="callgraph"){if(!s.positional)throw new Error("callgraph needs a symbol: cli.mjs callgraph --repo ");let m=f(),g=lr(m,ar(m)),h=cr(g,s.positional,{...s.depth!==void 0?{depth:s.depth}:{},...s.direction?{direction:s.direction}:{}});if(!h.root.length)throw new Error(`no symbol named ${s.positional}`);se(JSON.stringify(h,null,2)+` -`,s.out)}else if(n==="search"){if(!s.positional)throw new Error('search needs a query: cli.mjs search "" --repo ');let m=f(),g={limit:s.limit,fuzzy:s.fuzzy,...s.exact?{exact:!0}:{},...s.rank?{rank:s.rank}:{}},h=()=>{let{explain:_}=en(m,s.positional,g);_.note&&v.stderr.write(`codeindex: ${_.note} -`)};if(s.semantic){let _=jt(),y=()=>{let x=Ft(m,s.positional,g);se(JSON.stringify(x,null,2)+` -`,s.out)};if(_)try{let x=await Cr(m),E=await Mr(s.positional),w=on(m,s.positional,x,{queryVec:E,limit:s.limit,fuzzy:s.fuzzy});se(JSON.stringify(w,null,2)+` -`,s.out)}catch(x){v.stderr.write(`codeindex: embedding endpoint ${_} unavailable (${x instanceof Error?x.message:x}) \u2014 returning lexical results -`),y()}else{let x=St(s.repo),E=x?Lt(x):void 0;if(!E)v.stderr.write("codeindex: semantic search unavailable (no embedding model or endpoint) \u2014 returning lexical results; run `codeindex embed pull` or set CODEINDEX_EMBED_ENDPOINT to enable it\n"),y();else{let w=sn(m,E),k=on(m,s.positional,w,{model:E,limit:s.limit,fuzzy:s.fuzzy});se(JSON.stringify(k,null,2)+` -`,s.out)}}h()}else{let{results:_,explain:y}=en(m,s.positional,g);se(JSON.stringify(s.explain?{results:_,explain:y}:_,null,2)+` -`,s.out),y.note&&v.stderr.write(`codeindex: ${y.note} -`)}}else if(n==="embed"){let m=s.positional,g=St(s.repo);if(m==="status"){let h=g?Lt(g):void 0,_=jt(),x={embedVersion:nt,mode:_?"endpoint":h?"static":"none",model:h?{present:!0,dir:g,modelId:h.modelId,dim:h.dim,vocabSize:h.vocabSize}:{present:!1},endpoint:_??null};_&&(x.endpointReachable=await Rr(_)),se(JSON.stringify(x,null,2)+` -`,s.out)}else if(m==="serve"){let h=["run","-d","-p","8756:8756","ghcr.io/maxgfr/codeindex-embed:latest"],_=`docker ${h.join(" ")}`;if(!it("docker")){v.stderr.write(`codeindex: docker not found on PATH. Install Docker, then run: - `+_+` -`),v.exitCode=1;return}if(s.run){v.stderr.write(`codeindex: starting embedding server \u2192 ${_} -`);let y=me("docker",h);if(y.stdout.trim()&&v.stdout.write(y.stdout.trim()+` -`),!y.ok){v.stderr.write(y.stderr||`codeindex: docker run failed -`),v.exitCode=1;return}v.stderr.write(`codeindex: server starting on http://localhost:8756 \u2014 then: +`;function Fy(e){let t={repo:R.cwd(),include:[],exclude:[],gitignore:!0,ignoreDirs:[],noAst:!1,fuzzy:!0,semantic:!1};for(let n=0;n{let a=e[++n];if(a===void 0)throw new Error(`missing value for ${r}`);return a},o=()=>{let a=s(),l=Number(a);if(!Number.isFinite(l)||l<=0)throw new Error(`${r} expects a positive number, got "${a}"`);return l};if(r==="--repo")t.repo=Ne(s());else if(r==="--out"){let a=s();t.out=a==="-"?"-":Ne(a)}else if(r==="--project-root")t.projectRoot=s();else if(r==="--include")t.include.push(s());else if(r==="--exclude")t.exclude.push(s());else if(r==="--scope")t.scope=s();else if(r==="--no-gitignore")t.gitignore=!1;else if(r==="--ignore-dir")t.ignoreDirs.push(s());else if(r==="--max-files")t.maxFiles=o();else if(r==="--max-bytes")t.maxBytes=o();else if(r==="--max-calls")t.maxCalls=o();else if(r==="--ignore-case")t.ignoreCase=!0;else if(r==="--max-hits")t.maxHits=o();else if(r==="--budget-tokens")t.budgetTokens=o();else if(r==="--min-files")t.minFiles=o();else if(r==="--min-count")t.minCount=o();else if(r==="--include-tests")t.includeTests=!0;else if(r==="--no-ast")t.noAst=!0;else if(r==="--index")t.indexDir=s();else if(r==="--no-index-cache")t.noIndexCache=!0;else if(r==="--workers"){let a=s(),l=Number(a);if(!Number.isInteger(l)||l<0)throw new Error(`--workers expects a non-negative integer, got "${a}"`);t.workers=l}else if(r==="--since")t.since=s();else if(r==="--config")t.config=Ne(s());else if(r==="--limit")t.limit=o();else if(r==="--no-fuzzy")t.fuzzy=!1;else if(r==="--exact")t.exact=!0;else if(r==="--explain")t.explain=!0;else if(r==="--semantic")t.semantic=!0;else if(r==="--recall")t.recall=!0;else if(r==="--run")t.run=!0;else if(r==="--probe")t.probe=!0;else if(r==="--base")t.base=s();else if(r==="--staged")t.staged=!0;else if(r==="--depth")t.depth=o();else if(r==="--kind")t.kind=s();else if(r==="--rank"){let a=s();if(a!=="graph"&&a!=="lexical")throw new Error(`--rank expects graph|lexical, got "${a}"`);t.rank=a}else if(r==="--direction"){let a=s();if(a!=="out"&&a!=="in"&&a!=="both")throw new Error(`--direction expects out|in|both, got "${a}"`);t.direction=a}else if(r==="--json")t.json=!0;else if(!r.startsWith("--")&&t.positional===void 0)t.positional=r;else throw new Error(`unknown flag: ${r}`)}return t}function ie(e,t){t?Re(t,e):R.stdout.write(e)}function Pn(e,t){return{include:e.include.length?e.include:void 0,exclude:e.exclude.length?e.exclude:void 0,scope:e.scope,gitignore:e.gitignore,ignoreDirs:e.ignoreDirs.length?e.ignoreDirs:void 0,maxFiles:e.maxFiles,maxBytes:e.maxBytes,maxCallsPerFile:e.maxCalls,precomputedWalk:t}}var Py=new Set(["grep","churn","coupling","workspaces","grammars"]);function $y(e){let t,n,r,s,o=!1;for(let a=0;a");return{defaultRepo:t,serverInfo:n?{name:n}:void 0,maxResponseBytes:r,profile:s,watch:o}}var Ly=new Set(["--repo","--out","--project-root","--include","--exclude","--scope","--ignore-dir","--max-files","--max-bytes","--max-calls","--max-hits","--budget-tokens","--min-files","--min-count","--since","--config","--limit","--server-name","--tools","--workers","--index","--max-response-bytes","--base","--depth","--kind","--rank","--direction"]);function Dy(e){let t=[],n=0;for(;n=e.length?e:[e[n],...t,...e.slice(n+1)]}async function jy(e){let t=Dy(e),[n,...r]=t;if(!n||n==="help"||n==="--help"||n==="-h"){R.stdout.write(Wu);return}if(n==="version"||n==="--version"){R.stdout.write(fe+` +`);return}if(n==="rewrite"){let{rewriteCommand:_}=await Promise.resolve().then(()=>(Ka(),ju)),E=_(r.join(" "));if(!E){R.exitCode=1;return}R.stdout.write(E+` +`);return}if(n==="mcp"){let{runMcpServer:_}=await Promise.resolve().then(()=>(Ja(),$u));await _($y(r));return}let s=Fy(r);if(!H(s.repo))throw new Error(`--repo path does not exist: ${s.repo}`);if(!Ee(s.repo).isDirectory())throw new Error(`--repo path is not a directory: ${s.repo}`);let o=!Py.has(n)&&!(n==="embed"&&s.positional!=="build"),a;o&&!s.noAst&&(a=Fe(s.repo,{maxFileBytes:s.maxBytes,maxFiles:s.maxFiles,gitignore:s.gitignore,ignoreDirs:s.ignoreDirs.length?s.ignoreDirs:void 0}));let l=!1,c=async()=>{l||s.noAst||!a||(await et(bt(a.files.map(_=>_.ext))),l=!0)},d=s.indexDir??ut,f=!1,u,m,p=async()=>{if(u)return u;if(f)return m;if(f=!0,!s.noIndexCache)return u=Is(s.repo,Pn(s,a),c,d).then(_=>(_&&(m={scan:_.scan,arts:_.arts,loadArtifacts:_.loadArtifacts}),m)),u},g,y=async()=>{let _=(await p())?.scan;return _||(g??=c().then(()=>Pt(s.repo,{...Pn(s,a),workers:s.workers})))},h,S=async()=>{let _=await p();return _?.arts?_.arts:_?_.arts??=_.loadArtifacts?.()??Et(_.scan,Pn(s,a)):h??=y().then(E=>Et(E,Pn(s,a)))};if(n==="index"){if(!s.out)throw new Error("index needs --out ");let _=s.out;gt(_,{recursive:!0});let E=I(_,"cache.json"),b,x={};try{let B=JSON.parse(te(E,"utf8"));B.schemaVersion===5&&B.extractorVersion===14&&(b=new Map(Object.entries(B.files)),x={engineVersion:B.engineVersion,commit:B.commit,graphSha1:B.graphSha1,symbolsSha1:B.symbolsSha1,embed:B.embed})}catch{}await c();let v=await Pt(s.repo,{...Pn(s,a),cache:b,out:_,workers:s.workers}),A=vt(s.repo),O=A?Wt(A):void 0,N=I(_,"graph.json"),U=I(_,"symbols.json"),le=I(_,"embeddings.bin"),V=B=>{try{return Me(te(B))}catch{return}},z=B=>{let re={};for(let J of v.files){let ee={hash:J.hash,record:J,size:J.size},be=v.mtimes.get(J.rel);be!==void 0&&(ee.mtimeMs=be),re[J.rel]=ee}Re(E,JSON.stringify({schemaVersion:5,extractorVersion:14,engineVersion:fe,commit:v.commit,graphSha1:B.graphSha1,symbolsSha1:B.symbolsSha1,embed:B.embed,files:re})+` +`)},P=!O||x.embed!==void 0&&x.embed.embedVersion===it&&x.embed.modelId===O.modelId&&x.embed.sha1!==void 0&&V(le)===x.embed.sha1;if(v.contentUnchanged&&x.engineVersion===fe&&x.commit===v.commit&&x.graphSha1!==void 0&&V(N)===x.graphSha1&&x.symbolsSha1!==void 0&&V(U)===x.symbolsSha1&&P)v.cacheDirty&&z(x),R.stderr.write(`codeindex: ${v.files.length} files \u2192 ${_}/graph.json + symbols.json${v.capped?" (capped)":""} (unchanged \u2014 artifacts reused) +`);else{let{graph:B,symbols:re}=Et(v),J=In(B),ee=js(re);Re(N,J),Re(U,ee);let be="",Ie;if(O){let X=on(v,O),Z=oi(X);Re(le,Z),Ie={embedVersion:it,modelId:O.modelId,sha1:Me(Z)},be=` + embeddings.bin (${X.records.length} records, model ${O.modelId})`}z({graphSha1:Me(J),symbolsSha1:Me(ee),embed:Ie}),R.stderr.write(`codeindex: ${v.files.length} files \u2192 ${_}/graph.json + symbols.json${be}${v.capped?" (capped)":""} +`)}}else if(n==="scan"){let _=rr(s.repo,Pn(s,a)),E={engineVersion:fe,commit:_.commit,fileCount:_.fileCount,languages:_.languages,capped:_.capped};ie(JSON.stringify(E,null,2)+` +`,s.out)}else if(n==="graph"){let{graph:_}=await S();ie(In(_),s.out)}else if(n==="symbols"){let{symbols:_}=await S();ie(js(_),s.out)}else if(n==="scip"){let _=await y(),E=ya(_,{projectRoot:s.projectRoot}),b=s.out??Ne("index.scip");b==="-"?R.stdout.write(T.from(E)):(Re(b,E),R.stderr.write(`codeindex: SCIP index \u2192 ${b} (${E.length} bytes) +`))}else if(n==="callers"){let _=await y(),E=Zt(_,void 0,{recall:s.recall}),b={};for(let[x,v]of E)b[x]=v;ie(JSON.stringify(b,null,2)+` +`,s.out)}else if(n==="hierarchy"){let _=await y(),E=kn(_,dr(_));if(s.positional){let b=E.get(s.positional);if(!b)throw new Error(`no type named ${s.positional}`);ie(JSON.stringify(b,null,2)+` +`,s.out)}else{let b={};for(let[x,v]of E)b[x]=v;ie(JSON.stringify(b,null,2)+` +`,s.out)}}else if(n==="implementations"){if(!s.positional)throw new Error("implementations needs a type name: cli.mjs implementations --repo ");let _=await y(),E=kn(_,dr(_));if(!E.has(s.positional))throw new Error(`no type named ${s.positional}`);ie(JSON.stringify({name:s.positional,implementations:lr(E,s.positional)},null,2)+` +`,s.out)}else if(n==="callgraph"){if(!s.positional)throw new Error("callgraph needs a symbol: cli.mjs callgraph --repo ");let _=await y(),E=ur(_,dr(_)),b=fr(E,s.positional,{...s.depth!==void 0?{depth:s.depth}:{},...s.direction?{direction:s.direction}:{}});if(!b.root.length)throw new Error(`no symbol named ${s.positional}`);ie(JSON.stringify(b,null,2)+` +`,s.out)}else if(n==="search"){if(!s.positional)throw new Error('search needs a query: cli.mjs search "" --repo ');let _=await y(),E={limit:s.limit,fuzzy:s.fuzzy,...s.exact?{exact:!0}:{},...s.rank?{rank:s.rank}:{}},b=()=>{let{explain:x}=tn(_,s.positional,E);x.note&&R.stderr.write(`codeindex: ${x.note} +`)};if(s.semantic){let x=Ut(),v=()=>{let A=Lt(_,s.positional,E);ie(JSON.stringify(A,null,2)+` +`,s.out)};if(x)try{let A=await Ir(_),O=await Tr(s.positional),N=an(_,s.positional,A,{queryVec:O,limit:s.limit,fuzzy:s.fuzzy});ie(JSON.stringify(N,null,2)+` +`,s.out)}catch(A){R.stderr.write(`codeindex: embedding endpoint ${x} unavailable (${A instanceof Error?A.message:A}) \u2014 returning lexical results +`),v()}else{let A=vt(s.repo),O=A?Wt(A):void 0;if(!O)R.stderr.write("codeindex: semantic search unavailable (no embedding model or endpoint) \u2014 returning lexical results; run `codeindex embed pull` or set CODEINDEX_EMBED_ENDPOINT to enable it\n"),v();else{let N=on(_,O),U=an(_,s.positional,N,{model:O,limit:s.limit,fuzzy:s.fuzzy});ie(JSON.stringify(U,null,2)+` +`,s.out)}}b()}else{let{results:x,explain:v}=tn(_,s.positional,E);ie(JSON.stringify(s.explain?{results:x,explain:v}:x,null,2)+` +`,s.out),v.note&&R.stderr.write(`codeindex: ${v.note} +`)}}else if(n==="embed"){let _=s.positional,E=vt(s.repo);if(_==="status"){let b=E?Wt(E):void 0,x=Ut(),A={embedVersion:it,mode:x?"endpoint":b?"static":"none",model:b?{present:!0,dir:E,modelId:b.modelId,dim:b.dim,vocabSize:b.vocabSize}:{present:!1},endpoint:x??null};x&&(A.endpointReachable=await Ar(x)),ie(JSON.stringify(A,null,2)+` +`,s.out)}else if(_==="serve"){let b=["run","-d","-p","8756:8756","ghcr.io/maxgfr/codeindex-embed:latest"],x=`docker ${b.join(" ")}`;if(!at("docker")){R.stderr.write(`codeindex: docker not found on PATH. Install Docker, then run: + `+x+` +`),R.exitCode=1;return}if(s.run){R.stderr.write(`codeindex: starting embedding server \u2192 ${x} +`);let v=pe("docker",b);if(v.stdout.trim()&&R.stdout.write(v.stdout.trim()+` +`),!v.ok){R.stderr.write(v.stderr||`codeindex: docker run failed +`),R.exitCode=1;return}R.stderr.write(`codeindex: server starting on http://localhost:8756 \u2014 then: CODEINDEX_EMBED_ENDPOINT=http://localhost:8756 codeindex search "" --repo . --semantic -`)}else v.stdout.write(_+` -`),v.stderr.write('codeindex: run the line above to start the embedding server (or `embed serve --run`), then:\n CODEINDEX_EMBED_ENDPOINT=http://localhost:8756 codeindex search "" --repo . --semantic\n')}else if(m==="build"){if(!s.out)throw new Error("embed build needs --out ");if(!g){v.stderr.write("codeindex: no embedding model present \u2014 run `codeindex embed pull` first (nothing written)\n"),v.exitCode=1;return}let h=Lt(g);ft(s.out,{recursive:!0});let _=f(),y=sn(_,h);Re(I(s.out,"embeddings.bin"),Xs(y)),v.stderr.write(`codeindex: ${y.records.length} embedding records \u2192 ${s.out}/embeddings.bin (model ${h.modelId}) -`)}else if(m==="pull"){let{url:h,sha256:_}=da(),y=v.env.CODEINDEX_EMBED_DIR??I(s.repo,".codeindex","models");ft(y,{recursive:!0}),v.stderr.write(`codeindex: fetching model from ${h} \u2192 ${I(y,"model.json")} -`);let x;try{x=await Fd(h,_)}catch(E){v.stderr.write(`codeindex: pull failed \u2014 ${E instanceof Error?E.message:String(E)} (nothing written) -`),v.exitCode=1;return}try{ca(JSON.parse(x),h)}catch(E){v.stderr.write(`codeindex: pull failed \u2014 response is not a valid model.json (${E instanceof Error?E.message:String(E)}) (nothing written) -`),v.exitCode=1;return}Re(I(y,"model.json"),x),v.stderr.write(`codeindex: model written to ${I(y,"model.json")} -`)}else throw new Error("embed needs a subcommand: status | build | pull | serve")}else if(n==="lsp"){if(s.positional!=="status")throw new Error("lsp needs a subcommand: status");se(JSON.stringify(await Nr(f(),s.repo,s.probe===!0),null,2)+` -`,s.out)}else if(n==="grammars"){let m=s.positional,g=yn();if(m==="status"){let h=Xe(),_=A=>h.dirs.some(F=>z(I(F,A))),y=_("web-tree-sitter.wasm"),x=Es(),E=A=>[...A].filter(F=>_(`${F}.wasm`)).sort(),w=E(qn),k=E(Vn),C={engineVersion:fe,tier:h.tier,dir:h.dir??null,dirs:h.dirs,cacheDir:g,runtimePresent:y,pullNeeded:!y,core:{resolved:w.length,of:qn.size,missing:[...qn].filter(A=>!w.includes(A)).sort()},extended:{resolved:k.length,of:Vn.size,missing:[...Vn].filter(A=>!k.includes(A)).sort()},url:x.url};se(JSON.stringify(C,null,2)+` -`,s.out)}else if(m==="pull"){let h=await nr(g,{onNote:_=>v.stderr.write(_)});v.stderr.write(h.message),h.ok||(v.exitCode=1)}else throw new Error("grammars needs a subcommand: status | pull")}else if(n==="rules"){if(!s.config)throw new Error("rules needs --config ");let m=Or(JSON.parse(te(s.config,"utf8"))),{graph:g}=p(),h=Fr(g,m),_=h.filter(y=>y.severity==="error").length;se(JSON.stringify({errors:_,warnings:h.length-_,violations:h},null,2)+` -`,s.out),_>0&&(v.exitCode=1)}else if(n==="workspaces"){let m=tn(s.repo);se(JSON.stringify({packages:m.packages,cycle:m.cycle??null,topoOrder:m.topoOrder},null,2)+` -`,s.out)}else if(n==="churn"){let{churn:m,ok:g}=Je(s.repo,{since:s.since}),h={};for(let _ of[...m.keys()].sort())h[_]=m.get(_);se(JSON.stringify({ok:g,churn:h},null,2)+` -`,s.out)}else if(n==="repomap"){let{scan:m,graph:g}=p();se(an(m,g,{budgetTokens:s.budgetTokens}),s.out)}else if(n==="hotspots"){let m=f(),{churn:g,ok:h}=Je(s.repo,{since:s.since});se(JSON.stringify({churnOk:h,hotspots:ln(m,g)},null,2)+` -`,s.out)}else if(n==="coupling"){let{ok:m,couplings:g}=Tr(s.repo,{since:s.since});se(JSON.stringify({ok:m,couplings:g},null,2)+` -`,s.out)}else if(n==="deadcode")se(JSON.stringify(Pr(f()),null,2)+` -`,s.out);else if(n==="literals"){let m=nn(f(),{minFiles:s.minFiles,minCount:s.minCount,includeTests:s.includeTests});se(JSON.stringify(m,null,2)+` -`,s.out)}else if(n==="complexity"){let m=f();se(JSON.stringify(mr(m,s.positional),null,2)+` -`,s.out)}else if(n==="risk"){let m=f(),{churn:g,ok:h}=Je(s.repo,{since:s.since});se(JSON.stringify({churnOk:h,risks:pr(m,g)},null,2)+` -`,s.out)}else if(n==="delta"){let{graph:m,symbols:g}=p(),h=Ta(s.repo,m,g,{base:s.base,staged:s.staged,depth:s.depth});if("error"in h)throw new Error(h.error);se(s.json?JSON.stringify(h,null,2)+` -`:Ia(h),s.out)}else if(n==="impact"){if(!s.positional)throw new Error("impact needs a target: cli.mjs impact --repo ");let{graph:m}=p(),g=Dr(m,s.positional,s.depth??1/0);if(!g)throw new Error(`no such file or module in the index: ${s.positional}`);se(JSON.stringify(g,null,2)+` -`,s.out)}else if(n==="neighbors"){if(!s.positional)throw new Error("neighbors needs a target: cli.mjs neighbors --repo ");let{graph:m}=p(),g=s.kind?new Set(s.kind.split(",").map(_=>_.trim()).filter(Boolean)):void 0,h=Ca(m,s.positional,s.depth??1,g);if(!h)throw new Error(`no such file or module in the index: ${s.positional}`);se(JSON.stringify(h,null,2)+` -`,s.out)}else if(n==="mermaid"){let{graph:m}=p();se($r(m,{module:s.positional}),s.out)}else if(n==="grep"){if(!s.positional)throw new Error("grep needs a pattern: cli.mjs grep --repo ");let g=[...s.scope?[`${s.scope.replace(/\/+$/,"")}/**`]:[],...s.include,...s.exclude.map(_=>`!${_}`)],h=xr(s.repo,s.positional,{globs:g.length?g:void 0,ignoreCase:s.ignoreCase,maxHits:s.maxHits});se(JSON.stringify(h,null,2)+` -`,s.out)}else v.stderr.write(`unknown command: ${n} +`)}else R.stdout.write(x+` +`),R.stderr.write('codeindex: run the line above to start the embedding server (or `embed serve --run`), then:\n CODEINDEX_EMBED_ENDPOINT=http://localhost:8756 codeindex search "" --repo . --semantic\n')}else if(_==="build"){if(!s.out)throw new Error("embed build needs --out ");if(!E){R.stderr.write("codeindex: no embedding model present \u2014 run `codeindex embed pull` first (nothing written)\n"),R.exitCode=1;return}let b=Wt(E);gt(s.out,{recursive:!0});let x=await y(),v=on(x,b);Re(I(s.out,"embeddings.bin"),oi(v)),R.stderr.write(`codeindex: ${v.records.length} embedding records \u2192 ${s.out}/embeddings.bin (model ${b.modelId}) +`)}else if(_==="pull"){let{url:b,sha256:x}=wa(),v=R.env.CODEINDEX_EMBED_DIR??I(s.repo,".codeindex","models");gt(v,{recursive:!0}),R.stderr.write(`codeindex: fetching model from ${b} \u2192 ${I(v,"model.json")} +`);let A;try{A=await Xd(b,x)}catch(O){R.stderr.write(`codeindex: pull failed \u2014 ${O instanceof Error?O.message:String(O)} (nothing written) +`),R.exitCode=1;return}try{ba(JSON.parse(A),b)}catch(O){R.stderr.write(`codeindex: pull failed \u2014 response is not a valid model.json (${O instanceof Error?O.message:String(O)}) (nothing written) +`),R.exitCode=1;return}Re(I(v,"model.json"),A),R.stderr.write(`codeindex: model written to ${I(v,"model.json")} +`)}else throw new Error("embed needs a subcommand: status | build | pull | serve")}else if(n==="lsp"){if(s.positional!=="status")throw new Error("lsp needs a subcommand: status");ie(JSON.stringify(await Pr(await y(),s.repo,s.probe===!0),null,2)+` +`,s.out)}else if(n==="grammars"){let _=s.positional,E=wn();if(_==="status"){let b=Qe(),x=V=>b.dirs.some(z=>H(I(z,V))),v=x("web-tree-sitter.wasm"),A=Fs(),O=V=>[...V].filter(z=>x(`${z}.wasm`)).sort(),N=O(Xn),U=O(Zn),le={engineVersion:fe,tier:b.tier,dir:b.dir??null,dirs:b.dirs,cacheDir:E,runtimePresent:v,pullNeeded:!v,core:{resolved:N.length,of:Xn.size,missing:[...Xn].filter(V=>!N.includes(V)).sort()},extended:{resolved:U.length,of:Zn.size,missing:[...Zn].filter(V=>!U.includes(V)).sort()},url:A.url};ie(JSON.stringify(le,null,2)+` +`,s.out)}else if(_==="pull"){let b=await ir(E,{onNote:x=>R.stderr.write(x)});R.stderr.write(b.message),b.ok||(R.exitCode=1)}else throw new Error("grammars needs a subcommand: status | pull")}else if(n==="rules"){if(!s.config)throw new Error("rules needs --config ");let _=$r(JSON.parse(te(s.config,"utf8"))),{graph:E}=await S(),b=Lr(E,_),x=b.filter(v=>v.severity==="error").length;ie(JSON.stringify({errors:x,warnings:b.length-x,violations:b},null,2)+` +`,s.out),x>0&&(R.exitCode=1)}else if(n==="workspaces"){let _=nn(s.repo);ie(JSON.stringify({packages:_.packages,cycle:_.cycle??null,topoOrder:_.topoOrder},null,2)+` +`,s.out)}else if(n==="churn"){let{churn:_,ok:E}=Ze(s.repo,{since:s.since}),b={};for(let x of[..._.keys()].sort())b[x]=_.get(x);ie(JSON.stringify({ok:E,churn:b},null,2)+` +`,s.out)}else if(n==="repomap"){let{scan:_,graph:E}=await S();ie(ln(_,E,{budgetTokens:s.budgetTokens}),s.out)}else if(n==="hotspots"){let _=await y(),{churn:E,ok:b}=Ze(s.repo,{since:s.since});ie(JSON.stringify({churnOk:b,hotspots:cn(_,E)},null,2)+` +`,s.out)}else if(n==="coupling"){let{ok:_,couplings:E}=Or(s.repo,{since:s.since});ie(JSON.stringify({ok:_,couplings:E},null,2)+` +`,s.out)}else if(n==="deadcode")ie(JSON.stringify(Dr(await y()),null,2)+` +`,s.out);else if(n==="literals"){let _=rn(await y(),{minFiles:s.minFiles,minCount:s.minCount,includeTests:s.includeTests});ie(JSON.stringify(_,null,2)+` +`,s.out)}else if(n==="complexity"){let _=await y();ie(JSON.stringify(_r(_,s.positional),null,2)+` +`,s.out)}else if(n==="risk"){let _=await y(),{churn:E,ok:b}=Ze(s.repo,{since:s.since});ie(JSON.stringify({churnOk:b,risks:hr(_,E)},null,2)+` +`,s.out)}else if(n==="delta"){let{graph:_,symbols:E}=await S(),b=Wa(s.repo,_,E,{base:s.base,staged:s.staged,depth:s.depth});if("error"in b)throw new Error(b.error);ie(s.json?JSON.stringify(b,null,2)+` +`:Ua(b),s.out)}else if(n==="impact"){if(!s.positional)throw new Error("impact needs a target: cli.mjs impact --repo ");let{graph:_}=await S(),E=Wr(_,s.positional,s.depth??1/0);if(!E)throw new Error(`no such file or module in the index: ${s.positional}`);ie(JSON.stringify(E,null,2)+` +`,s.out)}else if(n==="neighbors"){if(!s.positional)throw new Error("neighbors needs a target: cli.mjs neighbors --repo ");let{graph:_}=await S(),E=s.kind?new Set(s.kind.split(",").map(x=>x.trim()).filter(Boolean)):void 0,b=Da(_,s.positional,s.depth??1,E);if(!b)throw new Error(`no such file or module in the index: ${s.positional}`);ie(JSON.stringify(b,null,2)+` +`,s.out)}else if(n==="mermaid"){let{graph:_}=await S();ie(jr(_,{module:s.positional}),s.out)}else if(n==="grep"){if(!s.positional)throw new Error("grep needs a pattern: cli.mjs grep --repo ");let E=[...s.scope?[`${s.scope.replace(/\/+$/,"")}/**`]:[],...s.include,...s.exclude.map(x=>`!${x}`)],b=Er(s.repo,s.positional,{globs:E.length?E:void 0,ignoreCase:s.ignoreCase,maxHits:s.maxHits});ie(JSON.stringify(b,null,2)+` +`,s.out)}else R.stderr.write(`unknown command: ${n} -${Eu}`),v.exitCode=2}we();S();we();Qe();var Ua="/grammars",Wa="web-tree-sitter.wasm";function vu(e){Mu(Wa,e)}function Ru(e,t){Mu(`${e}.wasm`,t)}function Mu(e,t){Xr(`${Ua}/${e}`,t),v.env.CODEINDEX_GRAMMAR_DIR=Ua}function Cu(e){return`${e}.wasm`}async function yy(e,t){let n=_t(e);if(!n.length)return{tier:"regex",loaded:[],failed:[],note:"no language here ships a tree-sitter grammar"};try{vu(await t(Wa))}catch(o){return{tier:"regex",loaded:[],failed:[...n],note:`tree-sitter runtime unavailable (${o.message})`}}await Promise.all(n.map(async o=>{try{Ru(o,await t(Cu(o)))}catch{}})),await Ze(n);let r=n.filter(o=>Ye(o)).sort(),s=n.filter(o=>!Ye(o)).sort();return{tier:r.length?"ast":"regex",loaded:r,failed:s,note:s.length?`${s.join(", ")} could not load; those languages use the regex tier`:""}}export{qn as CORE_GRAMMARS,Aa as DEFAULT_DELTA_DEPTH,Ro as DEFAULT_GRAMMARS_URL,Vu as DEFAULT_MAX_FILES,nt as EMBED_VERSION,fe as ENGINE_VERSION,Vn as EXTENDED_GRAMMARS,fn as EXTRACTOR_VERSION,_s as EXT_GRAMMAR,Ua as GRAMMARS_DIR,yt as INDEX_DIR,ti as LspTimeout,Ui as MARKDOWN_EXT,qd as MAX_FRAME_BYTES,kt as RISK_WEIGHTS,Wa as RUNTIME_WASM,We as SCHEMA_VERSION,xa as agreementOf,oo as allGrammarKeys,Lo as applyCentrality,Pd as basicTokenize,ad as betweennessOf,Dt as buildArtifactsFromScan,Xt as buildCallerIndex,xo as buildCodeRecord,sn as buildEmbeddingIndex,Cr as buildEndpointIndex,zo as buildGraph,la as buildIndexArtifacts,Oo as buildModules,sg as buildRawCallerIndex,Io as buildResolveContext,lr as buildSymbolGraph,Do as buildSymbolIndex,xn as buildTypeHierarchy,Hi as byKey,R as byStr,_p as categorize,Tr as changeCoupling,Ju as changedSince,Fr as checkRules,Wi as classify,Hu as clip,zu as clipInline,tu as columnOfSymbol,l_ as communityOf,gt as compileGlobs,$s as complexityOfSource,uu as computeDelta,ar as computeImportPairs,Hs as computeSurprises,$o as computeSymbolRefs,ur as computeTestMap,ga as createFramer,ea as deleteMemory,Ta as deltaFor,Ch as deserializeEmbeddings,sa as detectCommunities,tn as detectWorkspaces,Fi as diffFiles,Pi as diffHunks,Wd as embedEndpointUrl,fa as embedViaEndpoint,Ks as embeddingUnits,rg as enclosingSymbol,Er as encode,Qs as encodeMessage,Mr as encodeQueryViaEndpoint,Ze as ensureGrammars,He as escapeRegExp,en as explainQuery,qt as extToLang,_o as extractAst,Ss as extractCode,zc as extractGrammarsTarball,$c as extractInParallel,zi as extractMarkdown,Li as extractSymbols,yp as extractTags,Hc as extractTarInto,Bc as fetchExpectedSha256,Uc as fetchGrammarsTarball,cn as fileUri,Pr as findDeadCode,nn as findLiteralDuplications,Vo as findReferences,Mn as findSymbol,mt as foldText,Ia as formatDeltaPanel,Je as gitChurn,Jn as grammarKeyForExt,_t as grammarKeysForExts,Ye as grammarReady,Cu as grammarWasmName,xr as grepRepo,vh as hasEmbedModel,Du as hasFileBytes,it as have,ns as headCommit,Bd as healthzUrl,lu as hubThreshold,Dr as impactOf,ir as implementationsOf,Ko as insertAfterSymbol,Xo as insertBeforeSymbol,ua as intDot,jl as isCode,Ll as isDoc,Ni as isGitWorktree,es as isIgnored,E_ as isSurprising,Ms as isTestFile,Ot as isTestPath,ko as keptCodeFiles,Yr as keywords,ji as languageOf,ta as listMemories,Lt as loadEmbedModel,yy as loadGrammars,ri as loadLspConfig,ei as locationsToRefs,Nr as lspStatus,Ut as lspUnavailable,Ja as mountFiles,Ru as mountGrammar,vu as mountRuntime,cr as neighborhood,Ca as neighborsOf,ma as onboardBrief,ha as openLspSession,fr as pagerankOf,Mi as parseGitignore,Xd as parseLspConfig,Or as parseRules,Fc as preloadArtifacts,er as preloadSession,Rr as probeEndpoint,Lu as pruneUnfetched,nr as pullGrammars,kr as quantize,ln as rankHotspots,Gu as rankedKeywords,Qo as readMemory,Oc as readPersistedIndex,G as readText,va as referencesWithLsp,Vd as relFromUri,An as renderGraphJson,$r as renderMermaid,Zh as renderMermaidClustered,an as renderRepoMap,aa as renderScip,As as renderSymbolsJson,Jo as replaceSymbolBody,$u as resetVfs,ju as residentBytes,Oi as resolveBaseRef,Fo as resolveCallEdges,No as resolveDocLink,jt as resolveEmbedEndpoint,St as resolveEmbedModelDir,da as resolveEmbedPullUrl,om as resolveGrammarsDir,Es as resolveGrammarsPullTarget,Xe as resolveGrammarsTier,rr as resolveImport,ni as resolveLspConfigPath,Po as resolveRelationEdges,sr as resolveRelations,Us as resolveUniqueSymbol,cu as reverseClosure,Su as rewriteCommand,pr as riskHotspots,Ld as roundHalfToEven,vi as rrf,hy as runCli,ip as runExtractWorker,bu as runMcpServer,Pe as scanRepo,Eo as scanRepoParallel,Qn as scanSummary,Ft as searchIndex,on as searchSemantic,Xs as serializeEmbeddings,ba as serverForLang,Xr as setFileBytes,me as sh,ve as sha1,yn as sharedGrammarsCacheDir,nf as shortHash,Ei as slugify,ka as spawnLspTransport,pt as subtokens,mr as symbolComplexity,Qt as symbolId,du as symbolsInHunks,qo as symbolsOverview,hp as tagsQueryStatus,ug as testsForModule,Vc as tierForPath,Nt as toCacheMap,Dd as tokenize,ng as typeEntry,Bo as uniqueSymbolDefs,fg as untestedModules,rs as untrackedFiles,Le as walk,xp as warmGrammars,$d as wordpiece,Pc as workerCount,_r as writeMemory}; +${Wu}`),R.exitCode=2}xe();k();xe();nt();var Xa="/grammars",Za="web-tree-sitter.wasm";function Uu(e){zu(Za,e)}function Bu(e,t){zu(`${e}.wasm`,t)}function zu(e,t){ts(`${Xa}/${e}`,t),R.env.CODEINDEX_GRAMMAR_DIR=Xa}function Hu(e){return`${e}.wasm`}async function Wy(e,t){let n=bt(e);if(!n.length)return{tier:"regex",loaded:[],failed:[],note:"no language here ships a tree-sitter grammar"};try{Uu(await t(Za))}catch(o){return{tier:"regex",loaded:[],failed:[...n],note:`tree-sitter runtime unavailable (${o.message})`}}await Promise.all(n.map(async o=>{try{Bu(o,await t(Hu(o)))}catch{}})),await et(n);let r=n.filter(o=>tt(o)).sort(),s=n.filter(o=>!tt(o)).sort();return{tier:r.length?"ast":"regex",loaded:r,failed:s,note:s.length?`${s.join(", ")} could not load; those languages use the regex tier`:""}}export{Xn as CORE_GRAMMARS,ja as DEFAULT_DELTA_DEPTH,Lo as DEFAULT_GRAMMARS_URL,cf as DEFAULT_MAX_FILES,it as EMBED_VERSION,fe as ENGINE_VERSION,Zn as EXTENDED_GRAMMARS,mn as EXTRACTOR_VERSION,Es as EXT_GRAMMAR,Xa as GRAMMARS_DIR,ut as INDEX_DIR,ui as LspTimeout,Zi as MARKDOWN_EXT,au as MAX_FRAME_BYTES,Rt as RISK_WEIGHTS,Za as RUNTIME_WASM,He as SCHEMA_VERSION,Ia as agreementOf,go as allGrammarKeys,Ko as applyCentrality,Zd as basicTokenize,wd as betweennessOf,Et as buildArtifactsFromScan,Zt as buildCallerIndex,Ts as buildCodeRecord,on as buildEmbeddingIndex,Ir as buildEndpointIndex,ta as buildGraph,Dh as buildIndexArtifacts,Ho as buildModules,Sg as buildRawCallerIndex,Bo as buildResolveContext,ur as buildSymbolGraph,Jo as buildSymbolIndex,kn as buildTypeHierarchy,Yi as byKey,M as byStr,Op as categorize,Or as changeCoupling,df as changedSince,Lr as checkRules,zn as classify,sf as clip,of as clipInline,_u as columnOfSymbol,M_ as communityOf,yt as compileGlobs,Gs as complexityOfSource,Ru as computeDelta,dr as computeImportPairs,Qs as computeSurprises,Vo as computeSymbolRefs,pr as computeTestMap,va as createFramer,ua as deleteMemory,Wa as deltaFor,Kh as deserializeEmbeddings,ga as detectCommunities,nn as detectWorkspaces,qi as diffFiles,Gi as diffHunks,nu as embedEndpointUrl,Sa as embedViaEndpoint,ii as embeddingUnits,xg as enclosingSymbol,Mr as encode,ci as encodeMessage,Tr as encodeQueryViaEndpoint,et as ensureGrammars,Ge as escapeRegExp,tn as explainQuery,Vt as extToLang,Eo as extractAst,Co as extractCode,rd as extractGrammarsTarball,Kc as extractInParallel,Qi as extractMarkdown,Ki as extractSymbols,Pp as extractTags,nd as extractTarInto,td as fetchExpectedSha256,Qc as fetchGrammarsTarball,dn as fileUri,Dr as findDeadCode,rn as findLiteralDuplications,sa as findReferences,An as findSymbol,_t as foldText,Ua as formatDeltaPanel,Ze as gitChurn,Yn as grammarKeyForExt,bt as grammarKeysForExts,tt as grammarReady,Hu as grammarWasmName,Er as grepRepo,qh as hasEmbedModel,Qu as hasFileBytes,at as have,as as headCommit,ru as healthzUrl,ku as hubThreshold,Wr as impactOf,lr as implementationsOf,oa as insertAfterSymbol,aa as insertBeforeSymbol,xa as intDot,Ql as isCode,Yl as isDoc,zi as isGitWorktree,is as isIgnored,z_ as isSurprising,Ls as isTestFile,$t as isTestPath,Io as keptCodeFiles,rs as keywords,Xi as languageOf,fa as listMemories,Wt as loadEmbedModel,Wy as loadGrammars,mi as loadLspConfig,di as locationsToRefs,Pr as lspStatus,Bt as lspUnavailable,ol as mountFiles,Bu as mountGrammar,Uu as mountRuntime,fr as neighborhood,Da as neighborsOf,ka as onboardBrief,Ma as openLspSession,gr as pagerankOf,Di as parseGitignore,uu as parseLspConfig,$r as parseRules,Fo as preloadArtifacts,Po as preloadSession,Ar as probeEndpoint,ef as pruneUnfetched,ir as pullGrammars,Rr as quantize,cn as rankHotspots,af as rankedKeywords,da as readMemory,Oo as readPersistedIndex,G as readText,Pa as referencesWithLsp,lu as relFromUri,In as renderGraphJson,jr as renderMermaid,yy as renderMermaidClustered,ln as renderRepoMap,ya as renderScip,js as renderSymbolsJson,ia as replaceSymbolBody,Yu as resetVfs,tf as residentBytes,Hi as resolveBaseRef,qo as resolveCallEdges,zo as resolveDocLink,Ut as resolveEmbedEndpoint,vt as resolveEmbedModelDir,wa as resolveEmbedPullUrl,Sm as resolveGrammarsDir,Fs as resolveGrammarsPullTarget,Qe as resolveGrammarsTier,or as resolveImport,fi as resolveLspConfigPath,Go as resolveRelationEdges,ar as resolveRelations,Xs as resolveUniqueSymbol,Eu as reverseClosure,Du as rewriteCommand,hr as riskHotspots,eu as roundHalfToEven,$i as rrf,jy as runCli,Sp as runExtractWorker,Pu as runMcpServer,Pe as scanRepo,Pt as scanRepoParallel,rr as scanSummary,Lt as searchIndex,an as searchSemantic,oi as serializeEmbeddings,Aa as serverForLang,ts as setFileBytes,pe as sh,Me as sha1,wn as sharedGrammarsCacheDir,yf as shortHash,Pi as slugify,Oa as spawnLspTransport,ht as subtokens,_r as symbolComplexity,en as symbolId,vu as symbolsInHunks,ra as symbolsOverview,Fp as tagsQueryStatus,Ag as testsForModule,od as tierForPath,De as toCacheMap,Qd as tokenize,wg as typeEntry,Qo as uniqueSymbolDefs,Tg as untestedModules,ls as untrackedFiles,Fe as walk,jp as warmGrammars,Yd as wordpiece,Jc as workerCount,br as writeMemory}; diff --git a/scripts/engine.d.mts b/scripts/engine.d.mts index bcd1043..4c1e2e9 100644 --- a/scripts/engine.d.mts +++ b/scripts/engine.d.mts @@ -1,6 +1,6 @@ declare const ENGINE_VERSION = "2.28.0"; declare const SCHEMA_VERSION = 5; -declare const EXTRACTOR_VERSION = 13; +declare const EXTRACTOR_VERSION = 14; type FileKind = "code" | "doc" | "config" | "asset" | "other"; type EdgeKind = "contains" | "doc-link" | "import" | "call" | "extends" | "implements" | "use" | "mention"; type Tier = 0 | 1 | 2; @@ -1553,6 +1553,7 @@ interface McpServerOptions { defaultRepo?: string; maxResponseBytes?: number; profile?: string; + watch?: boolean; } declare function runMcpServer(opts?: McpServerOptions): Promise; diff --git a/scripts/engine.mjs b/scripts/engine.mjs index 68dd1d3..e4d3a6d 100755 --- a/scripts/engine.mjs +++ b/scripts/engine.mjs @@ -1,8 +1,13 @@ #!/usr/bin/env node var __defProp = Object.defineProperty; var __getOwnPropNames = Object.getOwnPropertyNames; -var __esm = (fn, res) => function __init() { - return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res; +var __esm = (fn, res, err2) => function __init() { + if (err2) throw err2[0]; + try { + return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res; + } catch (e) { + throw err2 = [e], e; + } }; var __export = (target, all) => { for (var name2 in all) @@ -16,7 +21,7 @@ var init_types = __esm({ "use strict"; ENGINE_VERSION = "2.28.0"; SCHEMA_VERSION = 5; - EXTRACTOR_VERSION = 13; + EXTRACTOR_VERSION = 14; } }); @@ -350,6 +355,9 @@ var init_ignore = __esm({ // src/walk.ts import { readdirSync, statSync, lstatSync, readFileSync, realpathSync } from "fs"; import { join, sep, extname } from "path"; +function isIgnoredDirectory(name2, ignoreDirs) { + return ignoreDirs.has(name2) || name2.startsWith(".codeindex-edit-"); +} function walk(root, opts = {}) { const maxFileBytes = opts.maxFileBytes ?? 1024 * 1024; const maxFiles = opts.maxFiles ?? Infinity; @@ -398,7 +406,7 @@ function walk(root, opts = {}) { const abs = join(frame.dir, name2); const rel2 = frame.rel ? `${frame.rel}/${name2}` : name2; const isLink = entry.isSymbolicLink(); - if (entry.isDirectory() && ignoreDirs.has(name2)) continue; + if (entry.isDirectory() && isIgnoredDirectory(name2, ignoreDirs)) continue; let st; try { st = isLink ? statSync(abs) : lstatSync(abs); @@ -406,7 +414,7 @@ function walk(root, opts = {}) { continue; } if (st.isDirectory()) { - if (ignoreDirs.has(name2)) continue; + if (isIgnoredDirectory(name2, ignoreDirs)) continue; if (isLink) continue; if (useGitignore && rules.length && isIgnored(rules, rel2, true)) continue; stack.push({ dir: abs, rel: rel2, rules }); @@ -5741,7 +5749,7 @@ ${JSON.stringify(symbolNames, null, 2)}`); }); // src/ast/loader.ts -import { readFileSync as readFileSync2, existsSync } from "fs"; +import { readFileSync as readFileSync2, existsSync, statSync as statSync2 } from "fs"; import { homedir } from "os"; import { dirname, join as join2 } from "path"; import { fileURLToPath } from "url"; @@ -5798,16 +5806,26 @@ async function ensureGrammars(keys) { parser = new Parser(); } for (const key of new Set(keys)) { - if (loaded.has(key) || failed.has(key)) continue; + if (loaded.has(key)) continue; const wasm = firstIn(`${key}.wasm`); + const fingerprint = wasm ? (() => { + try { + const st = statSync2(wasm); + return `${wasm}:${st.size}:${st.mtimeMs}`; + } catch { + return `${wasm}:unreadable`; + } + })() : `missing:${dirs.join("|")}`; + if (failed.get(key) === fingerprint) continue; if (!wasm) { - failed.add(key); + failed.set(key, fingerprint); continue; } try { loaded.set(key, await Language.load(new Uint8Array(readFileSync2(wasm)))); + failed.delete(key); } catch { - failed.add(key); + failed.set(key, fingerprint); } } } @@ -5903,7 +5921,7 @@ var init_loader = __esm({ runtimeReady = false; parser = null; loaded = /* @__PURE__ */ new Map(); - failed = /* @__PURE__ */ new Set(); + failed = /* @__PURE__ */ new Map(); } }); @@ -8111,6 +8129,7 @@ function buildCodeRecord(rel2, ext, size, content, hash, lang, opts = {}) { record.truncated = code.truncated; record.relations = code.relations; record.terms = code.terms; + record.literals = code.literals; } else { record.title = basename(rel2); } @@ -8189,7 +8208,7 @@ function scanRepo(root, opts = {}) { files.push(preUsable.record); continue; } - const record = { + const record = kind === "code" ? buildCodeRecord(f.rel, f.ext, f.size, content, hash, lang, opts) : { rel: f.rel, ext: f.ext, size: f.size, @@ -8201,37 +8220,21 @@ function scanRepo(root, opts = {}) { symbols: [], refs: [] }; - if (content) { - if (kind === "doc" && MARKDOWN_EXT.has(f.ext)) { + if (kind !== "code") { + if (content && kind === "doc" && MARKDOWN_EXT.has(f.ext)) { const md = extractMarkdown(content); record.title = md.title ?? basename(f.rel); record.summary = md.summary; record.headings = md.headings; record.refs = md.refs; - } else if (kind === "doc") { + } else if (content && kind === "doc") { record.title = basename(f.rel); - } else if (kind === "code") { - const code = extractCode(f.rel, f.ext, content, { maxCallsPerFile: opts.maxCallsPerFile }); - record.title = basename(f.rel); - record.summary = code.summary; - record.symbols = code.symbols; - record.refs = code.refs; - record.pkg = code.pkg; - record.idents = code.idents; - record.calls = code.calls; - record.importedNames = code.importedNames; - record.truncated = code.truncated; - record.relations = code.relations; - record.terms = code.terms; - record.literals = code.literals; - } else if (kind === "config") { + } else if (content && kind === "config") { record.title = basename(f.rel); record.literals = extractConfigLiterals(content); } else { record.title = basename(f.rel); } - } else { - record.title = basename(f.rel); } if (kind === "doc" && content) docText.set(f.rel, content); files.push(record); @@ -8278,6 +8281,13 @@ function toCacheMap(scan2) { for (const f of scan2.files) m.set(f.rel, { hash: f.hash, record: f, size: f.size, mtimeMs: scan2.mtimes.get(f.rel) }); return m; } +function needsGrammarWarm(walked, cache, fullHash = false) { + const codeFiles = walked.files.filter((file) => classify(file.rel, file.ext) === "code"); + return fullHash && codeFiles.length > 0 || codeFiles.some((file) => { + const cached = cache.get(file.rel); + return !cached || cached.size !== file.size || cached.mtimeMs !== file.mtimeMs; + }); +} function readPersistedIndex(repo, indexDir = INDEX_DIR) { let parsed; try { @@ -8329,6 +8339,34 @@ function preloadSession(repo, opts, indexDir = INDEX_DIR) { const scan2 = scanRepo(repo, { ...opts, cache: persisted.cacheMap }); return { scan: scan2, cacheMap: toCacheMap(scan2), arts: preloadArtifacts(repo, scan2, persisted.meta, indexDir) }; } +async function preloadSessionLazy(repo, opts, warm, indexDir = INDEX_DIR) { + const persisted = readPersistedIndex(repo, indexDir); + if (!persisted) return void 0; + const walked = opts.precomputedWalk ?? walk(repo, { + maxFileBytes: opts.maxBytes, + maxFiles: opts.maxFiles, + gitignore: opts.gitignore, + ignoreDirs: opts.ignoreDirs + }); + const needsWarm = needsGrammarWarm(walked, persisted.cacheMap, opts.fullHash); + if (needsWarm) { + await warm(); + } + const scan2 = scanRepo(repo, { ...opts, cache: persisted.cacheMap, precomputedWalk: walked }); + let artifactsTried = false; + let artifacts; + return { + scan: scan2, + cacheMap: toCacheMap(scan2), + loadArtifacts: () => { + if (!artifactsTried) { + artifactsTried = true; + artifacts = preloadArtifacts(repo, scan2, persisted.meta, indexDir); + } + return artifacts; + } + }; +} var INDEX_DIR; var init_preload = __esm({ "src/preload.ts"() { @@ -8336,10 +8374,151 @@ var init_preload = __esm({ init_types(); init_scan(); init_hash(); + init_walk(); + init_classify(); INDEX_DIR = ".codeindex"; } }); +// src/pool.ts +import { existsSync as existsSync2, statSync as statSync3 } from "fs"; +import * as os from "os"; +import { dirname as dirname2, join as join4 } from "path"; +import { fileURLToPath as fileURLToPath2, pathToFileURL } from "url"; +import { Worker } from "worker_threads"; +function resolveEngineUrl() { + try { + const here = fileURLToPath2(import.meta.url); + if (here.endsWith("engine.mjs")) return pathToFileURL(here).href; + const adjacent = join4(dirname2(here), "engine.mjs"); + if (existsSync2(adjacent)) return pathToFileURL(adjacent).href; + return void 0; + } catch { + return void 0; + } +} +function workerCount(requested) { + const env = process.env["CODEINDEX_WORKERS"]; + const raw = requested ?? (env !== void 0 && env !== "" ? Number(env) : void 0); + if (raw !== void 0) return Number.isFinite(raw) && raw > 0 ? Math.floor(raw) : 0; + let cores = 1; + try { + cores = typeof os.availableParallelism === "function" ? os.availableParallelism() : os.cpus().length; + } catch { + cores = 1; + } + return Math.max(0, Math.min(cores - 1, 8)); +} +async function runExtractWorker(input, post) { + await ensureGrammars(input.grammarKeys); + const ready = input.grammarKeys.filter((k) => grammarReady(k)); + const records = []; + for (const job of input.jobs) { + let size; + let mtimeMs; + try { + const st = statSync3(job.abs); + size = st.size; + mtimeMs = st.mtimeMs; + } catch { + continue; + } + const content = readText(job.abs); + const record = buildCodeRecord(job.rel, job.ext, size, content, sha1(content), extToLang(job.ext), { + maxCallsPerFile: input.maxCallsPerFile + }); + records.push({ rel: job.rel, size, mtimeMs, record }); + } + post({ ready, records }); +} +async function extractInParallel(jobs, grammarKeys, count, opts = {}) { + if (count < 2 || jobs.length === 0) return void 0; + const engineUrl = resolveEngineUrl(); + if (!engineUrl) return void 0; + const wanted = grammarKeys.filter((k) => grammarReady(k)).sort(); + const shards = Array.from({ length: Math.min(count, jobs.length) }, () => []); + jobs.forEach((j, i2) => shards[i2 % shards.length].push(j)); + const bootstrap = `import { runExtractWorker } from ${JSON.stringify(engineUrl)}; +import { parentPort, workerData } from "node:worker_threads"; +runExtractWorker(workerData.input, (o) => parentPort.postMessage(o)).catch((e) => parentPort.postMessage({ error: String(e) })); +`; + try { + const outputs = await Promise.all( + shards.map( + (jobsForShard) => new Promise((resolve5, reject) => { + const w = new Worker(bootstrap, { + eval: true, + workerData: { input: { jobs: jobsForShard, grammarKeys: wanted, maxCallsPerFile: opts.maxCallsPerFile } } + }); + const timer = setTimeout(() => { + reject(new Error("extraction worker timed out")); + void w.terminate(); + }, WORKER_TIMEOUT_MS); + const settle = (fn) => { + clearTimeout(timer); + fn(); + }; + w.once("message", (m) => { + settle(() => resolve5(m)); + void w.terminate(); + }); + w.once("error", (e) => settle(() => reject(e))); + w.once("exit", (code) => { + if (code !== 0) settle(() => reject(new Error(`extraction worker exited with ${code}`))); + }); + }) + ) + ); + const out2 = /* @__PURE__ */ new Map(); + for (const o of outputs) { + if ("error" in o) return void 0; + if (o.ready.slice().sort().join(",") !== wanted.join(",")) return void 0; + for (const r of o.records) out2.set(r.rel, { size: r.size, mtimeMs: r.mtimeMs, record: r.record }); + } + return out2; + } catch { + return void 0; + } +} +async function scanRepoParallel(root, opts = {}) { + const count = workerCount(opts.workers); + if (count < 2) return scanRepo(root, opts); + const walked = opts.precomputedWalk ?? walk(root, { + maxFileBytes: opts.maxBytes, + maxFiles: opts.maxFiles, + gitignore: opts.gitignore, + ignoreDirs: opts.ignoreDirs + }); + const scanOpts = { ...opts, precomputedWalk: walked }; + const jobs = []; + for (const { f } of keptCodeFiles(root, scanOpts)) { + const cached = opts.cache?.get(f.rel); + if (!opts.fullHash && cached && cached.size !== void 0 && cached.mtimeMs !== void 0 && cached.size === f.size && cached.mtimeMs === f.mtimeMs) { + continue; + } + jobs.push({ abs: f.abs, rel: f.rel, ext: f.ext }); + } + if (jobs.length === 0) return scanRepo(root, scanOpts); + const workersForced = opts.workers !== void 0 || (process.env["CODEINDEX_WORKERS"] ?? "") !== ""; + if (!workersForced && jobs.length < DEFAULT_MIN_PARALLEL_JOBS) return scanRepo(root, scanOpts); + const grammarKeys = grammarKeysForExts(walked.files.map((f) => f.ext)); + const extracted = await extractInParallel(jobs, grammarKeys, count, { maxCallsPerFile: opts.maxCallsPerFile }); + return scanRepo(root, extracted ? { ...scanOpts, extracted } : scanOpts); +} +var WORKER_TIMEOUT_MS, DEFAULT_MIN_PARALLEL_JOBS; +var init_pool = __esm({ + "src/pool.ts"() { + "use strict"; + init_hash(); + init_walk(); + init_registry(); + init_loader(); + init_scan(); + WORKER_TIMEOUT_MS = 10 * 60 * 1e3; + DEFAULT_MIN_PARALLEL_JOBS = 200; + } +}); + // src/resolve.ts import { posix } from "path"; import { join as join7 } from "path"; @@ -9451,6 +9630,17 @@ function buildCallerIndex(scan2, importPairs, opts = {}) { arr.push(s); } } + const defsByFamily = /* @__PURE__ */ new Map(); + for (const [name2, sites2] of defs) { + const families = /* @__PURE__ */ new Map(); + for (const site of sites2) { + const family = familyOf(site.lang); + let grouped = families.get(family); + if (!grouped) families.set(family, grouped = []); + grouped.push(site); + } + defsByFamily.set(name2, families); + } const localDefs = /* @__PURE__ */ new Map(); for (const f of scan2.files) { const byName = /* @__PURE__ */ new Map(); @@ -9476,7 +9666,7 @@ function buildCallerIndex(scan2, importPairs, opts = {}) { record(local, recall ? { file: f.rel, line: c2.line, confidence: "corroborated" } : { file: f.rel, line: c2.line }); continue; } - const cands = (defs.get(c2.name) ?? []).filter((d) => familyOf(d.lang) === family && d.file !== f.rel).map((d) => ({ file: d.file, lang: d.lang })); + const cands = (defsByFamily.get(c2.name)?.get(family) ?? []).filter((d) => d.file !== f.rel); if (!cands.length) continue; const imported = cands.filter((d) => pairs.has(`${f.rel}|${d.file}`)); const chosen = family === "js" ? imported.length ? pickCandidate(f.rel, imported) : ( @@ -9485,7 +9675,7 @@ function buildCallerIndex(scan2, importPairs, opts = {}) { recall && cands.length === 1 ? cands[0] : void 0 ) : imported.length ? pickCandidate(f.rel, imported) : pickCandidate(f.rel, cands); if (!chosen) continue; - const def = defs.get(c2.name).find((d) => d.file === chosen.file); + const def = chosen; record( def, recall ? { file: f.rel, line: c2.line, confidence: imported.length ? "corroborated" : "unique-name" } : { file: f.rel, line: c2.line } @@ -10263,6 +10453,25 @@ function cacheFor(scan2) { if (!c2) caches.set(scan2, c2 = {}); return c2; } +function fileByRelFor(scan2) { + const c2 = cacheFor(scan2); + return c2.fileByRel ??= new Map(scan2.files.map((file) => [file.rel, file])); +} +function symbolsByNameFor(scan2) { + const c2 = cacheFor(scan2); + if (!c2.symbolsByName) { + const byName = /* @__PURE__ */ new Map(); + for (const file of scan2.files) { + for (const symbol of file.symbols) { + const group = byName.get(symbol.name); + if (group) group.push(symbol); + else byName.set(symbol.name, [symbol]); + } + } + c2.symbolsByName = byName; + } + return c2.symbolsByName; +} function resolveContextFor(scan2) { const c2 = cacheFor(scan2); return c2.resolveCtx ??= buildResolveContext(scan2); @@ -10569,8 +10778,11 @@ var init_graph = __esm({ // src/query.ts import { join as join11 } from "path"; +function* allSymbols(scan2) { + for (const file of scan2.files) yield* file.symbols; +} function symbolsOverview(scan2, rel2) { - const f = scan2.files.find((x) => x.rel === rel2); + const f = fileByRelFor(scan2).get(rel2); if (!f) return []; return [...f.symbols].filter((s) => !REFERENCE_KINDS5.has(s.kind)).sort((a, b) => a.line - b.line || byStr(a.name, b.name)); } @@ -10581,27 +10793,37 @@ function findSymbol(scan2, namePath, opts = {}) { const parents = segments.slice(0, -1); const matchName = (name2, wanted) => opts.substring ? name2.toLowerCase().includes(wanted.toLowerCase()) : name2 === wanted; const out2 = []; - for (const f of scan2.files) { - for (const s of f.symbols) { - if (REFERENCE_KINDS5.has(s.kind)) continue; - if (!matchName(s.name, leaf)) continue; - if (parents.length) { - const parent = parents[parents.length - 1]; - if (!s.parent || s.parent !== parent) continue; - } - out2.push({ ...s }); + const candidates = opts.substring ? allSymbols(scan2) : symbolsByNameFor(scan2).get(leaf) ?? []; + for (const s of candidates) { + if (REFERENCE_KINDS5.has(s.kind)) continue; + if (!matchName(s.name, leaf)) continue; + if (parents.length) { + const parent = parents[parents.length - 1]; + if (!s.parent || s.parent !== parent) continue; } + out2.push({ ...s }); } out2.sort( (a, b) => Number(b.name === leaf) - Number(a.name === leaf) || byStr(a.file, b.file) || a.line - b.line ); const capped = out2.slice(0, opts.maxResults ?? 50); if (opts.includeBody) { + const linesByFile = /* @__PURE__ */ new Map(); + const unreadableFiles = /* @__PURE__ */ new Set(); for (const m of capped) { const end = m.endLine ?? m.line; - const content = readText(join11(scan2.root, m.file)); - if (!content) continue; - m.body = content.split("\n").slice(m.line - 1, end).join("\n"); + if (unreadableFiles.has(m.file)) continue; + let lines = linesByFile.get(m.file); + if (!lines) { + const content = readText(join11(scan2.root, m.file)); + if (!content) { + unreadableFiles.add(m.file); + continue; + } + lines = content.split("\n"); + linesByFile.set(m.file, lines); + } + m.body = lines.slice(m.line - 1, end).join("\n"); } } if (opts.concise) { @@ -10654,8 +10876,8 @@ var init_query = __esm({ }); // src/edit.ts -import { readFileSync as readFileSync6, writeFileSync as writeFileSync2 } from "fs"; -import { join as join12 } from "path"; +import { chmodSync, mkdtempSync as mkdtempSync2, readFileSync as readFileSync6, realpathSync as realpathSync2, renameSync as renameSync2, rmSync as rmSync2, statSync as statSync4, writeFileSync as writeFileSync2 } from "fs"; +import { basename as basename3, dirname as dirname4, join as join12 } from "path"; function resolveUniqueSymbol(scan2, namePath, file) { let matches = findSymbol(scan2, namePath); if (file) matches = matches.filter((m) => m.file === file); @@ -10670,6 +10892,34 @@ function resolveUniqueSymbol(scan2, namePath, file) { function readLines(abs) { return readFileSync6(abs, "utf8").split("\n"); } +function atomicWriteText(abs, content, cleanup = rmSync2) { + const target = realpathSync2(abs); + const mode = statSync4(target).mode; + let tempDir; + try { + tempDir = mkdtempSync2(join12(dirname4(target), ".codeindex-edit-")); + } catch { + writeFileSync2(target, content); + chmodSync(target, mode); + return; + } + const tempFile = join12(tempDir, basename3(target)); + try { + writeFileSync2(tempFile, content); + chmodSync(tempFile, mode); + try { + renameSync2(tempFile, target); + } catch { + writeFileSync2(target, content); + chmodSync(target, mode); + } + } finally { + try { + cleanup(tempDir, { recursive: true, force: true }); + } catch { + } + } +} function replaceSymbolBody(scan2, namePath, body2, file) { const sym = resolveUniqueSymbol(scan2, namePath, file); const end = sym.endLine ?? sym.line; @@ -10677,7 +10927,7 @@ function replaceSymbolBody(scan2, namePath, body2, file) { const lines = readLines(abs); const newLines = body2.replace(/^\n+|\n+$/g, "").split("\n"); lines.splice(sym.line - 1, end - sym.line + 1, ...newLines); - writeFileSync2(abs, lines.join("\n")); + atomicWriteText(abs, lines.join("\n")); return { file: sym.file, startLine: sym.line, endLine: sym.line + newLines.length - 1, lines: newLines.length }; } function insertAt(scan2, sym, body2, index, blankBefore, blankAfter) { @@ -10690,7 +10940,7 @@ function insertAt(scan2, sym, body2, index, blankBefore, blankAfter) { block.push(...newLines); if (blankAfter && minGap && lines[index]?.trim() !== "") block.push(""); lines.splice(index, 0, ...block); - writeFileSync2(abs, lines.join("\n")); + atomicWriteText(abs, lines.join("\n")); return { file: sym.file, startLine: index + 1, endLine: index + block.length, lines: block.length }; } function insertAfterSymbol(scan2, namePath, body2, file) { @@ -10712,8 +10962,8 @@ var init_edit = __esm({ }); // src/memory.ts -import { mkdirSync as mkdirSync2, readdirSync as readdirSync2, readFileSync as readFileSync7, rmSync as rmSync2, statSync as statSync3, writeFileSync as writeFileSync3 } from "fs"; -import { dirname as dirname4, join as join13 } from "path"; +import { mkdirSync as mkdirSync2, readdirSync as readdirSync2, readFileSync as readFileSync7, rmSync as rmSync3, statSync as statSync5, writeFileSync as writeFileSync3 } from "fs"; +import { dirname as dirname5, join as join13 } from "path"; function sanitize(name2) { const clean = name2.replace(/^mem:/, "").replace(/\.md$/, ""); if (!clean) throw new Error("memory name is empty"); @@ -10731,7 +10981,7 @@ function memoryPath(repo, name2) { } function writeMemory(repo, name2, content) { const path = memoryPath(repo, name2); - mkdirSync2(dirname4(path), { recursive: true }); + mkdirSync2(dirname5(path), { recursive: true }); writeFileSync3(path, content.endsWith("\n") ? content : content + "\n"); return sanitize(name2); } @@ -10745,11 +10995,11 @@ function readMemory(repo, name2) { function deleteMemory(repo, name2) { const path = memoryPath(repo, name2); try { - statSync3(path); + statSync5(path); } catch { return false; } - rmSync2(path); + rmSync3(path); return true; } function listMemories(repo) { @@ -10779,7 +11029,7 @@ var init_memory = __esm({ }); // src/workspaces.ts -import { existsSync as existsSync5, readdirSync as readdirSync3, statSync as statSync4 } from "fs"; +import { existsSync as existsSync5, readdirSync as readdirSync3, statSync as statSync6 } from "fs"; import { join as join14 } from "path"; function readJson(path, label, warnings) { const raw = readText(path); @@ -10948,7 +11198,7 @@ function addPackage(root, dir, found, kind, warnings) { } function isDirAt(root, rel2) { try { - return statSync4(join14(root, rel2)).isDirectory(); + return statSync6(join14(root, rel2)).isDirectory(); } catch { return false; } @@ -12107,31 +12357,31 @@ function serializeEmbeddings(index) { count: index.records.length, records: index.records.map((r) => ({ file: r.file, symbol: r.symbol ?? "", line: r.line ?? 0 })) }); - const headerBuf = Buffer.from(header, "utf8"); - const body2 = Buffer.alloc(index.records.length * index.dim); - let off = 0; + const headerBuf = new TextEncoder().encode(header); + const bodyLength = index.records.length * index.dim; + const out2 = new Uint8Array(8 + headerBuf.length + bodyLength); + out2.set([67, 73, 69, 49], 0); + new DataView(out2.buffer, out2.byteOffset, out2.byteLength).setUint32(4, headerBuf.length, true); + out2.set(headerBuf, 8); + let off = 8 + headerBuf.length; for (const r of index.records) { - for (let d = 0; d < index.dim; d++) body2.writeInt8(r.vec[d] ?? 0, off++); + for (let d = 0; d < index.dim; d++) out2[off++] = r.vec[d] ?? 0; } - const out2 = Buffer.alloc(8 + headerBuf.length + body2.length); - out2.write(MAGIC, 0, "ascii"); - out2.writeUInt32LE(headerBuf.length, 4); - headerBuf.copy(out2, 8); - body2.copy(out2, 8 + headerBuf.length); return out2; } function deserializeEmbeddings(bytes) { - const buf = Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength); - if (buf.length < 8 || buf.toString("ascii", 0, 4) !== MAGIC) { + if (bytes.byteLength < 8 || String.fromCharCode(...bytes.subarray(0, 4)) !== MAGIC) { throw new Error("embeddings.bin: bad magic (not a codeindex embeddings artifact)"); } - const headerLen = buf.readUInt32LE(4); - const header = JSON.parse(buf.toString("utf8", 8, 8 + headerLen)); + const data = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength); + const headerLen = data.getUint32(4, true); + if (8 + headerLen > bytes.byteLength) throw new Error("embeddings.bin: truncated header"); + const header = JSON.parse(new TextDecoder().decode(bytes.subarray(8, 8 + headerLen))); const bodyOff = 8 + headerLen; const { dim } = header; + if (bodyOff + header.records.length * dim > bytes.byteLength) throw new Error("embeddings.bin: truncated body"); const records = header.records.map((m, i2) => { - const vec = new Int8Array(dim); - for (let d = 0; d < dim; d++) vec[d] = buf.readInt8(bodyOff + i2 * dim + d); + const vec = new Int8Array(bytes.buffer.slice(bytes.byteOffset + bodyOff + i2 * dim, bytes.byteOffset + bodyOff + (i2 + 1) * dim)); const rec = { file: m.file, vec }; if (m.symbol) rec.symbol = m.symbol; if (m.line) rec.line = m.line; @@ -12511,18 +12761,33 @@ function createFramer() { }; } function fileUri(root, rel2) { - const abs = `${root.replace(/\/+$/, "")}/${rel2.replace(/^\/+/, "")}`; + const rootPath = root.replace(/\\/g, "/").replace(/\/+$/, ""); + const relPath = rel2.replace(/\\/g, "/").replace(/^\/+/, ""); + const abs = `${rootPath}/${relPath}`; + if (abs.startsWith("//")) { + const [host = "", ...segments] = abs.slice(2).split("/"); + return `file://${encodeURIComponent(host)}/${segments.map(encodeURIComponent).join("/")}`; + } const drive = /^([A-Za-z]):/.exec(abs); const path = drive ? `/${abs}` : abs; - return "file://" + path.split("/").map((segment, i2) => i2 === 0 ? segment : encodeURIComponent(segment)).join("/"); + return "file://" + path.split("/").map((segment, i2) => i2 === 0 || i2 === 1 && /^[A-Za-z]:$/.test(segment) ? segment : encodeURIComponent(segment)).join("/"); } function relFromUri(root, uri) { if (!uri.startsWith("file://")) return void 0; - let path = decodeURIComponent(uri.slice("file://".length)); + let path; + try { + const encoded = uri.slice("file://".length); + path = decodeURIComponent(encoded.startsWith("/") ? encoded : `//${encoded}`).replace(/\\/g, "/"); + } catch { + return void 0; + } if (/^\/[A-Za-z]:/.test(path)) path = path.slice(1); - const base = root.replace(/\/+$/, ""); - if (path === base) return ""; - if (!path.startsWith(`${base}/`)) return void 0; + const base = root.replace(/\\/g, "/").replace(/\/+$/, ""); + const windows = /^[A-Za-z]:/.test(base) || base.startsWith("//"); + const comparablePath = windows ? path.toLowerCase() : path; + const comparableBase = windows ? base.toLowerCase() : base; + if (comparablePath === comparableBase) return ""; + if (!comparablePath.startsWith(`${comparableBase}/`)) return void 0; return path.slice(base.length + 1); } function locationsToRefs(root, raw) { @@ -13326,9 +13591,13 @@ function validateArgs(schema, args2) { if (!spec?.type) continue; const actual = Array.isArray(value) ? "array" : typeof value; if (spec.type === "number") { - if (actual === "number") continue; - if (actual === "string" && Number.isFinite(Number(value)) && value.trim() !== "") continue; - return `\`${key}\` must be a number, got ${actual === "string" ? JSON.stringify(value) : actual}`; + const numeric = actual === "number" ? value : actual === "string" && value.trim() !== "" ? Number(value) : NaN; + if (!Number.isFinite(numeric)) { + return `\`${key}\` must be a number, got ${actual === "string" ? JSON.stringify(value) : actual}`; + } + if (spec.minimum !== void 0 && numeric < spec.minimum) return `\`${key}\` must be at least ${spec.minimum}`; + if (spec.maximum !== void 0 && numeric > spec.maximum) return `\`${key}\` must be at most ${spec.maximum}`; + continue; } if (spec.type === "array") { if (actual !== "array") return `\`${key}\` must be an array of strings, got ${actual}`; @@ -13545,7 +13814,7 @@ var init_tools = __esm({ type: "boolean", description: "Return only name/kind/file/line \u2014 drop the signature, line span, visibility and language. Roughly 2.5x smaller; use it when you are resolving a path and nothing more (default false)." }, - maxResults: { type: "number", description: "Cap matches (default 50)" } + maxResults: { type: "number", minimum: 1, description: "Cap matches (default 50)" } }, required: ["repo", "namePath"] } @@ -13585,7 +13854,7 @@ var init_tools = __esm({ type: "object", properties: { ...repoProp, - budgetTokens: { type: "number", description: "Token budget for the key-files section (default 900)" }, + budgetTokens: { type: "number", minimum: 1, description: "Token budget for the key-files section (default 900)" }, remember: { type: "boolean", description: "Persist the brief as the `onboarding` memory (default true)" } }, required: ["repo"] @@ -13596,7 +13865,7 @@ var init_tools = __esm({ description: "Token-budgeted map of the repository: the highest-PageRank files with their key exported signatures, deterministically rendered to fit `budgetTokens` (default 1024). The densest single read to understand an unfamiliar codebase.", inputSchema: { type: "object", - properties: { ...repoProp, budgetTokens: { type: "number", description: "Approximate token budget (default 1024)" } }, + properties: { ...repoProp, budgetTokens: { type: "number", minimum: 1, description: "Approximate token budget (default 1024)" } }, required: ["repo"] } }, @@ -13690,7 +13959,7 @@ var init_tools = __esm({ properties: { ...repoProp, ...scopeProps, - limit: { type: "number", description: "Cap entries (default: all)" } + limit: { type: "number", minimum: 0, description: "Cap entries (default: all)" } }, required: ["repo"] } @@ -13703,10 +13972,10 @@ var init_tools = __esm({ properties: { ...repoProp, ...scopeProps, - minFiles: { type: "number", description: "Distinct files a value must span (default 2)" }, - minCount: { type: "number", description: "Total occurrences required (default 3)" }, + minFiles: { type: "number", minimum: 1, description: "Distinct files a value must span (default 2)" }, + minCount: { type: "number", minimum: 1, description: "Total occurrences required (default 3)" }, includeTests: { type: "boolean", description: "Count test files too (default false)" }, - limit: { type: "number", description: "Cap duplications (default: all)" } + limit: { type: "number", minimum: 0, description: "Cap duplications (default: all)" } }, required: ["repo"] } @@ -13716,7 +13985,13 @@ var init_tools = __esm({ description: "Cyclomatic-complexity estimates (branch-token counting over AST line spans), most-complex first. Pass `file` for one file's symbols, omit for the repo-wide top. Combine with hotspots: the `risk` field of this tool's sibling ranks complexity \xD7 churn.", inputSchema: { type: "object", - properties: { ...repoProp, file: { type: "string" }, risk: { type: "boolean", description: "Return complexity \xD7 git-churn risk ranking instead" } }, + properties: { + ...repoProp, + file: { type: "string" }, + risk: { type: "boolean", description: "Return complexity \xD7 git-churn risk ranking instead" }, + since: { type: "string", description: "Only count risk churn after this ref" }, + top: { type: "number", minimum: 1, description: "Cap ranked symbols" } + }, required: ["repo"] } }, @@ -13725,7 +14000,11 @@ var init_tools = __esm({ description: "Mermaid diagram of the module graph (renders inline in Claude/GitHub \u2014 no graph database). Optionally scoped to one module's neighborhood.", inputSchema: { type: "object", - properties: { ...repoProp, module: { type: "string", description: "Module slug to focus on" } }, + properties: { + ...repoProp, + module: { type: "string", description: "Module slug to focus on" }, + maxEdges: { type: "number", minimum: 1, description: "Cap rendered edges" } + }, required: ["repo"] } }, @@ -13740,7 +14019,7 @@ var init_tools = __esm({ scope: { type: "string", description: "Restrict to one directory (repo-relative)" }, globs: { type: "array", items: { type: "string" }, description: "Restrict to matching paths" }, ignoreCase: { type: "boolean" }, - maxHits: { type: "number" } + maxHits: { type: "number", minimum: 1 } }, required: ["repo", "pattern"] } @@ -13754,7 +14033,7 @@ var init_tools = __esm({ ...repoProp, ...scopeProps, query: { type: "string", description: "Natural-language or identifier query" }, - limit: { type: "number", description: "Max results (default 20)" }, + limit: { type: "number", minimum: 0, description: "Max results (default 20)" }, fuzzy: { type: "boolean", description: 'Fallback for query terms with zero document frequency: a morphological stem match first ("caching" finds "cache"), then trigram similarity for typos (default true)' @@ -13788,7 +14067,7 @@ var init_tools = __esm({ ...repoProp, ...scopeProps, query: { type: "string", description: "Natural-language or identifier query" }, - limit: { type: "number", description: "Max results (default 20)" }, + limit: { type: "number", minimum: 0, description: "Max results (default 20)" }, fuzzy: { type: "boolean", description: "Stem/trigram fallback for zero-document-frequency terms (default true)" }, exact: { type: "boolean", description: "Drop results carrying no verbatim term match (default false)" } }, @@ -13826,7 +14105,7 @@ var init_tools = __esm({ properties: { ...repoProp, symbol: { type: "string", description: "Symbol name to centre on" }, - depth: { type: "number", description: "Hops to follow (default 2, max 5)" }, + depth: { type: "number", minimum: 1, maximum: 5, description: "Hops to follow (default 2, max 5)" }, direction: { type: "string", description: "out | in | both (default both)" } }, required: ["repo", "symbol"] @@ -14079,7 +14358,7 @@ var init_tools = __esm({ }); // src/mcp/session.ts -import { statSync as statSync5 } from "fs"; +import { statSync as statSync7 } from "fs"; import { join as join21 } from "path"; function scanFingerprint(scan2) { return sha1(scan2.files.map((f) => `${f.rel}:${f.hash}`).join("\n")); @@ -14094,7 +14373,7 @@ async function memoizedEmbeddingIndex(key, build) { function memoizedEmbedModel(modelDir) { let stat; try { - stat = statSync5(join21(modelDir, "model.json")); + stat = statSync7(join21(modelDir, "model.json")); } catch { return void 0; } @@ -14121,6 +14400,14 @@ function sessionPut(entry) { function sessionClear() { sessionCaches.length = 0; } +function sessionInvalidate(repo, rel2) { + const prefix = repo + "\0"; + for (const entry of sessionCaches) { + if (!entry.key.startsWith(prefix)) continue; + if (rel2) entry.cacheMap.delete(rel2); + else entry.cacheMap.clear(); + } +} function sessionKey(repo, opts) { return repo + "\0" + JSON.stringify({ scope: opts.scope, @@ -14142,7 +14429,11 @@ function getScan(repo, opts = {}, walked) { const fresh = scanRepo(repo, { ...opts, cache: hit.cacheMap, precomputedWalk: walked }); if (fresh.contentUnchanged) { if (fresh.cacheDirty) hit.cacheMap = toCacheMap(fresh); - if (hit.scan.commit !== fresh.commit) hit.scan.commit = fresh.commit; + if (hit.scan.commit !== fresh.commit) { + hit.scan.commit = fresh.commit; + hit.arts = void 0; + hit.loadArtifacts = void 0; + } return hit.scan; } sessionPut({ key, scan: fresh, cacheMap: toCacheMap(fresh) }); @@ -14150,31 +14441,77 @@ function getScan(repo, opts = {}, walked) { } const preloaded = preloadSession(repo, { ...opts, precomputedWalk: walked }); if (preloaded) { - sessionPut({ key, scan: preloaded.scan, cacheMap: preloaded.cacheMap, arts: preloaded.arts }); + sessionPut({ + key, + scan: preloaded.scan, + cacheMap: preloaded.cacheMap, + arts: preloaded.arts + }); return preloaded.scan; } const scan2 = scanRepo(repo, { ...opts, precomputedWalk: walked }); sessionPut({ key, scan: scan2, cacheMap: toCacheMap(scan2) }); return scan2; } -function getScanSummary(repo, opts = {}, walked) { - if (sessionCaches.some((e) => e.key === sessionKey(repo, opts))) { - const scan2 = getScan(repo, opts, walked); - return { - root: scan2.root, - commit: scan2.commit, - fileCount: scan2.files.length, - languages: scan2.languages, - capped: scan2.capped, - excluded: scan2.excluded +async function getScanParallel(repo, opts = {}, walked, warm = async () => { +}) { + const key = sessionKey(repo, opts); + const existing = sessionCaches.find((entry) => entry.key === key); + if (existing) { + const originalCache = existing.cacheMap; + const reuseUnchanged = (fresh) => { + if (fresh.cacheDirty) existing.cacheMap = toCacheMap(fresh); + if (existing.scan.commit !== fresh.commit) { + existing.scan.commit = fresh.commit; + existing.arts = void 0; + existing.loadArtifacts = void 0; + } + sessionGet(key); + return existing.scan; }; + if (walked && needsGrammarWarm(walked, originalCache, opts.fullHash)) { + await warm(); + const fresh = await scanRepoParallel(repo, { ...opts, cache: originalCache, precomputedWalk: walked }); + if (fresh.contentUnchanged) return reuseUnchanged(fresh); + sessionPut({ key, scan: fresh, cacheMap: toCacheMap(fresh) }); + return fresh; + } + const provisional = scanRepo(repo, { ...opts, cache: originalCache, precomputedWalk: walked }); + if (provisional.contentUnchanged) { + return reuseUnchanged(provisional); + } + if (walked) { + sessionPut({ key, scan: provisional, cacheMap: toCacheMap(provisional) }); + return provisional; + } + await warm(); + const scan3 = await scanRepoParallel(repo, { ...opts, cache: originalCache, precomputedWalk: walked }); + sessionPut({ key, scan: scan3, cacheMap: toCacheMap(scan3) }); + return scan3; + } + const preloaded = await preloadSessionLazy(repo, { ...opts, precomputedWalk: walked }, warm); + if (preloaded) { + sessionPut({ + key, + scan: preloaded.scan, + cacheMap: preloaded.cacheMap, + arts: preloaded.arts, + loadArtifacts: preloaded.loadArtifacts + }); + return preloaded.scan; } + await warm(); + const scan2 = await scanRepoParallel(repo, { ...opts, precomputedWalk: walked }); + sessionPut({ key, scan: scan2, cacheMap: toCacheMap(scan2) }); + return scan2; +} +function getScanSummary(repo, opts = {}, walked) { return scanSummary(repo, { ...opts, precomputedWalk: walked }); } -function getArtifacts(repo, opts = {}, walked) { - const scan2 = getScan(repo, opts, walked); +function getArtifacts(repo, opts = {}, walked, prepared) { + const scan2 = prepared ?? getScan(repo, opts, walked); const entry = sessionCaches.find((e) => e.scan === scan2); - if (entry) return entry.arts ??= buildArtifactsFromScan(scan2, opts); + if (entry) return entry.arts ??= entry.loadArtifacts?.() ?? buildArtifactsFromScan(scan2, opts); return buildArtifactsFromScan(scan2, opts); } async function warmGrammarsForRepo(repo) { @@ -14189,6 +14526,7 @@ var init_session = __esm({ "use strict"; init_pipeline(); init_scan(); + init_pool(); init_preload(); init_walk(); init_loader(); @@ -14213,6 +14551,7 @@ __export(mcp_exports, { capResponse: () => capResponse, getArtifacts: () => getArtifacts, getScan: () => getScan, + getScanParallel: () => getScanParallel, getScanSummary: () => getScanSummary, memoizedEmbedModel: () => memoizedEmbedModel, memoizedEmbeddingIndex: () => memoizedEmbeddingIndex, @@ -14229,9 +14568,20 @@ __export(mcp_exports, { warmGrammarsForRepo: () => warmGrammarsForRepo, warmGrammarsForWalk: () => warmGrammarsForWalk }); -import { readFileSync as readFileSync12 } from "fs"; +import { readFileSync as readFileSync12, statSync as statSync8, watch as watchFs } from "fs"; import { isAbsolute, join as join22 } from "path"; import { createInterface } from "readline"; +function isRpcRequest(value) { + if (!value || typeof value !== "object" || Array.isArray(value)) return false; + const req = value; + if (req.jsonrpc !== "2.0" || typeof req.method !== "string") return false; + return req.id === void 0 || req.id === null || typeof req.id === "number" || typeof req.id === "string"; +} +function isRpcResponse(value) { + if (!value || typeof value !== "object" || Array.isArray(value)) return false; + const response = value; + return response.jsonrpc === "2.0" && typeof response.method !== "string" && ("result" in response || "error" in response); +} function str(v) { return typeof v === "string" && v ? v : void 0; } @@ -14240,7 +14590,11 @@ function strArray(v) { } function num(v) { const n = typeof v === "number" ? v : typeof v === "string" && v.trim() !== "" ? Number(v) : NaN; - return Number.isFinite(n) && n > 0 ? n : void 0; + return Number.isFinite(n) && n >= 0 ? n : void 0; +} +function positiveNum(v) { + const n = num(v); + return n !== void 0 && n > 0 ? n : void 0; } function errMessage(e) { return e instanceof Error ? e.message : String(e); @@ -14248,14 +14602,27 @@ function errMessage(e) { async function callTool(name2, args2, defaultRepo) { const repo = str(args2.repo) ?? defaultRepo; if (!repo) throw new Error("`repo` is required (absolute path to the repository root)"); + try { + if (!statSync8(repo).isDirectory()) throw new Error("not a directory"); + } catch { + throw new Error(`repository root is not a readable directory: ${repo}`); + } const scanOpts = { scope: str(args2.scope), include: strArray(args2.include), exclude: strArray(args2.exclude) }; const rankArg = str(args2.rank); const rankOpt = rankArg === "graph" || rankArg === "lexical" ? { rank: rankArg } : {}; let walked; + let preparedScan; if (!SCANLESS_TOOLS.has(name2)) { walked = walk(repo, {}); - await warmGrammarsForWalk(walked); + preparedScan = await getScanParallel( + repo, + scanOpts, + walked, + () => walked ? warmGrammarsForWalk(walked) : Promise.resolve() + ); } + const readScan = () => preparedScan ?? getScan(repo, scanOpts, walked); + const readArtifacts = () => getArtifacts(repo, scanOpts, walked, preparedScan); if (name2 === "scan_summary") { const s = getScanSummary(repo, scanOpts, walked); return JSON.stringify( @@ -14265,10 +14632,10 @@ async function callTool(name2, args2, defaultRepo) { ); } if (name2 === "graph") { - return renderGraphJson(getArtifacts(repo, scanOpts, walked).graph); + return renderGraphJson(readArtifacts().graph); } if (name2 === "symbols") { - const { symbols } = getArtifacts(repo, scanOpts, walked); + const { symbols } = readArtifacts(); const lookup = str(args2.name); if (lookup) { return JSON.stringify({ name: lookup, defs: symbols.defs[lookup] ?? [], refs: symbols.refs[lookup] ?? [] }, null, 2); @@ -14276,7 +14643,7 @@ async function callTool(name2, args2, defaultRepo) { return JSON.stringify(symbols, null, 2); } if (name2 === "callers") { - const scan2 = getScan(repo, scanOpts, walked); + const scan2 = readScan(); const index = args2.recall === true ? buildCallerIndex(scan2, void 0, { recall: true }) : callerIndexFor(scan2); const lookup = str(args2.name); if (lookup) { @@ -14300,35 +14667,35 @@ async function callTool(name2, args2, defaultRepo) { if (name2 === "symbols_overview") { const file = str(args2.file); if (!file) throw new Error("`file` is required"); - return JSON.stringify(symbolsOverview(getScan(repo, scanOpts, walked), file), null, 2); + return JSON.stringify(symbolsOverview(readScan(), file), null, 2); } if (name2 === "find_symbol") { const namePath = str(args2.namePath); if (!namePath) throw new Error("`namePath` is required"); - const matches = findSymbol(getScan(repo, scanOpts, walked), namePath, { + const matches = findSymbol(readScan(), namePath, { substring: args2.substring === true, includeBody: args2.includeBody === true, concise: args2.concise === true, - maxResults: num(args2.maxResults) + maxResults: positiveNum(args2.maxResults) }); return JSON.stringify(matches, null, 2); } if (name2 === "find_references") { const symName = str(args2.name); if (!symName) throw new Error("`name` is required"); - const scan2 = getScan(repo, scanOpts, walked); + const scan2 = readScan(); const statik = findReferences(scan2, symName); if (args2.lsp === true) return JSON.stringify(await referencesWithLsp(scan2, repo, symName, statik), null, 2); return JSON.stringify(statik, null, 2); } if (name2 === "lsp_status") { - return JSON.stringify(await lspStatus(getScan(repo, scanOpts, walked), repo, args2.probe === true), null, 2); + return JSON.stringify(await lspStatus(readScan(), repo, args2.probe === true), null, 2); } if (name2 === "replace_symbol_body" || name2 === "insert_after_symbol" || name2 === "insert_before_symbol") { const namePath = str(args2.namePath); const body2 = typeof args2.body === "string" ? args2.body : void 0; if (!namePath || body2 === void 0) throw new Error("`namePath` and `body` are required"); - const scan2 = getScan(repo, scanOpts, walked); + const scan2 = readScan(); const fn = name2 === "replace_symbol_body" ? replaceSymbolBody : name2 === "insert_after_symbol" ? insertAfterSymbol : insertBeforeSymbol; const result = fn(scan2, namePath, body2, str(args2.file)); sessionClear(); @@ -14356,15 +14723,15 @@ async function callTool(name2, args2, defaultRepo) { return JSON.stringify({ deleted: deleteMemory(repo, memName) }, null, 2); } if (name2 === "dead_code") { - const all = findDeadCode(getScan(repo, scanOpts, walked)); + const all = findDeadCode(readScan()); const limit = num(args2.limit); if (limit === void 0 || all.length <= limit) return JSON.stringify(all, null, 2); return JSON.stringify({ total: all.length, shown: limit, truncated: true, candidates: all.slice(0, limit) }, null, 2); } if (name2 === "duplicated_literals") { - const report = findLiteralDuplications(getScan(repo, scanOpts, walked), { - minFiles: num(args2.minFiles), - minCount: num(args2.minCount), + const report = findLiteralDuplications(readScan(), { + minFiles: positiveNum(args2.minFiles), + minCount: positiveNum(args2.minCount), includeTests: args2.includeTests === true }); const limit = num(args2.limit); @@ -14382,23 +14749,23 @@ async function callTool(name2, args2, defaultRepo) { ); } if (name2 === "complexity") { - const scan2 = getScan(repo, scanOpts, walked); + const scan2 = readScan(); if (args2.risk === true) { const { churn, ok } = gitChurn(repo, { since: str(args2.since) }); - return JSON.stringify({ churnOk: ok, risks: riskHotspots(scan2, churn, num(args2.top)) }, null, 2); + return JSON.stringify({ churnOk: ok, risks: riskHotspots(scan2, churn, positiveNum(args2.top)) }, null, 2); } - return JSON.stringify(symbolComplexity(scan2, str(args2.file), num(args2.top)), null, 2); + return JSON.stringify(symbolComplexity(scan2, str(args2.file), positiveNum(args2.top)), null, 2); } if (name2 === "mermaid") { - const { graph } = getArtifacts(repo, scanOpts, walked); - return renderMermaid(graph, { module: str(args2.module), maxEdges: num(args2.maxEdges) }); + const { graph } = readArtifacts(); + return renderMermaid(graph, { module: str(args2.module), maxEdges: positiveNum(args2.maxEdges) }); } if (name2 === "onboard") { - const scan2 = getScan(repo, scanOpts, walked); - const { graph } = getArtifacts(repo, scanOpts, walked); + const scan2 = readScan(); + const { graph } = readArtifacts(); return JSON.stringify( onboardBrief(scan2, graph, { - ...typeof args2.budgetTokens === "number" ? { budgetTokens: args2.budgetTokens } : {}, + ...positiveNum(args2.budgetTokens) !== void 0 ? { budgetTokens: positiveNum(args2.budgetTokens) } : {}, ...args2.remember === false ? { remember: false } : {} }), null, @@ -14406,11 +14773,11 @@ async function callTool(name2, args2, defaultRepo) { ); } if (name2 === "repo_map") { - const { scan: scan2, graph } = getArtifacts(repo, scanOpts, walked); - return renderRepoMap(scan2, graph, { budgetTokens: typeof args2.budgetTokens === "number" ? args2.budgetTokens : void 0 }); + const { scan: scan2, graph } = readArtifacts(); + return renderRepoMap(scan2, graph, { budgetTokens: positiveNum(args2.budgetTokens) }); } if (name2 === "hotspots") { - const scan2 = getScan(repo, scanOpts, walked); + const scan2 = readScan(); const { churn, ok } = gitChurn(repo, { since: str(args2.since) }); return JSON.stringify({ churnOk: ok, hotspots: rankHotspots(scan2, churn) }, null, 2); } @@ -14426,15 +14793,15 @@ async function callTool(name2, args2, defaultRepo) { const hits = grepRepo(repo, pattern, { globs: scope ? [...globs ?? [], `${scope.replace(/\/+$/, "")}/**`] : globs, ignoreCase: args2.ignoreCase === true, - maxHits: typeof args2.maxHits === "number" ? args2.maxHits : void 0 + maxHits: positiveNum(args2.maxHits) }); return JSON.stringify(hits, null, 2); } if (name2 === "search") { const query = str(args2.query); if (!query) throw new Error("`query` is required"); - const scan2 = getScan(repo, scanOpts, walked); - const limit = typeof args2.limit === "number" ? args2.limit : void 0; + const scan2 = readScan(); + const limit = num(args2.limit); const fuzzy = typeof args2.fuzzy === "boolean" ? args2.fuzzy : void 0; const exactOpt = args2.exact === true ? { exact: true } : {}; if (args2.semantic === true) { @@ -14477,8 +14844,8 @@ async function callTool(name2, args2, defaultRepo) { if (name2 === "explain_search") { const query = str(args2.query); if (!query) throw new Error("`query` is required"); - const scan2 = getScan(repo, scanOpts, walked); - const limit = typeof args2.limit === "number" ? args2.limit : void 0; + const scan2 = readScan(); + const limit = num(args2.limit); const fuzzy = typeof args2.fuzzy === "boolean" ? args2.fuzzy : void 0; const { results, explain } = explainQuery(scan2, query, { limit, @@ -14503,7 +14870,7 @@ async function callTool(name2, args2, defaultRepo) { return JSON.stringify(status, null, 2); } if (name2 === "type_hierarchy") { - const hierarchy = hierarchyFor(getScan(repo, scanOpts, walked)); + const hierarchy = hierarchyFor(readScan()); const wanted = str(args2.name); if (!wanted) { const obj = {}; @@ -14517,7 +14884,7 @@ async function callTool(name2, args2, defaultRepo) { if (name2 === "implementations") { const wanted = str(args2.name); if (!wanted) throw new Error("`name` is required"); - const hierarchy = hierarchyFor(getScan(repo, scanOpts, walked)); + const hierarchy = hierarchyFor(readScan()); if (!hierarchy.has(wanted)) return JSON.stringify({ error: `no type named ${wanted}` }, null, 2); return JSON.stringify({ name: wanted, implementations: implementationsOf(hierarchy, wanted) }, null, 2); } @@ -14526,8 +14893,8 @@ async function callTool(name2, args2, defaultRepo) { if (!symbol) throw new Error("`symbol` is required"); const direction = str(args2.direction); const dir = direction === "out" || direction === "in" ? direction : "both"; - const result = neighborhood(symbolGraphFor(getScan(repo, scanOpts, walked)), symbol, { - ...typeof args2.depth === "number" ? { depth: args2.depth } : {}, + const result = neighborhood(symbolGraphFor(readScan()), symbol, { + ...positiveNum(args2.depth) !== void 0 ? { depth: positiveNum(args2.depth) } : {}, direction: dir }); if (!result.root.length) return JSON.stringify({ error: `no symbol named ${symbol}` }, null, 2); @@ -14546,7 +14913,7 @@ async function callTool(name2, args2, defaultRepo) { } if (payload === void 0) throw new Error("`rules` (or `configPath`) is required"); const rules = parseRules(payload); - const { graph } = getArtifacts(repo, scanOpts, walked); + const { graph } = readArtifacts(); return JSON.stringify(checkRules(graph, rules), null, 2); } throw new Error(`unknown tool: ${name2}`); @@ -14558,31 +14925,81 @@ async function runMcpServer(opts = {}) { }; let protocolVersion = PROTOCOL_VERSIONS[0]; let tools = toolsFor(opts.defaultRepo, protocolVersion, opts.profile); + let watcher; + if (opts.watch && opts.defaultRepo) { + try { + watcher = watchFs(opts.defaultRepo, { recursive: true }, (_event, filename) => { + const rel2 = filename?.toString().replaceAll("\\", "/") ?? ""; + const ignored = rel2.split("/").some( + (segment) => IGNORE_DIRS.has(segment) || segment.startsWith(".codeindex-edit-") + ); + if (ignored) return; + sessionInvalidate(opts.defaultRepo, rel2 || void 0); + }); + watcher.on("error", (error) => { + process.stderr.write(`codeindex: MCP watcher disabled (${error.message}); using freshness scans +`); + watcher?.close(); + watcher = void 0; + sessionInvalidate(opts.defaultRepo); + }); + } catch (error) { + process.stderr.write( + `codeindex: MCP watcher unavailable (${error instanceof Error ? error.message : String(error)}); using freshness scans +` + ); + } + } const send = (msg) => { - process.stdout.write(JSON.stringify({ jsonrpc: "2.0", ...msg }) + "\n"); + const wire = Array.isArray(msg) ? msg.map((entry) => ({ jsonrpc: "2.0", ...entry })) : { jsonrpc: "2.0", ...msg }; + process.stdout.write(JSON.stringify(wire) + "\n"); }; const rl = createInterface({ input: process.stdin, terminal: false }); - for await (const line of rl) { - const trimmed = line.trim(); - if (!trimmed) continue; - let parsed; - try { - parsed = JSON.parse(trimmed); - } catch { - send({ id: null, error: { code: -32700, message: "parse error" } }); - continue; + try { + for await (const line of rl) { + const trimmed = line.trim(); + if (!trimmed) continue; + let parsed; + try { + parsed = JSON.parse(trimmed); + } catch { + send({ id: null, error: { code: -32700, message: "parse error" } }); + continue; + } + if (Array.isArray(parsed) && parsed.length === 0) { + send({ id: null, error: { code: -32600, message: "invalid request" } }); + continue; + } + const dispatch = async (req) => { + if (isRpcResponse(req)) return void 0; + if (!isRpcRequest(req)) { + return { id: null, error: { code: -32600, message: "invalid request" } }; + } + return handle2(req); + }; + if (Array.isArray(parsed)) { + const replies = []; + for (const req of parsed) { + const reply = await dispatch(req); + if (reply) replies.push(reply); + } + if (replies.length > 0) send(replies); + } else { + const reply = await dispatch(parsed); + if (reply) send(reply); + } } - const requests = Array.isArray(parsed) ? parsed : [parsed]; - for (const req of requests) await handle2(req); + } finally { + watcher?.close(); } async function handle2(req) { - if (req.id === void 0 || req.id === null) return; + const notification = !("id" in req); + const respond = (body2) => notification ? void 0 : { id: req.id ?? null, ...body2 }; try { if (req.method === "initialize") { protocolVersion = negotiateProtocol(req.params?.protocolVersion); tools = toolsFor(opts.defaultRepo, protocolVersion, opts.profile); - send({ - id: req.id, + return respond({ result: { protocolVersion, capabilities: { tools: {} }, @@ -14590,9 +15007,9 @@ async function runMcpServer(opts = {}) { } }); } else if (req.method === "ping") { - send({ id: req.id, result: {} }); + return respond({ result: {} }); } else if (req.method === "tools/list") { - send({ id: req.id, result: { tools } }); + return respond({ result: { tools } }); } else if (req.method === "tools/call") { const params = req.params ?? {}; const name2 = str(params.name) ?? ""; @@ -14609,24 +15026,22 @@ async function runMcpServer(opts = {}) { const capped = text !== raw; const link = capped && protocolVersion >= RICH_TOOLS_SINCE ? resourceLinkFor(text, name2) : void 0; const structured = protocolVersion >= RICH_TOOLS_SINCE ? structuredContentFor(text, capped, OUTPUT_SCHEMAS[name2] !== void 0) : void 0; - send({ - id: req.id, + return respond({ result: { content: link ? [{ type: "text", text }, link] : [{ type: "text", text }], ...structured ? { structuredContent: structured } : {} } }); } catch (e) { - send({ - id: req.id, + return respond({ result: { content: [{ type: "text", text: e instanceof Error ? e.message : String(e) }], isError: true } }); } } else { - send({ id: req.id, error: { code: -32601, message: `method not found: ${req.method}` } }); + return respond({ error: { code: -32601, message: `method not found: ${req.method}` } }); } } catch (e) { - send({ id: req.id, error: { code: -32603, message: e instanceof Error ? e.message : String(e) } }); + return respond({ error: { code: -32603, message: e instanceof Error ? e.message : String(e) } }); } } } @@ -14678,8 +15093,7 @@ var init_mcp = __esm({ "delete_memory", "embed_status", // scan_summary counts and classifies by path only — it never parses, so the - // grammar warm (a whole extra walk) would be pure overhead. When a scan is - // already cached getScanSummary reuses it, warm grammars included. + // grammar warm (a whole extra walk) would be pure overhead. "scan_summary" ]); } @@ -14806,138 +15220,7 @@ init_walk(); init_scan(); init_scan(); init_preload(); - -// src/pool.ts -init_hash(); -init_walk(); -init_registry(); -init_loader(); -init_scan(); -import { existsSync as existsSync2, statSync as statSync2 } from "fs"; -import { availableParallelism } from "os"; -import { dirname as dirname2, join as join4 } from "path"; -import { fileURLToPath as fileURLToPath2, pathToFileURL } from "url"; -import { Worker } from "worker_threads"; -function resolveEngineUrl() { - try { - const here = fileURLToPath2(import.meta.url); - if (here.endsWith("engine.mjs")) return pathToFileURL(here).href; - const adjacent = join4(dirname2(here), "engine.mjs"); - if (existsSync2(adjacent)) return pathToFileURL(adjacent).href; - return void 0; - } catch { - return void 0; - } -} -var WORKER_TIMEOUT_MS = 10 * 60 * 1e3; -function workerCount(requested) { - const env = process.env["CODEINDEX_WORKERS"]; - const raw = requested ?? (env !== void 0 && env !== "" ? Number(env) : void 0); - if (raw !== void 0) return Number.isFinite(raw) && raw > 0 ? Math.floor(raw) : 0; - let cores = 1; - try { - cores = availableParallelism(); - } catch { - cores = 1; - } - return Math.max(0, Math.min(cores - 1, 8)); -} -async function runExtractWorker(input, post) { - await ensureGrammars(input.grammarKeys); - const ready = input.grammarKeys.filter((k) => grammarReady(k)); - const records = []; - for (const job of input.jobs) { - let size; - let mtimeMs; - try { - const st = statSync2(job.abs); - size = st.size; - mtimeMs = st.mtimeMs; - } catch { - continue; - } - const content = readText(job.abs); - const record = buildCodeRecord(job.rel, job.ext, size, content, sha1(content), extToLang(job.ext), { - maxCallsPerFile: input.maxCallsPerFile - }); - records.push({ rel: job.rel, size, mtimeMs, record }); - } - post({ ready, records }); -} -async function extractInParallel(jobs, grammarKeys, count, opts = {}) { - if (count < 2 || jobs.length === 0) return void 0; - const engineUrl = resolveEngineUrl(); - if (!engineUrl) return void 0; - const wanted = grammarKeys.filter((k) => grammarReady(k)).sort(); - const shards = Array.from({ length: Math.min(count, jobs.length) }, () => []); - jobs.forEach((j, i2) => shards[i2 % shards.length].push(j)); - const bootstrap = `import { runExtractWorker } from ${JSON.stringify(engineUrl)}; -import { parentPort, workerData } from "node:worker_threads"; -runExtractWorker(workerData.input, (o) => parentPort.postMessage(o)).catch((e) => parentPort.postMessage({ error: String(e) })); -`; - try { - const outputs = await Promise.all( - shards.map( - (jobsForShard) => new Promise((resolve5, reject) => { - const w = new Worker(bootstrap, { - eval: true, - workerData: { input: { jobs: jobsForShard, grammarKeys: wanted, maxCallsPerFile: opts.maxCallsPerFile } } - }); - const timer = setTimeout(() => { - reject(new Error("extraction worker timed out")); - void w.terminate(); - }, WORKER_TIMEOUT_MS); - const settle = (fn) => { - clearTimeout(timer); - fn(); - }; - w.once("message", (m) => { - settle(() => resolve5(m)); - void w.terminate(); - }); - w.once("error", (e) => settle(() => reject(e))); - w.once("exit", (code) => { - if (code !== 0) settle(() => reject(new Error(`extraction worker exited with ${code}`))); - }); - }) - ) - ); - const out2 = /* @__PURE__ */ new Map(); - for (const o of outputs) { - if ("error" in o) return void 0; - if (o.ready.slice().sort().join(",") !== wanted.join(",")) return void 0; - for (const r of o.records) out2.set(r.rel, { size: r.size, mtimeMs: r.mtimeMs, record: r.record }); - } - return out2; - } catch { - return void 0; - } -} -async function scanRepoParallel(root, opts = {}) { - const count = workerCount(opts.workers); - if (count < 2) return scanRepo(root, opts); - const walked = opts.precomputedWalk ?? walk(root, { - maxFileBytes: opts.maxBytes, - maxFiles: opts.maxFiles, - gitignore: opts.gitignore, - ignoreDirs: opts.ignoreDirs - }); - const scanOpts = { ...opts, precomputedWalk: walked }; - const jobs = []; - for (const { f } of keptCodeFiles(root, scanOpts)) { - const cached = opts.cache?.get(f.rel); - if (!opts.fullHash && cached && cached.size !== void 0 && cached.mtimeMs !== void 0 && cached.size === f.size && cached.mtimeMs === f.mtimeMs) { - continue; - } - jobs.push({ abs: f.abs, rel: f.rel, ext: f.ext }); - } - if (jobs.length === 0) return scanRepo(root, scanOpts); - const grammarKeys = grammarKeysForExts(walked.files.map((f) => f.ext)); - const extracted = await extractInParallel(jobs, grammarKeys, count, { maxCallsPerFile: opts.maxCallsPerFile }); - return scanRepo(root, extracted ? { ...scanOpts, extracted } : scanOpts); -} - -// src/engine.ts +init_pool(); init_glob(); init_ignore(); init_classify(); @@ -15251,6 +15534,64 @@ function extractGrammarsTarball(bytes, destDir) { const raw = b.length >= 2 && b[0] === 31 && b[1] === 139 ? gunzipSync(b) : b; return extractTarInto(raw, destDir); } +function installGrammarCacheAtomically(tempDir, cacheDir, markerPath, expectedSha256, rename = renameSync, cleanup = rmSync) { + const parent = dirname3(cacheDir); + const swapDir = mkdtempSync(join6(parent, ".grammars-swap-")); + const previousCache = join6(swapDir, "previous-cache"); + const previousMarker = join6(swapDir, "previous-marker"); + const nextMarker = join6(swapDir, "next-marker"); + let cacheBackedUp = false; + let markerBackedUp = false; + let cacheInstalled = false; + let markerInstalled = false; + try { + if (expectedSha256) writeFileSync(nextMarker, expectedSha256 + "\n"); + if (existsSync4(cacheDir)) { + rename(cacheDir, previousCache); + cacheBackedUp = true; + } + if (existsSync4(markerPath)) { + rename(markerPath, previousMarker); + markerBackedUp = true; + } + rename(tempDir, cacheDir); + cacheInstalled = true; + if (expectedSha256) { + rename(nextMarker, markerPath); + markerInstalled = true; + } + } catch (error) { + const rollbackErrors = []; + const attempt = (operation) => { + try { + operation(); + } catch (rollback) { + rollbackErrors.push(rollback); + } + }; + if (markerInstalled && existsSync4(markerPath)) attempt(() => rmSync(markerPath, { force: true })); + if (cacheInstalled && existsSync4(cacheDir)) attempt(() => rmSync(cacheDir, { recursive: true, force: true })); + if (markerBackedUp && existsSync4(previousMarker)) attempt(() => rename(previousMarker, markerPath)); + if (cacheBackedUp && existsSync4(previousCache)) attempt(() => rename(previousCache, cacheDir)); + if (rollbackErrors.length === 0) { + try { + rmSync(swapDir, { recursive: true, force: true }); + } catch { + } + } + if (rollbackErrors.length > 0) { + const rollbackError = rollbackErrors[0]; + throw new Error( + `${error instanceof Error ? error.message : String(error)}; rollback failed: ${rollbackError instanceof Error ? rollbackError.message : String(rollbackError)} (backup preserved at ${swapDir})` + ); + } + throw error; + } + try { + cleanup(swapDir, { recursive: true, force: true }); + } catch { + } +} async function pullGrammars(cacheDir, opts = {}) { const note = opts.onNote ?? (() => { }); @@ -15299,10 +15640,8 @@ async function pullGrammars(cacheDir, opts = {}) { if (!existsSync4(join6(tmp, "web-tree-sitter.wasm"))) { throw new Error("archive is missing web-tree-sitter.wasm"); } - if (existsSync4(cacheDir)) rmSync(cacheDir, { recursive: true, force: true }); - renameSync(tmp, cacheDir); + installGrammarCacheAtomically(tmp, cacheDir, markerPath, expected); tmp = void 0; - if (expected) writeFileSync(markerPath, expected + "\n"); } catch (e) { if (tmp) { try { @@ -16078,13 +16417,14 @@ init_util(); init_types(); init_types(); init_loader(); -import { existsSync as existsSync10, mkdirSync as mkdirSync3, readFileSync as readFileSync13, writeFileSync as writeFileSync4 } from "fs"; +import { existsSync as existsSync10, mkdirSync as mkdirSync3, readFileSync as readFileSync13, statSync as statSync9, writeFileSync as writeFileSync4 } from "fs"; import { join as join23, resolve as resolve4 } from "path"; init_pipeline(); init_hash(); init_graph_json(); init_symbols_json(); init_scan(); +init_pool(); init_preload(); init_walk(); init_relations(); @@ -16211,7 +16551,8 @@ Commands: advertises a named subset (all | orient | find | impact | edit | risk, default all) \u2014 every advertised tool's schema costs an agent context on EVERY turn, and a tool left out is still answerable - when called by name + when called by name; --watch enables proactive invalidation for a + pinned repo while retaining per-request freshness verification version Print the engine version Flags (accepted before OR after the subcommand: '--repo X scan' and @@ -16362,6 +16703,7 @@ function parseMcpFlags(argv) { let name2; let maxResponseBytes; let profile; + let watch = false; for (let i2 = 0; i2 < argv.length; i2++) { const a = argv[i2]; if (a === "--repo") { @@ -16382,12 +16724,15 @@ function parseMcpFlags(argv) { if (!v) throw new Error(`--tools requires a profile: ${profileNames().join(", ")}`); toolsInProfiles(v); profile = v === "all" ? void 0 : v; + } else if (a === "--watch") { + watch = true; } else { throw new Error(`unknown flag for \`mcp\`: ${a}`); } } if (defaultRepo && !existsSync10(defaultRepo)) throw new Error(`--repo path does not exist: ${defaultRepo}`); - return { defaultRepo, serverInfo: name2 ? { name: name2 } : void 0, maxResponseBytes, profile }; + if (watch && !defaultRepo) throw new Error("--watch requires --repo "); + return { defaultRepo, serverInfo: name2 ? { name: name2 } : void 0, maxResponseBytes, profile, watch }; } var VALUE_FLAGS = /* @__PURE__ */ new Set([ "--repo", @@ -16411,7 +16756,12 @@ var VALUE_FLAGS = /* @__PURE__ */ new Set([ "--tools", "--workers", "--index", - "--max-response-bytes" + "--max-response-bytes", + "--base", + "--depth", + "--kind", + "--rank", + "--direction" ]); function hoistLeadingFlags(argv) { const lead = []; @@ -16457,6 +16807,7 @@ async function runCli(rawArgv) { } const flags2 = parseFlags(rest); if (!existsSync10(flags2.repo)) throw new Error(`--repo path does not exist: ${flags2.repo}`); + if (!statSync9(flags2.repo).isDirectory()) throw new Error(`--repo path is not a directory: ${flags2.repo}`); const scans = !SCANLESS_COMMANDS.has(cmd) && !(cmd === "embed" && flags2.positional !== "build"); let precomputedWalk; if (scans && !flags2.noAst) { @@ -16466,25 +16817,45 @@ async function runCli(rawArgv) { gitignore: flags2.gitignore, ignoreDirs: flags2.ignoreDirs.length ? flags2.ignoreDirs : void 0 }); - await ensureGrammars(grammarKeysForExts(precomputedWalk.files.map((f) => f.ext))); } + let grammarsWarmed = false; + const warmPresentGrammars = async () => { + if (grammarsWarmed || flags2.noAst || !precomputedWalk) return; + await ensureGrammars(grammarKeysForExts(precomputedWalk.files.map((f) => f.ext))); + grammarsWarmed = true; + }; const indexDir = flags2.indexDir ?? INDEX_DIR; let preloadTried = false; + let preloadPromise; let preloaded; - const tryPreload = () => { + const tryPreload = async () => { + if (preloadPromise) return preloadPromise; if (preloadTried) return preloaded; preloadTried = true; if (flags2.noIndexCache) return void 0; - const p = preloadSession(flags2.repo, scanOptions(flags2, precomputedWalk), indexDir); - if (p) preloaded = { scan: p.scan, arts: p.arts }; - return preloaded; + preloadPromise = preloadSessionLazy(flags2.repo, scanOptions(flags2, precomputedWalk), warmPresentGrammars, indexDir).then((p) => { + if (p) preloaded = { scan: p.scan, arts: p.arts, loadArtifacts: p.loadArtifacts }; + return preloaded; + }); + return preloadPromise; }; - const readScan = () => tryPreload()?.scan ?? scanRepo(flags2.repo, scanOptions(flags2, precomputedWalk)); - const readArtifacts = () => { - const p = tryPreload(); + let readScanPromise; + const readScan = async () => { + const preloadedScan = (await tryPreload())?.scan; + if (preloadedScan) return preloadedScan; + return readScanPromise ??= warmPresentGrammars().then( + () => scanRepoParallel(flags2.repo, { + ...scanOptions(flags2, precomputedWalk), + workers: flags2.workers + }) + ); + }; + let readArtifactsPromise; + const readArtifacts = async () => { + const p = await tryPreload(); if (p?.arts) return p.arts; - if (p) return buildArtifactsFromScan(p.scan, scanOptions(flags2, precomputedWalk)); - return buildIndexArtifacts(flags2.repo, scanOptions(flags2, precomputedWalk)); + if (p) return p.arts ??= p.loadArtifacts?.() ?? buildArtifactsFromScan(p.scan, scanOptions(flags2, precomputedWalk)); + return readArtifactsPromise ??= readScan().then((scan2) => buildArtifactsFromScan(scan2, scanOptions(flags2, precomputedWalk))); }; if (cmd === "index") { if (!flags2.out) throw new Error("index needs --out "); @@ -16507,6 +16878,7 @@ async function runCli(rawArgv) { } } catch { } + await warmPresentGrammars(); const scan2 = await scanRepoParallel(flags2.repo, { ...scanOptions(flags2, precomputedWalk), cache, @@ -16585,13 +16957,13 @@ async function runCli(rawArgv) { }; emit(JSON.stringify(summary, null, 2) + "\n", flags2.out); } else if (cmd === "graph") { - const { graph } = readArtifacts(); + const { graph } = await readArtifacts(); emit(renderGraphJson(graph), flags2.out); } else if (cmd === "symbols") { - const { symbols } = readArtifacts(); + const { symbols } = await readArtifacts(); emit(renderSymbolsJson(symbols), flags2.out); } else if (cmd === "scip") { - const scan2 = readScan(); + const scan2 = await readScan(); const bytes = renderScip(scan2, { projectRoot: flags2.projectRoot }); const out2 = flags2.out ?? resolve4("index.scip"); if (out2 === "-") process.stdout.write(Buffer.from(bytes)); @@ -16601,13 +16973,13 @@ async function runCli(rawArgv) { `); } } else if (cmd === "callers") { - const scan2 = readScan(); + const scan2 = await readScan(); const index = buildCallerIndex(scan2, void 0, { recall: flags2.recall }); const obj = {}; for (const [name2, entry] of index) obj[name2] = entry; emit(JSON.stringify(obj, null, 2) + "\n", flags2.out); } else if (cmd === "hierarchy") { - const scan2 = readScan(); + const scan2 = await readScan(); const hierarchy = buildTypeHierarchy(scan2, computeImportPairs(scan2)); if (flags2.positional) { const entry = hierarchy.get(flags2.positional); @@ -16620,7 +16992,7 @@ async function runCli(rawArgv) { } } else if (cmd === "implementations") { if (!flags2.positional) throw new Error("implementations needs a type name: cli.mjs implementations --repo "); - const scan2 = readScan(); + const scan2 = await readScan(); const hierarchy = buildTypeHierarchy(scan2, computeImportPairs(scan2)); if (!hierarchy.has(flags2.positional)) throw new Error(`no type named ${flags2.positional}`); emit( @@ -16629,7 +17001,7 @@ async function runCli(rawArgv) { ); } else if (cmd === "callgraph") { if (!flags2.positional) throw new Error("callgraph needs a symbol: cli.mjs callgraph --repo "); - const scan2 = readScan(); + const scan2 = await readScan(); const graph = buildSymbolGraph(scan2, computeImportPairs(scan2)); const result = neighborhood(graph, flags2.positional, { ...flags2.depth !== void 0 ? { depth: flags2.depth } : {}, @@ -16639,7 +17011,7 @@ async function runCli(rawArgv) { emit(JSON.stringify(result, null, 2) + "\n", flags2.out); } else if (cmd === "search") { if (!flags2.positional) throw new Error('search needs a query: cli.mjs search "" --repo '); - const scan2 = readScan(); + const scan2 = await readScan(); const searchOpts = { limit: flags2.limit, fuzzy: flags2.fuzzy, @@ -16744,7 +17116,7 @@ async function runCli(rawArgv) { } const model = loadEmbedModel(modelDir); mkdirSync3(flags2.out, { recursive: true }); - const scan2 = readScan(); + const scan2 = await readScan(); const index = buildEmbeddingIndex(scan2, model); writeFileSync4(join23(flags2.out, "embeddings.bin"), serializeEmbeddings(index)); process.stderr.write(`codeindex: ${index.records.length} embedding records \u2192 ${flags2.out}/embeddings.bin (model ${model.modelId}) @@ -16783,7 +17155,7 @@ async function runCli(rawArgv) { } else if (cmd === "lsp") { const sub = flags2.positional; if (sub !== "status") throw new Error("lsp needs a subcommand: status"); - emit(JSON.stringify(await lspStatus(readScan(), flags2.repo, flags2.probe === true), null, 2) + "\n", flags2.out); + emit(JSON.stringify(await lspStatus(await readScan(), flags2.repo, flags2.probe === true), null, 2) + "\n", flags2.out); } else if (cmd === "grammars") { const sub = flags2.positional; const cacheDir = sharedGrammarsCacheDir(); @@ -16822,7 +17194,7 @@ async function runCli(rawArgv) { } else if (cmd === "rules") { if (!flags2.config) throw new Error("rules needs --config "); const rules = parseRules(JSON.parse(readFileSync13(flags2.config, "utf8"))); - const { graph } = readArtifacts(); + const { graph } = await readArtifacts(); const violations = checkRules(graph, rules); const errors = violations.filter((v) => v.severity === "error").length; emit(JSON.stringify({ errors, warnings: violations.length - errors, violations }, null, 2) + "\n", flags2.out); @@ -16843,33 +17215,33 @@ async function runCli(rawArgv) { for (const k of [...churn.keys()].sort()) sorted[k] = churn.get(k); emit(JSON.stringify({ ok, churn: sorted }, null, 2) + "\n", flags2.out); } else if (cmd === "repomap") { - const { scan: scan2, graph } = readArtifacts(); + const { scan: scan2, graph } = await readArtifacts(); emit(renderRepoMap(scan2, graph, { budgetTokens: flags2.budgetTokens }), flags2.out); } else if (cmd === "hotspots") { - const scan2 = readScan(); + const scan2 = await readScan(); const { churn, ok } = gitChurn(flags2.repo, { since: flags2.since }); emit(JSON.stringify({ churnOk: ok, hotspots: rankHotspots(scan2, churn) }, null, 2) + "\n", flags2.out); } else if (cmd === "coupling") { const { ok, couplings } = changeCoupling(flags2.repo, { since: flags2.since }); emit(JSON.stringify({ ok, couplings }, null, 2) + "\n", flags2.out); } else if (cmd === "deadcode") { - emit(JSON.stringify(findDeadCode(readScan()), null, 2) + "\n", flags2.out); + emit(JSON.stringify(findDeadCode(await readScan()), null, 2) + "\n", flags2.out); } else if (cmd === "literals") { - const report = findLiteralDuplications(readScan(), { + const report = findLiteralDuplications(await readScan(), { minFiles: flags2.minFiles, minCount: flags2.minCount, includeTests: flags2.includeTests }); emit(JSON.stringify(report, null, 2) + "\n", flags2.out); } else if (cmd === "complexity") { - const scan2 = readScan(); + const scan2 = await readScan(); emit(JSON.stringify(symbolComplexity(scan2, flags2.positional), null, 2) + "\n", flags2.out); } else if (cmd === "risk") { - const scan2 = readScan(); + const scan2 = await readScan(); const { churn, ok } = gitChurn(flags2.repo, { since: flags2.since }); emit(JSON.stringify({ churnOk: ok, risks: riskHotspots(scan2, churn) }, null, 2) + "\n", flags2.out); } else if (cmd === "delta") { - const { graph, symbols } = readArtifacts(); + const { graph, symbols } = await readArtifacts(); const res = deltaFor(flags2.repo, graph, symbols, { base: flags2.base, staged: flags2.staged, @@ -16879,19 +17251,19 @@ async function runCli(rawArgv) { emit(flags2.json ? JSON.stringify(res, null, 2) + "\n" : formatDeltaPanel(res), flags2.out); } else if (cmd === "impact") { if (!flags2.positional) throw new Error("impact needs a target: cli.mjs impact --repo "); - const { graph } = readArtifacts(); + const { graph } = await readArtifacts(); const res = impactOf(graph, flags2.positional, flags2.depth ?? Infinity); if (!res) throw new Error(`no such file or module in the index: ${flags2.positional}`); emit(JSON.stringify(res, null, 2) + "\n", flags2.out); } else if (cmd === "neighbors") { if (!flags2.positional) throw new Error("neighbors needs a target: cli.mjs neighbors --repo "); - const { graph } = readArtifacts(); + const { graph } = await readArtifacts(); const kinds = flags2.kind ? new Set(flags2.kind.split(",").map((k) => k.trim()).filter(Boolean)) : void 0; const res = neighborsOf(graph, flags2.positional, flags2.depth ?? 1, kinds); if (!res) throw new Error(`no such file or module in the index: ${flags2.positional}`); emit(JSON.stringify(res, null, 2) + "\n", flags2.out); } else if (cmd === "mermaid") { - const { graph } = readArtifacts(); + const { graph } = await readArtifacts(); emit(renderMermaid(graph, { module: flags2.positional }), flags2.out); } else if (cmd === "grep") { if (!flags2.positional) throw new Error("grep needs a pattern: cli.mjs grep --repo "); diff --git a/src/ast/grammars-pull.ts b/src/ast/grammars-pull.ts index 8eb2f28..b421ed1 100644 --- a/src/ast/grammars-pull.ts +++ b/src/ast/grammars-pull.ts @@ -188,6 +188,89 @@ export interface GrammarsPullResult { message: string; } +type Rename = (from: string, to: string) => void; + +// Swap a fully validated temporary extraction into place with rollback. The +// previous cache and checksum marker remain on the same filesystem inside a +// swap directory until both new objects have been installed successfully. +// `rename` is injectable only so the failure boundary can be regression-tested. +export function installGrammarCacheAtomically( + tempDir: string, + cacheDir: string, + markerPath: string, + expectedSha256: string | undefined, + rename: Rename = renameSync, + cleanup: typeof rmSync = rmSync, +): void { + const parent = dirname(cacheDir); + const swapDir = mkdtempSync(join(parent, ".grammars-swap-")); + const previousCache = join(swapDir, "previous-cache"); + const previousMarker = join(swapDir, "previous-marker"); + const nextMarker = join(swapDir, "next-marker"); + let cacheBackedUp = false; + let markerBackedUp = false; + let cacheInstalled = false; + let markerInstalled = false; + try { + if (expectedSha256) writeFileSync(nextMarker, expectedSha256 + "\n"); + if (existsSync(cacheDir)) { + rename(cacheDir, previousCache); + cacheBackedUp = true; + } + if (existsSync(markerPath)) { + rename(markerPath, previousMarker); + markerBackedUp = true; + } + rename(tempDir, cacheDir); + cacheInstalled = true; + // No sidecar means the new cache is deliberately unverified: leave no old + // digest marker that could falsely certify these different bytes. + if (expectedSha256) { + rename(nextMarker, markerPath); + markerInstalled = true; + } + } catch (error) { + const rollbackErrors: unknown[] = []; + const attempt = (operation: () => void): void => { + try { + operation(); + } catch (rollback) { + rollbackErrors.push(rollback); + } + }; + if (markerInstalled && existsSync(markerPath)) attempt(() => rmSync(markerPath, { force: true })); + if (cacheInstalled && existsSync(cacheDir)) attempt(() => rmSync(cacheDir, { recursive: true, force: true })); + if (markerBackedUp && existsSync(previousMarker)) attempt(() => rename(previousMarker, markerPath)); + if (cacheBackedUp && existsSync(previousCache)) attempt(() => rename(previousCache, cacheDir)); + // Only discard the swap directory when every backup was restored. On an + // incomplete rollback it is the last recoverable copy of the old cache. + if (rollbackErrors.length === 0) { + try { + rmSync(swapDir, { recursive: true, force: true }); + } catch { + // Preserve the original installation error. + } + } + if (rollbackErrors.length > 0) { + const rollbackError = rollbackErrors[0]; + throw new Error( + `${error instanceof Error ? error.message : String(error)}; rollback failed: ${ + rollbackError instanceof Error ? rollbackError.message : String(rollbackError) + } (backup preserved at ${swapDir})`, + ); + } + throw error; + } + // Cleanup is not part of the transaction. Once both renames succeeded the + // new cache is live; an antivirus/indexer holding the backup directory must + // not turn a successful install into a destructive rollback. + try { + cleanup(swapDir, { recursive: true, force: true }); + } catch { + // A later pull may leave/reuse no data from this uniquely named orphan. + } +} + // The whole `grammars pull` mechanic — resolve target, fetch the sha256 sidecar, // skip when the cache already holds that exact digest, download, then install // ATOMICALLY (extract into a tmp sibling, verify the runtime wasm landed, swap @@ -249,10 +332,8 @@ export async function pullGrammars( if (!existsSync(join(tmp, "web-tree-sitter.wasm"))) { throw new Error("archive is missing web-tree-sitter.wasm"); } - if (existsSync(cacheDir)) rmSync(cacheDir, { recursive: true, force: true }); - renameSync(tmp, cacheDir); + installGrammarCacheAtomically(tmp, cacheDir, markerPath, expected); tmp = undefined; - if (expected) writeFileSync(markerPath, expected + "\n"); } catch (e) { if (tmp) { try { diff --git a/src/ast/loader.ts b/src/ast/loader.ts index b62f213..373eced 100644 --- a/src/ast/loader.ts +++ b/src/ast/loader.ts @@ -1,4 +1,4 @@ -import { readFileSync, existsSync } from "node:fs"; +import { readFileSync, existsSync, statSync } from "node:fs"; import { homedir } from "node:os"; import { dirname, join } from "node:path"; import { fileURLToPath } from "node:url"; @@ -135,11 +135,13 @@ export function resolveGrammarsDir(opts?: { moduleDir?: string }): string | unde let runtimeReady = false; let parser: Parser | null = null; const loaded = new Map(); -const failed = new Set(); +const failed = new Map(); // Load the runtime (once) and the requested grammar keys (each once). Idempotent -// and safe to call repeatedly. A missing/broken wasm is remembered as failed so -// the caller silently falls back to regex rather than retrying every file. +// and safe to call repeatedly. A missing/broken wasm is remembered together +// with the state that failed. If a browser mount, pull, or disk replacement +// changes that state, the next call retries instead of poisoning the process +// for its entire lifetime. export async function ensureGrammars(keys: Iterable): Promise { const { dirs } = resolveGrammarsTier(); if (!dirs.length) return; // nothing resolvable (adjacent/env/cache all absent) → regex everywhere @@ -158,16 +160,28 @@ export async function ensureGrammars(keys: Iterable): Promise { parser = new Parser(); } for (const key of new Set(keys)) { - if (loaded.has(key) || failed.has(key)) continue; + if (loaded.has(key)) continue; const wasm = firstIn(`${key}.wasm`); + const fingerprint = wasm + ? (() => { + try { + const st = statSync(wasm); + return `${wasm}:${st.size}:${st.mtimeMs}`; + } catch { + return `${wasm}:unreadable`; + } + })() + : `missing:${dirs.join("|")}`; + if (failed.get(key) === fingerprint) continue; if (!wasm) { - failed.add(key); + failed.set(key, fingerprint); continue; } try { loaded.set(key, await Language.load(new Uint8Array(readFileSync(wasm)))); + failed.delete(key); } catch { - failed.add(key); + failed.set(key, fingerprint); } } } diff --git a/src/browser/fs.ts b/src/browser/fs.ts index c154651..85e5a11 100644 --- a/src/browser/fs.ts +++ b/src/browser/fs.ts @@ -27,18 +27,25 @@ interface FileEntry { kind: "file"; size: number; mtimeMs: number; + mode: number; bytes?: Uint8Array; // absent = mounted from a manifest, contents not fetched yet } interface DirEntry { kind: "dir"; mtimeMs: number; + mode: number; children: Set; } type Entry = FileEntry | DirEntry; -const entries = new Map([[ROOT, { kind: "dir", mtimeMs: 0, children: new Set() }]]); +const entries = new Map([[ROOT, { kind: "dir", mtimeMs: 0, mode: 0o777, children: new Set() }]]); +let logicalMtime = 0; + +function nextMtime(): number { + return ++logicalMtime; +} // Absolute, normalized, no trailing slash (except the root itself). function key(path: string): string { @@ -72,7 +79,7 @@ function ensureDir(path: string): DirEntry { if (existing.kind !== "dir") throw enotdir(path, "mkdir"); return existing; } - const dir: DirEntry = { kind: "dir", mtimeMs: 0, children: new Set() }; + const dir: DirEntry = { kind: "dir", mtimeMs: 0, mode: 0o777, children: new Set() }; entries.set(k, dir); if (k !== ROOT) { const parent = ensureDir(dirname(k)); @@ -96,7 +103,9 @@ export interface MountedFile { /** Drop everything. Called between two repos so nothing leaks across sessions. */ export function resetVfs(): void { entries.clear(); - entries.set(ROOT, { kind: "dir", mtimeMs: 0, children: new Set() }); + logicalMtime = 0; + tempCounter = 0; + entries.set(ROOT, { kind: "dir", mtimeMs: 0, mode: 0o777, children: new Set() }); } /** @@ -108,7 +117,7 @@ export function mountFiles(files: Iterable): void { for (const f of files) { const k = key(f.path); ensureDir(dirname(k)).children.add(basename(k)); - entries.set(k, { kind: "file", size: f.size, mtimeMs: 0, bytes: f.bytes }); + entries.set(k, { kind: "file", size: f.size, mtimeMs: nextMtime(), mode: 0o666, bytes: f.bytes }); } } @@ -123,6 +132,7 @@ export function setFileBytes(path: string, bytes: Uint8Array): void { if (entry && entry.kind === "file") { entry.bytes = bytes; entry.size = bytes.byteLength; + entry.mtimeMs = nextMtime(); return; } mountFiles([{ path: k, size: bytes.byteLength, bytes }]); @@ -184,6 +194,7 @@ export interface Dirent { export interface Stats { size: number; + mode: number; mtimeMs: number; mtime: Date; isFile(): boolean; @@ -216,6 +227,7 @@ function makeStats(entry: Entry): Stats { const size = entry.kind === "file" ? entry.size : 0; return { size, + mode: entry.mode, mtimeMs: entry.mtimeMs, mtime: new Date(entry.mtimeMs), isFile: () => entry.kind === "file", @@ -287,6 +299,12 @@ export function writeFileSync(path: string, data: string | Uint8Array): void { setFileBytes(path, bytes); } +export function chmodSync(path: string, mode: number): void { + const entry = entries.get(key(path)); + if (!entry) throw enoent(path, "chmod"); + entry.mode = mode; +} + export function mkdirSync(path: string, _options?: { recursive?: boolean }): string | undefined { ensureDir(path); return undefined; @@ -333,6 +351,10 @@ export function renameSync(from: string, to: string): void { rmSync(fromKey, { force: true }); } +export function watch(): never { + throw new Error("recursive filesystem watching is unavailable in the browser VFS"); +} + export default { existsSync, statSync, @@ -341,8 +363,10 @@ export default { readdirSync, readFileSync, writeFileSync, + chmodSync, mkdirSync, mkdtempSync, rmSync, renameSync, + watch, }; diff --git a/src/browser/os.ts b/src/browser/os.ts index e469580..a8bfa61 100644 --- a/src/browser/os.ts +++ b/src/browser/os.ts @@ -21,10 +21,22 @@ export function availableParallelism(): number { return typeof navigator !== "undefined" && navigator?.hardwareConcurrency ? navigator.hardwareConcurrency : 1; } +export function cpus(): Array<{ + model: string; + speed: number; + times: { user: number; nice: number; sys: number; idle: number; irq: number }; +}> { + return Array.from({ length: availableParallelism() }, () => ({ + model: "browser", + speed: 0, + times: { user: 0, nice: 0, sys: 0, idle: 0, irq: 0 }, + })); +} + export function platform(): string { return "browser"; } export const EOL = "\n"; -export default { homedir, tmpdir, availableParallelism, platform, EOL }; +export default { homedir, tmpdir, availableParallelism, cpus, platform, EOL }; diff --git a/src/callers.ts b/src/callers.ts index 3644ca7..30da809 100644 --- a/src/callers.ts +++ b/src/callers.ts @@ -13,7 +13,7 @@ // graph.json stays byte-compatible with ultraindex. import type { CodeSymbol } from "./types.js"; import type { RepoScan } from "./scan.js"; -import { familyOf, pickCandidate, type Cand } from "./calls.js"; +import { familyOf, pickCandidate } from "./calls.js"; import { importPairsFor } from "./derived.js"; import { byStr } from "./sort.js"; @@ -80,6 +80,21 @@ export function buildCallerIndex( arr.push(s); } } + // The hot loop below resolves every call. Group definitions by language + // family once so it does not allocate a filtered + mapped candidate list for + // each site. CodeSymbol structurally contains Cand's file/lang fields, and + // pickCandidate returns the selected object unchanged. + const defsByFamily = new Map>(); + for (const [name, sites] of defs) { + const families = new Map(); + for (const site of sites) { + const family = familyOf(site.lang); + let grouped = families.get(family); + if (!grouped) families.set(family, (grouped = [])); + grouped.push(site); + } + defsByFamily.set(name, families); + } // Same-file binding also needs non-exported defs (a private helper shadows // an exported symbol of the same name elsewhere). const localDefs = new Map>(); @@ -111,9 +126,7 @@ export function buildCallerIndex( record(local, recall ? { file: f.rel, line: c.line, confidence: "corroborated" } : { file: f.rel, line: c.line }); continue; } - const cands: Cand[] = (defs.get(c.name) ?? []) - .filter((d) => familyOf(d.lang) === family && d.file !== f.rel) - .map((d) => ({ file: d.file, lang: d.lang })); + const cands = (defsByFamily.get(c.name)?.get(family) ?? []).filter((d) => d.file !== f.rel); if (!cands.length) continue; const imported = cands.filter((d) => pairs.has(`${f.rel}|${d.file}`)); const chosen = @@ -129,7 +142,7 @@ export function buildCallerIndex( ? pickCandidate(f.rel, imported) : pickCandidate(f.rel, cands); if (!chosen) continue; - const def = defs.get(c.name)!.find((d) => d.file === chosen.file)!; + const def = chosen as CodeSymbol; record( def, recall diff --git a/src/derived.ts b/src/derived.ts index 3d0ee40..0e5a05d 100644 --- a/src/derived.ts +++ b/src/derived.ts @@ -28,7 +28,7 @@ // only (no module-evaluation-time cross-calls), which Node ESM and esbuild // resolve safely. import { join } from "node:path"; -import type { Edge } from "./types.js"; +import type { CodeSymbol, Edge, FileRecord } from "./types.js"; import type { RepoScan } from "./scan.js"; import { buildResolveContext, resolveImport, type ResolveContext } from "./resolve.js"; import { uniqueSymbolDefs } from "./graph.js"; @@ -42,6 +42,8 @@ import { complexityOfSource } from "./complexity.js"; import { readText } from "./walk.js"; interface DerivedCache { + fileByRel?: Map; + symbolsByName?: Map; resolveCtx?: ResolveContext; importPairs?: Set; // `${from}|${to}` resolved-import pairs uniqueDefs?: Map; // uniqueSymbolDefs(scan) @@ -62,6 +64,27 @@ function cacheFor(scan: RepoScan): DerivedCache { return c; } +export function fileByRelFor(scan: RepoScan): Map { + const c = cacheFor(scan); + return (c.fileByRel ??= new Map(scan.files.map((file) => [file.rel, file]))); +} + +export function symbolsByNameFor(scan: RepoScan): Map { + const c = cacheFor(scan); + if (!c.symbolsByName) { + const byName = new Map(); + for (const file of scan.files) { + for (const symbol of file.symbols) { + const group = byName.get(symbol.name); + if (group) group.push(symbol); + else byName.set(symbol.name, [symbol]); + } + } + c.symbolsByName = byName; + } + return c.symbolsByName; +} + export function resolveContextFor(scan: RepoScan): ResolveContext { const c = cacheFor(scan); return (c.resolveCtx ??= buildResolveContext(scan)); diff --git a/src/edit.ts b/src/edit.ts index 867e56c..1bb77e6 100644 --- a/src/edit.ts +++ b/src/edit.ts @@ -4,8 +4,8 @@ // from the deterministic index instead of a live language server. Line-span // granularity: the caller supplies the replacement body verbatim, including // its indentation (same contract as Serena's replace_symbol_body). -import { readFileSync, writeFileSync } from "node:fs"; -import { join } from "node:path"; +import { chmodSync, mkdtempSync, readFileSync, realpathSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs"; +import { basename, dirname, join } from "node:path"; import type { CodeSymbol } from "./types.js"; import type { RepoScan } from "./scan.js"; import { findSymbol } from "./query.js"; @@ -42,6 +42,47 @@ function readLines(abs: string): string[] { return readFileSync(abs, "utf8").split("\n"); } +// Write beside the resolved target and atomically rename over it where the +// platform permits. Symlinks stay symlinks because their real target is edited. +// As with every rename-based atomic replacement, the target receives a new +// inode (hard links/open descriptors keep the old one). Windows locks and +// file-writable/directory-read-only setups fall back to the historical in-place +// write rather than turning a valid edit into EPERM. A killed process can leave +// the hidden temp directory visible to git in a consumer repo; the scanner and +// MCP watcher always ignore the prefix so it cannot become a phantom symbol. +export function atomicWriteText(abs: string, content: string, cleanup: typeof rmSync = rmSync): void { + const target = realpathSync(abs); + const mode = statSync(target).mode; + let tempDir: string; + try { + tempDir = mkdtempSync(join(dirname(target), ".codeindex-edit-")); + } catch { + writeFileSync(target, content); + chmodSync(target, mode); + return; + } + const tempFile = join(tempDir, basename(target)); + try { + writeFileSync(tempFile, content); + chmodSync(tempFile, mode); + try { + renameSync(tempFile, target); + } catch { + writeFileSync(target, content); + chmodSync(target, mode); + } + } finally { + // The target may already have been atomically replaced. Cleanup failure is + // therefore not an edit failure: reporting it as one invites a retry that + // can duplicate insert-before/after operations. + try { + cleanup(tempDir, { recursive: true, force: true }); + } catch { + // The uniquely named orphan is harmless and can be removed later. + } + } +} + // Replace the symbol's whole declaration (lines start..endLine) with `body`. // The body is taken verbatim after trimming outer blank lines — supply it // fully indented for its context. @@ -52,7 +93,7 @@ export function replaceSymbolBody(scan: RepoScan, namePath: string, body: string const lines = readLines(abs); const newLines = body.replace(/^\n+|\n+$/g, "").split("\n"); lines.splice(sym.line - 1, end - sym.line + 1, ...newLines); - writeFileSync(abs, lines.join("\n")); + atomicWriteText(abs, lines.join("\n")); return { file: sym.file, startLine: sym.line, endLine: sym.line + newLines.length - 1, lines: newLines.length }; } @@ -73,7 +114,7 @@ function insertAt( block.push(...newLines); if (blankAfter && minGap && lines[index]?.trim() !== "") block.push(""); lines.splice(index, 0, ...block); - writeFileSync(abs, lines.join("\n")); + atomicWriteText(abs, lines.join("\n")); return { file: sym.file, startLine: index + 1, endLine: index + block.length, lines: block.length }; } diff --git a/src/embed/index.ts b/src/embed/index.ts index 2b9ea97..004ebf6 100644 --- a/src/embed/index.ts +++ b/src/embed/index.ts @@ -96,17 +96,16 @@ export function serializeEmbeddings(index: EmbeddingIndex): Uint8Array { count: index.records.length, records: index.records.map((r) => ({ file: r.file, symbol: r.symbol ?? "", line: r.line ?? 0 })), }); - const headerBuf = Buffer.from(header, "utf8"); - const body = Buffer.alloc(index.records.length * index.dim); - let off = 0; + const headerBuf = new TextEncoder().encode(header); + const bodyLength = index.records.length * index.dim; + const out = new Uint8Array(8 + headerBuf.length + bodyLength); + out.set([0x43, 0x49, 0x45, 0x31], 0); // CIE1 + new DataView(out.buffer, out.byteOffset, out.byteLength).setUint32(4, headerBuf.length, true); + out.set(headerBuf, 8); + let off = 8 + headerBuf.length; for (const r of index.records) { - for (let d = 0; d < index.dim; d++) body.writeInt8(r.vec[d] ?? 0, off++); + for (let d = 0; d < index.dim; d++) out[off++] = r.vec[d] ?? 0; } - const out = Buffer.alloc(8 + headerBuf.length + body.length); - out.write(MAGIC, 0, "ascii"); - out.writeUInt32LE(headerBuf.length, 4); - headerBuf.copy(out, 8); - body.copy(out, 8 + headerBuf.length); return out; } @@ -115,12 +114,13 @@ export function serializeEmbeddings(index: EmbeddingIndex): Uint8Array { // on a bad magic (a corrupt or foreign file) so a caller fails loudly rather // than misreading arbitrary bytes. export function deserializeEmbeddings(bytes: Uint8Array): EmbeddingIndex { - const buf = Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength); - if (buf.length < 8 || buf.toString("ascii", 0, 4) !== MAGIC) { + if (bytes.byteLength < 8 || String.fromCharCode(...bytes.subarray(0, 4)) !== MAGIC) { throw new Error("embeddings.bin: bad magic (not a codeindex embeddings artifact)"); } - const headerLen = buf.readUInt32LE(4); - const header = JSON.parse(buf.toString("utf8", 8, 8 + headerLen)) as { + const data = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength); + const headerLen = data.getUint32(4, true); + if (8 + headerLen > bytes.byteLength) throw new Error("embeddings.bin: truncated header"); + const header = JSON.parse(new TextDecoder().decode(bytes.subarray(8, 8 + headerLen))) as { embedVersion: number; modelId: string; dim: number; @@ -129,9 +129,9 @@ export function deserializeEmbeddings(bytes: Uint8Array): EmbeddingIndex { }; const bodyOff = 8 + headerLen; const { dim } = header; + if (bodyOff + header.records.length * dim > bytes.byteLength) throw new Error("embeddings.bin: truncated body"); const records: EmbeddingRecord[] = header.records.map((m, i) => { - const vec = new Int8Array(dim); - for (let d = 0; d < dim; d++) vec[d] = buf.readInt8(bodyOff + i * dim + d); + const vec = new Int8Array(bytes.buffer.slice(bytes.byteOffset + bodyOff + i * dim, bytes.byteOffset + bodyOff + (i + 1) * dim)); const rec: EmbeddingRecord = { file: m.file, vec }; if (m.symbol) rec.symbol = m.symbol; if (m.line) rec.line = m.line; diff --git a/src/engine-cli.ts b/src/engine-cli.ts index 2319dc0..a7ffc63 100644 --- a/src/engine-cli.ts +++ b/src/engine-cli.ts @@ -1,4 +1,4 @@ -import { existsSync, mkdirSync, mkdtempSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs"; +import { existsSync, mkdirSync, mkdtempSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs"; import { dirname, join, resolve } from "node:path"; import { SCHEMA_VERSION, EXTRACTOR_VERSION, type FileRecord } from "./types.js"; import { ENGINE_VERSION } from "./types.js"; @@ -11,14 +11,14 @@ import { sharedGrammarsCacheDir, } from "./ast/loader.js"; import { resolveGrammarsPullTarget, pullGrammars } from "./ast/grammars-pull.js"; -import { buildIndexArtifacts, buildArtifactsFromScan, type BuildIndexOptions, type IndexArtifacts } from "./pipeline.js"; +import { buildArtifactsFromScan, type BuildIndexOptions, type IndexArtifacts } from "./pipeline.js"; import { sha1 } from "./hash.js"; import { renderGraphJson } from "./render/graph-json.js"; import { renderSymbolsJson } from "./render/symbols-json.js"; import { renderScip } from "./render/scip.js"; -import { scanRepo, scanSummary, type RepoScan } from "./scan.js"; +import { scanSummary, type RepoScan } from "./scan.js"; import { scanRepoParallel } from "./pool.js"; -import { preloadSession, INDEX_DIR } from "./preload.js"; +import { preloadSessionLazy, INDEX_DIR } from "./preload.js"; import { walk, type WalkResult } from "./walk.js"; import { buildTypeHierarchy, implementationsOf } from "./relations.js"; import { computeImportPairs } from "./callers.js"; @@ -152,7 +152,8 @@ Commands: advertises a named subset (all | orient | find | impact | edit | risk, default all) — every advertised tool's schema costs an agent context on EVERY turn, and a tool left out is still answerable - when called by name + when called by name; --watch enables proactive invalidation for a + pinned repo while retaining per-request freshness verification version Print the engine version Flags (accepted before OR after the subcommand: '--repo X scan' and @@ -365,11 +366,13 @@ export function parseMcpFlags(argv: string[]): { serverInfo?: { name?: string }; maxResponseBytes?: number; profile?: string; + watch?: boolean; } { let defaultRepo: string | undefined; let name: string | undefined; let maxResponseBytes: number | undefined; let profile: string | undefined; + let watch = false; for (let i = 0; i < argv.length; i++) { const a = argv[i]; if (a === "--repo") { @@ -392,12 +395,15 @@ export function parseMcpFlags(argv: string[]): { // profile that silently advertised everything would look like it worked. toolsInProfiles(v); profile = v === "all" ? undefined : v; + } else if (a === "--watch") { + watch = true; } else { throw new Error(`unknown flag for \`mcp\`: ${a}`); } } if (defaultRepo && !existsSync(defaultRepo)) throw new Error(`--repo path does not exist: ${defaultRepo}`); - return { defaultRepo, serverInfo: name ? { name } : undefined, maxResponseBytes, profile }; + if (watch && !defaultRepo) throw new Error("--watch requires --repo "); + return { defaultRepo, serverInfo: name ? { name } : undefined, maxResponseBytes, profile, watch }; } // Flags that consume the following argv element. Needed to hoist leading flags @@ -426,6 +432,11 @@ const VALUE_FLAGS = new Set([ "--workers", "--index", "--max-response-bytes", + "--base", + "--depth", + "--kind", + "--rank", + "--direction", ]); // Accept global flags BEFORE the subcommand as well as after, so @@ -496,6 +507,7 @@ export async function runCli(rawArgv: string[]): Promise { const flags = parseFlags(rest); if (!existsSync(flags.repo)) throw new Error(`--repo path does not exist: ${flags.repo}`); + if (!statSync(flags.repo).isDirectory()) throw new Error(`--repo path is not a directory: ${flags.repo}`); // Warm ONLY the grammars for languages actually present, and only for commands // that scan the file tree. Scan-less commands (grep, churn, coupling, @@ -513,8 +525,13 @@ export async function runCli(rawArgv: string[]): Promise { gitignore: flags.gitignore, ignoreDirs: flags.ignoreDirs.length ? flags.ignoreDirs : undefined, }); - await ensureGrammars(grammarKeysForExts(precomputedWalk.files.map((f) => f.ext))); } + let grammarsWarmed = false; + const warmPresentGrammars = async (): Promise => { + if (grammarsWarmed || flags.noAst || !precomputedWalk) return; + await ensureGrammars(grammarKeysForExts(precomputedWalk.files.map((f) => f.ext))); + grammarsWarmed = true; + }; // Read commands reuse a persisted index instead of rebuilding from scratch. // @@ -531,21 +548,40 @@ export async function runCli(rawArgv: string[]): Promise { // uses either the scan or the artifacts, never both. const indexDir = flags.indexDir ?? INDEX_DIR; let preloadTried = false; - let preloaded: { scan: RepoScan; arts?: IndexArtifacts } | undefined; - const tryPreload = (): { scan: RepoScan; arts?: IndexArtifacts } | undefined => { + let preloadPromise: Promise<{ + scan: RepoScan; + arts?: IndexArtifacts; + loadArtifacts?: () => IndexArtifacts | undefined; + } | undefined> | undefined; + let preloaded: { scan: RepoScan; arts?: IndexArtifacts; loadArtifacts?: () => IndexArtifacts | undefined } | undefined; + const tryPreload = async (): Promise => { + if (preloadPromise) return preloadPromise; if (preloadTried) return preloaded; preloadTried = true; if (flags.noIndexCache) return undefined; - const p = preloadSession(flags.repo, scanOptions(flags, precomputedWalk), indexDir); - if (p) preloaded = { scan: p.scan, arts: p.arts }; - return preloaded; + preloadPromise = preloadSessionLazy(flags.repo, scanOptions(flags, precomputedWalk), warmPresentGrammars, indexDir).then((p) => { + if (p) preloaded = { scan: p.scan, arts: p.arts, loadArtifacts: p.loadArtifacts }; + return preloaded; + }); + return preloadPromise; + }; + let readScanPromise: Promise | undefined; + const readScan = async (): Promise => { + const preloadedScan = (await tryPreload())?.scan; + if (preloadedScan) return preloadedScan; + return (readScanPromise ??= warmPresentGrammars().then(() => + scanRepoParallel(flags.repo, { + ...scanOptions(flags, precomputedWalk), + workers: flags.workers, + }), + )); }; - const readScan = (): RepoScan => tryPreload()?.scan ?? scanRepo(flags.repo, scanOptions(flags, precomputedWalk)); - const readArtifacts = (): IndexArtifacts => { - const p = tryPreload(); + let readArtifactsPromise: Promise | undefined; + const readArtifacts = async (): Promise => { + const p = await tryPreload(); if (p?.arts) return p.arts; - if (p) return buildArtifactsFromScan(p.scan, scanOptions(flags, precomputedWalk)); - return buildIndexArtifacts(flags.repo, scanOptions(flags, precomputedWalk)); + if (p) return (p.arts ??= p.loadArtifacts?.() ?? buildArtifactsFromScan(p.scan, scanOptions(flags, precomputedWalk))); + return (readArtifactsPromise ??= readScan().then((scan) => buildArtifactsFromScan(scan, scanOptions(flags, precomputedWalk)))); }; if (cmd === "index") { @@ -589,6 +625,7 @@ export async function runCli(rawArgv: string[]): Promise { } catch { // no cache yet (or unreadable) — cold build } + await warmPresentGrammars(); const scan = await scanRepoParallel(flags.repo, { ...scanOptions(flags, precomputedWalk), cache, @@ -709,13 +746,13 @@ export async function runCli(rawArgv: string[]): Promise { }; emit(JSON.stringify(summary, null, 2) + "\n", flags.out); } else if (cmd === "graph") { - const { graph } = readArtifacts(); + const { graph } = await readArtifacts(); emit(renderGraphJson(graph), flags.out); } else if (cmd === "symbols") { - const { symbols } = readArtifacts(); + const { symbols } = await readArtifacts(); emit(renderSymbolsJson(symbols), flags.out); } else if (cmd === "scip") { - const scan = readScan(); + const scan = await readScan(); const bytes = renderScip(scan, { projectRoot: flags.projectRoot }); const out = flags.out ?? resolve("index.scip"); if (out === "-") process.stdout.write(Buffer.from(bytes)); @@ -724,13 +761,13 @@ export async function runCli(rawArgv: string[]): Promise { process.stderr.write(`codeindex: SCIP index → ${out} (${bytes.length} bytes)\n`); } } else if (cmd === "callers") { - const scan = readScan(); + const scan = await readScan(); const index = buildCallerIndex(scan, undefined, { recall: flags.recall }); const obj: Record = {}; for (const [name, entry] of index) obj[name] = entry; emit(JSON.stringify(obj, null, 2) + "\n", flags.out); } else if (cmd === "hierarchy") { - const scan = readScan(); + const scan = await readScan(); const hierarchy = buildTypeHierarchy(scan, computeImportPairs(scan)); if (flags.positional) { const entry = hierarchy.get(flags.positional); @@ -743,7 +780,7 @@ export async function runCli(rawArgv: string[]): Promise { } } else if (cmd === "implementations") { if (!flags.positional) throw new Error("implementations needs a type name: cli.mjs implementations --repo "); - const scan = readScan(); + const scan = await readScan(); const hierarchy = buildTypeHierarchy(scan, computeImportPairs(scan)); if (!hierarchy.has(flags.positional)) throw new Error(`no type named ${flags.positional}`); emit( @@ -752,7 +789,7 @@ export async function runCli(rawArgv: string[]): Promise { ); } else if (cmd === "callgraph") { if (!flags.positional) throw new Error("callgraph needs a symbol: cli.mjs callgraph --repo "); - const scan = readScan(); + const scan = await readScan(); const graph = buildSymbolGraph(scan, computeImportPairs(scan)); const result = neighborhood(graph, flags.positional, { ...(flags.depth !== undefined ? { depth: flags.depth } : {}), @@ -762,7 +799,7 @@ export async function runCli(rawArgv: string[]): Promise { emit(JSON.stringify(result, null, 2) + "\n", flags.out); } else if (cmd === "search") { if (!flags.positional) throw new Error('search needs a query: cli.mjs search "" --repo '); - const scan = readScan(); + const scan = await readScan(); const searchOpts = { limit: flags.limit, fuzzy: flags.fuzzy, @@ -887,7 +924,7 @@ export async function runCli(rawArgv: string[]): Promise { } const model = loadEmbedModel(modelDir)!; mkdirSync(flags.out, { recursive: true }); - const scan = readScan(); + const scan = await readScan(); const index = buildEmbeddingIndex(scan, model); writeFileSync(join(flags.out, "embeddings.bin"), serializeEmbeddings(index)); process.stderr.write(`codeindex: ${index.records.length} embedding records → ${flags.out}/embeddings.bin (model ${model.modelId})\n`); @@ -930,7 +967,7 @@ export async function runCli(rawArgv: string[]): Promise { // A MALFORMED config is the one case that exits 1: here the config IS the // question being asked, so swallowing the parse error would answer it // wrongly. Everywhere else an unusable tier degrades on exit 0. - emit(JSON.stringify(await lspStatus(readScan(), flags.repo, flags.probe === true), null, 2) + "\n", flags.out); + emit(JSON.stringify(await lspStatus(await readScan(), flags.repo, flags.probe === true), null, 2) + "\n", flags.out); } else if (cmd === "grammars") { const sub = flags.positional; const cacheDir = sharedGrammarsCacheDir(); @@ -980,7 +1017,7 @@ export async function runCli(rawArgv: string[]): Promise { } else if (cmd === "rules") { if (!flags.config) throw new Error("rules needs --config "); const rules = parseRules(JSON.parse(readFileSync(flags.config, "utf8"))); - const { graph } = readArtifacts(); + const { graph } = await readArtifacts(); const violations = checkRules(graph, rules); const errors = violations.filter((v) => v.severity === "error").length; emit(JSON.stringify({ errors, warnings: violations.length - errors, violations }, null, 2) + "\n", flags.out); @@ -1001,33 +1038,33 @@ export async function runCli(rawArgv: string[]): Promise { for (const k of [...churn.keys()].sort()) sorted[k] = churn.get(k)!; emit(JSON.stringify({ ok, churn: sorted }, null, 2) + "\n", flags.out); } else if (cmd === "repomap") { - const { scan, graph } = readArtifacts(); + const { scan, graph } = await readArtifacts(); emit(renderRepoMap(scan, graph, { budgetTokens: flags.budgetTokens }), flags.out); } else if (cmd === "hotspots") { - const scan = readScan(); + const scan = await readScan(); const { churn, ok } = gitChurn(flags.repo, { since: flags.since }); emit(JSON.stringify({ churnOk: ok, hotspots: rankHotspots(scan, churn) }, null, 2) + "\n", flags.out); } else if (cmd === "coupling") { const { ok, couplings } = changeCoupling(flags.repo, { since: flags.since }); emit(JSON.stringify({ ok, couplings }, null, 2) + "\n", flags.out); } else if (cmd === "deadcode") { - emit(JSON.stringify(findDeadCode(readScan()), null, 2) + "\n", flags.out); + emit(JSON.stringify(findDeadCode(await readScan()), null, 2) + "\n", flags.out); } else if (cmd === "literals") { - const report = findLiteralDuplications(readScan(), { + const report = findLiteralDuplications(await readScan(), { minFiles: flags.minFiles, minCount: flags.minCount, includeTests: flags.includeTests, }); emit(JSON.stringify(report, null, 2) + "\n", flags.out); } else if (cmd === "complexity") { - const scan = readScan(); + const scan = await readScan(); emit(JSON.stringify(symbolComplexity(scan, flags.positional), null, 2) + "\n", flags.out); } else if (cmd === "risk") { - const scan = readScan(); + const scan = await readScan(); const { churn, ok } = gitChurn(flags.repo, { since: flags.since }); emit(JSON.stringify({ churnOk: ok, risks: riskHotspots(scan, churn) }, null, 2) + "\n", flags.out); } else if (cmd === "delta") { - const { graph, symbols } = readArtifacts(); + const { graph, symbols } = await readArtifacts(); const res = deltaFor(flags.repo, graph, symbols, { base: flags.base, staged: flags.staged, @@ -1037,19 +1074,19 @@ export async function runCli(rawArgv: string[]): Promise { emit(flags.json ? JSON.stringify(res, null, 2) + "\n" : formatDeltaPanel(res), flags.out); } else if (cmd === "impact") { if (!flags.positional) throw new Error("impact needs a target: cli.mjs impact --repo "); - const { graph } = readArtifacts(); + const { graph } = await readArtifacts(); const res = impactOf(graph, flags.positional, flags.depth ?? Infinity); if (!res) throw new Error(`no such file or module in the index: ${flags.positional}`); emit(JSON.stringify(res, null, 2) + "\n", flags.out); } else if (cmd === "neighbors") { if (!flags.positional) throw new Error("neighbors needs a target: cli.mjs neighbors --repo "); - const { graph } = readArtifacts(); + const { graph } = await readArtifacts(); const kinds = flags.kind ? new Set(flags.kind.split(",").map((k) => k.trim()).filter(Boolean)) : undefined; const res = neighborsOf(graph, flags.positional, flags.depth ?? 1, kinds); if (!res) throw new Error(`no such file or module in the index: ${flags.positional}`); emit(JSON.stringify(res, null, 2) + "\n", flags.out); } else if (cmd === "mermaid") { - const { graph } = readArtifacts(); + const { graph } = await readArtifacts(); emit(renderMermaid(graph, { module: flags.positional }), flags.out); } else if (cmd === "grep") { if (!flags.positional) throw new Error("grep needs a pattern: cli.mjs grep --repo "); diff --git a/src/lsp/protocol.ts b/src/lsp/protocol.ts index 3546a01..e20803d 100644 --- a/src/lsp/protocol.ts +++ b/src/lsp/protocol.ts @@ -128,14 +128,20 @@ export function createFramer(): { push(chunk: Uint8Array | string): LspMessage[] /** `file:///abs/path` for a repo-relative path, percent-encoding each segment. */ export function fileUri(root: string, rel: string): string { - const abs = `${root.replace(/\/+$/, "")}/${rel.replace(/^\/+/, "")}`; + const rootPath = root.replace(/\\/g, "/").replace(/\/+$/, ""); + const relPath = rel.replace(/\\/g, "/").replace(/^\/+/, ""); + const abs = `${rootPath}/${relPath}`; + if (abs.startsWith("//")) { + const [host = "", ...segments] = abs.slice(2).split("/"); + return `file://${encodeURIComponent(host)}/${segments.map(encodeURIComponent).join("/")}`; + } const drive = /^([A-Za-z]):/.exec(abs); const path = drive ? `/${abs}` : abs; return ( "file://" + path .split("/") - .map((segment, i) => (i === 0 ? segment : encodeURIComponent(segment))) + .map((segment, i) => (i === 0 || (i === 1 && /^[A-Za-z]:$/.test(segment)) ? segment : encodeURIComponent(segment))) .join("/") ); } @@ -143,11 +149,22 @@ export function fileUri(root: string, rel: string): string { /** The inverse, or undefined when the URI points outside the repository. */ export function relFromUri(root: string, uri: string): string | undefined { if (!uri.startsWith("file://")) return undefined; - let path = decodeURIComponent(uri.slice("file://".length)); + let path: string; + try { + const encoded = uri.slice("file://".length); + // A non-empty URI authority is a Windows UNC host. Local paths start with + // '/', including canonical drive URIs (`file:///C:/...`). + path = decodeURIComponent(encoded.startsWith("/") ? encoded : `//${encoded}`).replace(/\\/g, "/"); + } catch { + return undefined; + } if (/^\/[A-Za-z]:/.test(path)) path = path.slice(1); - const base = root.replace(/\/+$/, ""); - if (path === base) return ""; - if (!path.startsWith(`${base}/`)) return undefined; + const base = root.replace(/\\/g, "/").replace(/\/+$/, ""); + const windows = /^[A-Za-z]:/.test(base) || base.startsWith("//"); + const comparablePath = windows ? path.toLowerCase() : path; + const comparableBase = windows ? base.toLowerCase() : base; + if (comparablePath === comparableBase) return ""; + if (!comparablePath.startsWith(`${comparableBase}/`)) return undefined; return path.slice(base.length + 1); } diff --git a/src/mcp.ts b/src/mcp.ts index 2cf51a6..90ae319 100644 --- a/src/mcp.ts +++ b/src/mcp.ts @@ -9,7 +9,7 @@ // (NOT `node scripts/engine.mjs mcp`: engine.mjs is a side-effect-free library // with no main-module guard — see src/engine.ts — so that command does nothing. // The entrypoint is the `codeindex` bin, i.e. scripts/cli.mjs.) -import { readFileSync } from "node:fs"; +import { readFileSync, statSync, watch as watchFs, type FSWatcher } from "node:fs"; import { isAbsolute, join } from "node:path"; import { createInterface } from "node:readline"; import { ENGINE_VERSION } from "./types.js"; @@ -38,7 +38,7 @@ import { EMBED_VERSION, resolveEmbedModelDir } from "./embed/model.js"; import { buildEmbeddingIndex } from "./embed/index.js"; import { searchSemantic } from "./embed/search.js"; import { resolveEmbedEndpoint, buildEndpointIndex, encodeQueryViaEndpoint, probeEndpoint } from "./embed/endpoint.js"; -import { walk, type WalkResult } from "./walk.js"; +import { IGNORE_DIRS, walk, type WalkResult } from "./walk.js"; import { toolsFor, OUTPUT_SCHEMAS } from "./mcp/tools.js"; import { DEFAULT_MAX_RESPONSE_BYTES, @@ -53,11 +53,13 @@ import { import { getArtifacts, getScan, + getScanParallel, getScanSummary, memoizedEmbeddingIndex, memoizedEmbedModel, scanFingerprint, sessionClear, + sessionInvalidate, warmGrammarsForWalk, type SessionScanOptions, } from "./mcp/session.js"; @@ -78,6 +80,7 @@ export { export { getArtifacts, getScan, + getScanParallel, getScanSummary, memoizedEmbeddingIndex, memoizedEmbedModel, @@ -95,18 +98,35 @@ interface RpcRequest { params?: Record; } +function isRpcRequest(value: unknown): value is RpcRequest { + if (!value || typeof value !== "object" || Array.isArray(value)) return false; + const req = value as Record; + if (req.jsonrpc !== "2.0" || typeof req.method !== "string") return false; + return req.id === undefined || req.id === null || typeof req.id === "number" || typeof req.id === "string"; +} + +function isRpcResponse(value: unknown): boolean { + if (!value || typeof value !== "object" || Array.isArray(value)) return false; + const response = value as Record; + return response.jsonrpc === "2.0" && typeof response.method !== "string" && ("result" in response || "error" in response); +} + function str(v: unknown): string | undefined { return typeof v === "string" && v ? v : undefined; } function strArray(v: unknown): string[] | undefined { return Array.isArray(v) && v.every((x) => typeof x === "string") && v.length ? (v as string[]) : undefined; } -// A positive numeric argument. Also accepts the numeric STRING a JSON-Schema-less +// A non-negative numeric argument. Also accepts the numeric STRING a JSON-Schema-less // client may send: `"50"` used to fall through to the default in silence, which // reads to the caller as the option being ignored. function num(v: unknown): number | undefined { const n = typeof v === "number" ? v : typeof v === "string" && v.trim() !== "" ? Number(v) : NaN; - return Number.isFinite(n) && n > 0 ? n : undefined; + return Number.isFinite(n) && n >= 0 ? n : undefined; +} +function positiveNum(v: unknown): number | undefined { + const n = num(v); + return n !== undefined && n > 0 ? n : undefined; } function errMessage(e: unknown): string { return e instanceof Error ? e.message : String(e); @@ -121,8 +141,7 @@ const SCANLESS_TOOLS = new Set([ "write_memory", "read_memory", "list_memories", "delete_memory", "embed_status", // scan_summary counts and classifies by path only — it never parses, so the - // grammar warm (a whole extra walk) would be pure overhead. When a scan is - // already cached getScanSummary reuses it, warm grammars included. + // grammar warm (a whole extra walk) would be pure overhead. "scan_summary", ]); @@ -132,6 +151,11 @@ async function callTool(name: string, args: Record, defaultRepo // to one workspace, so agents need not know — or restate — the absolute path. const repo = str(args.repo) ?? defaultRepo; if (!repo) throw new Error("`repo` is required (absolute path to the repository root)"); + try { + if (!statSync(repo).isDirectory()) throw new Error("not a directory"); + } catch { + throw new Error(`repository root is not a readable directory: ${repo}`); + } const scanOpts = { scope: str(args.scope), include: strArray(args.include), exclude: strArray(args.exclude) }; // `search`'s optional structural prior; anything else falls back to the default. const rankArg = str(args.rank); @@ -140,10 +164,21 @@ async function callTool(name: string, args: Record, defaultRepo // before any scan so extraction takes the AST tier; scan-less tools skip it. // ONE walk feeds both the warm and the scan below — see warmGrammarsForWalk. let walked: WalkResult | undefined; + let preparedScan: ReturnType | undefined; if (!SCANLESS_TOOLS.has(name)) { + // fs.watch is an eager invalidation hint, never a freshness oracle: an + // immediate request can beat event delivery. Always perform the normal + // walk/stat proof before trusting a warm scan. walked = walk(repo, {}); - await warmGrammarsForWalk(walked); + preparedScan = await getScanParallel( + repo, + scanOpts, + walked, + () => (walked ? warmGrammarsForWalk(walked) : Promise.resolve()), + ); } + const readScan = (): ReturnType => preparedScan ?? getScan(repo, scanOpts, walked); + const readArtifacts = () => getArtifacts(repo, scanOpts, walked, preparedScan); if (name === "scan_summary") { const s = getScanSummary(repo, scanOpts, walked); @@ -154,10 +189,10 @@ async function callTool(name: string, args: Record, defaultRepo ); } if (name === "graph") { - return renderGraphJson(getArtifacts(repo, scanOpts, walked).graph); + return renderGraphJson(readArtifacts().graph); } if (name === "symbols") { - const { symbols } = getArtifacts(repo, scanOpts, walked); + const { symbols } = readArtifacts(); const lookup = str(args.name); if (lookup) { return JSON.stringify({ name: lookup, defs: symbols.defs[lookup] ?? [], refs: symbols.refs[lookup] ?? [] }, null, 2); @@ -170,7 +205,7 @@ async function callTool(name: string, args: Record, defaultRepo // repo in the project's own benchmark). The memoized one is keyed on scan // object identity, which the session cache preserves across calls. // Recall mode is option-dependent, so it cannot use the memoized index. - const scan = getScan(repo, scanOpts, walked); + const scan = readScan(); const index = args.recall === true ? buildCallerIndex(scan, undefined, { recall: true }) : callerIndexFor(scan); const lookup = str(args.name); if (lookup) { @@ -194,23 +229,23 @@ async function callTool(name: string, args: Record, defaultRepo if (name === "symbols_overview") { const file = str(args.file); if (!file) throw new Error("`file` is required"); - return JSON.stringify(symbolsOverview(getScan(repo, scanOpts, walked), file), null, 2); + return JSON.stringify(symbolsOverview(readScan(), file), null, 2); } if (name === "find_symbol") { const namePath = str(args.namePath); if (!namePath) throw new Error("`namePath` is required"); - const matches = findSymbol(getScan(repo, scanOpts, walked), namePath, { + const matches = findSymbol(readScan(), namePath, { substring: args.substring === true, includeBody: args.includeBody === true, concise: args.concise === true, - maxResults: num(args.maxResults), + maxResults: positiveNum(args.maxResults), }); return JSON.stringify(matches, null, 2); } if (name === "find_references") { const symName = str(args.name); if (!symName) throw new Error("`name` is required"); - const scan = getScan(repo, scanOpts, walked); + const scan = readScan(); const statik = findReferences(scan, symName); // The static answer is computed FIRST and passed in, so the LSP tier is // structurally incapable of removing anything from it — it can only append @@ -219,13 +254,13 @@ async function callTool(name: string, args: Record, defaultRepo return JSON.stringify(statik, null, 2); } if (name === "lsp_status") { - return JSON.stringify(await lspStatus(getScan(repo, scanOpts, walked), repo, args.probe === true), null, 2); + return JSON.stringify(await lspStatus(readScan(), repo, args.probe === true), null, 2); } if (name === "replace_symbol_body" || name === "insert_after_symbol" || name === "insert_before_symbol") { const namePath = str(args.namePath); const body = typeof args.body === "string" ? args.body : undefined; if (!namePath || body === undefined) throw new Error("`namePath` and `body` are required"); - const scan = getScan(repo, scanOpts, walked); + const scan = readScan(); const fn = name === "replace_symbol_body" ? replaceSymbolBody : name === "insert_after_symbol" ? insertAfterSymbol : insertBeforeSymbol; const result = fn(scan, namePath, body, str(args.file)); // A write WE just performed must not be trusted to the stat oracle: an @@ -259,16 +294,16 @@ async function callTool(name: string, args: Record, defaultRepo return JSON.stringify({ deleted: deleteMemory(repo, memName) }, null, 2); } if (name === "dead_code") { - const all = findDeadCode(getScan(repo, scanOpts, walked)); + const all = findDeadCode(readScan()); const limit = num(args.limit); // Additive: without `limit` the payload is exactly what it always was. if (limit === undefined || all.length <= limit) return JSON.stringify(all, null, 2); return JSON.stringify({ total: all.length, shown: limit, truncated: true, candidates: all.slice(0, limit) }, null, 2); } if (name === "duplicated_literals") { - const report = findLiteralDuplications(getScan(repo, scanOpts, walked), { - minFiles: num(args.minFiles), - minCount: num(args.minCount), + const report = findLiteralDuplications(readScan(), { + minFiles: positiveNum(args.minFiles), + minCount: positiveNum(args.minCount), includeTests: args.includeTests === true, }); const limit = num(args.limit); @@ -288,27 +323,27 @@ async function callTool(name: string, args: Record, defaultRepo ); } if (name === "complexity") { - const scan = getScan(repo, scanOpts, walked); + const scan = readScan(); if (args.risk === true) { // `since` was accepted by the CLI's `risk` but silently dropped here. const { churn, ok } = gitChurn(repo, { since: str(args.since) }); - return JSON.stringify({ churnOk: ok, risks: riskHotspots(scan, churn, num(args.top)) }, null, 2); + return JSON.stringify({ churnOk: ok, risks: riskHotspots(scan, churn, positiveNum(args.top)) }, null, 2); } - return JSON.stringify(symbolComplexity(scan, str(args.file), num(args.top)), null, 2); + return JSON.stringify(symbolComplexity(scan, str(args.file), positiveNum(args.top)), null, 2); } if (name === "mermaid") { - const { graph } = getArtifacts(repo, scanOpts, walked); - return renderMermaid(graph, { module: str(args.module), maxEdges: num(args.maxEdges) }); + const { graph } = readArtifacts(); + return renderMermaid(graph, { module: str(args.module), maxEdges: positiveNum(args.maxEdges) }); } if (name === "onboard") { // getArtifacts, not a fresh build: the session cache already holds the // graph, and onboarding is precisely the first call of a session — paying // for a second pass here is paying at the worst possible moment. - const scan = getScan(repo, scanOpts, walked); - const { graph } = getArtifacts(repo, scanOpts, walked); + const scan = readScan(); + const { graph } = readArtifacts(); return JSON.stringify( onboardBrief(scan, graph, { - ...(typeof args.budgetTokens === "number" ? { budgetTokens: args.budgetTokens } : {}), + ...(positiveNum(args.budgetTokens) !== undefined ? { budgetTokens: positiveNum(args.budgetTokens)! } : {}), ...(args.remember === false ? { remember: false } : {}), }), null, @@ -316,11 +351,11 @@ async function callTool(name: string, args: Record, defaultRepo ); } if (name === "repo_map") { - const { scan, graph } = getArtifacts(repo, scanOpts, walked); - return renderRepoMap(scan, graph, { budgetTokens: typeof args.budgetTokens === "number" ? args.budgetTokens : undefined }); + const { scan, graph } = readArtifacts(); + return renderRepoMap(scan, graph, { budgetTokens: positiveNum(args.budgetTokens) }); } if (name === "hotspots") { - const scan = getScan(repo, scanOpts, walked); + const scan = readScan(); const { churn, ok } = gitChurn(repo, { since: str(args.since) }); return JSON.stringify({ churnOk: ok, hotspots: rankHotspots(scan, churn) }, null, 2); } @@ -338,15 +373,15 @@ async function callTool(name: string, args: Record, defaultRepo const hits = grepRepo(repo, pattern, { globs: scope ? [...(globs ?? []), `${scope.replace(/\/+$/, "")}/**`] : globs, ignoreCase: args.ignoreCase === true, - maxHits: typeof args.maxHits === "number" ? args.maxHits : undefined, + maxHits: positiveNum(args.maxHits), }); return JSON.stringify(hits, null, 2); } if (name === "search") { const query = str(args.query); if (!query) throw new Error("`query` is required"); - const scan = getScan(repo, scanOpts, walked); - const limit = typeof args.limit === "number" ? args.limit : undefined; + const scan = readScan(); + const limit = num(args.limit); const fuzzy = typeof args.fuzzy === "boolean" ? args.fuzzy : undefined; const exactOpt = args.exact === true ? { exact: true as const } : {}; if (args.semantic === true) { @@ -405,8 +440,8 @@ async function callTool(name: string, args: Record, defaultRepo if (name === "explain_search") { const query = str(args.query); if (!query) throw new Error("`query` is required"); - const scan = getScan(repo, scanOpts, walked); - const limit = typeof args.limit === "number" ? args.limit : undefined; + const scan = readScan(); + const limit = num(args.limit); const fuzzy = typeof args.fuzzy === "boolean" ? args.fuzzy : undefined; // Always an object, which is exactly why this is a tool of its own rather // than another shape `search` can return: a stable shape is what lets it @@ -436,7 +471,7 @@ async function callTool(name: string, args: Record, defaultRepo return JSON.stringify(status, null, 2); } if (name === "type_hierarchy") { - const hierarchy = hierarchyFor(getScan(repo, scanOpts, walked)); + const hierarchy = hierarchyFor(readScan()); const wanted = str(args.name); if (!wanted) { const obj: Record = {}; @@ -450,7 +485,7 @@ async function callTool(name: string, args: Record, defaultRepo if (name === "implementations") { const wanted = str(args.name); if (!wanted) throw new Error("`name` is required"); - const hierarchy = hierarchyFor(getScan(repo, scanOpts, walked)); + const hierarchy = hierarchyFor(readScan()); if (!hierarchy.has(wanted)) return JSON.stringify({ error: `no type named ${wanted}` }, null, 2); return JSON.stringify({ name: wanted, implementations: implementationsOf(hierarchy, wanted) }, null, 2); } @@ -459,8 +494,8 @@ async function callTool(name: string, args: Record, defaultRepo if (!symbol) throw new Error("`symbol` is required"); const direction = str(args.direction); const dir: Direction = direction === "out" || direction === "in" ? direction : "both"; - const result = neighborhood(symbolGraphFor(getScan(repo, scanOpts, walked)), symbol, { - ...(typeof args.depth === "number" ? { depth: args.depth } : {}), + const result = neighborhood(symbolGraphFor(readScan()), symbol, { + ...(positiveNum(args.depth) !== undefined ? { depth: positiveNum(args.depth)! } : {}), direction: dir, }); if (!result.root.length) return JSON.stringify({ error: `no symbol named ${symbol}` }, null, 2); @@ -482,7 +517,7 @@ async function callTool(name: string, args: Record, defaultRepo } if (payload === undefined) throw new Error("`rules` (or `configPath`) is required"); const rules = parseRules(payload); // throws a descriptive error on a malformed payload - const { graph } = getArtifacts(repo, scanOpts, walked); + const { graph } = readArtifacts(); return JSON.stringify(checkRules(graph, rules), null, 2); } throw new Error(`unknown tool: ${name}`); @@ -507,6 +542,11 @@ export interface McpServerOptions { // what is ADVERTISED, not what is answerable: a tool left out of the profile // still works when called. Undefined = all tools, so no existing setup moves. profile?: string; + // Opt into proactive event-driven invalidation for a pinned repository. + // Every request still performs the normal freshness proof because event + // delivery can lag behind a request. Unsupported platforms warn and retain + // the same per-call freshness scan. + watch?: boolean; } export async function runMcpServer(opts: McpServerOptions = {}): Promise { @@ -521,41 +561,96 @@ export async function runMcpServer(opts: McpServerOptions = {}): Promise { // Rebuilt when negotiation lands: the pin cannot change mid-session, but the // fields we are allowed to advertise depend on the version. let tools = toolsFor(opts.defaultRepo, protocolVersion, opts.profile); + let watcher: FSWatcher | undefined; + if (opts.watch && opts.defaultRepo) { + try { + watcher = watchFs(opts.defaultRepo, { recursive: true }, (_event, filename) => { + const rel = filename?.toString().replaceAll("\\", "/") ?? ""; + const ignored = rel.split("/").some((segment) => + IGNORE_DIRS.has(segment) || segment.startsWith(".codeindex-edit-"), + ); + if (ignored) return; + sessionInvalidate(opts.defaultRepo!, rel || undefined); + }); + watcher.on("error", (error) => { + process.stderr.write(`codeindex: MCP watcher disabled (${error.message}); using freshness scans\n`); + watcher?.close(); + watcher = undefined; + sessionInvalidate(opts.defaultRepo!); + }); + } catch (error) { + process.stderr.write( + `codeindex: MCP watcher unavailable (${error instanceof Error ? error.message : String(error)}); using freshness scans\n`, + ); + } + } // No startup warm: each scan-needing tool warms the present-language grammars // for its repo before it runs (warmGrammarsForRepo re-derives them per call), // so a session that never scans — or only touches one language — loads no // unused wasm, and a language first seen mid-session still gets warmed. - const send = (msg: Record): void => { - process.stdout.write(JSON.stringify({ jsonrpc: "2.0", ...msg }) + "\n"); + const send = (msg: Record | Record[]): void => { + const wire = Array.isArray(msg) + ? msg.map((entry) => ({ jsonrpc: "2.0", ...entry })) + : { jsonrpc: "2.0", ...msg }; + process.stdout.write(JSON.stringify(wire) + "\n"); }; const rl = createInterface({ input: process.stdin, terminal: false }); - for await (const line of rl) { - const trimmed = line.trim(); - if (!trimmed) continue; - let parsed: unknown; - try { - parsed = JSON.parse(trimmed); - } catch { - send({ id: null, error: { code: -32700, message: "parse error" } }); - continue; + try { + for await (const line of rl) { + const trimmed = line.trim(); + if (!trimmed) continue; + let parsed: unknown; + try { + parsed = JSON.parse(trimmed); + } catch { + send({ id: null, error: { code: -32700, message: "parse error" } }); + continue; + } + if (Array.isArray(parsed) && parsed.length === 0) { + send({ id: null, error: { code: -32600, message: "invalid request" } }); + continue; + } + const dispatch = async (req: unknown): Promise | undefined> => { + // The server currently initiates no requests, but a peer response is + // still a response — JSON-RPC forbids replying to it with -32600. + if (isRpcResponse(req)) return undefined; + if (!isRpcRequest(req)) { + return { id: null, error: { code: -32600, message: "invalid request" } }; + } + return handle(req); + }; + if (Array.isArray(parsed)) { + const replies: Record[] = []; + for (const req of parsed) { + const reply = await dispatch(req); + if (reply) replies.push(reply); + } + // A notification-only batch has no response. Any actual responses must + // share one JSON array, as required by JSON-RPC 2.0. + if (replies.length > 0) send(replies); + } else { + const reply = await dispatch(parsed); + if (reply) send(reply); + } } - // JSON-RPC 2.0 batch: answer each member (a batching client would - // otherwise hang forever on a silently dropped array). - const requests = Array.isArray(parsed) ? (parsed as RpcRequest[]) : [parsed as RpcRequest]; - for (const req of requests) await handle(req); + } finally { + watcher?.close(); } - async function handle(req: RpcRequest): Promise { - if (req.id === undefined || req.id === null) return; // notification — no response + async function handle(req: RpcRequest): Promise | undefined> { + // Only an ABSENT id denotes a notification. Explicit null is discouraged + // by JSON-RPC but remains a request and must receive an id:null response. + const notification = !("id" in req); + const respond = (body: Record): Record | undefined => + notification ? undefined : { id: req.id ?? null, ...body }; try { if (req.method === "initialize") { protocolVersion = negotiateProtocol(req.params?.protocolVersion); tools = toolsFor(opts.defaultRepo, protocolVersion, opts.profile); - send({ - id: req.id, + return respond({ result: { protocolVersion, capabilities: { tools: {} }, @@ -563,9 +658,9 @@ export async function runMcpServer(opts: McpServerOptions = {}): Promise { }, }); } else if (req.method === "ping") { - send({ id: req.id, result: {} }); + return respond({ result: {} }); } else if (req.method === "tools/list") { - send({ id: req.id, result: { tools } }); + return respond({ result: { tools } }); } else if (req.method === "tools/call") { const params = req.params ?? {}; const name = str(params.name) ?? ""; @@ -595,24 +690,22 @@ export async function runMcpServer(opts: McpServerOptions = {}): Promise { protocolVersion >= RICH_TOOLS_SINCE ? structuredContentFor(text, capped, OUTPUT_SCHEMAS[name] !== undefined) : undefined; - send({ - id: req.id, + return respond({ result: { content: link ? [{ type: "text", text }, link] : [{ type: "text", text }], ...(structured ? { structuredContent: structured } : {}), }, }); } catch (e) { - send({ - id: req.id, + return respond({ result: { content: [{ type: "text", text: e instanceof Error ? e.message : String(e) }], isError: true }, }); } } else { - send({ id: req.id, error: { code: -32601, message: `method not found: ${req.method}` } }); + return respond({ error: { code: -32601, message: `method not found: ${req.method}` } }); } } catch (e) { - send({ id: req.id, error: { code: -32603, message: e instanceof Error ? e.message : String(e) } }); + return respond({ error: { code: -32603, message: e instanceof Error ? e.message : String(e) } }); } } } diff --git a/src/mcp/protocol.ts b/src/mcp/protocol.ts index e031050..e190943 100644 --- a/src/mcp/protocol.ts +++ b/src/mcp/protocol.ts @@ -44,7 +44,12 @@ export function validateArgs( schema: { properties?: Record }, args: Record, ): string | undefined { - const props = (schema.properties ?? {}) as Record; + const props = (schema.properties ?? {}) as Record; for (const [key, value] of Object.entries(args)) { if (value === undefined || value === null) continue; const spec = props[key]; @@ -52,9 +57,17 @@ export function validateArgs( const actual = Array.isArray(value) ? "array" : typeof value; if (spec.type === "number") { // A numeric string is accepted (num() coerces it); anything else is not. - if (actual === "number") continue; - if (actual === "string" && Number.isFinite(Number(value as string)) && (value as string).trim() !== "") continue; - return `\`${key}\` must be a number, got ${actual === "string" ? JSON.stringify(value) : actual}`; + const numeric = actual === "number" + ? value as number + : actual === "string" && (value as string).trim() !== "" + ? Number(value as string) + : NaN; + if (!Number.isFinite(numeric)) { + return `\`${key}\` must be a number, got ${actual === "string" ? JSON.stringify(value) : actual}`; + } + if (spec.minimum !== undefined && numeric < spec.minimum) return `\`${key}\` must be at least ${spec.minimum}`; + if (spec.maximum !== undefined && numeric > spec.maximum) return `\`${key}\` must be at most ${spec.maximum}`; + continue; } if (spec.type === "array") { if (actual !== "array") return `\`${key}\` must be an array of strings, got ${actual}`; diff --git a/src/mcp/session.ts b/src/mcp/session.ts index b7327d8..1fcb0b6 100644 --- a/src/mcp/session.ts +++ b/src/mcp/session.ts @@ -9,7 +9,8 @@ import { statSync } from "node:fs"; import { join } from "node:path"; import { buildArtifactsFromScan, type IndexArtifacts } from "../pipeline.js"; import { scanRepo, scanSummary, type RepoScan, type ScanOptions, type ScanSummary } from "../scan.js"; -import { preloadSession, toCacheMap, type PersistedCacheEntry, type PersistedCacheMap } from "../preload.js"; +import { scanRepoParallel } from "../pool.js"; +import { needsGrammarWarm, preloadSession, preloadSessionLazy, toCacheMap, type PersistedCacheEntry, type PersistedCacheMap } from "../preload.js"; import { walk, type WalkResult } from "../walk.js"; import { ensureGrammars, grammarKeysForExts } from "../ast/loader.js"; import { resolveEmbedModelDir, loadEmbedModel, type StaticEmbedModel } from "../embed/model.js"; @@ -115,6 +116,7 @@ interface SessionEntry { scan: RepoScan; cacheMap: SessionCacheMap; arts?: IndexArtifacts; + loadArtifacts?: () => IndexArtifacts | undefined; } // A SMALL bounded LRU — never an unbounded map. @@ -150,6 +152,20 @@ export function sessionClear(): void { sessionCaches.length = 0; } +// Invalidate only the watched repository while retaining its incremental +// records and every other repo in the LRU. Removing one known path defeats the +// same-size/same-mtime fastpath for that file; an unknown filename keeps the +// entry but drops all record fastpaths. The next request still walks/stats and +// proves the complete repository state before returning anything. +export function sessionInvalidate(repo: string, rel?: string): void { + const prefix = repo + "\0"; + for (const entry of sessionCaches) { + if (!entry.key.startsWith(prefix)) continue; + if (rel) entry.cacheMap.delete(rel); + else entry.cacheMap.clear(); + } +} + // Fixed property order (and JSON.stringify dropping undefined) keeps the key // deterministic regardless of how the caller assembled the options object. export function sessionKey(repo: string, opts: SessionScanOptions): string { @@ -193,13 +209,14 @@ export function getScan(repo: string, opts: SessionScanOptions = {}, walked?: Wa // changes headCommit without altering any file's size or mtime, so // contentUnchanged stays true while the cached scan's commit went stale. // `fresh` recomputed it just now (exactly what a cold process reports), so - // sync it onto the returned object; otherwise scan_summary would emit the - // OLD commit a from-scratch scanRepo never would. Mutate the SAME object - // rather than clone — cloning would forfeit the identity the artifacts and - // derived.ts WeakMap key on. Safe: no artifact carries commit (graph / - // symbols render byte-identically regardless), so nothing memoized here - // depends on this field. - if (hit.scan.commit !== fresh.commit) hit.scan.commit = fresh.commit; + // sync it onto the returned object; otherwise graph/scan metadata would + // expose the old HEAD. Mutate the SAME scan object to preserve derived + // indexes, but rebuild artifacts because Graph itself carries `commit`. + if (hit.scan.commit !== fresh.commit) { + hit.scan.commit = fresh.commit; + hit.arts = undefined; + hit.loadArtifacts = undefined; + } return hit.scan; } sessionPut({ key, scan: fresh, cacheMap: toCacheMap(fresh) }); @@ -211,7 +228,12 @@ export function getScan(repo: string, opts: SessionScanOptions = {}, walked?: Wa // the cold path EXACTLY as before. const preloaded = preloadSession(repo, { ...opts, precomputedWalk: walked }); if (preloaded) { - sessionPut({ key, scan: preloaded.scan, cacheMap: preloaded.cacheMap, arts: preloaded.arts }); + sessionPut({ + key, + scan: preloaded.scan, + cacheMap: preloaded.cacheMap, + arts: preloaded.arts, + }); return preloaded.scan; } const scan = scanRepo(repo, { ...opts, precomputedWalk: walked }); @@ -219,36 +241,100 @@ export function getScan(repo: string, opts: SessionScanOptions = {}, walked?: Wa return scan; } +// Async cold-start companion used by the MCP request boundary. Existing warm +// entries and persisted indexes keep their proven cache paths; only a genuinely +// cold repo is extracted across workers. The resulting scan is inserted into +// the same LRU, so every synchronous query helper below observes one object and +// all derived WeakMap caches retain their identity semantics. +export async function getScanParallel( + repo: string, + opts: SessionScanOptions = {}, + walked?: WalkResult, + warm: () => Promise = async () => {}, +): Promise { + const key = sessionKey(repo, opts); + const existing = sessionCaches.find((entry) => entry.key === key); + if (existing) { + const originalCache = existing.cacheMap; + const reuseUnchanged = (fresh: RepoScan): RepoScan => { + if (fresh.cacheDirty) existing.cacheMap = toCacheMap(fresh); + if (existing.scan.commit !== fresh.commit) { + existing.scan.commit = fresh.commit; + existing.arts = undefined; + existing.loadArtifacts = undefined; + } + sessionGet(key); + return existing.scan; + }; + + // A metadata change in a code file requires grammars, but not a throwaway + // provisional extraction. Warm first and perform exactly one parallel scan. + if (walked && needsGrammarWarm(walked, originalCache, opts.fullHash)) { + await warm(); + const fresh = await scanRepoParallel(repo, { ...opts, cache: originalCache, precomputedWalk: walked }); + if (fresh.contentUnchanged) return reuseUnchanged(fresh); + sessionPut({ key, scan: fresh, cacheMap: toCacheMap(fresh) }); + return fresh; + } + + const provisional = scanRepo(repo, { ...opts, cache: originalCache, precomputedWalk: walked }); + if (provisional.contentUnchanged) { + return reuseUnchanged(provisional); + } + // With a walk, the metadata proof above established that only docs/config, + // deletions or scope changed; the provisional scan is already final. The + // no-walk fallback retains the conservative warm + rescan contract. + if (walked) { + sessionPut({ key, scan: provisional, cacheMap: toCacheMap(provisional) }); + return provisional; + } + await warm(); + const scan = await scanRepoParallel(repo, { ...opts, cache: originalCache, precomputedWalk: walked }); + sessionPut({ key, scan, cacheMap: toCacheMap(scan) }); + return scan; + } + + const preloaded = await preloadSessionLazy(repo, { ...opts, precomputedWalk: walked }, warm); + if (preloaded) { + sessionPut({ + key, + scan: preloaded.scan, + cacheMap: preloaded.cacheMap, + arts: preloaded.arts, + loadArtifacts: preloaded.loadArtifacts, + }); + return preloaded.scan; + } + + await warm(); + const scan = await scanRepoParallel(repo, { ...opts, precomputedWalk: walked }); + sessionPut({ key, scan, cacheMap: toCacheMap(scan) }); + return scan; +} + // The scan_summary numbers, without paying for a scan. // // A file count and a language histogram come from the walk plus the path-based -// classifiers — no read, no hash, no tree-sitter. When this session already -// holds a scan for the same (repo, opts) we derive from it instead (identical -// numbers, and it keeps a warm session warm); otherwise scanSummary walks once. +// classifiers — no read, no hash, no tree-sitter. Always use that path-only +// operation, even when the session holds a scan: refreshing a changed file from +// this grammar-free path would replace an AST record with a regex-tier record. // The summary is NEVER written into the session cache: it carries no // FileRecords, so caching it would starve every record-shaped tool that ran next. export function getScanSummary(repo: string, opts: SessionScanOptions = {}, walked?: WalkResult): ScanSummary { - if (sessionCaches.some((e) => e.key === sessionKey(repo, opts))) { - const scan = getScan(repo, opts, walked); - return { - root: scan.root, - commit: scan.commit, - fileCount: scan.files.length, - languages: scan.languages, - capped: scan.capped, - excluded: scan.excluded, - }; - } + // Never refresh a record-shaped session here: this path intentionally loads + // no grammar, so extracting a changed file would poison later AST queries + // with a regex-tier record. The path-only summary is already the cheap and + // exact operation this tool needs. return scanSummary(repo, { ...opts, precomputedWalk: walked }); } // Lazy pipeline memoized on scan OBJECT IDENTITY: graph-shaped tools reuse the // artifacts exactly as long as getScan keeps returning the same scan object. // Exported for tests. -export function getArtifacts(repo: string, opts: SessionScanOptions = {}, walked?: WalkResult): IndexArtifacts { - const scan = getScan(repo, opts, walked); +export function getArtifacts(repo: string, opts: SessionScanOptions = {}, walked?: WalkResult, prepared?: RepoScan): IndexArtifacts { + const scan = prepared ?? getScan(repo, opts, walked); const entry = sessionCaches.find((e) => e.scan === scan); - if (entry) return (entry.arts ??= buildArtifactsFromScan(scan, opts)); + if (entry) return (entry.arts ??= entry.loadArtifacts?.() ?? buildArtifactsFromScan(scan, opts)); // Defensive fallback (getScan always leaves an entry holding `scan`). return buildArtifactsFromScan(scan, opts); } diff --git a/src/mcp/tools.ts b/src/mcp/tools.ts index 7e5f08d..fb0e907 100644 --- a/src/mcp/tools.ts +++ b/src/mcp/tools.ts @@ -95,7 +95,7 @@ export const TOOLS = [ description: "Return only name/kind/file/line — drop the signature, line span, visibility and language. Roughly 2.5x smaller; use it when you are resolving a path and nothing more (default false).", }, - maxResults: { type: "number", description: "Cap matches (default 50)" }, + maxResults: { type: "number", minimum: 1, description: "Cap matches (default 50)" }, }, required: ["repo", "namePath"], }, @@ -139,7 +139,7 @@ export const TOOLS = [ type: "object", properties: { ...repoProp, - budgetTokens: { type: "number", description: "Token budget for the key-files section (default 900)" }, + budgetTokens: { type: "number", minimum: 1, description: "Token budget for the key-files section (default 900)" }, remember: { type: "boolean", description: "Persist the brief as the `onboarding` memory (default true)" }, }, required: ["repo"], @@ -151,7 +151,7 @@ export const TOOLS = [ "Token-budgeted map of the repository: the highest-PageRank files with their key exported signatures, deterministically rendered to fit `budgetTokens` (default 1024). The densest single read to understand an unfamiliar codebase.", inputSchema: { type: "object", - properties: { ...repoProp, budgetTokens: { type: "number", description: "Approximate token budget (default 1024)" } }, + properties: { ...repoProp, budgetTokens: { type: "number", minimum: 1, description: "Approximate token budget (default 1024)" } }, required: ["repo"], }, }, @@ -252,7 +252,7 @@ export const TOOLS = [ properties: { ...repoProp, ...scopeProps, - limit: { type: "number", description: "Cap entries (default: all)" }, + limit: { type: "number", minimum: 0, description: "Cap entries (default: all)" }, }, required: ["repo"], }, @@ -266,10 +266,10 @@ export const TOOLS = [ properties: { ...repoProp, ...scopeProps, - minFiles: { type: "number", description: "Distinct files a value must span (default 2)" }, - minCount: { type: "number", description: "Total occurrences required (default 3)" }, + minFiles: { type: "number", minimum: 1, description: "Distinct files a value must span (default 2)" }, + minCount: { type: "number", minimum: 1, description: "Total occurrences required (default 3)" }, includeTests: { type: "boolean", description: "Count test files too (default false)" }, - limit: { type: "number", description: "Cap duplications (default: all)" }, + limit: { type: "number", minimum: 0, description: "Cap duplications (default: all)" }, }, required: ["repo"], }, @@ -280,7 +280,13 @@ export const TOOLS = [ "Cyclomatic-complexity estimates (branch-token counting over AST line spans), most-complex first. Pass `file` for one file's symbols, omit for the repo-wide top. Combine with hotspots: the `risk` field of this tool's sibling ranks complexity × churn.", inputSchema: { type: "object", - properties: { ...repoProp, file: { type: "string" }, risk: { type: "boolean", description: "Return complexity × git-churn risk ranking instead" } }, + properties: { + ...repoProp, + file: { type: "string" }, + risk: { type: "boolean", description: "Return complexity × git-churn risk ranking instead" }, + since: { type: "string", description: "Only count risk churn after this ref" }, + top: { type: "number", minimum: 1, description: "Cap ranked symbols" }, + }, required: ["repo"], }, }, @@ -290,7 +296,11 @@ export const TOOLS = [ "Mermaid diagram of the module graph (renders inline in Claude/GitHub — no graph database). Optionally scoped to one module's neighborhood.", inputSchema: { type: "object", - properties: { ...repoProp, module: { type: "string", description: "Module slug to focus on" } }, + properties: { + ...repoProp, + module: { type: "string", description: "Module slug to focus on" }, + maxEdges: { type: "number", minimum: 1, description: "Cap rendered edges" }, + }, required: ["repo"], }, }, @@ -306,7 +316,7 @@ export const TOOLS = [ scope: { type: "string", description: "Restrict to one directory (repo-relative)" }, globs: { type: "array", items: { type: "string" }, description: "Restrict to matching paths" }, ignoreCase: { type: "boolean" }, - maxHits: { type: "number" }, + maxHits: { type: "number", minimum: 1 }, }, required: ["repo", "pattern"], }, @@ -321,7 +331,7 @@ export const TOOLS = [ ...repoProp, ...scopeProps, query: { type: "string", description: "Natural-language or identifier query" }, - limit: { type: "number", description: "Max results (default 20)" }, + limit: { type: "number", minimum: 0, description: "Max results (default 20)" }, fuzzy: { type: "boolean", description: @@ -361,7 +371,7 @@ export const TOOLS = [ ...repoProp, ...scopeProps, query: { type: "string", description: "Natural-language or identifier query" }, - limit: { type: "number", description: "Max results (default 20)" }, + limit: { type: "number", minimum: 0, description: "Max results (default 20)" }, fuzzy: { type: "boolean", description: "Stem/trigram fallback for zero-document-frequency terms (default true)" }, exact: { type: "boolean", description: "Drop results carrying no verbatim term match (default false)" }, }, @@ -403,7 +413,7 @@ export const TOOLS = [ properties: { ...repoProp, symbol: { type: "string", description: "Symbol name to centre on" }, - depth: { type: "number", description: "Hops to follow (default 2, max 5)" }, + depth: { type: "number", minimum: 1, maximum: 5, description: "Hops to follow (default 2, max 5)" }, direction: { type: "string", description: "out | in | both (default both)" }, }, required: ["repo", "symbol"], diff --git a/src/pool.ts b/src/pool.ts index 16b0775..81d26f5 100644 --- a/src/pool.ts +++ b/src/pool.ts @@ -17,7 +17,7 @@ // Sequential fallback is always available and always correct: any failure to // resolve, spawn, or agree returns undefined and the caller scans as before. import { existsSync, statSync } from "node:fs"; -import { availableParallelism } from "node:os"; +import * as os from "node:os"; import { dirname, join } from "node:path"; import { fileURLToPath, pathToFileURL } from "node:url"; import { Worker } from "node:worker_threads"; @@ -74,6 +74,7 @@ function resolveEngineUrl(): string | undefined { // of a very large repo can legitimately take minutes, and tripping this only // costs a fallback to the sequential scan. const WORKER_TIMEOUT_MS = 10 * 60 * 1000; +const DEFAULT_MIN_PARALLEL_JOBS = 200; // How many workers to run. `CODEINDEX_WORKERS` wins when set; 0 or 1 means // sequential. Default leaves a core for the main thread and caps at 8 — past @@ -84,7 +85,7 @@ export function workerCount(requested?: number): number { if (raw !== undefined) return Number.isFinite(raw) && raw > 0 ? Math.floor(raw) : 0; let cores = 1; try { - cores = availableParallelism(); + cores = typeof os.availableParallelism === "function" ? os.availableParallelism() : os.cpus().length; } catch { cores = 1; } @@ -264,6 +265,8 @@ export async function scanRepoParallel( jobs.push({ abs: f.abs, rel: f.rel, ext: f.ext }); } if (jobs.length === 0) return scanRepo(root, scanOpts); + const workersForced = opts.workers !== undefined || (process.env["CODEINDEX_WORKERS"] ?? "") !== ""; + if (!workersForced && jobs.length < DEFAULT_MIN_PARALLEL_JOBS) return scanRepo(root, scanOpts); const grammarKeys = grammarKeysForExts(walked.files.map((f) => f.ext)); const extracted = await extractInParallel(jobs, grammarKeys, count, { maxCallsPerFile: opts.maxCallsPerFile }); diff --git a/src/preload.ts b/src/preload.ts index e2257cb..d42b3cf 100644 --- a/src/preload.ts +++ b/src/preload.ts @@ -26,6 +26,8 @@ import type { FileRecord, Graph, SymbolIndex } from "./types.js"; import { scanRepo, type RepoScan, type ScanOptions } from "./scan.js"; import type { IndexArtifacts } from "./pipeline.js"; import { sha1 } from "./hash.js"; +import { walk, type WalkResult } from "./walk.js"; +import { classify } from "./classify.js"; // The default index location, relative to the repo root. export const INDEX_DIR = ".codeindex"; @@ -45,6 +47,14 @@ export interface PersistedMeta { symbolsSha1?: string; } +export interface PreloadedSession { + scan: RepoScan; + cacheMap: PersistedCacheMap; + arts?: IndexArtifacts; + /** Async preload callers defer the large graph/symbol JSON read until needed. */ + loadArtifacts?: () => IndexArtifacts | undefined; +} + // A scan re-expressed as the `ScanOptions.cache` shape (the exact map the CLI // persists as cache.json): rel → (hash, record, size, mtimeMs), so the next // scanRepo can take the stat fastpath / hash-match reuse paths against it. @@ -54,6 +64,22 @@ export function toCacheMap(scan: RepoScan): PersistedCacheMap { return m; } +// Whether a persisted scan needs grammars BEFORE its next extraction pass. +// Only code files reach tree-sitter. New/stat-changed code may need parsing; +// docs/config changes and deletions do not. fullHash removes the stat proof, so +// any present code file conservatively warms. +export function needsGrammarWarm( + walked: WalkResult, + cache: PersistedCacheMap, + fullHash = false, +): boolean { + const codeFiles = walked.files.filter((file) => classify(file.rel, file.ext) === "code"); + return (fullHash && codeFiles.length > 0) || codeFiles.some((file) => { + const cached = cache.get(file.rel); + return !cached || cached.size !== file.size || cached.mtimeMs !== file.mtimeMs; + }); +} + // Read /cache.json into the (cacheMap, meta) the preload needs. // Per-file records are reusable ONLY when (schemaVersion, extractorVersion) // match this engine — the exact gate the CLI applies before trusting a cache — @@ -157,3 +183,48 @@ export function preloadSession( const scan = scanRepo(repo, { ...opts, cache: persisted.cacheMap }); return { scan, cacheMap: toCacheMap(scan), arts: preloadArtifacts(repo, scan, persisted.meta, indexDir) }; } + +// Async variant for process boundaries that can defer grammar initialization. +// First inspect the persisted records and walk metadata. The common unchanged +// case loads no tree-sitter wasm; a new/stat-changed path warms BEFORE the one +// extraction pass, so changed files land at the AST tier without a provisional +// regex extraction followed by a second scan. +export async function preloadSessionLazy( + repo: string, + opts: Omit, + warm: () => Promise, + indexDir: string = INDEX_DIR, +): Promise { + const persisted = readPersistedIndex(repo, indexDir); + if (!persisted) return undefined; + const walked = opts.precomputedWalk ?? walk(repo, { + maxFileBytes: opts.maxBytes, + maxFiles: opts.maxFiles, + gitignore: opts.gitignore, + ignoreDirs: opts.ignoreDirs, + }); + // Decide whether grammars are needed from metadata BEFORE extraction. The old + // flow first extracted every changed code file without grammars, discovered + // the scan was stale, then warmed and extracted those files again. A new or + // stat-changed path may need AST work; deletions, scope-only differences and + // an unchanged index do not. fullHash deliberately warms because equal stats + // are no longer a freshness proof in that mode. + const needsWarm = needsGrammarWarm(walked, persisted.cacheMap, opts.fullHash); + if (needsWarm) { + await warm(); + } + const scan = scanRepo(repo, { ...opts, cache: persisted.cacheMap, precomputedWalk: walked }); + let artifactsTried = false; + let artifacts: IndexArtifacts | undefined; + return { + scan, + cacheMap: toCacheMap(scan), + loadArtifacts: () => { + if (!artifactsTried) { + artifactsTried = true; + artifacts = preloadArtifacts(repo, scan, persisted.meta, indexDir); + } + return artifacts; + }, + }; +} diff --git a/src/query.ts b/src/query.ts index 152dc4b..1dadae3 100644 --- a/src/query.ts +++ b/src/query.ts @@ -9,15 +9,19 @@ import type { CodeSymbol } from "./types.js"; import type { RepoScan } from "./scan.js"; import { readText } from "./walk.js"; import type { CallerSite } from "./callers.js"; -import { callerIndexFor, uniqueDefsFor } from "./derived.js"; +import { callerIndexFor, fileByRelFor, symbolsByNameFor, uniqueDefsFor } from "./derived.js"; import { byStr } from "./sort.js"; const REFERENCE_KINDS = new Set(["reexport", "reexport-all", "default"]); +function* allSymbols(scan: RepoScan): Generator { + for (const file of scan.files) yield* file.symbols; +} + // All symbols declared in one file, in declaration order — the fastest way to // understand a file without reading it. export function symbolsOverview(scan: RepoScan, rel: string): CodeSymbol[] { - const f = scan.files.find((x) => x.rel === rel); + const f = fileByRelFor(scan).get(rel); if (!f) return []; return [...f.symbols].filter((s) => !REFERENCE_KINDS.has(s.kind)).sort((a, b) => a.line - b.line || byStr(a.name, b.name)); } @@ -59,31 +63,46 @@ export function findSymbol(scan: RepoScan, namePath: string, opts: FindSymbolOpt opts.substring ? name.toLowerCase().includes(wanted.toLowerCase()) : name === wanted; const out: SymbolMatch[] = []; - for (const f of scan.files) { - for (const s of f.symbols) { - if (REFERENCE_KINDS.has(s.kind)) continue; - if (!matchName(s.name, leaf)) continue; - // Walk the parent chain (single level in practice — extractor records the - // enclosing symbol name) against the requested path suffix. Substring - // matching applies to the LAST segment only (Serena's contract): parent - // segments always match exactly. - if (parents.length) { - const parent = parents[parents.length - 1]!; - if (!s.parent || s.parent !== parent) continue; - } - out.push({ ...s }); + const candidates: Iterable = opts.substring + ? allSymbols(scan) + : symbolsByNameFor(scan).get(leaf) ?? []; + for (const s of candidates) { + if (REFERENCE_KINDS.has(s.kind)) continue; + if (!matchName(s.name, leaf)) continue; + // Walk the parent chain (single level in practice — extractor records the + // enclosing symbol name) against the requested path suffix. Substring + // matching applies to the LAST segment only (Serena's contract): parent + // segments always match exactly. + if (parents.length) { + const parent = parents[parents.length - 1]!; + if (!s.parent || s.parent !== parent) continue; } + out.push({ ...s }); } out.sort( (a, b) => Number(b.name === leaf) - Number(a.name === leaf) || byStr(a.file, b.file) || a.line - b.line, ); const capped = out.slice(0, opts.maxResults ?? 50); if (opts.includeBody) { + // Several overloads / methods commonly live in the same file. Read and + // split each source file once per query rather than once per matching + // declaration; result ownership and freshness semantics stay unchanged. + const linesByFile = new Map(); + const unreadableFiles = new Set(); for (const m of capped) { const end = m.endLine ?? m.line; - const content = readText(join(scan.root, m.file)); - if (!content) continue; - m.body = content.split("\n").slice(m.line - 1, end).join("\n"); + if (unreadableFiles.has(m.file)) continue; + let lines = linesByFile.get(m.file); + if (!lines) { + const content = readText(join(scan.root, m.file)); + if (!content) { + unreadableFiles.add(m.file); + continue; + } + lines = content.split("\n"); + linesByFile.set(m.file, lines); + } + m.body = lines.slice(m.line - 1, end).join("\n"); } } // Applied LAST so it composes predictably: `concise` with `includeBody` keeps diff --git a/src/scan.ts b/src/scan.ts index eca2330..5ece681 100644 --- a/src/scan.ts +++ b/src/scan.ts @@ -133,6 +133,7 @@ export function buildCodeRecord( record.truncated = code.truncated; record.relations = code.relations; record.terms = code.terms; + record.literals = code.literals; } else { record.title = basename(rel); } @@ -296,44 +297,35 @@ export function scanRepo(root: string, opts: ScanOptions = {}): RepoScan { continue; } - const record: FileRecord = { - rel: f.rel, - ext: f.ext, - size: f.size, - lines: countLines(content!), - hash, - kind, - lang, - headings: [], - symbols: [], - refs: [], - }; + // Keep code extraction in ONE builder shared with worker threads. A second + // field-by-field copy here previously omitted `literals`, making parallel + // and sequential graph output diverge. + const record: FileRecord = kind === "code" + ? buildCodeRecord(f.rel, f.ext, f.size, content!, hash, lang, opts) + : { + rel: f.rel, + ext: f.ext, + size: f.size, + lines: countLines(content!), + hash, + kind, + lang, + headings: [], + symbols: [], + refs: [], + }; - if (content) { - if (kind === "doc" && MARKDOWN_EXT.has(f.ext)) { + if (kind !== "code") { + if (content && kind === "doc" && MARKDOWN_EXT.has(f.ext)) { const md = extractMarkdown(content); record.title = md.title ?? basename(f.rel); record.summary = md.summary; record.headings = md.headings; record.refs = md.refs; - } else if (kind === "doc") { + } else if (content && kind === "doc") { // Non-markdown prose (.rst/.txt): title from basename, no link graph. record.title = basename(f.rel); - } else if (kind === "code") { - const code = extractCode(f.rel, f.ext, content, { maxCallsPerFile: opts.maxCallsPerFile }); - record.title = basename(f.rel); - record.summary = code.summary; - record.symbols = code.symbols; - record.refs = code.refs; - record.pkg = code.pkg; - record.idents = code.idents; - record.calls = code.calls; - record.importedNames = code.importedNames; - record.truncated = code.truncated; - record.relations = code.relations; - record.terms = code.terms; - record.literals = code.literals; - } else if (kind === "config") { + } else if (content && kind === "config") { // Config files carry no symbols, but they DO carry values — and a value // duplicated across a language boundary is the one no compiler checks. record.title = basename(f.rel); @@ -341,8 +333,6 @@ export function scanRepo(root: string, opts: ScanOptions = {}): RepoScan { } else { record.title = basename(f.rel); } - } else { - record.title = basename(f.rel); } // Retain doc content for the graph's mention pass (docs only) so it is read diff --git a/src/types.ts b/src/types.ts index 19268fc..668039f 100644 --- a/src/types.ts +++ b/src/types.ts @@ -74,7 +74,7 @@ export const SCHEMA_VERSION = 5; // threshold. Config files (JSON/YAML/TOML) get the same collector, because the // dangerous duplications are the ones that cross a language boundary where no // compiler is looking. -export const EXTRACTOR_VERSION = 13; +export const EXTRACTOR_VERSION = 14; // How a file is classified. `code` gets symbol/import extraction; `doc` gets // link/heading extraction; the rest are catalogued but not deeply parsed. diff --git a/src/walk.ts b/src/walk.ts index b1971d0..02156ec 100644 --- a/src/walk.ts +++ b/src/walk.ts @@ -15,6 +15,14 @@ export const IGNORE_DIRS = new Set([ "tmp", ".ultraindex", ".codeindex", "Pods", "DerivedData", ".terraform", "elm-stuff", ".dart_tool", ]); +function isIgnoredDirectory(name: string, ignoreDirs: Set): boolean { + // A process killed during an atomic symbolic edit can leave this directory + // beside the source. It contains a copy of that source and must never become + // a duplicate phantom file in the next index, even when the consumer repo + // has no matching .gitignore rule. + return ignoreDirs.has(name) || name.startsWith(".codeindex-edit-"); +} + // Lockfiles: huge, machine-generated, and pure noise for a code/docs question — // they'd otherwise rank as keyword-dense "code" hits (e.g. package-lock.json // matching a dependency name). Skipped entirely. @@ -149,7 +157,7 @@ export function walk(root: string, opts: WalkOptions = {}): WalkResult { // false on its dirent and falls through to the stat-based // classification below, so a link named node_modules still classifies // by its target exactly as before. - if (entry.isDirectory() && ignoreDirs.has(name)) continue; + if (entry.isDirectory() && isIgnoredDirectory(name, ignoreDirs)) continue; let st; try { // Non-links: a single lstatSync supplies isDirectory/isFile/size/ @@ -162,7 +170,7 @@ export function walk(root: string, opts: WalkOptions = {}): WalkResult { continue; } if (st.isDirectory()) { - if (ignoreDirs.has(name)) continue; + if (isIgnoredDirectory(name, ignoreDirs)) continue; // An in-repo DIRECTORY symlink is skipped entirely: its target is (or // will be) walked under its canonical name, and letting both paths race // through the cycle guard would keep whichever readdir served first — diff --git a/tests/browser-build.test.ts b/tests/browser-build.test.ts index 261d72d..64ffda4 100644 --- a/tests/browser-build.test.ts +++ b/tests/browser-build.test.ts @@ -184,4 +184,49 @@ describe("browser bundle", () => { const web = await indexInBrowser(diskRoot); expect(web.scan.commit).toBeUndefined(); }); + + it("invalidates a cached scan after a same-size VFS edit", () => { + browser.resetVfs(); + const before = new TextEncoder().encode("export const aa = 1;\n"); + const after = new TextEncoder().encode("export const bb = 2;\n"); + browser.mountFiles([{ path: "/repo/a.ts", size: before.byteLength, bytes: before }]); + const first = browser.scanRepo("/repo"); + const cache = new Map(first.files.map((f: Bundle) => [f.rel, { hash: f.hash, record: f, size: f.size, mtimeMs: first.mtimes.get(f.rel) }])); + + browser.setFileBytes("/repo/a.ts", after); + const second = browser.scanRepo("/repo", { cache }); + + expect(second.files[0].symbols.map((s: Bundle) => s.name)).toContain("bb"); + expect(second.files[0].symbols.map((s: Bundle) => s.name)).not.toContain("aa"); + expect(second.files[0].hash).not.toBe(first.files[0].hash); + }); + + it("round-trips embedding artifacts through the browser bundle", () => { + const index = { + embedVersion: 1, + modelId: "fixture", + dim: 3, + records: [{ file: "src/a.ts", symbol: "a", line: 2, vec: new Int8Array([-128, 0, 127]) }], + }; + const bytes = browser.serializeEmbeddings(index); + const view = bytes.subarray(0); + const decoded = browser.deserializeEmbeddings(view); + expect(decoded).toEqual(index); + }); + + it("retries a grammar after it becomes available later", async () => { + browser.resetVfs(); + const runtime = new Uint8Array(readFileSync(join(GRAMMARS, browser.RUNTIME_WASM))); + const first = await browser.loadGrammars(new Set([".scala"]), async (name: string) => { + if (name === "scala.wasm") throw new Error("not mounted yet"); + return runtime; + }); + expect(first.failed).toEqual(["scala"]); + + const second = await browser.loadGrammars(new Set([".scala"]), async (name: string) => { + return new Uint8Array(readFileSync(join(GRAMMARS, name))); + }); + expect(second.failed).toEqual([]); + expect(second.loaded).toEqual(["scala"]); + }); }); diff --git a/tests/e2e-real-repos.test.ts b/tests/e2e-real-repos.test.ts index d94af95..e454518 100644 --- a/tests/e2e-real-repos.test.ts +++ b/tests/e2e-real-repos.test.ts @@ -91,6 +91,17 @@ const REPOS: RealRepo[] = [ crossEdge: [/^crates\/core\//, /^crates\/(?!core\/)/], budgetMs: 120_000, }, + { + // Large Gradle multi-project: Java + Kotlin across config/core/web modules. + // Added after the stabilization audit as an independent real-world proof, + // not one of the repositories used to design the fixes. + slug: "spring-projects/spring-security", + sha: "61feae94a04ab78ede3aa7c5c97b1b0e993cca48", + maxDanglingRatio: 0.001, // measured baseline: 0/48,146 edges + primaryLang: "java", + crossEdge: [/^config\//, /^core\//], + budgetMs: 120_000, + }, ]; // Shallow-fetch the pinned commit into the cache; re-runs are offline. diff --git a/tests/grammars-pull.test.ts b/tests/grammars-pull.test.ts index 65fe75f..0d8f1c4 100644 --- a/tests/grammars-pull.test.ts +++ b/tests/grammars-pull.test.ts @@ -1,6 +1,6 @@ import { execFile } from "node:child_process"; import { createHash } from "node:crypto"; -import { copyFileSync, cpSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync } from "node:fs"; +import { copyFileSync, cpSync, existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, renameSync, rmSync, writeFileSync } from "node:fs"; import http from "node:http"; import type { AddressInfo } from "node:net"; import { tmpdir } from "node:os"; @@ -16,6 +16,7 @@ import { extractTarInto, fetchExpectedSha256, fetchGrammarsTarball, + installGrammarCacheAtomically, resolveGrammarsPullTarget, } from "../src/ast/grammars-pull.js"; import type { GrammarsPullTarget } from "../src/engine.js"; @@ -306,6 +307,90 @@ describe("tar extraction + path-traversal guard", () => { }); describe("CLI grammars status + pull", () => { + it("restores the previous cache if the final install rename fails", () => { + const parent = mk("ci-gr-swap-"); + const cache = join(parent, "cache"); + const incoming = join(parent, "incoming"); + const marker = join(parent, "marker.sha256"); + mkdirSync(cache); + mkdirSync(incoming); + writeFileSync(join(cache, "web-tree-sitter.wasm"), "old"); + writeFileSync(join(incoming, "web-tree-sitter.wasm"), "new"); + writeFileSync(marker, "old-hash\n"); + let calls = 0; + const failInstall = (from: string, to: string): void => { + calls++; + if (calls === 3) throw new Error("simulated rename failure"); + renameSync(from, to); + }; + + expect(() => installGrammarCacheAtomically(incoming, cache, marker, "new-hash", failInstall)).toThrow(/simulated/); + expect(readFileSync(join(cache, "web-tree-sitter.wasm"), "utf8")).toBe("old"); + expect(readFileSync(marker, "utf8")).toBe("old-hash\n"); + expect(readFileSync(join(incoming, "web-tree-sitter.wasm"), "utf8")).toBe("new"); + }); + + it("keeps a successful install when backup cleanup fails", () => { + const parent = mk("ci-gr-cleanup-"); + const cache = join(parent, "cache"); + const incoming = join(parent, "incoming"); + const marker = join(parent, "marker.sha256"); + mkdirSync(cache); + mkdirSync(incoming); + writeFileSync(join(cache, "web-tree-sitter.wasm"), "old"); + writeFileSync(join(incoming, "web-tree-sitter.wasm"), "new"); + writeFileSync(marker, "old-hash\n"); + + expect(() => + installGrammarCacheAtomically(incoming, cache, marker, "new-hash", renameSync, () => { + throw new Error("simulated cleanup failure"); + }), + ).not.toThrow(); + expect(readFileSync(join(cache, "web-tree-sitter.wasm"), "utf8")).toBe("new"); + expect(readFileSync(marker, "utf8")).toBe("new-hash\n"); + }); + + it("removes a stale digest marker when the new cache has no checksum", () => { + const parent = mk("ci-gr-unverified-"); + const cache = join(parent, "cache"); + const incoming = join(parent, "incoming"); + const marker = join(parent, "marker.sha256"); + mkdirSync(cache); + mkdirSync(incoming); + writeFileSync(join(cache, "web-tree-sitter.wasm"), "old"); + writeFileSync(join(incoming, "web-tree-sitter.wasm"), "unverified-new"); + writeFileSync(marker, "old-hash\n"); + + installGrammarCacheAtomically(incoming, cache, marker, undefined); + expect(readFileSync(join(cache, "web-tree-sitter.wasm"), "utf8")).toBe("unverified-new"); + expect(existsSync(marker)).toBe(false); + }); + + it("restores every possible backup and preserves the rest when rollback is incomplete", () => { + const parent = mk("ci-gr-rollback-partial-"); + const cache = join(parent, "cache"); + const incoming = join(parent, "incoming"); + const marker = join(parent, "marker.sha256"); + mkdirSync(cache); + mkdirSync(incoming); + writeFileSync(join(cache, "web-tree-sitter.wasm"), "old"); + writeFileSync(join(incoming, "web-tree-sitter.wasm"), "new"); + writeFileSync(marker, "old-hash\n"); + const failInstallAndMarkerRestore = (from: string, to: string): void => { + if (from === incoming || from.endsWith("previous-marker")) throw new Error(`simulated rename failure: ${from}`); + renameSync(from, to); + }; + + expect(() => + installGrammarCacheAtomically(incoming, cache, marker, "new-hash", failInstallAndMarkerRestore), + ).toThrow(/rollback failed/); + // The cache restoration must still run after marker restoration failed. + expect(readFileSync(join(cache, "web-tree-sitter.wasm"), "utf8")).toBe("old"); + const swap = readdirSync(parent).find((entry) => entry.startsWith(".grammars-swap-")); + expect(swap).toBeDefined(); + expect(readFileSync(join(parent, swap!, "previous-marker"), "utf8")).toBe("old-hash\n"); + }); + it("`grammars status` reports the adjacent tier + shape from the shipped bundle", async () => { const { stdout, status } = await runCli(["grammars", "status"], { ...process.env, ...NEUTRAL }); expect(status).toBe(0); diff --git a/tests/lsp.test.ts b/tests/lsp.test.ts index d87fb9b..317ebc4 100644 --- a/tests/lsp.test.ts +++ b/tests/lsp.test.ts @@ -115,6 +115,20 @@ describe("URI mapping", () => { expect(relFromUri(root, fileUri(root, rel))).toBe(rel); }); + it("round-trips canonical Windows file URIs", () => { + const root = "C:\\work\\repo"; + const rel = "src\\a b.ts"; + expect(fileUri(root, rel)).toBe("file:///C:/work/repo/src/a%20b.ts"); + expect(relFromUri(root, "file:///C:/work/repo/src/a%20b.ts")).toBe("src/a b.ts"); + }); + + it("emits and accepts canonical Windows UNC file URIs", () => { + const root = "\\\\server\\share\\repo"; + const rel = "src\\a b.ts"; + expect(fileUri(root, rel)).toBe("file://server/share/repo/src/a%20b.ts"); + expect(relFromUri(root, "file://server/share/repo/src/a%20b.ts")).toBe("src/a b.ts"); + }); + it("refuses a URI outside the repository rather than inventing a path", () => { // A definition in node_modules or the standard library is real, but has no // repo-relative path — reporting one would name a file that does not exist. diff --git a/tests/mcp.test.ts b/tests/mcp.test.ts index ac0b0f8..047fdbc 100644 --- a/tests/mcp.test.ts +++ b/tests/mcp.test.ts @@ -18,6 +18,7 @@ import { validateArgs, } from "../src/mcp.js"; import { parseMcpFlags } from "../src/engine-cli.js"; +import { sessionInvalidate } from "../src/mcp/session.js"; import { buildIndexArtifacts } from "../src/pipeline.js"; import { headCommit } from "../src/git.js"; import { renderGraphJson } from "../src/render/graph-json.js"; @@ -31,7 +32,7 @@ const REPO = fileURLToPath(new URL("./fixtures/mini-repo", import.meta.url)); const MODEL_DIR = fileURLToPath(new URL("./fixtures/embed-model", import.meta.url)); interface RpcMsg { - id?: number; + id?: number | string | null; result?: { protocolVersion?: string; serverInfo?: { name: string; version?: string }; @@ -89,11 +90,9 @@ function mcpSession( } // Same harness but the requests go out as ONE JSON-RPC batch array line. -function mcpBatch(requests: Record[]): Promise> { +function mcpBatch(requests: Record[]): Promise { return new Promise((resolvePromise, reject) => { const child = spawn(process.execPath, [CLI, "mcp"], { stdio: ["pipe", "pipe", "inherit"] }); - const expected = new Set(requests.filter((r) => r.id !== undefined).map((r) => r.id as number)); - const got = new Map(); let buf = ""; const timer = setTimeout(() => { child.kill(); @@ -106,13 +105,10 @@ function mcpBatch(requests: Record[]): Promise[]): Promise { + it("does not let scan_summary cache a changed file at the regex tier", async () => { + const parent = mkdtempSync(join(tmpdir(), "ci-mcp-lazy-grammar-")); + const repo = join(parent, "repo"); + cpSync(REPO, repo, { recursive: true }); + const source = join(repo, "src", "lazy.ts"); + writeFileSync(source, "export class LazyService {\n initialMethod(): number {\n return 1;\n }\n}\n"); + execFileSync(process.execPath, [CLI, "index", "--repo", repo, "--out", join(repo, ".codeindex"), "--workers", "0"]); + const child = spawn(process.execPath, [CLI, "mcp", "--repo", repo], { stdio: ["pipe", "pipe", "inherit"] }); + try { + const replies = await new Promise>((resolvePromise, reject) => { + const got = new Map(); + let buf = ""; + const timer = setTimeout(() => reject(new Error("lazy grammar MCP session timed out")), 15_000); + const sendCall = (id: number, name: string, args: Record): void => { + child.stdin.write(JSON.stringify({ jsonrpc: "2.0", id, method: "tools/call", params: { name, arguments: args } }) + "\n"); + }; + child.stdout.on("data", (chunk: Buffer) => { + buf += chunk.toString(); + let newline; + while ((newline = buf.indexOf("\n")) !== -1) { + const line = buf.slice(0, newline); + buf = buf.slice(newline + 1); + if (!line.trim()) continue; + const reply = JSON.parse(line) as RpcMsg; + if (typeof reply.id !== "number") continue; + got.set(reply.id, reply); + if (reply.id === 1) { + writeFileSync(source, "export class LazyService {\n laterMethod(): number {\n return 2;\n }\n}\n"); + sendCall(2, "scan_summary", {}); + } else if (reply.id === 2) { + sendCall(3, "find_symbol", { namePath: "laterMethod" }); + } else if (reply.id === 3) { + clearTimeout(timer); + resolvePromise(got); + } + } + }); + child.on("error", reject); + sendCall(1, "find_symbol", { namePath: "initialMethod" }); + }); + const initial = JSON.parse(replies.get(1)!.result!.content![0]!.text) as { name: string }[]; + const later = JSON.parse(replies.get(3)!.result!.content![0]!.text) as { name: string }[]; + expect(initial.some((match) => match.name === "initialMethod")).toBe(true); + expect(later.some((match) => match.name === "laterMethod")).toBe(true); + } finally { + child.kill(); + rmSync(parent, { recursive: true, force: true }); + } + }, 20_000); + + it("invalidates a watched pinned session after a filesystem change", async () => { + const parent = mkdtempSync(join(tmpdir(), "ci-mcp-watch-")); + const repo = join(parent, "repo"); + cpSync(REPO, repo, { recursive: true }); + const child = spawn(process.execPath, [CLI, "mcp", "--repo", repo, "--watch"], { + stdio: ["pipe", "pipe", "pipe"], + }); + try { + const replies = await new Promise>((resolvePromise, reject) => { + const got = new Map(); + let buf = ""; + const timer = setTimeout(() => reject(new Error("watched MCP session timed out")), 15_000); + child.stdout.on("data", (chunk: Buffer) => { + buf += chunk.toString(); + let newline; + while ((newline = buf.indexOf("\n")) !== -1) { + const line = buf.slice(0, newline); + buf = buf.slice(newline + 1); + if (!line.trim()) continue; + const reply = JSON.parse(line) as RpcMsg; + if (typeof reply.id !== "number") continue; + got.set(reply.id, reply); + if (reply.id === 1) { + writeFileSync(join(repo, "src", "watched.ts"), "export function watchedAdded(): number { return 1; }\n"); + child.stdin.write( + JSON.stringify({ + jsonrpc: "2.0", + id: 2, + method: "tools/call", + params: { name: "find_symbol", arguments: { namePath: "watchedAdded" } }, + }) + "\n", + ); + } else if (reply.id === 2) { + clearTimeout(timer); + resolvePromise(got); + } + } + }); + child.on("error", reject); + child.stdin.write( + JSON.stringify({ + jsonrpc: "2.0", + id: 1, + method: "tools/call", + params: { name: "find_symbol", arguments: { namePath: "fetchData" } }, + }) + "\n", + ); + }); + const matches = JSON.parse(replies.get(2)!.result!.content![0]!.text) as { name: string }[]; + expect(matches.some((match) => match.name === "watchedAdded")).toBe(true); + } finally { + child.kill(); + rmSync(parent, { recursive: true, force: true }); + } + }, 20_000); + + it("refreshes git commit metadata in watch mode without a worktree change", async () => { + const parent = mkdtempSync(join(tmpdir(), "ci-mcp-watch-head-")); + const repo = join(parent, "repo"); + cpSync(REPO, repo, { recursive: true }); + execFileSync("git", ["init", "-q"], { cwd: repo }); + execFileSync("git", ["config", "user.email", "codeindex@example.invalid"], { cwd: repo }); + execFileSync("git", ["config", "user.name", "codeindex test"], { cwd: repo }); + execFileSync("git", ["add", "."], { cwd: repo }); + execFileSync("git", ["commit", "-qm", "initial"], { cwd: repo }); + const firstCommit = execFileSync("git", ["rev-parse", "--short", "HEAD"], { cwd: repo, encoding: "utf8" }).trim(); + // Prime the persisted artifacts so this covers both the in-memory graph and + // preloadSessionLazy's memoized graph.json loader after HEAD moves. + execFileSync(process.execPath, [CLI, "index", "--repo", repo, "--out", join(repo, ".codeindex")]); + const child = spawn(process.execPath, [CLI, "mcp", "--repo", repo, "--watch"], { stdio: ["pipe", "pipe", "pipe"] }); + try { + const replies = await new Promise>((resolvePromise, reject) => { + const got = new Map(); + let buf = ""; + const timer = setTimeout(() => reject(new Error("watched MCP HEAD test timed out")), 15_000); + const requestGraph = (id: number): void => { + child.stdin.write(JSON.stringify({ jsonrpc: "2.0", id, method: "tools/call", params: { name: "graph", arguments: {} } }) + "\n"); + }; + child.stdout.on("data", (chunk: Buffer) => { + buf += chunk.toString(); + let newline; + while ((newline = buf.indexOf("\n")) !== -1) { + const line = buf.slice(0, newline); + buf = buf.slice(newline + 1); + if (!line.trim()) continue; + const reply = JSON.parse(line) as RpcMsg; + if (typeof reply.id !== "number") continue; + got.set(reply.id, reply); + if (reply.id === 1) { + execFileSync("git", ["commit", "--allow-empty", "-qm", "metadata only"], { cwd: repo }); + requestGraph(2); + } else if (reply.id === 2) { + clearTimeout(timer); + resolvePromise(got); + } + } + }); + child.on("error", reject); + requestGraph(1); + }); + const secondCommit = execFileSync("git", ["rev-parse", "--short", "HEAD"], { cwd: repo, encoding: "utf8" }).trim(); + const firstGraph = JSON.parse(replies.get(1)!.result!.content![0]!.text) as { commit?: string }; + const secondGraph = JSON.parse(replies.get(2)!.result!.content![0]!.text) as { commit?: string }; + expect(firstGraph.commit).toBe(firstCommit); + expect(secondGraph.commit).toBe(secondCommit); + expect(secondGraph.commit).not.toBe(firstGraph.commit); + } finally { + child.kill(); + rmSync(parent, { recursive: true, force: true }); + } + }, 20_000); + + it("rejects a null JSON-RPC member without terminating the server", () => { + const proc = spawnSync(process.execPath, [CLI, "mcp"], { + input: 'null\n{"jsonrpc":"2.0","id":1,"method":"ping"}\n', + encoding: "utf8", + }); + expect(proc.status).toBe(0); + const replies = proc.stdout.trim().split("\n").map((line) => JSON.parse(line) as RpcMsg); + expect(replies[0]!.error).toMatchObject({ code: -32600 }); + expect(replies[1]!.id).toBe(1); + expect(replies[1]!.result).toEqual({}); + }); + + it("does not answer a JSON-RPC response message", () => { + const proc = spawnSync(process.execPath, [CLI, "mcp"], { + input: '{"jsonrpc":"2.0","id":99,"result":{}}\n{"jsonrpc":"2.0","id":1,"method":"ping"}\n', + encoding: "utf8", + }); + expect(proc.status).toBe(0); + const replies = proc.stdout.trim().split("\n").map((line) => JSON.parse(line) as RpcMsg); + expect(replies).toHaveLength(1); + expect(replies[0]!.id).toBe(1); + }); + + it("answers a request whose explicit id is null", () => { + const proc = spawnSync(process.execPath, [CLI, "mcp"], { + input: '{"jsonrpc":"2.0","id":null,"method":"ping"}\n', + encoding: "utf8", + }); + expect(proc.status).toBe(0); + expect(JSON.parse(proc.stdout.trim())).toEqual({ jsonrpc: "2.0", id: null, result: {} }); + }); + + it("rejects missing and non-directory repositories", async () => { + const missing = join(tmpdir(), `codeindex-missing-${Date.now()}`); + const res = await mcpSession([ + { id: 1, method: "tools/call", params: { name: "scan_summary", arguments: { repo: missing } } }, + { id: 2, method: "tools/call", params: { name: "scan_summary", arguments: { repo: join(REPO, "README.md") } } }, + ]); + expect(res.get(1)!.result!.isError).toBe(true); + expect(res.get(2)!.result!.isError).toBe(true); + }); + + it("honours numeric strings accepted by the tool schema", async () => { + const res = await mcpSession([ + { id: 1, method: "tools/call", params: { name: "search", arguments: { repo: REPO, query: "client", limit: "1" } } }, + ]); + const hits = JSON.parse(res.get(1)!.result!.content![0]!.text) as unknown[]; + expect(hits).toHaveLength(1); + }); + + it("honours zero-valued limits instead of replacing them with defaults", async () => { + const res = await mcpSession([ + { id: 1, method: "tools/call", params: { name: "search", arguments: { repo: REPO, query: "client", limit: 0 } } }, + ]); + const hits = JSON.parse(res.get(1)!.result!.content![0]!.text) as unknown[]; + expect(hits).toEqual([]); + }); + it("handshakes, lists tools, and executes tool calls", async () => { const res = await mcpSession([ { id: 1, method: "initialize", params: { protocolVersion: "2024-11-05", capabilities: {} } }, @@ -253,8 +469,10 @@ describe("MCP server", () => { { id: 1, method: "ping" }, { id: 2, method: "tools/list" }, ]); - expect(res.get(1)!.result).toEqual({}); - expect(res.get(2)!.result!.tools!.length).toBeGreaterThan(0); + expect(Array.isArray(res)).toBe(true); + expect(res).toHaveLength(2); + expect(res.find((reply) => reply.id === 1)!.result).toEqual({}); + expect(res.find((reply) => reply.id === 2)!.result!.tools!.length).toBeGreaterThan(0); }, 20_000); }); @@ -1048,6 +1266,22 @@ describe("getScan — bounded LRU, not a single entry", () => { expect(getScan(two, {})).toBe(s2); }); + it("invalidates one watched repo without evicting another repo", () => { + const one = tmpFixtureCopy("ci-scan-invalidate-a-"); + const two = tmpFixtureCopy("ci-scan-invalidate-b-"); + getScan(one, {}); + const other = getScan(two, {}); + sessionInvalidate(one, "src/client.ts"); + expect(getScan(two, {})).toBe(other); + }); + + it("keeps memoized artifacts when an ignored background path changes", () => { + const repo = tmpFixtureCopy("ci-scan-invalidate-ignored-"); + const artifacts = getArtifacts(repo, {}); + sessionInvalidate(repo, "dist/generated.js"); + expect(getArtifacts(repo, {})).toBe(artifacts); + }); + it("stays bounded: the oldest entry is evicted past the cap", () => { const repo = tmpFixtureCopy("ci-scan-lru-cap-"); const oldest = getScan(repo, { scope: "src" }); @@ -1232,6 +1466,13 @@ describe("validateArgs", () => { expect(validateArgs(schema, { limit: "50" })).toBeUndefined(); }); + it("enforces declared numeric bounds for numbers and numeric strings", () => { + const bounded = { properties: { depth: { type: "number", minimum: 1, maximum: 5 } } }; + expect(validateArgs(bounded, { depth: 0 })).toMatch(/at least 1/); + expect(validateArgs(bounded, { depth: "6" })).toMatch(/at most 5/); + expect(validateArgs(bounded, { depth: "5" })).toBeUndefined(); + }); + it("names the offending argument and what it got", () => { expect(validateArgs(schema, { limit: "banana" })).toMatch(/`limit` must be a number/); expect(validateArgs(schema, { substring: "yes" })).toMatch(/`substring` must be a boolean, got string/); @@ -1321,6 +1562,8 @@ describe("tool profiles and onboarding", () => { // "all" is the default and must stay expressible. expect(parseMcpFlags(["--tools", "all"]).profile).toBeUndefined(); expect(parseMcpFlags(["--tools", "find,impact"]).profile).toBe("find,impact"); + expect(parseMcpFlags(["--repo", REPO, "--watch"]).watch).toBe(true); + expect(() => parseMcpFlags(["--watch"])).toThrow(/requires --repo/); }); it("onboard composes a brief and persists it as a memory", async () => { diff --git a/tests/pack-smoke.test.ts b/tests/pack-smoke.test.ts index 438ccd8..ff20170 100644 --- a/tests/pack-smoke.test.ts +++ b/tests/pack-smoke.test.ts @@ -127,5 +127,5 @@ describe("the `types` condition", () => { // by walking up from cwd (the repo root), while `-p` points tsc at the // scratch tsconfig/check.ts pair. execFileSync("npx", ["tsc", "-p", tmp], { cwd: REPO_ROOT, encoding: "utf8" }); - }); + }, 20_000); }); diff --git a/tests/phase2.test.ts b/tests/phase2.test.ts index c983b92..e9d4c4e 100644 --- a/tests/phase2.test.ts +++ b/tests/phase2.test.ts @@ -1,5 +1,5 @@ import { execFileSync } from "node:child_process"; -import { mkdirSync, mkdtempSync, writeFileSync } from "node:fs"; +import { chmodSync, lstatSync, mkdirSync, mkdtempSync, readlinkSync, statSync, symlinkSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { fileURLToPath } from "node:url"; @@ -12,7 +12,7 @@ import { gitChurn, changedSince } from "../src/git.js"; import { changeCoupling, rankHotspots } from "../src/coupling.js"; import { renderRepoMap } from "../src/repomap.js"; import { symbolsOverview, findSymbol, findReferences } from "../src/query.js"; -import { replaceSymbolBody, insertAfterSymbol, insertBeforeSymbol, resolveUniqueSymbol } from "../src/edit.js"; +import { atomicWriteText, replaceSymbolBody, insertAfterSymbol, insertBeforeSymbol, resolveUniqueSymbol } from "../src/edit.js"; import { writeMemory, readMemory, deleteMemory, listMemories } from "../src/memory.js"; import { readText as engineRead } from "../src/walk.js"; import { findDeadCode } from "../src/deadcode.js"; @@ -395,6 +395,50 @@ describe("symbolic editing", () => { expect(content).not.toContain("return a + b;"); }); + it("preserves source permissions across an atomic replacement", () => { + const root = makeRepo(); + const source = join(root, "calc.ts"); + chmodSync(source, 0o744); + replaceSymbolBody(scanRepo(root), "add", "export function add(): number {\n return 3;\n}"); + expect(statSync(source).mode & 0o777).toBe(0o744); + }); + + it("does not report a committed edit as failed when temp cleanup fails", () => { + const root = makeRepo(); + const source = join(root, "calc.ts"); + expect(() => + atomicWriteText(source, "export const committed = true;\n", () => { + throw new Error("simulated cleanup failure"); + }), + ).not.toThrow(); + expect(engineRead(source)).toBe("export const committed = true;\n"); + }); + + it("never indexes an orphaned symbolic-edit temp directory", () => { + const root = makeRepo(); + const orphan = join(root, ".codeindex-edit-crashed"); + mkdirSync(orphan); + writeFileSync(join(orphan, "calc.ts"), "export function phantom(): number { return 0; }\n"); + const scan = scanRepo(root); + expect(scan.files.some((file) => file.rel.includes(".codeindex-edit-"))).toBe(false); + expect(findSymbol(scan, "phantom")).toEqual([]); + }); + + it("edits a symlink target without replacing the symlink", () => { + const root = makeRepo(); + const target = join(root, "calc.ts"); + const link = join(root, "linked.ts"); + const scan = scanRepo(root); + symlinkSync(target, link); + const record = scan.files.find((file) => file.rel === "calc.ts")!; + record.rel = "linked.ts"; + for (const symbol of record.symbols) symbol.file = "linked.ts"; + replaceSymbolBody(scan, "add", "export function add(): number {\n return 9;\n}", "linked.ts"); + expect(lstatSync(link).isSymbolicLink()).toBe(true); + expect(readlinkSync(link)).toBe(target); + expect(engineRead(target)).toContain("return 9;"); + }); + it("insertAfterSymbol keeps a blank line and insertBeforeSymbol pushes down", () => { const root = makeRepo(); let scan = scanRepo(root); diff --git a/tests/pool.test.ts b/tests/pool.test.ts index 033932d..c4c8229 100644 --- a/tests/pool.test.ts +++ b/tests/pool.test.ts @@ -24,9 +24,17 @@ describe("parallel extraction — byte-identical to sequential (built CLI)", () it("produces the same graph.json and symbols.json at --workers 0 and 4", () => { const dir = mkdtempSync(join(tmpdir(), "ci-par-")); try { + const repo = join(dir, "repo"); + cpSync(REPO, repo, { recursive: true }); + // Exercise a field that symbols.json does not carry. The original worker + // record forgot literals, so small fixtures without a reported duplicate + // made this byte-identity gate pass vacuously while real graphs diverged. + for (const name of ["literal-a.ts", "literal-b.ts", "literal-c.ts"]) { + writeFileSync(join(repo, "src", name), `export const value = "parallel-regression-value";\n`); + } const build = (out: string, workers: string): void => { mkdirSync(out, { recursive: true }); - execFileSync(process.execPath, [CLI, "index", "--repo", REPO, "--out", out, "--workers", workers], { + execFileSync(process.execPath, [CLI, "index", "--repo", repo, "--out", out, "--workers", workers], { encoding: "utf8", }); }; @@ -40,6 +48,7 @@ describe("parallel extraction — byte-identical to sequential (built CLI)", () // A parallel build must actually have produced symbols — a silent // fallback to an empty index would otherwise pass the equality above. expect(Object.keys(JSON.parse(readFileSync(join(par, "symbols.json"), "utf8")).defs).length).toBeGreaterThan(0); + expect(readFileSync(join(par, "graph.json"), "utf8")).toContain("parallel-regression-value"); } finally { rmSync(dir, { recursive: true, force: true }); } @@ -76,6 +85,16 @@ describe("parallel extraction — byte-identical to sequential (built CLI)", () } }); + it("keeps a cold read command byte-identical when workers are enabled", () => { + const run = (workers: string): string => + execFileSync( + process.execPath, + [CLI, "search", "client", "--repo", REPO, "--workers", workers, "--no-index-cache"], + { encoding: "utf8" }, + ); + expect(run("4")).toBe(run("0")); + }); + it("rejects a negative --workers instead of silently guessing", () => { expect(() => execFileSync(process.execPath, [CLI, "index", "--repo", REPO, "--out", join(tmpdir(), "nope"), "--workers", "-1"], { diff --git a/tests/preload.test.ts b/tests/preload.test.ts index fb708a8..2322490 100644 --- a/tests/preload.test.ts +++ b/tests/preload.test.ts @@ -4,6 +4,9 @@ import { fileURLToPath } from "node:url"; import { cpSync, mkdtempSync, rmSync, readFileSync, writeFileSync, appendFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; +import { preloadSessionLazy } from "../src/preload.js"; +import { ensureGrammars, grammarKeysForExts } from "../src/ast/loader.js"; +import { walk } from "../src/walk.js"; const REPO = fileURLToPath(new URL("./fixtures/mini-repo", import.meta.url)); const CLI = fileURLToPath(new URL("../scripts/cli.mjs", import.meta.url)); @@ -30,6 +33,17 @@ function withRepo(fn: (repo: string) => void): void { } } +async function withRepoAsync(fn: (repo: string) => Promise): Promise { + const dir = mkdtempSync(join(tmpdir(), "ci-preload-async-")); + try { + const repo = join(dir, "repo"); + cpSync(REPO, repo, { recursive: true }); + await fn(repo); + } finally { + rmSync(dir, { recursive: true, force: true }); + } +} + const prime = (repo: string): void => { run(repo, ["index", "--out", join(repo, ".codeindex")]); }; @@ -105,3 +119,72 @@ describe("persisted-index reuse — output-identical", { timeout: 60_000 }, () = }); }); }); + +describe("lazy grammar warm on persisted indexes", { timeout: 30_000 }, () => { + it("does not warm tree-sitter when the persisted scan is unchanged", async () => { + await withRepoAsync(async (repo) => { + prime(repo); + let warms = 0; + const result = await preloadSessionLazy(repo, {}, async () => { + warms++; + }); + expect(result?.scan.contentUnchanged).toBe(true); + expect(warms).toBe(0); + expect(result?.arts).toBeUndefined(); + const artifacts = result?.loadArtifacts?.(); + expect(artifacts?.graph.fileCount).toBe(result?.scan.files.length); + expect(result?.loadArtifacts?.()).toBe(artifacts); + }); + }); + + it("defers artifact reads until the caller asks for graph-shaped data", async () => { + await withRepoAsync(async (repo) => { + prime(repo); + const result = await preloadSessionLazy(repo, {}, async () => {}); + writeFileSync(join(repo, ".codeindex", "graph.json"), "{ corrupt after preload"); + expect(result?.loadArtifacts?.()).toBeUndefined(); + }); + }); + + it("warms and rebuilds changed files at the AST tier", async () => { + await withRepoAsync(async (repo) => { + prime(repo); + appendFileSync(join(repo, "src", "client.ts"), "\nexport function lazyAdded(): number { return 7; }\n"); + const walked = walk(repo, {}); + let warms = 0; + const result = await preloadSessionLazy(repo, { precomputedWalk: walked }, async () => { + warms++; + await ensureGrammars(grammarKeysForExts(walked.files.map((file) => file.ext))); + }); + expect(warms).toBe(1); + expect(result?.scan.files.flatMap((file) => file.symbols).some((symbol) => symbol.name === "lazyAdded")).toBe(true); + }); + }); + + it("does not warm for a deletion that needs no new extraction", async () => { + await withRepoAsync(async (repo) => { + prime(repo); + rmSync(join(repo, "src", "client.ts")); + let warms = 0; + const result = await preloadSessionLazy(repo, {}, async () => { + warms++; + }); + expect(warms).toBe(0); + expect(result?.scan.files.some((file) => file.rel === "src/client.ts")).toBe(false); + }); + }); + + it("does not warm when only documentation changed", async () => { + await withRepoAsync(async (repo) => { + prime(repo); + appendFileSync(join(repo, "README.md"), "\nA documentation-only cache drift.\n"); + let warms = 0; + const result = await preloadSessionLazy(repo, {}, async () => { + warms++; + }); + expect(warms).toBe(0); + expect(result?.scan.contentUnchanged).toBe(false); + expect(result?.scan.files.find((file) => file.rel === "README.md")?.lines).toBeGreaterThan(10); + }); + }); +}); diff --git a/tests/rewrite.test.ts b/tests/rewrite.test.ts index 20208d1..6503bde 100644 --- a/tests/rewrite.test.ts +++ b/tests/rewrite.test.ts @@ -172,6 +172,16 @@ describe("hoistLeadingFlags", () => { expect(hoistLeadingFlags(["--repo", "/x", "scan"])).toEqual(["scan", "--repo", "/x"]); }); + it.each([ + ["--base", "HEAD", "changed"], + ["--depth", "2", "impact"], + ["--kind", "import", "context"], + ["--rank", "lexical", "search"], + ["--direction", "both", "callgraph"], + ])("keeps %s with its value when placed before the command", (flag, value, command) => { + expect(hoistLeadingFlags([flag, value, command, "target"])).toEqual([command, flag, value, "target"]); + }); + it("handles the iterion inject_flag shape", () => { // `codeindex grep foo` + inject_flag "--max-hits 40" spliced after argv[0]. expect(hoistLeadingFlags(["--max-hits", "40", "grep", "foo", "--scope", "src"])).toEqual([