diff --git a/.github/CONTRIBUTING.md b/.github/CONTRIBUTING.md index a5c2eb50e..0ff3d9777 100644 --- a/.github/CONTRIBUTING.md +++ b/.github/CONTRIBUTING.md @@ -104,7 +104,9 @@ $ pnpm test The outer loop includes the `*.outer.test.ts` integration suites, which seed the full API catalog, run native compiler comparisons, or exercise subprocess shutdown. Elixir exporter fixtures and live clang-format comparisons run here; -the medium loop keeps the pinned formatter fixtures. It also adds type +the medium loop keeps the pinned formatter fixtures. Adversarial example, +workspace-showcase, and product-copy CLI checks also run in outer because +they spawn subprocesses and temporary Git repositories. It also adds type checks and starts its own Astro development server from current source. Browser checks cover prose, an MCP table, row permalinks, API equivalents, and phone dropdown placement at 1440, 768, and 390 pixels. The @@ -115,14 +117,25 @@ medium, and outer respectively; measure the complete pnpm command when changing a loop. `test:fast` aliases medium. The runner stops an over-budget loop and fails. -The medium and outer loops first stage the integrated Ruby and Lua guides -from local Git objects. Each revision comes from `site/src/data/api/.json`; -the checkout's current branch and uncommitted files do not affect these guides. -Keep those repositories at their standard `checkout` paths in `ports.ts`, or -set `LIBTMUX_DOCS_CHECKOUT_RUBY` and `LIBTMUX_DOCS_CHECKOUT_LUA` to local clones -containing the required commits. Missing repositories or commits fail with -the required revision and environment variable. The gate does not fetch; -a fresh docs clone needs these source checkouts before `pnpm test`. +`scripts/test-tiers.json` assigns existing compiler/rendering, subprocess/Git, +and full-catalog integration suites to outer, with a reason for each group. +Publication retains exhaustive link rendering and destination/literal catalog audits. +Medium and outer exclude publication suites; the unfiltered package tests in +`test:publication` run every suite, including both manifest tiers and suffix +tiers. Native shell tree/search fixtures stay in inner; owned Git collection +fixtures run in outer. No tier changes a test's assertions. + +The medium and outer loops stage every port in `SOURCE_GUIDE_PORTS` in +[`port-documentation.ts`](../site/src/lib/port-documentation.ts), including Perl. +Native guides come from local Git objects at each integrated +`site/src/data/api/.json` revision; the checkout's current branch and +uncommitted files do not affect them. Wrapper guides use the committed guide cache. +Keep native repositories at their `checkout` paths in +[`ports.ts`](../site/src/lib/ports.ts), or set `LIBTMUX_DOCS_CHECKOUT_` +to a clone containing the required commit, such as `LIBTMUX_DOCS_CHECKOUT_PERL`. +Missing repositories or commits report the exact revision and override. +The gate never fetches. Provision every catalogued native checkout before +running these loops in a fresh docs clone; unchanged staged guides retain their timestamps. Browser checks use Playwright's installed Chromium by default. To use local Chrome: @@ -661,9 +674,41 @@ review evidence. Custom output and cache locations need their own cleanup. ## Pull requests +Apply the `no-preview` label before pushing a revision that needs CI validation +while publication awaits approval. CI still builds and audits the artifact and +runs the publisher dry run; the label holds the preview publishing job. +The guard reads the triggering event's labels. Adding the label later does +not stop an existing run. + Keep commits focused on one topic. Explain the problem, resulting behavior, and verification, including failures or skipped checks. Keep unrelated cleanup in separate work. Follow [WRITING.md](../WRITING.md#commits) for commit messages and [AGENTS.md](../AGENTS.md#repository-boundaries) for push and deployment limits. + +### Perl source-bound documentation checks + +The reusable port builder checks the selected Perl artifact after rendering. +It runs the native model/POD/source/inventory suites and the shared Node type +checks before uploading an artifact. These checks use the selected source +revision and the builder workflow's own committed docs revision. They do not +replace the development-loop timing gates or the full publication audit. + +```console +$ node site/node_modules/vitest/vitest.mjs run \ + --root packages/api-model \ + test/perl.test.ts +``` + +```console +$ node site/node_modules/vitest/vitest.mjs run \ + --root site \ + test/perl-pod-links.test.ts \ + test/perl-source-usage.test.ts \ + test/source-only-inventory.test.ts +``` + +```console +$ pnpm run --recursive type-check +``` diff --git a/.github/workflows/port-docs.yml b/.github/workflows/port-docs.yml index 88b9edabc..67255dc8e 100644 --- a/.github/workflows/port-docs.yml +++ b/.github/workflows/port-docs.yml @@ -100,7 +100,7 @@ jobs: echo "::error::GitHub Cloud job.workflow_repository/job.workflow_sha are required" >&2 exit 1 } - - uses: actions/checkout@v7 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: repository: ${{ job.workflow_repository }} ref: ${{ job.workflow_sha }} @@ -108,7 +108,7 @@ jobs: scripts site/src/lib persist-credentials: false - - uses: actions/setup-node@v7 + - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7 with: node-version: '26' - id: identity @@ -160,7 +160,7 @@ jobs: echo "::error::GitHub Cloud job.workflow_repository/job.workflow_sha are required" >&2 exit 1 } - - uses: actions/checkout@v7 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: ref: ${{ needs.identity.outputs.source-ref }} fetch-depth: 0 @@ -183,7 +183,7 @@ jobs: } echo "sha=$sha" >> "$GITHUB_OUTPUT" - - uses: actions/checkout@v7 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: repository: ${{ job.workflow_repository }} ref: ${{ job.workflow_sha }} @@ -194,7 +194,7 @@ jobs: # Record both checkouts before either native exporter produces files. - name: Check out native documentation tooling if: matrix.port == 'powershell' || matrix.port == 'julia' - uses: actions/checkout@v7 + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: ref: ${{ github.sha }} path: docs-generator @@ -234,14 +234,14 @@ jobs: echo "$product=$ref" >> "$GITHUB_OUTPUT" done - if: inputs.port == 'py' - uses: actions/checkout@v7 + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: repository: tmux-python/tmuxp ref: ${{ steps.python-products.outputs.workspace }} path: python-workspace persist-credentials: false - if: inputs.port == 'py' - uses: actions/checkout@v7 + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: repository: tmux-python/libtmux-mcp ref: ${{ steps.python-products.outputs.mcp }} @@ -251,10 +251,10 @@ jobs: # No dependency cache: this job checks out whichever ref it was asked # to publish, and a cache it saved could be restored by a later # default-branch run. - - uses: pnpm/action-setup@v6 + - uses: pnpm/action-setup@73e46992e05b19abd31f2f3c20e0e7370d762115 # v6 with: package_json_file: docs/package.json - - uses: actions/setup-node@v7 + - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7 with: node-version: '26' - run: pnpm install --frozen-lockfile @@ -316,8 +316,32 @@ jobs: if: matrix.port == 'elixir' run: python3 docs/scripts/read-elixir-toolchain.py port + - name: Read selected Haskell toolchain + id: haskell-runtime + if: matrix.port == 'haskell' + run: python3 docs/scripts/read-haskell-toolchain.py port + + - name: Read selected Erlang toolchain + id: erlang-runtime + if: matrix.port == 'erlang' + run: | + python3 - <<'PY' + import os, pathlib, re + entries = [line.split() for line in pathlib.Path('port/.tool-versions').read_text().splitlines()] + versions = {} + for tool, supported in [('erlang', '29.1.2'), ('rebar', '3.28.0')]: + selected = [entry for entry in entries if entry and entry[0] == tool] + if len(selected) != 1 or len(selected[0]) != 2 or not re.fullmatch(r'[0-9]+\.[0-9]+\.[0-9]+', selected[0][1]): + raise ValueError(f'Erlang documentation requires one exact {tool} version') + if selected[0][1] != supported: + raise ValueError(f'Unsupported Erlang documentation {tool} version: {selected[0][1]}') + versions[tool] = selected[0][1] + with open(os.environ['GITHUB_OUTPUT'], 'a') as output: + output.write(f"otp-version={versions['erlang']}\nrebar3-version={versions['rebar']}\n") + PY + - name: Install native system dependencies - if: steps.mcp.outputs.required == 'true' || matrix.port == 'cxx' + if: steps.mcp.outputs.required == 'true' || matrix.port == 'cxx' || matrix.port == 'erlang' env: PORT: ${{ matrix.port }} run: | @@ -326,6 +350,9 @@ jobs: if [[ "$PORT" == julia ]]; then packages=(build-essential pkg-config libevent-dev libncurses-dev bison) fi + if [[ "$PORT" == erlang ]]; then + packages=(build-essential) + fi if [[ "$PORT" == cxx ]]; then packages+=(clang-18 libc++-18-dev libc++abi-18-dev ninja-build) fi @@ -341,7 +368,7 @@ jobs: bin="$stage/tmux/3.7c/bin" "$bin/tmux" -V printf '%s\n' "$bin" >> "$GITHUB_PATH" - else + elif [[ "$PORT" != erlang ]]; then tmux -V fi @@ -380,13 +407,13 @@ jobs: if: matrix.port == 'ts' working-directory: port run: bun install --frozen-lockfile - - if: matrix.port == 'java' || matrix.port == 'kotlin' || matrix.port == 'scala' + - if: matrix.port == 'java' || matrix.port == 'kotlin' || matrix.port == 'scala' || matrix.port == 'clojure' uses: actions/setup-java@de7274f081f381c8f8158605e0321c36c376e2e6 # v6 with: distribution: temurin # The repository's Gradle conventions compile and run on JDK 25. java-version: '25' - - if: matrix.port == 'java' || matrix.port == 'kotlin' || matrix.port == 'scala' + - if: matrix.port == 'java' || matrix.port == 'kotlin' || matrix.port == 'scala' || matrix.port == 'clojure' uses: gradle/actions/setup-gradle@3f5f9adaf7d9fecd50b5935e54106014257a94e6 # v6.4.0 with: validate-wrappers: true @@ -483,6 +510,33 @@ jobs: install-hex: true install-rebar: false + - if: matrix.port == 'haskell' + uses: haskell-actions/setup@0f8e8c99d88aeb3fbfd523f1ef2c6f762d10d64d # v2.12.1 + with: + ghc-version: ${{ steps.haskell-runtime.outputs.ghc-version }} + cabal-version: ${{ steps.haskell-runtime.outputs.cabal-version }} + enable-stack: false + + - name: Provision selected Haskell documentation dependencies + if: matrix.port == 'haskell' + working-directory: port + run: | + set -euo pipefail + cabal update + cabal build lib:libtmux-haskell --only-dependencies --enable-documentation + + - name: Export Haskell API from the selected source + if: matrix.port == 'haskell' + env: + PORT_CHECKOUT: ${{ github.workspace }}/port + SOURCE_SHA: ${{ steps.source.outputs.sha }} + EXPORTER: ${{ github.workspace }}/docs/packages/api-model/scripts/export-haskell.py + run: | + set -euo pipefail + python3 "$EXPORTER" --checkout "$PORT_CHECKOUT" \ + --source-revision "$SOURCE_SHA" \ + --output "$PORT_CHECKOUT/.cache/docs/api.json" + # The exporter is this repository's script, run in the selected source so # the build step finds _build/docs/api.json. Mix compiles the package and # its C helper before the exporter reads the documentation chunks. @@ -497,6 +551,130 @@ jobs: mix deps.get --only prod mix run --no-start "$EXPORTER" _build/docs/api.json + - if: matrix.port == 'ocaml' + uses: ocaml/setup-ocaml@ff66428f72b64472e749b22e0ad4dded4b2ddca6 # v3.9.1 + with: + ocaml-compiler: ocaml-base-compiler.5.5.2 + opam-local-packages: port/*.opam + - name: Export OCaml API from the selected source + if: matrix.port == 'ocaml' + working-directory: port + env: + LIBTMUX_API_EXPORT: '1' + run: | + set -euo pipefail + opam install . --deps-only --with-doc --yes + opam exec -- dune build @install tools/api_export.exe + opam exec -- python3 tools/export_api.py --output _build/docs/ocaml.json + + - name: Verify OCaml producer input ownership + if: matrix.port == 'ocaml' + working-directory: docs + run: node scripts/gen-api-model-ocaml.negative.mjs --checkout "$GITHUB_WORKSPACE/port" + + - name: Read the selected Perl documentation runtime + if: matrix.port == 'perl' + id: perl-runtime + working-directory: port + run: | + python3 - <<'PYCODE' + import os, pathlib, re + rows = [line.split() for line in pathlib.Path('.tool-versions').read_text().splitlines()] + versions = [row[1] for row in rows if len(row) == 2 and row[0] == 'perl'] + if len(versions) != 1 or not re.fullmatch(r'[0-9]+\.[0-9]+\.[0-9]+', versions[0]): + raise ValueError('Perl documentation requires an exact native runtime pin') + with open(os.environ['GITHUB_OUTPUT'], 'a') as output: + output.write(f'version={versions[0]}\n') + PYCODE + - name: Install the selected Perl and documentation dependencies + if: matrix.port == 'perl' + uses: shogo82148/actions-setup-perl@eebc5c886de14ebbfcd2493d49a12007d2c30477 # v1.44.5 + with: + perl-version: ${{ steps.perl-runtime.outputs.version }} + working-directory: port + install-modules-with: cpm + install-modules-args: --top-level-phase configure,runtime,develop + enable-modules-cache: false + - name: Export the selected Perl declarations and native POD + if: matrix.port == 'perl' + working-directory: port + env: + SOURCE_SHA: ${{ steps.source.outputs.sha }} + run: | + perl scripts/export-api.pl --revision "$SOURCE_SHA" \ + --exporter-revision "$SOURCE_SHA" --output docs/_build/api.json + + - name: Install Common Lisp documentation toolchain + if: matrix.port == 'lisp' + uses: jdx/mise-action@b44d12e7d0d8ee7461bb893e1b1993500433185b # v5.2.7 + with: + version: 2026.11.3 + working_directory: port + cache: false + - name: Install locked Common Lisp dependencies + if: matrix.port == 'lisp' + working-directory: port + run: mise run setup + - name: Export Common Lisp API from the selected source + if: matrix.port == 'lisp' + working-directory: port + run: mise run docs-artifact + + - name: Install selected Erlang runtime + if: matrix.port == 'erlang' + uses: erlef/setup-beam@54075bcc5e249e4758d363f27d099f55d843f124 # v1.24.1 + with: + otp-version: ${{ steps.erlang-runtime.outputs.otp-version }} + version-type: strict + install-hex: false + install-rebar: false + + - name: Install pinned Erlang Rebar3 + if: matrix.port == 'erlang' + shell: bash + env: + GH_TOKEN: ${{ github.token }} + REBAR3_VERSION: ${{ steps.erlang-runtime.outputs.rebar3-version }} + run: | + set -euo pipefail + case "$REBAR3_VERSION" in + 3.28.0) + rebar_asset=664140441 + rebar_sha=5a28b1cca082d3b023ec0f5df9d9f9d52557036c6f2a21c1ffa11b93a984dd42 + ;; + *) echo "::error::Unsupported pinned Rebar3 version: $REBAR3_VERSION" >&2; exit 1 ;; + esac + rebar_dir=$(mktemp -d "$RUNNER_TEMP/libtmux-erlang-rebar3.XXXXXXXX") + rebar_ready=false + cleanup_rebar() { + if [[ "$rebar_ready" != true ]]; then + rm -rf -- "$rebar_dir" + fi + } + trap cleanup_rebar EXIT + gh api -H 'Accept: application/octet-stream' \ + "repos/erlang/rebar3/releases/assets/$rebar_asset" > "$rebar_dir/rebar3" + printf '%s %s\n' "$rebar_sha" "$rebar_dir/rebar3" | sha256sum --check --strict + chmod 755 "$rebar_dir/rebar3" + rebar_version=$(REBAR_GLOBAL_CONFIG_DIR="$RUNNER_TEMP/rebar3-empty-config" \ + REBAR_CONFIG="$RUNNER_TEMP/rebar3-empty.config" "$rebar_dir/rebar3" version) + printf '%s\n' "$rebar_version" + [[ "$rebar_version" == "rebar $REBAR3_VERSION "* ]] || { + echo "::error::Expected Rebar3 $REBAR3_VERSION, got $rebar_version" >&2 + exit 1 + } + printf '%s\n' "$rebar_dir" >> "$GITHUB_PATH" + rebar_ready=true + + - name: Export Erlang API from the selected source + if: matrix.port == 'erlang' + working-directory: port + env: + EXPORTER: ${{ github.workspace }}/docs/packages/api-model/scripts/export-erlang.escript + run: | + set -euo pipefail + escript "$EXPORTER" . libtmux_erlang _build/docs/api.json + - if: matrix.port == 'ruby' uses: ruby/setup-ruby@14594264cd68ce8a2345dd349bc3d138a4ef85c8 # v1.327.0 with: @@ -510,7 +688,7 @@ jobs: run: bundle install - if: inputs.port == 'py' - uses: astral-sh/setup-uv@v10.2.0 + uses: astral-sh/setup-uv@c18668ad3cf93ea998bef934396af7bb5c839dc7 # v10.2.0 with: enable-cache: false python-version: '3.14' @@ -610,6 +788,21 @@ jobs: test -s "_site/en/py/$LIBTMUX_DOCS_VERSION/api/api/index.html" fi + - name: Check Perl native model and authored POD links + if: matrix.port == 'perl' + working-directory: docs + env: + LIBTMUX_DOCS_TEST_SOURCE_ONLY: '1' + run: | + time node site/node_modules/vitest/vitest.mjs run --root packages/api-model test/perl.test.ts + time node site/node_modules/vitest/vitest.mjs run --root site \ + test/perl-pod-links.test.ts test/perl-source-usage.test.ts test/source-only-inventory.test.ts + + - name: Check shared TypeScript and Astro types for Perl + if: matrix.port == 'perl' + working-directory: docs + run: time pnpm run --recursive type-check + # The version directory itself: its contents become # //. - id: content diff --git a/.github/workflows/reusable-deploy.yml b/.github/workflows/reusable-deploy.yml index 2c32efe52..ff2006894 100644 --- a/.github/workflows/reusable-deploy.yml +++ b/.github/workflows/reusable-deploy.yml @@ -144,7 +144,7 @@ jobs: echo "::error::path-prefix '$p' must be an unrooted path using letters, digits, '.', '_', '-' and '/', without '..'" >&2 exit 1 fi - reserved=(py ruby lua powershell julia elixir ts rs go java kotlin scala csharp fsharp cxx swift manifest _shell) + reserved=(py ruby lua powershell julia erlang elixir haskell lisp ts rs go java clojure kotlin scala csharp fsharp cxx swift ocaml perl manifest _shell) for r in "${reserved[@]}"; do if [[ "$p" == "$r" ]]; then echo "::error::path-prefix '$p' is a bare reserved top-level name — qualify it, e.g. '$r/latest'" >&2 @@ -153,7 +153,7 @@ jobs: done if [[ -n "${PORT_IN:-}" ]]; then case "$PORT_IN" in - py|ruby|lua|powershell|julia|elixir|ts|rs|go|java|kotlin|scala|csharp|fsharp|cxx|swift) ;; + py|ruby|lua|powershell|julia|erlang|elixir|haskell|lisp|ts|rs|go|java|clojure|kotlin|scala|csharp|fsharp|cxx|swift|ocaml|perl) ;; *) echo "::error::unknown port '$PORT_IN'" >&2; exit 1 ;; esac if [[ ! "$VERSION_IN" =~ ^[a-zA-Z0-9][a-zA-Z0-9._-]*$ || "$VERSION_IN" == *..* ]]; then diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 91f9f8e88..36c004136 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -53,11 +53,18 @@ jobs: - name: Resolve integrated guide sources id: integrated-sources run: | - echo "ruby=$(jq -r .revision site/src/data/api/ruby.json)" >> "$GITHUB_OUTPUT" - echo "lua=$(jq -r .revision site/src/data/api/lua.json)" >> "$GITHUB_OUTPUT" - echo "powershell=$(jq -r .revision site/src/data/api/powershell.json)" >> "$GITHUB_OUTPUT" - echo "julia=$(jq -r .revision site/src/data/api/julia.json)" >> "$GITHUB_OUTPUT" - echo "elixir=$(jq -r .revision site/src/data/api/elixir.json)" >> "$GITHUB_OUTPUT" + { + echo "ruby=$(jq -r .revision site/src/data/api/ruby.json)" + echo "lua=$(jq -r .revision site/src/data/api/lua.json)" + echo "powershell=$(jq -r .revision site/src/data/api/powershell.json)" + echo "julia=$(jq -r .revision site/src/data/api/julia.json)" + echo "elixir=$(jq -r .revision site/src/data/api/elixir.json)" + echo "ocaml=$(jq -r .revision site/src/data/api/ocaml.json)" + echo "haskell=$(jq -r .revision site/src/data/api/haskell.json)" + echo "perl=$(jq -r .revision site/src/data/api/perl.json)" + } >> "$GITHUB_OUTPUT" + echo "lisp=$(jq -r .revision site/src/data/api/lisp.json)" >> "$GITHUB_OUTPUT" + echo "erlang=$(jq -r .revision site/src/data/api/erlang.json)" >> "$GITHUB_OUTPUT" - uses: actions/checkout@v7 with: @@ -89,6 +96,36 @@ jobs: ref: ${{ steps.integrated-sources.outputs.elixir }} path: .port-sources/elixir persist-credentials: false + - uses: actions/checkout@v7 + with: + repository: libtmux/libtmux-ocaml + ref: ${{ steps.integrated-sources.outputs.ocaml }} + path: .port-sources/ocaml + persist-credentials: false + - uses: actions/checkout@v7 + with: + repository: libtmux/libtmux-haskell + ref: ${{ steps.integrated-sources.outputs.haskell }} + path: .port-sources/haskell + persist-credentials: false + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 + with: + repository: libtmux/libtmux-perl + ref: ${{ steps.integrated-sources.outputs.perl }} + path: .port-sources/perl + persist-credentials: false + - uses: actions/checkout@v7 + with: + repository: libtmux/libtmux-lisp + ref: ${{ steps.integrated-sources.outputs.lisp }} + path: .port-sources/lisp + persist-credentials: false + - uses: actions/checkout@v7 + with: + repository: libtmux/libtmux-erlang + ref: ${{ steps.integrated-sources.outputs.erlang }} + path: .port-sources/erlang + persist-credentials: false # The exporter tests compile a fixture with the package's own toolchain: # the exact pair the integrated Elixir source pins, read as port-docs.yml @@ -103,7 +140,50 @@ jobs: # Exact versions only: a loose match would resolve a moving release. version-type: strict install-hex: true - install-rebar: false + + - name: Cache pinned Rebar3 + uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + with: + path: ${{ runner.temp }}/libtmux-docs-tools/rebar3/rebar3 + key: rebar3-${{ runner.os }}-${{ runner.arch }}-3.28.0-5a28b1cca082d3b023ec0f5df9d9f9d52557036c6f2a21c1ffa11b93a984dd42 + + - name: Install pinned Rebar3 + shell: bash + env: + GH_TOKEN: ${{ github.token }} + run: | + rebar_dir="$RUNNER_TEMP/libtmux-docs-tools/rebar3" + rebar_file="$rebar_dir/rebar3" + rebar_sha=5a28b1cca082d3b023ec0f5df9d9f9d52557036c6f2a21c1ffa11b93a984dd42 + rebar_download='' + rebar_install_dir='' + rebar_ready=false + cleanup_rebar() { + if [[ -n "$rebar_download" ]]; then + rm -f -- "$rebar_download" + fi + if [[ "$rebar_ready" != true && -n "$rebar_install_dir" ]]; then + rm -rf -- "$rebar_install_dir" + fi + } + trap cleanup_rebar EXIT + mkdir -p "$rebar_dir" + if [[ ! -f "$rebar_file" ]] || ! printf '%s %s\n' "$rebar_sha" "$rebar_file" | sha256sum --check --status; then + rebar_download=$(mktemp "$rebar_dir/.rebar3.XXXXXXXX") + gh api -H 'Accept: application/octet-stream' \ + repos/erlang/rebar3/releases/assets/664140441 > "$rebar_download" + printf '%s %s\n' "$rebar_sha" "$rebar_download" | sha256sum --check --strict + mv "$rebar_download" "$rebar_file" + fi + rebar_install_dir=$(mktemp -d "$RUNNER_TEMP/libtmux-docs-rebar3.XXXXXXXX") + install -m 755 "$rebar_file" "$rebar_install_dir/rebar3" + printf '%s %s\n' "$rebar_sha" "$rebar_install_dir/rebar3" | sha256sum --check --strict + rebar_version=$(REBAR_GLOBAL_CONFIG_DIR="$RUNNER_TEMP/rebar3-empty-config" \ + REBAR_CONFIG="$RUNNER_TEMP/rebar3-empty.config" "$rebar_install_dir/rebar3" version) + printf '%s\n' "$rebar_version" + [[ "$rebar_version" == 'rebar 3.28.0 '* ]] + printf '%s\n' "$rebar_install_dir" >> "$GITHUB_PATH" + rebar_ready=true - name: Stage integrated source guides env: @@ -112,6 +192,11 @@ jobs: LIBTMUX_DOCS_CHECKOUT_POWERSHELL: ${{ github.workspace }}/.port-sources/powershell LIBTMUX_DOCS_CHECKOUT_JULIA: ${{ github.workspace }}/.port-sources/julia LIBTMUX_DOCS_CHECKOUT_ELIXIR: ${{ github.workspace }}/.port-sources/elixir + LIBTMUX_DOCS_CHECKOUT_OCAML: ${{ github.workspace }}/.port-sources/ocaml + LIBTMUX_DOCS_CHECKOUT_HASKELL: ${{ github.workspace }}/.port-sources/haskell + LIBTMUX_DOCS_CHECKOUT_PERL: ${{ github.workspace }}/.port-sources/perl + LIBTMUX_DOCS_CHECKOUT_LISP: ${{ github.workspace }}/.port-sources/lisp + LIBTMUX_DOCS_CHECKOUT_ERLANG: ${{ github.workspace }}/.port-sources/erlang run: | node scripts/stage-port-docs.mjs --from-source node scripts/stage-port-docs.mjs --cached --check @@ -131,12 +216,17 @@ jobs: PREVIEW_PREFIX: pr-${{ github.event.pull_request.number }} LIBTMUX_DOCS_CHECKOUT_RUBY: ${{ github.workspace }}/.port-sources/ruby LIBTMUX_DOCS_CHECKOUT_LUA: ${{ github.workspace }}/.port-sources/lua - # PowerShell, Julia and Elixir paths stay scoped to guide staging + LIBTMUX_DOCS_CHECKOUT_OCAML: ${{ github.workspace }}/.port-sources/ocaml + LIBTMUX_DOCS_CHECKOUT_LISP: ${{ github.workspace }}/.port-sources/lisp + # PowerShell, Julia, Elixir, Haskell and Perl paths stay scoped to guide staging # above, which checks the cache used by ordinary builds. Native API # and MCP export freshness remain owning-port checks, not claims of # this root audit. Elixir's exporter tests run in the unit step; its # committed model is derived again by port-docs.yml at publication. - LIBTMUX_DOCS_SKIP_NATIVE_MODEL_PORTS: ruby,lua,powershell,julia,elixir + # OCaml's checkout also feeds source-derived usage checks. Its + # compiled API is qualified by the owning port's exporter job. + # Common Lisp's checkout stays available here so example sources are checked against the exact revision. + LIBTMUX_DOCS_SKIP_NATIVE_MODEL_PORTS: ruby,lua,powershell,julia,elixir,ocaml,haskell,perl,lisp,erlang - name: Upload audited preview if: github.event_name == 'pull_request' @@ -194,12 +284,13 @@ jobs: set -euo pipefail PATH="$PWD/bin:$PATH" bash publish-default-versions.sh - # Forks are audited but never enter an AWS environment or receive secrets. + # Forks and no-preview PRs keep the audit and dry-run without AWS publication. publish-preview: needs: [test, check-publish-preview] if: | github.event_name == 'pull_request' && - github.event.pull_request.head.repo.full_name == github.repository + github.event.pull_request.head.repo.full_name == github.repository && + !contains(github.event.pull_request.labels.*.name, 'no-preview') permissions: contents: read id-token: write diff --git a/.gitignore b/.gitignore index 49c0e2a16..f02f9da67 100644 --- a/.gitignore +++ b/.gitignore @@ -29,3 +29,4 @@ site/src/content/docs/_staged/ # comparison fails, and never removes it. Committed, they outlive the failure # they document and read as a difference that is still there. site/test/baselines/*.diff.png +site/public/badges/ diff --git a/notes/adding-a-port.md b/notes/adding-a-port.md index 62720f9a9..fd2909f48 100644 --- a/notes/adding-a-port.md +++ b/notes/adding-a-port.md @@ -54,7 +54,9 @@ products. Leave out private workspaces and development tools. Name a package page or API reference only where the host really serves one. A port installed from Git, or from its own registry, names no host page. Set an entry `planned` or `configured-unpublished` until its host serves it: only -`published` entries produce links. List a page an ecosystem suggests and its +`published` entries produce registry/API links. Set `sourceAvailable: true` +only for a verified public source directory or file; that source can be linked +while the distribution remains `configured-unpublished`. List a page an ecosystem suggests and its host does not serve as `unavailable`. Give a package that ships inside another distribution (a Go package, a @@ -84,9 +86,9 @@ and records what it found: $ node scripts/verify-destinations.mjs ``` -The verifier refuses to run, with or without `--check`, if a port in `ports.ts` -has no inventory entry with a published library: the header builds its links -from that entry, so a port without one would offer nothing. A host the +The verifier requires a published library, or a configured but unpublished +has no library with a public distribution or explicitly available source:source repository and source installation instructions. +The latter names no registry or API host until those pages exist. A host the inventory has not named before needs an identity rule in `scripts/lib/destination-verification.mjs` and its cases in `scripts/verify-destinations.negative.mjs`; without a rule its destinations are @@ -153,6 +155,111 @@ In the new worktree, on `docs-site`: notes in `notes/research/04-versioning.md` §5 for the pattern used by each existing skinned generator. +Haskell's [Haddock exporter](../packages/api-model/scripts/export-haskell.py) +builds a selected committed source archive. Its +[adapter](../packages/api-model/src/languages/haskell.ts) currently qualifies +`LibTmux.Id`, `LibTmux.Value` and `LibTmux.Version` with the port's pinned +GHC/Haddock toolchain. It preserves native signature links, opaque data +heads, constructor and record-label ownership, instance heads, and authored +export groups. The stored model retains those groups so sidebar regeneration +needs no checkout or native toolchain. Additional module and declaration +forms need native fixtures and qualification before the adapter accepts them. + +Haskell's reader guides use the routes in +[`port-documentation.ts`](../site/src/lib/port-documentation.ts). Its section +profile currently offers Guides; navigation and landing pages use that same +profile. After regenerating the API model, refresh the committed guide cache: + +```console +$ node scripts/stage-port-docs.mjs \ + --port haskell \ + --from-source \ + --refresh-cache +``` + +The command reads committed guide bytes at the API model's revision. Public +module links reach the shared reference; source fragments retain their pinned +GitHub destinations. Add the pinned source checkout to `test.yml` when a port +gains source-owned guides. Reading a guide checkout does not qualify native +export freshness; the port's publisher runs its selected native toolchain. + +Haskell command usage is read from `src/` and `internal/` at the API model's +revision by the [source reader](../scripts/lib/tmux-usage-haskell.mjs). +The pinned WASM grammar is qualified against those inputs, not all GHC2024 +syntax. The reader follows demanded same-file actions, lexical helpers and +literal argument builders. Unused lazy actions are not sends. Unsupported +command-bearing flows, including imported or higher-order helpers, CPP and +Template Haskell, fail generation; literate inputs are not qualified. +The initial argv profile accepts a separate command name and at most one +single-letter option. Combined flags and ambiguous option operands need +option-arity qualification. Custom `do` semantics, command-bearing pattern +bindings, tmux command separators and sends beyond the shared helper-depth +limit fail explicitly. Actual sends require a resolved scope and public +attribution; ambiguous or widely shared helpers need further qualification. +The current public scalar modules send no commands, so the generated usage +document has no symbol entries. New public operations need source evidence +and reader qualification before appearing on tmux command pages. + +### Erlang compiler artifact + +The Erlang exporter builds a clean source checkout with its selected Rebar3 +in a temporary build directory, then reads EEP-48 Markdown and abstract code. +Use the source project's OTP 29 and Rebar3 toolchain on `PATH`. With the +Erlang source checkout beside this docs worktree, export its core API: + +```console +$ escript packages/api-model/scripts/export-erlang.escript \ + ../libtmux-erlang \ + libtmux_erlang \ + ../libtmux-erlang/_build/docs/api.json +``` + +The version-3 artifact records the source commit, tracked input hashes, OTP +version and exporter source digest. +It retains native module, function, type and callback documentation, typespecs, +nominal types, supporting non-exported types and exported native records. +Source locations follow included headers. Opaque declarations expose their +name and parameters. Hidden modules and members stay out. Dirty sources, +missing compiler chunks and ambiguous source paths fail the export. + +The exporter parses formatted declarations to identify type and native-record +references, including their arities and UTF-16 ranges. It checks that formatting +preserves the syntax tree. OTP destinations require a compiler-known builtin or +an entry in that module's documentation; unknown types remain unresolved. +The exporter observes compiler file calls inside the temporary Rebar VM and +uses an identity parse transform to capture the actual compiler options before +OTP's deterministic build removes preprocessing context. OTP's preprocessor recovers +full paths in that same VM, preserving its library paths, environment and +working directory. The resulting forms must match the compiled +forms. This rejects external public headers even when their basenames and +declarations match tracked headers. Private OTP headers may supply implementation +records, but every documented declaration must resolve to a regular tracked +source file. Tracked source symlinks are rejected; temporary Rebar build links +back to those regular files are permitted. +An unreproducible preprocessing context fails the export. Explicit `-file` +source remapping is unsupported. Temporary compiler +context and build output are removed on completion or an export error. + +`extractErlang` maps the artifact to the shared API model. The compiler supplies +callable parameters, return types, overload clauses and quoted atom spellings. +The model retains native arities, supporting types and distinct type/callback +identities. Native `m:`, `t:` and `c:` references resolve within their module. +API signatures and their Markdown copies retain Erlang syntax and use the +compiler's reference ranges for links. The site checks the 60-column display +limit after native formatting. The `libtmux_erlang_workspace` application maps +to the workspace product; the core application maps to core. +Erlang has no shared site routes or package destinations until the port's +delivery checks are complete. The compiler fixture runs in the outer test loop; it +requires OTP 29 and Rebar3 on CI and skips locally when that toolchain is absent. + +The tmux-usage reader also requires OTP 29. It uses `erl_scan` for literal +decoding and canonical atom names, then attributes written calls by module +and arity, including static imports. Deferred fun bodies do not establish +that their enclosing function sends a command. Macro-generated declaration +heads fail rather than disappear from the scan. Variable-carried commands, +custom sigils and macro-expanded calls need reviewed usage claims. Native +scanner checks belong to the outer loop. + ### Wrapper libraries Kotlin and Scala share Java's repository and release version. F# shares @@ -254,6 +361,27 @@ bytes are a no-op and different bytes fail before upload. ## Checklist summary +After assembling the complete site, record the new port's resolved API +cross-references. The publication audit requires an entry for every port: + +```console +$ node scripts/check-xrefs.mjs _site/en --update +``` + +Review `scripts/xref-floor.json`: the new port needs a positive measured count, +and existing floors must remain intact. A selected-port build measures only +that port; use its count without replacing other ports' entries. + +Record the unresolved type-name count as well, including an explicit zero: + +```console +$ node scripts/check-type-links.mjs _site/en --update +``` + +Review `scripts/type-links-ceiling.json` and retain every other port's entry. +If the new count is positive, inspect it with `--list` before recording it; +`--force` permits a deliberate nonzero initial ceiling. + - [ ] `ports.ts`: new `Port` entry, renderer and product availability decided - [ ] `port-inventory.ts`: entries from the manifests, verified, with evidence committed - [ ] Worktree added on branch `docs-site`, `checkout`/`worktree` paths match @@ -261,6 +389,8 @@ bytes are a no-op and different bytes fail before upload. - [ ] Source-owned prose/examples stage from the selected revision - [ ] Registry, version grammar, installs, prompts, and product routes agree - [ ] Source-bound trunk, branch, PR, tag, and alias builds are checked +- [ ] Measured cross-reference floor added without lowering existing floors +- [ ] Measured type-link ceiling added without changing other ports' ceilings - [ ] CI caller and exact preview cleanup are committed on `docs-site` - [ ] Port and reusable-workflow pins use the same public full site SHA - [ ] Maintainer opens the port PR and coordinates publication and shell search diff --git a/notes/branding.md b/notes/branding.md index 7ba73e061..5cbd40552 100644 --- a/notes/branding.md +++ b/notes/branding.md @@ -25,6 +25,19 @@ the assets and CSS palette are available for that work. Its manifests use the shared site root and browser display mode, preserving preview and locale prefixes without pointing to an unpublished language route. +OCaml, Erlang, Common Lisp, Haskell, and Clojure have library, workspace, +and MCP sets with provenance in each language's `source.json`. Their manifests +use the same shared-root overrides as Elixir. The UI palettes keep neutral +surfaces and reading text, with language colors reserved for accents. These +assets are ready for the separate port integrations; they do not add routes +or claim that workspace/MCP consumers are implemented. Clojure's library +card uses the facade in the Java repository. + +Perl includes the same three product sets, with Linguist's `#0298C3` primary +and neutral reading surfaces. Its library cards describe the repository +scaffold without an API example. Provenance is recorded in +[`perl/source.json`](../site/public/brand/perl/source.json). + - [GitHub Linguist colors](https://github.com/github-linguist/linguist/blob/538da05f034fa5c83bd81df128d144e208898da3/lib/linguist/languages.yml) - The original libtmux and tmuxp geometry was supplied by the project owner. - The MCP overlay uses the symbol, without the wordmark, from the diff --git a/package.json b/package.json index 28d8c5e9e..f3321168e 100644 --- a/package.json +++ b/package.json @@ -32,5 +32,8 @@ "oxlint": "catalog:", "smol-toml": "1.9.1", "typescript": "catalog:" + }, + "dependencies": { + "badge-maker": "6.0.0" } } diff --git a/packages/api-model/package.json b/packages/api-model/package.json index 3f2d1c352..2690311b6 100644 --- a/packages/api-model/package.json +++ b/packages/api-model/package.json @@ -5,7 +5,11 @@ "type": "module", "description": "A shared API model for language ports, extracted from native documentation artifacts and source.", "exports": { - ".": "./src/index.ts" + ".": "./src/index.ts", + "./products": "./src/products.ts", + "./modules": "./src/modules.ts", + "./link": "./src/link.ts", + "./reference": "./src/reference.ts" }, "scripts": { "test": "vitest run", @@ -16,6 +20,7 @@ "mdast-util-from-markdown": "2.1.0", "mdast-util-to-markdown": "2.2.0", "smol-toml": "1.9.1", + "tree-sitter-haskell": "0.23.1", "tree-sitter-scala": "0.24.0", "tree-sitter-wasms": "catalog:", "web-tree-sitter": "catalog:" diff --git a/packages/api-model/scripts/export-clojure.clj b/packages/api-model/scripts/export-clojure.clj new file mode 100644 index 000000000..8b4ab463c --- /dev/null +++ b/packages/api-model/scripts/export-clojure.clj @@ -0,0 +1,145 @@ +(ns libtmux.docs.export-clojure + "Build-only export of compiled public namespace and var metadata." + (:require [clojure.java.io :as io] + [clojure.string :as str]) + (:import [com.fasterxml.jackson.databind ObjectMapper] + [java.nio.charset StandardCharsets] + [java.nio.file Files] + [java.security MessageDigest] + [java.util HexFormat List] + [java.util.regex Pattern])) + +(set! *warn-on-reflection* true) + +(def ^:private repo "libtmux/libtmux-java") +(def ^:private exporter-script *file*) + +(defn- sha256 [^bytes bytes] + (.formatHex (HexFormat/of) (.digest (MessageDigest/getInstance "SHA-256") bytes))) + +(defn- bytes-at [file] + (Files/readAllBytes (.toPath (io/file file)))) + +(defn- prose [text] + (when (str/blank? text) (throw (ex-info "Public Clojure declaration has no docstring" {}))) + (str/replace (str/trim text) #"\n " "\n")) + +(defn- tag-text [namespace metadata] + (when-let [tag (:tag metadata)] + (let [resolved (if (class? tag) tag + (when (symbol? tag) (ns-resolve namespace tag)))] + (if (class? resolved) (.getName ^Class resolved) (str tag))))) + +(defn- parameters [namespace arguments] + (loop [remaining (seq arguments) variadic? false result []] + (if-let [argument (first remaining)] + (if (= '& argument) + (recur (next remaining) true result) + (recur (next remaining) false + (conj result (cond-> {"name" (if (symbol? argument) (str argument) (pr-str argument))} + variadic? (assoc "variadic" "positional") + (tag-text namespace (meta argument)) (assoc "type" (tag-text namespace (meta argument))))))) + result))) + +(defn- signatures [namespace name metadata] + (when-not (seq (:arglists metadata)) + (throw (ex-info "Public Clojure var has no callable arities" {:var name}))) + (mapv (fn [arguments] + (cond-> {"raw" (pr-str (cons (symbol name) arguments)) + "params" (parameters namespace arguments)} + (tag-text namespace metadata) (assoc "returns" (tag-text namespace metadata)))) + (:arglists metadata))) + +(defn- public-functions [namespace] + (->> (ns-publics namespace) + (keep (fn [[name value]] + (let [metadata (meta value)] + (when (and (:file metadata) (not (:no-doc metadata))) + [(str name) metadata])))) + (sort-by first))) + +(defn- source-record [module file revision line] + {"file" (str (get module "path") "/src/main/clojure/" file) + "line" line "repo" repo "revision" revision}) + +(defn- namespace-line [source namespace] + (let [pattern (re-pattern (str "(?m)^\\(ns\\s+" (Pattern/quote (str namespace)) "(?:\\s|$)")) + matcher (re-matcher pattern source)] + (when-not (.find matcher) + (throw (ex-info "Cannot locate the compiled namespace in source" {:namespace namespace}))) + (inc (count (filter #{\newline} (subs source 0 (.start matcher))))))) + +(defn- namespace-symbols [root module namespace revision] + (let [file (str (-> (str namespace) (str/replace "." "/") (str/replace "-" "_")) ".clj") + path (str (get module "path") "/src/main/clojure/" file) + ^bytes source-bytes (bytes-at (io/file root path)) + resource (or (io/resource file) (throw (ex-info "Compiled Clojure source is absent" {:file file}))) + loaded-bytes (with-open [stream (io/input-stream resource)] (.readAllBytes stream)) + _ (when-not (= (sha256 source-bytes) (sha256 loaded-bytes)) + (throw (ex-info "Loaded Clojure resource differs from selected source" {:file path}))) + functions (public-functions namespace) + common {"package" (get module "package") "product" "core" "apiScope" "exported" + "namespace" (str namespace) "publicOwner" (str namespace)}] + (when-not (seq functions) (throw (ex-info "Public Clojure namespace has no functions" {:namespace namespace}))) + {:input {"path" path "sha256" (sha256 source-bytes)} + :symbols + (into [(merge common {"id" (str namespace) "publicId" (str namespace) + "qualifiedName" (str namespace) "name" (str namespace) + "kind" "module" "modifiers" [] + "signatures" [{"raw" (str "(ns " namespace ")") "params" []}] + "docstring" (prose (:doc (meta (the-ns namespace)))) + "source" (source-record module file revision + (namespace-line (String. source-bytes StandardCharsets/UTF_8) namespace))})] + (for [[name metadata] functions] + (do + (when-not (and (= file (:file metadata)) (pos-int? (:line metadata))) + (throw (ex-info "Public var source is outside its namespace" {:namespace namespace :var name}))) + (merge common {"id" (str namespace "/" name) "publicId" (str namespace "/" name) + "qualifiedName" (str namespace "/" name) "name" name "kind" "function" + "parent" (str namespace) + "modifiers" (cond-> [] (> (count (:arglists metadata)) 1) (conj "overload") + (:macro metadata) (conj "macro") + (:deprecated metadata) (conj "deprecated")) + "signatures" (signatures namespace name metadata) + "docstring" (prose (:doc metadata)) + "source" (source-record module file revision (:line metadata))}))))})) + +(defn- exporter-provenance [] + (let [directory (.getParentFile (io/file exporter-script)) + files (mapv (fn [name] + {"path" (str "packages/api-model/scripts/" name) + "sha256" (sha256 (bytes-at (io/file directory name)))}) + ["export-clojure.clj" "export-clojure.gradle"]) + digest (sha256 (.getBytes (str/join "\n" (map #(str (get % "path") ":" (get % "sha256")) files)) + StandardCharsets/UTF_8))] + {"name" "clojure-public-var-metadata" "revision" (str "sha256:" digest) + "files" files})) + +(defn- -main [root destination revision] + (when-not (re-matches #"[a-f0-9]{40}" revision) + (throw (ex-info "A selected source revision is required" {}))) + (let [mapper (ObjectMapper.) + ^List modules (.readValue mapper (System/getProperty "libtmux.docs.clojure.modules") List) + namespaces (vec (for [module modules namespace (get module "namespaces")] + [module (symbol namespace)]))] + (when (or (empty? namespaces) (not= (count namespaces) (count (set (map second namespaces))))) + (throw (ex-info "Published Clojure namespaces are absent or duplicated" {}))) + (doseq [[_ namespace] namespaces] (require namespace)) + (let [exports (mapv (fn [[module namespace]] (namespace-symbols root module namespace revision)) namespaces) + symbols (into [] (mapcat :symbols) exports) + artifact {"schema" "libtmux.clojure-api/1" "port" "clojure" "repo" repo "revision" revision + "compiler" (clojure-version) "extractor" "clojure-public-var-metadata/1" + "sources" (mapv (fn [module] + {"product" "core" "package" (get module "package") "repo" repo + "revision" revision "extractedRevision" revision "version" (get module "version")}) modules) + "nativeProvenance" {"files" (mapv :input exports) "exporter" (exporter-provenance)} + "symbols" symbols} + output (.getAbsoluteFile (io/file destination))] + (when-not (= (count symbols) (count (set (map #(get % "id") symbols)))) + (throw (ex-info "Duplicate native Clojure public identity" {}))) + (.mkdirs (.getParentFile output)) + (spit output (str (.writeValueAsString (.writerWithDefaultPrettyPrinter mapper) artifact) "\n") :encoding "UTF-8") + (binding [*out* *err*] + (println "Clojure" (clojure-version) ": exported" (count symbols) "public declarations"))))) + +(apply -main *command-line-args*) diff --git a/packages/api-model/scripts/export-clojure.gradle b/packages/api-model/scripts/export-clojure.gradle new file mode 100644 index 000000000..9bf2d7c2a --- /dev/null +++ b/packages/api-model/scripts/export-clojure.gradle @@ -0,0 +1,57 @@ +import groovy.json.JsonOutput +import org.gradle.api.tasks.JavaExec + +gradle.projectsEvaluated { + def root = gradle.rootProject + def modules = root.allprojects.findAll { it.plugins.hasPlugin('libtmux.clojure-library') } + .sort { it.path } + if (!modules) return + def scriptPath = root.findProperty('libtmuxClojureExporter') + if (!scriptPath) throw new GradleException('Set libtmuxClojureExporter to export-clojure.clj') + def manifest = modules.collect { module -> + def declared = module.tasks.named('clojureNamespaceLoad', JavaExec).get() + .systemProperties['libtmux.clojure.main-namespaces'] + if (!declared) throw new GradleException("Missing public namespaces for ${module.path}") + [path: root.relativePath(module.projectDir), artifact: module.name, + package: "${module.group}:${module.name}", version: module.version.toString(), + namespaces: declared.toString().split(',').toList()] + } + def launcher = modules.first().tasks.named('clojureNamespaceLoad', JavaExec).get().javaLauncher.get() + root.tasks.register('exportClojureApi', JavaExec) { + group = 'documentation' + description = 'Exports public Clojure metadata for the shared documentation model.' + dependsOn(modules.collect { it.tasks.named('classes') }) + javaLauncher.set(launcher) + mainClass.set('clojure.main') + classpath = root.files(modules.collect { it.sourceSets.main.runtimeClasspath }, + root.project(':libtmux-jackson').configurations.runtimeClasspath) + workingDir(root.projectDir) + def destination = root.file(root.findProperty('libtmuxClojureApiOutput') ?: 'build/docs/clojure-api.json') + def revision = root.findProperty('libtmuxDocsSourceRevision') + if (!(revision ==~ /[a-f0-9]{40}/)) throw new GradleException('Set libtmuxDocsSourceRevision to the selected Git revision') + systemProperty('libtmux.docs.clojure.modules', JsonOutput.toJson(manifest)) + jvmArgs('-Xmx384m', '-XX:ActiveProcessorCount=2', '-Dclojure.main.report=stderr') + args(scriptPath, root.projectDir.path, destination.path, revision) + inputs.files(new File(scriptPath), new File(new File(scriptPath).parentFile, 'export-clojure.gradle')) + inputs.property('sourceRevision', revision) + inputs.property('publicModules', JsonOutput.toJson(manifest)) + modules.each { inputs.dir(it.file('src/main/clojure')) } + outputs.file(destination) + def errors = new ByteArrayOutputStream() + errorOutput = errors + ignoreExitValue = true + doLast { + def diagnostic = errors.toString('UTF-8') + System.err.print(diagnostic) + def result = executionResult.get() + if (result.exitValue != 0) { + destination.delete() + result.assertNormalExitValue() + } + if (diagnostic =~ /(?m)^(Reflection warning|Performance warning|Boxed math warning)/) { + destination.delete() + throw new GradleException('Clojure API export emitted compiler warnings') + } + } + } +} diff --git a/packages/api-model/scripts/export-erlang.escript b/packages/api-model/scripts/export-erlang.escript new file mode 100755 index 000000000..0df7ac8b6 --- /dev/null +++ b/packages/api-model/scripts/export-erlang.escript @@ -0,0 +1,629 @@ +#!/usr/bin/env escript +-mode(compile). +-include_lib("kernel/include/eep48.hrl"). +-export([capture_compiler/0, parse_transform/2]). + +%% Build in the source checkout's toolchain; read compiler chunks, never source regexes. +main([Root0, AppName, Output0]) -> + Output = filename:absname(Output0), + try + ExporterDigest = exporter_digest(), + Exporter = filename:absname(escript:script_name()), + "29" = erlang:system_info(otp_release), + Root = filename:absname(Root0), + ok = file:set_cwd(Root), + Revision = trim(run("git", ["rev-parse", "HEAD"])), + clean(), + Files = inputs(), + Repository = repository(trim(run("git", ["remote", "get-url", "origin"]))), + {Properties, Public} = with_compilation(Exporter, fun(Build, Context) -> + Ebin = filename:join([Build, "default", "lib", AppName, "ebin"]), + AppFile = filename:join(Ebin, AppName ++ ".app"), + {ok, [{application, App, Props}]} = file:consult(AppFile), + true = atom_to_list(App) =:= AppName, + Modules = lists:sort(proplists:get_value(modules, Props)), + {Props, [M || Name <- Modules, + M <- [module(Name, Ebin, Files, Modules, Context)], M =/= hidden]} + end), + require(Public =/= [], "application documents no public modules"), + clean(), + require(Files =:= inputs(), "source inputs changed while compiling"), + require(Revision =:= trim(run("git", ["rev-parse", "HEAD"])), + "source revision changed while compiling"), + Artifact = #{schema => 1, port => <<"erlang">>, + source => #{repository => Repository, revision => Revision, files => Files}, + exporter => #{name => <<"Erlang EEP-48 and abstract code">>, version => 3, + otp => otp_version(), columns => 60, + source_sha256 => ExporterDigest}, + package => #{name => bin(AppName), version => bin(proplists:get_value(vsn, Properties))}, + modules => Public}, + ok = filelib:ensure_dir(Output), + ok = file:write_file(Output, [json:encode(Artifact), $\n]) + catch + throw:{export_error, Message} -> + io:format(standard_error, "Erlang export: ~ts~n", [Message]), halt(1); + error:Reason -> + io:format(standard_error, "Erlang export failed: ~p~n", [Reason]), halt(1) + end; +main(_) -> + io:format(standard_error, "usage: export-erlang.escript SOURCE_ROOT APP OUTPUT.json~n", []), + halt(1). + +module(Name, Ebin, Files, ProjectModules, Context) -> + Beam = filename:join(Ebin, atom_to_list(Name) ++ ".beam"), + case beam_lib:chunks(Beam, [abstract_code, "Docs"]) of + {ok, {Name, [{abstract_code, {raw_abstract_v1, Forms}}, {"Docs", DocsBin}]}} -> + case binary_to_term(DocsBin) of + #docs_v1{beam_language = erlang, format = <<"text/markdown">>, + module_doc = hidden} -> hidden; + #docs_v1{beam_language = erlang, format = <<"text/markdown">>, + module_doc = Doc, metadata = Meta, docs = Entries} -> + {File, Located} = source_forms(Name, Forms, Files, Context), + Exports = lists:append([Fs || {attribute, _, export, Fs} <- Forms]), + Types = lists:append([Ts || {attribute, _, export_type, Ts} <- Forms]), + Records = lists:append([Rs || {attribute, _, export_record, Rs} <- Forms]), + Scope = #{owner => Name, modules => ProjectModules, files => Files, + otp_types => otp_types(Forms, ProjectModules)}, + Members = [member(E, Located, Types, Scope) || E <- lists:sort(Entries), + public(E, Exports)], + #{name => bin(Name), display_name => atom_text(Name), doc => documentation(Doc), + source => location(File, maps:get(source_anno, Meta, 1)), + members => Members, + records => [#{name => bin(R), display_name => atom_text(R), declaration => pretty(F), + references => form_references(pretty(F), Scope), + source => location(source_file(RecordFile, Files), Anno)} || + {RecordFile, F = {attribute, Anno, native_record, {R, _}}} <- Located, + lists:member(R, Records)]}; + _ -> fail([bin(Name), <<": unsupported compiler documentation format">>]) + end; + _ -> fail([bin(Name), <<": cannot read compiler chunks (EEP-48 and abstract code required)">>]) + end. + +public({{Kind, Name, Arity}, _, _, Doc, _}, Exports) -> + Doc =/= hidden andalso case Kind of + function -> lists:member({Name, Arity}, Exports); + type -> true; + callback -> true + end. + +member({{Kind, Name, Arity}, _, Signatures, Doc, Meta}, Located, Types, Scope) -> + Declarations = [{File, F} || {File, F} <- Located, declaration(F, Kind, Name, Arity)], + require(Declarations =/= [], [bin(Name), <<": missing compiler declaration">>]), + Visibility = case [K || {_, {attribute, _, K, _}} <- Declarations] of + [opaque] -> opaque; + [nominal] -> nominal; + _ -> public + end, + #{kind => Kind, name => bin(Name), display_name => atom_text(Name), arity => Arity, + signatures => Signatures, doc => documentation(Doc), + specs => callable_specs(Kind, Name, Arity, Located, Declarations, Scope), + since => metadata(since, Meta), deprecated => metadata(deprecated, Meta), + visibility => Visibility, + exported => Kind =/= type orelse lists:member({Name, Arity}, Types), + source => member_location(Kind, Name, Arity, Located, Declarations, maps:get(files, Scope)), + declarations => [declaration_text(F) || {_, F} <- Declarations], + declaration_references => [declaration_references(F, Scope) || {_, F} <- Declarations]}. + +callable_specs(type, _, _, _, _, _) -> []; +callable_specs(Kind, Name, Arity, Located, Declarations, Scope) -> + Patterns = case [Args || {_, {function, _, N, A, [{clause, _, Args, _, _} | _]}} <- Located, + N =:= Name, A =:= Arity] of + [Args] -> Args; + [] -> lists:duplicate(Arity, none) + end, + Attribute = case Kind of function -> spec; callback -> callback end, + [spec_clause(Clause, Patterns, Attribute, Anno, Name, Arity, Scope) + || {_, {attribute, Anno, AttributeName, {{Name1, Arity1}, Clauses}}} <- Declarations, + AttributeName =:= Attribute, Name1 =:= Name, Arity1 =:= Arity, Clause <- Clauses]. + +spec_clause(Clause, Patterns, Attribute, Anno, Name, Arity, Scope) -> + Fun = case Clause of + {type, _, bounded_fun, [Function, _]} -> Function; + _ -> Clause + end, + {type, _, 'fun', [{type, _, product, Parameters}, Return]} = Fun, + require(length(Parameters) =:= Arity, "compiler typespec arity mismatch"), + Text = pretty({attribute, Anno, Attribute, {{Name, Arity}, [Clause]}}), + ReturnText = type_text(Return), + #{parameters => [parameter(Type, Pattern, Index, Scope) + || {Type, Pattern, Index} <- lists:zip3(Parameters, Patterns, lists:seq(1, Arity))], + returns => ReturnText, returns_references => type_references(ReturnText, Scope), + text => Text, references => form_references(Text, Scope)}. + +parameter({ann_type, _, [{var, _, Name}, Type]}, _, _, Scope) -> + typed_parameter(bin(Name), Type, Scope); +parameter(Type, Pattern, Index, Scope) -> + Name = case Pattern of + {var, _, Variable} when Variable =/= '_' -> bin(Variable); + {match, _, {var, _, Variable}, _} when Variable =/= '_' -> bin(Variable); + {match, _, _, {var, _, Variable}} when Variable =/= '_' -> bin(Variable); + _ -> <<"Argument", (integer_to_binary(Index))/binary>> + end, + typed_parameter(Name, Type, Scope). + +typed_parameter(Name, Type, Scope) -> + Text = type_text(Type), + #{name => Name, type => Text, references => type_references(Text, Scope)}. + +declaration_references({attribute, _, opaque, _}, _) -> []; +declaration_references({function, _, _, _, _}, _) -> []; +declaration_references(Form, Scope) -> form_references(pretty(Form), Scope). + +type_references(Text, Scope) -> + Prefix = <<"-type reference() :: ">>, + Offset = utf16_length(Prefix), + [R#{start := maps:get(start, R) - Offset, 'end' := maps:get('end', R) - Offset} + || R <- form_references(<>, Scope)]. + +%% Rescan the compiler's own spelling. Parser annotations distinguish types +%% from declaration names, variables and literal lookalikes without a lexer +%% maintained in another language. Browser offsets count UTF-16 code units. +form_references(Text, Scope) -> + Characters = unicode:characters_to_list(Text), + {ok, Tokens, _} = erl_scan:string(Characters, {1, 1}, [text]), + {ok, Form} = erl_parse:parse_form(Tokens), + Positions = positions(Characters, 1, 1, 0, #{}), + References = references(Form, Scope, Positions), + lists:sort(fun(A, B) -> maps:get(start, A) < maps:get(start, B) end, References). + +references({user_type, Anno, Name, Arguments}, Scope, Positions) -> + [reference(Anno, Anno, maps:get(owner, Scope), Name, length(Arguments), Scope, Positions) + | references(Arguments, Scope, Positions)]; +references({remote_type, _, [{atom, First, Module}, {atom, Last, Name}, Arguments]}, Scope, Positions) -> + [reference(First, Last, Module, Name, length(Arguments), Scope, Positions) + | references(Arguments, Scope, Positions)]; +references({type, First, record, [{tuple, _, [{atom, _, Module}, {atom, Last, Name}]} | Fields]}, Scope, Positions) -> + [record_reference(First, Last, Module, Name, Positions) | references(Fields, Scope, Positions)]; +references({type, First, record, [{atom, Last, Name} | Fields]}, Scope, Positions) -> + [record_reference(First, Last, maps:get(owner, Scope), Name, Positions) + | references(Fields, Scope, Positions)]; +references({type, Anno, Name, Arguments}, Scope, Positions) -> + Arity = case Arguments of any -> 0; _ when is_list(Arguments) -> length(Arguments) end, + Explicit = erl_anno:text(Anno) =:= unicode:characters_to_list(atom_text(Name)), + Head = case Explicit andalso erl_internal:is_type(Name, Arity) of + true -> [reference(Anno, Anno, erlang, Name, Arity, Scope, Positions)]; + false -> [] + end, + Head ++ references(Arguments, Scope, Positions); +references(Tuple, Scope, Positions) when is_tuple(Tuple) -> + references(tuple_to_list(Tuple), Scope, Positions); +references(List, Scope, Positions) when is_list(List) -> + lists:append([references(Item, Scope, Positions) || Item <- List]); +references(_, _, _) -> []. + +reference(First, Last, Module, Name, Arity, Scope, Positions) -> + Target = <<"t:", (atom_text(Module))/binary, ":", (atom_text(Name))/binary, + "/", (integer_to_binary(Arity))/binary>>, + Range = reference_range(First, Last, Target, Positions), + case lists:member(Module, maps:get(modules, Scope)) of + true -> Range; + false -> + case documented_otp_type(Module, Name, Arity, Scope) of + none -> Range; + Application -> + Href = iolist_to_binary([<<"https://www.erlang.org/doc/apps/">>, + Application, <<"/">>, uri_string:quote(bin(Module)), <<".html#t:">>, + uri_string:quote(atom_text(Name)), <<"/">>, integer_to_binary(Arity)]), + Range#{external => #{href => Href, project => <<"Erlang/OTP">>}} + end + end. + +otp_types(Forms, ProjectModules) -> + Modules = lists:usort(remote_modules(Forms)), + maps:from_list([{Module, {otp_application(Module), documented_types(Module)}} + || Module <- Modules, not lists:member(Module, ProjectModules), + otp_application(Module) =/= none]). + +documented_types(Module) -> + case code:get_doc(Module) of + {ok, #docs_v1{module_doc = Doc, docs = Entries}} when Doc =/= hidden -> + sets:from_list([{Name, Arity} || {{type, Name, Arity}, _, _, TypeDoc, _} <- Entries, + TypeDoc =/= hidden]); + _ -> sets:new() + end. + +documented_otp_type(erlang, Name, Arity, Scope) -> + case erl_internal:is_type(Name, Arity) of + true -> <<"erts">>; + false -> lookup_otp_type(erlang, Name, Arity, Scope) + end; +documented_otp_type(Module, Name, Arity, Scope) -> lookup_otp_type(Module, Name, Arity, Scope). + +lookup_otp_type(Module, Name, Arity, Scope) -> + case maps:find(Module, maps:get(otp_types, Scope)) of + {ok, {Application, Types}} -> + case sets:is_element({Name, Arity}, Types) of true -> Application; false -> none end; + error -> none + end. + +remote_modules({remote_type, _, [{atom, _, Module}, _, Arguments]}) -> + [Module | remote_modules(Arguments)]; +remote_modules(Tuple) when is_tuple(Tuple) -> remote_modules(tuple_to_list(Tuple)); +remote_modules(List) when is_list(List) -> lists:append([remote_modules(Item) || Item <- List]); +remote_modules(_) -> []. + +record_reference(First, Last, Module, Name, Positions) -> + Target = <<"#", (atom_text(Module))/binary, ":", (atom_text(Name))/binary, "{}">>, + reference_range(First, Last, Target, Positions). + +reference_range(First, Last, Target, Positions) -> + #{start => maps:get(erl_anno:location(First), Positions), + 'end' => maps:get(erl_anno:location(Last), Positions) + utf16_length(erl_anno:text(Last)), + target => Target}. + +otp_application(erlang) -> <<"erts">>; +otp_application(Module) -> + case code:which(Module) of + Beam when is_list(Beam) -> + Library = filename:split(code:lib_dir()), + Parts = filename:split(Beam), + case lists:prefix(Library, Parts) of + true -> + [Application, "ebin", _] = lists:nthtail(length(Library), Parts), + [Name | _] = string:split(Application, "-"), + bin(Name); + false -> none + end; + _ -> none + end. + +positions([], Line, Column, Offset, Acc) -> Acc#{{Line, Column} => Offset}; +positions([Character | Rest], Line, Column, Offset, Acc) -> + Next = Acc#{{Line, Column} => Offset}, + Units = case Character > 16#ffff of true -> 2; false -> 1 end, + case Character of + $\n -> positions(Rest, Line + 1, 1, Offset + Units, Next); + _ -> positions(Rest, Line, Column + 1, Offset + Units, Next) + end. + +utf16_length(Text) -> byte_size(unicode:characters_to_binary(Text, unicode, {utf16, big})) div 2. + +type_text(Type) -> + [_, Body] = binary:split(pretty({attribute, 0, type, {doc_type, Type, []}}), <<"::">>), + trim(binary:part(Body, 0, byte_size(Body) - 1)). + +atom_text(Name) -> unicode:characters_to_binary(erl_pp:expr({atom, 0, Name}, [{encoding, unicode}])). + +exporter_digest() -> + {ok, Source} = file:read_file(escript:script_name()), + binary:encode_hex(crypto:hash(sha256, Source), lowercase). + +member_location(function, Name, Arity, Located, _, Files) -> + [{File, {function, Anno, Name, Arity, _}}] = + [{F, Form} || {F, Form = {function, _, N, A, _}} <- Located, + N =:= Name, A =:= Arity], + location(source_file(File, Files), Anno); +member_location(_, _, _, _, [{File, {attribute, Anno, _, _}} | _], Files) -> + location(source_file(File, Files), Anno). + +%% EEP-48 line annotations omit filenames; -file forms retain include boundaries. +located_forms(Forms) -> + {Located, _} = lists:mapfoldl(fun + (Form = {attribute, _, file, {Path, _}}, _) -> + File = bin(Path), + {{File, Form}, File}; + (Form, File) -> {{File, Form}, File} + end, undefined, Forms), + Located. + +declaration({attribute, _, spec, {{Name, Arity}, _}}, function, Name, Arity) -> true; +declaration({attribute, _, callback, {{Name, Arity}, _}}, callback, Name, Arity) -> true; +declaration({attribute, _, K, {Name, _, Args}}, type, Name, Arity) + when K =:= type; K =:= opaque; K =:= nominal -> length(Args) =:= Arity; +declaration(_, _, _, _) -> false. + +%% An opaque declaration exposes its name and parameters, not its private body. +declaration_text({attribute, _, opaque, {Name, _, Args}}) -> + Parameters = lists:join(<<", ">>, [bin(erl_pp:expr(A)) || A <- Args]), + unicode:characters_to_binary([<<"-opaque ">>, + erl_pp:expr({atom, 0, Name}, [{encoding, unicode}]), $(, Parameters, <<").">>]); +declaration_text(Form) -> pretty(Form). + +pretty(Form) -> + State = #{next => 0, names => #{}, atoms => sets:from_list(form_atoms(Form))}, + {Printable, #{names := Names}} = qualified_records(Form, State), + Text = format_form(Printable, Names, 60), + {ok, Tokens, _} = erl_scan:string(unicode:characters_to_list(Text), {1, 1}, [text]), + {ok, Parsed} = erl_parse:parse_form(Tokens), + require(normalized_form(Form) =:= normalized_form(Parsed), + [<<"native declaration formatter changed its syntax tree: ">>, Text]), + Text. + +%% erl_pp can append punctuation beyond linewidth. Reduce its hint when the +%% rendered declaration exceeds the cap; indivisible tokens remain visible +%% to the site's final display-width check instead of being truncated. +format_form(Form, Names, Width) -> + Printed = trim(unicode:characters_to_binary(erl_pp:form(Form, [{linewidth, Width}]))), + Text = restore_record_names(Printed, Names), + Longest = lists:max([length(unicode:characters_to_list(Line)) + || Line <- binary:split(Text, <<"\n">>, [global])]), + case Longest =< 60 orelse Width =:= 1 of + true -> Text; + false -> format_form(Form, Names, max(1, Width - (Longest - 60))) + end. + +normalized_form({attribute, Anno, Kind, Body}) when Kind =:= native_record; Kind =:= nominal -> + %% map_anno does not traverse these new attribute bodies. Their annotation + %% layout matches record/type; retain the actual kind after traversal. + Traversal = case Kind of native_record -> record; nominal -> type end, + {attribute, Zero, Traversal, CleanBody} = + erl_parse:map_anno(fun(_) -> 0 end, {attribute, Anno, Traversal, Body}), + {attribute, Zero, Kind, CleanBody}; +normalized_form(Form) -> erl_parse:map_anno(fun(_) -> 0 end, Form). + +%% OTP29 erl_pp handles local record types but loses a qualified record name. +%% Format those names through private, wider atom tokens, then restore only +%% their scanner tokens. Literal lookalikes cannot be rewritten. The parser +%% round trip above checks the public declaration before it leaves this VM. +qualified_records({type, Anno, record, + [{tuple, _, [{atom, _, Module}, {atom, Last, Name}]} | Fields]}, State0) -> + {Marker, State1} = record_marker(Module, Name, State0), + {Mapped, State} = qualified_records(Fields, State1), + {{type, Anno, record, [{atom, Last, Marker} | Mapped]}, State}; +qualified_records(Tuple, State0) when is_tuple(Tuple) -> + {List, State} = qualified_records(tuple_to_list(Tuple), State0), + {list_to_tuple(List), State}; +qualified_records(List, State) when is_list(List) -> + lists:mapfoldl(fun qualified_records/2, State, List); +qualified_records(Other, State) -> {Other, State}. + +record_marker(Module, Name, #{next := Next, names := Names, atoms := Used} = State) -> + Characters = "__libtmux_record_" ++ integer_to_list(Next) ++ "_" ++ + atom_to_list(Module) ++ ":" ++ atom_to_list(Name), + require(length(Characters) =< 255, "qualified record name exceeds formatter budget"), + Marker = list_to_atom(Characters), + case sets:is_element(Marker, Used) of + true -> record_marker(Module, Name, State#{next := Next + 1}); + false -> + Label = <<(atom_text(Module))/binary, ":", (atom_text(Name))/binary>>, + {Marker, State#{next := Next + 1, names := Names#{Marker => Label}}} + end. + +restore_record_names(Text, Names) when map_size(Names) =:= 0 -> Text; +restore_record_names(Text, Names) -> + Characters = unicode:characters_to_list(Text), + {ok, Tokens, _} = erl_scan:string(Characters, {1, 1}, [text]), + Positions = positions(Characters, 1, 1, 0, #{}), + Ranges = [{maps:get(erl_anno:location(Anno), Positions), + utf16_length(erl_anno:text(Anno)), maps:get(Name, Names)} + || {atom, Anno, Name} <- Tokens, maps:is_key(Name, Names)], + Encoded = unicode:characters_to_binary(Text, unicode, {utf16, big}), + Restored = lists:foldl(fun({Start, Length, Label}, Bytes) -> + PrefixBytes = Start * 2, + NameBytes = Length * 2, + <> = Bytes, + Replacement = unicode:characters_to_binary(Label, unicode, {utf16, big}), + <> + end, Encoded, lists:reverse(lists:sort(Ranges))), + unicode:characters_to_binary(Restored, {utf16, big}, utf8). + +form_atoms(Atom) when is_atom(Atom) -> [Atom]; +form_atoms(Tuple) when is_tuple(Tuple) -> form_atoms(tuple_to_list(Tuple)); +form_atoms(List) when is_list(List) -> lists:append([form_atoms(Item) || Item <- List]); +form_atoms(_) -> []. + +documentation(none) -> null; +documentation(Doc) when is_map(Doc) -> + case maps:find(<<"en">>, Doc) of + {ok, English} when is_binary(English) -> English; + _ -> fail("compiler documentation has no English Markdown") + end. + +metadata(Key, Meta) -> + case maps:get(Key, Meta, null) of + null -> null; + Value when is_binary(Value) -> Value; + Value when is_list(Value) -> bin(Value) + end. + +location(File, Anno) -> #{file => File, line => erl_anno:line(Anno)}. + +%% Deterministic BEAMs omit paths and preprocessing options. Capture the +%% actual compiler context with an identity transform in a fresh build; +%% no project configuration or existing build directory is rewritten. +with_compilation(Exporter, Function) -> + Temporary = filename:join(case os:getenv("TMPDIR") of false -> "/tmp"; P -> P end, + "libtmux-erlang-export-" ++ integer_to_list(erlang:system_time(nanosecond))), + ok = file:make_dir(Temporary), + try + {ok, Sections} = escript:extract(Exporter, [compile_source]), + {source, Beam} = lists:keyfind(source, 1, Sections), + {ok, {Transform, _}} = beam_lib:chunks(Beam, []), + ok = file:write_file(filename:join(Temporary, atom_to_list(Transform) ++ ".beam"), Beam), + Build = filename:join(Temporary, "build"), + Flags = case os:getenv("ERL_AFLAGS") of false -> ""; Existing -> Existing end, + Options = [{parse_transform, Transform} | compile:env_compiler_options()], + Environment = [{"REBAR_BASE_DIR", Build}, + {"LIBTMUX_ERLANG_EXPORT_CONTEXT", Temporary}, + {"ERL_AFLAGS", Flags ++ " -pa " ++ lists:flatten(io_lib:format("~tp", [Temporary])) ++ + " -s " ++ atom_to_list(Transform) ++ " capture_compiler"}, + {"ERL_COMPILER_OPTIONS", lists:flatten(io_lib:format("~tp", [Options]))}], + _ = run("rebar3", ["compile"], Environment), + Function(Build, Temporary) + after + ok = file:del_dir_r(Temporary) + end. + +parse_transform(Forms, Options) -> + [Name] = [M || {attribute, _, module, M} <- Forms], + %% Trace signals may lag ordinary sends from a reused compiler worker. + %% Deliver its current file call before requesting the recorded entry. + Delivered = erlang:trace_delivered(self()), + receive {trace_delivered, _, Delivered} -> ok + after 1000 -> error(compiler_trace_not_delivered) + end, + Ref = make_ref(), + whereis(?MODULE) ! {source, self(), Ref}, + Source = receive {Ref, File} -> File + after 1000 -> error(compiler_source_entry_not_observed) + end, + true = filename:pathtype(Source) =:= absolute, + Preprocessing = preprocessing_context(Source, Options), + Output = context_file(os:getenv("LIBTMUX_ERLANG_EXPORT_CONTEXT"), Name), + ok = file:write_file(Output, term_to_binary({Source, Forms, Preprocessing})), + Forms. + +%% include_lib, environment expansion and relative includes belong to the +%% compiler VM. Recover paths there instead of replaying its ambient state +%% in the exporter. Keep failures as data; only documented modules need proof. +preprocessing_context(Source, Options) -> + try + Includes = [".", filename:dirname(Source) | [I || {i, I} <- Options]], + Macros = [{N, V} || {d, N, V} <- Options] ++ [{N, true} || {d, N} <- Options], + {ok, {Features, Reserved}} = erl_features:init_parse_state(Options, fun erl_scan:f_reserved_word/1), + EppOptions = [{includes, Includes}, {macros, Macros}, + {features, Features}, {reserved_word_fun, Reserved}, {location, {1, 1}}], + {ok, Original} = epp:parse_file(Source, + [{deterministic, lists:member(deterministic, Options)} | EppOptions]), + {ok, Located} = epp:parse_file(Source, [{deterministic, false} | EppOptions]), + Absolute = [case Form of + {attribute, Anno, file, {Path, Line}} -> + {attribute, Anno, file, {filename:absname(Path), Line}}; + _ -> Form + end || Form <- Located], + {ok, Original, Absolute} + catch + Class:Reason -> {error, {Class, Reason}} + end. + +%% Observe the compiler's actual file argument, not a basename reconstructed +%% from BEAM metadata. Tracing is confined to the temporary Rebar VM. +capture_compiler() -> + {module, compile} = code:ensure_loaded(compile), + Tracer = spawn(fun() -> compiler_entries(#{}, #{}) end), + true = register(?MODULE, Tracer), + erlang:trace_pattern({compile, file, 2}, true, [local]), + erlang:trace_pattern({compile, noenv_file, 2}, true, [local]), + erlang:trace(all, true, [call, set_on_spawn, {tracer, Tracer}]), + ok. + +compiler_entries(Sources, Pending) -> + receive + {trace, Pid, call, {compile, _, [Source, _]}} -> + case maps:take(Pid, Pending) of + {{From, Ref}, Rest} -> + From ! {Ref, Source}, compiler_entries(Sources#{Pid => Source}, Rest); + error -> compiler_entries(Sources#{Pid => Source}, Pending) + end; + {source, From, Ref} -> + case maps:find(From, Sources) of + {ok, Source} -> From ! {Ref, Source}, compiler_entries(Sources, Pending); + error -> compiler_entries(Sources, Pending#{From => {From, Ref}}) + end + end. + +context_file(Directory, Name) -> + Digest = binary:encode_hex(crypto:hash(sha256, atom_to_binary(Name)), lowercase), + filename:join(Directory, <>). + +source_forms(Name, Compiled, Files, Context) -> + Base = <<(atom_to_binary(Name))/binary, ".erl">>, + {Actual, Captured, Preprocessing} = binary_to_term(read(context_file(Context, Name))), + Source = source_file(Actual, Files), + require(source_tree(Captured) =:= source_tree(Compiled), + [Base, <<": compiler transform context differs from compiled forms">>]), + {Deterministic, Located} = case Preprocessing of + {ok, D, L} -> {D, L}; + _ -> fail([Base, <<": preprocessing context is unavailable">>]) + end, + require(not lists:any(fun + ({attribute, Anno, file, _}) -> erl_anno:generated(Anno); + (_) -> false + end, Located), [Base, <<": explicit source remapping cannot be verified">>]), + Expected = source_tree(Compiled), + require(source_tree(Deterministic) =:= Expected andalso source_tree(Located) =:= Expected, + [Base, <<": preprocessing context cannot reproduce compiled forms">>]), + {source_file(Source, Files), located_forms(Located)}. + +%% OTP consumes doc attributes before saving abstract code. File attributes +%% are the locations being recovered; every other form must still agree. +source_tree(Forms) -> + [normalized_form(F) || F <- Forms, source_form(F)]. + +source_form({attribute, _, Kind, _}) -> not lists:member(Kind, [file, doc, moduledoc]); +source_form(_) -> true. + +source_file(Path, Files) -> + Base = filename:basename(bin(Path)), + Resolved = source_path(Path), + case [P || #{path := P} <- Files, Resolved =/= unsafe, + filename:basename(P) =:= Base, source_path(P) =:= Resolved] of + [File] -> File; + _ -> fail([Base, <<": source path is missing or ambiguous">>]) + end. + +%% Rebar's isolated build links src/include back to the source checkout. +%% Follow each link before processing '..', with a bounded symlink count. +source_path(Path) -> source_path(filename:split(filename:absname(bin(Path))), [], 40). + +source_path([], Parts, _) -> filename:join(Parts); +source_path([<<".">> | Rest], Parts, Left) -> source_path(Rest, Parts, Left); +source_path([<<"..">> | Rest], Parts, Left) when length(Parts) > 1 -> + source_path(Rest, lists:droplast(Parts), Left); +source_path([<<"..">> | Rest], Parts, Left) -> source_path(Rest, Parts, Left); +source_path([Part | Rest], Parts, Left) -> + Candidate = filename:join(Parts ++ [Part]), + case file:read_link_all(Candidate) of + {ok, Link} when Left > 0 -> + Prefix = case filename:pathtype(Link) of absolute -> []; relative -> Parts end, + source_path(filename:split(bin(Link)) ++ Rest, Prefix, Left - 1); + {error, einval} -> source_path(Rest, Parts ++ [Part], Left); + _ -> unsafe + end. + +inputs() -> + Names = binary:split(run("git", ["ls-files", "-z"]), <<0>>, [global]), + [#{path => Name, sha256 => binary:encode_hex(crypto:hash(sha256, input_bytes(Name)), lowercase)} + || Name <- lists:sort(Names), Name =/= <<>>, input(Name)]. + +input(Name) -> lists:member(filename:extension(Name), [<<".erl">>, <<".hrl">>, <<".src">>]) + orelse lists:member(filename:basename(Name), + [<<"rebar.config">>, <<"rebar.config.script">>, <<"rebar.lock">>, <<".tool-versions">>]). + +input_bytes(Name) -> + require(file:read_link_all(Name) =:= {error, einval}, + [filename:basename(Name), <<": source input must be a regular file">>]), + read(Name). + +read(Name) -> {ok, Content} = file:read_file(Name), Content. +clean() -> require(trim(run("git", ["status", "--porcelain", "--untracked-files=all"])) =:= <<>>, + "checkout has uncommitted changes; no revision describes it"). + +repository(Url) -> + case re:run(Url, <<"^(?:https://github\\.com/|git@github\\.com:|ssh://git@github\\.com/)([A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+?)(?:\\.git)?$">>, + [{capture, [1], binary}]) of + {match, [Repository]} -> Repository; + _ -> fail("origin must name a GitHub repository") + end. + +otp_version() -> + File = filename:join([code:root_dir(), "releases", erlang:system_info(otp_release), "OTP_VERSION"]), + trim(read(File)). + +run(Executable, Arguments) -> + run(Executable, Arguments, []). + +run(Executable, Arguments, Environment) -> + case os:find_executable(Executable) of + false -> fail([bin(Executable), <<" is required on PATH">>]); + Path -> + Port = open_port({spawn_executable, Path}, [binary, exit_status, use_stdio, + stderr_to_stdout, {args, Arguments}, {env, Environment}]), + collect(Port, [], Executable) + end. + +collect(Port, Acc, Executable) -> + receive + {Port, {data, Data}} -> collect(Port, [Data | Acc], Executable); + {Port, {exit_status, 0}} -> iolist_to_binary(lists:reverse(Acc)); + {Port, {exit_status, Status}} -> + fail([bin(Executable), <<" failed (">>, integer_to_binary(Status), <<"): ">>, + lists:reverse(Acc)]) + end. + +require(true, _) -> ok; +require(false, Message) -> fail(Message). +fail(Message) -> throw({export_error, unicode:characters_to_binary(Message)}). +trim(Binary) -> string:trim(Binary). +bin(Atom) when is_atom(Atom) -> atom_to_binary(Atom); +bin(List) -> unicode:characters_to_binary(List). diff --git a/packages/api-model/scripts/export-haskell.py b/packages/api-model/scripts/export-haskell.py new file mode 100755 index 000000000..b3e35209a --- /dev/null +++ b/packages/api-model/scripts/export-haskell.py @@ -0,0 +1,711 @@ +#!/usr/bin/env python3 +"""Export the configured public library through pinned Haddock artifacts.""" + +from __future__ import annotations + +import argparse +import hashlib +import io +import json +import re +import shutil +import subprocess +import tarfile +import tempfile +from collections import Counter +from html.parser import HTMLParser +from pathlib import Path +from urllib.parse import unquote, urlsplit + + +class _Node: + """An inert native-document tree; parsing never loads scripts or assets.""" + + def __init__(self, tag="", attrs=(), parent=None): + self.tag = tag + self.attrs = dict(attrs) + self.parent = parent + self.children = [] + + def has(self, name): + return name in self.attrs.get("class", "").split() + + def walk(self): + yield self + for child in self.children: + if isinstance(child, _Node): + yield from child.walk() + + def elements(self): + return [child for child in self.children if isinstance(child, _Node)] + + def text(self): + if self.has("link") or self.has("selflink"): + return "" + return "".join( + child.text() if isinstance(child, _Node) else child for child in self.children + ) + + +class _Document(HTMLParser): + def __init__(self, text): + super().__init__(convert_charrefs=True) + self.root = _Node() + self.stack = [self.root] + self.feed(text) + + def handle_starttag(self, tag, attrs): + node = _Node(tag, attrs, self.stack[-1]) + self.stack[-1].children.append(node) + if tag not in { + "area", + "base", + "br", + "col", + "embed", + "hr", + "img", + "input", + "link", + "meta", + "param", + "source", + "track", + "wbr", + }: + self.stack.append(node) + + def handle_endtag(self, tag): + for index in range(len(self.stack) - 1, 0, -1): + if self.stack[index].tag == tag: + self.stack = self.stack[:index] + return + + def handle_data(self, data): + self.stack[-1].children.append(data) + + +def _one(nodes, description): + if len(nodes) != 1: + msg = f"Expected one {description}, found {len(nodes)}" + raise ValueError(msg) + return nodes[0] + + +def _compact(text): + return " ".join(text.split()) + + +def _definition(node): + return _one([item for item in node.walk() if item.has("def")], "public declaration anchor") + + +def _native_id(module, node): + anchor = _definition(node).attrs.get("id", "") + if not re.fullmatch(r"[tv]:.+", anchor): + msg = f"Unsupported Haddock public anchor: {anchor}" + raise ValueError(msg) + return f"{module}#{anchor}" + + +def extract_modules(pages, installed, exposed, locations, revision): + """Read public declarations; never infer an interface from implementation text.""" + interfaces = {item["module"].rsplit("$", 1)[-1]: item for item in installed["inst_ifaces"]} + if len(set(exposed)) != len(exposed) or set(pages) != set(exposed): + msg = "Public module inputs disagree with the configured component" + raise ValueError(msg) + for module in exposed: + if module not in interfaces or "OptHide" in interfaces[module]["options"]: + msg = f"Configured public module is absent or hidden: {module}" + raise ValueError(msg) + + documents = {module: _Document(pages[module]).root for module in exposed} + page_modules = {module.replace(".", "-") + ".html": module for module in exposed} + entries = [] + groups = {module: [] for module in exposed} + for module, document in documents.items(): + interface = _one( + [node for node in document.walk() if node.attrs.get("id") == "interface"], + "module interface", + ) + group = None + for block in interface.elements(): + if block.attrs.get("id", "").startswith("g:"): + group = {"title": _compact(block.text()), "members": []} + groups[module].append(group) + continue + if not block.has("top"): + msg = f"Unsupported direct Haddock interface block: {module}: {block.tag}" + raise ValueError(msg) + for subsection in block.walk(): + if not subsection.has("subs"): + continue + parent = subsection.parent + in_instances = False + while parent is not None and parent is not block: + in_instances = in_instances or parent.has("instances") + parent = parent.parent + if not in_instances and not any( + subsection.has(name) for name in ["constructors", "fields", "instances"] + ): + classes = subsection.attrs.get("class") + msg = f"Unsupported native declaration subsection: {module}: {classes}" + raise ValueError(msg) + header = _one( + [node for node in block.elements() if node.tag == "p" and node.has("src")], + "declaration header", + ) + identity = _native_id(module, header) + if identity.split("#", 1)[1].startswith("t:"): + if not re.match( + r"^(?:data|newtype)\s+(?!(?:family|instance)\b)", _compact(header.text()) + ): + msg = f"Unsupported native type shape: {identity}" + raise ValueError(msg) + kind = "typealias" + else: + if "::" not in header.text(): + msg = f"Unsupported incomplete native function signature: {identity}" + raise ValueError(msg) + kind = "function" + entries.append((module, identity, kind, module, header, block)) + if group: + group["members"].append(identity) + for constructors in [node for node in block.elements() if node.has("constructors")]: + for row in [node for node in constructors.walk() if node.tag == "tr"]: + entries.extend( + (module, _native_id(module, cell), "function", identity, cell, row) + for cell in row.elements() + if cell.tag == "td" and cell.has("src") + ) + for fields in [node for node in block.walk() if node.has("fields")]: + entries.extend( + (module, _native_id(module, field), "property", identity, field, field.parent) + for field in fields.walk() + if field.tag == "dfn" and field.has("src") + ) + + identities = [identity for _, identity, *_ in entries] + if len(identities) != len(set(identities)): + msg = "Duplicate namespace-aware public identity" + raise ValueError(msg) + targets = set(identities) | set(exposed) + for module in exposed: + observed = Counter( + _definition(header).text() for owner, _, _, _, header, _ in entries if owner == module + ) + expected = Counter( + name.rsplit("$", 1)[-1] for name in interfaces[module]["visible_exports"] + ) + if observed != expected: + msg = f"Native declaration and visible-export sets disagree: {module}" + raise ValueError(msg) + + def link(href, module): + parsed = urlsplit(href) + if parsed.scheme or parsed.netloc: + if parsed.scheme not in {"https", "http", "mailto"}: + msg = f"Unsupported documentation link scheme: {parsed.scheme}" + raise ValueError(msg) + return None + owner = page_modules.get(parsed.path) if parsed.path else module + target = owner if not parsed.fragment else f"{owner}#{unquote(parsed.fragment)}" + if owner is None or target not in targets: + msg = f"Documentation link has no public target: {module}: {href}" + raise ValueError(msg) + return target + + def markdown(node, module): + if isinstance(node, str): + return node + content = "".join(markdown(child, module) for child in node.children) + if node.tag == "a" and "href" in node.attrs: + target = link(node.attrs["href"], module) + return ( + f":obj:`{_compact(node.text())} <{target}>`" + if target + else f"[{_compact(node.text())}]({node.attrs['href']})" + ) + if node.tag == "code": + return content if any(item.tag == "a" for item in node.walk()) else f"`{node.text()}`" + if node.tag == "pre": + return "\n\n```haskell\n" + node.text().strip("\n") + "\n```\n\n" + if node.tag in {"p", "div", "td"}: + return content.strip() + "\n\n" + if node.tag in {"strong", "b"}: + return f"**{content}**" + if node.tag in {"em", "i"}: + return f"*{content}*" + if node.tag == "br": + return "\n" + if node.tag == "ul": + return "\n" + content + "\n" + if node.tag == "li": + return "- " + content.strip() + "\n" + if node.tag in {"h1", "h2", "h3", "h4"}: + return "\n\n### " + content + "\n\n" + if node.tag not in {"a", "span"}: + msg = f"Unsupported authored Haddock markup: {node.tag}" + raise ValueError(msg) + return content + + def signature(header, module, constructor=False): + spans = [] + pending_space = False + + def append(character, metadata): + if ( + spans + and {key: value for key, value in spans[-1].items() if key != "text"} == metadata + ): + spans[-1]["text"] += character + else: + spans.append({"text": character, **metadata}) + + def text(value, metadata): + nonlocal pending_space + for character in value: + if character.isspace(): + pending_space = True + continue + if pending_space and spans: + append(" ", {}) + pending_space = False + append(character, metadata) + + def walk(node, inherited=None): + metadata = inherited or {} + if isinstance(node, str): + text(node, metadata) + return + if node.has("link") or node.has("selflink"): + return + if node.has("def"): + metadata = {**metadata, "declaration": True} + if node.has("keyword"): + metadata = {**metadata, "keyword": True} + if node.tag == "a" and "href" in node.attrs: + href = node.attrs["href"] + target = link(href, module) + metadata = {**metadata, "href": href, **({"target": target} if target else {})} + for child in node.children: + walk(child, metadata) + + walk(header) + raw = _compact(header.text()) + if "".join(span["text"] for span in spans) != raw: + msg = f"Native signature spans disagree with their declaration: {module}: {raw}" + raise ValueError(msg) + return { + "raw": raw, + "params": [], + "nativeSpans": spans, + **({"methodKind": "constructor"} if constructor else {}), + } + + def documentation(container, module): + docs = [node for node in container.elements() if node.has("doc")] + if not docs: + return None + body = markdown(_one(docs, "authored documentation block"), module).strip() + paragraphs = body.split("\n\n", 1) + return ( + {"summary": paragraphs[0], **({"body": paragraphs[1]} if len(paragraphs) == 2 else {})} + if body + else None + ) + + def source(module, name, href=None): + result = {"file": "src/" + module.replace(".", "/") + ".hs", "revision": revision} + if href and urlsplit(href).path != f"src/{module}.html": + msg = f"Unsupported cross-module native source: {module}: {href}" + raise ValueError(msg) + anchor = unquote(urlsplit(href).fragment) if href else name + if anchor.startswith("line-"): + matches = [int(anchor[5:])] + else: + matches = locations[module].get(anchor, []) + if matches and len(set(matches)) == 1: + result["line"] = matches[0] + return result + + symbols = [] + for module, document in documents.items(): + description = _one( + [node for node in document.walk() if node.attrs.get("id") == "description"], + "module description", + ) + symbols.append( + { + "id": module, + "name": module, + "kind": "module", + "parent": None, + "modifiers": [], + "signatures": [], + "doc": documentation(description, module), + "source": source(module, ""), + "package": "libtmux-haskell", + "product": "core", + "apiScope": "exported", + } + ) + for module, identity, kind, parent, header, block in entries: + name = _definition(header).text() + symbol = { + "id": identity, + "publicId": identity, + "qualifiedName": f"{module}.{name}", + "name": name, + "namespace": module, + "kind": kind, + "parent": parent, + "modifiers": [], + "signatures": [signature(header, module, kind == "function" and parent != module)], + "doc": documentation(block, module), + "source": source( + module, + name, + next((node.attrs["href"] for node in header.walk() if node.has("link")), None), + ), + "package": "libtmux-haskell", + "product": "core", + "apiScope": "exported", + } + if kind == "typealias": + constructors = [node for node in block.elements() if node.has("constructors")] + if not constructors and _compact(header.text()).startswith(("data ", "newtype ")): + symbol["modifiers"].append("opaque") + instances = [] + for section in [node for node in block.elements() if node.has("instances")]: + for row in [node for node in section.walk() if node.tag == "tr"]: + cells = [ + node for node in row.elements() if node.tag == "td" and node.has("src") + ] + if not cells: + continue + heads = [node for node in cells[0].walk() if node.has("inst-left")] + head = _one(heads, "instance declaration head") + if not _compact(head.text()): + msg = "Empty native instance declaration" + raise ValueError(msg) + references = [] + for node in head.walk(): + if node.tag == "a" and "href" in node.attrs: + target = link(node.attrs["href"], module) + references.append( + { + "text": _compact(node.text()), + "href": node.attrs["href"], + **({"target": target} if target else {}), + } + ) + sources = [node.attrs["href"] for node in cells[0].walk() if node.has("link")] + instances.append( + { + "raw": "instance " + _compact(head.text()), + "markdown": "instance " + markdown(head, module).strip(), + "references": references, + "source": source( + module, name, _one(sources, "instance source") if sources else None + ), + "doc": documentation(row, module), + } + ) + symbol["instances"] = instances + symbols.append(symbol) + return { + "modules": [{"name": module, "groups": groups[module]} for module in exposed], + "symbols": symbols, + } + + +class _SourceLocations(HTMLParser): + """Index native source anchors without interpreting Haskell source text.""" + + def __init__(self, text): + super().__init__(convert_charrefs=True) + self.line = 1 + self.locations = {} + self.feed(text) + + def handle_starttag(self, tag, attrs): + anchor = dict(attrs).get("id", "") + if anchor.startswith("line-"): + self.line = int(anchor[5:]) + elif anchor: + self.locations.setdefault(anchor, []).append(self.line) + + +def _command(arguments, cwd): + result = subprocess.run( + arguments, cwd=cwd, capture_output=True, text=True, timeout=60, check=False + ) + if result.returncode: + msg = f"Command failed: {arguments[0]}\n{result.stdout}\n{result.stderr}" + raise RuntimeError(msg) + return result + + +def _git(checkout, *arguments): + return _command(["git", "-C", str(checkout), *arguments], checkout).stdout.strip() + + +def _sha256(data): + return hashlib.sha256(data).hexdigest() + + +def _checked_component(plan, source_root, registration): + if ( + plan.get("compiler-id") != "ghc-9.14.1" + or plan.get("os") != "linux" + or plan.get("arch") != "x86_64" + or plan.get("cabal-version") != "3.18.2.0" + or plan.get("cabal-lib-version") != "3.18.2.0" + ): + msg = "Actual Cabal build identity differs from the qualified toolchain" + raise ValueError(msg) + component = _one( + [ + item + for item in plan.get("install-plan", []) + if item.get("pkg-name") == "libtmux-haskell" and item.get("component-name") == "lib" + ], + "selected public library component", + ) + if ( + component.get("type") != "configured" + or component.get("style") != "local" + or component.get("id") != registration["id"] + or component.get("pkg-name") != registration["name"] + or component.get("pkg-version") != registration["version"] + or component.get("pkg-src", {}).get("type") != "local" + or Path(component.get("pkg-src", {}).get("path", "")).resolve() + != Path(source_root).resolve() + ): + msg = "Registered library component does not match the selected committed source" + raise ValueError(msg) + return component + + +def build_native(checkout, revision): + """Build committed source in isolation and extract its configured public API.""" + checkout = Path(checkout).resolve() + if ( + not re.fullmatch(r"[a-f0-9]{40}", revision) + or _git(checkout, "rev-parse", f"{revision}^{{commit}}") != revision + ): + msg = "Library source must name an existing full commit" + raise ValueError(msg) + tools = {} + for name in ["ghc", "ghc-pkg", "haddock", "cabal"]: + path = shutil.which(name) + if path is None: + msg = f"The qualified native documentation tool is unavailable: {name}" + raise ValueError(msg) + tools[name] = str(Path(path).absolute()) + ghc = _command([tools["ghc"], "--numeric-version"], checkout).stdout.strip() + haddock = _command([tools["haddock"], "--version"], checkout).stdout.strip() + cabal = _command([tools["cabal"], "--numeric-version"], checkout).stdout.strip() + if ( + ghc != "9.14.1" + or not re.match(r"Haddock version 2\.33\.0(?:\s|,)", haddock) + or cabal != "3.18.2.0" + ): + msg = ( + "Native export requires the qualified GHC 9.14.1/" + "Haddock 2.33.0/Cabal 3.18.2.0 toolchain" + ) + raise ValueError(msg) + if ( + _command([tools["ghc-pkg"], "--version"], checkout).stdout.strip() + != "GHC package manager version 9.14.1" + or _command([tools["haddock"], "--ghc-version"], checkout).stdout.strip() != ghc + ): + msg = "Native package and documentation tools use a different compiler" + raise ValueError(msg) + archive = subprocess.check_output(["git", "-C", str(checkout), "archive", revision]) + with tempfile.TemporaryDirectory(prefix="libtmux-haskell-export-") as directory: + source_root = Path(directory, "source") + source_root.mkdir() + with tarfile.open(fileobj=io.BytesIO(archive)) as source_archive: + source_archive.extractall(source_root, filter="data") + pins = dict( + line.split() + for line in (source_root / ".tool-versions").read_text().splitlines() + if line.strip() + ) + if pins.get("ghc") != ghc or pins.get("cabal") != cabal: + msg = "Selected library toolchain pins disagree with the exporter" + raise ValueError(msg) + build = Path(directory, "build") + _command( + [ + tools["cabal"], + "haddock", + "lib:libtmux-haskell", + "--offline", + f"--builddir={build}", + f"--with-compiler={tools['ghc']}", + f"--with-hc-pkg={tools['ghc-pkg']}", + f"--with-haddock={tools['haddock']}", + ], + source_root, + ) + interfaces = list(build.rglob("libtmux-haskell.haddock")) + interface = _one(interfaces, "configured library Haddock interface") + package_configs = list(build.rglob("libtmux-haskell-*-inplace.conf")) + package_config = _one(package_configs, "configured library package registration") + + def field(name): + return _command( + [ + tools["ghc-pkg"], + "--package-db", + str(package_config.parent), + "field", + "libtmux-haskell", + name, + "--simple-output", + ], + source_root, + ).stdout.strip() + + registration = {name: field(name) for name in ["name", "version", "id"]} + plan = json.loads((build / "cache/plan.json").read_text()) + component = _checked_component(plan, source_root, registration) + if not interface.is_relative_to(Path(component["dist-dir"])): + msg = "Native interface is outside the selected library build" + raise ValueError(msg) + modules = field("exposed-modules").split() + if not modules or any( + not re.fullmatch(r"[A-Z][\w']*(?:\.[A-Z][\w']*)*", module) for module in modules + ): + msg = "Unsupported configured public module or re-export shape" + raise ValueError(msg) + shown = _command([tools["haddock"], f"--show-interface={interface}"], source_root) + if bool(shown.stdout.strip()) == bool(shown.stderr.strip()): + msg = "Expected one complete native JSON interface stream" + raise ValueError(msg) + native_json = shown.stdout if shown.stdout.strip() else shown.stderr + installed = json.loads(native_json) + if installed.get("package_info") != f"{registration['name']}-{registration['version']}": + msg = "Native interface package differs from its registered library" + raise ValueError(msg) + for item in installed["inst_ifaces"]: + if ( + item["module"].rsplit("$", 1)[-1] in modules + and item["info"].get("language") != "GHC2024" + ): + msg = "Public native interface does not use the selected GHC2024 edition" + raise ValueError(msg) + rendered = { + module: (interface.parent / (module.replace(".", "-") + ".html")).read_text() + for module in modules + } + source_pages = { + module: (interface.parent / "src" / (module + ".html")).read_text() + for module in modules + } + locations = { + module: _SourceLocations(text).locations for module, text in source_pages.items() + } + result = extract_modules(rendered, installed, modules, locations, revision) + files = [".tool-versions", "cabal.project", "libtmux-haskell.cabal"] + files.extend("src/" + module.replace(".", "/") + ".hs" for module in modules) + native_files = { + "interface.haddock": interface.read_bytes(), + "interface.json": native_json.encode(), + } + native_files.update( + {module.replace(".", "-") + ".html": text.encode() for module, text in rendered.items()} + ) + native_files.update( + {"src/" + module + ".html": text.encode() for module, text in source_pages.items()} + ) + return { + "schema": "libtmux.haskell-api/1", + "port": "haskell", + "repo": "libtmux/libtmux-haskell", + "revision": revision, + "compiler": ghc, + "haddock": "2.33.0", + "component": "lib:libtmux-haskell", + "package": { + "name": registration["name"], + "version": registration["version"], + "exposedModules": modules, + }, + "nativeProvenance": { + "files": [ + {"path": name, "sha256": _sha256((source_root / name).read_bytes())} + for name in files + ], + "exporter": { + "name": "Haddock public interface export", + "version": 1, + "build": { + "compiler": plan["compiler-id"], + "cabal": plan["cabal-version"], + "unit": registration["id"], + "platform": f"{plan['arch']}-{plan['os']}", + }, + "nativeArtifacts": [ + {"path": name, "sha256": _sha256(data)} + for name, data in sorted(native_files.items()) + ], + "interfaceStream": "stdout" if shown.stdout.strip() else "stderr", + }, + }, + **result, + } + + +def _exporter_identity(): + script = Path(__file__).resolve() + root = Path(_git(script.parent, "rev-parse", "--show-toplevel")) + relative = script.relative_to(root).as_posix() + revision = _git(root, "log", "-1", "--format=%H", "--", relative) + if not re.fullmatch(r"[a-f0-9]{40}", revision): + msg = "Commit the reviewed exporter before producing a qualified artifact" + raise ValueError(msg) + committed = subprocess.check_output(["git", "-C", str(root), "show", f"{revision}:{relative}"]) + if committed != script.read_bytes(): + msg = "Exporter bytes differ from their committed revision" + raise ValueError(msg) + return { + "repository": "libtmux/docs", + "revision": revision, + "path": relative, + "sha256": _sha256(committed), + } + + +def main(): + """Write a source-bound native artifact without changing either repository.""" + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--checkout", type=Path, required=True) + parser.add_argument("--source-revision", required=True) + parser.add_argument("--output", type=Path, required=True) + arguments = parser.parse_args() + exporter = _exporter_identity() + artifact = build_native(arguments.checkout, arguments.source_revision) + artifact["nativeProvenance"]["exporter"].update(exporter) + arguments.output.parent.mkdir(parents=True, exist_ok=True) + arguments.output.write_text( + json.dumps(artifact, indent=2, sort_keys=True, ensure_ascii=False) + "\n" + ) + print( + json.dumps( + { + "port": "haskell", + "revision": artifact["revision"], + "exporterRevision": exporter["revision"], + "symbols": len(artifact["symbols"]), + } + ) + ) + + +if __name__ == "__main__": + main() diff --git a/packages/api-model/src/builtins.ts b/packages/api-model/src/builtins.ts index 246d01d17..edec46bd9 100644 --- a/packages/api-model/src/builtins.ts +++ b/packages/api-model/src/builtins.ts @@ -153,6 +153,23 @@ const ELIXIR_BUILTIN_TYPES = [ ] export const BUILTINS: Record> = { + erlang: { + 'erl_error:format_exception/3': 'https://www.erlang.org/doc/apps/stdlib/erl_error.html#format_exception/3', + }, + ocaml: { + Iarray: 'https://ocaml.org/manual/5.5/api/Iarray.html', + 'Iarray.t': 'https://ocaml.org/manual/5.5/api/Iarray.html#TYPEt', + List: 'https://ocaml.org/manual/5.5/api/List.html', + Seq: 'https://ocaml.org/manual/5.5/api/Seq.html', + 'Seq.t': 'https://ocaml.org/manual/5.5/api/Seq.html#TYPEt', + 'Seq.filter': 'https://ocaml.org/manual/5.5/api/Seq.html#VALfilter', + Unix: 'https://ocaml.org/manual/5.5/api/Unix.html', + }, + haskell: { + IO: 'https://hackage-content.haskell.org/package/base-4.22.0.0/docs/System-IO.html#t:IO', + Either: 'https://hackage-content.haskell.org/package/base-4.22.0.0/docs/Data-Either.html#t:Either', + Integer: 'https://hackage-content.haskell.org/package/base-4.22.0.0/docs/Prelude.html#t:Integer', + }, elixir: { ...Object.fromEntries(ELIXIR_BASIC_TYPES.map((name) => [name, elixirDocs('typespecs.html#basic-types')])), ...Object.fromEntries(ELIXIR_BUILTIN_TYPES.map((name) => [name, elixirDocs('typespecs.html#built-in-types')])), @@ -487,6 +504,11 @@ export const BUILTINS: Record> = { byte: 'https://docs.oracle.com/javase/specs/jls/se21/html/jls-4.html#jls-4.2.1', void: 'https://docs.oracle.com/javase/specs/jls/se21/html/jls-8.html#jls-8.4.5', }, + clojure: { + // The runtime declaration identifies the Java class; core.async names the library. + ExceptionInfo: 'https://github.com/clojure/clojure/blob/clojure-1.12.6/src/jvm/clojure/lang/ExceptionInfo.java', + 'core.async': 'https://github.com/clojure/core.async', + }, // Lua's eight value types share one section of the manual; `integer` is // the subtype 5.3 added and LuaLS spells separately. `any` is a LuaLS // annotation type, with no counterpart in the language. LuaLS's `unknown` @@ -518,7 +540,7 @@ export const CURATED_BEFORE_INVENTORY: ReadonlySet = new Set(['kotlin', * "the Java ones" is about the project's wrappers of the Java API and not a switch to Java: its `Vector` is Scala's. * A sentence that names a language the port does not reach (a Python page on Rust's `Vec`) still decides the name. */ -export const PLATFORM_REACH: Readonly> = { kotlin: ['java'], scala: ['java'] } +export const PLATFORM_REACH: Readonly> = { kotlin: ['java'], scala: ['java'], clojure: ['java'] } /** * Names the JDK's inventory holds that Kotlin and Scala prose means another library's by. A Scala sentence's "an Ox diff --git a/packages/api-model/src/concepts.ts b/packages/api-model/src/concepts.ts index f5b23c9ac..9faf18f01 100644 --- a/packages/api-model/src/concepts.ts +++ b/packages/api-model/src/concepts.ts @@ -45,6 +45,7 @@ export const CONCEPTS: Record = { swift: 'WorkspaceBuilder.build(_:on:)', powershell: 'LibTmux.Workspace\\Invoke-TmuxWorkspace', julia: 'LibTmuxWorkspace.apply', + lisp: 'libtmux.workspace:apply-workspace', }, notes: { powershell: 'Applies the exact reviewed `-Plan` after PowerShell confirmation. `-WhatIf` previews without applying it; application is detached.', @@ -154,6 +155,7 @@ export const CONCEPTS: Record = { csharp: 'LibTmux.Pane.SendKeysAsync', cxx: 'libtmux::Pane::send_text', swift: 'Server.sendKeys(_:to:literally:)', + lisp: 'libtmux:send-keys', }, absent: { java: 'no direct equivalent; `Pane.paste` writes a buffer instead', @@ -3823,17 +3825,311 @@ for (const [id, binding] of Object.entries(ELIXIR_CONCEPTS)) { concept.symbols.elixir = binding.symbol if (binding.note) (concept.notes ??= {}).elixir = binding.note } +// Captured Perl entities resolve locally; Server owns every explicit operation. +const PERL_CONCEPTS: Record = { + server: { symbol: 'LibTmux::Server', note: 'Construction records connection settings without tmux I/O. Optional LibTmux::Async::Server returns standard Future results for operations.' }, + session: { symbol: 'LibTmux::Session', note: 'A captured read-only entity; explicit Server operations accept its stable identity.' }, + window: { symbol: 'LibTmux::Window', note: 'Physical window identity. WindowLink owns each session/index placement.' }, + pane: { symbol: 'LibTmux::Pane', note: 'A physical pane retains its captured graph, without retaining transport.' }, + 'workspace-description': { symbol: 'LibTmux::Workspace::new', note: 'Validates and copies a libtmux.workspace/v1 JSON-compatible configuration.' }, + 'build-workspace': { symbol: 'LibTmux::Workspace::load', note: 'Loads through installed public core APIs; existing-target policy and known owned rollback effects are explicit.' }, + snapshot: { symbol: 'LibTmux::Server::snapshot', note: 'Strict acquisition observes an interval, not an atomic transaction; retained handles do not refresh.' }, + 'server-cmd': { symbol: 'LibTmux::Server::cmd', note: 'Checked literal argument vector; no shell wrapper or implicit tmux command list.' }, + 'list-sessions': { symbol: 'LibTmux::Snapshot::sessions', note: 'Reads captured membership locally, preserving order.' }, + 'list-server-windows': { symbol: 'LibTmux::Snapshot::windows', note: 'One entry per physical identity. window_links retains all session placements.' }, + 'list-server-panes': { symbol: 'LibTmux::Snapshot::panes', note: 'One entry per captured physical pane; raw listings preserve contextual rows separately.' }, + 'list-clients': { symbol: 'LibTmux::Snapshot::clients', note: 'Local captured client membership; Server::clients explicitly acquires a new graph.' }, + 'list-panes': { symbol: 'LibTmux::Window::panes', note: 'Reads this physical window’s captured panes without I/O.' }, + 'pane-window': { symbol: 'LibTmux::Pane::window', note: 'Resolves the physical window from the retained graph, without selecting a session context.' }, + 'window-session': { symbol: 'LibTmux::WindowLink::session', note: 'The session belongs to an explicit WindowLink placement; a physical Window has no arbitrary single session.' }, + 'window-link-window': { symbol: 'LibTmux::WindowLink::window' }, + 'client-session': { symbol: 'LibTmux::Client::session', note: 'Captured nullable relation; unloaded data remains an error.' }, + 'active-pane': { symbol: 'LibTmux::Window::active_pane', note: 'Local captured relation. Unknown membership cannot prove that no pane is active.' }, + 'get-session': { symbol: 'LibTmux::Snapshot::session_by_id', note: 'Captured stable-ID lookup returns an entity or undef. Use Selection::one for strict criteria/name lookup.' }, + 'get-window': { symbol: 'LibTmux::Snapshot::window_by_id', note: 'Resolves physical identity without choosing an arbitrary session placement.' }, + 'get-pane': { symbol: 'LibTmux::Snapshot::pane_by_id' }, + 'search-server-panes': { symbol: 'LibTmux::Server::query_panes', note: 'Explicit acquisition supports validated criteria or an exclusive native_filter expression. Local Selection::where performs no I/O.' }, +} +for (const [concept, method] of Object.entries({ + 'capture-pane': 'capture_pane', 'send-keys': 'send_keys', 'split-pane': 'split_pane', + 'set-pane-title': 'set_title', 'select-layout': 'select_layout', 'unlink-window': 'unlink_window', + 'new-session': 'new_session', 'new-window': 'new_window', 'kill-server': 'kill_server', + 'kill-session': 'kill_session', 'kill-window': 'kill_window', 'kill-pane': 'kill_pane', + 'rename-session': 'rename_session', 'rename-window': 'rename_window', 'select-window': 'select_window', + 'select-pane': 'select_pane', 'resize-pane': 'resize_pane', 'link-window': 'link_window', + 'move-window': 'move_window', 'detach-client': 'detach_client', 'show-buffer': 'show_buffer', + 'set-buffer': 'set_buffer', 'delete-buffer': 'delete_buffer', +})) { + PERL_CONCEPTS[concept] = { symbol: `LibTmux::Server::${method}`, + note: ['select-window', 'move-window', 'unlink-window'].includes(concept) + ? 'Requires an explicit WindowLink or session_id:index context; a physical window alone does not select a session placement.' + : 'Explicit Server operation. Captured entities remain local observations; use a new snapshot to observe changes.' } +} +for (const [concept, owner, field] of [ + ['session-id', 'Session', 'id'], ['window-id', 'Window', 'id'], ['pane-id', 'Pane', 'id'], + ['session-name', 'Session', 'name'], ['window-name', 'Window', 'name'], + ['window-index', 'WindowLink', 'index'], ['window-active', 'WindowLink', 'active'], + ['pane-index', 'Pane', 'index'], ['window-height', 'Window', 'height'], ['window-width', 'Window', 'width'], + ['pane-height', 'Pane', 'height'], ['pane-width', 'Pane', 'width'], ['pane-title', 'Pane', 'title'], + ['pane-active', 'Pane', 'active'], ['session-attached', 'Session', 'attached'], ['session-created', 'Session', 'created'], + ['session-path', 'Session', 'path'], ['window-layout', 'Window', 'layout'], + ['pane-current-command', 'Pane', 'current_command'], ['pane-current-path', 'Pane', 'current_path'], + ['pane-pid', 'Pane', 'pid'], ['pane-dead', 'Pane', 'dead'], +]) { + PERL_CONCEPTS[concept] = { symbol: `LibTmux::${owner}::${field}`, note: owner === 'WindowLink' + ? 'Captured session-relative placement data; this is not a property of the physical window.' + : concept === 'session-attached' ? 'Returns the captured attached-client count; zero means no attached client.' + : 'Schema-validated captured data; reading performs no tmux I/O.' } +} +for (const scope of ['server', 'session', 'window', 'pane']) { + for (const [verb, method] of [['', 'get_option'], ['set-', 'set_option'], ['unset-', 'unset_option']]) { + PERL_CONCEPTS[`${verb}${scope}-option`] = { symbol: `LibTmux::Server::${method}`, + note: `Pass scope => '${scope}' and the explicit target ID where applicable; inherited and global reads are deliberate options.` } + } +} +PERL_CONCEPTS['set-global-option'] = { symbol: 'LibTmux::Server::set_option', note: "Pass scope => 'session', global => true to set a session default." } +for (const scope of ['server', 'session']) { + const selection = scope === 'server' ? 'global => true' : 'an explicit session target ID' + PERL_CONCEPTS[`${scope}-hooks`] = { symbol: 'LibTmux::Server::show_hooks', note: `Use ${selection}; raw bytes preserve sparse hook indexes and tmux quoting.` } + PERL_CONCEPTS[`set-${scope}-hook`] = { symbol: 'LibTmux::Server::set_hook', note: `Use ${selection}; command is an explicit native tmux command string.` } + for (const [concept, method] of [[`set-${scope}-environment`, 'set_environment'], [`unset-${scope}-environment`, 'unset_environment'], [`${scope}-get-environment`, 'get_environment']]) { + PERL_CONCEPTS[concept] = { symbol: `LibTmux::Server::${method}`, note: scope === 'server' + ? 'Omit session for the global environment. Missing or explicitly unset values remain failures.' + : 'Pass an explicit session ID. Empty text and zero-like text remain values.' } + } +} +for (const [id, binding] of Object.entries(PERL_CONCEPTS)) { + const concept = CONCEPTS[id] + if (!concept) throw new Error(`concepts: Perl maps unknown concept ${id}`) + concept.symbols.perl = binding.symbol + if (binding.note) (concept.notes ??= {}).perl = binding.note + if (binding.symbol.startsWith('LibTmux::Server::') && !binding.symbol.endsWith('::attach_argv')) { + (concept.variants ??= {}).perl = [binding.symbol.replace('LibTmux::Server::', 'LibTmux::Async::Server::')] + } +} +const PERL_ABSENT: Record = { + 'attach-session': 'attach_argv builds caller-owned terminal arguments without performing attachment; the caller owns process and TTY lifetime.', + 'chain-commands': 'batch executes ordered independent requests, not a tmux command list in one invocation; command chaining is deferred.', + 'freeze-workspace': 'The JSON workspace distribution validates, plans and loads configurations; live-session export is outside the selected scope.', + 'list-windows': 'Traverse Session::window_links and resolve each link’s window, preserving explicit session placement and multiplicity.', + 'list-session-panes': 'Traverse the session’s window links and physical windows; choose explicitly whether repeated linked panes should repeat.', + 'active-window': 'Select the active captured WindowLink, then resolve its physical window.', + 'linked-sessions': 'Window::links returns WindowLink records; resolve each link’s session explicitly.', + 'pane-session': 'A physical pane’s window can be linked into several sessions; choose an explicit WindowLink context.', + 'pane-window-id': 'Use pane->window->id; the public pane relationship returns the physical Window rather than a separate ID reader.', + 'pane-session-id': 'Physical panes have no arbitrary session context; obtain the session ID through an explicit WindowLink.', + 'window-session-id': 'Use link->session->id; physical Window identity is separate from session placement.', + 'session-window-count': 'Count Session::window_links membership; repeated links remain distinct occurrences.', + 'window-pane-count': 'Count the Window::panes selection or use native Perl array length.', + 'server-alive': 'Explicit snapshot acquisition returns observed data or a typed failure; operational failures are not converted to false.', + 'raise-if-dead': 'Explicit acquisition already propagates typed operational failures.', + 'server-version': 'Read the acquired snapshot metadata version; the core has no standalone live version getter.', + 'config-file': 'config_file is a constructor setting; there is no public configuration-file accessor.', + 'socket-path': 'socket_path is a constructor selector; acquired snapshots record observed server scope separately.', + 'socket-name': 'socket_name is a constructor selector; no inferred name is added to captured handles.', + 'session-server': 'Captured handles retain a graph store, not a live Server or transport.', + 'window-server': 'Captured handles retain a graph store, not a live Server or transport.', + 'pane-server': 'Captured handles retain a graph store, not a live Server or transport.', + 'client-server': 'Captured handles retain a graph store, not a live Server or transport.', + 'refresh-session': 'Acquire a new snapshot; retained captured entities never refresh in place.', + 'refresh-window': 'Acquire a new snapshot; retained captured entities never refresh in place.', + 'refresh-pane': 'Acquire a new snapshot; retained captured entities never refresh in place.', +} +for (const [id, concept] of Object.entries(CONCEPTS)) { + if (!concept.symbols.perl) (concept.absent ??= {}).perl = PERL_ABSENT[id] + ?? 'No dedicated equivalent in the selected Perl surface. Explicit Server::cmd remains available for native tmux commands.' +} + +// Common Lisp keeps captured relationships on ordinary generic functions. +// FETCH-SNAPSHOT performs acquisition; SESSIONS, WINDOWS, PANES and CLIENTS +// only traverse the retained observation. +const LISP_CONCEPTS: Record = { + session: { symbol: 'libtmux:session/type', note: '`session` is an immutable captured entity. The same name also has a relation accessor with a distinct public identity.' }, + window: { symbol: 'libtmux:window/type', note: '`window` is a physical captured window. `window-link` preserves each session placement.' }, + pane: { symbol: 'libtmux:pane', note: '`pane` is an immutable captured physical pane.' }, + snapshot: { symbol: 'libtmux:fetch-snapshot', note: '`fetch-snapshot` acquires a new interval observation. Retained snapshots never refresh in place.' }, + 'list-sessions': { symbol: 'libtmux:sessions', note: '`sessions` returns a fresh vector from a captured snapshot without contacting tmux.' }, + 'list-windows': { symbol: 'libtmux:windows', note: '`windows` traverses a captured session. Repeated links preserve their physical-window multiplicity.' }, + 'list-panes': { symbol: 'libtmux:panes', note: '`panes` traverses a captured window without contacting tmux.' }, + 'list-session-panes': { symbol: 'libtmux:panes', note: '`panes` traverses captured observations; applying it to a session returns panes reachable through its retained links.' }, + 'list-server-windows': { symbol: 'libtmux:windows', note: '`windows` on a snapshot returns captured physical windows once each.' }, + 'list-server-panes': { symbol: 'libtmux:panes', note: '`panes` on a snapshot returns captured physical panes once each.' }, + 'list-clients': { symbol: 'libtmux:clients', note: '`clients` returns fresh attached-client observations from a retained snapshot.' }, +} +for (const [id, binding] of Object.entries(LISP_CONCEPTS)) { + const concept = CONCEPTS[id] + if (!concept) throw new Error(`concepts: Common Lisp maps unknown concept ${id}`) + concept.symbols.lisp = binding.symbol + if (binding.note) (concept.notes ??= {}).lisp = binding.note +} +const ERLANG_CONCEPTS: Record = { + server: { symbol: 'tmux_server', note: '`open/1` observes an existing daemon and starts an endpoint owner. Domain rows remain immutable values.' }, + session: { symbol: '#tmux_model:session{}' }, + window: { symbol: '#tmux_model:window{}', note: 'A physical window can have several session memberships. `window_link` holds the session-relative index and active flag.' }, + pane: { symbol: '#tmux_model:pane{}' }, + snapshot: { symbol: 'tmux_server:snapshot/1', note: 'Captures a new graph over an observation interval. Retained snapshots never refresh.' }, + 'server-cmd': { symbol: 'tmux_server:command/3', note: 'Executes an explicit command value with bounded output and separate outcome and cleanup evidence.' }, + 'list-sessions': { symbol: 'tmux_snapshot:sessions/1', note: 'Returns captured rows without tmux I/O.' }, + 'list-server-windows': { symbol: 'tmux_snapshot:windows/1', note: 'Returns unique captured physical windows. `window_links/1` lists session memberships.' }, + 'list-server-panes': { symbol: 'tmux_snapshot:panes/1', note: 'Returns unique captured physical panes without tmux I/O.' }, + 'list-windows': { symbol: 'tmux_snapshot:related/3', note: 'Pass `windows`, a captured session and its snapshot for a local relationship read.' }, + 'list-panes': { symbol: 'tmux_snapshot:related/3', note: 'Pass `panes`, a captured physical window and its snapshot for a local relationship read.' }, + 'capture-pane': { symbol: 'tmux_pane:capture/2' }, + 'send-keys': { symbol: 'tmux_pane:send_keys/2' }, + 'split-pane': { symbol: 'tmux_pane:split/2' }, + 'respawn-pane': { symbol: 'tmux_pane:respawn/2' }, + 'resize-pane': { symbol: 'tmux_pane:resize/2' }, + 'kill-pane': { symbol: 'tmux_pane:kill/1' }, + 'break-pane': { symbol: 'tmux_pane:break/4' }, + 'join-pane': { symbol: 'tmux_pane:join/3' }, + 'move-pane': { symbol: 'tmux_pane:move/3' }, + 'swap-pane': { symbol: 'tmux_pane:swap/3' }, + 'pipe-pane': { symbol: 'tmux_pane:pipe/3' }, + 'new-session': { symbol: 'tmux_session:create/2' }, + 'kill-session': { symbol: 'tmux_session:kill/1' }, + 'rename-session': { symbol: 'tmux_session:rename/2' }, + 'new-window': { symbol: 'tmux_window:create/2' }, + 'kill-window': { symbol: 'tmux_window:kill/1', note: 'Removes the physical window and its memberships.' }, + 'rename-window': { symbol: 'tmux_window:rename/2' }, + 'select-layout': { symbol: 'tmux_window:select_layout/2' }, + 'respawn-window': { symbol: 'tmux_window:respawn/2' }, + 'link-window': { symbol: 'tmux_window_link:link/3' }, + 'unlink-window': { symbol: 'tmux_window_link:unlink/2', note: 'Acts on one session-relative membership.' }, + 'move-window': { symbol: 'tmux_window_link:move/3' }, + 'swap-window': { symbol: 'tmux_window_link:swap/3' }, + 'select-window': { symbol: 'tmux_window_link:select/1', note: 'Selects a captured membership in its session.' }, + 'get-session': { symbol: 'tmux_session:get/2' }, + 'get-window': { symbol: 'tmux_window:get/2' }, + 'get-pane': { symbol: 'tmux_pane:get/2' }, + 'list-buffers': { symbol: 'tmux_buffer:list/1' }, + 'show-buffer': { symbol: 'tmux_buffer:show/2' }, + 'load-buffer': { symbol: 'tmux_buffer:load/3' }, + 'delete-buffer': { symbol: 'tmux_buffer:delete/2' }, + 'paste-buffer': { symbol: 'tmux_buffer:paste/3' }, + 'list-keys': { symbol: 'tmux_key:listing/1' }, + 'bind-key': { symbol: 'tmux_key:bind/3' }, + 'unbind-key': { symbol: 'tmux_key:unbind/2' }, + 'start-server': { symbol: 'tmux_server:start_owned/1', note: 'Starts a private daemon and returns an ownership token.' }, + 'kill-server': { symbol: 'tmux_server:stop_owned/1', note: 'Requires the ownership token for a library-owned daemon. Closing a borrowed endpoint preserves its daemon.' }, + 'server-version': { symbol: 'tmux_server:version/1' }, + 'source-file': { symbol: 'tmux_command:source_file/2', note: 'Builds a trusted command value. Execute it explicitly with `tmux_server:command/3`.' }, + 'wait-for': { symbol: 'tmux_command:wait_for/2', note: 'Builds a command value; construction performs no I/O.' }, +} +for (const [id, binding] of Object.entries(ERLANG_CONCEPTS)) { + const concept = CONCEPTS[id] + if (!concept) throw new Error(`concepts: Erlang maps unknown concept ${id}`) + concept.symbols.erlang = binding.symbol + if (binding.note) (concept.notes ??= {}).erlang = binding.note +} CONCEPTS['list-session-panes']!.absent!.julia = 'Traverse `windows(session)` and `panes(window)` in the captured snapshot. `panes(snapshot)` has server-wide scope.' + +const OCAML_CONCEPTS: Record = { + server: { symbol: 'Libtmux_unix.Client.t', variants: ['Libtmux_eio.Client.t'], note: 'A client is a live, generation-bound server connection. Endpoint describes a socket without connecting; closing a client releases its resources.' }, + session: { symbol: 'Libtmux.Session.t' }, + window: { symbol: 'Libtmux.Window.t', note: 'A global window can have several session placements. Window_link holds the session, index and current flag.' }, + pane: { symbol: 'Libtmux.Pane.t' }, + 'workspace-description': { symbol: 'Libtmux_workspace.Config.t' }, + 'build-workspace': { symbol: 'Libtmux_unix.Workspace.await', variants: ['Libtmux_eio.Workspace.await'], note: 'Apply a validated Plan through submit, then await its retained execution receipt. Inspect preserves partial and late outcomes.' }, + snapshot: { symbol: 'Libtmux_unix.Client.capture', variants: ['Libtmux_eio.Client.capture'], note: 'Acquires a complete immutable graph over an interval. Earlier observations remain readable without refreshing.' }, + 'list-sessions': { symbol: 'Libtmux.Snapshot.sessions', note: 'Reads an immutable array of already captured sessions without I/O.' }, + 'list-windows': { symbol: 'Libtmux.Session.windows', note: 'Reads distinct captured global windows in this session. window_links preserves individual indexed placements.' }, + 'list-panes': { symbol: 'Libtmux.Window.panes', note: 'Reads captured panes in one global window without I/O.' }, + 'list-server-windows': { symbol: 'Libtmux.Snapshot.windows', note: 'Reads captured global windows; use window_links for indexed session placements.' }, + 'list-server-panes': { symbol: 'Libtmux.Snapshot.panes' }, + 'list-clients': { symbol: 'Libtmux.Snapshot.clients', note: 'Reads captured attached-client observations, separate from transport Client.t handles.' }, + 'pane-window': { symbol: 'Libtmux.Pane.window' }, + 'window-session': { symbol: 'Libtmux.Window_link.session', note: 'The session belongs to a placement. A global Window has no single containing session.' }, + 'window-link-window': { symbol: 'Libtmux.Window_link.window' }, + 'client-session': { symbol: 'Libtmux.Client_observation.session', note: 'Returns the captured session when the attached client had one.' }, + 'get-session': { symbol: 'Libtmux.Snapshot.find_session', note: 'Exact opaque-ID lookup in an existing snapshot, without I/O or tmux target expansion.' }, + 'get-window': { symbol: 'Libtmux.Snapshot.find_window', note: 'Exact opaque-ID lookup in an existing snapshot, without I/O.' }, + 'get-pane': { symbol: 'Libtmux.Snapshot.find_pane', note: 'Exact opaque-ID lookup in an existing snapshot, without I/O.' }, + 'window-index': { symbol: 'Libtmux.Window_link.index' }, + 'window-active': { symbol: 'Libtmux.Window_link.is_current' }, +} +for (const [concept, operation] of Object.entries({ + 'capture-pane': 'capture_text', 'send-keys': 'send_keys', 'split-pane': 'split_pane', + 'respawn-pane': 'respawn_pane', 'clear-history': 'clear_history', 'set-pane-title': 'set_pane_title', + 'select-layout': 'select_layout', 'rotate-panes': 'rotate_panes', 'unlink-window': 'unlink_window_at', + 'new-session': 'create_session', 'new-window': 'create_window', 'kill-session': 'kill_session', + 'kill-window': 'kill_window', 'kill-pane': 'kill_pane', 'rename-session': 'rename_session', + 'rename-window': 'rename_window', 'select-window': 'select_window_at', 'select-pane': 'select_pane', + 'resize-pane': 'resize_pane', 'resize-window': 'resize_window', 'link-window': 'link_window', + 'move-window': 'move_window_at', 'break-pane': 'break_pane', 'move-pane': 'move_pane', + 'join-pane': 'move_pane', 'swap-pane': 'swap_panes', 'detach-client': 'request_detach_client_at', + 'refresh-client': 'refresh_client_at', 'switch-client': 'switch_client_at', + 'wait-for': 'wait_for', 'server-version': 'version', +})) OCAML_CONCEPTS[concept] = { symbol: `Libtmux_unix.Client.${operation}`, variants: [`Libtmux_eio.Client.${operation}`] } +for (const [prefix, owner, members] of [ + ['session', 'Session', ['id', 'name', 'attached']], + ['window', 'Window', ['id', 'name', 'height', 'width', 'layout']], + ['pane', 'Pane', ['id', 'index', 'height', 'width', 'title', 'active', 'current_command', 'current_path', 'pid', 'dead']], +] as const) for (const member of members) OCAML_CONCEPTS[`${prefix}-${member.replaceAll('_', '-')}`] = { symbol: `Libtmux.${owner}.${member}` } +for (const scope of ['server', 'session', 'window', 'pane']) { + for (const [suffix, operation] of Object.entries({ options: 'capture_options', option: 'read_option', hooks: 'capture_hooks' })) { + OCAML_CONCEPTS[`${scope}-${suffix}`] = { symbol: `Libtmux_unix.Client.${operation}`, variants: [`Libtmux_eio.Client.${operation}`], note: 'Pass the corresponding explicit Options scope; captured tables preserve their source and inheritance policy.' } + } + for (const [prefix, operation] of Object.entries({ 'set-': 'set_option', 'unset-': 'unset_option' })) OCAML_CONCEPTS[`${prefix}${scope}-option`] = { symbol: `Libtmux_unix.Client.${operation}`, variants: [`Libtmux_eio.Client.${operation}`] } + for (const [prefix, operation] of Object.entries({ 'set-': 'set_hook', 'unset-': 'remove_hook' })) OCAML_CONCEPTS[`${prefix}${scope}-hook`] = { symbol: `Libtmux_unix.Client.${operation}`, variants: [`Libtmux_eio.Client.${operation}`] } +} +for (const scope of ['server', 'session']) { + OCAML_CONCEPTS[`${scope}-environment`] = { symbol: 'Libtmux_unix.Client.capture_environment', variants: ['Libtmux_eio.Client.capture_environment'], note: 'Pass Environment.Global for server values or Environment.Session with a bound session target. Acquisition is explicit.' } + for (const [prefix, operation] of Object.entries({ 'set-': 'set_environment', 'unset-': 'unset_environment', 'remove-': 'remove_environment' })) OCAML_CONCEPTS[`${prefix}${scope}-environment`] = { symbol: `Libtmux_unix.Client.${operation}`, variants: [`Libtmux_eio.Client.${operation}`] } +} +for (const [id, binding] of Object.entries(OCAML_CONCEPTS)) { + const concept = CONCEPTS[id] + if (!concept) throw new Error(`concepts: OCaml maps unknown concept ${id}`) + concept.symbols.ocaml = binding.symbol + if (binding.note) (concept.notes ??= {}).ocaml = binding.note + if (binding.variants) (concept.variants ??= {}).ocaml = binding.variants +} +for (const [id, reason] of Object.entries({ + 'freeze-workspace': 'The workspace packages validate and apply descriptions; they do not export a live session as configuration.', + 'list-session-panes': 'Traverse Session.windows and Window.panes in the captured graph. Snapshot.panes has server-wide scope.', + 'pane-session': 'A pane belongs to a global window that can have several session placements. Traverse Window.links and Window_link.session.', + 'kill-server': 'Client.close releases transport resources. The public client API does not terminate a borrowed tmux daemon.', + 'server-from-env': 'Endpoint selection is explicit. Construct a named socket or socket path; the library does not infer an ambient server.', +})) (CONCEPTS[id]!.absent ??= {}).ocaml = reason +const CLOJURE_CONCEPTS: Record = { + server: { symbol: 'libtmux.core/open!', note: 'Opens a closeable Java server client for an explicit endpoint. Acquisitions return persistent maps with explicit Java references for effects.' }, + session: { symbol: 'libtmux.core/sessions!', note: 'Acquires a vector of captured session maps. The session value is a map, not a wrapper class.' }, + window: { symbol: 'libtmux.data/windows', note: 'Traverses captured window-placement maps without I/O; the window value is a map with an explicit Java reference for effects.' }, + pane: { symbol: 'libtmux.data/panes', note: 'Traverses captured pane maps without I/O. Use keyword lookup for scalar observations and the preserved :tmux/ref for effects.' }, + 'capture-pane': { symbol: 'libtmux.core/capture!' }, + 'send-keys': { symbol: 'libtmux.core/send-keys!' }, + 'split-pane': { symbol: 'libtmux.core/split-pane!' }, + 'new-session': { symbol: 'libtmux.core/new-session!' }, + 'new-window': { symbol: 'libtmux.core/new-window!' }, + 'kill-server': { symbol: 'libtmux.core/kill-server!' }, + 'list-sessions': { symbol: 'libtmux.core/sessions!', note: 'Acquires a new captured graph and returns its session maps; acquisition failure throws.' }, + 'list-windows': { symbol: 'libtmux.data/windows', note: 'Traverses one capture locally. It does not issue a list-windows command.' }, + 'list-panes': { symbol: 'libtmux.data/panes', note: 'Traverses one capture locally. It does not issue a list-panes command.' }, + 'list-server-windows': { symbol: 'libtmux.core/windows!', note: 'Acquires a new graph and returns its window placements without deduplicating linked windows.' }, + 'list-server-panes': { symbol: 'libtmux.core/panes!', note: 'Acquires a new graph and returns its pane occurrences.' }, + 'list-clients': { symbol: 'libtmux.core/clients!' }, + snapshot: { symbol: 'libtmux.core/snapshot!', note: 'Acquires a captured graph of persistent values. Retained values do not refresh after mutation or close.' }, +} +for (const [id, binding] of Object.entries(CLOJURE_CONCEPTS)) { + const concept = CONCEPTS[id] + if (!concept) throw new Error(`concepts: Clojure maps unknown concept ${id}`) + concept.symbols.clojure = binding.symbol + if (binding.note) (concept.notes ??= {}).clojure = binding.note +} for (const concept of Object.values(CONCEPTS)) { concept.absent ??= {} if (!concept.symbols.powershell) concept.absent.powershell ??= 'No source-verified PowerShell equivalent is recorded for this operation.' if (!concept.symbols.julia) concept.absent.julia ??= 'No source-verified Julia equivalent is recorded for this operation.' if (!concept.symbols.elixir) concept.absent.elixir = 'No source-verified Elixir equivalent is recorded for this operation.' + if (!concept.symbols.haskell) concept.absent.haskell = 'No public Haskell equivalent is implemented; the current modules expose scalar values and version parsing.' + if (!concept.symbols.erlang) concept.absent.erlang = 'No source-verified Erlang equivalent is recorded for this operation.' if (!concept.symbols.ruby) concept.absent.ruby = 'No source-verified Ruby equivalent is recorded for this operation.' if (!concept.symbols.lua) concept.absent.lua = 'No source-verified Lua equivalent is recorded for this operation.' if (!concept.symbols.kotlin) concept.absent.kotlin = 'No source-verified Kotlin equivalent is recorded for this operation.' if (!concept.symbols.scala) concept.absent.scala = 'No source-verified Scala equivalent is recorded for this operation.' if (!concept.symbols.fsharp) concept.absent.fsharp = 'No source-verified F# equivalent is recorded for this operation.' + if (!concept.symbols.ocaml) concept.absent.ocaml ??= 'No direct public OCaml equivalent is recorded for this operation.' + if (!concept.symbols.clojure) concept.absent.clojure = 'No source-verified Clojure equivalent is recorded for this operation.' + if (!concept.symbols.lisp) concept.absent.lisp = 'No source-verified Common Lisp equivalent is recorded for this operation.' } /** Every concept naming this symbol, including concepts sharing an overload group. */ diff --git a/site/src/lib/api-prose.ts b/packages/api-model/src/doc/prose-blocks.ts similarity index 89% rename from site/src/lib/api-prose.ts rename to packages/api-model/src/doc/prose-blocks.ts index acaeeb5b1..09476a4a3 100644 --- a/site/src/lib/api-prose.ts +++ b/packages/api-model/src/doc/prose-blocks.ts @@ -1,3 +1,15 @@ +import type { ApiSymbol } from '../model.ts' + +/** Context-scoped section IDs keep spaces, Unicode and punctuation distinct. */ +export function docSectionId(symbol: ApiSymbol, title: string): string { + const component = encodeURIComponent(title).replace(/[!'()*]/g, (character) => `%${character.charCodeAt(0).toString(16).toUpperCase()}`) + return `${symbol.publicId ?? symbol.id}.section.${component}` +} + +/** Only headings the prose renderer emits can be authored section targets. */ +export const docSectionTitles = (symbol: ApiSymbol): string[] => parseApiProse(symbol.doc?.body ?? '') + .flatMap((block) => block.kind === 'rubric' ? [block.text] : []) + export interface ProseItem { text: string children: ProseItem[] diff --git a/packages/api-model/src/doc/roles.ts b/packages/api-model/src/doc/roles.ts index 791867b29..a45540364 100644 --- a/packages/api-model/src/doc/roles.ts +++ b/packages/api-model/src/doc/roles.ts @@ -48,6 +48,10 @@ export type DocSpan = target: string /** What to show. `~` means "last segment only"; explicit titles win. */ label: string + /** Custom odoc labels are prose rather than code. */ + code?: boolean + /** An authored symbol link, rather than inline code offered for resolution. */ + explicit?: boolean } /** @@ -278,6 +282,8 @@ function labelFor(raw: string): { target: string; label: string } { */ const SYNTAX: Record> = { py: new Set(['rest', 'citation']), + // Pod::Simple exports local POD targets as roles and external targets as Markdown links. + perl: new Set(['pod', 'markdown-link']), rs: new Set(['intra-doc']), go: new Set(['go-link']), java: new Set(['jsdoc']), @@ -292,10 +298,15 @@ const SYNTAX: Record> = { cxx: new Set([]), kotlin: new Set(['kdoc', 'jsdoc']), scala: new Set(['scaladoc', 'jsdoc']), + clojure: new Set(['cljdoc', 'markdown-link']), julia: new Set(['markdown-link', 'documenter']), // ExDoc links a Markdown destination written as code: [the server](`LibTmux.Server`). elixir: new Set(['markdown-link', 'exdoc']), + erlang: new Set(['markdown-link', 'exdoc']), powershell: new Set(['markdown-link']), + ocaml: new Set(['odoc', 'markdown-link']), + // Haddock's producer resolves public links into roles and preserves external Markdown links. + haskell: new Set(['rest-role', 'markdown-link', 'literal-code']), } /** @@ -352,6 +363,21 @@ function tokenizeRun(text: string, lang?: string): DocSpan[] { type Hit = { start: number; end: number; span: DocSpan } const hits: Hit[] = [] + if (syntax.has('odoc')) { + // The native exporter preserves references and converts odoc code and URL links to Markdown. + for (const match of text.matchAll(/\{\{!([^{}\s]+)\}([^{}]*)\}|\{!([^{}\s]+)\}/g)) { + let target = match[1] ?? match[3]! + const legacy = /^(type|val|module|module-type|class|class-type|exception|constructor|field):(.+)$/.exec(target) + const typed = /(?:^|\.)(module-type|class-type|type|val|value|module|class|exception|exn|constructor|const|field|recfield)-([^.]+)$/.exec(target) + const kind = legacy?.[1] ?? typed?.[1] + if (legacy) target = legacy[2]! + else if (typed) target = target.slice(0, typed.index) + (typed[0].startsWith('.') ? '.' : '') + typed[2]! + const label = match[1] ? match[2]! : target.replace(/(?:^|(?<=\.))(?:module-type|class-type|type|val|value|module|class|exception|exn|constructor|const|field|recfield)-/g, '') + hits.push({ start: match.index, end: match.index + match[0].length, + span: { kind: 'ref', role: `odoc:${kind ?? 'any'}`, target, label, ...(match[1] ? { code: false } : {}) } }) + } + } + if (syntax.has('documenter')) { // Documenter's named @ref destination contains spaces that Markdown URLs cannot. for (const match of text.matchAll(/\[(?:(`+)([^\n]*?)\1|([^\]\n]+))\]\(@ref\s+([^\n)]+)\)/g)) { @@ -395,22 +421,24 @@ function tokenizeRun(text: string, lang?: string): DocSpan[] { hits.push({ start: match.index, end: match.index + match[0].length, span: { kind: 'kbd', text: match[1] } }) } - if (syntax.has('kdoc') || syntax.has('scaladoc')) { + if (syntax.has('kdoc') || syntax.has('scaladoc') || syntax.has('cljdoc')) { const prose = text.split('') for (const pattern of [LITERAL_RE, BACKTICK_RE]) { for (const match of text.matchAll(pattern)) { for (let i = match.index; i < match.index + match[0].length; i++) prose[i] = ' ' } } - const links = syntax.has('scaladoc') + const wiki = syntax.has('scaladoc') || syntax.has('cljdoc') + const links = wiki ? /\[\[([^\]\s]+)(?:\s+([^\]]+))?\]\]/g : /(?=&$%/-]+$/ : /^[\w.#]+$/).test(target)) continue hits.push({ start: match.index, end: match.index + match[0].length, - span: { kind: 'ref', role: 'any', target, label } }) + span: { kind: 'ref', role: 'any', target, label, + ...(syntax.has('cljdoc') ? { explicit: true } : {}) } }) } } @@ -514,7 +542,7 @@ function tokenizeRun(text: string, lang?: string): DocSpan[] { } } - if (syntax.has('rest')) for (const m of text.matchAll(ROLE_RE)) { + if (syntax.has('rest') || syntax.has('rest-role') || syntax.has('pod')) for (const m of text.matchAll(ROLE_RE)) { const role = m[1].replace(/^py:/, '') const { target, label } = labelFor(m[2]) if (!ROLES.has(m[1])) { @@ -599,11 +627,13 @@ function tokenizeRun(text: string, lang?: string): DocSpan[] { } } else { for (const code of markdownCode(text, masked.join(''))) { - const span: DocSpan = code.ticks === 1 + const span: DocSpan = syntax.has('odoc') || syntax.has('literal-code') || syntax.has('pod') ? { kind: 'code', text: code.text } + : code.ticks === 1 ? { kind: 'ref', role: 'any', target: syntax.has('intra-doc') && RUST_CODE_PATH_RE.test(code.text) ? rustTarget(code.text) : code.text, label: code.text } : syntax.has('docc') && code.ticks === 2 ? { kind: 'ref', role: 'any', target: doccTarget(code.text), label: code.text } : { kind: 'code', text: code.text } + if (lang === 'erlang' && span.kind === 'ref') span.label = span.label.replace(/^[mtc]:/, '') hits.push({ start: code.start, end: code.end, span }) } } diff --git a/packages/api-model/src/index.ts b/packages/api-model/src/index.ts index f85d23d4f..856684be4 100644 --- a/packages/api-model/src/index.ts +++ b/packages/api-model/src/index.ts @@ -1,4 +1,6 @@ +export { extractPerlArtifact } from './languages/perl.ts' export * from './model.ts' +export * from './doc/prose-blocks.ts' export { sourceUrl, symbolsForProduct } from './products.ts' export { loadLanguage, parserFor, type GrammarName } from './parser.ts' export { extractPython } from './languages/python.ts' @@ -8,7 +10,9 @@ export { extractLua } from './languages/lua.ts' export { extractPowerShell } from './languages/powershell.ts' export { extractJulia } from './languages/julia.ts' export { ELIXIR_DECLARATION_COLUMNS, extractElixir } from './languages/elixir.ts' +export { extractErlang } from './languages/erlang.ts' export { extractFSharp, extractFSharpArtifact } from './languages/fsharp.ts' +export { extractHaskellArtifact } from './languages/haskell.ts' export { extractProject } from './project.ts' export { resolvePublicIds } from './reexports.ts' export { SymbolIndex, keywordArgument, parameterId, typeParameterId, type LinkTarget, type KeywordHelp, type TypeParameterBinding } from './link.ts' diff --git a/packages/api-model/src/inventory.ts b/packages/api-model/src/inventory.ts index 7c6867981..1be2c2b82 100644 --- a/packages/api-model/src/inventory.ts +++ b/packages/api-model/src/inventory.ts @@ -32,20 +32,26 @@ export function symbolEntries(entries: T[]): T[] { /** Sphinx v2 uses object types in records; roles resolve those types. */ const DOMAIN: Record = { + perl: 'std', py: 'py', ruby: 'std', lua: 'std', powershell: 'std', julia: 'std', elixir: 'std', + haskell: 'std', + lisp: 'std', + erlang: 'std', cxx: 'cpp', ts: 'js', rs: 'std', go: 'std', java: 'std', + clojure: 'std', kotlin: 'std', scala: 'std', fsharp: 'std', + ocaml: 'std', csharp: 'std', swift: 'std', } diff --git a/packages/api-model/src/languages/clojure-examples.ts b/packages/api-model/src/languages/clojure-examples.ts new file mode 100644 index 000000000..0ab7c4973 --- /dev/null +++ b/packages/api-model/src/languages/clojure-examples.ts @@ -0,0 +1,100 @@ +import type { ApiSymbol, DocBlock } from '../model.ts' + +interface ExampleFile { sourceFile: string; path: string; language?: string } +interface Program extends ExampleFile { + id: string + variant: string + language: string + description: string + mainNamespace: string + targets: string[] + expectedOutput: string + cliAliases?: string[] + requiresControl?: boolean + unsupportedOutput?: string +} + +/** Attach the native Clojure catalog without changing the JVM example schema. */ +export function attachCompleteClojureExamples( + symbols: ApiSymbol[], + read: (path: string) => string | undefined, + source: { repo: string; revision: string }, +): void { + const raw = read('examples/api/clojure/manifest.json') + if (!raw || source.repo !== 'libtmux/libtmux-java' || !/^[a-f0-9]{40}$/.test(source.revision)) { + throw new Error('Clojure examples require their native catalog and source revision') + } + const manifest = JSON.parse(raw) as { + schemaVersion: number; examples: Program[]; variants: { clojure: { files: ExampleFile[] } } + } + const files = manifest.variants?.clojure?.files + if (manifest.schemaVersion !== 1 || !Array.isArray(manifest.examples) || !manifest.examples.length || + !Array.isArray(files) || ![1, 2].includes(files.length) || + new Set(files.map((file) => file.path)).size !== files.length || + !files.some((file) => file.path === 'deps.edn') || + !files.every((file) => ['deps.edn', 'run.sh'].includes(file.path))) { + throw new Error('Invalid Clojure example catalog or setup') + } + const usesLauncher = files.some((file) => file.path === 'run.sh') + const codeFor = (path: string): string => { + if (!/^examples\/(?:[\w-]+\/)*[\w.-]+$/.test(path) || path.split('/').includes('..')) { + throw new Error(`Invalid Clojure example source path: ${path}`) + } + const code = read(path) + if (!code?.trim()) throw new Error(`Missing complete Clojure example file: ${path}`) + return code + } + const urlFor = (path: string) => `https://github.com/${source.repo}/blob/${source.revision}/${path}` + const ids = new Set() + for (const program of manifest.examples) { + const namespace = /^libtmux\.examples\.api\.[a-z][a-z-]*$/.test(program.mainNamespace ?? '') + if (!program.id || ids.has(program.id) || program.variant !== 'clojure' || program.language !== 'clojure' || + !namespace || program.path !== `src/main/clojure/${program.mainNamespace.replaceAll('.', '/').replaceAll('-', '_')}.clj` || + program.sourceFile !== `examples/${program.path}` || !program.description?.trim() || + !program.expectedOutput?.trim() || !program.expectedOutput.endsWith('\n') || + !Array.isArray(program.targets) || !program.targets.length || + new Set(program.targets).size !== program.targets.length || + program.cliAliases && (program.cliAliases.length !== 1 || program.cliAliases[0] !== 'core-async') || + program.requiresControl && (!program.unsupportedOutput?.trim() || !program.unsupportedOutput.endsWith('\n'))) { + throw new Error(`Invalid Clojure example metadata: ${program.id}`) + } + ids.add(program.id) + const adapter = program.cliAliases?.includes('core-async') + const publish = [':libtmux:publishToMavenLocal', ':libtmux-clojure:publishToMavenLocal', + ...(adapter ? [':libtmux-clojure-core-async:publishToMavenLocal'] : [])] + const blocks: NonNullable = [{ + lang: 'console', + intro: `${program.description} Use JDK 25 or newer, the Clojure CLI, Git and tmux on Linux or macOS, with /bin/cat and /bin/sh available. These packages are unpublished. In an empty directory, install this exact source into the consumer's isolated Maven repository:`, + code: `$ git clone https://github.com/${source.repo} libtmux-source && \\\n git -C libtmux-source checkout --detach ${source.revision} && \\\n (cd libtmux-source && ./gradlew \\\n ${publish.join(' \\\n ')} \\\n --console=plain \\\n "-Dmaven.repo.local=$PWD/../m2")\n`, + }, ...files.map((file) => ({ + lang: file.path === 'run.sh' ? 'sh' : 'clojure', + intro: `Save this file as \`${file.path}\`. ${file.path === 'run.sh' + ? 'The launcher creates and stops a private server, including after program failure, and reports leaked servers as errors.' + : 'Dependencies resolve from the isolated m2 directory; the core.async dependency is only enabled by its alias.'}`, + code: codeFor(file.sourceFile), sourceUrl: urlFor(file.sourceFile), + })), { + lang: 'clojure', intro: `Save the complete program as \`${program.path}\`, creating its parent directories. ${usesLauncher + ? "Closing its client leaves the launcher's server running." + : 'The program starts its own private tmux server and stops it on exit.'}`, + code: codeFor(program.sourceFile), sourceUrl: urlFor(program.sourceFile), + }, { + lang: 'console', intro: usesLauncher + ? 'Run it with the private fixture. Set TMUX_BIN to select another tmux binary:' + : 'Run the program directly:', + code: `$ ${usesLauncher ? 'sh run.sh ' : ''}clojure \\\n -J-Dclojure.main.report=stderr \\\n -M${adapter ? ':core-async' : ''} \\\n -m ${program.mainNamespace}\n`, + }, { + lang: 'text', intro: program.requiresControl ? 'Expected output on tmux 3.7 or newer:' : 'Expected output:', + code: program.expectedOutput, + }] + if (program.requiresControl) blocks.push({ + lang: 'text', intro: 'On an older supported tmux, the program reports the control capability refusal:', + code: program.unsupportedOutput!, + }) + for (const target of program.targets) { + const matches = symbols.filter((symbol) => symbol.id === target) + if (matches.length !== 1) throw new Error(`Clojure example target must resolve once: ${target}`) + const symbol = matches[0]! + symbol.doc = { summary: '', ...symbol.doc, examples: [...(symbol.doc?.examples ?? []), ...blocks] } + } + } +} diff --git a/packages/api-model/src/languages/clojure.ts b/packages/api-model/src/languages/clojure.ts new file mode 100644 index 000000000..b7efbec3e --- /dev/null +++ b/packages/api-model/src/languages/clojure.ts @@ -0,0 +1,91 @@ +import { parseMarkdownDocFull } from '../doc/markdown.ts' +import { tokenizeDoc } from '../doc/roles.ts' +import type { ApiModel, ApiSource, ApiSymbol } from '../model.ts' + +interface ClojureArtifact { + schema: string + port: string + repo: string + revision: string + compiler: string + extractor: string + sources: ApiSource[] + nativeProvenance: NonNullable + symbols: (ApiSymbol & { docstring: string })[] +} + +/** Preserve compiled public Clojure vars, native arities, hints and authored links. */ +export function extractClojure(input: unknown, expectedRevision?: string): ApiModel { + const artifact = input as ClojureArtifact + if (artifact?.schema !== 'libtmux.clojure-api/1' || artifact.port !== 'clojure' || + !/^[a-f0-9]{40}$/.test(artifact.revision ?? '') || + expectedRevision !== undefined && expectedRevision !== artifact.revision) { + throw new Error('Clojure artifact schema or selected source revision mismatch') + } + const sourceFiles = artifact.nativeProvenance?.files + const exporter = artifact.nativeProvenance?.exporter + if (!/^[0-9]+\.[0-9]+\.[0-9]+(?:[.-][\w.-]+)?$/.test(artifact.compiler ?? '') || + artifact.repo !== 'libtmux/libtmux-java' || !artifact.extractor || + !Array.isArray(sourceFiles) || !sourceFiles.length || + sourceFiles.some((file) => !file.path || !/^[a-f0-9]{64}$/.test(file.sha256)) || + new Set(sourceFiles.map((file) => file.path)).size !== sourceFiles.length || + exporter?.name !== 'clojure-public-var-metadata' || + typeof exporter.revision !== 'string' || !/^sha256:[a-f0-9]{64}$/.test(exporter.revision) || + !Array.isArray(exporter.files) || !exporter.files.length || + exporter.files.some((file) => !file?.path || !/^[a-f0-9]{64}$/.test(file.sha256))) { + throw new Error('Clojure artifact requires compiler, source and exporter provenance') + } + const packages = new Map() + for (const source of artifact.sources ?? []) { + const module = /^io\.github\.libtmux:(libtmux-clojure(?:-core-async)?)$/.exec(source.package)?.[1] + if (!module || source.repo !== artifact.repo || source.revision !== artifact.revision || + !source.version || source.product !== 'core' || packages.has(source.package)) { + throw new Error('Clojure package source identity is invalid') + } + packages.set(source.package, module) + } + if (!packages.size || !Array.isArray(artifact.symbols) || !artifact.symbols.length) { + throw new Error('Clojure artifact documents no public packages or declarations') + } + const ids = new Set(artifact.symbols.map((symbol) => symbol.id)) + const namespaces = new Set(artifact.symbols.filter((symbol) => symbol.kind === 'module').map((symbol) => symbol.id)) + if (ids.size !== artifact.symbols.length) throw new Error('Clojure public identity is duplicated') + for (const symbol of artifact.symbols) { + const namespace = symbol.namespace + const module = packages.get(symbol.package ?? '') + if (!namespace || !/^libtmux\.[\w.-]+$/.test(namespace) || !module || + !['module', 'function'].includes(symbol.kind) || symbol.apiScope !== 'exported' || + symbol.modifiers.includes('private') || symbol.publicOwner !== namespace || + symbol.publicId !== symbol.id || symbol.qualifiedName !== symbol.id || + symbol.id !== (symbol.kind === 'module' ? namespace : `${namespace}/${symbol.name}`) || + symbol.kind === 'function' && (symbol.parent !== namespace || !namespaces.has(namespace))) { + throw new Error(`Clojure public declaration is invalid: ${symbol.id}`) + } + const file = `${module}/src/main/clojure/${namespace.replaceAll('.', '/').replaceAll('-', '_')}.clj` + if (symbol.source?.file !== file || !sourceFiles.some((entry) => entry.path === file) || + !Number.isSafeInteger(symbol.source.line) || (symbol.source.line ?? 0) < 1 || + symbol.source.repo !== artifact.repo || symbol.source.revision !== artifact.revision) { + throw new Error(`Clojure source identity is invalid: ${symbol.id}`) + } + if (!symbol.docstring?.trim() || !Array.isArray(symbol.signatures) || !symbol.signatures.length || + symbol.signatures.some((signature) => !signature.raw?.endsWith(')') || + !(signature.raw.startsWith(`(${symbol.kind === 'module' ? 'ns' : symbol.name} `) || signature.raw === `(${symbol.name})`) || + !Array.isArray(signature.params) || signature.params.some((parameter) => !parameter.name))) { + throw new Error(`Clojure native signature or docstring is absent: ${symbol.id}`) + } + for (const reference of tokenizeDoc(symbol.docstring, 'clojure')) { + if (reference.kind !== 'ref' || !reference.explicit) continue + if (!ids.has(reference.target) && !ids.has(`${namespace}/${reference.target}`)) { + throw new Error(`Clojure docstring has an unresolved public reference: ${reference.target}`) + } + } + } + return { + port: 'clojure', repo: artifact.repo, revision: artifact.revision, + extractor: artifact.extractor, sources: artifact.sources, nativeProvenance: artifact.nativeProvenance, + symbols: artifact.symbols.map(({ docstring, ...symbol }) => { + const [summary, ...body] = docstring.split('\n') + return { ...symbol, doc: parseMarkdownDocFull([summary, '', ...body].join('\n'), 'clojure').doc } + }), + } +} diff --git a/packages/api-model/src/languages/erlang.ts b/packages/api-model/src/languages/erlang.ts new file mode 100644 index 000000000..ad9a1bd78 --- /dev/null +++ b/packages/api-model/src/languages/erlang.ts @@ -0,0 +1,229 @@ +import { parseMarkdownDocFull } from '../doc/markdown.ts' +import type { ApiModel, ApiSymbol, DocBlock, Modifier, Signature, TypeReference } from '../model.ts' + +interface Source { file: string; line: number } +interface Spec { + parameters: { name: string; type: string; references: TypeReference[] }[] + returns: string + returns_references: TypeReference[] + text: string + references: TypeReference[] +} +interface Member { + name: string + display_name: string + kind: 'function' | 'callback' | 'type' + arity: number + doc: string | null + since: string | null + deprecated: string | null + visibility: 'public' | 'opaque' | 'nominal' + exported: boolean + signatures: string[] + declarations: string[] + declaration_references: TypeReference[][] + specs: Spec[] + source: Source +} +interface Module { + name: string + display_name: string + doc: string | null + source: Source + members: Member[] + records: { name: string; display_name: string; declaration: string; references: TypeReference[]; source: Source }[] +} +interface Artifact { + schema: number + port: string + source: { repository: string; revision: string; files: { path: string; sha256: string }[] } + exporter: { name: string; version: number; columns: number; otp: string; source_sha256: string } + package: { name: string; version: string } + modules: Module[] +} + +function assertArtifact(input: unknown, expectedRevision?: string): Artifact { + const artifact = input as Artifact + if (artifact?.schema !== 1 || artifact.port !== 'erlang' || artifact.exporter?.version !== 3 || + artifact.exporter.columns !== 60 || !/^[a-f0-9]{64}$/.test(artifact.exporter.source_sha256 ?? '') || + !Array.isArray(artifact.modules) || !artifact.modules.length || + !/^[a-f0-9]{40}$/.test(artifact.source?.revision ?? '') || + !Array.isArray(artifact.source?.files) || !artifact.source.files.length || + !artifact.source.repository || !artifact.package?.name || !artifact.package.version) { + throw new Error('Erlang compiler artifact has an unsupported schema or source identity') + } + if (expectedRevision && artifact.source.revision !== expectedRevision) { + throw new Error('Erlang artifact source revision differs from the selected checkout') + } + const files = new Set(artifact.source.files.map((file) => { + if (!file.path || file.path.startsWith('/') || file.path.split('/').includes('..') || + !/^[a-f0-9]{64}$/.test(file.sha256)) throw new Error('Erlang artifact has invalid source inputs') + return file.path + })) + if (files.size !== artifact.source.files.length) throw new Error('Erlang artifact repeats a source input') + const location = (source: Source) => { + if (!source || !files.has(source.file) || !Number.isInteger(source.line) || source.line < 1) { + throw new Error('Erlang artifact lost a declaration source') + } + } + const seen = new Set() + const unique = (id: string) => { + if (seen.has(id)) throw new Error(`Erlang artifact repeats ${id}`) + seen.add(id) + } + for (const module of artifact.modules) { + if (!module.display_name || !Array.isArray(module.members) || !Array.isArray(module.records)) { + throw new Error('Erlang artifact lost a module declaration') + } + unique(module.display_name) + location(module.source) + for (const member of module.members) { + if (!['function', 'callback', 'type'].includes(member.kind) || !member.display_name || + !Number.isInteger(member.arity) || member.arity < 0 || member.arity > 255 || + !member.declarations?.length || !Array.isArray(member.specs) || + typeof member.exported !== 'boolean' || !['public', 'opaque', 'nominal'].includes(member.visibility)) { + throw new Error('Erlang artifact lost a member declaration') + } + unique(memberId(module, member)) + location(member.source) + if (member.visibility === 'opaque' && member.declarations.some(opaqueBody)) { + throw new Error('Erlang artifact exposes an opaque type body') + } + if (!Array.isArray(member.declaration_references) || + member.declaration_references.length !== member.declarations.length || + member.visibility === 'opaque' && member.declaration_references.some((refs) => refs.length)) { + throw new Error('Erlang artifact lost declaration references or exposes an opaque body') + } + member.declarations.forEach((text, index) => assertReferences(text, member.declaration_references[index])) + if (member.kind !== 'type' && (!Array.isArray(member.signatures) || + !member.signatures.length || member.signatures.some((head) => typeof head !== 'string' || !head.trim()) || + !member.specs.length || member.specs.some((spec) => !spec || + !Array.isArray(spec.parameters) || spec.parameters.length !== member.arity || + spec.parameters.some((parameter) => !parameter || + typeof parameter.name !== 'string' || !parameter.name.trim() || + typeof parameter.type !== 'string' || !parameter.type.trim()) || + typeof spec.returns !== 'string' || !spec.returns.trim() || + typeof spec.text !== 'string' || !spec.text.trim()))) { + throw new Error('Erlang artifact lost its native callable signature') + } + for (const spec of member.specs) { + assertReferences(spec.text, spec.references) + assertReferences(spec.returns, spec.returns_references) + for (const parameter of spec.parameters) assertReferences(parameter.type, parameter.references) + } + } + for (const record of module.records) { + if (!record.display_name || !record.declaration) throw new Error('Erlang artifact lost a native record declaration') + unique(recordId(module, record.display_name)) + location(record.source) + assertReferences(record.declaration, record.references) + } + } + return artifact +} + +function assertReferences(text: string, references: TypeReference[] | undefined): void { + if (!Array.isArray(references)) throw new Error('Erlang artifact lost its compiler references') + let offset = 0 + const boundary = (at: number) => !(at > 0 && at < text.length && + /[\uD800-\uDBFF]/.test(text[at - 1]!) && /[\uDC00-\uDFFF]/.test(text[at]!)) + for (const reference of references) { + if (!reference || !Number.isInteger(reference.start) || !Number.isInteger(reference.end) || + reference.start < offset || reference.end <= reference.start || reference.end > text.length || + !boundary(reference.start) || !boundary(reference.end) || + typeof reference.target !== 'string' || !/^(?:t:.+\/\d+|#.+\{\})$/.test(reference.target)) { + throw new Error('Erlang artifact has invalid compiler reference ranges') + } + if (reference.external) { + let url: URL + try { url = new URL(reference.external.href) } + catch { throw new Error('Erlang artifact has an invalid OTP reference destination') } + const target = /^t:([a-z][A-Za-z0-9_]*):(.+)\/(\d+)$/.exec(reference.target) + if (!target || reference.external.project !== 'Erlang/OTP' || + url.origin !== 'https://www.erlang.org' || url.username || url.password || url.search || + !/^\/doc\/apps\/[a-z][a-z0-9_]*\/[a-z][A-Za-z0-9_]*\.html$/.test(url.pathname) || + !url.pathname.endsWith(`/${target[1]}.html`) || + decodeURIComponent(url.hash.slice(1)) !== `t:${target[2]}/${target[3]}`) { + throw new Error('Erlang artifact has an invalid OTP reference destination') + } + } + offset = reference.end + } +} + +/** A body delimiter inside a compiler-quoted atom is part of its name. */ +function opaqueBody(text: string): boolean { + let quoted = false + for (let at = 0; at < text.length; at++) { + const character = text[at] + if (quoted && character === '\\') { at++; continue } + if (character === "'") { quoted = !quoted; continue } + if (!quoted && character === ':' && text[at + 1] === ':') return true + } + return quoted +} + +const memberId = (module: Module, member: Member): string => + `${member.kind === 'type' ? 't:' : member.kind === 'callback' ? 'c:' : ''}${module.display_name}:${member.display_name}/${member.arity}` +const recordId = (module: Module, name: string): string => `#${module.display_name}:${name}{}` + +function documentation(text: string | null, since?: string | null, deprecated?: string | null): DocBlock | undefined { + const doc = text?.trim() ? parseMarkdownDocFull(text, 'erlang').doc : undefined + return doc || since || deprecated + ? { ...(doc ?? { summary: '' }), ...(since ? { since } : {}), ...(deprecated ? { deprecated } : {}) } + : undefined +} + +/** Map compiler declarations without guessing types or parsing Erlang source in JavaScript. */ +export function extractErlang(input: unknown, expectedRevision?: string): ApiModel { + const artifact = assertArtifact(input, expectedRevision) + const source = (location: Source): ApiSymbol['source'] => ({ + ...location, repo: artifact.source.repository, revision: artifact.source.revision, + extractedRevision: artifact.source.revision, + }) + const common = { package: artifact.package.name, + product: artifact.package.name === 'libtmux_erlang_workspace' ? 'workspace' as const : 'core' as const } + const symbols: ApiSymbol[] = [] + for (const module of artifact.modules) { + const owner = module.display_name + symbols.push({ id: owner, publicId: owner, qualifiedName: owner, name: owner, + kind: 'module', modifiers: [], signatures: [], apiScope: 'exported', + ...common, doc: documentation(module.doc), source: source(module.source) }) + for (const member of module.members) { + const type = member.kind === 'type' + const modifiers: Modifier[] = [ + ...(member.visibility === 'opaque' ? ['opaque' as const] : []), + ...(member.kind === 'callback' ? ['abstract' as const] : []), + ...(member.deprecated ? ['deprecated' as const] : []), + ...(member.specs.length > 1 ? ['overload' as const] : []), + ] + const signatures: Signature[] = type + ? member.declarations.map((raw, index) => ({ raw, params: [], references: member.declaration_references[index] })) + : member.specs.map((spec) => { + const prefix = member.kind === 'callback' ? '' : `${member.signatures[0]}\n` + return { raw: prefix + spec.text, + references: spec.references.map((ref) => ({ ...ref, start: ref.start + prefix.length, end: ref.end + prefix.length })), + params: spec.parameters.map((param) => ({ name: param.name, type: param.type, typeReferences: param.references })), + returns: spec.returns, returnsReferences: spec.returns_references } + }) + const id = memberId(module, member) + symbols.push({ id, publicId: id, qualifiedName: `${owner}:${member.display_name}/${member.arity}`, + name: `${member.display_name}/${member.arity}`, namespace: owner, parent: owner, + kind: type ? 'typealias' : 'function', modifiers, signatures, + ...common, apiScope: member.exported ? 'exported' : 'supporting', + doc: documentation(member.doc, member.since, member.deprecated), source: source(member.source) }) + } + for (const record of module.records) { + const id = recordId(module, record.display_name) + symbols.push({ id, publicId: id, qualifiedName: id, name: `#${record.display_name}{}`, + namespace: owner, parent: owner, kind: 'struct', modifiers: [], + signatures: [{ raw: record.declaration, params: [], references: record.references }], ...common, + apiScope: 'exported', source: source(record.source) }) + } + } + return { port: 'erlang', repo: artifact.source.repository, revision: artifact.source.revision, + extractor: `@libtmux/api-model@0.0.1 (${artifact.exporter.name} v${artifact.exporter.version})`, + nativeProvenance: { files: artifact.source.files, exporter: artifact.exporter }, + sources: [{ ...common, version: artifact.package.version, repo: artifact.source.repository, + revision: artifact.source.revision, extractedRevision: artifact.source.revision }], symbols } +} diff --git a/packages/api-model/src/languages/haskell.ts b/packages/api-model/src/languages/haskell.ts new file mode 100644 index 000000000..1871eee9f --- /dev/null +++ b/packages/api-model/src/languages/haskell.ts @@ -0,0 +1,229 @@ +import type { ApiModel, ApiSymbol, DocBlock, Signature } from '../model.ts' +import { exportGroupsNav } from '../nav-sidecar.ts' +import { sourceUrl } from '../products.ts' + +interface NativeSource { file: string; revision: string; line?: number } +interface NativeLink { text: string; href: string; target?: string } +interface NativeInstance { + raw: string + markdown: string + doc: string | null + references: NativeLink[] + source: NativeSource +} +interface NativeSymbol extends Omit { + doc: DocBlock | null + parent: string | null + source: NativeSource + instances?: NativeInstance[] +} +interface HashedInput { path: string; sha256: string } +interface HaskellArtifact { + schema: string + port: string + repo: string + revision: string + compiler: string + haddock: string + component: string + package: { name: string; version: string; exposedModules: string[] } + nativeProvenance: { + files: HashedInput[] + exporter: { + name: string; version: number; repository: string; revision: string; path: string; sha256: string + build: { compiler: string; cabal: string; unit: string; platform: string } + interfaceStream: string + nativeArtifacts: HashedInput[] + } + } + modules: { name: string; groups: { title: string; members: string[] }[] }[] + symbols: NativeSymbol[] +} + +const COMMIT = /^[a-f0-9]{40}$/ +const HASH = /^[a-f0-9]{64}$/ +const QUALIFIED_MODULES = ['LibTmux.Id', 'LibTmux.Value', 'LibTmux.Version'] +const VERSION = /^(?:0|[1-9]\d*)(?:\.(?:0|[1-9]\d*))+$/ + +function check(condition: unknown, reason: string): asserts condition { + if (!condition) throw new Error(`Invalid Haskell documentation artifact: ${reason}`) +} + +function hashedInputs(inputs: HashedInput[], expected: string[], label: string): void { + check(Array.isArray(inputs) && inputs.length === expected.length, `incomplete ${label}`) + const remaining = new Set(expected) + for (const input of inputs) { + check(input && typeof input.path === 'string' && remaining.delete(input.path) && + typeof input.sha256 === 'string' && HASH.test(input.sha256), `invalid or repeated ${label}`) + } +} + +/** Preserve the native destination; resolve only explicitly identified public declarations. */ +function validateLink(link: NativeLink, byId: Map): void { + check(link && typeof link.text === 'string' && link.text.length && typeof link.href === 'string', 'missing native link') + if (link.target !== undefined) { + const target = byId.get(link.target) + check(target, `unknown public link target ${link.target}`) + const [module, anchor] = link.target.split('#') + const expected = `${module.replaceAll('.', '-')}.html${anchor ? `#${anchor}` : ''}` + check(link.href === expected, `native destination differs from ${link.target}`) + } else { + let url: URL + try { url = new URL(link.href) } catch { throw new Error(`Invalid Haskell native URL: ${link.href}`) } + check(['http:', 'https:'].includes(url.protocol) && !url.username && !url.password, `unsafe native URL ${link.href}`) + } +} + +function validateSignature(signature: Signature, symbol: NativeSymbol, byId: Map): void { + check(typeof signature.raw === 'string' && signature.raw.length && Array.isArray(signature.params) && + signature.params.length === 0 && Array.isArray(signature.nativeSpans) && signature.nativeSpans.length, `missing native signature for ${symbol.id}`) + const spans = signature.nativeSpans + check(spans.every((span) => span && typeof span.text === 'string' && span.text.length && + (span.declaration === undefined || span.declaration === true) && (span.keyword === undefined || span.keyword === true)), + `invalid native signature spans for ${symbol.id}`) + check(spans.map((span) => span.text).join('') === signature.raw, `native signature text differs for ${symbol.id}`) + const declarations = spans.filter((span) => span.declaration) + check(declarations.length === 1 && declarations[0].text === symbol.name && !declarations[0].href && !declarations[0].target, + `missing declaration marker for ${symbol.id}`) + for (const span of spans) { + check(span.target === undefined || span.href !== undefined, `link target has no destination in ${symbol.id}`) + if (span.href !== undefined) validateLink(span as NativeLink, byId) + } + check(signature.methodKind === undefined || signature.methodKind === 'constructor', `unsupported method kind for ${symbol.id}`) +} + +/** Adapt the qualified GHC 9.14/Haddock public profile without parsing Haskell source. */ +export function extractHaskellArtifact(input: unknown, expectedRevision?: string): ApiModel { + check(input && typeof input === 'object', 'missing document') + const artifact = structuredClone(input) as HaskellArtifact + check(artifact.schema === 'libtmux.haskell-api/1' && artifact.port === 'haskell' && + artifact.repo === 'libtmux/libtmux-haskell' && typeof artifact.revision === 'string' && COMMIT.test(artifact.revision), + 'unsupported schema or source identity') + check(!expectedRevision || artifact.revision === expectedRevision, 'source revision differs from the selected checkout') + check(artifact.compiler === '9.14.1' && artifact.haddock === '2.33.0' && artifact.component === 'lib:libtmux-haskell', + 'unsupported native tool or component profile') + check(artifact.package?.name === 'libtmux-haskell' && VERSION.test(artifact.package.version) && + Array.isArray(artifact.package.exposedModules) && artifact.package.exposedModules.length, 'invalid Cabal package identity') + const modules = artifact.package.exposedModules + check(modules.length === QUALIFIED_MODULES.length && modules.every((module, index) => module === QUALIFIED_MODULES[index]), + 'unqualified exposed module profile') + check(Array.isArray(artifact.modules) && artifact.modules.length === modules.length && + artifact.modules.every((module, index) => module?.name === modules[index] && Array.isArray(module.groups)), + 'native modules differ from the configured public modules') + const exporter = artifact.nativeProvenance?.exporter + check(exporter?.name === 'Haddock public interface export' && exporter.version === 1 && exporter.repository === 'libtmux/docs' && + typeof exporter.revision === 'string' && COMMIT.test(exporter.revision) && + exporter.path === 'packages/api-model/scripts/export-haskell.py' && HASH.test(exporter.sha256), 'missing committed producer identity') + check(exporter.build?.compiler === `ghc-${artifact.compiler}` && exporter.build.cabal === '3.18.2.0' && + exporter.build.unit === `${artifact.package.name}-${artifact.package.version}-inplace` && + typeof exporter.build.platform === 'string' && /^[\w]+-[\w]+$/.test(exporter.build.platform) && + ['stdout', 'stderr'].includes(exporter.interfaceStream), 'invalid configured native build') + const sourceFiles = modules.map((module) => `src/${module.replaceAll('.', '/')}.hs`) + hashedInputs(artifact.nativeProvenance.files, ['.tool-versions', 'cabal.project', 'libtmux-haskell.cabal', ...sourceFiles], 'source inputs') + hashedInputs(exporter.nativeArtifacts, ['interface.haddock', 'interface.json', + ...modules.flatMap((module) => [`${module.replaceAll('.', '-')}.html`, `src/${module}.html`])], 'native inputs') + check(Array.isArray(artifact.symbols) && artifact.symbols.length, 'no public declarations') + const byId = new Map() + for (const symbol of artifact.symbols) { + check(symbol && typeof symbol.id === 'string' && !byId.has(symbol.id), 'missing or repeated public identity') + check(symbol.apiScope === 'exported' && symbol.product === 'core' && symbol.package === artifact.package.name, + `nonpublic or unrecognized package declaration ${symbol.id}`) + check(['module', 'typealias', 'function', 'property'].includes(symbol.kind) && typeof symbol.name === 'string' && + Array.isArray(symbol.modifiers) && symbol.modifiers.every((modifier) => modifier === 'opaque') && + symbol.modifiers.length <= 1 && Array.isArray(symbol.signatures), `unsupported declaration shape ${symbol.id}`) + if (symbol.kind === 'module') { + check(modules.includes(symbol.id) && symbol.name === symbol.id && symbol.parent === null && + symbol.signatures.length === 0 && symbol.modifiers.length === 0, `invalid public module ${symbol.id}`) + } else { + check(typeof symbol.namespace === 'string' && modules.includes(symbol.namespace) && + /^[A-Za-z_][\w']*$/.test(symbol.name) && symbol.qualifiedName === `${symbol.namespace}.${symbol.name}` && + symbol.id === `${symbol.namespace}#${symbol.kind === 'typealias' ? 't' : 'v'}:${symbol.name}` && + symbol.publicId === symbol.id && symbol.signatures.length === 1, `invalid public declaration identity ${symbol.id}`) + } + const module = symbol.kind === 'module' ? symbol.id : symbol.namespace! + check(symbol.source?.file === `src/${module.replaceAll('.', '/')}.hs` && symbol.source.revision === artifact.revision && + (symbol.source.line === undefined || (Number.isSafeInteger(symbol.source.line) && symbol.source.line > 0)), + `source differs from the public declaration ${symbol.id}`) + check(symbol.doc === null || (symbol.doc && typeof symbol.doc.summary === 'string' && + (symbol.doc.body === undefined || typeof symbol.doc.body === 'string')), `invalid authored documentation ${symbol.id}`) + byId.set(symbol.id, symbol) + } + check(modules.every((module) => byId.get(module)?.kind === 'module'), 'missing public module declaration') + const constructorOwners = new Set(artifact.symbols.filter((symbol) => symbol.kind === 'function' && + symbol.signatures[0]?.methodKind === 'constructor').map((symbol) => symbol.parent)) + for (const symbol of artifact.symbols) { + if (symbol.kind === 'module') continue + const parent = byId.get(symbol.parent ?? '') + const constructor = symbol.signatures[0].methodKind === 'constructor' + check(parent && (parent.kind === 'module' ? parent.id === symbol.namespace && symbol.kind !== 'property' && !constructor + : parent.kind === 'typealias' && !parent.modifiers.includes('opaque') && parent.namespace === symbol.namespace && + ((symbol.kind === 'property' && !constructor) || (symbol.kind === 'function' && constructor))), `invalid public parent for ${symbol.id}`) + if (symbol.kind === 'typealias') { + // This producer profile exports scalar data heads, not aliases or hidden representations. + check(symbol.signatures[0].raw === `data ${symbol.name}` && Array.isArray(symbol.instances), + `unsupported type representation or missing instances for ${symbol.id}`) + check(symbol.modifiers.includes('opaque') === !constructorOwners.has(symbol.id), `opaque status differs for ${symbol.id}`) + } else check(symbol.modifiers.length === 0, `opaque non-type ${symbol.id}`) + validateSignature(symbol.signatures[0], symbol, byId) + } + const model: ApiModel = { + port: 'haskell', repo: artifact.repo, revision: artifact.revision, + extractor: `@libtmux/api-model@0.0.1 (${exporter.name} v${exporter.version})`, + nativeProvenance: artifact.nativeProvenance, + sources: [{ product: 'core', package: artifact.package.name, version: artifact.package.version, + repo: artifact.repo, revision: artifact.revision, extractedRevision: artifact.revision }], + exportGroups: artifact.modules.flatMap((module) => module.groups.map((group) => ({ owner: module.name, ...group }))), + symbols: [], + } + model.symbols = artifact.symbols.map((native): ApiSymbol => { + const source = { ...native.source, repo: artifact.repo, extractedRevision: artifact.revision } + const references: NonNullable = [] + const refer = (target: string) => { + if (!references.some((reference) => reference.target === target)) { + references.push({ target, kind: byId.get(target)!.kind === 'typealias' ? 'type' : 'reference' }) + } + } + for (const span of native.signatures.flatMap((signature) => signature.nativeSpans ?? [])) if (span.target) refer(span.target) + let doc = native.doc ?? undefined + if (native.instances !== undefined) { + check(native.kind === 'typealias' && Array.isArray(native.instances), `instances on a non-type ${native.id}`) + const heads = new Set() + const items = native.instances.map((instance) => { + check(instance && typeof instance.raw === 'string' && instance.raw.startsWith('instance ') && !heads.has(instance.raw) && + typeof instance.markdown === 'string' && instance.markdown.startsWith('instance ') && + (instance.doc === null || typeof instance.doc === 'string') && Array.isArray(instance.references), + `invalid native instance for ${native.id}`) + heads.add(instance.raw) + check(instance.source?.file === native.source.file && instance.source.revision === artifact.revision && + (instance.source.line === undefined || (Number.isSafeInteger(instance.source.line) && instance.source.line > 0)), + `instance source differs for ${native.id}`) + for (const link of instance.references) { + validateLink(link, byId) + if (link.target) refer(link.target) + } + // Only simple class/type heads are qualified; owner and display must agree. + const [typeclass, owner] = instance.references + check(instance.references.length === 2 && !typeclass.target && /^[A-Z][\w']*$/.test(typeclass.text) && + owner.target === native.id && owner.text === native.name && + instance.raw === `instance ${typeclass.text} ${native.name}` && + instance.markdown === `instance [${typeclass.text}](${typeclass.href}) :obj:\`${native.name} <${native.id}>\``, + `instance head, links or owner differ for ${native.id}`) + const href = sourceUrl(model, { ...native, source: instance.source } as ApiSymbol)! + return `- ${instance.markdown} ([Source](${href}))${instance.doc ? `\n\n ${instance.doc.replaceAll('\n', '\n ')}` : ''}` + }) + if (items.length) doc = { summary: doc?.summary ?? '', + body: [doc?.body, '## Instances', items.join('\n\n')].filter(Boolean).join('\n\n') } + } + return { + id: native.id, publicId: native.publicId ?? native.id, name: native.name, + ...(native.qualifiedName ? { qualifiedName: native.qualifiedName } : {}), + ...(native.namespace ? { namespace: native.namespace } : {}), + ...(native.parent ? { parent: native.parent } : {}), + kind: native.kind, modifiers: native.modifiers, signatures: native.signatures, + package: native.package, product: 'core', apiScope: 'exported', source, + ...(doc ? { doc } : {}), ...(references.length ? { references } : {}), + } + }) + exportGroupsNav(model) + return model +} diff --git a/packages/api-model/src/languages/lisp.ts b/packages/api-model/src/languages/lisp.ts new file mode 100644 index 000000000..4792996ad --- /dev/null +++ b/packages/api-model/src/languages/lisp.ts @@ -0,0 +1,271 @@ +import type { ApiModel, ApiProduct, ApiSymbol, DocBlock, Modifier, Param, Signature, SymbolKind } from '../model.ts' + +interface NativeDocumentation { summary: string; body?: string; seeAlso?: string[] } +interface NativeSource { file: string; line: number } +interface NativeMethod { signature: string; qualifiers: string[]; specializers: string[] } +interface NativeSymbol { + id: string + name: string + kind: 'function' | 'class' | 'exception' + signature?: string + modifiers: string[] + generic?: boolean + methods?: NativeMethod[] + supertypes?: string[] + documentation: NativeDocumentation + source: NativeSource +} +interface NativePackage { + name: string + system: string + product: ApiProduct + documentation: NativeDocumentation + source: NativeSource + symbols: NativeSymbol[] +} +interface CommonLispArtifact { + schema: string + port: string + library: { version: string } + runtime: { implementation: string; implementationVersion: string; asdfVersion: string } + source: { + repository: string + revision: string + dirty: boolean + files: { path: string; sha256: string }[] + } + exporter: { name: string; version: number; revision: string; dirty: boolean } + packages: NativePackage[] +} + +const SHA1 = /^[0-9a-f]{40}$/ +const SHA256 = /^[0-9a-f]{64}$/ +const PACKAGE_CONTRACT = [ + ['libtmux', 'libtmux', 'core'], + ['libtmux.control', 'libtmux/control', 'core'], + ['libtmux.json', 'libtmux/json', 'core'], + ['libtmux.query', 'libtmux/query', 'core'], + ['libtmux.workspace', 'libtmux/workspace', 'workspace'], + ['libtmux.workspace.cli', 'libtmux/workspace/cli', 'workspace'], +] as const + +function documentation(value: NativeDocumentation): DocBlock { + const body = [value.body, value.seeAlso?.length + ? `See also: ${value.seeAlso.map((target) => `\`${target}\``).join(', ')}.` : undefined] + .filter(Boolean).join('\n\n') + return { + summary: value.summary, + ...(body ? { body } : {}), + ...(value.seeAlso?.length ? { seeAlso: [...value.seeAlso] } : {}), + } +} + +/** A CLOS method specializes required arguments; optional/key bindings keep their ordinary roles. */ +function methodSignature(id: string, method: NativeMethod, names: Map): Signature { + const [name, ...argumentsAndQualifiers] = listItems(method.signature) + const args = argumentsAndQualifiers.slice(method.qualifiers.length) + const plain = args.map((argument, index) => index < method.specializers.length + ? listItems(argument)[0]! : argument) + const params = parameters(`(${name} ${plain.join(' ')})`).map((param, index) => ({ + ...param, ...(index < method.specializers.length + ? { type: names.get(method.specializers[index]!) ?? method.specializers[index]! } : {}), + })) + return { + identity: JSON.stringify([id, method.qualifiers, method.specializers]), + methodKind: 'function', raw: method.signature, params, + label: `${method.qualifiers.join(' ') || 'Primary'} method: ${method.specializers.map((type) => names.get(type) ?? type).join(', ')}`, + } +} + +/** Split one printed Lisp list without evaluating or interning its contents. */ +function listItems(value: string): string[] { + const text = value.trim() + if (!text.startsWith('(') || !text.endsWith(')')) return [] + const items: string[] = [] + let depth = 0 + let start = -1 + let string = false + let escaped = false + let escapedSymbol = false + for (let index = 0; index < text.length; index++) { + const char = text[index]! + if (escaped) { escaped = false; continue } + if (char === '\\' && (string || escapedSymbol)) { escaped = true; continue } + if (char === '"' && !escapedSymbol) { + if (depth === 1 && start < 0) start = index + string = !string + continue + } + if (char === '|' && !string) { + if (depth === 1 && start < 0) start = index + escapedSymbol = !escapedSymbol + continue + } + if (string || escapedSymbol) continue + if (char === '(') { + depth++ + if (depth === 2 && start < 0) start = index + continue + } + if (char === ')') { + if (depth === 1 && start >= 0) { items.push(text.slice(start, index)); start = -1 } + if (depth === 2 && start >= 0) { + depth-- + if (depth === 1) { items.push(text.slice(start, index + 1)); start = -1 } + continue + } + depth-- + continue + } + if (depth !== 1) continue + if (/\s/.test(char)) { + if (start >= 0) { items.push(text.slice(start, index)); start = -1 } + } else if (start < 0) start = index + } + return items +} + +/** Read caller-visible names from a printed Common Lisp lambda list. */ +function parameters(signature: string): Param[] { + const [, ...lambdaList] = listItems(signature) + const params: Param[] = [] + let mode: 'required' | 'optional' | 'rest' | 'key' = 'required' + let skipNext = false + for (const item of lambdaList) { + const marker = item.toLowerCase() + if (marker === '&optional') { mode = 'optional'; continue } + if (marker === '&rest' || marker === '&body') { mode = 'rest'; continue } + if (marker === '&key') { mode = 'key'; continue } + if (marker === '&allow-other-keys') continue + if (marker === '&aux') break + if (marker === '&whole' || marker === '&environment') { skipNext = true; continue } + if (skipNext) { skipNext = false; continue } + const parts = item.startsWith('(') ? listItems(item) : [] + const binding = parts[0] ?? item + const name = mode === 'required' ? item + : mode === 'key' && binding.startsWith('(') ? listItems(binding)[1] ?? binding : binding + const defaultValue = mode === 'optional' || mode === 'key' ? parts[1] : undefined + params.push({ + name, + ...(defaultValue ? { default: defaultValue } : {}), + ...(mode === 'optional' || mode === 'key' ? { optional: true } : {}), + ...(mode === 'key' ? { keywordOnly: true } : {}), + ...(mode === 'rest' ? { variadic: 'positional' as const } : {}), + }) + } + return params +} + +function assertArtifact(input: unknown, revision?: string): CommonLispArtifact { + const artifact = input as CommonLispArtifact + if (artifact?.schema !== 'libtmux.lisp.api/1' || artifact.port !== 'lisp' || + artifact.source?.repository !== 'libtmux/libtmux-lisp' || !SHA1.test(artifact.source?.revision ?? '') || + artifact.source?.dirty !== false || revision !== undefined && artifact.source.revision !== revision) { + throw new Error('Common Lisp artifact schema, source identity or selected checkout differs') + } + if (artifact.exporter?.name !== 'libtmux.documentation' || artifact.exporter.version !== 1 || + !SHA1.test(artifact.exporter.revision ?? '') || artifact.exporter.dirty !== false || + artifact.runtime?.implementation !== 'SBCL' || !artifact.runtime.implementationVersion || + !artifact.runtime.asdfVersion || !/^\d+\.\d+\.\d+$/.test(artifact.library?.version ?? '')) { + throw new Error('Common Lisp artifact producer identity is unsupported or dirty') + } + const filePaths = artifact.source.files?.map((file) => file.path) ?? [] + if (!filePaths.length || new Set(filePaths).size !== filePaths.length || + artifact.source.files.some((file) => !file.path || !SHA256.test(file.sha256)) || + !filePaths.includes('tools/documentation.lisp')) { + throw new Error('Common Lisp artifact source provenance is incomplete') + } + const hasControl = Array.isArray(artifact.packages) && artifact.packages.some((pkg) => pkg.name === 'libtmux.control') + const packageContract = PACKAGE_CONTRACT.filter(([name]) => name !== 'libtmux.control' || hasControl) + if (!Array.isArray(artifact.packages) || artifact.packages.length !== packageContract.length || + artifact.packages.some((pkg, index) => { + const expected = packageContract[index]! + return pkg.name !== expected[0] || pkg.system !== expected[1] || pkg.product !== expected[2] + })) { + throw new Error('Common Lisp public package inventory differs') + } + const ids = new Set() + for (const pkg of artifact.packages) { + if (!pkg.documentation?.summary || !filePaths.includes(pkg.source?.file) || !Number.isInteger(pkg.source?.line) || pkg.source.line < 1 || + !Array.isArray(pkg.symbols) || !pkg.symbols.length) { + throw new Error(`Common Lisp package metadata is incomplete: ${pkg.name}`) + } + for (const symbol of pkg.symbols) { + if (!symbol.id?.startsWith(`${pkg.name}:`) || ids.has(symbol.id) || !symbol.name || + !['function', 'class', 'exception'].includes(symbol.kind) || !symbol.documentation?.summary || + !filePaths.includes(symbol.source?.file) || !Number.isInteger(symbol.source?.line) || symbol.source.line < 1 || + symbol.kind === 'function' && !symbol.signature || + symbol.modifiers.some((modifier) => !['macro', 'opaque'].includes(modifier))) { + throw new Error(`Invalid Common Lisp public declaration: ${symbol.id}`) + } + ids.add(symbol.id) + } + } + for (const pkg of artifact.packages) { + for (const symbol of pkg.symbols) { + for (const target of symbol.documentation.seeAlso ?? []) { + if (!ids.has(target)) throw new Error(`Unresolved Common Lisp cross-reference: ${target}`) + } + if (symbol.generic && (!Array.isArray(symbol.methods) || !symbol.methods.length)) { + throw new Error(`Missing Common Lisp method applicability: ${symbol.id}`) + } + for (const method of symbol.methods ?? []) { + if (!symbol.generic || !method.signature || !Array.isArray(method.qualifiers) || + method.qualifiers.some((qualifier) => typeof qualifier !== 'string') || + !Array.isArray(method.specializers) || !method.specializers.length || + method.specializers.some((target) => target !== 'common-lisp:t' && + !artifact.packages.some((owner) => owner.symbols.some((entry) => entry.id === target && entry.kind !== 'function')))) { + throw new Error(`Invalid Common Lisp method applicability: ${symbol.id}`) + } + } + } + } + return artifact +} + +/** Adapt an SBCL-native public-package artifact without parsing Common Lisp source. */ +export function extractCommonLisp(input: unknown, revision?: string): ApiModel { + const artifact = assertArtifact(input, revision) + const source = (location: NativeSource): ApiSymbol['source'] => ({ + ...location, repo: artifact.source.repository, revision: artifact.source.revision, + extractedRevision: artifact.exporter.revision, + }) + const symbols: ApiSymbol[] = [] + const names = new Map(artifact.packages.flatMap((pkg) => pkg.symbols + .map((symbol) => [symbol.id, `${pkg.name}:${symbol.name}`] as const))) + for (const pkg of artifact.packages) { + symbols.push({ + id: pkg.name, publicId: pkg.name, qualifiedName: pkg.name, namespace: '', name: pkg.name, + kind: 'module', modifiers: [], signatures: [], product: pkg.product, package: pkg.system, + publicOwner: pkg.name, apiScope: 'exported', doc: documentation(pkg.documentation), source: source(pkg.source), + }) + for (const symbol of pkg.symbols) { + symbols.push({ + id: symbol.id, publicId: symbol.id, qualifiedName: `${pkg.name}:${symbol.name}`, + namespace: pkg.name, name: symbol.name, kind: symbol.kind as SymbolKind, + modifiers: symbol.modifiers as Modifier[], parent: pkg.name, + signatures: [ + ...(symbol.signature ? [{ raw: symbol.signature, params: parameters(symbol.signature) }] : []), + ...(symbol.methods ?? []).map((method) => methodSignature(symbol.id, method, names)), + ], + product: pkg.product, package: pkg.system, publicOwner: pkg.name, apiScope: 'exported', + doc: documentation(symbol.documentation), source: source(symbol.source), + ...(symbol.supertypes?.length ? { extends: [...symbol.supertypes] } : {}), + }) + } + } + return { + port: 'lisp', repo: artifact.source.repository, revision: artifact.source.revision, + extractor: `${artifact.exporter.name}/${artifact.exporter.version}`, + nativeProvenance: { + files: artifact.source.files.map((file) => ({ ...file })), + exporter: { ...artifact.exporter, runtime: { ...artifact.runtime }, library: { ...artifact.library } }, + }, + sources: artifact.packages.map((pkg) => ({ + product: pkg.product, package: pkg.system, repo: artifact.source.repository, + revision: artifact.source.revision, extractedRevision: artifact.exporter.revision, + version: artifact.library.version, + })), + symbols, + } +} diff --git a/packages/api-model/src/languages/ocaml-examples.ts b/packages/api-model/src/languages/ocaml-examples.ts new file mode 100644 index 000000000..682a31a09 --- /dev/null +++ b/packages/api-model/src/languages/ocaml-examples.ts @@ -0,0 +1,57 @@ +import type { ApiSymbol } from '../model.ts' + +interface Showcase { + capability: string + title: string + file: string + whole_file: boolean + command: string[] + expected_stdout_line: string + success_exit_code: number +} + +const targets: Readonly> = { + bootstrap: ['Libtmux_unix.Workspace.submit_bootstrap', 'Libtmux_unix.Workspace.await', 'Libtmux_unix.Workspace.client'], + graph: ['Libtmux.Snapshot.sessions', 'Libtmux.Session.window_links', 'Libtmux.Window.panes', 'Libtmux_unix.Client.capture'], + watch: ['Libtmux_eio.Client.subscribe', 'Libtmux_eio.Subscription.wait_for_bytes'], + 'send-keys': ['Libtmux_unix.Client.send_text', 'Libtmux_unix.Client.send_keys'], + 'rename-window': ['Libtmux_unix.Client.rename_window'], + 'create-window': ['Libtmux_unix.Client.create_window'], + 'move-window': ['Libtmux_unix.Client.move_window_at'], + layout: ['Libtmux_unix.Client.select_layout'], +} + +/** Read whole, CI-executed programs at the same commit as the public interface. */ +export function attachCompleteOcamlExamples(symbols: ApiSymbol[], read: (path: string) => string, revision: string): void { + const manifest = JSON.parse(read('examples/showcase.json')) as { + schema: string; tmux_floor: string; ci: { workflow: string; job: string; runner: string }; examples: Showcase[] + } + if (manifest.schema !== 'libtmux.showcase/1' || manifest.tmux_floor !== '3.3a' || + manifest.ci.workflow !== '.github/workflows/ocaml.yml' || manifest.ci.job !== 'native' || + manifest.ci.runner !== 'test/showcase_test.py' || !Array.isArray(manifest.examples)) { + throw new Error('Invalid OCaml CI showcase manifest') + } + const found = new Set() + for (const example of manifest.examples) { + if (!targets[example.capability] || found.has(example.capability) || !example.whole_file || + !/^examples\/showcase_[a-z_]+\.ml$/.test(example.file) || example.success_exit_code !== 0 || + JSON.stringify(example.command) !== JSON.stringify(['opam', 'exec', '--', 'dune', 'exec', + example.file.replace(/\.ml$/, '.exe'), '--', 'tmux'])) throw new Error('Invalid OCaml whole program') + found.add(example.capability) + const code = read(example.file) + if (!code.includes('let () =') || code.split('\n').length > 151) throw new Error('Incomplete OCaml entry point') + const sourceUrl = `https://github.com/libtmux/libtmux-ocaml/blob/${revision}/${example.file}` + for (const target of targets[example.capability]!) { + const matches = symbols.filter((symbol) => symbol.id === target) + if (matches.length !== 1) throw new Error(`OCaml showcase target must resolve once: ${target}`) + const symbol = matches[0]! + symbol.doc = { summary: '', ...symbol.doc, examples: [...(symbol.doc?.examples ?? []), + { lang: 'ocaml', code, sourceUrl, + intro: `${example.title}. This complete program creates a private daemon, checks its result and closes its clients. Use OCaml 5.5.2 on Linux with tmux 3.3a through 3.8. Run it from the source checkout after following the installation guide.` }, + { lang: 'console', code: `$ ${example.command.join(' ')}\n`, intro: 'Run the recorded entry point:' }, + { lang: 'text', code: example.expected_stdout_line + '\n', intro: 'Expected outcome line, after the temporary socket path:' }, + ] } + } + } + if (found.size !== Object.keys(targets).length) throw new Error('Missing OCaml capability showcase') +} diff --git a/packages/api-model/src/languages/ocaml.test.ts b/packages/api-model/src/languages/ocaml.test.ts new file mode 100644 index 000000000..67e53846f --- /dev/null +++ b/packages/api-model/src/languages/ocaml.test.ts @@ -0,0 +1,102 @@ +import { describe, expect, it } from 'vitest' +import { extractOcamlArtifact } from './ocaml.ts' +import { SymbolIndex } from '../link.ts' +import type { ApiSymbol } from '../model.ts' + +const revision = 'a'.repeat(40) +const exporter = 'b'.repeat(40) +const artifact = () => ({ + schema: 'libtmux.ocaml-api/1', port: 'ocaml', compiler: '5.5.2', revision, + repo: 'https://github.com/libtmux/libtmux-ocaml', extractor: 'native cmti', + nativeProvenance: { files: [{ path: 'lib/libtmux.mli', sha256: 'c'.repeat(64) }], exporter: { revision: exporter } }, + sources: [{ package: 'libtmux', product: 'core', repo: 'https://github.com/libtmux/libtmux-ocaml', revision }], + symbols: [ + { id: 'Libtmux', name: 'Libtmux', qualifiedName: 'Libtmux', publicId: 'Libtmux', publicOwner: 'Libtmux', + apiScope: 'exported', package: 'libtmux', product: 'core', kind: 'module', modifiers: [], signatures: [], + source: { file: 'lib/libtmux.mli', line: 1, revision } }, + { id: 'Libtmux.t', name: 't', qualifiedName: 'Libtmux.t', publicId: 'Libtmux.t', parent: 'Libtmux', publicOwner: 'Libtmux', + apiScope: 'exported', package: 'libtmux', product: 'core', kind: 'typealias', modifiers: ['opaque'], + signatures: [{ raw: 'type t', params: [] }], source: { file: 'lib/libtmux.mli', line: 2, revision } }, + ], +}) + +describe('OCaml compiled public interfaces', () => { + it('keeps typed odoc links, custom labels, guide URLs and literal code distinct', () => { + const symbols = artifact().symbols as ApiSymbol[] + const common = { ...symbols[1]!, name: 'state', qualifiedName: 'Libtmux.state', modifiers: [] } + symbols.push({ ...common, id: 'Libtmux.state', publicId: 'Libtmux.state', kind: 'function' }, + { ...common, id: 'Libtmux.state:type', publicId: 'Libtmux.state:type', kind: 'enum' }, + { ...common, id: 'Libtmux.state:type.Ready', publicId: 'Libtmux.state:type.Ready', parent: 'Libtmux.state:type', name: 'Ready', qualifiedName: 'Libtmux.Ready', kind: 'constant', variant: 'unit' }) + const index = new SymbolIndex(symbols, (symbol) => `/${symbol.id}`, 'ocaml') + const spans = index.docSpans('{!type-state} {!val-state} {{!type-state}the state type} `state` [Guide](https://ocaml.org/manual/5.5/typedecl.html)', symbols[0]) + const references = spans.filter((span) => span.kind === 'ref') + expect(references.map((span) => span.link?.symbol?.id)).toEqual(['Libtmux.state:type', 'Libtmux.state', 'Libtmux.state:type']) + expect(references[2]).toMatchObject({ label: 'the state type', code: false }) + expect(spans).toContainEqual({ kind: 'code', text: 'state' }) + expect(spans).toContainEqual({ kind: 'link', text: 'Guide', href: 'https://ocaml.org/manual/5.5/typedecl.html' }) + expect(index.docSpans('{!type-missing}', symbols[0])[0]).toMatchObject({ target: 'missing', link: undefined }) + expect(index.docSpans('{!module-Libtmux.type-state}', symbols[1])[0]).toMatchObject({ link: { symbol: { id: 'Libtmux.state:type' } } }) + expect(index.docSpans('{!type:Libtmux.state}', symbols[1])[0]).toMatchObject({ link: { symbol: { id: 'Libtmux.state:type' } } }) + expect(index.docSpans('{!module-state}', symbols[0])[0]).toMatchObject({ link: undefined }) + expect(index.docSpans('{!Libtmux.Ready}', symbols[0])[0]).toMatchObject({ link: { symbol: { id: 'Libtmux.state:type.Ready' } } }) + expect(index.docSpans('{!type-state.constructor-Ready}', symbols[0])[0]).toMatchObject({ link: { symbol: { id: 'Libtmux.state:type.Ready' } } }) + expect(index.docSpans('{!val-Ready}', symbols[0])[0]).toMatchObject({ link: undefined }) + const signature = { raw: 'val state : t -> state', params: [] } + const typeSpans = index.linkType(signature.raw, symbols[2], signature) + expect(typeSpans.filter((span) => span.text === 'state')).toMatchObject([ + { declaration: true }, { link: { symbol: { id: 'Libtmux.state:type' } } }, + ]) + expect(index.linkType("('state, 'other) state", symbols[2]).filter((span) => span.link) + .map((span) => span.link?.symbol?.id)).toEqual(['Libtmux.state:type']) + expect(index.resolve('Iarray')?.href).toBe('https://ocaml.org/manual/5.5/api/Iarray.html') + expect(index.linkType('state Seq.t', symbols[2]).find((span) => span.text === 'Seq.t')?.link) + .toMatchObject({ href: 'https://ocaml.org/manual/5.5/api/Seq.html#TYPEt', external: true }) + }) + + it('retains opaque types, native signatures and independent source/tool identities', () => { + const model = extractOcamlArtifact(artifact(), revision) + expect(model.port).toBe('ocaml') + expect(model.symbols[1]?.signatures[0]?.raw).toBe('type t') + expect(model.symbols[1]?.modifiers).toEqual(['opaque']) + expect(model.revision).toBe(revision) + expect(model.nativeProvenance?.exporter.revision).toBe(exporter) + }) + + it('resolves module-alias members in odoc and signatures without crossing namespaces', () => { + const root = artifact().symbols[0]! as ApiSymbol + const symbol = (id: string, kind: ApiSymbol['kind'], parent: string, extra = {}): ApiSymbol => ({ + ...root, id, publicId: id, qualifiedName: id.replace(/:type$/, ''), + name: id.split('.').at(-1)!.replace(/:type$/, ''), kind, parent, ...extra, + }) + const owner = symbol('Libtmux.Client', 'module', 'Libtmux') + const values = [root, owner, + symbol('Libtmux.Report', 'module', 'Libtmux'), + symbol('Libtmux.Report.state', 'function', 'Libtmux.Report'), + symbol('Libtmux.Report.state:type', 'typealias', 'Libtmux.Report'), + symbol('Libtmux.Cleanup', 'module', 'Libtmux', { exportedFrom: 'Libtmux.Report' }), + symbol('Libtmux.Client.Local', 'module', owner.id, { exportedFrom: 'Libtmux.Cleanup' }), + symbol('Libtmux.Cycle', 'module', 'Libtmux', { exportedFrom: 'Libtmux.Cycle' }), + ] + const index = new SymbolIndex(values, (value) => `/${value.id}`, 'ocaml') + expect(index.resolve('Cleanup.state', 'odoc:val', owner)?.symbol?.id).toBe('Libtmux.Report.state') + expect(index.resolve('module-Local.type-state', 'odoc:type', owner)?.symbol?.id).toBe('Libtmux.Report.state:type') + expect(index.linkType('Local.state', owner)[0]?.link?.symbol?.id).toBe('Libtmux.Report.state:type') + expect(index.resolve('Cleanup.state', 'odoc:module', owner)).toBeUndefined() + expect(index.resolve('type-Cleanup.val-state', 'odoc:val', owner)).toBeUndefined() + expect(index.resolve('Cleanup.missing', 'odoc:val', owner)).toBeUndefined() + expect(index.resolve('Cycle.state', 'odoc:val', owner)).toBeUndefined() + }) + + it('rejects stale revisions, private paths, unknown products and unresolved aliases', () => { + expect(() => extractOcamlArtifact(artifact(), exporter)).toThrow(/revision/) + const privateSymbol = artifact() + privateSymbol.symbols[1]!.id = 'Libtmux__Graph.t' + expect(() => extractOcamlArtifact(privateSymbol)).toThrow(/public/) + const mcp = artifact() + mcp.symbols[1]!.product = 'mcp' + expect(() => extractOcamlArtifact(mcp)).toThrow(/product/) + const missing = artifact() + Object.assign(missing.symbols[1]!, { exportedFrom: 'Libtmux.Private' }) + expect(() => extractOcamlArtifact(missing)).toThrow(/alias/) + }) +}) diff --git a/packages/api-model/src/languages/ocaml.ts b/packages/api-model/src/languages/ocaml.ts new file mode 100644 index 000000000..b4771fe6a --- /dev/null +++ b/packages/api-model/src/languages/ocaml.ts @@ -0,0 +1,52 @@ +import type { ApiModel, ApiSymbol } from '../model.ts' + +interface OcamlArtifact extends ApiModel { + schema: string + compiler: string +} + +const roots: Readonly> = { + Libtmux: 'libtmux', Libtmux_workspace: 'libtmux-workspace', Libtmux_json: 'libtmux-json', + Libtmux_unix: 'libtmux-unix', Libtmux_eio: 'libtmux-eio', +} + +/** Adapt the native public .cmti export without parsing OCaml as another language. */ +export function extractOcamlArtifact(input: unknown, revision?: string): ApiModel { + const artifact = input as OcamlArtifact + if (artifact?.schema !== 'libtmux.ocaml-api/1' || artifact.port !== 'ocaml' || + artifact.compiler !== '5.5.2' || !/^[a-f0-9]{40}$/.test(artifact.revision ?? '') || + revision !== undefined && revision !== artifact.revision) { + throw new Error('OCaml artifact schema, compiler or library revision mismatch') + } + const exporterRevision = artifact.nativeProvenance?.exporter.revision + if (typeof exporterRevision !== 'string' || !/^[a-f0-9]{40}$/.test(exporterRevision) || + !artifact.nativeProvenance?.files.length || !Array.isArray(artifact.symbols) || !artifact.symbols.length) { + throw new Error('OCaml artifact requires committed exporter and public input provenance') + } + const ids = new Set(artifact.symbols.map((symbol) => symbol.id)) + if (ids.size !== artifact.symbols.length) throw new Error('Duplicate OCaml public identity') + for (const symbol of artifact.symbols) { + const root = symbol.id.split('.')[0]! + if (!roots[root] || symbol.id.includes('__') || symbol.package !== roots[root] || + symbol.apiScope !== 'exported' || symbol.publicOwner !== root || symbol.publicId !== symbol.id || + !symbol.qualifiedName || !symbol.name || symbol.parent && !ids.has(symbol.parent)) { + throw new Error(`Invalid OCaml public declaration: ${symbol.id}`) + } + if (!['core', 'workspace'].includes(symbol.product ?? '')) throw new Error('Unsupported OCaml product') + if (!/^(lib|unix|eio|json|workspace)\/\w+\.mli$/.test(symbol.source.file) || + !Number.isInteger(symbol.source.line) || (symbol.source.line ?? 0) < 1 || + symbol.source.revision !== artifact.revision) { + throw new Error(`Invalid OCaml source identity: ${symbol.id}`) + } + if (symbol.exportedFrom && !ids.has(symbol.exportedFrom)) throw new Error('Unresolved OCaml public alias') + if (!Array.isArray(symbol.signatures) || symbol.signatures.some((signature) => + !signature.raw || signature.params.some((param) => param.default !== undefined))) { + throw new Error(`Invalid OCaml native signature: ${symbol.id}`) + } + } + return { + port: 'ocaml', revision: artifact.revision, repo: artifact.repo, sources: artifact.sources, + extractor: artifact.extractor, nativeProvenance: artifact.nativeProvenance, + symbols: artifact.symbols.map((symbol): ApiSymbol => ({ ...symbol })), + } +} diff --git a/packages/api-model/src/languages/perl.ts b/packages/api-model/src/languages/perl.ts new file mode 100644 index 000000000..07770afe7 --- /dev/null +++ b/packages/api-model/src/languages/perl.ts @@ -0,0 +1,98 @@ +import type { ApiModel, ApiSymbol, DocBlock } from '../model.ts' +import { docSectionTitles } from '../doc/prose-blocks.ts' + +interface PerlArtifact extends ApiModel { + schema: string + examples?: { owner: string; path: string; code: string }[] +} + +const PACKAGES = new Set(['LibTmux', 'LibTmux-Async', 'LibTmux-Workspace']) +const SHA = /^[a-f0-9]{40}$/ +const publicId = /^LibTmux(?:::[A-Za-z][A-Za-z0-9_]*)*$/ + +/** Adapt PPI signatures and Pod::Simple links; never parse Perl as TypeScript. */ +export function extractPerlArtifact(input: unknown, revision?: string): ApiModel { + const artifact = input as PerlArtifact + if (artifact?.schema !== 'libtmux.perl-api/v1' || artifact.port !== 'perl' || + !SHA.test(artifact.revision ?? '') || revision !== undefined && revision !== artifact.revision) { + throw new Error('Perl native artifact schema or library revision mismatch') + } + const exporter = artifact.nativeProvenance?.exporter + if (!exporter || (typeof exporter.revision !== 'string' || !SHA.test(exporter.revision)) || exporter.working_tree !== false || + !artifact.nativeProvenance?.files.length || !Array.isArray(artifact.symbols) || !artifact.symbols.length) { + throw new Error('Perl artifact requires committed exporter and public input provenance') + } + const ids = new Set(artifact.symbols.map((symbol) => symbol.id)) + if (ids.size !== artifact.symbols.length) throw new Error('Duplicate Perl public identity') + const files = new Set(artifact.nativeProvenance.files.map((file) => file.path)) + for (const file of artifact.nativeProvenance.files) { + if (!/^[a-f0-9]{64}$/.test(file.sha256) || file.path.startsWith('/') || file.path.split('/').includes('..')) { + throw new Error('Invalid Perl native input provenance') + } + } + for (const symbol of artifact.symbols) { + if (!publicId.test(symbol.id) || symbol.name.startsWith('_') || symbol.name === 'DESTROY' || + /^LibTmux::(?:Codec|Platform)(?:::|$)/.test(symbol.id) || symbol.apiScope !== 'exported' || + !PACKAGES.has(symbol.package ?? '') || !['core', 'workspace'].includes(symbol.product ?? '') || + symbol.parent && !ids.has(symbol.parent) || symbol.publicId !== symbol.id) { + throw new Error(`Invalid Perl public declaration: ${symbol.id}`) + } + if (!/^packages\/(?:core|async|workspace)\/lib\/LibTmux(?:\/[^/]+)*\.pm$/.test(symbol.source.file) || + !files.has(symbol.source.file) || !Number.isInteger(symbol.source.line) || (symbol.source.line ?? 0) < 1 || + symbol.source.revision !== artifact.revision || !Array.isArray(symbol.signatures) || + symbol.signatures.some((signature) => !signature.raw || !Array.isArray(signature.params))) { + throw new Error(`Invalid Perl native signature or source identity: ${symbol.id}`) + } + } + const resolvePod = (text: string): string => text.replace(/\[([^\]]+)\]\(pod:([^\n)]+)\)/g, (_all, label: string, target: string) => { + const separator = target.indexOf('/') + const module = separator < 0 ? target : target.slice(0, separator) + const rawSection = separator < 0 ? undefined : target.slice(separator + 1) + let section: string | undefined + try { + // Earlier native artifacts wrote section titles containing spaces literally. + section = rawSection === undefined ? undefined : /\s/u.test(rawSection) ? rawSection : decodeURIComponent(rawSection) + } catch { throw new Error(`Malformed authored Perl POD target: ${target}`) } + if (!module.startsWith('LibTmux')) { + const href = module === 'JSON::PP' ? 'https://perldoc.perl.org/5.44.0/JSON::PP' + : `https://metacpan.org/pod/${module}` + return `[${label}](${href}${section ? `#${encodeURIComponent(section)}` : ''})` + } + let id = module === 'LibTmux::Transport' && section === 'RESULTS' ? 'LibTmux::CommandResult' + : section ? `${module}::${section}` : module + if (!ids.has(id) && section) { + // One POD file can document several declared packages, including error subclasses. + const owner = artifact.symbols.find((symbol) => symbol.id === module) + const methods = owner ? artifact.symbols.filter((symbol) => symbol.kind === 'method' + && !symbol.inheritedFrom && symbol.name === section && symbol.source.file === owner.source.file) : [] + if (methods.length > 1) throw new Error(`Ambiguous authored Perl POD target: ${target}`) + if (methods.length === 1) id = methods[0].id + else if (owner) { + const headings = docSectionTitles(owner).filter((title) => title === section) + if (headings.length > 1) throw new Error(`Ambiguous authored Perl POD target: ${target}`) + if (headings.length === 1) return `:obj:\`${label.replace(/`/g, '')} <${owner.id}#${encodeURIComponent(section)}>\`` + } + } + if (!ids.has(id)) throw new Error(`Unresolved authored Perl POD target: ${target}`) + return `:obj:\`${label.replace(/`/g, '')} <${id}>\`` + }) + const doc = (value?: DocBlock): DocBlock | undefined => value ? { + ...value, summary: resolvePod(value.summary), ...(value.body ? { body: resolvePod(value.body) } : {}), + ...(value.examples ? { examples: value.examples.map((example) => ({ ...example, ...(example.intro ? { intro: resolvePod(example.intro) } : {}) })) } : {}), + } : undefined + const symbols: ApiSymbol[] = artifact.symbols.map((symbol) => ({ + ...symbol, signatures: symbol.signatures.map((signature) => ({ ...signature, params: signature.params.map((param) => ({ ...param })) })), doc: doc(symbol.doc), + })) + for (const example of artifact.examples ?? []) { + const owner = symbols.find((symbol) => symbol.id === example.owner) + if (!owner || !/^examples\/[a-z-]+\.pl$/.test(example.path) || !files.has(example.path) || !example.code) { + throw new Error('Invalid complete Perl example provenance') + } + owner.doc ??= { summary: '' } + owner.doc.examples = [...owner.doc.examples ?? [], { lang: 'perl', code: example.code, + intro: 'Complete installed-package program with an owned tmux fixture and result/cleanup assertions.', + sourceUrl: `https://github.com/libtmux/libtmux-perl/blob/${artifact.revision}/${example.path}` }] + } + return { port: 'perl', repo: artifact.repo, revision: artifact.revision, sources: artifact.sources, + extractor: artifact.extractor, nativeProvenance: artifact.nativeProvenance, symbols } +} diff --git a/packages/api-model/src/link.ts b/packages/api-model/src/link.ts index e8e8553be..36e987cac 100644 --- a/packages/api-model/src/link.ts +++ b/packages/api-model/src/link.ts @@ -1,6 +1,7 @@ import { RUST_CRATE_PREFIX, tokenizeDoc, type DocSpan } from './doc/roles.ts' +import { docSectionId, docSectionTitles } from './doc/prose-blocks.ts' import { symbolEntries, type InventoryEntry } from './inventory.ts' -import type { ApiProduct, ApiSource, ApiSymbol, Signature, SymbolKind, TypeParameter } from './model.ts' +import type { ApiProduct, ApiSource, ApiSymbol, Param, Signature, SymbolKind, TypeParameter } from './model.ts' import { cargoFeatureHref, documentedFeature } from './cargo-features.ts' import { builtinHref, CURATED_BEFORE_INVENTORY, ELIXIR_STDLIB_MODULES, elixirStdlibHref, NOT_THE_JDKS } from './builtins.ts' import { neverLinks } from './never-links.ts' @@ -34,6 +35,16 @@ const ROLE_KINDS: Record = { any: [], } +const ODOC_KINDS = new Map([ + ['type', ['typealias', 'enum', 'struct', 'union']], + ['val', ['function', 'constant']], ['value', ['function', 'constant']], + ['module', ['module']], ['module-type', ['interface']], + ['class', ['class']], ['class-type', ['interface']], + ['exception', ['exception']], ['exn', ['exception']], + ['constructor', ['constant']], ['const', ['constant']], + ['field', ['attribute']], ['recfield', ['attribute']], +]) + /** * Names that belong to the language, not to us. * @@ -89,6 +100,7 @@ const SIGNATURE_KEYWORDS: Record> = Object.fromEntries(Objec // Attributes that open a declaration, and the guard of a spec. elixir: 'spec type opaque callback macrocallback when', cxx: 'alignas alignof auto class concept const consteval constexpr constinit decltype default delete enum explicit extern final friend inline mutable namespace noexcept operator override register requires static struct template thread_local typedef typename union using virtual volatile', + ocaml: 'type val module sig end with and of private mutable exception include functor', }).map(([port, words]) => [port, new Set(words.split(' '))])) /** Language help stays separate from links to API declarations. */ @@ -317,6 +329,8 @@ function implSelfArguments(header: string): string[] | undefined { export class SymbolIndex { private readonly byPublic = new Map() private readonly byQualified = new Map() + /** Native qualified names and contextual constructor/field paths share this lookup. */ + private readonly ocamlPaths = new Map() // Keyed by declaration id. `parent` is a declaration id, so looking an owner // up in byPublic silently misses every time — which is why relative // references stayed at 0% until this map existed. @@ -364,6 +378,7 @@ export class SymbolIndex { * forgets to say produces fewer links, not wrong ones. */ private readonly lang: string | undefined + private readonly docHref: ((href: string) => string) | undefined /** The port this index describes, which decides how a page writes a symbol. */ get language(): string | undefined { @@ -375,9 +390,10 @@ export class SymbolIndex { return symbol.parent ? this.byDeclared.get(symbol.parent) : undefined } - constructor(symbols: ApiSymbol[], hrefFor: (symbol: ApiSymbol) => string, lang?: string) { + constructor(symbols: ApiSymbol[], hrefFor: (symbol: ApiSymbol) => string, lang?: string, docHref?: (href: string) => string) { this.lang = lang this.hrefFor = hrefFor + this.docHref = docHref for (const s of symbols) { if (!this.byDeclared.has(s.id) || !s.inheritedFrom) this.byDeclared.set(s.id, s) const pub = s.publicId ?? s.id @@ -390,6 +406,12 @@ export class SymbolIndex { aliases.push(s) this.byQualified.set(qualified, aliases) + if (this.lang === 'ocaml') { + for (const path of new Set([qualified, s.id.replace(/:type(?=\.|$)/g, '')])) { + this.ocamlPaths.set(path, [...(this.ocamlPaths.get(path) ?? []), s]) + } + } + const suffixes = new Set([pub, qualified].flatMap((name) => { const parts = name.split('.') return parts.slice(1).map((_, i) => parts.slice(i + 1).join('.')) @@ -706,6 +728,7 @@ export class SymbolIndex { * turned 59 dead references into links, most of the remaining gap. */ resolve(target: string, role = 'any', context?: ApiSymbol): LinkTarget | undefined { + if (this.lang === 'ocaml' && role.startsWith('odoc:')) return this.resolveOdoc(target, role.slice(5), context) // A name the context binds as a type parameter is that parameter, never a // same-named global. if (context && TYPE_PARAMETER_ROLES.has(role) && /^[A-Za-z_$][\w$]*$/.test(target)) { @@ -715,7 +738,71 @@ export class SymbolIndex { return role === 'typeparam' ? undefined : this.resolveSymbol(target, role, context) } + /** Resolve odoc's namespaces from the containing module outward, without a global suffix guess. */ + private resolveOdoc(target: string, role: string, context?: ApiSymbol, aliases = new Set()): LinkTarget | undefined { + const segments = target.split('.').map((part) => { + const typed = /^(module-type|class-type|type|val|value|module|class|exception|exn|constructor|const|field|recfield)-(.+)$/.exec(part) + return { name: typed?.[2] ?? part, role: typed?.[1] } + }) + if (segments.some((part) => !part.name)) return undefined + const path = segments.map((part) => part.name).join('.') + const matches = (symbol: ApiSymbol, kind: string | undefined) => { + if (!kind || kind === 'any') return true + if (!ODOC_KINDS.get(kind)?.includes(symbol.kind)) return false + if (kind === 'constructor' || kind === 'const') return symbol.variant !== undefined + if (kind === 'val' || kind === 'value') return symbol.variant === undefined + return true + } + const scopes = new Set() + for (let owner = context; owner; owner = this.parentOf(owner)) { + if (owner.kind === 'module' || owner.kind === 'interface') scopes.add(`${qualifiedNameOf(owner)}.`) + } + scopes.add('') + const parentsMatch = (symbol: ApiSymbol, last: number) => { + let ancestor = this.parentOf(symbol) + for (let i = last - 1; i >= 0; i--) { + // OCaml also exposes record labels and variant constructors directly in their module. + while (ancestor && ancestor.name !== segments[i]!.name && !['module', 'interface'].includes(ancestor.kind)) ancestor = this.parentOf(ancestor) + if (!ancestor || ancestor.name !== segments[i]!.name || !matches(ancestor, segments[i]!.role)) return false + ancestor = this.parentOf(ancestor) + } + return true + } + for (const scope of scopes) { + const candidates = (this.ocamlPaths.get(`${scope}${path}`) ?? []) + .filter((symbol) => matches(symbol, role) && parentsMatch(symbol, segments.length - 1)) + if (candidates.length === 1) { + const symbol = candidates[0]! + return { href: this.hrefFor(symbol), external: false, symbol } + } + if (candidates.length > 1) return undefined + // A module alias keeps its own page; its members link to their public declarations. + for (let count = segments.length - 1; count > 0; count--) { + const prefix = `${scope}${segments.slice(0, count).map((part) => part.name).join('.')}` + const modules = (this.ocamlPaths.get(prefix) ?? []).filter((symbol) => + symbol.kind === 'module' && symbol.exportedFrom && + matches(symbol, segments[count - 1]!.role) && parentsMatch(symbol, count - 1)) + if (modules.length > 1) return undefined + const alias = modules[0] + if (!alias) continue + if (aliases.has(alias.id)) return undefined + const suffix = target.split('.').slice(count).join('.') + return this.resolveOdoc(`${alias.exportedFrom}.${suffix}`, role, undefined, new Set([...aliases, alias.id])) + } + } + return undefined + } + private resolveSymbol(target: string, role: string, context?: ApiSymbol): LinkTarget | undefined { + if (this.lang === 'perl' && target.includes('#')) { + const separator = target.indexOf('#') + const owner = this.byDeclared.get(target.slice(0, separator)) + let section: string + try { section = decodeURIComponent(target.slice(separator + 1)) } catch { return undefined } + if (!owner || docSectionTitles(owner).filter((title) => title === section).length !== 1) return undefined + return { href: `${this.hrefFor(owner).split('#')[0]}#${encodeURIComponent(docSectionId(owner, section))}`, external: false, symbol: owner } + } + if (this.lang === 'erlang') return this.resolveErlang(target, role, context) const relative = target.startsWith('.') const goType = this.lang === 'go' && role === 'class' if (this.lang === 'ruby') { @@ -948,6 +1035,25 @@ export class SymbolIndex { return undefined } + /** Resolve compiler-qualified Erlang identities within the native namespace. */ + private resolveErlang(target: string, role: string, context?: ApiSymbol): LinkTarget | undefined { + const prefix = /^(?:([mtc]):)?/.exec(target)![1] + const body = prefix ? target.slice(2) : target + const wanted = prefix === 'm' ? body : target + const kinds = ROLE_KINDS[role] ?? [] + const matches = (symbol: ApiSymbol | undefined) => symbol && + (!kinds.length || kinds.includes(symbol.kind)) && + (prefix === 'm' ? symbol.kind === 'module' : prefix === 't' ? symbol.kind === 'typealias' + : prefix === 'c' ? symbol.modifiers.includes('abstract') : !symbol.id.startsWith('t:') && !symbol.id.startsWith('c:')) + let hit = this.byDeclared.get(wanted) + if (!matches(hit) && prefix !== 'm') { + let owner = context + while (owner?.parent) owner = this.byDeclared.get(owner.parent) + if (owner?.kind === 'module') hit = this.byDeclared.get(`${prefix ? `${prefix}:` : ''}${owner.id}:${body}`) + } + return matches(hit) ? { href: this.hrefFor(hit!), external: false, symbol: hit } : undefined + } + /** The module a declaration belongs to: itself, or its parent. */ private elixirOwner(context?: ApiSymbol): ApiSymbol | undefined { return context?.parent ? this.byDeclared.get(context.parent) : context @@ -1083,6 +1189,7 @@ export class SymbolIndex { linkDoc(spans: DocSpan[], context?: ApiSymbol): (DocSpan & { link?: LinkTarget })[] { return spans.map((span) => { + if (span.kind === 'link' && this.docHref) return { ...span, href: this.docHref(span.href) } if (span.kind !== 'ref') return span const resolved = this.resolve(span.target, span.role, context) const lone = /^([A-Za-z_$][\w$]*)(\(.*\))?$/s.exec(span.target) @@ -1330,6 +1437,61 @@ export class SymbolIndex { return [{ text: ident, ...(builtin ? { link: { href: builtin, external: true } } : {}) }] } + /** Consume exact compiler ranges; literal gaps never introduce a guessed type. */ + private erlangTypeSpans(annotation: string, context?: ApiSymbol, signature?: Signature): TypeSpan[] { + const candidates = (signature ? [signature] : context?.signatures ?? []).flatMap((entry) => [ + { text: entry.raw, references: entry.references }, + { text: entry.returns, references: entry.returnsReferences }, + ...entry.params.map((param) => ({ text: param.type, references: param.typeReferences })), + ]) + const match = candidates.find((entry) => entry.text === annotation && entry.references !== undefined) + if (!match) return [{ text: annotation }] + const out: TypeSpan[] = [] + let offset = 0 + for (const reference of match.references!) { + if (reference.start > offset) out.push({ text: annotation.slice(offset, reference.start), nonReference: true }) + const link = this.resolveErlang(reference.target, 'any', context) ?? + (reference.external ? { ...reference.external, external: true } : undefined) + out.push({ text: annotation.slice(reference.start, reference.end), ...(link ? { link } : {}) }) + offset = reference.end + } + if (offset < annotation.length) out.push({ text: annotation.slice(offset), nonReference: true }) + return out + } + + + /** Lisp names include package colons and hyphens; only method specializers are type references in a lambda list. */ + private lispType(annotation: string, context?: ApiSymbol, signature?: Signature): TypeSpan[] { + if (!annotation.trimStart().startsWith('(')) { + const text = annotation.trim() + const link = /^[^\s()"]+$/.test(text) ? this.resolveSymbol(text, 'class', context) : undefined + return [{ text: annotation, ...(link ? { link } : {}) }] + } + const frames: { atoms: number; parameter?: Param }[] = [] + const out: TypeSpan[] = [] + for (const match of annotation.matchAll(/"(?:\\[\s\S]|[^"\\])*"|[()]|[^\s()"]+|\s+/g)) { + const text = match[0] + if (text === '(') { frames.push({ atoms: 0 }); out.push({ text }); continue } + if (text === ')') { frames.pop(); out.push({ text }); continue } + const frame = frames.at(-1) + if (!frame || /^\s|^"/.test(text)) { out.push({ text }); continue } + const at = frame.atoms++ + const parameter = signature?.params.find((param) => param.name === text) + if (frames.length === 1 && at === 0) { + out.push({ text, declaration: true }) + } else if (parameter && (frames.length === 1 || frames.length === 2 && at === 0)) { + if (frames.length === 2) frame.parameter = parameter + out.push({ text, declaration: true }) + } else if (frames.length === 2 && at === 1 && frame.parameter?.type === text && + !frame.parameter.optional && !frame.parameter.variadic) { + out.push({ text, link: this.resolveSymbol(text, 'class', context) }) + } else { + out.push({ text, ...(/^[:&]/.test(text) ? { keyword: true } : {}) }) + } + } + return out + } + /** * Split a type annotation into linked and literal spans. * @@ -1340,7 +1502,9 @@ export class SymbolIndex { * makes those all work without a grammar for type syntax. */ linkType(annotation: string, context?: ApiSymbol, signature?: Signature): TypeSpan[] { + if (this.lang === 'erlang') return this.erlangTypeSpans(annotation, context, signature) if (neverLinks(annotation)) return [{ text: annotation }] + if (this.lang === 'lisp') return this.lispType(annotation, context, signature) const out: TypeSpan[] = [] const rustPayload = this.lang === 'rs' && (context?.variant || (context?.parent && this.byDeclared.get(context.parent)?.variant)) const variantDelimiters: string[] = [] @@ -1360,6 +1524,7 @@ export class SymbolIndex { ? String.raw`[A-Za-z_][A-Za-z0-9_]*(?:\.[A-Za-z_][A-Za-z0-9_]*)*!?` // A number is matched whole, so `1_000` is not a literal followed by a name. : this.lang === 'elixir' ? String.raw`\d[\d_]*(?:\.\d+)?(?:[eE][+-]?\d+)?|[A-Za-z_][A-Za-z0-9_]*(?:\.[A-Za-z_][A-Za-z0-9_]*)*[!?]?` + : this.lang === 'clojure' ? String.raw`::?[^\s,()[\]{}"';]+|[A-Za-z_][A-Za-z0-9_.]*(?:::[A-Za-z_][A-Za-z0-9_.]*)*` : this.lang === 'powershell' ? String.raw`(?:[A-Za-z_][A-Za-z0-9_.]*\\)?[A-Za-z_][A-Za-z0-9_.-]*` : this.lang === 'ts' ? String.raw`[A-Za-z_$][A-Za-z0-9_$.]*` : this.lang === 'rs' ? String.raw`(?:r#)?[A-Za-z_][A-Za-z0-9_.]*(?:::(?:r#)?[A-Za-z_][A-Za-z0-9_.]*)*` @@ -1367,12 +1532,12 @@ export class SymbolIndex { // C++ prefixes, escaped quotes, raw delimiters and suffixes belong to the // literal token. Its contents cannot introduce an attribute or type link. const cppLiteral = String.raw`(?:(?:u8|u|U|L)?R"(?[^ ()\\\t\v\f\r\n]{0,16})\([\s\S]*?\)\k"|(?:u8|u|U|L)?(?:"(?:\\[\s\S]|[^"\\])*"|'(?:\\[\s\S]|[^'\\])*'))(?:[A-Za-z_]\w*)?` - const initial = this.lang === 'ts' ? 'A-Za-z_$' : this.lang === 'elixir' ? 'A-Za-z_0-9' : 'A-Za-z_' - const pattern = String.raw`(?\/\*[\s\S]*?\*\/|\/\/[^\n]*|"(?:\\[\s\S]|[^"\\])*"|'(?:\\[\s\S]|[^'\\])*'|${identifier})|(?[^${initial}"'/]+|["'/])` + const initial = this.lang === 'ts' ? 'A-Za-z_$' : this.lang === 'elixir' ? 'A-Za-z_0-9' : this.lang === 'clojure' ? 'A-Za-z_:' : 'A-Za-z_' + const pattern = String.raw`(?\/\*[\s\S]*?\*\/|\/\/[^\n]*|"(?:\\[\s\S]|[^"\\])*"|'(?:\\[\s\S]|[^'\\])*'|${identifier})|(?[^${initial}"'/]+|["'/${this.lang === 'clojure' ? ':' : ''}])` // F# type variables start with an apostrophe but do not close like strings. const re = new RegExp(this.lang === 'cxx' ? String.raw`(?${cppLiteral}|\d(?:[eEpP][+-]|[\w.'])*)|(?\/\*[\s\S]*?\*\/|\/\/[^\n]*|${identifier})|(?[^A-Za-z_0-9"'/]+|["'/])` - : this.lang === 'fsharp' ? pattern.replace('(?', String.raw`(?'[A-Za-z_][A-Za-z0-9_]*(?![A-Za-z0-9_'])|`) + : this.lang === 'fsharp' || this.lang === 'ocaml' ? pattern.replace('(?', String.raw`(?'[A-Za-z_][A-Za-z0-9_]*(?![A-Za-z0-9_'])|`) : pattern, 'g') for (const m of annotation.matchAll(re)) { const whole = m[0] @@ -1387,6 +1552,11 @@ export class SymbolIndex { out.push({ text: whole }) continue } + // Keywords are values, including a namespaced key inside a map. + if (this.lang === 'clojure' && ident.startsWith(':')) { + out.push({ text: ident, nonReference: true }) + continue + } if (/^(?:["']|\/[/*])/.test(ident)) { out.push({ text: ident }) continue @@ -1534,7 +1704,15 @@ export class SymbolIndex { // renders unlinked in a signature is a builtin — `bool`, `Task`, // `Result`, `string` — which nothing here defines and no intersphinx // inventory covers for five of the eight ports. - const link = this.resolveSymbol(path, 'class', context) + let link = this.lang === 'ocaml' + ? /^[A-Z]/.test(path.split('.').at(-1)!) + ? this.resolveOdoc(path, 'module', context) ?? this.resolveOdoc(path, 'module-type', context) + : this.resolveOdoc(path, 'type', context) + : this.resolveSymbol(path, 'class', context) + if (!link && this.lang === 'ocaml') { + const href = builtinHref('ocaml', path) + if (href) link = { href, external: true } + } if (link || !['kotlin', 'scala'].includes(this.lang ?? '') || !ident.includes('.')) { out.push({ text: ident, link }) continue diff --git a/packages/api-model/src/member-order.ts b/packages/api-model/src/member-order.ts index 4b37a0513..024d8e818 100644 --- a/packages/api-model/src/member-order.ts +++ b/packages/api-model/src/member-order.ts @@ -182,6 +182,7 @@ const bareName = (s: ApiSymbol) => .replace(/\(.*$/, '') .replace(/\/\d+$/, '') .replace(/Async$/, '') + .replace(/[!?]$/, '') .toLowerCase() export function memberTier(s: ApiSymbol, signals: MemberSignals): MemberTier { diff --git a/packages/api-model/src/mentions.ts b/packages/api-model/src/mentions.ts index f93be1085..aee95e4e1 100644 --- a/packages/api-model/src/mentions.ts +++ b/packages/api-model/src/mentions.ts @@ -1,6 +1,6 @@ import { fromMarkdown } from 'mdast-util-from-markdown' import type { ApiModel, ApiProduct } from './model.ts' -import { decideMention, isLikelyReference, looksLikeApiMention, notApiReason } from './prose.ts' +import { decideMention, isLikelyReference, looksLikeApiMention, notApiReason, portFromSentence } from './prose.ts' import { notASymbol, type Resolver } from './resolver.ts' export { looksLikeApiMention } from './prose.ts' @@ -94,6 +94,8 @@ const FENCE_PORT: Record = { cpp: 'cxx', 'c++': 'cxx', swift: 'swift', powershell: 'powershell', pwsh: 'powershell', ps1: 'powershell', julia: 'julia', elixir: 'elixir', ex: 'elixir', exs: 'elixir', + perl: 'perl', pl: 'perl', pm: 'perl', + lisp: 'lisp', 'common-lisp': 'lisp', } /** A symbol that a link on a page names. */ @@ -192,8 +194,9 @@ export function pageMentions(input: PageMentionsInput): { targets: LinkedOwner[] const linkedHere = new LinkedOwners() for (const { port: contextPort, text, line, before, linked, href } of proseMentions(input.body, input.portByLabel, input.portAt)) { const pagePort = authoredPort ?? contextPort + const effectivePort = portFromSentence(before) ?? pagePort if (!linked && nativeTmux) continue - if (notASymbol(text)) continue + if (notASymbol(text, effectivePort)) continue let target: LinkedOwner | undefined if (linked) { target = input.authoredTarget(href) @@ -204,8 +207,8 @@ export function pageMentions(input: PageMentionsInput): { targets: LinkedOwner[] const authored = decision.kind === 'unresolved' ? linkedHere.recur(contextPort, text) : undefined if (!authored && decision.kind === 'unresolved' && pagePort && ownedByPrecedingType(text, before, pagePort, resolver, product)) continue if (!authored) { - if (decision.kind === 'unresolved' && pagePort && isLikelyReference(text) && !notApiReason(text)) { - dangling.push({ port: pagePort, text, page, line, why: decision.why }) + if (decision.kind === 'unresolved' && effectivePort && isLikelyReference(text) && !notApiReason(text, effectivePort)) { + dangling.push({ port: effectivePort, text, page, line, why: decision.why }) } continue } diff --git a/packages/api-model/src/model.ts b/packages/api-model/src/model.ts index 7ebbdd9c4..9ade56f16 100644 --- a/packages/api-model/src/model.ts +++ b/packages/api-model/src/model.ts @@ -14,7 +14,7 @@ */ /** Language libraries, by the slug the site uses. */ -export type PortSlug = 'py' | 'ruby' | 'lua' | 'ts' | 'rs' | 'go' | 'java' | 'csharp' | 'cxx' | 'swift' | 'kotlin' | 'scala' | 'fsharp' | 'powershell' | 'julia' | 'elixir' +export type PortSlug = 'perl' | 'py' | 'ruby' | 'lua' | 'ts' | 'rs' | 'go' | 'java' | 'csharp' | 'cxx' | 'swift' | 'kotlin' | 'scala' | 'fsharp' | 'powershell' | 'julia' | 'elixir' | 'ocaml' | 'haskell' | 'clojure' | 'lisp' | 'erlang' export type ApiProduct = 'core' | 'workspace' | 'mcp' @@ -80,11 +80,22 @@ export type Modifier = | 'unsafe' | 'annotation' +/** A compiler-resolved name in exact annotation text; offsets use UTF-16 code units. */ +export interface TypeReference { + start: number + end: number + /** Native symbol identity, including its namespace and arity where applicable. */ + target: string + /** A provider-validated canonical language-library destination. */ + external?: { href: string; project: string } +} + /** One parameter, as written. */ export interface Param { name: string /** Type annotation verbatim from the source, unresolved. */ type?: string + typeReferences?: TypeReference[] /** Default value verbatim, when one is written. */ default?: string /** The caller may omit the parameter without supplying a default. */ @@ -169,12 +180,27 @@ export interface Signature { extension?: string /** Native signature text when its grammar carries more than the shared fields. */ raw?: string + /** Native header text and links, in order. Their text concatenates exactly to `raw`. */ + nativeSpans?: { + text: string + /** Original native destination, retained even when a public target is remapped. */ + href?: string + /** Public identity resolved by the native producer. */ + target?: string + declaration?: boolean + keyword?: boolean + }[] + /** Native producer offsets into raw declaration text; no renderer reparsing. */ + nativeSyntax?: ({ start: number; end: number; kind: 'name' } | { start: number; end: number; kind: 'parameter'; parameter: number })[] + /** References into `raw`, supplied by the native compiler rather than inferred from spelling. */ + references?: TypeReference[] /** Native impl or trait header that owns this callable, without its body. */ enclosingDeclaration?: string /** Lexical bindings from that impl or trait, separate from callable generics. */ enclosingTypeParamNames?: string[] params: Param[] returns?: string + returnsReferences?: TypeReference[] returnsDoc?: string /** Type parameters / generics, as written: `T`, `T: Clone`, ``. */ typeParams?: string[] @@ -282,6 +308,8 @@ export interface ApiSymbol { variant?: 'unit' | 'tuple' | 'struct' /** Distinct native declarations sharing one public name, such as a TypeScript type/value pair. */ declarations?: { kind: SymbolKind; text: string; source: ApiSymbol['source']; doc?: DocBlock }[] + /** Original native comments; doc holds their normalized rendered content. */ + nativeDocumentation?: string[] /** Explicit source imports used to resolve aliases in native signatures. */ imports?: Record /** Relationships resolved by the native documentation producer. */ @@ -350,6 +378,8 @@ export interface ApiSymbol { /** Everything extracted from one port's source tree. */ /** Declarations and provenance shared by library and source references. */ export interface ApiModelBase { + /** Native module export groups, in authored order, with exact public identities. */ + exportGroups?: { owner: string; title: string; members: string[] }[] /** Native producer and inputs retained alongside the normalized surface. */ nativeProvenance?: { files: { path: string; sha256: string }[] diff --git a/packages/api-model/src/nav-config.ts b/packages/api-model/src/nav-config.ts index 5ed414cd3..417990d53 100644 --- a/packages/api-model/src/nav-config.ts +++ b/packages/api-model/src/nav-config.ts @@ -584,6 +584,14 @@ const OVERRIDES: Record }> = { 'LibTmux.Base.show': 'one display extension page shared by IDs, servers, snapshots, control connections and observation streams', }, }, + lisp: { + unsettled: { + libtmux: 'public package spanning the task buckets; its exported declarations have their own placements', + 'libtmux.json': 'optional interchange package; its exported declarations sit under Formats and Errors', + 'libtmux.workspace': 'workspace package spanning plans, steps, errors and operations', + 'libtmux.workspace.cli': 'workspace command package; MAIN has its own placement', + }, + }, lua: { unsettled: { 'libtmux.Configurable': 'options and hooks shared by sessions, windows and panes; the concrete handle is the subclass', @@ -597,6 +605,12 @@ const OVERRIDES: Record }> = { 'libtmux.Watch': 'watch handle shared by several tmux objects', }, }, + perl: { + unsettled: { + LibTmux: 'distribution namespace and version; concrete packages have their own placements', + 'LibTmux::Entity': 'shared captured-handle base; concrete entity packages own the tmux objects', + }, + }, ruby: { unsettled: { 'LibTmux::Entity': 'base of the tmux entity hierarchy; the concrete entity is the subclass', @@ -744,6 +758,25 @@ const OVERRIDES: Record }> = { /** Place language-specific public helpers with the task they support. */ const LANGUAGE_PLACEMENTS: Record> = { + ocaml: { + server: ['Libtmux_unix.Client', 'Libtmux_eio.Client', 'Libtmux.Endpoint', 'Libtmux.Generation', 'Libtmux.Source'], + snapshots: ['Libtmux.Snapshot', 'Libtmux.Captured_text', 'Libtmux_unix.Rendered', 'Libtmux_eio.Rendered'], + queries: ['Libtmux.Field', 'Libtmux.Relation', 'Libtmux.Expr', 'Libtmux.Query', 'Libtmux.Model', 'Libtmux.Cardinality', 'Libtmux.Plan', 'Libtmux_json.Expr'], + commands: ['Libtmux', 'Libtmux.ID', 'Libtmux.Created', 'Libtmux.Operations', 'Libtmux.Spawn'], + layout: ['Libtmux.Geometry'], + options: ['Libtmux.Options'], + errors: ['Libtmux_json.Decode_error', 'Libtmux_unix.Cleanup', 'Libtmux_eio.Cleanup'], + workspace: ['Libtmux_workspace', 'Libtmux_workspace.Config', 'Libtmux_workspace.Execution'], + runtime: ['Libtmux_unix', 'Libtmux_eio', 'Libtmux_json'], + control: ['Libtmux.Output', 'Libtmux_unix.Cancellation', 'Libtmux_unix.Operation', 'Libtmux_eio.Operation', 'Libtmux_unix.Subscription', 'Libtmux_eio.Subscription'], + }, + perl: { + queries: ['Schema', 'Selection', 'Selection::Iterator', 'PaneSelection', 'WindowSelection', + 'WindowLinkSelection', 'SessionSelection', 'ClientSelection'].map((name) => `LibTmux::${name}`), + commands: ['LibTmux::Operation'], + async: ['LibTmux::Async::Server', 'LibTmux::Async::Transport'], + errors: ['LibTmux::X', 'LibTmux::Async::X', 'LibTmux::Workspace::X'], + }, powershell: { commands: ['LibTmux\\Invoke-TmuxChain'], pane: ['LibTmux\\Send-TmuxText'], @@ -766,6 +799,23 @@ const LANGUAGE_PLACEMENTS: Record> = { errors: ['CrossServerReference', 'StaleReference', 'ObservationLost', 'UnsupportedCriterion', 'Base.showerror'] .map((name) => `LibTmux.${name}`).concat('LibTmuxWorkspace.Base.showerror'), }, + erlang: { + server: ['tmux_server'], + session: ['tmux_session'], + window: ['tmux_window', 'tmux_window_link'], + pane: ['tmux_pane'], + buffers: ['tmux_buffer'], + capabilities: ['tmux_capability'], + commands: ['tmux_command', 'tmux_operation', 'tmux_scope'], + control: ['tmux_control'], + queries: ['tmux_filter', 'tmux_matcher', 'tmux_schema', 'tmux_select', 'tmux_query', 'tmux_json'], + snapshots: ['tmux_model', 'tmux_identity', 'tmux_snapshot'], + hooks: ['tmux_hook'], + keys: ['tmux_key'], + options: ['tmux_option'], + version: ['tmux_version'], + errors: ['tmux_error'], + }, // Elixir's modules are named for what they do rather than for a tmux object. elixir: { queries: ['Selection', 'Schema', 'Wire'].map((name) => `LibTmux.${name}`), @@ -774,10 +824,33 @@ const LANGUAGE_PLACEMENTS: Record> = { control: ['LibTmux.Protocol'], snapshots: ['LibTmux.Ref'], }, + lisp: { + server: ['libtmux:client', 'libtmux:daemon'], + session: ['libtmux:session/type'], + window: ['libtmux:window/type', 'libtmux:window-link'], + pane: ['libtmux:pane', 'libtmux:clear-history', 'libtmux:copy-mode', 'libtmux:current-path', + 'libtmux:dead-p'], + client: ['libtmux:attached-client'], + keys: ['libtmux:send-prefix', 'libtmux:send-text'], + layout: ['libtmux:height', 'libtmux:width'], + formats: ['libtmux.json:document-limit', 'libtmux.json:document-path', 'libtmux:display-message'], + control: ['libtmux:wait-for'], + snapshots: ['libtmux:active-p', 'libtmux:entity', 'libtmux:entity-data', 'libtmux:entity-model', + 'libtmux:id', 'libtmux:index', 'libtmux:name', 'libtmux:provenance', 'libtmux:refresh', + 'libtmux:same-entity-p', 'libtmux:snapshot', 'libtmux:title'], + workspace: ['libtmux.workspace:workspace', 'libtmux.workspace:workspace-plan', + 'libtmux.workspace:workspace-result', 'libtmux.workspace:workspace-step', + 'libtmux.workspace.cli:main'], + }, java: { commands: ['MessageLog', 'PrintedText', 'Prompt', 'Shell'].map((name) => `io.github.libtmux.${name}.${name}`), server: ['io.github.libtmux.IncarnationFence.IncarnationFence'], }, + clojure: { + server: ['libtmux.core'], + snapshots: ['libtmux.data'], + async: ['libtmux.async', 'libtmux.core-async'], + }, kotlin: { commands: ['Batch', 'ExecutionPolicy', 'MessageLog', 'Prompt', 'Shell', 'retryIfSafe'].map((name) => `io.github.libtmux.kotlin.${name}`), server: ['io.github.libtmux.kotlin.LibTmuxDsl'], @@ -801,6 +874,7 @@ const LANGUAGE_PLACEMENTS: Record> = { /** Free functions and cmdlets need the same discovery-first order as object members. */ const LANGUAGE_ORDER: Record> = { + ocaml: { server: ['Libtmux_unix.Client', 'Libtmux_eio.Client', 'Libtmux.Endpoint', 'Libtmux.Source', 'Libtmux.Generation'] }, julia: Object.fromEntries(Object.entries({ server: ['Server', 'open_server', 'with_server', 'from_env', 'OwnedServer', 'ServerIdentity'], session: ['sessions', 'session', 'new_session', 'rename_session', 'kill_session', 'SessionRef', 'SessionID', 'SessionWhere'], @@ -854,7 +928,7 @@ function languageBucket(bucket: Bucket, port: string, root = bucket.id): Bucket } export const NAV: Record = Object.fromEntries( - ['powershell', 'julia', 'elixir', 'py', 'ruby', 'lua', 'ts', 'rs', 'go', 'java', 'kotlin', 'scala', 'fsharp', 'csharp', 'cxx', 'swift'].map((port) => [ + ['perl', 'powershell', 'julia', 'elixir', 'lisp', 'erlang', 'py', 'ruby', 'lua', 'ts', 'rs', 'go', 'java', 'clojure', 'kotlin', 'scala', 'fsharp', 'csharp', 'cxx', 'swift', 'ocaml'].map((port) => [ port, { port, diff --git a/packages/api-model/src/nav-sidecar.ts b/packages/api-model/src/nav-sidecar.ts index 3cb42f7fe..e76ca7691 100644 --- a/packages/api-model/src/nav-sidecar.ts +++ b/packages/api-model/src/nav-sidecar.ts @@ -28,6 +28,54 @@ export interface NavSidecarBucket { target?: { id: string; name: string; slug: string; kind: ApiSymbol['kind'] } } +/** Validate native export coverage before selecting sidebar candidates. */ +export function exportGroupsNav(model: ApiModelBase): NavConfig { + const groups = model.exportGroups + const fail = (reason: string): never => { throw new Error(`Invalid native export groups: ${reason}`) } + if (!Array.isArray(groups) || !groups.length) fail('no groups') + const byId = new Map(model.symbols.map((symbol) => [symbol.publicId ?? symbol.id, symbol])) + if (byId.size !== model.symbols.length || new Set(model.symbols.map((symbol) => symbol.id)).size !== model.symbols.length) { + fail('repeated declaration identity') + } + const publicSymbol = (symbol: ApiSymbol) => !symbol.apiScope || symbol.apiScope === 'exported' + const modules = new Map(model.symbols.filter((symbol) => symbol.kind === 'module' && publicSymbol(symbol)) + .map((symbol) => [symbol.id, symbol])) + const owners = new Map() + const members = new Set() + for (const group of groups!) { + if (!group || typeof group.owner !== 'string') fail('missing group owner') + const owner = byId.get(group.owner) + if (!owner || !modules.has(owner.id)) fail(`unknown or nonpublic module ${group.owner}`) + if (typeof group.title !== 'string' || !group.title.trim() || !Array.isArray(group.members) || !group.members.length) { + fail(`empty group in ${group.owner}`) + } + let bucket = owners.get(group.owner) + if (!bucket) { + bucket = { id: `exports:${encodeURIComponent(group.owner)}`, label: owner!.name, + match: { kind: 'id', is: group.owner }, order: [group.owner], children: [] } + owners.set(group.owner, bucket) + } + for (const id of group.members) { + const member = byId.get(id) + if (!member || member.parent !== owner!.id || !publicSymbol(member) || members.has(id)) { + fail(`unknown, repeated or nonpublic direct export ${id} in ${group.owner}`) + } + members.add(id) + } + bucket.children!.push({ id: `${bucket.id}:${bucket.children!.length}`, label: group.title, + match: { kind: 'id', is: [...group.members] }, order: [...group.members] }) + } + for (const symbol of model.symbols) { + if (symbol.kind === 'module' && publicSymbol(symbol) && !owners.has(symbol.publicId ?? symbol.id)) { + fail(`module has no groups: ${symbol.id}`) + } + if (symbol.parent && modules.has(symbol.parent) && publicSymbol(symbol) && !members.has(symbol.publicId ?? symbol.id)) { + fail(`direct export has no group: ${symbol.id}`) + } + } + return { buckets: [...owners.values()] } +} + /** * A port's compiled sidebar, exactly as `.nav.json` holds it. * @@ -38,18 +86,23 @@ export interface NavSidecarBucket { * `gen-api-model.mjs --nav` writes this and `check-nav.mjs` compares it. */ export function navSidecar(port: string, model: ApiModel) { - const nav = NAV[port] + const nav = model.exportGroups || port === 'haskell' ? exportGroupsNav(model) : NAV[port] if (!nav) return undefined return navSidecarFor(port, model, nav) } /** Compile the same navigation contract for an explicitly supplied catalog. */ export function navSidecarFor(scope: string, model: ApiModelBase, nav: NavConfig) { + if (model.exportGroups || scope === 'haskell') exportGroupsNav(model) // Every top-level symbol, not only the types: a free function, constant or // type alias has a page, and a sidebar that placed only types gave 1,282 of // those pages no row. const moduleIds = new Set(model.symbols.filter((symbol) => symbol.kind === 'module').map((symbol) => symbol.id)) - const topLevel = model.symbols.filter((s) => !s.parent || (['powershell', 'julia'].includes(scope) && moduleIds.has(s.parent))) + const roots = new Set(model.symbols.filter((symbol) => !symbol.parent).map((symbol) => symbol.id)) + const topLevel = model.symbols.filter((s) => + (!model.exportGroups || !s.apiScope || s.apiScope === 'exported') && + (!s.parent || (scope === 'ocaml' && roots.has(s.parent)) || + ((model.exportGroups || ['powershell', 'julia', 'lisp'].includes(scope)) && moduleIds.has(s.parent)))) const conceptIds = Object.fromEntries( Object.entries(CONCEPTS) .map(([k, c]) => [k, c.symbols[scope]] as const) diff --git a/packages/api-model/src/parser.ts b/packages/api-model/src/parser.ts index 2fec1d696..90a8e071f 100644 --- a/packages/api-model/src/parser.ts +++ b/packages/api-model/src/parser.ts @@ -8,7 +8,7 @@ import { Language, Parser } from 'web-tree-sitter' * prebuilt WASM in `tree-sitter-wasms` is ABI 13-14; runtime 0.26 and 0.27 * both reject it, and 0.27 does so by throwing a bare `Error` with no message * from inside `getDylinkMetadata` — which reads like a corrupt file rather - * than a version mismatch. 0.25.10 loads all eight. The dependency is pinned + * than a version mismatch. 0.25.10 loads the pinned grammars. The dependency is pinned * exactly, not caret-ranged, for that reason. * * Prebuilt WASM rather than building grammars here: `tree-sitter build --wasm` @@ -33,6 +33,8 @@ const GRAMMAR = { scala: 'scala', ruby: 'ruby', lua: 'lua', + ocaml: 'ocaml', + haskell: 'haskell', } as const export type GrammarName = keyof typeof GRAMMAR @@ -49,6 +51,7 @@ export async function loadLanguage(name: GrammarName): Promise { // The older bundle predates Scala 3 opaque types, givens, and extensions. const wasm = require.resolve(name === 'scala' ? 'tree-sitter-scala/tree-sitter-scala.wasm' + : name === 'haskell' ? 'tree-sitter-haskell/tree-sitter-haskell.wasm' : `tree-sitter-wasms/out/tree-sitter-${GRAMMAR[name]}.wasm`) const lang = await Language.load(wasm) cache.set(name, lang) diff --git a/packages/api-model/src/prose-fields.ts b/packages/api-model/src/prose-fields.ts index 988a36a2e..14ebc8f0e 100644 --- a/packages/api-model/src/prose-fields.ts +++ b/packages/api-model/src/prose-fields.ts @@ -50,17 +50,23 @@ export const STRUCTURAL_FIELDS: string[] = [ '.apiScope', '.exportedFrom', '.extends[]', '.id', '.inheritedFrom', '.kind', '.modifiers[]', '.name', '.namespace', '.namespaceImports[]', '.package', '.parent', '.product', '.publicId', '.publicOwner', '.qualifiedName', '.slug', '.value', '.variant', '.type', '.imports.*', '.source.*', + '.references[].kind', '.references[].target', // Types and signatures, which are linked as types. '.typeParamNames[]', '.typeParams[]', '.typeParameters[].bound', '.typeParameters[].default', '.typeParameters[].kind', '.typeParameters[].modifier', '.typeParameters[].name', '.signatures[].enclosingDeclaration', '.signatures[].enclosingTypeParamNames[]', '.signatures[].extension', '.signatures[].identity', '.signatures[].label', '.signatures[].methodKind', '.signatures[].raw', '.signatures[].returns', + '.signatures[].nativeSpans[].text', '.signatures[].nativeSpans[].href', '.signatures[].nativeSpans[].target', + '.signatures[].nativeSyntax[].kind', '.signatures[].source.*', '.signatures[].typeParamNames[]', '.signatures[].typeParams[]', '.signatures[].typeParameters[].bound', '.signatures[].typeParameters[].default', '.signatures[].typeParameters[].kind', '.signatures[].typeParameters[].modifier', '.signatures[].typeParameters[].name', '.signatures[].receiver.*', '.signatures[].raises[].type', '.signatures[].params[].name', '.signatures[].params[].type', '.signatures[].params[].default', '.signatures[].params[].variadic', '.signatures[].params[].since', '.signatures[].params[].deprecated', + '.signatures[].references[].target', '.signatures[].references[].external.*', + '.signatures[].returnsReferences[].target', '.signatures[].returnsReferences[].external.*', + '.signatures[].params[].typeReferences[].target', '.signatures[].params[].typeReferences[].external.*', // A command's facts and a parameter's binding are written into prose by `commandFacts` and `parameterBindingText`. '.command.confirmImpact', '.command.defaultParameterSet', '.command.kind', '.command.outputTypes[]', '.command.inputTypes[].type', '.command.inputTypes[].description', '.command.relatedLinks[].*', @@ -73,6 +79,8 @@ export const STRUCTURAL_FIELDS: string[] = [ '.doc.admonitions[].kind', '.doc.references[].name', '.doc.since', '.doc.examples[].code', '.doc.examples[].lang', '.doc.examples[].sourceUrl', // Extracted, and rendered by no component. + // OCaml's original odoc comments are provenance; `.doc` holds their rendered prose. + '.nativeDocumentation[]', '.doc.seeAlso[]', '.declarations[].*', '.declarations[].doc.*', '.declarations[].source.*', ] diff --git a/packages/api-model/src/prose.ts b/packages/api-model/src/prose.ts index f7486aab9..2625cb3e0 100644 --- a/packages/api-model/src/prose.ts +++ b/packages/api-model/src/prose.ts @@ -16,11 +16,14 @@ import { neverLinks } from './never-links.ts' */ export const PORT_NAME: Record = { + ocaml: 'OCaml', py: 'Python', + perl: 'Perl', ts: 'TypeScript', rs: 'Rust', go: 'Go', java: 'Java', + clojure: 'Clojure', csharp: 'C#', cxx: 'C++', swift: 'Swift', @@ -32,6 +35,8 @@ export const PORT_NAME: Record = { powershell: 'PowerShell', julia: 'Julia', elixir: 'Elixir', + haskell: 'Haskell', + lisp: 'Common Lisp', } /** Declarations that own a page of members. */ @@ -137,7 +142,7 @@ export function looksLikeApiMention(text: string): boolean { if (/^(?:[\w.]+\\)?[A-Z][A-Za-z]+-[A-Za-z][\w]*$/.test(t)) return true // `wait_for`, `capture_pane`, `activeWindow`: an identifier, admitted as a // candidate for the resolver to accept or reject. - return /^@?[a-z_][A-Za-z0-9_]*!?$/.test(t) + return /^@?[a-z_][A-Za-z0-9_-]*!?$/.test(t) } /** @@ -228,6 +233,7 @@ const NOT_API: { why: string; test: RegExp }[] = [ { why: 'call with arguments', test: /\([^)]*[\s:][^)]*\)/ }, // A YAML key or a doc marker: `environment:`, `docs:watching`. { why: 'configuration key', test: /:$|^[a-z]+:[a-z]/ }, + { why: 'Cabal project file', test: /^cabal\.project$/ }, // A fragment beginning with the separator — `.filter()`, `.gt(...)` — names // a method without its receiver, so there is nothing to resolve against. { why: 'method without a receiver', test: /^[.:]/ }, @@ -238,9 +244,12 @@ const NOT_API: { why: string; test: RegExp }[] = [ ] /** Why this span is not an API reference, or undefined if it might be. */ -export function notApiReason(text: string): string | undefined { +export function notApiReason(text: string, port?: string): string | undefined { const t = text.trim() - for (const { why, test } of NOT_API) if (test.test(t)) return why + for (const { why, test } of NOT_API) { + if (port === 'lisp' && why === 'configuration key' && /^libtmux(?:\.[\w-]+)*:[\w-]+$/.test(t)) continue + if (test.test(t)) return why + } return undefined } @@ -254,7 +263,9 @@ export function notApiReason(text: string): string | undefined { export function notApiInContext(text: string, before: string | undefined): string | undefined { const t = text.trim() const sentence = (before ?? '').split(/(?<=[.!?])\s+(?=[A-Z])/).pop() ?? '' - if (/^[A-Z][A-Za-z0-9]*$/.test(t) && /\bkey\s+names?\s+(?:such as|like|including)\b/i.test(sentence)) return 'tmux key name' + const keyNames = /\b(?:key\s+names?\s+(?:such as|like|including)|tmux\s+recognizes\s+names?\s+such as)\b/i.test(sentence) + if (/^[A-Z][A-Za-z0-9]*$/.test(t) && (keyNames || (t === 'Enter' && /\bsend-keys\b/.test(sentence)))) return 'tmux key name' + if (/^[A-Z][A-Za-z0-9]*$/.test(t) && /\b(?:typ(?:e|es|ing)\s+the\s+word|(?:screen|output)\s+contains)\s*$/i.test(sentence)) return 'literal text' if (/^[a-z_]\w*(?:\.[a-z_]\w*)+$/.test(t) && /\bjson\b/i.test(sentence)) return 'field of JSON output' return undefined } @@ -305,6 +316,10 @@ export function decideMention( if (!looksLikeApiMention(text)) return { kind: 'skip', why: 'not a mention' } const never = neverLinks(text) if (never) return { kind: 'skip', why: never } + // Tools.deps names a package with a slash; only registered coordinates are packages, not vars. + if (ctx.pagePort === 'clojure' && models.clojure?.sources?.some((source) => source.package.replace(':', '/') === text)) { + return { kind: 'skip', why: 'a dependency coordinate' } + } const link = (port: string, res: ReturnType): MentionDecision | undefined => { if (res.how === 'federated') { diff --git a/packages/api-model/src/reference.ts b/packages/api-model/src/reference.ts new file mode 100644 index 000000000..01b704134 --- /dev/null +++ b/packages/api-model/src/reference.ts @@ -0,0 +1,26 @@ +/** Model, linking and navigation for readers; native extraction stays in the author entry. */ +export * from './model.ts' +export * from './doc/prose-blocks.ts' +export { sourceUrl, symbolsForProduct } from './products.ts' +export { SymbolIndex, keywordArgument, parameterId, typeParameterId, type LinkTarget, type KeywordHelp, type TypeParameterBinding } from './link.ts' +export { boundLabel, parseTypeParameter, parseTypeParameters, typeParameterList, typeParametersOf, withTypeParameterDocs } from './type-params.ts' +export { tokenizeDoc, docSummaryText, referencesIn, type DocSpan } from './doc/roles.ts' +export { parsePythonDoc } from './doc/python.ts' +export { writeInventory, writeInventoryEntries, readInventory, inventoryType, isSymbolEntry, symbolEntries, NON_SYMBOL_ROLES, type InventoryEntry } from './inventory.ts' +export { targetKey, targetEntries, compatibilityEntries, type InventoryTarget } from './targets.ts' +export { Resolver, notASymbol, toPath, DEFAULT_TEMPLATES, DEFAULT_PRIMARY_MODULES } from './resolver.ts' +export type { Resolution, UrlTemplate } from './resolver.ts' +export { qualifiedNameOf, moduleOf, modulesIn } from './modules.ts' +export { CONCEPTS, conceptsFor, type Concept } from './concepts.ts' +export { PROSE_FIELDS, RENDERED_TEXTS, STRUCTURAL_FIELDS, commandFacts, conceptNotes, isProseField, isStructuralField, parameterBindingFacts, parameterBindingText, proseTexts, stringFields, unclassifiedFields, type ProseForm, type ProseText } from './prose-fields.ts' +export { neverLinks } from './never-links.ts' +export { looksLikeApiMention, tableMentions, proseMentions, pageMentions, LinkedOwners, type TableMention, type ProseMention, type LinkedOwner, type DanglingMention, type PageMentionsInput } from './mentions.ts' +export { parseHunks, mapLine, type Hunk } from './source-lines.ts' +export * from './prose.ts' +export { BUILTINS, builtinHref } from './builtins.ts' +export { cargoFeatureHref } from './cargo-features.ts' +export * from './nav.ts' +export { NAV } from './nav-config.ts' +export { MEMBER_TIERS, memberSignals, memberTier, compareMembers, membersOf, pageMembersOf, aliasTarget, aliasMembersTarget, type MemberSignals, type MemberTier } from './member-order.ts' +export { parentInventory } from './parent-inventory.ts' +export { navSidecarFor, type NavConfig } from './nav-sidecar.ts' diff --git a/packages/api-model/src/resolver.ts b/packages/api-model/src/resolver.ts index 676e2b52d..4877124fc 100644 --- a/packages/api-model/src/resolver.ts +++ b/packages/api-model/src/resolver.ts @@ -76,6 +76,8 @@ export const DEFAULT_PRIMARY_MODULES: Record = { powershell: 'LibTmux', julia: 'LibTmux', elixir: 'LibTmux', + perl: 'LibTmux', + lisp: 'libtmux', } export const DEFAULT_TEMPLATES: UrlTemplate[] = [ @@ -97,17 +99,27 @@ export const DEFAULT_TEMPLATES: UrlTemplate[] = [ * spikes gained zero. A denominator full of things that can never resolve * makes a resolver look worse than it is and hides the failures that matter. */ -export function notASymbol(text: string): string | undefined { +export function notASymbol(text: string, port?: string): string | undefined { + if (/^libtmux\.docs\.(?:socket|binary)$/.test(text)) return 'an example fixture system property' if (/^[a-z][a-z0-9+.-]*:\/\//i.test(text)) return 'a protocol URI' if (/^(?:net|v)?\d+\.\d+(?:\.\d+)?(?:[a-z]|[-+][\w.-]+)?$/.test(text)) return 'a version' if (/^(?:net|v)?\d+(?:\.\d+)*\.[xXnN]$/.test(text)) return 'a version line' // `X.Y` stands for a release number and `X.Y-rcN` for one of its candidates. if (/^v?[XYZ](?:\.[XYZ])+(?:-[a-z]+N)?$/.test(text)) return 'a version placeholder' - if (/^\w+(?:\.\w+)+:[\w.-]+(?::[\w.<>{}-]+)?$/.test(text)) return 'a dependency coordinate' + if (port !== 'lisp' && /^\w+(?:\.\w+)+:[\w.-]+(?::[\w.<>{}-]+)?$/.test(text)) return 'a dependency coordinate' // `objects.inv` is the published Sphinx inventory, named by the setup guides next to a Python fence. - if (/\.(?:tsv|html|inv)$/.test(text)) return 'a filename' - if (/\.(py|ts|go|rs|java|kt|kts|scala|cs|fs|fsi|fsproj|properties|cpp|hpp|c|h|lua|rb|swift|jl|exs?|ps1|psm1|psd1|md|json|ya?ml|toml|sh)\b/.test(text)) return 'a filename' + if (/\.(?:tsv|html|inv|lisp|asd|conf|sock|txt|gz)$/.test(text)) return 'a filename' + if (/\.(py|ts|go|rs|java|kt|kts|scala|cs|fs|fsi|fsproj|properties|cpp|hpp|c|h|lua|rb|swift|jl|exs?|ps1|psm1|psd1|ml|mli|opam|md|json|ya?ml|toml|sh)\b/.test(text)) return 'a filename' + if (/^[A-Za-z_][\w-]*:\d+$/.test(text)) return 'a numeric label' + // Erlang's rebar files and sources, and the getopt strings of the command capability tables: atoms and modules are lowercase. + if (port === 'erlang' && /\.(?:erl|hrl|config|lock)$/.test(text)) return 'a filename' + if (port === 'erlang' && /^[A-Za-z:]*[A-Z][A-Za-z:]*$/.test(text)) return 'a command option string' if (/(^|\s)--?[A-Za-z]/.test(text)) return 'a command-line flag' + if (/^[A-Z_][A-Z0-9_]*=/.test(text)) return 'an environment assignment' + if (/^(?:=[^:\s]+:[^\s]+|[\w-]+:\d+\.\d+)$/.test(text)) return 'a tmux target' + if (port === 'lisp' && /^[a-z][\w-]*(?:\.[\w-]+)+\/\d+$/.test(text)) return 'a versioned schema identifier' + if (text.startsWith('#(')) return 'a Lisp vector literal' + if (/^@\[[^\]]+\][+*?]?$/.test(text)) return 'a regular expression' if (/[=<>!]=|\s[=<>]\s/.test(text)) return 'an expression, not a reference' if (/^new\s/.test(text)) return 'a constructor call' if (/^\.{3}/.test(text)) return 'an ellipsis' @@ -274,7 +286,7 @@ export class Resolver { /** Resolve one mention within one port. */ resolve(port: string, text: string, product?: ApiProduct): Resolution { - const why = notASymbol(text) + const why = notASymbol(text, port) if (why) return { how: 'not-a-symbol', why } // Selector labels distinguish Swift methods from same-named properties. diff --git a/packages/api-model/test/builtins.test.ts b/packages/api-model/test/builtins.test.ts index 3d7ce1d7f..92c4addcf 100644 --- a/packages/api-model/test/builtins.test.ts +++ b/packages/api-model/test/builtins.test.ts @@ -92,6 +92,16 @@ describe('C++ standard references', () => { }) describe('standard types in product signatures', () => { + it('links the OCaml modules and sequence function used in native guides', () => { + const index = new SymbolIndex([], () => '#', 'ocaml') + for (const [name, page] of [['List', 'List.html'], ['Unix', 'Unix.html'], ['Seq.filter', 'Seq.html#VALfilter']]) { + expect(builtinHref('ocaml', name), name).toBe(`https://ocaml.org/manual/5.5/api/${page}`) + expect(index.resolve(name), name).toMatchObject({ href: `https://ocaml.org/manual/5.5/api/${page}`, external: true }) + expect(builtinHref('ts', name), name).toBeUndefined() + } + expect(index.resolve('Seq.invented')).toBeUndefined() + }) + it('links Scala Using.resource without losing the callee owner or expression', () => { const model = JSON.parse(readFileSync(new URL('../../../site/src/data/api/scala.json', import.meta.url), 'utf8')) as ApiModel const context = model.symbols.find((symbol) => symbol.id === 'io.github.libtmux.scaladsl.Server')! diff --git a/packages/api-model/test/clojure.test.ts b/packages/api-model/test/clojure.test.ts new file mode 100644 index 000000000..5e06fb27b --- /dev/null +++ b/packages/api-model/test/clojure.test.ts @@ -0,0 +1,118 @@ +import { describe, expect, it } from 'vitest' +import { extractClojure } from '../src/languages/clojure.ts' +import { attachCompleteClojureExamples } from '../src/languages/clojure-examples.ts' +import { SymbolIndex } from '../src/link.ts' + +const revision = '1'.repeat(40) +const repo = 'libtmux/libtmux-java' +const coordinate = 'io.github.libtmux:libtmux-clojure' +const location = (namespace: string) => ({ + file: `libtmux-clojure/src/main/clojure/${namespace.replaceAll('.', '/')}.clj`, + line: 1, revision, repo, +}) +const namespace = (name: string) => ({ + id: name, publicId: name, qualifiedName: name, name, namespace: name, publicOwner: name, + kind: 'module', modifiers: [], signatures: [{ raw: `(ns ${name})`, params: [] }], + package: coordinate, product: 'core', apiScope: 'exported', docstring: 'Captured operations.', source: location(name), +}) +const callable = (owner: string, name: string, arities: string[][], docstring = 'Owns a resource.') => ({ + ...namespace(owner), id: `${owner}/${name}`, publicId: `${owner}/${name}`, qualifiedName: `${owner}/${name}`, + parent: owner, name, kind: 'function', docstring, + modifiers: arities.length > 1 ? ['overload'] : [], + signatures: arities.map((params) => ({ raw: `(${name} ${params.join(' ')})`, params: params.map((name) => ({ name })) })), +}) +function artifact() { + return { + schema: 'libtmux.clojure-api/1', port: 'clojure', repo, revision, compiler: '1.12.6', + extractor: 'clojure-public-var-metadata/1', + sources: [{ product: 'core', package: coordinate, repo, revision, extractedRevision: revision, version: '0.1.2-SNAPSHOT' }], + nativeProvenance: { + files: ['core', 'control', 'data'].map((name) => ({ path: location(`libtmux.${name}`).file, sha256: 'a'.repeat(64) })), + exporter: { name: 'clojure-public-var-metadata', revision: `sha256:${'b'.repeat(64)}`, + files: [{ path: 'packages/api-model/scripts/export-clojure.clj', sha256: 'c'.repeat(64) }] }, + }, + symbols: [ + namespace('libtmux.core'), namespace('libtmux.control'), namespace('libtmux.data'), + callable('libtmux.core', 'close!', [['server']]), + callable('libtmux.control', 'close!', [['resource']], 'Closes the subscription.\nSee [[close!]] and [[libtmux.core/close!]]. `:signalled` is a value.'), + callable('libtmux.data', 'matching', [['expression'], ['expression', 'entries']]), + ], + } +} + +describe('compiled Clojure artifact', () => { + it('keeps keywords literal when their names match callable declarations', () => { + const input = artifact() + input.symbols.push(callable('libtmux.core', 'timeout', [['value']])) + const model = extractClojure(input, revision) + const index = new SymbolIndex(model.symbols, (symbol) => `/${symbol.id}/`, 'clojure') + for (const text of [':timeout', '::timeout', ':libtmux.core/timeout', '{:timeout 100 :request/timeout 200}']) { + for (const parts of [index.linkType(text), index.linkLiteral(text)]) { + expect(parts.map((part) => part.text).join('')).toBe(text) + expect(parts.some((part) => part.link), text).toBe(false) + } + const spans = index.docSpans(`Use \`${text}\`.`) + expect(spans.some((span) => span.link || span.parts?.some((part) => part.link)), text).toBe(false) + } + expect(index.resolve('timeout')?.symbol?.id).toBe('libtmux.core/timeout') + expect(index.docSpans('See [[libtmux.core/close!]].')[1]?.link?.symbol?.id).toBe('libtmux.core/close!') + }) + + it('keeps every arity, native call spelling, package, source and docstring link', () => { + const model = extractClojure(artifact(), revision) + expect(model.symbols.find((symbol) => symbol.name === 'matching')?.signatures.map((signature) => signature.raw)) + .toEqual(['(matching expression)', '(matching expression entries)']) + const close = model.symbols.find((symbol) => symbol.id === 'libtmux.control/close!')! + expect(close.package).toBe(coordinate) + expect(close.source.revision).toBe(revision) + expect(close.doc?.body).toContain('[[libtmux.core/close!]]') + expect(close).not.toHaveProperty('docstring') + const index = new SymbolIndex(model.symbols, (symbol) => `/${symbol.id}/`, 'clojure') + const references = index.docSpans(close.doc!.body!, close) + .filter((span) => span.kind === 'ref' && span.explicit) + expect(references.map((span) => span.kind === 'ref' ? span.link?.symbol?.id : undefined)) + .toEqual(['libtmux.control/close!', 'libtmux.core/close!']) + }) + + it.each(['private', 'source', 'reference', 'provenance'] as const)('rejects a broken %s boundary', (boundary) => { + const input = artifact() + if (boundary === 'private') input.symbols[3]!.modifiers.push('private') + if (boundary === 'source') input.symbols[3]!.source.file = '../private.clj' + if (boundary === 'reference') input.symbols[4]!.docstring = 'See [[missing-var]].' + if (boundary === 'provenance') input.nativeProvenance.files[0]!.sha256 = 'stale' + expect(() => extractClojure(input, revision)).toThrow(/Clojure/) + }) +}) + +describe('Clojure example ownership', () => { + it.each([false, true])('preserves the selected source with launcher=%s', (launcher) => { + const symbol = extractClojure(artifact(), revision).symbols.find((entry) => entry.id === 'libtmux.core/close!')! + const program = '(ns libtmux.examples.api.connect)\n' + const setup = [ + { sourceFile: 'examples/api/clojure/deps.edn', path: 'deps.edn' }, + ...(launcher ? [{ sourceFile: 'examples/api/run.sh', path: 'run.sh' }] : []), + ] + const files: Record = { + 'examples/api/clojure/manifest.json': JSON.stringify({ + schemaVersion: 1, variants: { clojure: { files: setup } }, + examples: [{ id: 'connect', variant: 'clojure', language: 'clojure', description: 'Connect.', + mainNamespace: 'libtmux.examples.api.connect', path: 'src/main/clojure/libtmux/examples/api/connect.clj', + sourceFile: 'examples/src/main/clojure/libtmux/examples/api/connect.clj', + targets: [symbol.id], expectedOutput: 'connected=true\n' }], + }), + 'examples/api/clojure/deps.edn': '{:paths ["src/main/clojure"]}\n', + 'examples/src/main/clojure/libtmux/examples/api/connect.clj': program, + ...(launcher ? { 'examples/api/run.sh': '#!/bin/sh\nexec "$@"\n' } : {}), + } + attachCompleteClojureExamples([symbol], (path) => files[path], { repo, revision }) + const blocks = symbol.doc!.examples! + expect(blocks.find((block) => block.code === program)?.sourceUrl) + .toBe(`https://github.com/${repo}/blob/${revision}/examples/src/main/clojure/libtmux/examples/api/connect.clj`) + const run = blocks.filter((block) => block.lang === 'console').at(-1)! + expect(run.code).toBe(`$ ${launcher ? 'sh run.sh ' : ''}clojure \\\n -J-Dclojure.main.report=stderr \\\n -M \\\n -m libtmux.examples.api.connect\n`) + expect(blocks.some((block) => block.sourceUrl?.endsWith('/examples/api/run.sh'))).toBe(launcher) + const ownership = blocks.find((block) => block.code === program)!.intro! + expect(ownership.includes('own private tmux server')).toBe(!launcher) + expect(ownership.includes("launcher's server")).toBe(launcher) + }) +}) diff --git a/packages/api-model/test/concepts.test.ts b/packages/api-model/test/concepts.test.ts index 666339552..d25f7a9c0 100644 --- a/packages/api-model/test/concepts.test.ts +++ b/packages/api-model/test/concepts.test.ts @@ -101,6 +101,7 @@ describe('concept map', () => { ['powershell', 'LibTmux\\New-TmuxServer', 'function'], ['julia', 'LibTmux.Server', 'struct'], ['fsharp', 'LibTmux.FSharp.Server', 'module'], + ['ocaml', 'Libtmux_unix.Client.t', 'typealias'], ] for (const [port, id, kind] of expected) { const symbol = models.get(port)!.symbols.find((symbol) => (symbol.publicId ?? symbol.id) === id)! diff --git a/packages/api-model/test/erlang.test.ts b/packages/api-model/test/erlang.test.ts new file mode 100644 index 000000000..2e6877276 --- /dev/null +++ b/packages/api-model/test/erlang.test.ts @@ -0,0 +1,138 @@ +import { readFileSync } from 'node:fs' +import { createHash } from 'node:crypto' +import { describe, expect, it } from 'vitest' +import { extractErlang } from '../src/languages/erlang.ts' +import { SymbolIndex } from '../src/link.ts' +import { tokenizeDoc } from '../src/doc/roles.ts' + +const fixture = JSON.parse(readFileSync(new URL('./fixtures/erlang-native.json', import.meta.url), 'utf8')) +const model = () => extractErlang(fixture, fixture.source.revision) + +describe('Erlang compiler artifact adapter', () => { + it('retains source identity, native arities and compiler declarations', () => { + const result = model() + const symbol = (id: string) => result.symbols.find((entry) => entry.id === id)! + expect(result).toMatchObject({ port: 'erlang', revision: fixture.source.revision, repo: 'libtmux/probe' }) + expect(result.nativeProvenance?.files).toEqual(fixture.source.files) + expect(fixture.exporter.source_sha256).toBe(createHash('sha256') + .update(readFileSync(new URL('../scripts/export-erlang.escript', import.meta.url))).digest('hex')) + for (const file of fixture.source.files) { + expect(file.sha256).toBe(createHash('sha256') + .update(readFileSync(new URL(`./fixtures/erlang-project/${file.path}`, import.meta.url))).digest('hex')) + } + expect(symbol('probe:double/1')).toMatchObject({ name: 'double/1', parent: 'probe', kind: 'function' }) + expect(symbol('probe:double/1').signatures.map((signature) => + signature.params.map(({ name, type }) => ({ name, type })))).toEqual([ + [{ name: 'Number', type: 'integer()' }], [{ name: 'Number', type: 'float()' }], + ]) + expect(symbol('probe:double/1').modifiers).toContain('overload') + expect(symbol('t:probe:handle/0').signatures[0]?.raw).toBe('-opaque handle().') + expect(symbol('t:probe:handle/0').type).toBeUndefined() + expect(symbol('t:probe:internal_mode/0').apiScope).toBe('supporting') + expect(symbol('t:probe:id/0').signatures[0]?.raw).toContain('-nominal id()') + expect(symbol('t:probe:included_id/0').source?.file).toBe('include/public_types.hrl') + expect(symbol("t:probe:'λ-handle'/1").name).toBe("'λ-handle'/1") + expect(symbol("t:probe:'a::b'/0").signatures[0]?.raw).toBe("-opaque 'a::b'().") + expect(symbol('#probe:row{}')).toMatchObject({ kind: 'struct', parent: 'probe' }) + expect(symbol('c:probe:prepare/1').signatures[0]?.raw).toContain('-callback prepare(') + expect(symbol('probe').doc?.examples?.[0]?.code).toContain('1> probe:double(2).') + }) + + it('resolves native module, function, type and callback references in their module', () => { + const result = model() + const index = new SymbolIndex(result.symbols, (symbol) => `/reference/${encodeURIComponent(symbol.id)}`, 'erlang') + const context = result.symbols.find((symbol) => symbol.id === 'probe:read/1')! + const refs = tokenizeDoc('`m:probe` `read/1` `t:handle/0` `c:prepare/1`', 'erlang') + expect(refs.filter((span) => span.kind === 'ref').map((span) => span.label)).toEqual(['probe', 'read/1', 'handle/0', 'prepare/1']) + for (const [target, id] of [['m:probe', 'probe'], ['read/1', 'probe:read/1'], ['t:handle/0', 't:probe:handle/0'], ['c:prepare/1', 'c:probe:prepare/1']]) { + expect(index.resolve(target!, 'any', context)?.symbol?.id).toBe(id) + } + expect(index.resolve('handle/0', 'any', context)?.symbol?.id).toBe('probe:handle/0') + expect(tokenizeDoc('[the module](`m:probe`)', 'erlang')).toEqual([ + { kind: 'ref', role: 'any', target: 'm:probe', label: 'the module' }, + ]) + expect(index.resolve('missing:read/1', 'any', context)).toBeUndefined() + expect(index.resolve('t:read/1', 'any', context)).toBeUndefined() + expect(index.resolve('probe:read/1', 'class', context)).toBeUndefined() + }) + + it('rejects unsupported, mismatched, duplicate or source-less artifacts', () => { + expect(() => extractErlang(fixture, '0'.repeat(40))).toThrow(/revision/) + expect(() => extractErlang({ ...fixture, schema: 2 })).toThrow(/schema/) + const duplicate = structuredClone(fixture) + duplicate.modules[0].members.push(duplicate.modules[0].members[0]) + expect(() => extractErlang(duplicate)).toThrow(/repeats/) + const missing = structuredClone(fixture) + missing.modules[0].members[0].source.file = '../outside.erl' + expect(() => extractErlang(missing)).toThrow(/source/) + const opaque = structuredClone(fixture) + opaque.modules[0].members.find((member: { visibility: string }) => member.visibility === 'opaque').declarations[0] += ' :: private_body' + expect(() => extractErlang(opaque)).toThrow(/opaque type body/) + const head = structuredClone(fixture) + head.modules[0].members.find((member: { kind: string }) => member.kind === 'function').signatures = [] + expect(() => extractErlang(head)).toThrow(/signature/) + const parameter = structuredClone(fixture) + delete parameter.modules[0].members.find((member: { kind: string; arity: number }) => member.kind === 'function' && member.arity > 0).specs[0].parameters[0].type + expect(() => extractErlang(parameter)).toThrow(/signature/) + }) + + it('links compiler type ranges by native arity and namespace without rewriting text', () => { + const result = model() + const index = new SymbolIndex(result.symbols, (symbol) => `/reference/${encodeURIComponent(symbol.id)}`, 'erlang') + const read = result.symbols.find((symbol) => symbol.id === 'probe:read/1')! + const handle = result.symbols.find((symbol) => symbol.id === 'probe:handle/0')! + expect(index.linkType(read.signatures[0]!.params[0]!.type!, read) + .filter((span) => span.link).map((span) => span.link?.symbol?.id)).toEqual(['t:probe:handle/0']) + const handleSpans = index.linkType(handle.signatures[0]!.raw!, handle, handle.signatures[0]) + expect(handleSpans.filter((span) => span.link).map((span) => span.link?.symbol?.id)).toEqual(['t:probe:handle/0']) + const links = result.symbols.find((symbol) => symbol.id === 'probe:links/1')! + const signature = links.signatures[0]! + const spans = index.linkType(signature.raw!, links, signature) + expect(spans.map((span) => span.text).join('')).toBe(signature.raw) + expect(spans.filter((span) => span.link?.symbol).map((span) => span.link!.symbol!.id)).toEqual([ + 't:probe:container/3', 't:probe:box/0', '#probe:row{}', + 't:probe:box/0', "t:probe:'🧭'/0", "t:probe:'a::b'/0", 't:probe:box/1', + ]) + expect(spans.find((span) => span.link?.href.includes('/kernel/file.html'))?.text).toBe('file:filename_all') + expect(spans.find((span) => span.link?.symbol?.id === "t:probe:'🧭'/0")?.text).toBe("'🧭'") + expect(spans.find((span) => span.link?.symbol?.id === '#probe:row{}')?.text).toBe('#probe:row') + expect(spans.filter((span) => span.link).some((span) => span.text.includes('literal'))).toBe(false) + expect(spans.filter((span) => span.link).some((span) => span.text.includes('__libtmux_record'))).toBe(false) + const unresolved = result.symbols.find((symbol) => symbol.id === 't:probe:unresolved/0')! + expect(index.linkType(unresolved.signatures[0]!.raw!, unresolved) + .find((span) => span.text === 'file:no_such_type')?.link).toBeUndefined() + }) + + it('retains the workspace application product boundary', () => { + const workspace = structuredClone(fixture) + workspace.package.name = 'libtmux_erlang_workspace' + expect(extractErlang(workspace).symbols.every((symbol) => symbol.product === 'workspace' && + symbol.package === 'libtmux_erlang_workspace')).toBe(true) + expect(model().symbols.every((symbol) => symbol.product === 'core')).toBe(true) + }) + + it('rejects malformed, overlapping, surrogate-splitting and unsafe external reference ranges', () => { + const changed = (mutate: (input: typeof fixture) => void) => { + const input = structuredClone(fixture) + mutate(input) + return () => extractErlang(input) + } + const read = (input: typeof fixture) => input.modules[0].members.find((member: { name: string }) => member.name === 'read') + expect(changed((input) => { delete read(input).specs[0].parameters[0].references })).toThrow(/references/) + expect(changed((input) => { read(input).specs[0].references[1].start = 0 })).toThrow(/ranges/) + expect(changed((input) => { read(input).specs[0].parameters[0].references[0].end = 999 })).toThrow(/ranges/) + expect(changed((input) => { + const spec = input.modules[0].members.find((member: { name: string }) => member.name === 'links').specs[0] + const at = spec.parameters[0].type.indexOf('🧭') + expect(at).toBeGreaterThan(0) + spec.parameters[0].references = [{ start: at + 1, end: at + 2, target: "t:probe:'🧭'/0" }] + })).toThrow(/ranges/) + expect(changed((input) => { + read(input).specs[0].parameters[0].references[0].external = { href: 'javascript:alert(1)', project: 'Erlang/OTP' } + })).toThrow(/destination/) + expect(changed((input) => { + input.modules[0].members.find((member: { name: string; kind: string }) => member.name === 'handle' && member.kind === 'type') + .declaration_references[0] = [{ start: 8, end: 14, target: 't:probe:private/0' }] + })).toThrow(/opaque/) + }) +}) diff --git a/packages/api-model/test/export-erlang.outer.test.ts b/packages/api-model/test/export-erlang.outer.test.ts new file mode 100644 index 000000000..65dd58df9 --- /dev/null +++ b/packages/api-model/test/export-erlang.outer.test.ts @@ -0,0 +1,250 @@ +import { execFileSync, spawnSync } from 'node:child_process' +import { createHash } from 'node:crypto' +import { cpSync, mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join, relative } from 'node:path' +import { describe, expect, it } from 'vitest' + +const script = new URL('../scripts/export-erlang.escript', import.meta.url).pathname +const fixture = new URL('./fixtures/erlang-project/', import.meta.url).pathname +const env = { ...process.env, ERL_FLAGS: '+S 2:2' } +const version = spawnSync('erl', ['-noshell', '-eval', 'io:put_chars(erlang:system_info(otp_release)), halt().'], { encoding: 'utf8', env }).stdout +const available = version === '29' && spawnSync('rebar3', ['version'], { encoding: 'utf8', env }).status === 0 +const ci = !!process.env.CI && !['0', 'false'].includes(process.env.CI) + +it('requires OTP 29 on CI for the compiler exporter', () => { + if (!available && ci) throw new Error('Install Erlang/OTP 29 and Rebar3 before the exporter tests') +}) + +function checkout() { + const directory = mkdtempSync(join(tmpdir(), 'export-erlang-')) + cpSync(fixture, directory, { recursive: true }) + const git = (...args: string[]) => execFileSync('git', args, { cwd: directory, encoding: 'utf8' }).trim() + git('init', '-q') + git('remote', 'add', 'origin', 'https://github.com/libtmux/probe.git') + git('add', '.') + git('-c', 'user.name=Fixture', '-c', 'user.email=fixture@example.invalid', 'commit', '-qm', 'Fixture') + return { directory, git, revision: git('rev-parse', 'HEAD') } +} + +const exportFrom = (directory: string, output = join(directory, '_build/api.json'), environment = env) => + spawnSync('escript', [script, directory, 'probe', output], { encoding: 'utf8', env: environment }) + +// These cases compile a real OTP project; they belong outside the medium loop. +describe.skipIf(!available)('Erlang compiler export', { timeout: 30_000 }, () => { + it('retains native declarations, documentation, source identity and hiding', () => { + const { directory, revision } = checkout() + try { + const result = exportFrom(directory) + expect(result.status, result.stderr + result.stdout).toBe(0) + const artifact = JSON.parse(readFileSync(join(directory, '_build/api.json'), 'utf8')) + expect(artifact).toMatchObject({ schema: 1, port: 'erlang', source: { repository: 'libtmux/probe', revision }, package: { name: 'probe', version: '0.1.0' } }) + expect(artifact.source.files.map((file: { path: string }) => file.path)).toContain('src/probe.erl') + expect(artifact.exporter.source_sha256).toBe(createHash('sha256').update(readFileSync(script)).digest('hex')) + const module = artifact.modules[0] + expect(module.name).toBe('probe') + expect(module.doc).toContain('`m:probe` and `read/1`') + const member = (kind: string, name: string) => module.members.find((m: { kind: string; name: string }) => m.kind === kind && m.name === name) + const parameter = member('function', 'read').specs[0].parameters[0] + expect(parameter.references).toEqual([ + { start: 0, end: 6, target: 't:probe:handle/0' }, + ]) + expect(member('type', 'handle').declaration_references).toEqual([[]]) + expect(member('function', 'hidden')).toBeUndefined() + expect(member('function', 'wide').specs[0].text.split('\n') + .every((line: string) => Array.from(line).length <= 60)).toBe(true) + expect(member('function', 'double')).toMatchObject({ arity: 1, since: '0.1.0', deprecated: 'Use a calculator.', source: { file: 'src/probe.erl' } }) + expect(member('function', 'double').declarations.join('')).toContain('float()') + expect(member('function', 'double').declarations.join('')).toContain('integer()') + expect(member('function', 'double').specs).toEqual([ + expect.objectContaining({ parameters: [expect.objectContaining({ name: 'Number', type: 'integer()' })], returns: 'integer()' }), + expect.objectContaining({ parameters: [expect.objectContaining({ name: 'Number', type: 'float()' })], returns: 'float()' }), + ]) + const linked = member('function', 'links').specs[0] + const parameterTargets = linked.parameters[0].references.map((ref: { target: string }) => ref.target) + expect(parameterTargets).toEqual([ + 't:probe:container/3', 't:probe:box/0', '#probe:row{}', + 't:probe:box/0', "t:probe:'🧭'/0", + ]) + const returned = linked.returns_references + expect(returned.map((ref: { target: string }) => ref.target)).toEqual([ + "t:probe:'a::b'/0", 't:probe:box/1', 't:erlang:term/0', 't:file:filename_all/0', + ]) + expect(returned.at(-1).external).toEqual({ + href: 'https://www.erlang.org/doc/apps/kernel/file.html#t:filename_all/0', + project: 'Erlang/OTP', + }) + expect(member('type', 'unresolved').declaration_references[0]).toEqual([ + expect.objectContaining({ target: 't:file:no_such_type/0' }), + ]) + expect(member('type', 'unresolved').declaration_references[0][0].external).toBeUndefined() + for (const ref of returned) { + expect(linked.returns.slice(ref.start, ref.end)).not.toContain('literal') + } + expect(member('type', 'λ-handle').display_name).toBe("'λ-handle'") + expect(member('type', 'handle')).toMatchObject({ visibility: 'opaque', declarations: ['-opaque handle().'] }) + expect(JSON.stringify(artifact)).not.toContain('private_token') + expect(member('type', 'id').declarations.join('')).toContain('-nominal id()') + expect.soft(member('type', 'internal_mode')).toMatchObject({ exported: false }) + expect.soft(member('type', 'odd-name').declarations).toEqual(["-opaque 'odd-name'(T)."]) + expect.soft(member('type', 'λ-handle').declarations).toEqual(["-opaque 'λ-handle'(T)."]) + expect.soft(member('type', 'included_id').source).toEqual({ file: 'include/public_types.hrl', line: 2 }) + expect(member('callback', 'prepare').declarations.join('')).toContain('-callback prepare(') + expect(module.records[0]).toMatchObject({ name: 'row' }) + expect(module.records[0].declaration).toContain('-record #row{') + expect(module.members.every((m: { source: { line: number } }) => m.source.line > 0)).toBe(true) + const first = readFileSync(join(directory, '_build/api.json'), 'utf8') + const repository = new URL('../../../', import.meta.url).pathname + const repeat = spawnSync('escript', [relative(repository, script), relative(repository, directory), 'probe', join(directory, '_build/api.json')], + { cwd: repository, encoding: 'utf8', env }) + expect(repeat.status, repeat.stderr).toBe(0) + expect(readFileSync(join(directory, '_build/api.json'), 'utf8')).toBe(first) + } finally { rmSync(directory, { recursive: true, force: true }) } + }) + + it('rejects dirty sources and unreadable chunks without writing an artifact', () => { + const { directory, git } = checkout() + try { + const source = join(directory, 'src/probe.erl') + writeFileSync(source, `${readFileSync(source, 'utf8')}\n% changed\n`) + expect(exportFrom(directory).stderr).toContain('uncommitted changes') + git('-c', 'user.name=Fixture', '-c', 'user.email=fixture@example.invalid', 'commit', '-qam', 'Change') + writeFileSync(join(directory, 'rebar.config'), '{erl_opts, [no_docs, no_debug_info]}.\n{deps, []}.\n') + git('-c', 'user.name=Fixture', '-c', 'user.email=fixture@example.invalid', 'commit', '-qam', 'Strip chunks') + const failure = exportFrom(directory) + expect(failure.status).not.toBe(0) + expect(failure.stderr).toContain('compiler chunks') + expect(spawnSync('test', ['-e', join(directory, '_build/api.json')]).status).toBe(1) + } finally { rmSync(directory, { recursive: true, force: true }) } + }) + + it('rejects an external public header even when its basename matches a tracked header', () => { + const { directory, git } = checkout() + const outside = mkdtempSync(join(tmpdir(), 'export-erlang-header-')) + try { + const header = join(outside, 'public_types.hrl') + writeFileSync(header, '-type outsourced() :: binary().\n') + const source = join(directory, 'src/probe.erl') + writeFileSync(source, readFileSync(source, 'utf8').replace('-module(probe).', + `-module(probe).\n-export_type([outsourced/0]).\n-include("${header}").`)) + git('-c', 'user.name=Fixture', '-c', 'user.email=fixture@example.invalid', 'commit', '-qam', 'Include external type') + const result = exportFrom(directory) + expect(result.status).not.toBe(0) + expect(result.stderr).toContain('public_types.hrl: source path is missing or ambiguous') + } finally { + rmSync(directory, { recursive: true, force: true }) + rmSync(outside, { recursive: true, force: true }) + } + }) + + it('captures compiler macros when identical headers have different source provenance', () => { + const { directory, git } = checkout() + const outside = mkdtempSync(join(tmpdir(), 'export-erlang-macro-')) + try { + const header = join(outside, 'public_types.hrl') + cpSync(join(directory, 'include/public_types.hrl'), header) + const source = join(directory, 'src/probe.erl') + writeFileSync(source, readFileSync(source, 'utf8').replace('-include("public_types.hrl").', + `-ifdef(USE_EXTERNAL).\n-include("${header}").\n-else.\n-include("public_types.hrl").\n-endif.`)) + const config = join(directory, 'rebar.config') + writeFileSync(config, readFileSync(config, 'utf8').replace('deterministic,', + "deterministic, {d, 'USE_EXTERNAL'},")) + git('-c', 'user.name=Fixture', '-c', 'user.email=fixture@example.invalid', 'commit', '-qam', 'Select identical external header') + const result = exportFrom(directory) + expect(result.status).not.toBe(0) + expect(result.stderr).toContain('public_types.hrl: source path is missing or ambiguous') + } finally { + rmSync(directory, { recursive: true, force: true }) + rmSync(outside, { recursive: true, force: true }) + } + }) + + it('rejects an external header that remaps itself to a tracked source', () => { + const { directory, git } = checkout() + const outside = mkdtempSync(join(tmpdir(), 'export-erlang-remap-')) + try { + const header = join(outside, 'public_types.hrl') + writeFileSync(header, '-file("include/public_types.hrl", 1).\n-type outsourced() :: binary().\n') + const source = join(directory, 'src/probe.erl') + writeFileSync(source, readFileSync(source, 'utf8').replace('-module(probe).', + `-module(probe).\n-export_type([outsourced/0]).\n-include("${header}").`)) + git('-c', 'user.name=Fixture', '-c', 'user.email=fixture@example.invalid', 'commit', '-qam', 'Remap external header') + const result = exportFrom(directory) + expect(result.status).not.toBe(0) + expect(result.stderr).toContain('explicit source remapping cannot be verified') + } finally { + rmSync(directory, { recursive: true, force: true }) + rmSync(outside, { recursive: true, force: true }) + } + }) + + it('rejects a tracked source symlink instead of citing its target bytes', () => { + const { directory, git } = checkout() + const outside = mkdtempSync(join(tmpdir(), 'export-erlang-link-')) + try { + const header = join(outside, 'public_types.hrl') + const tracked = join(directory, 'include/public_types.hrl') + cpSync(tracked, header) + rmSync(tracked) + symlinkSync(header, tracked) + git('add', '.') + git('-c', 'user.name=Fixture', '-c', 'user.email=fixture@example.invalid', 'commit', '-qm', 'Link external source') + const result = exportFrom(directory) + expect(result.status).not.toBe(0) + expect(result.stderr).toContain('source input must be a regular file') + } finally { + rmSync(directory, { recursive: true, force: true }) + rmSync(outside, { recursive: true, force: true }) + } + }) + + it('binds the primary source to the compiler entry rather than a same-named tracked file', () => { + const { directory, git } = checkout() + const outside = mkdtempSync(join(tmpdir(), 'export-erlang-entry-')) + try { + const external = join(outside, 'probe.erl') + cpSync(join(directory, 'src/probe.erl'), external) + mkdirSync(join(directory, 'unused')) + git('mv', 'src/probe.erl', 'unused/probe.erl') + symlinkSync(external, join(directory, 'src/probe.erl')) + const ignore = join(directory, '.gitignore') + writeFileSync(ignore, `${readFileSync(ignore, 'utf8')}\nsrc/probe.erl\n`) + git('add', '.') + git('-c', 'user.name=Fixture', '-c', 'user.email=fixture@example.invalid', 'commit', '-qm', 'Compile ignored external source') + const result = exportFrom(directory) + expect(result.status).not.toBe(0) + expect(result.stderr).toContain('probe.erl: source path is missing or ambiguous') + } finally { + rmSync(directory, { recursive: true, force: true }) + rmSync(outside, { recursive: true, force: true }) + } + }) + + it('resolves include_lib in the compiler VM instead of the exporter library path', () => { + const { directory, git } = checkout() + const outside = mkdtempSync(join(tmpdir(), 'export-erlang-library-')) + try { + const tracked = join(directory, 'vendor/aliaslib') + const external = join(outside, 'aliaslib') + for (const library of [tracked, external]) { + mkdirSync(join(library, 'include'), { recursive: true }) + mkdirSync(join(library, 'ebin')) + writeFileSync(join(library, 'include/public_types.hrl'), '-type outsourced() :: binary().\n') + writeFileSync(join(library, 'ebin/aliaslib.app'), '{application, aliaslib, [{vsn, "0.1.0"}, {modules, []}]}.\n') + } + writeFileSync(join(directory, 'rebar.config.script'), + `true = code:add_patha(${JSON.stringify(join(external, 'ebin'))}), CONFIG.\n`) + const source = join(directory, 'src/probe.erl') + writeFileSync(source, readFileSync(source, 'utf8').replace('-module(probe).', + '-module(probe).\n-export_type([outsourced/0]).\n-include_lib("aliaslib/include/public_types.hrl").')) + git('add', '.') + git('-c', 'user.name=Fixture', '-c', 'user.email=fixture@example.invalid', 'commit', '-qm', 'Select compiler library path') + const result = exportFrom(directory, undefined, { ...env, ERL_LIBS: join(directory, 'vendor') }) + expect(result.status).not.toBe(0) + expect(result.stderr).toContain('public_types.hrl: source path is missing or ambiguous') + } finally { + rmSync(directory, { recursive: true, force: true }) + rmSync(outside, { recursive: true, force: true }) + } + }) +}) diff --git a/packages/api-model/test/fixtures/erlang-native.json b/packages/api-model/test/fixtures/erlang-native.json new file mode 100644 index 000000000..d2f185485 --- /dev/null +++ b/packages/api-model/test/fixtures/erlang-native.json @@ -0,0 +1 @@ +{"port":"erlang","modules":[{"name":"probe","records":[{"name":"row","source":{"line":18,"file":"src/probe.erl"},"display_name":"row","declaration":"-record #row{id :: id()}.","references":[{"start":19,"end":21,"target":"t:probe:id/0"}]}],"doc":"Captured values with `m:probe` and `read/1` references.\n\n```erlang\n1> probe:double(2).\n4\n```","source":{"line":1,"file":"src/probe.erl"},"display_name":"probe","members":[{"arity":1,"name":"prepare","deprecated":null,"doc":"Prepare one row.","exported":true,"specs":[{"text":"-callback prepare(row()) -> {ok, handle()}.","references":[{"start":18,"end":21,"target":"t:probe:row/0"},{"start":33,"end":39,"target":"t:probe:handle/0"}],"parameters":[{"name":"Argument1","type":"row()","references":[{"start":0,"end":3,"target":"t:probe:row/0"}]}],"returns":"{ok, handle()}","returns_references":[{"start":5,"end":11,"target":"t:probe:handle/0"}]}],"source":{"line":40,"file":"src/probe.erl"},"display_name":"prepare","kind":"callback","signatures":["prepare/1"],"since":null,"visibility":"public","declarations":["-callback prepare(row()) -> {ok, handle()}."],"declaration_references":[[{"start":18,"end":21,"target":"t:probe:row/0"},{"start":33,"end":39,"target":"t:probe:handle/0"}]]},{"arity":1,"name":"double","deprecated":"Use a calculator.","doc":"Double an integer or float.","exported":true,"specs":[{"text":"-spec double(integer()) -> integer().","references":[{"external":{"href":"https://www.erlang.org/doc/apps/erts/erlang.html#t:integer/0","project":"Erlang/OTP"},"start":13,"end":20,"target":"t:erlang:integer/0"},{"external":{"href":"https://www.erlang.org/doc/apps/erts/erlang.html#t:integer/0","project":"Erlang/OTP"},"start":27,"end":34,"target":"t:erlang:integer/0"}],"parameters":[{"name":"Number","type":"integer()","references":[{"external":{"href":"https://www.erlang.org/doc/apps/erts/erlang.html#t:integer/0","project":"Erlang/OTP"},"start":0,"end":7,"target":"t:erlang:integer/0"}]}],"returns":"integer()","returns_references":[{"external":{"href":"https://www.erlang.org/doc/apps/erts/erlang.html#t:integer/0","project":"Erlang/OTP"},"start":0,"end":7,"target":"t:erlang:integer/0"}]},{"text":"-spec double(float()) -> float().","references":[{"external":{"href":"https://www.erlang.org/doc/apps/erts/erlang.html#t:float/0","project":"Erlang/OTP"},"start":13,"end":18,"target":"t:erlang:float/0"},{"external":{"href":"https://www.erlang.org/doc/apps/erts/erlang.html#t:float/0","project":"Erlang/OTP"},"start":25,"end":30,"target":"t:erlang:float/0"}],"parameters":[{"name":"Number","type":"float()","references":[{"external":{"href":"https://www.erlang.org/doc/apps/erts/erlang.html#t:float/0","project":"Erlang/OTP"},"start":0,"end":5,"target":"t:erlang:float/0"}]}],"returns":"float()","returns_references":[{"external":{"href":"https://www.erlang.org/doc/apps/erts/erlang.html#t:float/0","project":"Erlang/OTP"},"start":0,"end":5,"target":"t:erlang:float/0"}]}],"source":{"line":45,"file":"src/probe.erl"},"display_name":"double","kind":"function","signatures":["double(Number)"],"since":"0.1.0","visibility":"public","declarations":["-spec double(integer()) -> integer();\n (float()) -> float()."],"declaration_references":[[{"external":{"href":"https://www.erlang.org/doc/apps/erts/erlang.html#t:integer/0","project":"Erlang/OTP"},"start":13,"end":20,"target":"t:erlang:integer/0"},{"external":{"href":"https://www.erlang.org/doc/apps/erts/erlang.html#t:integer/0","project":"Erlang/OTP"},"start":27,"end":34,"target":"t:erlang:integer/0"},{"external":{"href":"https://www.erlang.org/doc/apps/erts/erlang.html#t:float/0","project":"Erlang/OTP"},"start":51,"end":56,"target":"t:erlang:float/0"},{"external":{"href":"https://www.erlang.org/doc/apps/erts/erlang.html#t:float/0","project":"Erlang/OTP"},"start":63,"end":68,"target":"t:erlang:float/0"}]]},{"arity":0,"name":"handle","deprecated":null,"doc":"Construct a handle; the type and function share a name.","exported":true,"specs":[{"text":"-spec handle() -> handle().","references":[{"start":18,"end":24,"target":"t:probe:handle/0"}],"parameters":[],"returns":"handle()","returns_references":[{"start":0,"end":6,"target":"t:probe:handle/0"}]}],"source":{"line":53,"file":"src/probe.erl"},"display_name":"handle","kind":"function","signatures":["handle()"],"since":null,"visibility":"public","declarations":["-spec handle() -> handle()."],"declaration_references":[[{"start":18,"end":24,"target":"t:probe:handle/0"}]]},{"arity":1,"name":"links","deprecated":null,"doc":"Compiler references distinguish arities, native records and literal names.","exported":true,"specs":[{"text":"-spec links(probe:container(fun((box(),\n #probe:row{}) ->\n box()),\n #{key := 'a,b'},\n '🧭'())) ->\n {'literal:box()', '🧭',\n '__libtmux_record_0_probe:row',\n <<_:8>>,\n 'a::b'(),\n box(term()),\n file:filename_all()}.","references":[{"start":12,"end":27,"target":"t:probe:container/3"},{"start":33,"end":36,"target":"t:probe:box/0"},{"start":73,"end":83,"target":"#probe:row{}"},{"start":126,"end":129,"target":"t:probe:box/0"},{"start":207,"end":211,"target":"t:probe:'🧭'/0"},{"start":347,"end":353,"target":"t:probe:'a::b'/0"},{"start":373,"end":376,"target":"t:probe:box/1"},{"external":{"href":"https://www.erlang.org/doc/apps/erts/erlang.html#t:term/0","project":"Erlang/OTP"},"start":377,"end":381,"target":"t:erlang:term/0"},{"external":{"href":"https://www.erlang.org/doc/apps/kernel/file.html#t:filename_all/0","project":"Erlang/OTP"},"start":402,"end":419,"target":"t:file:filename_all/0"}],"parameters":[{"name":"_Input","type":"probe:container(fun((box(),\n #probe:row{}) ->\n box()),\n #{key := 'a,b'},\n '🧭'())","references":[{"start":0,"end":15,"target":"t:probe:container/3"},{"start":21,"end":24,"target":"t:probe:box/0"},{"start":59,"end":69,"target":"#probe:row{}"},{"start":110,"end":113,"target":"t:probe:box/0"},{"start":187,"end":191,"target":"t:probe:'🧭'/0"}]}],"returns":"{'literal:box()', '🧭',\n '__libtmux_record_0_probe:row',\n <<_:8>>,\n 'a::b'(),\n box(term()),\n file:filename_all()}","returns_references":[{"start":98,"end":104,"target":"t:probe:'a::b'/0"},{"start":119,"end":122,"target":"t:probe:box/1"},{"external":{"href":"https://www.erlang.org/doc/apps/erts/erlang.html#t:term/0","project":"Erlang/OTP"},"start":123,"end":127,"target":"t:erlang:term/0"},{"external":{"href":"https://www.erlang.org/doc/apps/kernel/file.html#t:filename_all/0","project":"Erlang/OTP"},"start":143,"end":160,"target":"t:file:filename_all/0"}]}],"source":{"line":60,"file":"src/probe.erl"},"display_name":"links","kind":"function","signatures":["links(Input)"],"since":null,"visibility":"public","declarations":["-spec links(probe:container(fun((box(),\n #probe:row{}) ->\n box()),\n #{key := 'a,b'},\n '🧭'())) ->\n {'literal:box()', '🧭',\n '__libtmux_record_0_probe:row',\n <<_:8>>,\n 'a::b'(),\n box(term()),\n file:filename_all()}."],"declaration_references":[[{"start":12,"end":27,"target":"t:probe:container/3"},{"start":33,"end":36,"target":"t:probe:box/0"},{"start":73,"end":83,"target":"#probe:row{}"},{"start":126,"end":129,"target":"t:probe:box/0"},{"start":207,"end":211,"target":"t:probe:'🧭'/0"},{"start":347,"end":353,"target":"t:probe:'a::b'/0"},{"start":373,"end":376,"target":"t:probe:box/1"},{"external":{"href":"https://www.erlang.org/doc/apps/erts/erlang.html#t:term/0","project":"Erlang/OTP"},"start":377,"end":381,"target":"t:erlang:term/0"},{"external":{"href":"https://www.erlang.org/doc/apps/kernel/file.html#t:filename_all/0","project":"Erlang/OTP"},"start":402,"end":419,"target":"t:file:filename_all/0"}]]},{"arity":1,"name":"read","deprecated":null,"doc":"Read one `t:handle/0`; see `c:prepare/1`.","exported":true,"specs":[{"text":"-spec read(handle()) -> {ok, internal_mode()}.","references":[{"start":11,"end":17,"target":"t:probe:handle/0"},{"start":29,"end":42,"target":"t:probe:internal_mode/0"}],"parameters":[{"name":"_Handle","type":"handle()","references":[{"start":0,"end":6,"target":"t:probe:handle/0"}]}],"returns":"{ok, internal_mode()}","returns_references":[{"start":5,"end":18,"target":"t:probe:internal_mode/0"}]}],"source":{"line":49,"file":"src/probe.erl"},"display_name":"read","kind":"function","signatures":["read(Handle)"],"since":null,"visibility":"public","declarations":["-spec read(handle()) -> {ok, internal_mode()}."],"declaration_references":[[{"start":11,"end":17,"target":"t:probe:handle/0"},{"start":29,"end":42,"target":"t:probe:internal_mode/0"}]]},{"arity":2,"name":"wide","deprecated":null,"doc":"Keep native typespec punctuation within the API column limit.","exported":true,"specs":[{"text":"-spec wide(probe:container(term(), term(), term()),\n box()) ->\n box().","references":[{"start":11,"end":26,"target":"t:probe:container/3"},{"external":{"href":"https://www.erlang.org/doc/apps/erts/erlang.html#t:term/0","project":"Erlang/OTP"},"start":27,"end":31,"target":"t:erlang:term/0"},{"external":{"href":"https://www.erlang.org/doc/apps/erts/erlang.html#t:term/0","project":"Erlang/OTP"},"start":35,"end":39,"target":"t:erlang:term/0"},{"external":{"href":"https://www.erlang.org/doc/apps/erts/erlang.html#t:term/0","project":"Erlang/OTP"},"start":43,"end":47,"target":"t:erlang:term/0"},{"start":63,"end":66,"target":"t:probe:box/0"},{"start":87,"end":90,"target":"t:probe:box/0"}],"parameters":[{"name":"_Input","type":"probe:container(term(), term(), term())","references":[{"start":0,"end":15,"target":"t:probe:container/3"},{"external":{"href":"https://www.erlang.org/doc/apps/erts/erlang.html#t:term/0","project":"Erlang/OTP"},"start":16,"end":20,"target":"t:erlang:term/0"},{"external":{"href":"https://www.erlang.org/doc/apps/erts/erlang.html#t:term/0","project":"Erlang/OTP"},"start":24,"end":28,"target":"t:erlang:term/0"},{"external":{"href":"https://www.erlang.org/doc/apps/erts/erlang.html#t:term/0","project":"Erlang/OTP"},"start":32,"end":36,"target":"t:erlang:term/0"}]},{"name":"Value","type":"box()","references":[{"start":0,"end":3,"target":"t:probe:box/0"}]}],"returns":"box()","returns_references":[{"start":0,"end":3,"target":"t:probe:box/0"}]}],"source":{"line":64,"file":"src/probe.erl"},"display_name":"wide","kind":"function","signatures":["wide(Input, Value)"],"since":null,"visibility":"public","declarations":["-spec wide(probe:container(term(), term(), term()),\n box()) ->\n box()."],"declaration_references":[[{"start":11,"end":26,"target":"t:probe:container/3"},{"external":{"href":"https://www.erlang.org/doc/apps/erts/erlang.html#t:term/0","project":"Erlang/OTP"},"start":27,"end":31,"target":"t:erlang:term/0"},{"external":{"href":"https://www.erlang.org/doc/apps/erts/erlang.html#t:term/0","project":"Erlang/OTP"},"start":35,"end":39,"target":"t:erlang:term/0"},{"external":{"href":"https://www.erlang.org/doc/apps/erts/erlang.html#t:term/0","project":"Erlang/OTP"},"start":43,"end":47,"target":"t:erlang:term/0"},{"start":63,"end":66,"target":"t:probe:box/0"},{"start":87,"end":90,"target":"t:probe:box/0"}]]},{"arity":0,"name":"a::b","deprecated":null,"doc":"A quoted opaque type whose name includes a delimiter.","exported":true,"specs":[],"source":{"line":28,"file":"src/probe.erl"},"display_name":"'a::b'","kind":"type","signatures":["'a::b'()"],"since":null,"visibility":"opaque","declarations":["-opaque 'a::b'()."],"declaration_references":[[]]},{"arity":0,"name":"box","deprecated":null,"doc":null,"exported":true,"specs":[],"source":{"line":33,"file":"src/probe.erl"},"display_name":"box","kind":"type","signatures":["box()"],"since":null,"visibility":"public","declarations":["-type box() :: atom()."],"declaration_references":[[{"external":{"href":"https://www.erlang.org/doc/apps/erts/erlang.html#t:atom/0","project":"Erlang/OTP"},"start":15,"end":19,"target":"t:erlang:atom/0"}]]},{"arity":1,"name":"box","deprecated":null,"doc":null,"exported":true,"specs":[],"source":{"line":34,"file":"src/probe.erl"},"display_name":"box","kind":"type","signatures":["box(T)"],"since":null,"visibility":"public","declarations":["-type box(T) :: [T]."],"declaration_references":[[]]},{"arity":3,"name":"container","deprecated":null,"doc":null,"exported":true,"specs":[],"source":{"line":35,"file":"src/probe.erl"},"display_name":"container","kind":"type","signatures":["container(A, B, C)"],"since":null,"visibility":"public","declarations":["-type container(A, B, C) :: {A, B, C}."],"declaration_references":[[]]},{"arity":0,"name":"handle","deprecated":null,"doc":"An opaque handle; its representation stays private.","exported":true,"specs":[],"source":{"line":22,"file":"src/probe.erl"},"display_name":"handle","kind":"type","signatures":["handle()"],"since":null,"visibility":"opaque","declarations":["-opaque handle()."],"declaration_references":[[]]},{"arity":0,"name":"id","deprecated":null,"doc":"A nominal identifier.","exported":true,"specs":[],"source":{"line":20,"file":"src/probe.erl"},"display_name":"id","kind":"type","signatures":["id()"],"since":null,"visibility":"nominal","declarations":["-nominal id() :: binary()."],"declaration_references":[[{"external":{"href":"https://www.erlang.org/doc/apps/erts/erlang.html#t:binary/0","project":"Erlang/OTP"},"start":17,"end":23,"target":"t:erlang:binary/0"}]]},{"arity":0,"name":"included_id","deprecated":null,"doc":"An included public type.","exported":true,"specs":[],"source":{"line":2,"file":"include/public_types.hrl"},"display_name":"included_id","kind":"type","signatures":["included_id()"],"since":null,"visibility":"public","declarations":["-type included_id() :: non_neg_integer()."],"declaration_references":[[{"external":{"href":"https://www.erlang.org/doc/apps/erts/erlang.html#t:non_neg_integer/0","project":"Erlang/OTP"},"start":23,"end":38,"target":"t:erlang:non_neg_integer/0"}]]},{"arity":0,"name":"internal_mode","deprecated":null,"doc":"A supporting output mode.","exported":false,"specs":[],"source":{"line":30,"file":"src/probe.erl"},"display_name":"internal_mode","kind":"type","signatures":["internal_mode()"],"since":null,"visibility":"public","declarations":["-type internal_mode() :: ready | stopped."],"declaration_references":[[]]},{"arity":1,"name":"odd-name","deprecated":null,"doc":"A handle with a quoted type name.","exported":true,"specs":[],"source":{"line":24,"file":"src/probe.erl"},"display_name":"'odd-name'","kind":"type","signatures":["'odd-name'(T)"],"since":null,"visibility":"opaque","declarations":["-opaque 'odd-name'(T)."],"declaration_references":[[]]},{"arity":0,"name":"row","deprecated":null,"doc":"One public row.","exported":true,"specs":[],"source":{"line":32,"file":"src/probe.erl"},"display_name":"row","kind":"type","signatures":["row()"],"since":null,"visibility":"public","declarations":["-type row() :: #row{}."],"declaration_references":[[{"start":15,"end":19,"target":"#probe:row{}"}]]},{"arity":0,"name":"unresolved","deprecated":null,"doc":null,"exported":true,"specs":[],"source":{"line":37,"file":"src/probe.erl"},"display_name":"unresolved","kind":"type","signatures":["unresolved()"],"since":null,"visibility":"public","declarations":["-type unresolved() :: file:no_such_type()."],"declaration_references":[[{"start":22,"end":39,"target":"t:file:no_such_type/0"}]]},{"arity":1,"name":"λ-handle","deprecated":null,"doc":"A handle with a Unicode name.","exported":true,"specs":[],"source":{"line":26,"file":"src/probe.erl"},"display_name":"'λ-handle'","kind":"type","signatures":["'\\x{3BB}-handle'(T)"],"since":null,"visibility":"opaque","declarations":["-opaque 'λ-handle'(T)."],"declaration_references":[[]]},{"arity":0,"name":"🧭","deprecated":null,"doc":null,"exported":true,"specs":[],"source":{"line":36,"file":"src/probe.erl"},"display_name":"'🧭'","kind":"type","signatures":["'\\x{1F9ED}'()"],"since":null,"visibility":"public","declarations":["-type '🧭'() :: integer()."],"declaration_references":[[{"external":{"href":"https://www.erlang.org/doc/apps/erts/erlang.html#t:integer/0","project":"Erlang/OTP"},"start":16,"end":23,"target":"t:erlang:integer/0"}]]}]}],"source":{"repository":"libtmux/probe","revision":"b808994828b801b465408b02e0b35a8893c4e1a5","files":[{"path":"include/public_types.hrl","sha256":"9bd63bbce8119cc4fed46a42aa8640d9350b01267a34ae4878b139fdcb8cfb01"},{"path":"rebar.config","sha256":"f94e6aa5c003ce3151b59b58106aa791612a98de65a14407bc5da2e174cdca4a"},{"path":"src/probe.app.src","sha256":"582fd682d87092b0497ca977f633d7061f0afb2185a8b4bed2e00745356a19ce"},{"path":"src/probe.erl","sha256":"c4c95aa75344f69eeee799ffff9873990ed22cae86d3620e6bfaf37914fc45c4"}]},"schema":1,"exporter":{"name":"Erlang EEP-48 and abstract code","version":3,"otp":"29.1.2","columns":60,"source_sha256":"2fc491ad480e74fded943bf072d5bfd452116a9dfc6dc7062860727fe487f1ab"},"package":{"name":"probe","version":"0.1.0"}} diff --git a/packages/api-model/test/fixtures/erlang-project/.gitignore b/packages/api-model/test/fixtures/erlang-project/.gitignore new file mode 100644 index 000000000..172c6579a --- /dev/null +++ b/packages/api-model/test/fixtures/erlang-project/.gitignore @@ -0,0 +1,2 @@ +_build/ +rebar.lock diff --git a/packages/api-model/test/fixtures/erlang-project/include/public_types.hrl b/packages/api-model/test/fixtures/erlang-project/include/public_types.hrl new file mode 100644 index 000000000..bb8c26df9 --- /dev/null +++ b/packages/api-model/test/fixtures/erlang-project/include/public_types.hrl @@ -0,0 +1,2 @@ +-doc "An included public type.". +-type included_id() :: non_neg_integer(). diff --git a/packages/api-model/test/fixtures/erlang-project/rebar.config b/packages/api-model/test/fixtures/erlang-project/rebar.config new file mode 100644 index 000000000..06710cba7 --- /dev/null +++ b/packages/api-model/test/fixtures/erlang-project/rebar.config @@ -0,0 +1,2 @@ +{erl_opts, [debug_info, deterministic, warnings_as_errors]}. +{deps, []}. diff --git a/packages/api-model/test/fixtures/erlang-project/src/probe.app.src b/packages/api-model/test/fixtures/erlang-project/src/probe.app.src new file mode 100644 index 000000000..ad1f5405b --- /dev/null +++ b/packages/api-model/test/fixtures/erlang-project/src/probe.app.src @@ -0,0 +1,2 @@ +{application, probe, [{vsn, "0.1.0"}, {modules, []}, + {applications, [kernel, stdlib]}]}. diff --git a/packages/api-model/test/fixtures/erlang-project/src/probe.erl b/packages/api-model/test/fixtures/erlang-project/src/probe.erl new file mode 100644 index 000000000..ecb266a03 --- /dev/null +++ b/packages/api-model/test/fixtures/erlang-project/src/probe.erl @@ -0,0 +1,67 @@ +-module(probe). +-moduledoc """ +Captured values with `m:probe` and `read/1` references. + +```erlang +1> probe:double(2). +4 +``` +""". +-export([double/1, hidden/0, read/1, handle/0, links/1, wide/2]). +-export_type([handle/0, id/0, row/0, included_id/0, 'odd-name'/1, 'λ-handle'/1, 'a::b'/0]). +-export_type([box/0, box/1, container/3, '🧭'/0]). +-export_type([unresolved/0]). +-include("public_types.hrl"). +-include_lib("kernel/include/file.hrl"). +-export_record([row]). + +-record #row{id :: id()}. +-doc "A nominal identifier.". +-nominal id() :: binary(). +-doc "An opaque handle; its representation stays private.". +-opaque handle() :: #{private_token := reference()}. +-doc "A handle with a quoted type name.". +-opaque 'odd-name'(T) :: {private_token, T}. +-doc "A handle with a Unicode name.". +-opaque 'λ-handle'(T) :: {private_token, T}. +-doc "A quoted opaque type whose name includes a delimiter.". +-opaque 'a::b'() :: private_token. +-doc "A supporting output mode.". +-type internal_mode() :: ready | stopped. +-doc "One public row.". +-type row() :: #row{}. +-type box() :: atom(). +-type box(T) :: [T]. +-type container(A, B, C) :: {A, B, C}. +-type '🧭'() :: integer(). +-type unresolved() :: file:no_such_type(). + +-doc "Prepare one row.". +-callback prepare(row()) -> {ok, handle()}. + +-doc "Double an integer or float.". +-doc #{since => "0.1.0", deprecated => "Use a calculator."}. +-spec double(integer()) -> integer(); (float()) -> float(). +double(Number) -> Number * 2. + +-doc "Read one `t:handle/0`; see `c:prepare/1`.". +-spec read(handle()) -> {ok, internal_mode()}. +read(_Handle) -> {ok, ready}. + +-doc "Construct a handle; the type and function share a name.". +-spec handle() -> handle(). +handle() -> #{private_token => make_ref()}. + +-doc "Compiler references distinguish arities, native records and literal names.". +-spec links(probe:container(fun((box(), #probe:row{}) -> box()), + #{key := 'a,b'}, '🧭'())) -> + {'literal:box()', '🧭', '__libtmux_record_0_probe:row', + <<_:8>>, 'a::b'(), box(term()), file:filename_all()}. +links(_Input) -> error(not_called). + +-doc "Keep native typespec punctuation within the API column limit.". +-spec wide(probe:container(term(), term(), term()), box()) -> box(). +wide(_Input, Value) -> Value. + +-doc false. +hidden() -> secret. diff --git a/packages/api-model/test/fixtures/haskell-native/LibTmux-Id.html b/packages/api-model/test/fixtures/haskell-native/LibTmux-Id.html new file mode 100644 index 000000000..cd9b0a4a8 --- /dev/null +++ b/packages/api-model/test/fixtures/haskell-native/LibTmux-Id.html @@ -0,0 +1,14 @@ +LibTmux.Id
libtmux-haskell
Safe HaskellNone
LanguageGHC2024

LibTmux.Id

Description

Distinct session, physical-window and physical-pane IDs.

Parsing and rendering are pure. An ID carries no endpoint, server lifetime + or liveness evidence. Render an ID for external text; use its numeric + accessor when an application needs the mathematical value.

Start with parseSessionId, parseWindowId or parsePaneId. Each type's + documentation links its parser and renderer. Contextual numeric indices + belong to LibTmux.Value.

>>> :set -XOverloadedStrings
+>>> fmap renderWindowId (parseWindowId "@17")
+Right "@17"
+>>> either (const "rejected") renderPaneId (parsePaneId "@17")
+"rejected"
+

Entity identities

data SessionId Source #

A session's unsigned 32-bit tmux identifier, written with a $ prefix. + Parse with parseSessionId; render with renderSessionId.

Instances

Instances details
NFData SessionId Source # 
Instance details

Defined in LibTmux.Id

Methods

rnf :: SessionId -> () #

Eq SessionId Source # 
Instance details

Defined in LibTmux.Id

Ord SessionId Source # 
Instance details

Defined in LibTmux.Id

Show SessionId Source # 
Instance details

Defined in LibTmux.Id

data WindowId Source #

A physical window's identifier, independent of its session links. + Parse with parseWindowId; render with renderWindowId.

Instances

Instances details
NFData WindowId Source # 
Instance details

Defined in LibTmux.Id

Methods

rnf :: WindowId -> () #

Eq WindowId Source # 
Instance details

Defined in LibTmux.Id

Ord WindowId Source # 
Instance details

Defined in LibTmux.Id

Show WindowId Source # 
Instance details

Defined in LibTmux.Id

data PaneId Source #

A physical pane's identifier, written with a % prefix. + Parse with parsePaneId; render with renderPaneId.

Instances

Instances details
NFData PaneId Source # 
Instance details

Defined in LibTmux.Id

Methods

rnf :: PaneId -> () #

Eq PaneId Source # 
Instance details

Defined in LibTmux.Id

Methods

(==) :: PaneId -> PaneId -> Bool #

(/=) :: PaneId -> PaneId -> Bool #

Ord PaneId Source # 
Instance details

Defined in LibTmux.Id

Show PaneId Source # 
Instance details

Defined in LibTmux.Id

Parse external values

data IdError Source #

Invalid canonical syntax, entity prefix or native unsigned range. + Diagnostics retain at most 64 characters of input.

Constructors

InvalidId 

Fields

Instances

Instances details
Eq IdError Source # 
Instance details

Defined in LibTmux.Id

Methods

(==) :: IdError -> IdError -> Bool #

(/=) :: IdError -> IdError -> Bool #

Show IdError Source # 
Instance details

Defined in LibTmux.Id

parseSessionId :: Text -> Either IdError SessionId Source #

Parse $0 through $4294967295. No whitespace or leading zeroes.

parseWindowId :: Text -> Either IdError WindowId Source #

Parse a canonical @number identifying a physical window.

parsePaneId :: Text -> Either IdError PaneId Source #

Parse a canonical %number identifying a physical pane.

Render target text

renderSessionId :: SessionId -> Text Source #

Render the session prefix and decimal ID.

renderWindowId :: WindowId -> Text Source #

Render the physical window prefix and decimal ID.

renderPaneId :: PaneId -> Text Source #

Render the physical pane prefix and decimal ID.

Read numeric values

sessionIdValue :: SessionId -> Integer Source #

Read the numeric session ID without narrowing conversion.

windowIdValue :: WindowId -> Integer Source #

Read the numeric physical window ID.

paneIdValue :: PaneId -> Integer Source #

Read the numeric physical pane ID.

\ No newline at end of file diff --git a/packages/api-model/test/fixtures/haskell-native/LibTmux-Value.html b/packages/api-model/test/fixtures/haskell-native/LibTmux-Value.html new file mode 100644 index 000000000..2ef57c688 --- /dev/null +++ b/packages/api-model/test/fixtures/haskell-native/LibTmux-Value.html @@ -0,0 +1,14 @@ +LibTmux.Value
libtmux-haskell
Safe HaskellNone
LanguageGHC2024

LibTmux.Value

Description

Positive dimensions and nonnegative contextual indices.

Construction and access are pure. Window-link indices and pane indices + have distinct types; neither substitutes for an entity ID. A constructor + checks the mathematical domain, while command-specific limits belong at + the operation boundary. Use mkDimension, mkWindowIndex and mkPaneIndex + to validate input; their accessors return mathematical integers. Entity + identifiers belong to LibTmux.Id.

>>> fmap dimensionValue (mkDimension 120)
+Right 120
+>>> mkDimension 0
+Left (NonPositiveDimension 0)
+

Checked types

data Dimension Source #

Positive cells, constructed with mkDimension. Command and field limits + are checked separately. Compare dimensions directly or use dimensionValue + with an integer literal.

Instances

Instances details
NFData Dimension Source # 
Instance details

Defined in LibTmux.Value

Methods

rnf :: Dimension -> () #

Eq Dimension Source # 
Instance details

Defined in LibTmux.Value

Ord Dimension Source # 
Instance details

Defined in LibTmux.Value

Show Dimension Source # 
Instance details

Defined in LibTmux.Value

data WindowIndex Source #

Nonnegative index of a window link within a session, not a physical window ID. + Construct with mkWindowIndex; read with windowIndexValue.

Instances

Instances details
NFData WindowIndex Source # 
Instance details

Defined in LibTmux.Value

Methods

rnf :: WindowIndex -> () #

Eq WindowIndex Source # 
Instance details

Defined in LibTmux.Value

Ord WindowIndex Source # 
Instance details

Defined in LibTmux.Value

Show WindowIndex Source # 
Instance details

Defined in LibTmux.Value

data PaneIndex Source #

Nonnegative pane index within a window, not a pane ID. + Construct with mkPaneIndex; read with paneIndexValue.

Instances

Instances details
NFData PaneIndex Source # 
Instance details

Defined in LibTmux.Value

Methods

rnf :: PaneIndex -> () #

Eq PaneIndex Source # 
Instance details

Defined in LibTmux.Value

Ord PaneIndex Source # 
Instance details

Defined in LibTmux.Value

Show PaneIndex Source # 
Instance details

Defined in LibTmux.Value

Validate input

data ValueError Source #

A scalar outside its mathematical domain.

Constructors

NonPositiveDimension !Integer

The supplied dimension was zero or negative.

NegativeIndex !Integer

The supplied contextual index was negative.

Instances

Instances details
Eq ValueError Source # 
Instance details

Defined in LibTmux.Value

Show ValueError Source # 
Instance details

Defined in LibTmux.Value

mkDimension :: Integer -> Either ValueError Dimension Source #

Construct a positive dimension without applying a command-specific maximum.

mkWindowIndex :: Integer -> Either ValueError WindowIndex Source #

Construct a nonnegative window-link index.

mkPaneIndex :: Integer -> Either ValueError PaneIndex Source #

Construct a nonnegative pane index.

Read numeric values

dimensionValue :: Dimension -> Integer Source #

Read a dimension as a mathematical integer, without narrowing conversion.

windowIndexValue :: WindowIndex -> Integer Source #

Read a window-link index as a mathematical integer.

paneIndexValue :: PaneIndex -> Integer Source #

Read a pane index as a mathematical integer.

\ No newline at end of file diff --git a/packages/api-model/test/fixtures/haskell-native/LibTmux-Version.html b/packages/api-model/test/fixtures/haskell-native/LibTmux-Version.html new file mode 100644 index 000000000..b839e8022 --- /dev/null +++ b/packages/api-model/test/fixtures/haskell-native/LibTmux-Version.html @@ -0,0 +1,11 @@ +LibTmux.Version
libtmux-haskell
Safe HaskellNone
LanguageGHC2024

LibTmux.Version

Description

Parse stable tmux releases and apply the minimum-version admission check.

These functions consume supplied text. They neither execute tmux -V + nor contact a server. Admission establishes the minimum release only; + individual features still need capability and conformance checks.

Use parseVersion for input, requireSupported for minimum-version + admission and renderVersion for canonical output.

>>> :set -XOverloadedStrings
+>>> fmap renderVersion (parseVersion "tmux 3.3\n" >>= requireSupported)
+Right "3.3"
+

Release identity and errors

data TmuxVersion Source #

A stable release, constructed by parseVersion and rendered by + renderVersion. Ordering compares numeric components before the patch letter.

data VersionError Source #

Invalid release syntax or a release below the supported floor.

Constructors

MalformedVersion !Text

Bounded copy of input that is not a stable release.

UnsupportedVersion !TmuxVersion

A stable release older than plain tmux 3.3.

Instances

Instances details
Eq VersionError Source # 
Instance details

Defined in LibTmux.Version

Show VersionError Source # 
Instance details

Defined in LibTmux.Version

Parse and render

parseVersion :: Text -> Either VersionError TmuxVersion Source #

Parse a stable release or the output of tmux -V, allowing one final LF. + Development builds and trailing data are rejected rather than assigned + capabilities from a guessed stable version. Diagnostics retain at most 64 chars.

renderVersion :: TmuxVersion -> Text Source #

Render the canonical release without the executable name or newline.

Admit a release

requireSupported :: TmuxVersion -> Either VersionError TmuxVersion Source #

Reject releases older than plain 3.3. Individual features need their own + capability checks; passing this check does not qualify an entire release.

\ No newline at end of file diff --git a/packages/api-model/test/fixtures/haskell-native/artifact.json b/packages/api-model/test/fixtures/haskell-native/artifact.json new file mode 100644 index 000000000..72c73ef89 --- /dev/null +++ b/packages/api-model/test/fixtures/haskell-native/artifact.json @@ -0,0 +1,2638 @@ +{ + "compiler": "9.14.1", + "component": "lib:libtmux-haskell", + "haddock": "2.33.0", + "modules": [ + { + "groups": [ + { + "members": [ + "LibTmux.Id#t:SessionId", + "LibTmux.Id#t:WindowId", + "LibTmux.Id#t:PaneId" + ], + "title": "Entity identities" + }, + { + "members": [ + "LibTmux.Id#t:IdError", + "LibTmux.Id#v:parseSessionId", + "LibTmux.Id#v:parseWindowId", + "LibTmux.Id#v:parsePaneId" + ], + "title": "Parse external values" + }, + { + "members": [ + "LibTmux.Id#v:renderSessionId", + "LibTmux.Id#v:renderWindowId", + "LibTmux.Id#v:renderPaneId" + ], + "title": "Render target text" + }, + { + "members": [ + "LibTmux.Id#v:sessionIdValue", + "LibTmux.Id#v:windowIdValue", + "LibTmux.Id#v:paneIdValue" + ], + "title": "Read numeric values" + } + ], + "name": "LibTmux.Id" + }, + { + "groups": [ + { + "members": [ + "LibTmux.Value#t:Dimension", + "LibTmux.Value#t:WindowIndex", + "LibTmux.Value#t:PaneIndex" + ], + "title": "Checked types" + }, + { + "members": [ + "LibTmux.Value#t:ValueError", + "LibTmux.Value#v:mkDimension", + "LibTmux.Value#v:mkWindowIndex", + "LibTmux.Value#v:mkPaneIndex" + ], + "title": "Validate input" + }, + { + "members": [ + "LibTmux.Value#v:dimensionValue", + "LibTmux.Value#v:windowIndexValue", + "LibTmux.Value#v:paneIndexValue" + ], + "title": "Read numeric values" + } + ], + "name": "LibTmux.Value" + }, + { + "groups": [ + { + "members": [ + "LibTmux.Version#t:TmuxVersion", + "LibTmux.Version#t:VersionError" + ], + "title": "Release identity and errors" + }, + { + "members": [ + "LibTmux.Version#v:parseVersion", + "LibTmux.Version#v:renderVersion" + ], + "title": "Parse and render" + }, + { + "members": [ + "LibTmux.Version#v:requireSupported" + ], + "title": "Admit a release" + } + ], + "name": "LibTmux.Version" + } + ], + "nativeProvenance": { + "exporter": { + "build": { + "cabal": "3.18.2.0", + "compiler": "ghc-9.14.1", + "platform": "x86_64-linux", + "unit": "libtmux-haskell-0.1.0.0-inplace" + }, + "interfaceStream": "stderr", + "name": "Haddock public interface export", + "nativeArtifacts": [ + { + "path": "LibTmux-Id.html", + "sha256": "cf7102eba62a0e9b02e7ea7acefb85d1822a4d192a1fceb680246ed42bd10d45" + }, + { + "path": "LibTmux-Value.html", + "sha256": "4160151534c27a8c787c9ab36fa6dcbf740fc193a7a3553935172be72111ff1d" + }, + { + "path": "LibTmux-Version.html", + "sha256": "7894f9afe9260e6d2d429aaf0b3f246428980b76756bba8d7a3ccc0637b22a6a" + }, + { + "path": "interface.haddock", + "sha256": "e5e681a81e00bd49b19e1795ca898be1f75428e723b3ede2c0dd4813bf53f523" + }, + { + "path": "interface.json", + "sha256": "86a91b1f70740fcf28ccfe9ceebc4135241393d3fd5d5a170411b04e76a24915" + }, + { + "path": "src/LibTmux.Id.html", + "sha256": "49f0a33965cbd4566467577a4a6456e90891bff58dd39371d1fa5eb869b7d405" + }, + { + "path": "src/LibTmux.Value.html", + "sha256": "7cb42aa24f8fc69c6b5cacd5a218cdeefd861ce58b8e3b043490c354979e353c" + }, + { + "path": "src/LibTmux.Version.html", + "sha256": "d537c07eb6f374824b8b4e5f0d7291690d49f83c7a080bc6006db604afe9b08e" + } + ], + "path": "packages/api-model/scripts/export-haskell.py", + "repository": "libtmux/docs", + "revision": "66367c42a52c2320a14b8ca97ddaf674fdb4bea9", + "sha256": "ef54874a2029410e3553ad2e5cce831c1748406fff3238b256698394a7a6425f", + "version": 1 + }, + "files": [ + { + "path": ".tool-versions", + "sha256": "13c8a19b336b86a161f4d5ea74347960e884e2c0887d399fe752d84eecfd35e7" + }, + { + "path": "cabal.project", + "sha256": "743c92538c542ba3a29c27efa077c5826f5fa1f186c4c69f53d63cb49176aa6a" + }, + { + "path": "libtmux-haskell.cabal", + "sha256": "ff1eb8adc0c11a88cc1e789acc9e680279e1550f09bd1867cceabb906a002096" + }, + { + "path": "src/LibTmux/Id.hs", + "sha256": "3456edf88bf412e8769e5c96cc5d35b7b118ea3bd3786f167c9002f9804fb3b7" + }, + { + "path": "src/LibTmux/Value.hs", + "sha256": "e199c3d0bbf08a159daa35bb4ae9a5d2ad4761117d375f292dd8b250bb459e55" + }, + { + "path": "src/LibTmux/Version.hs", + "sha256": "1ffed8288c61c2194de88d37c5398e099752e0798adf2fe6acceceeba0ba5530" + } + ] + }, + "package": { + "exposedModules": [ + "LibTmux.Id", + "LibTmux.Value", + "LibTmux.Version" + ], + "name": "libtmux-haskell", + "version": "0.1.0.0" + }, + "port": "haskell", + "repo": "libtmux/libtmux-haskell", + "revision": "b832983fc30d41f03fee84282794d5568f62e15a", + "schema": "libtmux.haskell-api/1", + "symbols": [ + { + "apiScope": "exported", + "doc": { + "body": "Parsing and rendering are pure. An ID carries no endpoint, server lifetime\n or liveness evidence. Render an ID for external text; use its numeric\n accessor when an application needs the mathematical value.\n\nStart with :obj:`parseSessionId `, :obj:`parseWindowId ` or :obj:`parsePaneId `. Each type's\n documentation links its parser and renderer. Contextual numeric indices\n belong to :obj:`LibTmux.Value `.\n\n\n\n```haskell\n>>> :set -XOverloadedStrings\n>>> fmap renderWindowId (parseWindowId \"@17\")\nRight \"@17\"\n>>> either (const \"rejected\") renderPaneId (parsePaneId \"@17\")\n\"rejected\"\n```", + "summary": "Distinct session, physical-window and physical-pane IDs." + }, + "id": "LibTmux.Id", + "kind": "module", + "modifiers": [], + "name": "LibTmux.Id", + "package": "libtmux-haskell", + "parent": null, + "product": "core", + "signatures": [], + "source": { + "file": "src/LibTmux/Id.hs", + "revision": "b832983fc30d41f03fee84282794d5568f62e15a" + } + }, + { + "apiScope": "exported", + "doc": { + "body": "Construction and access are pure. Window-link indices and pane indices\n have distinct types; neither substitutes for an entity ID. A constructor\n checks the mathematical domain, while command-specific limits belong at\n the operation boundary. Use :obj:`mkDimension `, :obj:`mkWindowIndex ` and :obj:`mkPaneIndex `\n to validate input; their accessors return mathematical integers. Entity\n identifiers belong to :obj:`LibTmux.Id `.\n\n\n\n```haskell\n>>> fmap dimensionValue (mkDimension 120)\nRight 120\n>>> mkDimension 0\nLeft (NonPositiveDimension 0)\n```", + "summary": "Positive dimensions and nonnegative contextual indices." + }, + "id": "LibTmux.Value", + "kind": "module", + "modifiers": [], + "name": "LibTmux.Value", + "package": "libtmux-haskell", + "parent": null, + "product": "core", + "signatures": [], + "source": { + "file": "src/LibTmux/Value.hs", + "revision": "b832983fc30d41f03fee84282794d5568f62e15a" + } + }, + { + "apiScope": "exported", + "doc": { + "body": "These functions consume supplied text. They neither execute `tmux -V`\n nor contact a server. Admission establishes the minimum release only;\n individual features still need capability and conformance checks.\n\nUse :obj:`parseVersion ` for input, :obj:`requireSupported ` for minimum-version\n admission and :obj:`renderVersion ` for canonical output.\n\n\n\n```haskell\n>>> :set -XOverloadedStrings\n>>> fmap renderVersion (parseVersion \"tmux 3.3\\n\" >>= requireSupported)\nRight \"3.3\"\n```", + "summary": "Parse stable tmux releases and apply the minimum-version admission check." + }, + "id": "LibTmux.Version", + "kind": "module", + "modifiers": [], + "name": "LibTmux.Version", + "package": "libtmux-haskell", + "parent": null, + "product": "core", + "signatures": [], + "source": { + "file": "src/LibTmux/Version.hs", + "revision": "b832983fc30d41f03fee84282794d5568f62e15a" + } + }, + { + "apiScope": "exported", + "doc": { + "summary": "A session's unsigned 32-bit tmux identifier, written with a `$` prefix.\n Parse with :obj:`parseSessionId `; render with :obj:`renderSessionId `." + }, + "id": "LibTmux.Id#t:SessionId", + "instances": [ + { + "doc": null, + "markdown": "instance [NFData](https://hackage.haskell.org/package/deepseq-1.5.1.0/docs/Control-DeepSeq.html#t:NFData) :obj:`SessionId `", + "raw": "instance NFData SessionId", + "references": [ + { + "href": "https://hackage.haskell.org/package/deepseq-1.5.1.0/docs/Control-DeepSeq.html#t:NFData", + "text": "NFData" + }, + { + "href": "LibTmux-Id.html#t:SessionId", + "target": "LibTmux.Id#t:SessionId", + "text": "SessionId" + } + ], + "source": { + "file": "src/LibTmux/Id.hs", + "line": 47, + "revision": "b832983fc30d41f03fee84282794d5568f62e15a" + } + }, + { + "doc": null, + "markdown": "instance [Eq](https://hackage.haskell.org/package/base-4.22.0.0/docs/Data-Eq.html#t:Eq) :obj:`SessionId `", + "raw": "instance Eq SessionId", + "references": [ + { + "href": "https://hackage.haskell.org/package/base-4.22.0.0/docs/Data-Eq.html#t:Eq", + "text": "Eq" + }, + { + "href": "LibTmux-Id.html#t:SessionId", + "target": "LibTmux.Id#t:SessionId", + "text": "SessionId" + } + ], + "source": { + "file": "src/LibTmux/Id.hs", + "line": 46, + "revision": "b832983fc30d41f03fee84282794d5568f62e15a" + } + }, + { + "doc": null, + "markdown": "instance [Ord](https://hackage.haskell.org/package/base-4.22.0.0/docs/Data-Ord.html#t:Ord) :obj:`SessionId `", + "raw": "instance Ord SessionId", + "references": [ + { + "href": "https://hackage.haskell.org/package/base-4.22.0.0/docs/Data-Ord.html#t:Ord", + "text": "Ord" + }, + { + "href": "LibTmux-Id.html#t:SessionId", + "target": "LibTmux.Id#t:SessionId", + "text": "SessionId" + } + ], + "source": { + "file": "src/LibTmux/Id.hs", + "line": 46, + "revision": "b832983fc30d41f03fee84282794d5568f62e15a" + } + }, + { + "doc": null, + "markdown": "instance [Show](https://hackage.haskell.org/package/base-4.22.0.0/docs/Prelude.html#t:Show) :obj:`SessionId `", + "raw": "instance Show SessionId", + "references": [ + { + "href": "https://hackage.haskell.org/package/base-4.22.0.0/docs/Prelude.html#t:Show", + "text": "Show" + }, + { + "href": "LibTmux-Id.html#t:SessionId", + "target": "LibTmux.Id#t:SessionId", + "text": "SessionId" + } + ], + "source": { + "file": "src/LibTmux/Id.hs", + "line": 46, + "revision": "b832983fc30d41f03fee84282794d5568f62e15a" + } + } + ], + "kind": "typealias", + "modifiers": [ + "opaque" + ], + "name": "SessionId", + "namespace": "LibTmux.Id", + "package": "libtmux-haskell", + "parent": "LibTmux.Id", + "product": "core", + "publicId": "LibTmux.Id#t:SessionId", + "qualifiedName": "LibTmux.Id.SessionId", + "signatures": [ + { + "nativeSpans": [ + { + "keyword": true, + "text": "data" + }, + { + "text": " " + }, + { + "declaration": true, + "text": "SessionId" + } + ], + "params": [], + "raw": "data SessionId" + } + ], + "source": { + "file": "src/LibTmux/Id.hs", + "line": 45, + "revision": "b832983fc30d41f03fee84282794d5568f62e15a" + } + }, + { + "apiScope": "exported", + "doc": { + "summary": "A physical window's identifier, independent of its session links.\n Parse with :obj:`parseWindowId `; render with :obj:`renderWindowId `." + }, + "id": "LibTmux.Id#t:WindowId", + "instances": [ + { + "doc": null, + "markdown": "instance [NFData](https://hackage.haskell.org/package/deepseq-1.5.1.0/docs/Control-DeepSeq.html#t:NFData) :obj:`WindowId `", + "raw": "instance NFData WindowId", + "references": [ + { + "href": "https://hackage.haskell.org/package/deepseq-1.5.1.0/docs/Control-DeepSeq.html#t:NFData", + "text": "NFData" + }, + { + "href": "LibTmux-Id.html#t:WindowId", + "target": "LibTmux.Id#t:WindowId", + "text": "WindowId" + } + ], + "source": { + "file": "src/LibTmux/Id.hs", + "line": 53, + "revision": "b832983fc30d41f03fee84282794d5568f62e15a" + } + }, + { + "doc": null, + "markdown": "instance [Eq](https://hackage.haskell.org/package/base-4.22.0.0/docs/Data-Eq.html#t:Eq) :obj:`WindowId `", + "raw": "instance Eq WindowId", + "references": [ + { + "href": "https://hackage.haskell.org/package/base-4.22.0.0/docs/Data-Eq.html#t:Eq", + "text": "Eq" + }, + { + "href": "LibTmux-Id.html#t:WindowId", + "target": "LibTmux.Id#t:WindowId", + "text": "WindowId" + } + ], + "source": { + "file": "src/LibTmux/Id.hs", + "line": 52, + "revision": "b832983fc30d41f03fee84282794d5568f62e15a" + } + }, + { + "doc": null, + "markdown": "instance [Ord](https://hackage.haskell.org/package/base-4.22.0.0/docs/Data-Ord.html#t:Ord) :obj:`WindowId `", + "raw": "instance Ord WindowId", + "references": [ + { + "href": "https://hackage.haskell.org/package/base-4.22.0.0/docs/Data-Ord.html#t:Ord", + "text": "Ord" + }, + { + "href": "LibTmux-Id.html#t:WindowId", + "target": "LibTmux.Id#t:WindowId", + "text": "WindowId" + } + ], + "source": { + "file": "src/LibTmux/Id.hs", + "line": 52, + "revision": "b832983fc30d41f03fee84282794d5568f62e15a" + } + }, + { + "doc": null, + "markdown": "instance [Show](https://hackage.haskell.org/package/base-4.22.0.0/docs/Prelude.html#t:Show) :obj:`WindowId `", + "raw": "instance Show WindowId", + "references": [ + { + "href": "https://hackage.haskell.org/package/base-4.22.0.0/docs/Prelude.html#t:Show", + "text": "Show" + }, + { + "href": "LibTmux-Id.html#t:WindowId", + "target": "LibTmux.Id#t:WindowId", + "text": "WindowId" + } + ], + "source": { + "file": "src/LibTmux/Id.hs", + "line": 52, + "revision": "b832983fc30d41f03fee84282794d5568f62e15a" + } + } + ], + "kind": "typealias", + "modifiers": [ + "opaque" + ], + "name": "WindowId", + "namespace": "LibTmux.Id", + "package": "libtmux-haskell", + "parent": "LibTmux.Id", + "product": "core", + "publicId": "LibTmux.Id#t:WindowId", + "qualifiedName": "LibTmux.Id.WindowId", + "signatures": [ + { + "nativeSpans": [ + { + "keyword": true, + "text": "data" + }, + { + "text": " " + }, + { + "declaration": true, + "text": "WindowId" + } + ], + "params": [], + "raw": "data WindowId" + } + ], + "source": { + "file": "src/LibTmux/Id.hs", + "line": 51, + "revision": "b832983fc30d41f03fee84282794d5568f62e15a" + } + }, + { + "apiScope": "exported", + "doc": { + "summary": "A physical pane's identifier, written with a `%` prefix.\n Parse with :obj:`parsePaneId `; render with :obj:`renderPaneId `." + }, + "id": "LibTmux.Id#t:PaneId", + "instances": [ + { + "doc": null, + "markdown": "instance [NFData](https://hackage.haskell.org/package/deepseq-1.5.1.0/docs/Control-DeepSeq.html#t:NFData) :obj:`PaneId `", + "raw": "instance NFData PaneId", + "references": [ + { + "href": "https://hackage.haskell.org/package/deepseq-1.5.1.0/docs/Control-DeepSeq.html#t:NFData", + "text": "NFData" + }, + { + "href": "LibTmux-Id.html#t:PaneId", + "target": "LibTmux.Id#t:PaneId", + "text": "PaneId" + } + ], + "source": { + "file": "src/LibTmux/Id.hs", + "line": 59, + "revision": "b832983fc30d41f03fee84282794d5568f62e15a" + } + }, + { + "doc": null, + "markdown": "instance [Eq](https://hackage.haskell.org/package/base-4.22.0.0/docs/Data-Eq.html#t:Eq) :obj:`PaneId `", + "raw": "instance Eq PaneId", + "references": [ + { + "href": "https://hackage.haskell.org/package/base-4.22.0.0/docs/Data-Eq.html#t:Eq", + "text": "Eq" + }, + { + "href": "LibTmux-Id.html#t:PaneId", + "target": "LibTmux.Id#t:PaneId", + "text": "PaneId" + } + ], + "source": { + "file": "src/LibTmux/Id.hs", + "line": 58, + "revision": "b832983fc30d41f03fee84282794d5568f62e15a" + } + }, + { + "doc": null, + "markdown": "instance [Ord](https://hackage.haskell.org/package/base-4.22.0.0/docs/Data-Ord.html#t:Ord) :obj:`PaneId `", + "raw": "instance Ord PaneId", + "references": [ + { + "href": "https://hackage.haskell.org/package/base-4.22.0.0/docs/Data-Ord.html#t:Ord", + "text": "Ord" + }, + { + "href": "LibTmux-Id.html#t:PaneId", + "target": "LibTmux.Id#t:PaneId", + "text": "PaneId" + } + ], + "source": { + "file": "src/LibTmux/Id.hs", + "line": 58, + "revision": "b832983fc30d41f03fee84282794d5568f62e15a" + } + }, + { + "doc": null, + "markdown": "instance [Show](https://hackage.haskell.org/package/base-4.22.0.0/docs/Prelude.html#t:Show) :obj:`PaneId `", + "raw": "instance Show PaneId", + "references": [ + { + "href": "https://hackage.haskell.org/package/base-4.22.0.0/docs/Prelude.html#t:Show", + "text": "Show" + }, + { + "href": "LibTmux-Id.html#t:PaneId", + "target": "LibTmux.Id#t:PaneId", + "text": "PaneId" + } + ], + "source": { + "file": "src/LibTmux/Id.hs", + "line": 58, + "revision": "b832983fc30d41f03fee84282794d5568f62e15a" + } + } + ], + "kind": "typealias", + "modifiers": [ + "opaque" + ], + "name": "PaneId", + "namespace": "LibTmux.Id", + "package": "libtmux-haskell", + "parent": "LibTmux.Id", + "product": "core", + "publicId": "LibTmux.Id#t:PaneId", + "qualifiedName": "LibTmux.Id.PaneId", + "signatures": [ + { + "nativeSpans": [ + { + "keyword": true, + "text": "data" + }, + { + "text": " " + }, + { + "declaration": true, + "text": "PaneId" + } + ], + "params": [], + "raw": "data PaneId" + } + ], + "source": { + "file": "src/LibTmux/Id.hs", + "line": 57, + "revision": "b832983fc30d41f03fee84282794d5568f62e15a" + } + }, + { + "apiScope": "exported", + "doc": { + "summary": "Invalid canonical syntax, entity prefix or native unsigned range.\n Diagnostics retain at most 64 characters of input." + }, + "id": "LibTmux.Id#t:IdError", + "instances": [ + { + "doc": null, + "markdown": "instance [Eq](https://hackage.haskell.org/package/base-4.22.0.0/docs/Data-Eq.html#t:Eq) :obj:`IdError `", + "raw": "instance Eq IdError", + "references": [ + { + "href": "https://hackage.haskell.org/package/base-4.22.0.0/docs/Data-Eq.html#t:Eq", + "text": "Eq" + }, + { + "href": "LibTmux-Id.html#t:IdError", + "target": "LibTmux.Id#t:IdError", + "text": "IdError" + } + ], + "source": { + "file": "src/LibTmux/Id.hs", + "line": 67, + "revision": "b832983fc30d41f03fee84282794d5568f62e15a" + } + }, + { + "doc": null, + "markdown": "instance [Show](https://hackage.haskell.org/package/base-4.22.0.0/docs/Prelude.html#t:Show) :obj:`IdError `", + "raw": "instance Show IdError", + "references": [ + { + "href": "https://hackage.haskell.org/package/base-4.22.0.0/docs/Prelude.html#t:Show", + "text": "Show" + }, + { + "href": "LibTmux-Id.html#t:IdError", + "target": "LibTmux.Id#t:IdError", + "text": "IdError" + } + ], + "source": { + "file": "src/LibTmux/Id.hs", + "line": 67, + "revision": "b832983fc30d41f03fee84282794d5568f62e15a" + } + } + ], + "kind": "typealias", + "modifiers": [], + "name": "IdError", + "namespace": "LibTmux.Id", + "package": "libtmux-haskell", + "parent": "LibTmux.Id", + "product": "core", + "publicId": "LibTmux.Id#t:IdError", + "qualifiedName": "LibTmux.Id.IdError", + "signatures": [ + { + "nativeSpans": [ + { + "keyword": true, + "text": "data" + }, + { + "text": " " + }, + { + "declaration": true, + "text": "IdError" + } + ], + "params": [], + "raw": "data IdError" + } + ], + "source": { + "file": "src/LibTmux/Id.hs", + "line": 63, + "revision": "b832983fc30d41f03fee84282794d5568f62e15a" + } + }, + { + "apiScope": "exported", + "doc": null, + "id": "LibTmux.Id#v:InvalidId", + "kind": "function", + "modifiers": [], + "name": "InvalidId", + "namespace": "LibTmux.Id", + "package": "libtmux-haskell", + "parent": "LibTmux.Id#t:IdError", + "product": "core", + "publicId": "LibTmux.Id#v:InvalidId", + "qualifiedName": "LibTmux.Id.InvalidId", + "signatures": [ + { + "methodKind": "constructor", + "nativeSpans": [ + { + "declaration": true, + "text": "InvalidId" + } + ], + "params": [], + "raw": "InvalidId" + } + ], + "source": { + "file": "src/LibTmux/Id.hs", + "line": 63, + "revision": "b832983fc30d41f03fee84282794d5568f62e15a" + } + }, + { + "apiScope": "exported", + "doc": { + "summary": "Required entity prefix." + }, + "id": "LibTmux.Id#v:expectedPrefix", + "kind": "property", + "modifiers": [], + "name": "expectedPrefix", + "namespace": "LibTmux.Id", + "package": "libtmux-haskell", + "parent": "LibTmux.Id#t:IdError", + "product": "core", + "publicId": "LibTmux.Id#v:expectedPrefix", + "qualifiedName": "LibTmux.Id.expectedPrefix", + "signatures": [ + { + "nativeSpans": [ + { + "declaration": true, + "text": "expectedPrefix" + }, + { + "text": " :: !" + }, + { + "href": "https://hackage.haskell.org/package/base-4.22.0.0/docs/Data-Char.html#t:Char", + "text": "Char" + } + ], + "params": [], + "raw": "expectedPrefix :: !Char" + } + ], + "source": { + "file": "src/LibTmux/Id.hs", + "line": 64, + "revision": "b832983fc30d41f03fee84282794d5568f62e15a" + } + }, + { + "apiScope": "exported", + "doc": { + "summary": "Bounded copy of the invalid input." + }, + "id": "LibTmux.Id#v:input", + "kind": "property", + "modifiers": [], + "name": "input", + "namespace": "LibTmux.Id", + "package": "libtmux-haskell", + "parent": "LibTmux.Id#t:IdError", + "product": "core", + "publicId": "LibTmux.Id#v:input", + "qualifiedName": "LibTmux.Id.input", + "signatures": [ + { + "nativeSpans": [ + { + "declaration": true, + "text": "input" + }, + { + "text": " :: !" + }, + { + "href": "https://hackage.haskell.org/package/text-2.1.3/docs/Data-Text.html#t:Text", + "text": "Text" + } + ], + "params": [], + "raw": "input :: !Text" + } + ], + "source": { + "file": "src/LibTmux/Id.hs", + "line": 65, + "revision": "b832983fc30d41f03fee84282794d5568f62e15a" + } + }, + { + "apiScope": "exported", + "doc": { + "summary": "Parse `$0` through `$4294967295`. No whitespace or leading zeroes." + }, + "id": "LibTmux.Id#v:parseSessionId", + "kind": "function", + "modifiers": [], + "name": "parseSessionId", + "namespace": "LibTmux.Id", + "package": "libtmux-haskell", + "parent": "LibTmux.Id", + "product": "core", + "publicId": "LibTmux.Id#v:parseSessionId", + "qualifiedName": "LibTmux.Id.parseSessionId", + "signatures": [ + { + "nativeSpans": [ + { + "declaration": true, + "text": "parseSessionId" + }, + { + "text": " :: " + }, + { + "href": "https://hackage.haskell.org/package/text-2.1.3/docs/Data-Text.html#t:Text", + "text": "Text" + }, + { + "text": " -> " + }, + { + "href": "https://hackage.haskell.org/package/base-4.22.0.0/docs/Data-Either.html#t:Either", + "text": "Either" + }, + { + "text": " " + }, + { + "href": "LibTmux-Id.html#t:IdError", + "target": "LibTmux.Id#t:IdError", + "text": "IdError" + }, + { + "text": " " + }, + { + "href": "LibTmux-Id.html#t:SessionId", + "target": "LibTmux.Id#t:SessionId", + "text": "SessionId" + } + ], + "params": [], + "raw": "parseSessionId :: Text -> Either IdError SessionId" + } + ], + "source": { + "file": "src/LibTmux/Id.hs", + "line": 71, + "revision": "b832983fc30d41f03fee84282794d5568f62e15a" + } + }, + { + "apiScope": "exported", + "doc": { + "summary": "Parse a canonical `@number` identifying a physical window." + }, + "id": "LibTmux.Id#v:parseWindowId", + "kind": "function", + "modifiers": [], + "name": "parseWindowId", + "namespace": "LibTmux.Id", + "package": "libtmux-haskell", + "parent": "LibTmux.Id", + "product": "core", + "publicId": "LibTmux.Id#v:parseWindowId", + "qualifiedName": "LibTmux.Id.parseWindowId", + "signatures": [ + { + "nativeSpans": [ + { + "declaration": true, + "text": "parseWindowId" + }, + { + "text": " :: " + }, + { + "href": "https://hackage.haskell.org/package/text-2.1.3/docs/Data-Text.html#t:Text", + "text": "Text" + }, + { + "text": " -> " + }, + { + "href": "https://hackage.haskell.org/package/base-4.22.0.0/docs/Data-Either.html#t:Either", + "text": "Either" + }, + { + "text": " " + }, + { + "href": "LibTmux-Id.html#t:IdError", + "target": "LibTmux.Id#t:IdError", + "text": "IdError" + }, + { + "text": " " + }, + { + "href": "LibTmux-Id.html#t:WindowId", + "target": "LibTmux.Id#t:WindowId", + "text": "WindowId" + } + ], + "params": [], + "raw": "parseWindowId :: Text -> Either IdError WindowId" + } + ], + "source": { + "file": "src/LibTmux/Id.hs", + "line": 75, + "revision": "b832983fc30d41f03fee84282794d5568f62e15a" + } + }, + { + "apiScope": "exported", + "doc": { + "summary": "Parse a canonical `%number` identifying a physical pane." + }, + "id": "LibTmux.Id#v:parsePaneId", + "kind": "function", + "modifiers": [], + "name": "parsePaneId", + "namespace": "LibTmux.Id", + "package": "libtmux-haskell", + "parent": "LibTmux.Id", + "product": "core", + "publicId": "LibTmux.Id#v:parsePaneId", + "qualifiedName": "LibTmux.Id.parsePaneId", + "signatures": [ + { + "nativeSpans": [ + { + "declaration": true, + "text": "parsePaneId" + }, + { + "text": " :: " + }, + { + "href": "https://hackage.haskell.org/package/text-2.1.3/docs/Data-Text.html#t:Text", + "text": "Text" + }, + { + "text": " -> " + }, + { + "href": "https://hackage.haskell.org/package/base-4.22.0.0/docs/Data-Either.html#t:Either", + "text": "Either" + }, + { + "text": " " + }, + { + "href": "LibTmux-Id.html#t:IdError", + "target": "LibTmux.Id#t:IdError", + "text": "IdError" + }, + { + "text": " " + }, + { + "href": "LibTmux-Id.html#t:PaneId", + "target": "LibTmux.Id#t:PaneId", + "text": "PaneId" + } + ], + "params": [], + "raw": "parsePaneId :: Text -> Either IdError PaneId" + } + ], + "source": { + "file": "src/LibTmux/Id.hs", + "line": 79, + "revision": "b832983fc30d41f03fee84282794d5568f62e15a" + } + }, + { + "apiScope": "exported", + "doc": { + "summary": "Render the session prefix and decimal ID." + }, + "id": "LibTmux.Id#v:renderSessionId", + "kind": "function", + "modifiers": [], + "name": "renderSessionId", + "namespace": "LibTmux.Id", + "package": "libtmux-haskell", + "parent": "LibTmux.Id", + "product": "core", + "publicId": "LibTmux.Id#v:renderSessionId", + "qualifiedName": "LibTmux.Id.renderSessionId", + "signatures": [ + { + "nativeSpans": [ + { + "declaration": true, + "text": "renderSessionId" + }, + { + "text": " :: " + }, + { + "href": "LibTmux-Id.html#t:SessionId", + "target": "LibTmux.Id#t:SessionId", + "text": "SessionId" + }, + { + "text": " -> " + }, + { + "href": "https://hackage.haskell.org/package/text-2.1.3/docs/Data-Text.html#t:Text", + "text": "Text" + } + ], + "params": [], + "raw": "renderSessionId :: SessionId -> Text" + } + ], + "source": { + "file": "src/LibTmux/Id.hs", + "line": 83, + "revision": "b832983fc30d41f03fee84282794d5568f62e15a" + } + }, + { + "apiScope": "exported", + "doc": { + "summary": "Render the physical window prefix and decimal ID." + }, + "id": "LibTmux.Id#v:renderWindowId", + "kind": "function", + "modifiers": [], + "name": "renderWindowId", + "namespace": "LibTmux.Id", + "package": "libtmux-haskell", + "parent": "LibTmux.Id", + "product": "core", + "publicId": "LibTmux.Id#v:renderWindowId", + "qualifiedName": "LibTmux.Id.renderWindowId", + "signatures": [ + { + "nativeSpans": [ + { + "declaration": true, + "text": "renderWindowId" + }, + { + "text": " :: " + }, + { + "href": "LibTmux-Id.html#t:WindowId", + "target": "LibTmux.Id#t:WindowId", + "text": "WindowId" + }, + { + "text": " -> " + }, + { + "href": "https://hackage.haskell.org/package/text-2.1.3/docs/Data-Text.html#t:Text", + "text": "Text" + } + ], + "params": [], + "raw": "renderWindowId :: WindowId -> Text" + } + ], + "source": { + "file": "src/LibTmux/Id.hs", + "line": 87, + "revision": "b832983fc30d41f03fee84282794d5568f62e15a" + } + }, + { + "apiScope": "exported", + "doc": { + "summary": "Render the physical pane prefix and decimal ID." + }, + "id": "LibTmux.Id#v:renderPaneId", + "kind": "function", + "modifiers": [], + "name": "renderPaneId", + "namespace": "LibTmux.Id", + "package": "libtmux-haskell", + "parent": "LibTmux.Id", + "product": "core", + "publicId": "LibTmux.Id#v:renderPaneId", + "qualifiedName": "LibTmux.Id.renderPaneId", + "signatures": [ + { + "nativeSpans": [ + { + "declaration": true, + "text": "renderPaneId" + }, + { + "text": " :: " + }, + { + "href": "LibTmux-Id.html#t:PaneId", + "target": "LibTmux.Id#t:PaneId", + "text": "PaneId" + }, + { + "text": " -> " + }, + { + "href": "https://hackage.haskell.org/package/text-2.1.3/docs/Data-Text.html#t:Text", + "text": "Text" + } + ], + "params": [], + "raw": "renderPaneId :: PaneId -> Text" + } + ], + "source": { + "file": "src/LibTmux/Id.hs", + "line": 91, + "revision": "b832983fc30d41f03fee84282794d5568f62e15a" + } + }, + { + "apiScope": "exported", + "doc": { + "summary": "Read the numeric session ID without narrowing conversion." + }, + "id": "LibTmux.Id#v:sessionIdValue", + "kind": "function", + "modifiers": [], + "name": "sessionIdValue", + "namespace": "LibTmux.Id", + "package": "libtmux-haskell", + "parent": "LibTmux.Id", + "product": "core", + "publicId": "LibTmux.Id#v:sessionIdValue", + "qualifiedName": "LibTmux.Id.sessionIdValue", + "signatures": [ + { + "nativeSpans": [ + { + "declaration": true, + "text": "sessionIdValue" + }, + { + "text": " :: " + }, + { + "href": "LibTmux-Id.html#t:SessionId", + "target": "LibTmux.Id#t:SessionId", + "text": "SessionId" + }, + { + "text": " -> " + }, + { + "href": "https://hackage.haskell.org/package/base-4.22.0.0/docs/Prelude.html#t:Integer", + "text": "Integer" + } + ], + "params": [], + "raw": "sessionIdValue :: SessionId -> Integer" + } + ], + "source": { + "file": "src/LibTmux/Id.hs", + "line": 95, + "revision": "b832983fc30d41f03fee84282794d5568f62e15a" + } + }, + { + "apiScope": "exported", + "doc": { + "summary": "Read the numeric physical window ID." + }, + "id": "LibTmux.Id#v:windowIdValue", + "kind": "function", + "modifiers": [], + "name": "windowIdValue", + "namespace": "LibTmux.Id", + "package": "libtmux-haskell", + "parent": "LibTmux.Id", + "product": "core", + "publicId": "LibTmux.Id#v:windowIdValue", + "qualifiedName": "LibTmux.Id.windowIdValue", + "signatures": [ + { + "nativeSpans": [ + { + "declaration": true, + "text": "windowIdValue" + }, + { + "text": " :: " + }, + { + "href": "LibTmux-Id.html#t:WindowId", + "target": "LibTmux.Id#t:WindowId", + "text": "WindowId" + }, + { + "text": " -> " + }, + { + "href": "https://hackage.haskell.org/package/base-4.22.0.0/docs/Prelude.html#t:Integer", + "text": "Integer" + } + ], + "params": [], + "raw": "windowIdValue :: WindowId -> Integer" + } + ], + "source": { + "file": "src/LibTmux/Id.hs", + "line": 99, + "revision": "b832983fc30d41f03fee84282794d5568f62e15a" + } + }, + { + "apiScope": "exported", + "doc": { + "summary": "Read the numeric physical pane ID." + }, + "id": "LibTmux.Id#v:paneIdValue", + "kind": "function", + "modifiers": [], + "name": "paneIdValue", + "namespace": "LibTmux.Id", + "package": "libtmux-haskell", + "parent": "LibTmux.Id", + "product": "core", + "publicId": "LibTmux.Id#v:paneIdValue", + "qualifiedName": "LibTmux.Id.paneIdValue", + "signatures": [ + { + "nativeSpans": [ + { + "declaration": true, + "text": "paneIdValue" + }, + { + "text": " :: " + }, + { + "href": "LibTmux-Id.html#t:PaneId", + "target": "LibTmux.Id#t:PaneId", + "text": "PaneId" + }, + { + "text": " -> " + }, + { + "href": "https://hackage.haskell.org/package/base-4.22.0.0/docs/Prelude.html#t:Integer", + "text": "Integer" + } + ], + "params": [], + "raw": "paneIdValue :: PaneId -> Integer" + } + ], + "source": { + "file": "src/LibTmux/Id.hs", + "line": 103, + "revision": "b832983fc30d41f03fee84282794d5568f62e15a" + } + }, + { + "apiScope": "exported", + "doc": { + "summary": "Positive cells, constructed with :obj:`mkDimension `. Command and field limits\n are checked separately. Compare dimensions directly or use :obj:`dimensionValue `\n with an integer literal." + }, + "id": "LibTmux.Value#t:Dimension", + "instances": [ + { + "doc": null, + "markdown": "instance [NFData](https://hackage.haskell.org/package/deepseq-1.5.1.0/docs/Control-DeepSeq.html#t:NFData) :obj:`Dimension `", + "raw": "instance NFData Dimension", + "references": [ + { + "href": "https://hackage.haskell.org/package/deepseq-1.5.1.0/docs/Control-DeepSeq.html#t:NFData", + "text": "NFData" + }, + { + "href": "LibTmux-Value.html#t:Dimension", + "target": "LibTmux.Value#t:Dimension", + "text": "Dimension" + } + ], + "source": { + "file": "src/LibTmux/Value.hs", + "line": 37, + "revision": "b832983fc30d41f03fee84282794d5568f62e15a" + } + }, + { + "doc": null, + "markdown": "instance [Eq](https://hackage.haskell.org/package/base-4.22.0.0/docs/Data-Eq.html#t:Eq) :obj:`Dimension `", + "raw": "instance Eq Dimension", + "references": [ + { + "href": "https://hackage.haskell.org/package/base-4.22.0.0/docs/Data-Eq.html#t:Eq", + "text": "Eq" + }, + { + "href": "LibTmux-Value.html#t:Dimension", + "target": "LibTmux.Value#t:Dimension", + "text": "Dimension" + } + ], + "source": { + "file": "src/LibTmux/Value.hs", + "line": 36, + "revision": "b832983fc30d41f03fee84282794d5568f62e15a" + } + }, + { + "doc": null, + "markdown": "instance [Ord](https://hackage.haskell.org/package/base-4.22.0.0/docs/Data-Ord.html#t:Ord) :obj:`Dimension `", + "raw": "instance Ord Dimension", + "references": [ + { + "href": "https://hackage.haskell.org/package/base-4.22.0.0/docs/Data-Ord.html#t:Ord", + "text": "Ord" + }, + { + "href": "LibTmux-Value.html#t:Dimension", + "target": "LibTmux.Value#t:Dimension", + "text": "Dimension" + } + ], + "source": { + "file": "src/LibTmux/Value.hs", + "line": 36, + "revision": "b832983fc30d41f03fee84282794d5568f62e15a" + } + }, + { + "doc": null, + "markdown": "instance [Show](https://hackage.haskell.org/package/base-4.22.0.0/docs/Prelude.html#t:Show) :obj:`Dimension `", + "raw": "instance Show Dimension", + "references": [ + { + "href": "https://hackage.haskell.org/package/base-4.22.0.0/docs/Prelude.html#t:Show", + "text": "Show" + }, + { + "href": "LibTmux-Value.html#t:Dimension", + "target": "LibTmux.Value#t:Dimension", + "text": "Dimension" + } + ], + "source": { + "file": "src/LibTmux/Value.hs", + "line": 36, + "revision": "b832983fc30d41f03fee84282794d5568f62e15a" + } + } + ], + "kind": "typealias", + "modifiers": [ + "opaque" + ], + "name": "Dimension", + "namespace": "LibTmux.Value", + "package": "libtmux-haskell", + "parent": "LibTmux.Value", + "product": "core", + "publicId": "LibTmux.Value#t:Dimension", + "qualifiedName": "LibTmux.Value.Dimension", + "signatures": [ + { + "nativeSpans": [ + { + "keyword": true, + "text": "data" + }, + { + "text": " " + }, + { + "declaration": true, + "text": "Dimension" + } + ], + "params": [], + "raw": "data Dimension" + } + ], + "source": { + "file": "src/LibTmux/Value.hs", + "line": 35, + "revision": "b832983fc30d41f03fee84282794d5568f62e15a" + } + }, + { + "apiScope": "exported", + "doc": { + "summary": "Nonnegative index of a window link within a session, not a physical window ID.\n Construct with :obj:`mkWindowIndex `; read with :obj:`windowIndexValue `." + }, + "id": "LibTmux.Value#t:WindowIndex", + "instances": [ + { + "doc": null, + "markdown": "instance [NFData](https://hackage.haskell.org/package/deepseq-1.5.1.0/docs/Control-DeepSeq.html#t:NFData) :obj:`WindowIndex `", + "raw": "instance NFData WindowIndex", + "references": [ + { + "href": "https://hackage.haskell.org/package/deepseq-1.5.1.0/docs/Control-DeepSeq.html#t:NFData", + "text": "NFData" + }, + { + "href": "LibTmux-Value.html#t:WindowIndex", + "target": "LibTmux.Value#t:WindowIndex", + "text": "WindowIndex" + } + ], + "source": { + "file": "src/LibTmux/Value.hs", + "line": 43, + "revision": "b832983fc30d41f03fee84282794d5568f62e15a" + } + }, + { + "doc": null, + "markdown": "instance [Eq](https://hackage.haskell.org/package/base-4.22.0.0/docs/Data-Eq.html#t:Eq) :obj:`WindowIndex `", + "raw": "instance Eq WindowIndex", + "references": [ + { + "href": "https://hackage.haskell.org/package/base-4.22.0.0/docs/Data-Eq.html#t:Eq", + "text": "Eq" + }, + { + "href": "LibTmux-Value.html#t:WindowIndex", + "target": "LibTmux.Value#t:WindowIndex", + "text": "WindowIndex" + } + ], + "source": { + "file": "src/LibTmux/Value.hs", + "line": 42, + "revision": "b832983fc30d41f03fee84282794d5568f62e15a" + } + }, + { + "doc": null, + "markdown": "instance [Ord](https://hackage.haskell.org/package/base-4.22.0.0/docs/Data-Ord.html#t:Ord) :obj:`WindowIndex `", + "raw": "instance Ord WindowIndex", + "references": [ + { + "href": "https://hackage.haskell.org/package/base-4.22.0.0/docs/Data-Ord.html#t:Ord", + "text": "Ord" + }, + { + "href": "LibTmux-Value.html#t:WindowIndex", + "target": "LibTmux.Value#t:WindowIndex", + "text": "WindowIndex" + } + ], + "source": { + "file": "src/LibTmux/Value.hs", + "line": 42, + "revision": "b832983fc30d41f03fee84282794d5568f62e15a" + } + }, + { + "doc": null, + "markdown": "instance [Show](https://hackage.haskell.org/package/base-4.22.0.0/docs/Prelude.html#t:Show) :obj:`WindowIndex `", + "raw": "instance Show WindowIndex", + "references": [ + { + "href": "https://hackage.haskell.org/package/base-4.22.0.0/docs/Prelude.html#t:Show", + "text": "Show" + }, + { + "href": "LibTmux-Value.html#t:WindowIndex", + "target": "LibTmux.Value#t:WindowIndex", + "text": "WindowIndex" + } + ], + "source": { + "file": "src/LibTmux/Value.hs", + "line": 42, + "revision": "b832983fc30d41f03fee84282794d5568f62e15a" + } + } + ], + "kind": "typealias", + "modifiers": [ + "opaque" + ], + "name": "WindowIndex", + "namespace": "LibTmux.Value", + "package": "libtmux-haskell", + "parent": "LibTmux.Value", + "product": "core", + "publicId": "LibTmux.Value#t:WindowIndex", + "qualifiedName": "LibTmux.Value.WindowIndex", + "signatures": [ + { + "nativeSpans": [ + { + "keyword": true, + "text": "data" + }, + { + "text": " " + }, + { + "declaration": true, + "text": "WindowIndex" + } + ], + "params": [], + "raw": "data WindowIndex" + } + ], + "source": { + "file": "src/LibTmux/Value.hs", + "line": 41, + "revision": "b832983fc30d41f03fee84282794d5568f62e15a" + } + }, + { + "apiScope": "exported", + "doc": { + "summary": "Nonnegative pane index within a window, not a pane ID.\n Construct with :obj:`mkPaneIndex `; read with :obj:`paneIndexValue `." + }, + "id": "LibTmux.Value#t:PaneIndex", + "instances": [ + { + "doc": null, + "markdown": "instance [NFData](https://hackage.haskell.org/package/deepseq-1.5.1.0/docs/Control-DeepSeq.html#t:NFData) :obj:`PaneIndex `", + "raw": "instance NFData PaneIndex", + "references": [ + { + "href": "https://hackage.haskell.org/package/deepseq-1.5.1.0/docs/Control-DeepSeq.html#t:NFData", + "text": "NFData" + }, + { + "href": "LibTmux-Value.html#t:PaneIndex", + "target": "LibTmux.Value#t:PaneIndex", + "text": "PaneIndex" + } + ], + "source": { + "file": "src/LibTmux/Value.hs", + "line": 49, + "revision": "b832983fc30d41f03fee84282794d5568f62e15a" + } + }, + { + "doc": null, + "markdown": "instance [Eq](https://hackage.haskell.org/package/base-4.22.0.0/docs/Data-Eq.html#t:Eq) :obj:`PaneIndex `", + "raw": "instance Eq PaneIndex", + "references": [ + { + "href": "https://hackage.haskell.org/package/base-4.22.0.0/docs/Data-Eq.html#t:Eq", + "text": "Eq" + }, + { + "href": "LibTmux-Value.html#t:PaneIndex", + "target": "LibTmux.Value#t:PaneIndex", + "text": "PaneIndex" + } + ], + "source": { + "file": "src/LibTmux/Value.hs", + "line": 48, + "revision": "b832983fc30d41f03fee84282794d5568f62e15a" + } + }, + { + "doc": null, + "markdown": "instance [Ord](https://hackage.haskell.org/package/base-4.22.0.0/docs/Data-Ord.html#t:Ord) :obj:`PaneIndex `", + "raw": "instance Ord PaneIndex", + "references": [ + { + "href": "https://hackage.haskell.org/package/base-4.22.0.0/docs/Data-Ord.html#t:Ord", + "text": "Ord" + }, + { + "href": "LibTmux-Value.html#t:PaneIndex", + "target": "LibTmux.Value#t:PaneIndex", + "text": "PaneIndex" + } + ], + "source": { + "file": "src/LibTmux/Value.hs", + "line": 48, + "revision": "b832983fc30d41f03fee84282794d5568f62e15a" + } + }, + { + "doc": null, + "markdown": "instance [Show](https://hackage.haskell.org/package/base-4.22.0.0/docs/Prelude.html#t:Show) :obj:`PaneIndex `", + "raw": "instance Show PaneIndex", + "references": [ + { + "href": "https://hackage.haskell.org/package/base-4.22.0.0/docs/Prelude.html#t:Show", + "text": "Show" + }, + { + "href": "LibTmux-Value.html#t:PaneIndex", + "target": "LibTmux.Value#t:PaneIndex", + "text": "PaneIndex" + } + ], + "source": { + "file": "src/LibTmux/Value.hs", + "line": 48, + "revision": "b832983fc30d41f03fee84282794d5568f62e15a" + } + } + ], + "kind": "typealias", + "modifiers": [ + "opaque" + ], + "name": "PaneIndex", + "namespace": "LibTmux.Value", + "package": "libtmux-haskell", + "parent": "LibTmux.Value", + "product": "core", + "publicId": "LibTmux.Value#t:PaneIndex", + "qualifiedName": "LibTmux.Value.PaneIndex", + "signatures": [ + { + "nativeSpans": [ + { + "keyword": true, + "text": "data" + }, + { + "text": " " + }, + { + "declaration": true, + "text": "PaneIndex" + } + ], + "params": [], + "raw": "data PaneIndex" + } + ], + "source": { + "file": "src/LibTmux/Value.hs", + "line": 47, + "revision": "b832983fc30d41f03fee84282794d5568f62e15a" + } + }, + { + "apiScope": "exported", + "doc": { + "summary": "A scalar outside its mathematical domain." + }, + "id": "LibTmux.Value#t:ValueError", + "instances": [ + { + "doc": null, + "markdown": "instance [Eq](https://hackage.haskell.org/package/base-4.22.0.0/docs/Data-Eq.html#t:Eq) :obj:`ValueError `", + "raw": "instance Eq ValueError", + "references": [ + { + "href": "https://hackage.haskell.org/package/base-4.22.0.0/docs/Data-Eq.html#t:Eq", + "text": "Eq" + }, + { + "href": "LibTmux-Value.html#t:ValueError", + "target": "LibTmux.Value#t:ValueError", + "text": "ValueError" + } + ], + "source": { + "file": "src/LibTmux/Value.hs", + "line": 55, + "revision": "b832983fc30d41f03fee84282794d5568f62e15a" + } + }, + { + "doc": null, + "markdown": "instance [Show](https://hackage.haskell.org/package/base-4.22.0.0/docs/Prelude.html#t:Show) :obj:`ValueError `", + "raw": "instance Show ValueError", + "references": [ + { + "href": "https://hackage.haskell.org/package/base-4.22.0.0/docs/Prelude.html#t:Show", + "text": "Show" + }, + { + "href": "LibTmux-Value.html#t:ValueError", + "target": "LibTmux.Value#t:ValueError", + "text": "ValueError" + } + ], + "source": { + "file": "src/LibTmux/Value.hs", + "line": 55, + "revision": "b832983fc30d41f03fee84282794d5568f62e15a" + } + } + ], + "kind": "typealias", + "modifiers": [], + "name": "ValueError", + "namespace": "LibTmux.Value", + "package": "libtmux-haskell", + "parent": "LibTmux.Value", + "product": "core", + "publicId": "LibTmux.Value#t:ValueError", + "qualifiedName": "LibTmux.Value.ValueError", + "signatures": [ + { + "nativeSpans": [ + { + "keyword": true, + "text": "data" + }, + { + "text": " " + }, + { + "declaration": true, + "text": "ValueError" + } + ], + "params": [], + "raw": "data ValueError" + } + ], + "source": { + "file": "src/LibTmux/Value.hs", + "line": 52, + "revision": "b832983fc30d41f03fee84282794d5568f62e15a" + } + }, + { + "apiScope": "exported", + "doc": { + "summary": "The supplied dimension was zero or negative." + }, + "id": "LibTmux.Value#v:NonPositiveDimension", + "kind": "function", + "modifiers": [], + "name": "NonPositiveDimension", + "namespace": "LibTmux.Value", + "package": "libtmux-haskell", + "parent": "LibTmux.Value#t:ValueError", + "product": "core", + "publicId": "LibTmux.Value#v:NonPositiveDimension", + "qualifiedName": "LibTmux.Value.NonPositiveDimension", + "signatures": [ + { + "methodKind": "constructor", + "nativeSpans": [ + { + "declaration": true, + "text": "NonPositiveDimension" + }, + { + "text": " !" + }, + { + "href": "https://hackage.haskell.org/package/base-4.22.0.0/docs/Prelude.html#t:Integer", + "text": "Integer" + } + ], + "params": [], + "raw": "NonPositiveDimension !Integer" + } + ], + "source": { + "file": "src/LibTmux/Value.hs", + "line": 53, + "revision": "b832983fc30d41f03fee84282794d5568f62e15a" + } + }, + { + "apiScope": "exported", + "doc": { + "summary": "The supplied contextual index was negative." + }, + "id": "LibTmux.Value#v:NegativeIndex", + "kind": "function", + "modifiers": [], + "name": "NegativeIndex", + "namespace": "LibTmux.Value", + "package": "libtmux-haskell", + "parent": "LibTmux.Value#t:ValueError", + "product": "core", + "publicId": "LibTmux.Value#v:NegativeIndex", + "qualifiedName": "LibTmux.Value.NegativeIndex", + "signatures": [ + { + "methodKind": "constructor", + "nativeSpans": [ + { + "declaration": true, + "text": "NegativeIndex" + }, + { + "text": " !" + }, + { + "href": "https://hackage.haskell.org/package/base-4.22.0.0/docs/Prelude.html#t:Integer", + "text": "Integer" + } + ], + "params": [], + "raw": "NegativeIndex !Integer" + } + ], + "source": { + "file": "src/LibTmux/Value.hs", + "line": 54, + "revision": "b832983fc30d41f03fee84282794d5568f62e15a" + } + }, + { + "apiScope": "exported", + "doc": { + "summary": "Construct a positive dimension without applying a command-specific maximum." + }, + "id": "LibTmux.Value#v:mkDimension", + "kind": "function", + "modifiers": [], + "name": "mkDimension", + "namespace": "LibTmux.Value", + "package": "libtmux-haskell", + "parent": "LibTmux.Value", + "product": "core", + "publicId": "LibTmux.Value#v:mkDimension", + "qualifiedName": "LibTmux.Value.mkDimension", + "signatures": [ + { + "nativeSpans": [ + { + "declaration": true, + "text": "mkDimension" + }, + { + "text": " :: " + }, + { + "href": "https://hackage.haskell.org/package/base-4.22.0.0/docs/Prelude.html#t:Integer", + "text": "Integer" + }, + { + "text": " -> " + }, + { + "href": "https://hackage.haskell.org/package/base-4.22.0.0/docs/Data-Either.html#t:Either", + "text": "Either" + }, + { + "text": " " + }, + { + "href": "LibTmux-Value.html#t:ValueError", + "target": "LibTmux.Value#t:ValueError", + "text": "ValueError" + }, + { + "text": " " + }, + { + "href": "LibTmux-Value.html#t:Dimension", + "target": "LibTmux.Value#t:Dimension", + "text": "Dimension" + } + ], + "params": [], + "raw": "mkDimension :: Integer -> Either ValueError Dimension" + } + ], + "source": { + "file": "src/LibTmux/Value.hs", + "line": 59, + "revision": "b832983fc30d41f03fee84282794d5568f62e15a" + } + }, + { + "apiScope": "exported", + "doc": { + "summary": "Construct a nonnegative window-link index." + }, + "id": "LibTmux.Value#v:mkWindowIndex", + "kind": "function", + "modifiers": [], + "name": "mkWindowIndex", + "namespace": "LibTmux.Value", + "package": "libtmux-haskell", + "parent": "LibTmux.Value", + "product": "core", + "publicId": "LibTmux.Value#v:mkWindowIndex", + "qualifiedName": "LibTmux.Value.mkWindowIndex", + "signatures": [ + { + "nativeSpans": [ + { + "declaration": true, + "text": "mkWindowIndex" + }, + { + "text": " :: " + }, + { + "href": "https://hackage.haskell.org/package/base-4.22.0.0/docs/Prelude.html#t:Integer", + "text": "Integer" + }, + { + "text": " -> " + }, + { + "href": "https://hackage.haskell.org/package/base-4.22.0.0/docs/Data-Either.html#t:Either", + "text": "Either" + }, + { + "text": " " + }, + { + "href": "LibTmux-Value.html#t:ValueError", + "target": "LibTmux.Value#t:ValueError", + "text": "ValueError" + }, + { + "text": " " + }, + { + "href": "LibTmux-Value.html#t:WindowIndex", + "target": "LibTmux.Value#t:WindowIndex", + "text": "WindowIndex" + } + ], + "params": [], + "raw": "mkWindowIndex :: Integer -> Either ValueError WindowIndex" + } + ], + "source": { + "file": "src/LibTmux/Value.hs", + "line": 65, + "revision": "b832983fc30d41f03fee84282794d5568f62e15a" + } + }, + { + "apiScope": "exported", + "doc": { + "summary": "Construct a nonnegative pane index." + }, + "id": "LibTmux.Value#v:mkPaneIndex", + "kind": "function", + "modifiers": [], + "name": "mkPaneIndex", + "namespace": "LibTmux.Value", + "package": "libtmux-haskell", + "parent": "LibTmux.Value", + "product": "core", + "publicId": "LibTmux.Value#v:mkPaneIndex", + "qualifiedName": "LibTmux.Value.mkPaneIndex", + "signatures": [ + { + "nativeSpans": [ + { + "declaration": true, + "text": "mkPaneIndex" + }, + { + "text": " :: " + }, + { + "href": "https://hackage.haskell.org/package/base-4.22.0.0/docs/Prelude.html#t:Integer", + "text": "Integer" + }, + { + "text": " -> " + }, + { + "href": "https://hackage.haskell.org/package/base-4.22.0.0/docs/Data-Either.html#t:Either", + "text": "Either" + }, + { + "text": " " + }, + { + "href": "LibTmux-Value.html#t:ValueError", + "target": "LibTmux.Value#t:ValueError", + "text": "ValueError" + }, + { + "text": " " + }, + { + "href": "LibTmux-Value.html#t:PaneIndex", + "target": "LibTmux.Value#t:PaneIndex", + "text": "PaneIndex" + } + ], + "params": [], + "raw": "mkPaneIndex :: Integer -> Either ValueError PaneIndex" + } + ], + "source": { + "file": "src/LibTmux/Value.hs", + "line": 71, + "revision": "b832983fc30d41f03fee84282794d5568f62e15a" + } + }, + { + "apiScope": "exported", + "doc": { + "summary": "Read a dimension as a mathematical integer, without narrowing conversion." + }, + "id": "LibTmux.Value#v:dimensionValue", + "kind": "function", + "modifiers": [], + "name": "dimensionValue", + "namespace": "LibTmux.Value", + "package": "libtmux-haskell", + "parent": "LibTmux.Value", + "product": "core", + "publicId": "LibTmux.Value#v:dimensionValue", + "qualifiedName": "LibTmux.Value.dimensionValue", + "signatures": [ + { + "nativeSpans": [ + { + "declaration": true, + "text": "dimensionValue" + }, + { + "text": " :: " + }, + { + "href": "LibTmux-Value.html#t:Dimension", + "target": "LibTmux.Value#t:Dimension", + "text": "Dimension" + }, + { + "text": " -> " + }, + { + "href": "https://hackage.haskell.org/package/base-4.22.0.0/docs/Prelude.html#t:Integer", + "text": "Integer" + } + ], + "params": [], + "raw": "dimensionValue :: Dimension -> Integer" + } + ], + "source": { + "file": "src/LibTmux/Value.hs", + "line": 77, + "revision": "b832983fc30d41f03fee84282794d5568f62e15a" + } + }, + { + "apiScope": "exported", + "doc": { + "summary": "Read a window-link index as a mathematical integer." + }, + "id": "LibTmux.Value#v:windowIndexValue", + "kind": "function", + "modifiers": [], + "name": "windowIndexValue", + "namespace": "LibTmux.Value", + "package": "libtmux-haskell", + "parent": "LibTmux.Value", + "product": "core", + "publicId": "LibTmux.Value#v:windowIndexValue", + "qualifiedName": "LibTmux.Value.windowIndexValue", + "signatures": [ + { + "nativeSpans": [ + { + "declaration": true, + "text": "windowIndexValue" + }, + { + "text": " :: " + }, + { + "href": "LibTmux-Value.html#t:WindowIndex", + "target": "LibTmux.Value#t:WindowIndex", + "text": "WindowIndex" + }, + { + "text": " -> " + }, + { + "href": "https://hackage.haskell.org/package/base-4.22.0.0/docs/Prelude.html#t:Integer", + "text": "Integer" + } + ], + "params": [], + "raw": "windowIndexValue :: WindowIndex -> Integer" + } + ], + "source": { + "file": "src/LibTmux/Value.hs", + "line": 81, + "revision": "b832983fc30d41f03fee84282794d5568f62e15a" + } + }, + { + "apiScope": "exported", + "doc": { + "summary": "Read a pane index as a mathematical integer." + }, + "id": "LibTmux.Value#v:paneIndexValue", + "kind": "function", + "modifiers": [], + "name": "paneIndexValue", + "namespace": "LibTmux.Value", + "package": "libtmux-haskell", + "parent": "LibTmux.Value", + "product": "core", + "publicId": "LibTmux.Value#v:paneIndexValue", + "qualifiedName": "LibTmux.Value.paneIndexValue", + "signatures": [ + { + "nativeSpans": [ + { + "declaration": true, + "text": "paneIndexValue" + }, + { + "text": " :: " + }, + { + "href": "LibTmux-Value.html#t:PaneIndex", + "target": "LibTmux.Value#t:PaneIndex", + "text": "PaneIndex" + }, + { + "text": " -> " + }, + { + "href": "https://hackage.haskell.org/package/base-4.22.0.0/docs/Prelude.html#t:Integer", + "text": "Integer" + } + ], + "params": [], + "raw": "paneIndexValue :: PaneIndex -> Integer" + } + ], + "source": { + "file": "src/LibTmux/Value.hs", + "line": 85, + "revision": "b832983fc30d41f03fee84282794d5568f62e15a" + } + }, + { + "apiScope": "exported", + "doc": { + "summary": "A stable release, constructed by :obj:`parseVersion ` and rendered by\n :obj:`renderVersion `. Ordering compares numeric components before the patch letter." + }, + "id": "LibTmux.Version#t:TmuxVersion", + "instances": [ + { + "doc": null, + "markdown": "instance [Eq](https://hackage.haskell.org/package/base-4.22.0.0/docs/Data-Eq.html#t:Eq) :obj:`TmuxVersion `", + "raw": "instance Eq TmuxVersion", + "references": [ + { + "href": "https://hackage.haskell.org/package/base-4.22.0.0/docs/Data-Eq.html#t:Eq", + "text": "Eq" + }, + { + "href": "LibTmux-Version.html#t:TmuxVersion", + "target": "LibTmux.Version#t:TmuxVersion", + "text": "TmuxVersion" + } + ], + "source": { + "file": "src/LibTmux/Version.hs", + "line": 32, + "revision": "b832983fc30d41f03fee84282794d5568f62e15a" + } + }, + { + "doc": null, + "markdown": "instance [Ord](https://hackage.haskell.org/package/base-4.22.0.0/docs/Data-Ord.html#t:Ord) :obj:`TmuxVersion `", + "raw": "instance Ord TmuxVersion", + "references": [ + { + "href": "https://hackage.haskell.org/package/base-4.22.0.0/docs/Data-Ord.html#t:Ord", + "text": "Ord" + }, + { + "href": "LibTmux-Version.html#t:TmuxVersion", + "target": "LibTmux.Version#t:TmuxVersion", + "text": "TmuxVersion" + } + ], + "source": { + "file": "src/LibTmux/Version.hs", + "line": 32, + "revision": "b832983fc30d41f03fee84282794d5568f62e15a" + } + }, + { + "doc": null, + "markdown": "instance [Show](https://hackage.haskell.org/package/base-4.22.0.0/docs/Prelude.html#t:Show) :obj:`TmuxVersion `", + "raw": "instance Show TmuxVersion", + "references": [ + { + "href": "https://hackage.haskell.org/package/base-4.22.0.0/docs/Prelude.html#t:Show", + "text": "Show" + }, + { + "href": "LibTmux-Version.html#t:TmuxVersion", + "target": "LibTmux.Version#t:TmuxVersion", + "text": "TmuxVersion" + } + ], + "source": { + "file": "src/LibTmux/Version.hs", + "line": 32, + "revision": "b832983fc30d41f03fee84282794d5568f62e15a" + } + } + ], + "kind": "typealias", + "modifiers": [ + "opaque" + ], + "name": "TmuxVersion", + "namespace": "LibTmux.Version", + "package": "libtmux-haskell", + "parent": "LibTmux.Version", + "product": "core", + "publicId": "LibTmux.Version#t:TmuxVersion", + "qualifiedName": "LibTmux.Version.TmuxVersion", + "signatures": [ + { + "nativeSpans": [ + { + "keyword": true, + "text": "data" + }, + { + "text": " " + }, + { + "declaration": true, + "text": "TmuxVersion" + } + ], + "params": [], + "raw": "data TmuxVersion" + } + ], + "source": { + "file": "src/LibTmux/Version.hs", + "line": 31, + "revision": "b832983fc30d41f03fee84282794d5568f62e15a" + } + }, + { + "apiScope": "exported", + "doc": { + "summary": "Invalid release syntax or a release below the supported floor." + }, + "id": "LibTmux.Version#t:VersionError", + "instances": [ + { + "doc": null, + "markdown": "instance [Eq](https://hackage.haskell.org/package/base-4.22.0.0/docs/Data-Eq.html#t:Eq) :obj:`VersionError `", + "raw": "instance Eq VersionError", + "references": [ + { + "href": "https://hackage.haskell.org/package/base-4.22.0.0/docs/Data-Eq.html#t:Eq", + "text": "Eq" + }, + { + "href": "LibTmux-Version.html#t:VersionError", + "target": "LibTmux.Version#t:VersionError", + "text": "VersionError" + } + ], + "source": { + "file": "src/LibTmux/Version.hs", + "line": 38, + "revision": "b832983fc30d41f03fee84282794d5568f62e15a" + } + }, + { + "doc": null, + "markdown": "instance [Show](https://hackage.haskell.org/package/base-4.22.0.0/docs/Prelude.html#t:Show) :obj:`VersionError `", + "raw": "instance Show VersionError", + "references": [ + { + "href": "https://hackage.haskell.org/package/base-4.22.0.0/docs/Prelude.html#t:Show", + "text": "Show" + }, + { + "href": "LibTmux-Version.html#t:VersionError", + "target": "LibTmux.Version#t:VersionError", + "text": "VersionError" + } + ], + "source": { + "file": "src/LibTmux/Version.hs", + "line": 38, + "revision": "b832983fc30d41f03fee84282794d5568f62e15a" + } + } + ], + "kind": "typealias", + "modifiers": [], + "name": "VersionError", + "namespace": "LibTmux.Version", + "package": "libtmux-haskell", + "parent": "LibTmux.Version", + "product": "core", + "publicId": "LibTmux.Version#t:VersionError", + "qualifiedName": "LibTmux.Version.VersionError", + "signatures": [ + { + "nativeSpans": [ + { + "keyword": true, + "text": "data" + }, + { + "text": " " + }, + { + "declaration": true, + "text": "VersionError" + } + ], + "params": [], + "raw": "data VersionError" + } + ], + "source": { + "file": "src/LibTmux/Version.hs", + "line": 35, + "revision": "b832983fc30d41f03fee84282794d5568f62e15a" + } + }, + { + "apiScope": "exported", + "doc": { + "summary": "Bounded copy of input that is not a stable release." + }, + "id": "LibTmux.Version#v:MalformedVersion", + "kind": "function", + "modifiers": [], + "name": "MalformedVersion", + "namespace": "LibTmux.Version", + "package": "libtmux-haskell", + "parent": "LibTmux.Version#t:VersionError", + "product": "core", + "publicId": "LibTmux.Version#v:MalformedVersion", + "qualifiedName": "LibTmux.Version.MalformedVersion", + "signatures": [ + { + "methodKind": "constructor", + "nativeSpans": [ + { + "declaration": true, + "text": "MalformedVersion" + }, + { + "text": " !" + }, + { + "href": "https://hackage.haskell.org/package/text-2.1.3/docs/Data-Text.html#t:Text", + "text": "Text" + } + ], + "params": [], + "raw": "MalformedVersion !Text" + } + ], + "source": { + "file": "src/LibTmux/Version.hs", + "line": 36, + "revision": "b832983fc30d41f03fee84282794d5568f62e15a" + } + }, + { + "apiScope": "exported", + "doc": { + "summary": "A stable release older than plain tmux 3.3." + }, + "id": "LibTmux.Version#v:UnsupportedVersion", + "kind": "function", + "modifiers": [], + "name": "UnsupportedVersion", + "namespace": "LibTmux.Version", + "package": "libtmux-haskell", + "parent": "LibTmux.Version#t:VersionError", + "product": "core", + "publicId": "LibTmux.Version#v:UnsupportedVersion", + "qualifiedName": "LibTmux.Version.UnsupportedVersion", + "signatures": [ + { + "methodKind": "constructor", + "nativeSpans": [ + { + "declaration": true, + "text": "UnsupportedVersion" + }, + { + "text": " !" + }, + { + "href": "LibTmux-Version.html#t:TmuxVersion", + "target": "LibTmux.Version#t:TmuxVersion", + "text": "TmuxVersion" + } + ], + "params": [], + "raw": "UnsupportedVersion !TmuxVersion" + } + ], + "source": { + "file": "src/LibTmux/Version.hs", + "line": 37, + "revision": "b832983fc30d41f03fee84282794d5568f62e15a" + } + }, + { + "apiScope": "exported", + "doc": { + "summary": "Parse a stable release or the output of `tmux -V`, allowing one final LF.\n Development builds and trailing data are rejected rather than assigned\n capabilities from a guessed stable version. Diagnostics retain at most 64 chars." + }, + "id": "LibTmux.Version#v:parseVersion", + "kind": "function", + "modifiers": [], + "name": "parseVersion", + "namespace": "LibTmux.Version", + "package": "libtmux-haskell", + "parent": "LibTmux.Version", + "product": "core", + "publicId": "LibTmux.Version#v:parseVersion", + "qualifiedName": "LibTmux.Version.parseVersion", + "signatures": [ + { + "nativeSpans": [ + { + "declaration": true, + "text": "parseVersion" + }, + { + "text": " :: " + }, + { + "href": "https://hackage.haskell.org/package/text-2.1.3/docs/Data-Text.html#t:Text", + "text": "Text" + }, + { + "text": " -> " + }, + { + "href": "https://hackage.haskell.org/package/base-4.22.0.0/docs/Data-Either.html#t:Either", + "text": "Either" + }, + { + "text": " " + }, + { + "href": "LibTmux-Version.html#t:VersionError", + "target": "LibTmux.Version#t:VersionError", + "text": "VersionError" + }, + { + "text": " " + }, + { + "href": "LibTmux-Version.html#t:TmuxVersion", + "target": "LibTmux.Version#t:TmuxVersion", + "text": "TmuxVersion" + } + ], + "params": [], + "raw": "parseVersion :: Text -> Either VersionError TmuxVersion" + } + ], + "source": { + "file": "src/LibTmux/Version.hs", + "line": 44, + "revision": "b832983fc30d41f03fee84282794d5568f62e15a" + } + }, + { + "apiScope": "exported", + "doc": { + "summary": "Render the canonical release without the executable name or newline." + }, + "id": "LibTmux.Version#v:renderVersion", + "kind": "function", + "modifiers": [], + "name": "renderVersion", + "namespace": "LibTmux.Version", + "package": "libtmux-haskell", + "parent": "LibTmux.Version", + "product": "core", + "publicId": "LibTmux.Version#v:renderVersion", + "qualifiedName": "LibTmux.Version.renderVersion", + "signatures": [ + { + "nativeSpans": [ + { + "declaration": true, + "text": "renderVersion" + }, + { + "text": " :: " + }, + { + "href": "LibTmux-Version.html#t:TmuxVersion", + "target": "LibTmux.Version#t:TmuxVersion", + "text": "TmuxVersion" + }, + { + "text": " -> " + }, + { + "href": "https://hackage.haskell.org/package/text-2.1.3/docs/Data-Text.html#t:Text", + "text": "Text" + } + ], + "params": [], + "raw": "renderVersion :: TmuxVersion -> Text" + } + ], + "source": { + "file": "src/LibTmux/Version.hs", + "line": 73, + "revision": "b832983fc30d41f03fee84282794d5568f62e15a" + } + }, + { + "apiScope": "exported", + "doc": { + "summary": "Reject releases older than plain 3.3. Individual features need their own\n capability checks; passing this check does not qualify an entire release." + }, + "id": "LibTmux.Version#v:requireSupported", + "kind": "function", + "modifiers": [], + "name": "requireSupported", + "namespace": "LibTmux.Version", + "package": "libtmux-haskell", + "parent": "LibTmux.Version", + "product": "core", + "publicId": "LibTmux.Version#v:requireSupported", + "qualifiedName": "LibTmux.Version.requireSupported", + "signatures": [ + { + "nativeSpans": [ + { + "declaration": true, + "text": "requireSupported" + }, + { + "text": " :: " + }, + { + "href": "LibTmux-Version.html#t:TmuxVersion", + "target": "LibTmux.Version#t:TmuxVersion", + "text": "TmuxVersion" + }, + { + "text": " -> " + }, + { + "href": "https://hackage.haskell.org/package/base-4.22.0.0/docs/Data-Either.html#t:Either", + "text": "Either" + }, + { + "text": " " + }, + { + "href": "LibTmux-Version.html#t:VersionError", + "target": "LibTmux.Version#t:VersionError", + "text": "VersionError" + }, + { + "text": " " + }, + { + "href": "LibTmux-Version.html#t:TmuxVersion", + "target": "LibTmux.Version#t:TmuxVersion", + "text": "TmuxVersion" + } + ], + "params": [], + "raw": "requireSupported :: TmuxVersion -> Either VersionError TmuxVersion" + } + ], + "source": { + "file": "src/LibTmux/Version.hs", + "line": 79, + "revision": "b832983fc30d41f03fee84282794d5568f62e15a" + } + } + ] +} diff --git a/packages/api-model/test/fixtures/haskell-native/installed.json b/packages/api-model/test/fixtures/haskell-native/installed.json new file mode 100644 index 000000000..45afe8995 --- /dev/null +++ b/packages/api-model/test/fixtures/haskell-native/installed.json @@ -0,0 +1 @@ +{"package_info":"libtmux-haskell-0.1.0.0","link_env":{"$libtmux-haskell-0.1.0.0-inplace$LibTmux.Id$paneIdValue":"LibTmux.Id","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Id$parsePaneId":"LibTmux.Id","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Id$parseSessionId":"LibTmux.Id","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Id$parseWindowId":"LibTmux.Id","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Id$renderPaneId":"LibTmux.Id","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Id$renderSessionId":"LibTmux.Id","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Id$renderWindowId":"LibTmux.Id","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Id$sessionIdValue":"LibTmux.Id","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Id$windowIdValue":"LibTmux.Id","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Id$IdError":"LibTmux.Id","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Id$InvalidId":"LibTmux.Id","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Id$expectedPrefix":"LibTmux.Id","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Id$input":"LibTmux.Id","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Id$PaneId":"LibTmux.Id","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Id$SessionId":"LibTmux.Id","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Id$WindowId":"LibTmux.Id","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Id$$fEqIdError":"LibTmux.Id","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Id$$fEqPaneId":"LibTmux.Id","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Id$$fEqSessionId":"LibTmux.Id","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Id$$fEqWindowId":"LibTmux.Id","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Id$$fNFDataPaneId":"LibTmux.Id","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Id$$fNFDataSessionId":"LibTmux.Id","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Id$$fNFDataWindowId":"LibTmux.Id","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Id$$fOrdPaneId":"LibTmux.Id","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Id$$fOrdSessionId":"LibTmux.Id","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Id$$fOrdWindowId":"LibTmux.Id","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Id$$fShowIdError":"LibTmux.Id","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Id$$fShowPaneId":"LibTmux.Id","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Id$$fShowSessionId":"LibTmux.Id","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Id$$fShowWindowId":"LibTmux.Id","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Value$dimensionValue":"LibTmux.Value","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Value$mkDimension":"LibTmux.Value","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Value$mkPaneIndex":"LibTmux.Value","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Value$mkWindowIndex":"LibTmux.Value","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Value$paneIndexValue":"LibTmux.Value","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Value$windowIndexValue":"LibTmux.Value","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Value$Dimension":"LibTmux.Value","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Value$PaneIndex":"LibTmux.Value","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Value$ValueError":"LibTmux.Value","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Value$NegativeIndex":"LibTmux.Value","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Value$NonPositiveDimension":"LibTmux.Value","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Value$WindowIndex":"LibTmux.Value","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Value$$fEqDimension":"LibTmux.Value","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Value$$fEqPaneIndex":"LibTmux.Value","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Value$$fEqValueError":"LibTmux.Value","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Value$$fEqWindowIndex":"LibTmux.Value","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Value$$fNFDataDimension":"LibTmux.Value","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Value$$fNFDataPaneIndex":"LibTmux.Value","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Value$$fNFDataWindowIndex":"LibTmux.Value","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Value$$fOrdDimension":"LibTmux.Value","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Value$$fOrdPaneIndex":"LibTmux.Value","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Value$$fOrdWindowIndex":"LibTmux.Value","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Value$$fShowDimension":"LibTmux.Value","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Value$$fShowPaneIndex":"LibTmux.Value","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Value$$fShowValueError":"LibTmux.Value","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Value$$fShowWindowIndex":"LibTmux.Value","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Version$parseVersion":"LibTmux.Version","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Version$renderVersion":"LibTmux.Version","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Version$requireSupported":"LibTmux.Version","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Version$TmuxVersion":"LibTmux.Version","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Version$VersionError":"LibTmux.Version","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Version$MalformedVersion":"LibTmux.Version","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Version$UnsupportedVersion":"LibTmux.Version","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Version$$fEqTmuxVersion":"LibTmux.Version","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Version$$fEqVersionError":"LibTmux.Version","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Version$$fOrdTmuxVersion":"LibTmux.Version","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Version$$fShowTmuxVersion":"LibTmux.Version","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Version$$fShowVersionError":"LibTmux.Version"},"inst_ifaces":[{"module":"$libtmux-haskell-0.1.0.0-inplace$LibTmux.Id","is_sig":false,"info":{"description":null,"copyright":null,"maintainer":null,"stability":null,"protability":null,"safety":"None","language":"GHC2024","extensions":["OverloadedStrings","DuplicateRecordFields","OverloadedRecordDot"]},"doc_map":{"$libtmux-haskell-0.1.0.0-inplace$LibTmux.Id$paneIdValue":{"meta":{"version":null},"document":{"tag":"DocParagraph","document":{"tag":"DocString","string":"Read the numeric physical pane ID."}}},"$libtmux-haskell-0.1.0.0-inplace$LibTmux.Id$parsePaneId":{"meta":{"version":null},"document":{"tag":"DocParagraph","document":{"tag":"DocAppend","first":{"tag":"DocString","string":"Parse a canonical "},"second":{"tag":"DocAppend","first":{"tag":"DocMonospaced","document":{"tag":"DocString","string":"%number"}},"second":{"tag":"DocString","string":" identifying a physical pane."}}}}},"$libtmux-haskell-0.1.0.0-inplace$LibTmux.Id$parseSessionId":{"meta":{"version":null},"document":{"tag":"DocParagraph","document":{"tag":"DocAppend","first":{"tag":"DocString","string":"Parse "},"second":{"tag":"DocAppend","first":{"tag":"DocMonospaced","document":{"tag":"DocString","string":"$0"}},"second":{"tag":"DocAppend","first":{"tag":"DocString","string":" through "},"second":{"tag":"DocAppend","first":{"tag":"DocMonospaced","document":{"tag":"DocString","string":"$4294967295"}},"second":{"tag":"DocString","string":". No whitespace or leading zeroes."}}}}}}},"$libtmux-haskell-0.1.0.0-inplace$LibTmux.Id$parseWindowId":{"meta":{"version":null},"document":{"tag":"DocParagraph","document":{"tag":"DocAppend","first":{"tag":"DocString","string":"Parse a canonical "},"second":{"tag":"DocAppend","first":{"tag":"DocMonospaced","document":{"tag":"DocString","string":"@number"}},"second":{"tag":"DocString","string":" identifying a physical window."}}}}},"$libtmux-haskell-0.1.0.0-inplace$LibTmux.Id$renderPaneId":{"meta":{"version":null},"document":{"tag":"DocParagraph","document":{"tag":"DocString","string":"Render the physical pane prefix and decimal ID."}}},"$libtmux-haskell-0.1.0.0-inplace$LibTmux.Id$renderSessionId":{"meta":{"version":null},"document":{"tag":"DocParagraph","document":{"tag":"DocString","string":"Render the session prefix and decimal ID."}}},"$libtmux-haskell-0.1.0.0-inplace$LibTmux.Id$renderWindowId":{"meta":{"version":null},"document":{"tag":"DocParagraph","document":{"tag":"DocString","string":"Render the physical window prefix and decimal ID."}}},"$libtmux-haskell-0.1.0.0-inplace$LibTmux.Id$sessionIdValue":{"meta":{"version":null},"document":{"tag":"DocParagraph","document":{"tag":"DocString","string":"Read the numeric session ID without narrowing conversion."}}},"$libtmux-haskell-0.1.0.0-inplace$LibTmux.Id$windowIdValue":{"meta":{"version":null},"document":{"tag":"DocParagraph","document":{"tag":"DocString","string":"Read the numeric physical window ID."}}},"$libtmux-haskell-0.1.0.0-inplace$LibTmux.Id$IdError":{"meta":{"version":null},"document":{"tag":"DocParagraph","document":{"tag":"DocString","string":"Invalid canonical syntax, entity prefix or native unsigned range.\n Diagnostics retain at most 64 characters of input."}}},"$libtmux-haskell-0.1.0.0-inplace$LibTmux.Id$expectedPrefix":{"meta":{"version":null},"document":{"tag":"DocParagraph","document":{"tag":"DocString","string":"Required entity prefix."}}},"$libtmux-haskell-0.1.0.0-inplace$LibTmux.Id$input":{"meta":{"version":null},"document":{"tag":"DocParagraph","document":{"tag":"DocString","string":"Bounded copy of the invalid input."}}},"$libtmux-haskell-0.1.0.0-inplace$LibTmux.Id$PaneId":{"meta":{"version":null},"document":{"tag":"DocParagraph","document":{"tag":"DocAppend","first":{"tag":"DocString","string":"A physical pane's identifier, written with a "},"second":{"tag":"DocAppend","first":{"tag":"DocMonospaced","document":{"tag":"DocString","string":"%"}},"second":{"tag":"DocAppend","first":{"tag":"DocString","string":" prefix.\n Parse with "},"second":{"tag":"DocAppend","first":{"tag":"DocIdentifier","name":"$libtmux-haskell-0.1.0.0-inplace$LibTmux.Id$parsePaneId"},"second":{"tag":"DocAppend","first":{"tag":"DocString","string":"; render with "},"second":{"tag":"DocAppend","first":{"tag":"DocIdentifier","name":"$libtmux-haskell-0.1.0.0-inplace$LibTmux.Id$renderPaneId"},"second":{"tag":"DocString","string":"."}}}}}}}}},"$libtmux-haskell-0.1.0.0-inplace$LibTmux.Id$SessionId":{"meta":{"version":null},"document":{"tag":"DocParagraph","document":{"tag":"DocAppend","first":{"tag":"DocString","string":"A session's unsigned 32-bit tmux identifier, written with a "},"second":{"tag":"DocAppend","first":{"tag":"DocMonospaced","document":{"tag":"DocString","string":"$"}},"second":{"tag":"DocAppend","first":{"tag":"DocString","string":" prefix.\n Parse with "},"second":{"tag":"DocAppend","first":{"tag":"DocIdentifier","name":"$libtmux-haskell-0.1.0.0-inplace$LibTmux.Id$parseSessionId"},"second":{"tag":"DocAppend","first":{"tag":"DocString","string":"; render with "},"second":{"tag":"DocAppend","first":{"tag":"DocIdentifier","name":"$libtmux-haskell-0.1.0.0-inplace$LibTmux.Id$renderSessionId"},"second":{"tag":"DocString","string":"."}}}}}}}}},"$libtmux-haskell-0.1.0.0-inplace$LibTmux.Id$WindowId":{"meta":{"version":null},"document":{"tag":"DocParagraph","document":{"tag":"DocAppend","first":{"tag":"DocString","string":"A physical window's identifier, independent of its session links.\n Parse with "},"second":{"tag":"DocAppend","first":{"tag":"DocIdentifier","name":"$libtmux-haskell-0.1.0.0-inplace$LibTmux.Id$parseWindowId"},"second":{"tag":"DocAppend","first":{"tag":"DocString","string":"; render with "},"second":{"tag":"DocAppend","first":{"tag":"DocIdentifier","name":"$libtmux-haskell-0.1.0.0-inplace$LibTmux.Id$renderWindowId"},"second":{"tag":"DocString","string":"."}}}}}}}},"arg_map":{},"exports":["$libtmux-haskell-0.1.0.0-inplace$LibTmux.Id$paneIdValue","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Id$parsePaneId","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Id$parseSessionId","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Id$parseWindowId","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Id$renderPaneId","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Id$renderSessionId","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Id$renderWindowId","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Id$sessionIdValue","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Id$windowIdValue","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Id$IdError","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Id$InvalidId","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Id$expectedPrefix","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Id$input","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Id$PaneId","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Id$SessionId","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Id$WindowId"],"visible_exports":["$libtmux-haskell-0.1.0.0-inplace$LibTmux.Id$SessionId","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Id$WindowId","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Id$PaneId","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Id$IdError","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Id$InvalidId","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Id$expectedPrefix","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Id$input","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Id$parseSessionId","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Id$parseWindowId","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Id$parsePaneId","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Id$renderSessionId","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Id$renderWindowId","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Id$renderPaneId","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Id$sessionIdValue","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Id$windowIdValue","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Id$paneIdValue"],"options":[],"fix_map":{}},{"module":"$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Budget","is_sig":false,"info":{"description":null,"copyright":null,"maintainer":null,"stability":null,"protability":null,"safety":"None","language":"GHC2024","extensions":["OverloadedStrings","DuplicateRecordFields","OverloadedRecordDot"]},"doc_map":{"$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Budget$acquireBytes":{"meta":{"version":null},"document":{"tag":"DocParagraph","document":{"tag":"DocAppend","first":{"tag":"DocString","string":"Reserve retained payload capacity independently of a child. An internal\n consumer keeps this lease through decoding or charged ownership transfer.\n Release with "},"second":{"tag":"DocAppend","first":{"tag":"DocIdentifier","name":"$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Budget$releaseBytes"},"second":{"tag":"DocString","string":". Zero bytes still require open admission."}}}}},"$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Budget$releaseBytes":{"meta":{"version":null},"document":{"tag":"DocParagraph","document":{"tag":"DocAppend","first":{"tag":"DocString","string":"Return the byte credits from "},"second":{"tag":"DocAppend","first":{"tag":"DocIdentifier","name":"$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Budget$acquireBytes"},"second":{"tag":"DocString","string":" once."}}}}},"$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Budget$acquireChild":{"meta":{"version":null},"document":{"tag":"DocParagraph","document":{"tag":"DocAppend","first":{"tag":"DocString","string":"Reserve one child and its byte allowance atomically. Neither credit\n changes on failure. Retain until physical retirement; see "},"second":{"tag":"DocAppend","first":{"tag":"DocIdentifier","name":"$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Budget$releaseChild"},"second":{"tag":"DocString","string":"."}}}}},"$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Budget$releaseChild":{"meta":{"version":null},"document":{"tag":"DocParagraph","document":{"tag":"DocAppend","first":{"tag":"DocString","string":"Return the child and byte credits from "},"second":{"tag":"DocAppend","first":{"tag":"DocIdentifier","name":"$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Budget$acquireChild"},"second":{"tag":"DocString","string":" once."}}}}},"$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Budget$acquireClient":{"meta":{"version":null},"document":{"tag":"DocParagraph","document":{"tag":"DocAppend","first":{"tag":"DocString","string":"Reserve one client until its pin cleanup succeeds. Release with\n "},"second":{"tag":"DocAppend","first":{"tag":"DocIdentifier","name":"$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Budget$releaseClient"},"second":{"tag":"DocAppend","first":{"tag":"DocString","string":"; closed/exhausted contexts throw "},"second":{"tag":"DocAppend","first":{"tag":"DocIdentifier","name":"$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Budget$LimitError"},"second":{"tag":"DocString","string":" in STM."}}}}}}},"$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Budget$releaseClient":{"meta":{"version":null},"document":{"tag":"DocParagraph","document":{"tag":"DocAppend","first":{"tag":"DocString","string":"Return a client credit once. Legal after "},"second":{"tag":"DocAppend","first":{"tag":"DocIdentifier","name":"$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Budget$closeAdmission"},"second":{"tag":"DocString","string":"."}}}}},"$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Budget$LimitError":{"meta":{"version":null},"document":{"tag":"DocParagraph","document":{"tag":"DocString","string":"Rejected admission. Exhaustion records resource, requested amount,\n current usage and limit. Failed reservations change no counters."}}},"$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Budget$closeAdmission":{"meta":{"version":null},"document":{"tag":"DocParagraph","document":{"tag":"DocString","string":"Reject future reservations without releasing existing leases or waiting\n for cleanup. Owners must still call their corresponding release operation."}}},"$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Budget$newBudget":{"meta":{"version":null},"document":{"tag":"DocParagraph","document":{"tag":"DocString","string":"Start an independent context: eight clients, sixteen children and\n 128 MiB of pending payload reservations."}}},"$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Budget$usage":{"meta":{"version":null},"document":{"tag":"DocParagraph","document":{"tag":"DocString","string":"Observe all counters in one transaction; no external resources are read."}}}},"arg_map":{},"exports":["$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Budget$acquireBytes","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Budget$acquireChild","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Budget$acquireClient","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Budget$closeAdmission","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Budget$newBudget","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Budget$releaseBytes","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Budget$releaseChild","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Budget$releaseClient","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Budget$usage","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Budget$Budget","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Budget$ByteLease","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Budget$ChildLease","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Budget$ClientLease","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Budget$LimitError","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Budget$AdmissionClosed","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Budget$Exhausted","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Budget$Resource","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Budget$Children","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Budget$Clients","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Budget$PendingBytes","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Budget$Usage","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Budget$Usage","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Budget$accepting","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Budget$children","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Budget$clients","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Budget$pendingBytes"],"visible_exports":[],"options":["OptHide"],"fix_map":{}},{"module":"$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Frame","is_sig":false,"info":{"description":null,"copyright":null,"maintainer":null,"stability":null,"protability":null,"safety":"None","language":"GHC2024","extensions":["OverloadedStrings","DuplicateRecordFields","OverloadedRecordDot"]},"doc_map":{},"arg_map":{},"exports":["$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Frame$decodeScalar","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Frame$parseNonce","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Frame$scalarFormat","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Frame$FrameError","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Frame$AmbiguousScalarFrame","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Frame$InvalidNonce","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Frame$InvalidScalarLimit","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Frame$NulInScalar","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Frame$ScalarLimitExceeded","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Frame$UnexpectedScalarFrame","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Frame$Nonce"],"visible_exports":[],"options":["OptHide"],"fix_map":{}},{"module":"$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Process.Native","is_sig":false,"info":{"description":null,"copyright":null,"maintainer":null,"stability":null,"protability":null,"safety":"None","language":"GHC2024","extensions":["OverloadedStrings","DuplicateRecordFields","OverloadedRecordDot"]},"doc_map":{"$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Process.Native$copySpec":{"meta":{"version":null},"document":{"tag":"DocParagraph","document":{"tag":"DocString","string":"Detach retained slices after validation and before publishing to a worker."}}},"$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Process.Native$launchWith":{"meta":{"version":null},"document":{"tag":"DocParagraph","document":{"tag":"DocString","string":"Marshal and decode during the call. The owner supplies the surrounding mask\n that spans this return and its own child/descriptor journal."}}},"$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Process.Native$validate":{"meta":{"version":null},"document":{"tag":"DocParagraph","document":{"tag":"DocString","string":"Bound list traversal as well as encoded bytes before entering native code."}}},"$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Process.Native$waitWith":{"meta":{"version":null},"document":{"tag":"DocParagraph","document":{"tag":"DocString","string":"Consume at most one status. The owner masks and immediately caches it."}}}},"arg_map":{},"exports":["$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Process.Native$cFeatures","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Process.Native$cRead","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Process.Native$cSignal","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Process.Native$cSpawn","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Process.Native$cWait","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Process.Native$cWrite","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Process.Native$chunkBytes","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Process.Native$close","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Process.Native$copySpec","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Process.Native$errno","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Process.Native$launch","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Process.Native$launchWith","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Process.Native$missingFeatures","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Process.Native$raise","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Process.Native$readChunk","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Process.Native$signalChild","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Process.Native$spec","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Process.Native$validate","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Process.Native$vectorLimitBytes","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Process.Native$waitChild","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Process.Native$waitWith","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Process.Native$writeBytes","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Process.Native$Child","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Process.Native$Child","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Process.Native$errors","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Process.Native$input","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Process.Native$output","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Process.Native$pidfd","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Process.Native$Exit","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Process.Native$Exited","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Process.Native$Signaled","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Process.Native$StatusLost","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Process.Native$Failure","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Process.Native$InvalidInput","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Process.Native$LaunchRefused","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Process.Native$Feature","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Process.Native$AtomicPidfdSpawn","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Process.Native$ChildDirectory","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Process.Native$CloseUnrelatedDescriptors","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Process.Native$LaunchCall","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Process.Native$Phase","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Process.Native$Execute","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Process.Native$FileActions","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Process.Native$HostFeatures","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Process.Native$HostSignalPolicy","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Process.Native$Pipes","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Process.Native$SpawnAttributes","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Process.Native$Spec","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Process.Native$Spec","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Process.Native$args","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Process.Native$cwd","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Process.Native$env","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Process.Native$file","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Process.Native$Start","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Process.Native$Owned","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Process.Native$Refused","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Process.Native$WaitCall"],"visible_exports":[],"options":["OptHide"],"fix_map":{}},{"module":"$libtmux-haskell-0.1.0.0-inplace$LibTmux.Value","is_sig":false,"info":{"description":null,"copyright":null,"maintainer":null,"stability":null,"protability":null,"safety":"None","language":"GHC2024","extensions":["OverloadedStrings","DuplicateRecordFields","OverloadedRecordDot"]},"doc_map":{"$libtmux-haskell-0.1.0.0-inplace$LibTmux.Value$dimensionValue":{"meta":{"version":null},"document":{"tag":"DocParagraph","document":{"tag":"DocString","string":"Read a dimension as a mathematical integer, without narrowing conversion."}}},"$libtmux-haskell-0.1.0.0-inplace$LibTmux.Value$mkDimension":{"meta":{"version":null},"document":{"tag":"DocParagraph","document":{"tag":"DocString","string":"Construct a positive dimension without applying a command-specific maximum."}}},"$libtmux-haskell-0.1.0.0-inplace$LibTmux.Value$mkPaneIndex":{"meta":{"version":null},"document":{"tag":"DocParagraph","document":{"tag":"DocString","string":"Construct a nonnegative pane index."}}},"$libtmux-haskell-0.1.0.0-inplace$LibTmux.Value$mkWindowIndex":{"meta":{"version":null},"document":{"tag":"DocParagraph","document":{"tag":"DocString","string":"Construct a nonnegative window-link index."}}},"$libtmux-haskell-0.1.0.0-inplace$LibTmux.Value$paneIndexValue":{"meta":{"version":null},"document":{"tag":"DocParagraph","document":{"tag":"DocString","string":"Read a pane index as a mathematical integer."}}},"$libtmux-haskell-0.1.0.0-inplace$LibTmux.Value$windowIndexValue":{"meta":{"version":null},"document":{"tag":"DocParagraph","document":{"tag":"DocString","string":"Read a window-link index as a mathematical integer."}}},"$libtmux-haskell-0.1.0.0-inplace$LibTmux.Value$Dimension":{"meta":{"version":null},"document":{"tag":"DocParagraph","document":{"tag":"DocAppend","first":{"tag":"DocString","string":"Positive cells, constructed with "},"second":{"tag":"DocAppend","first":{"tag":"DocIdentifier","name":"$libtmux-haskell-0.1.0.0-inplace$LibTmux.Value$mkDimension"},"second":{"tag":"DocAppend","first":{"tag":"DocString","string":". Command and field limits\n are checked separately. Compare dimensions directly or use "},"second":{"tag":"DocAppend","first":{"tag":"DocIdentifier","name":"$libtmux-haskell-0.1.0.0-inplace$LibTmux.Value$dimensionValue"},"second":{"tag":"DocString","string":"\n with an integer literal."}}}}}}},"$libtmux-haskell-0.1.0.0-inplace$LibTmux.Value$PaneIndex":{"meta":{"version":null},"document":{"tag":"DocParagraph","document":{"tag":"DocAppend","first":{"tag":"DocString","string":"Nonnegative pane index within a window, not a pane ID.\n Construct with "},"second":{"tag":"DocAppend","first":{"tag":"DocIdentifier","name":"$libtmux-haskell-0.1.0.0-inplace$LibTmux.Value$mkPaneIndex"},"second":{"tag":"DocAppend","first":{"tag":"DocString","string":"; read with "},"second":{"tag":"DocAppend","first":{"tag":"DocIdentifier","name":"$libtmux-haskell-0.1.0.0-inplace$LibTmux.Value$paneIndexValue"},"second":{"tag":"DocString","string":"."}}}}}}},"$libtmux-haskell-0.1.0.0-inplace$LibTmux.Value$ValueError":{"meta":{"version":null},"document":{"tag":"DocParagraph","document":{"tag":"DocString","string":"A scalar outside its mathematical domain."}}},"$libtmux-haskell-0.1.0.0-inplace$LibTmux.Value$NegativeIndex":{"meta":{"version":null},"document":{"tag":"DocParagraph","document":{"tag":"DocString","string":"The supplied contextual index was negative."}}},"$libtmux-haskell-0.1.0.0-inplace$LibTmux.Value$NonPositiveDimension":{"meta":{"version":null},"document":{"tag":"DocParagraph","document":{"tag":"DocString","string":"The supplied dimension was zero or negative."}}},"$libtmux-haskell-0.1.0.0-inplace$LibTmux.Value$WindowIndex":{"meta":{"version":null},"document":{"tag":"DocParagraph","document":{"tag":"DocAppend","first":{"tag":"DocString","string":"Nonnegative index of a window link within a session, not a physical window ID.\n Construct with "},"second":{"tag":"DocAppend","first":{"tag":"DocIdentifier","name":"$libtmux-haskell-0.1.0.0-inplace$LibTmux.Value$mkWindowIndex"},"second":{"tag":"DocAppend","first":{"tag":"DocString","string":"; read with "},"second":{"tag":"DocAppend","first":{"tag":"DocIdentifier","name":"$libtmux-haskell-0.1.0.0-inplace$LibTmux.Value$windowIndexValue"},"second":{"tag":"DocString","string":"."}}}}}}}},"arg_map":{},"exports":["$libtmux-haskell-0.1.0.0-inplace$LibTmux.Value$dimensionValue","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Value$mkDimension","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Value$mkPaneIndex","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Value$mkWindowIndex","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Value$paneIndexValue","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Value$windowIndexValue","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Value$Dimension","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Value$PaneIndex","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Value$ValueError","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Value$NegativeIndex","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Value$NonPositiveDimension","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Value$WindowIndex"],"visible_exports":["$libtmux-haskell-0.1.0.0-inplace$LibTmux.Value$Dimension","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Value$WindowIndex","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Value$PaneIndex","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Value$ValueError","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Value$NegativeIndex","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Value$NonPositiveDimension","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Value$mkDimension","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Value$mkWindowIndex","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Value$mkPaneIndex","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Value$dimensionValue","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Value$windowIndexValue","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Value$paneIndexValue"],"options":[],"fix_map":{}},{"module":"$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Graph","is_sig":false,"info":{"description":null,"copyright":null,"maintainer":null,"stability":null,"protability":null,"safety":"None","language":"GHC2024","extensions":["OverloadedStrings","DuplicateRecordFields","OverloadedRecordDot"]},"doc_map":{},"arg_map":{},"exports":["$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Graph$assembleEntityGraph","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Graph$graphLinks","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Graph$graphOccurrences","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Graph$graphPanes","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Graph$graphSessions","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Graph$graphWindows","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Graph$linksForSession","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Graph$lookupPane","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Graph$lookupSession","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Graph$lookupWindow","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Graph$panesForWindow","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Graph$EndpointIdentity","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Graph$EndpointIdentity","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Graph$EntityGraph","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Graph$Generation","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Graph$Generation","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Graph$GraphError","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Graph$ConflictingPane","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Graph$ConflictingSession","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Graph$ConflictingWindow","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Graph$DuplicatePaneIndex","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Graph$DuplicateWindowSlot","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Graph$ForeignGeneration","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Graph$InvalidAttachedCount","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Graph$InvalidGeneration","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Graph$InvalidPaneSelection","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Graph$InvalidSessionSelection","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Graph$MissingPane","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Graph$MissingSession","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Graph$MissingWindow","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Graph$UnlinkedWindow","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Graph$Pane","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Graph$Pane","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Graph$active","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Graph$currentCommand","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Graph$currentPath","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Graph$dead","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Graph$height","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Graph$index","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Graph$ref","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Graph$title","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Graph$width","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Graph$window","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Graph$PaneOccurrence","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Graph$PaneOccurrence","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Graph$link","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Graph$pane","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Graph$PaneRef","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Graph$PaneRef","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Graph$Session","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Graph$Session","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Graph$attached","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Graph$name","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Graph$ref","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Graph$SessionRef","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Graph$SessionRef","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Graph$Window","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Graph$Window","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Graph$height","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Graph$name","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Graph$ref","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Graph$width","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Graph$WindowLink","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Graph$WindowLink","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Graph$active","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Graph$index","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Graph$session","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Graph$window","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Graph$WindowRef","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Graph$WindowRef"],"visible_exports":[],"options":["OptHide"],"fix_map":{}},{"module":"$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.SocketPin","is_sig":false,"info":{"description":null,"copyright":null,"maintainer":null,"stability":null,"protability":null,"safety":"None","language":"GHC2024","extensions":["CApiFFI","OverloadedStrings","DuplicateRecordFields","OverloadedRecordDot"]},"doc_map":{},"arg_map":{},"exports":["$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.SocketPin$acquirePin","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.SocketPin$acquirePinWith","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.SocketPin$closePin","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.SocketPin$newPinOwner","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.SocketPin$pinGeneration","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.SocketPin$pinPath","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.SocketPin$PinCheckpoint","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.SocketPin$BeforeEntropy","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.SocketPin$BeforeLink","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.SocketPin$BeforePublish","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.SocketPin$DirectoryRegistered","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.SocketPin$LinkRegistered","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.SocketPin$PinError","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.SocketPin$PinAlreadyUsed","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.SocketPin$SocketPinCleanupFailed","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.SocketPin$SocketPinUnavailable","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.SocketPin$PinOwner","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.SocketPin$PinReason","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.SocketPin$AliasTooLong","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.SocketPin$EntropyUnavailable","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.SocketPin$FileSystemFailure","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.SocketPin$IdentityChanged","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.SocketPin$InvalidPath","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.SocketPin$SocketNotWritable","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.SocketPin$SocketOwnerMismatch","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.SocketPin$UntrustedDirectory","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.SocketPin$WrongSocketType","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.SocketPin$SocketPin"],"visible_exports":[],"options":["OptHide"],"fix_map":{}},{"module":"$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Process","is_sig":false,"info":{"description":null,"copyright":null,"maintainer":null,"stability":null,"protability":null,"safety":"None","language":"GHC2024","extensions":["OverloadedStrings","DuplicateRecordFields","OverloadedRecordDot"]},"doc_map":{"$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Process$cleanup":{"meta":{"version":null},"document":{"tag":"DocParagraph","document":{"tag":"DocString","string":"Close stream endpoints, terminate if still owned, then retain the reap."}}},"$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Process$preservingFinally":{"meta":{"version":null},"document":{"tag":"DocParagraph","document":{"tag":"DocString","string":"Keep an action failure primary and retain a simultaneous cleanup failure.\n A cleanup failure on its own remains a thrown exception."}}},"$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Process$reap":{"meta":{"version":null},"document":{"tag":"DocParagraph","document":{"tag":"DocString","string":"One masked consume/cache transition serves normal waiting and cleanup."}}},"$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Process$requestClose":{"meta":{"version":null},"document":{"tag":"DocParagraph","document":{"tag":"DocString","string":"Stop admission and report pending work without waiting for native calls."}}},"$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Process$submit":{"meta":{"version":null},"document":{"tag":"DocParagraph","document":{"tag":"DocAppend","first":{"tag":"DocString","string":"Return a detached caller-owned "},"second":{"tag":"DocAppend","first":{"tag":"DocIdentifier","name":"$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Process$Ticket"},"second":{"tag":"DocAppend","first":{"tag":"DocString","string":". Reserve shared child/byte credits\n before copying or forking; allocation failure rolls back both credits.\n Internal consumers precharge a separate parent envelope in\n "},"second":{"tag":"DocAppend","first":{"tag":"DocModule","string":"LibTmux.Internal.Budget"},"second":{"tag":"DocString","string":" for output retained after result publication."}}}}}}}},"arg_map":{},"exports":["$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Process$abort","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Process$abortAll","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Process$activeCount","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Process$await","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Process$awaitCleanup","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Process$both","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Process$childBytes","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Process$cleanup","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Process$completion","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Process$defaultHooks","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Process$finish","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Process$finishPin","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Process$first","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Process$forkIn","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Process$inputLimitBytes","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Process$newPool","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Process$normalFork","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Process$preservingFinally","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Process$progress","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Process$readStream","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Process$reap","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Process$recover","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Process$report","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Process$requestClose","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Process$retire","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Process$retireAll","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Process$runJob","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Process$stop","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Process$streamLimitBytes","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Process$submit","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Process$worker","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Process$CloseReport","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Process$CleanupComplete","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Process$CleanupIncomplete","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Process$PinCleanupFailed","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Process$PoolOpen","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Process$Completion","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Process$Completion","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Process$errors","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Process$exit","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Process$launchFailure","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Process$output","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Process$signalFailureCount","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Process$signalFailures","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Process$Fork","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Process$Hooks","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Process$Hooks","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Process$afterReap","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Process$afterStart","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Process$beforeSecondStream","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Process$launchNative","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Process$signalChild","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Process$waitNative","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Process$OwnerError","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Process$Aborted","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Process$PoolClosed","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Process$ResourceLimit","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Process$Pool","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Process$Pool","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Process$budget","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Process$capacity","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Process$clientLease","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Process$closing","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Process$forker","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Process$jobs","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Process$nextKey","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Process$pinBusy","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Process$pinOwner","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Process$pinResult","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Process$Progress","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Process$Progress","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Process$errorBytes","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Process$outputBytes","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Process$Ticket","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Process$Ticket","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Process$busy","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Process$cancelled","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Process$child","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Process$cleanupFailure","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Process$counts","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Process$descriptors","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Process$exitCache","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Process$failure","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Process$hooks","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Process$key","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Process$lease","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Process$result","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Process$signalErrorCount","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Process$signalErrors","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Internal.Process$signalLock"],"visible_exports":[],"options":["OptHide"],"fix_map":{}},{"module":"$libtmux-haskell-0.1.0.0-inplace$LibTmux.Version","is_sig":false,"info":{"description":null,"copyright":null,"maintainer":null,"stability":null,"protability":null,"safety":"None","language":"GHC2024","extensions":["OverloadedStrings","DuplicateRecordFields","OverloadedRecordDot"]},"doc_map":{"$libtmux-haskell-0.1.0.0-inplace$LibTmux.Version$parseVersion":{"meta":{"version":null},"document":{"tag":"DocParagraph","document":{"tag":"DocAppend","first":{"tag":"DocString","string":"Parse a stable release or the output of "},"second":{"tag":"DocAppend","first":{"tag":"DocMonospaced","document":{"tag":"DocString","string":"tmux -V"}},"second":{"tag":"DocString","string":", allowing one final LF.\n Development builds and trailing data are rejected rather than assigned\n capabilities from a guessed stable version. Diagnostics retain at most 64 chars."}}}}},"$libtmux-haskell-0.1.0.0-inplace$LibTmux.Version$renderVersion":{"meta":{"version":null},"document":{"tag":"DocParagraph","document":{"tag":"DocString","string":"Render the canonical release without the executable name or newline."}}},"$libtmux-haskell-0.1.0.0-inplace$LibTmux.Version$requireSupported":{"meta":{"version":null},"document":{"tag":"DocParagraph","document":{"tag":"DocString","string":"Reject releases older than plain 3.3. Individual features need their own\n capability checks; passing this check does not qualify an entire release."}}},"$libtmux-haskell-0.1.0.0-inplace$LibTmux.Version$TmuxVersion":{"meta":{"version":null},"document":{"tag":"DocParagraph","document":{"tag":"DocAppend","first":{"tag":"DocString","string":"A stable release, constructed by "},"second":{"tag":"DocAppend","first":{"tag":"DocIdentifier","name":"$libtmux-haskell-0.1.0.0-inplace$LibTmux.Version$parseVersion"},"second":{"tag":"DocAppend","first":{"tag":"DocString","string":" and rendered by\n "},"second":{"tag":"DocAppend","first":{"tag":"DocIdentifier","name":"$libtmux-haskell-0.1.0.0-inplace$LibTmux.Version$renderVersion"},"second":{"tag":"DocString","string":". Ordering compares numeric components before the patch letter."}}}}}}},"$libtmux-haskell-0.1.0.0-inplace$LibTmux.Version$VersionError":{"meta":{"version":null},"document":{"tag":"DocParagraph","document":{"tag":"DocString","string":"Invalid release syntax or a release below the supported floor."}}},"$libtmux-haskell-0.1.0.0-inplace$LibTmux.Version$MalformedVersion":{"meta":{"version":null},"document":{"tag":"DocParagraph","document":{"tag":"DocString","string":"Bounded copy of input that is not a stable release."}}},"$libtmux-haskell-0.1.0.0-inplace$LibTmux.Version$UnsupportedVersion":{"meta":{"version":null},"document":{"tag":"DocParagraph","document":{"tag":"DocString","string":"A stable release older than plain tmux 3.3."}}}},"arg_map":{},"exports":["$libtmux-haskell-0.1.0.0-inplace$LibTmux.Version$parseVersion","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Version$renderVersion","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Version$requireSupported","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Version$TmuxVersion","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Version$VersionError","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Version$MalformedVersion","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Version$UnsupportedVersion"],"visible_exports":["$libtmux-haskell-0.1.0.0-inplace$LibTmux.Version$TmuxVersion","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Version$VersionError","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Version$MalformedVersion","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Version$UnsupportedVersion","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Version$parseVersion","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Version$renderVersion","$libtmux-haskell-0.1.0.0-inplace$LibTmux.Version$requireSupported"],"options":[],"fix_map":{}}]} diff --git a/packages/api-model/test/fixtures/haskell-native/provenance.json b/packages/api-model/test/fixtures/haskell-native/provenance.json new file mode 100644 index 000000000..8a514e698 --- /dev/null +++ b/packages/api-model/test/fixtures/haskell-native/provenance.json @@ -0,0 +1,17 @@ +{ + "library_revision": "9fb506c96772affa6ea23bee41218cd41a931d51", + "ghc": "9.14.1", + "haddock": "2.33.0", + "modules": [ + "LibTmux.Id", + "LibTmux.Value", + "LibTmux.Version" + ], + "native_html_sha256": { + "LibTmux-Id.html": "cf7102eba62a0e9b02e7ea7acefb85d1822a4d192a1fceb680246ed42bd10d45", + "LibTmux-Value.html": "4160151534c27a8c787c9ab36fa6dcbf740fc193a7a3553935172be72111ff1d", + "LibTmux-Version.html": "7894f9afe9260e6d2d429aaf0b3f246428980b76756bba8d7a3ccc0637b22a6a" + }, + "installed_json_sha256": "268e9e69b454d362ffc8eeeabdb6a384d86e327e0d9487cba7b567f136e91fab", + "source_anchor_fixture": "Only native id/line markers retained; no implementation text." +} diff --git a/packages/api-model/test/fixtures/haskell-native/source-anchors.json b/packages/api-model/test/fixtures/haskell-native/source-anchors.json new file mode 100644 index 000000000..2211de276 --- /dev/null +++ b/packages/api-model/test/fixtures/haskell-native/source-anchors.json @@ -0,0 +1,579 @@ +{ + "LibTmux.Id": { + "SessionId": [ + 45, + 45 + ], + "local-6989586621679100011": [ + 46 + ], + "local-6989586621679100015": [ + 46 + ], + "local-6989586621679100022": [ + 46 + ], + "local-6989586621679100026": [ + 46 + ], + "local-6989586621679100029": [ + 46 + ], + "local-6989586621679100033": [ + 46 + ], + "local-6989586621679100036": [ + 46 + ], + "local-6989586621679100039": [ + 46 + ], + "local-6989586621679100042": [ + 46 + ], + "local-6989586621679100050": [ + 46 + ], + "local-6989586621679100054": [ + 46 + ], + "local-6989586621679100058": [ + 46 + ], + "local-6989586621679100063": [ + 47 + ], + "WindowId": [ + 51, + 51 + ], + "local-6989586621679100072": [ + 52 + ], + "local-6989586621679100075": [ + 52 + ], + "local-6989586621679100081": [ + 52 + ], + "local-6989586621679100084": [ + 52 + ], + "local-6989586621679100087": [ + 52 + ], + "local-6989586621679100091": [ + 52 + ], + "local-6989586621679100094": [ + 52 + ], + "local-6989586621679100097": [ + 52 + ], + "local-6989586621679100100": [ + 52 + ], + "local-6989586621679100103": [ + 52 + ], + "local-6989586621679100107": [ + 52 + ], + "local-6989586621679100111": [ + 52 + ], + "local-6989586621679100114": [ + 53 + ], + "PaneId": [ + 57, + 57 + ], + "local-6989586621679100120": [ + 58 + ], + "local-6989586621679100123": [ + 58 + ], + "local-6989586621679100129": [ + 58 + ], + "local-6989586621679100132": [ + 58 + ], + "local-6989586621679100135": [ + 58 + ], + "local-6989586621679100139": [ + 58 + ], + "local-6989586621679100142": [ + 58 + ], + "local-6989586621679100145": [ + 58 + ], + "local-6989586621679100148": [ + 58 + ], + "local-6989586621679100151": [ + 58 + ], + "local-6989586621679100155": [ + 58 + ], + "local-6989586621679100159": [ + 58 + ], + "local-6989586621679100162": [ + 59 + ], + "IdError": [ + 63 + ], + "InvalidId": [ + 63 + ], + "expectedPrefix": [ + 64 + ], + "input": [ + 65 + ], + "local-6989586621679100170": [ + 67 + ], + "local-6989586621679100175": [ + 67 + ], + "local-6989586621679100179": [ + 67 + ], + "local-6989586621679100186": [ + 67 + ], + "local-6989586621679100190": [ + 67 + ], + "parseSessionId": [ + 71 + ], + "parseWindowId": [ + 75 + ], + "parsePaneId": [ + 79 + ], + "renderSessionId": [ + 83 + ], + "local-6989586621679100194": [ + 83 + ], + "renderWindowId": [ + 87 + ], + "local-6989586621679100197": [ + 87 + ], + "renderPaneId": [ + 91 + ], + "local-6989586621679100198": [ + 91 + ], + "sessionIdValue": [ + 95 + ], + "local-6989586621679100199": [ + 95 + ], + "windowIdValue": [ + 99 + ], + "local-6989586621679100200": [ + 99 + ], + "paneIdValue": [ + 103 + ], + "local-6989586621679100201": [ + 103 + ], + "parseId": [ + 106 + ], + "local-6989586621679100202": [ + 106 + ], + "local-6989586621679100203": [ + 106 + ], + "local-6989586621679100205": [ + 108 + ], + "local-6989586621679100206": [ + 109 + ], + "local-6989586621679100210": [ + 111 + ], + "local-6989586621679100211": [ + 111 + ], + "local-6989586621679100213": [ + 113 + ], + "local-6989586621679100214": [ + 113 + ], + "local-6989586621679100219": [ + 115 + ], + "local-6989586621679100221": [ + 116 + ], + "local-6989586621679100223": [ + 116 + ], + "local-6989586621679100224": [ + 116 + ] + }, + "LibTmux.Value": { + "Dimension": [ + 35, + 35 + ], + "local-6989586621679101504": [ + 36 + ], + "local-6989586621679101508": [ + 36 + ], + "local-6989586621679101515": [ + 36 + ], + "local-6989586621679101518": [ + 36 + ], + "local-6989586621679101521": [ + 36 + ], + "local-6989586621679101525": [ + 36 + ], + "local-6989586621679101528": [ + 36 + ], + "local-6989586621679101531": [ + 36 + ], + "local-6989586621679101534": [ + 36 + ], + "local-6989586621679101542": [ + 36 + ], + "local-6989586621679101548": [ + 36 + ], + "local-6989586621679101552": [ + 36 + ], + "local-6989586621679101557": [ + 37 + ], + "WindowIndex": [ + 41, + 41 + ], + "local-6989586621679101566": [ + 42 + ], + "local-6989586621679101569": [ + 42 + ], + "local-6989586621679101575": [ + 42 + ], + "local-6989586621679101578": [ + 42 + ], + "local-6989586621679101581": [ + 42 + ], + "local-6989586621679101585": [ + 42 + ], + "local-6989586621679101588": [ + 42 + ], + "local-6989586621679101591": [ + 42 + ], + "local-6989586621679101594": [ + 42 + ], + "local-6989586621679101597": [ + 42 + ], + "local-6989586621679101601": [ + 42 + ], + "local-6989586621679101605": [ + 42 + ], + "local-6989586621679101608": [ + 43 + ], + "PaneIndex": [ + 47, + 47 + ], + "local-6989586621679101614": [ + 48 + ], + "local-6989586621679101617": [ + 48 + ], + "local-6989586621679101623": [ + 48 + ], + "local-6989586621679101626": [ + 48 + ], + "local-6989586621679101629": [ + 48 + ], + "local-6989586621679101633": [ + 48 + ], + "local-6989586621679101636": [ + 48 + ], + "local-6989586621679101639": [ + 48 + ], + "local-6989586621679101642": [ + 48 + ], + "local-6989586621679101645": [ + 48 + ], + "local-6989586621679101649": [ + 48 + ], + "local-6989586621679101653": [ + 48 + ], + "local-6989586621679101656": [ + 49 + ], + "ValueError": [ + 52 + ], + "NonPositiveDimension": [ + 53 + ], + "NegativeIndex": [ + 54 + ], + "local-6989586621679101663": [ + 55 + ], + "local-6989586621679101670": [ + 55 + ], + "local-6989586621679101674": [ + 55 + ], + "local-6989586621679101680": [ + 55 + ], + "local-6989586621679101684": [ + 55 + ], + "mkDimension": [ + 59 + ], + "local-6989586621679101686": [ + 59 + ], + "mkWindowIndex": [ + 65 + ], + "local-6989586621679101687": [ + 65 + ], + "mkPaneIndex": [ + 71 + ], + "local-6989586621679101688": [ + 71 + ], + "dimensionValue": [ + 77 + ], + "local-6989586621679101689": [ + 77 + ], + "windowIndexValue": [ + 81 + ], + "local-6989586621679101690": [ + 81 + ], + "paneIndexValue": [ + 85 + ], + "local-6989586621679101691": [ + 85 + ] + }, + "LibTmux.Version": { + "TmuxVersion": [ + 31, + 31 + ], + "local-6989586621679105033": [ + 32 + ], + "local-6989586621679105041": [ + 32 + ], + "local-6989586621679105049": [ + 32 + ], + "local-6989586621679105056": [ + 32 + ], + "local-6989586621679105061": [ + 32 + ], + "local-6989586621679105064": [ + 32 + ], + "local-6989586621679105067": [ + 32 + ], + "local-6989586621679105070": [ + 32 + ], + "local-6989586621679105073": [ + 32 + ], + "local-6989586621679105081": [ + 32 + ], + "local-6989586621679105089": [ + 32 + ], + "local-6989586621679105093": [ + 32 + ], + "VersionError": [ + 35 + ], + "MalformedVersion": [ + 36 + ], + "UnsupportedVersion": [ + 37 + ], + "local-6989586621679105101": [ + 38 + ], + "local-6989586621679105109": [ + 38 + ], + "local-6989586621679105113": [ + 38 + ], + "local-6989586621679105120": [ + 38 + ], + "local-6989586621679105124": [ + 38 + ], + "parseVersion": [ + 44 + ], + "local-6989586621679105126": [ + 44 + ], + "local-6989586621679105128": [ + 48 + ], + "local-6989586621679105133": [ + 49 + ], + "local-6989586621679105135": [ + 50 + ], + "local-6989586621679105130": [ + 51 + ], + "local-6989586621679105137": [ + 52 + ], + "local-6989586621679105138": [ + 52 + ], + "local-6989586621679105140": [ + 53 + ], + "local-6989586621679105141": [ + 54 + ], + "local-6989586621679105142": [ + 54 + ], + "local-6989586621679105145": [ + 55 + ], + "local-6989586621679105147": [ + 56 + ], + "local-6989586621679105148": [ + 57 + ], + "local-6989586621679105150": [ + 59 + ], + "local-6989586621679105146": [ + 63 + ], + "local-6989586621679105154": [ + 63 + ], + "local-6989586621679105156": [ + 65 + ], + "local-6989586621679105144": [ + 69 + ], + "local-6989586621679105162": [ + 69 + ], + "renderVersion": [ + 73 + ], + "local-6989586621679105163": [ + 73 + ], + "local-6989586621679105164": [ + 73 + ], + "local-6989586621679105165": [ + 73 + ], + "requireSupported": [ + 79 + ], + "local-6989586621679105168": [ + 79 + ] + } +} diff --git a/packages/api-model/test/guarantees.test.ts b/packages/api-model/test/guarantees.test.ts index b2f4451a4..76a9d987c 100644 --- a/packages/api-model/test/guarantees.test.ts +++ b/packages/api-model/test/guarantees.test.ts @@ -1,6 +1,4 @@ -import { execFileSync } from 'node:child_process' -import { existsSync, mkdtempSync, readFileSync, writeFileSync } from 'node:fs' -import { tmpdir } from 'node:os' +import { existsSync, readFileSync } from 'node:fs' import { dirname, join } from 'node:path' import { fileURLToPath } from 'node:url' import { describe, expect, it } from 'vitest' @@ -9,7 +7,6 @@ import { tokenizeDoc, docSummaryText } from '../src/doc/roles.ts' import { SymbolIndex } from '../src/link.ts' import { javadocToMarkdown, parseJavadoc } from '../src/doc/javadoc.ts' import { tableMentions } from '../src/mentions.ts' -import { readInventory, writeInventory } from '../src/inventory.ts' import type { ApiModel } from '../src/model.ts' const here = dirname(fileURLToPath(import.meta.url)) @@ -21,73 +18,6 @@ function load(port: string): ApiModel | undefined { return existsSync(path) ? (JSON.parse(readFileSync(path, 'utf8')) as ApiModel) : undefined } -/** Whether `uv` can run Sphinx here. Absent on a machine without it. */ -function sphinxAvailable(): boolean { - try { - execFileSync('uv', ['--version'], { stdio: 'ignore' }) - return true - } catch { - return false - } -} - -describe('Sphinx itself can read every inventory we write', () => { - /** - * Our reader is not evidence that our writer is right. - * - * `readInventory` and `writeInventory` were written together from the same - * reading of the format, so a shared misunderstanding round-trips perfectly - * and fails only in Sphinx. This loads each file with - * `sphinx.util.inventory.InventoryFile.load` — the code that will actually - * consume these files — and compares what it finds against the model. - * - * The header is as load-bearing as the body: four plaintext lines, the - * fourth naming the compression, then zlib. Sphinx rejects the file outright - * if any of that is wrong, which is a better failure than a silently empty - * inventory. - */ - const canRun = sphinxAvailable() - - it.runIf(canRun).each(PORTS)('%s loads in Sphinx with every entry intact', (port) => { - const model = load(port) - if (!model) return - - const bytes = writeInventory(model, { - project: `libtmux-${port}`, - version: 'test', - uriFor: (s) => `reference/${port}/#${s.publicId ?? s.id}`, - }) - const dir = mkdtempSync(join(tmpdir(), 'libtmux-inv-')) - const file = join(dir, 'objects.inv') - writeFileSync(file, bytes) - - const script = ` -import json, sys -from sphinx.util.inventory import InventoryFile -with open(sys.argv[1], "rb") as fh: - inv = InventoryFile.load(fh, "https://libtmux.org/", lambda base, uri: base + uri) -count = sum(len(entries) for entries in inv.values()) -names = sorted({name for entries in inv.values() for name in entries}) -print(json.dumps({"count": count, "domains": sorted(inv), "sample": names[:3]})) -` - const out = execFileSync( - 'uv', - ['run', '--with', 'sphinx', 'python', '-c', script, file], - { encoding: 'utf8', timeout: 120_000 }, - ) - const result = JSON.parse(out.trim().split('\n').pop() ?? '{}') as { - count: number - domains: string[] - sample: string[] - } - - expect(result.count, `${port}: Sphinx read a different number of entries`).toBe( - model.symbols.length, - ) - expect(result.domains.length, `${port}: no domains`).toBeGreaterThan(0) - }) -}) - describe('names are representable', () => { /** * An inventory record is whitespace-delimited, so a name containing a space diff --git a/packages/api-model/test/haskell-native.test.ts b/packages/api-model/test/haskell-native.test.ts new file mode 100644 index 000000000..d83bb8f82 --- /dev/null +++ b/packages/api-model/test/haskell-native.test.ts @@ -0,0 +1,13 @@ +import { spawnSync } from 'node:child_process' +import { fileURLToPath } from 'node:url' +import { expect, it } from 'vitest' + +it('preserves native Haskell declarations and source/exporter provenance', () => { + const root = fileURLToPath(new URL('../../../', import.meta.url)) + const result = spawnSync('python3', ['-m', 'unittest', 'packages/api-model/test/test_haskell_export.py'], { + cwd: root, encoding: 'utf8', + }) + expect(result.error).toBeUndefined() + expect(result.status, result.stderr).toBe(0) + expect(result.stderr).toMatch(/Ran [1-9]\d* tests?/) +}) diff --git a/packages/api-model/test/haskell.test.ts b/packages/api-model/test/haskell.test.ts new file mode 100644 index 000000000..cd17296b8 --- /dev/null +++ b/packages/api-model/test/haskell.test.ts @@ -0,0 +1,153 @@ +import { readFileSync } from 'node:fs' +import { describe, expect, it } from 'vitest' +import { extractHaskellArtifact } from '../src/languages/haskell.ts' +import { tokenizeDoc } from '../src/doc/roles.ts' +import { SymbolIndex } from '../src/link.ts' +import { navSidecar } from '../src/nav-sidecar.ts' +import { sourceUrl } from '../src/products.ts' + +const artifact = JSON.parse(readFileSync(new URL('./fixtures/haskell-native/artifact.json', import.meta.url), 'utf8')) +const native = (input: typeof artifact) => input.symbols.find((symbol: { id: string }) => symbol.id === 'LibTmux.Id#t:SessionId') + +describe('Haddock shared-model adapter', () => { + it('retains independently identified library, producer and native inputs', () => { + const model = extractHaskellArtifact(artifact, artifact.revision) + expect(model).toMatchObject({ port: 'haskell', repo: artifact.repo, revision: artifact.revision }) + expect(model.nativeProvenance).toEqual(artifact.nativeProvenance) + expect(model.nativeProvenance!.exporter.revision).not.toBe(model.revision) + expect(model.sources).toEqual([{ + product: 'core', package: 'libtmux-haskell', version: '0.1.0.0', repo: artifact.repo, + revision: artifact.revision, extractedRevision: artifact.revision, + }]) + expect(model.symbols).toHaveLength(38) + const pane = model.symbols.find((symbol) => symbol.id === 'LibTmux.Id#v:parsePaneId')! + expect(sourceUrl(model, pane)).toBe(`https://github.com/${artifact.repo}/blob/${artifact.revision}/src/LibTmux/Id.hs#L79`) + expect(sourceUrl(model, model.symbols[0])).toBe(`https://github.com/${artifact.repo}/blob/${artifact.revision}/src/LibTmux/Id.hs`) + }) + + it('preserves native signatures, opaque types, constructors and non-selector record labels', () => { + const model = extractHaskellArtifact(artifact) + const symbol = (id: string) => model.symbols.find((entry) => entry.id === id)! + for (const native of artifact.symbols) expect(symbol(native.id).signatures).toEqual(native.signatures) + expect(symbol('LibTmux.Id#t:SessionId')).toMatchObject({ kind: 'typealias', modifiers: ['opaque'] }) + expect(symbol('LibTmux.Id#t:SessionId').signatures[0].raw).toBe('data SessionId') + expect(symbol('LibTmux.Id#t:SessionId')).not.toHaveProperty('type') + expect(symbol('LibTmux.Id#t:SessionId')).not.toHaveProperty('extends') + expect(symbol('LibTmux.Id#v:InvalidId')).toMatchObject({ + parent: 'LibTmux.Id#t:IdError', signatures: [{ methodKind: 'constructor', raw: 'InvalidId', params: [] }], + }) + expect(symbol('LibTmux.Id#v:expectedPrefix')).toMatchObject({ + kind: 'property', parent: 'LibTmux.Id#t:IdError', signatures: [{ raw: 'expectedPrefix :: !Char' }], + }) + expect(model.symbols.filter((entry) => entry.name === 'expectedPrefix')).toHaveLength(1) + expect(model.symbols.some((entry) => ['show', 'compare', 'rnf'].includes(entry.name))).toBe(false) + }) + + it('keeps authored interlinks and examples and adds instance heads with their exact source links', () => { + const model = extractHaskellArtifact(artifact) + const module = model.symbols.find((symbol) => symbol.id === 'LibTmux.Id')! + expect(module.doc).toEqual(artifact.symbols.find((symbol: { id: string }) => symbol.id === module.id).doc) + const session = model.symbols.find((symbol) => symbol.id === 'LibTmux.Id#t:SessionId')! + expect(session.doc!.body).toContain('## Instances\n\n') + expect(session.doc!.body).toContain('instance [Eq](https://hackage.haskell.org/package/base-4.22.0.0/docs/Data-Eq.html#t:Eq)') + expect(session.doc!.body).toContain(':obj:`SessionId `') + expect(session.doc!.body).toContain(`[Source](https://github.com/${artifact.repo}/blob/${artifact.revision}/src/LibTmux/Id.hs#L46)`) + expect(session.references).toContainEqual({ target: session.id, kind: 'type' }) + expect(model.symbols.find((symbol) => symbol.id === 'LibTmux.Id#v:parsePaneId')!.references).toEqual([ + { target: 'LibTmux.Id#t:IdError', kind: 'type' }, { target: 'LibTmux.Id#t:PaneId', kind: 'type' }, + ]) + }) + + it('regenerates complete native navigation from the stored model alone', () => { + const model = extractHaskellArtifact(artifact) + expect(model.exportGroups).toEqual(artifact.modules.flatMap((module: { name: string; groups: object[] }) => + module.groups.map((group) => ({ owner: module.name, ...group })))) + const sidecar = navSidecar('haskell', JSON.parse(JSON.stringify(model)))! + expect(sidecar.buckets.map((bucket) => bucket.label)).toEqual(artifact.package.exposedModules) + expect(Object.keys(sidecar.placement)).toHaveLength(31) + expect(sidecar.diagnostics).toEqual({ unmatched: [], deadBuckets: [], ambiguous: [], staleUnsettled: [] }) + }) + + it('resolves the native public identities in normalized prose and keeps instance URLs', () => { + const model = extractHaskellArtifact(artifact) + const index = new SymbolIndex(model.symbols, (symbol) => `/${encodeURIComponent(symbol.publicId ?? symbol.id)}/`, 'haskell') + const text = model.symbols.find((symbol) => symbol.id === 'LibTmux.Id')!.doc!.body! + expect(tokenizeDoc(text, 'haskell')).toContainEqual({ + kind: 'ref', role: 'obj', target: 'LibTmux.Id#v:parseSessionId', label: 'parseSessionId', + }) + const instances = tokenizeDoc(model.symbols.find((symbol) => symbol.id === 'LibTmux.Id#t:SessionId')!.doc!.body!, 'haskell') + expect(instances).toContainEqual({ kind: 'link', text: 'Eq', + href: 'https://hackage.haskell.org/package/base-4.22.0.0/docs/Data-Eq.html#t:Eq' }) + for (const symbol of model.symbols) { + for (const prose of [symbol.doc?.summary, symbol.doc?.body].filter((text): text is string => !!text)) { + for (const span of tokenizeDoc(prose, 'haskell')) { + if (span.kind === 'ref') expect(index.resolve(span.target, span.role, symbol), span.target).toBeDefined() + } + } + } + }) + + it.each([ + ['schema', (a: typeof artifact) => { a.schema = 'libtmux.haskell-api/2' }], + ['compiler profile', (a: typeof artifact) => { a.compiler = '9.12.2' }], + ['selected source revision', (a: typeof artifact) => { a.revision = 'f'.repeat(40) }], + ['producer identity', (a: typeof artifact) => { a.nativeProvenance.exporter.revision = 'main' }], + ['native input hash', (a: typeof artifact) => { a.nativeProvenance.exporter.nativeArtifacts[0].sha256 = 'bad' }], + ['missing native input', (a: typeof artifact) => { a.nativeProvenance.exporter.nativeArtifacts.pop() }], + ['missing source input', (a: typeof artifact) => { a.nativeProvenance.files.pop() }], + ['duplicate symbol', (a: typeof artifact) => { a.symbols.push(a.symbols[0]) }], + ['public namespace', (a: typeof artifact) => { native(a).namespace = 'LibTmux.Private' }], + ['unsupported symbol kind', (a: typeof artifact) => { native(a).kind = 'class' }], + ['private declaration', (a: typeof artifact) => { native(a).apiScope = 'internal' }], + ['parent identity', (a: typeof artifact) => { native(a).parent = 'missing' }], + ['source path', (a: typeof artifact) => { native(a).source.file = '../secret.hs' }], + ['source revision', (a: typeof artifact) => { native(a).source.revision = 'e'.repeat(40) }], + ['source line', (a: typeof artifact) => { native(a).source.line = 0 }], + ['opaque representation', (a: typeof artifact) => { native(a).signatures[0].raw += ' = MkSessionId Word32' }], + ['lost opaque status', (a: typeof artifact) => { native(a).modifiers = [] }], + ['constructor role on a record label', (a: typeof artifact) => { + a.symbols.find((symbol: { name: string }) => symbol.name === 'expectedPrefix').signatures[0].methodKind = 'constructor' + }], + ['missing native spans', (a: typeof artifact) => { delete native(a).signatures[0].nativeSpans }], + ['mismatched native spans', (a: typeof artifact) => { native(a).signatures[0].nativeSpans[0].text = 'newtype' }], + ['declaration marker', (a: typeof artifact) => { delete native(a).signatures[0].nativeSpans[2].declaration }], + ['missing export group', (a: typeof artifact) => { a.modules[0].groups.pop() }], + ['missing module', (a: typeof artifact) => { a.modules.pop() }], + ['instance source', (a: typeof artifact) => { native(a).instances[0].source.revision = 'e'.repeat(40) }], + ['missing instances metadata', (a: typeof artifact) => { delete native(a).instances }], + ['another type\'s instances', (a: typeof artifact) => { + native(a).instances = a.symbols.find((symbol: { id: string }) => symbol.id === 'LibTmux.Id#t:PaneId').instances + }], + ['instance Markdown', (a: typeof artifact) => { native(a).instances[0].markdown += ' wrong display' }], + ['instance raw head', (a: typeof artifact) => { native(a).instances[0].raw = 'instance NFData PaneId' }], + ])('rejects invalid %s instead of publishing a partial reference', (_name, mutate) => { + const input = structuredClone(artifact) + mutate(input) + expect(() => extractHaskellArtifact(input, artifact.revision)).toThrow(/Haskell|export group/) + }) + + it('rejects a coherent but unqualified replacement module', () => { + const input = JSON.parse(JSON.stringify(artifact) + .replaceAll('LibTmux.Id', 'LibTmux.Other') + .replaceAll('LibTmux-Id', 'LibTmux-Other') + .replaceAll('LibTmux/Id.hs', 'LibTmux/Other.hs')) + expect(() => extractHaskellArtifact(input)).toThrow(/Haskell.*module/) + }) + + it.each([ + ['unknown target', { target: 'LibTmux.Private#t:Secret', href: 'LibTmux-Private.html#t:Secret' }], + ['wrong native anchor', { target: 'LibTmux.Id#t:IdError', href: 'LibTmux-Id.html#t:PaneId' }], + ['unresolved relative link', { href: 'LibTmux-Id.html#t:IdError' }], + ['unsafe external link', { href: 'javascript:alert(1)' }], + ])('rejects a %s in a signature or an instance', (_name, destination) => { + for (const context of ['signature', 'instance']) { + const input = structuredClone(artifact) + const reference = context === 'signature' + ? input.symbols.find((symbol: { name: string }) => symbol.name === 'parsePaneId').signatures[0].nativeSpans[5] + : native(input).instances[0].references[1] + delete reference.target + Object.assign(reference, destination) + expect(() => extractHaskellArtifact(input)).toThrow(/Haskell/) + } + }) +}) diff --git a/packages/api-model/test/inventory-sphinx.outer.test.ts b/packages/api-model/test/inventory-sphinx.outer.test.ts new file mode 100644 index 000000000..81a4aa965 --- /dev/null +++ b/packages/api-model/test/inventory-sphinx.outer.test.ts @@ -0,0 +1,72 @@ +// Outer: compare generated inventories with the installed, lock-pinned Sphinx reader. +import { execFileSync } from 'node:child_process' +import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { dirname, join } from 'node:path' +import { fileURLToPath } from 'node:url' +import { describe, expect, it } from 'vitest' +import { writeInventory } from '../src/inventory.ts' +import type { ApiModel } from '../src/model.ts' + +const here = dirname(fileURLToPath(import.meta.url)) +const DATA = join(here, '../../../site/src/data/api') +const PORTS = ['py', 'ruby', 'lua', 'ts', 'rs', 'go', 'java', 'csharp', 'cxx', 'swift', 'perl'] as const +const load = (port: string): ApiModel => JSON.parse(readFileSync(join(DATA, `${port}.json`), 'utf8')) + +describe('Sphinx itself can read every inventory we write', () => { + /** + * Our reader is not evidence that our writer is right. + * + * `readInventory` and `writeInventory` were written together from the same + * reading of the format, so a shared misunderstanding round-trips perfectly + * and fails only in Sphinx. This loads each file with + * `sphinx.util.inventory.InventoryFile.load` — the code that will actually + * consume these files — and compares what it finds against the model. + * + * The header is as load-bearing as the body: four plaintext lines, the + * fourth naming the compression, then zlib. Sphinx rejects the file outright + * if any of that is wrong, which is a better failure than a silently empty + * inventory. + */ + it.each(PORTS)('%s loads in Sphinx with every entry intact', (port) => { + const model = load(port) + const bytes = writeInventory(model, { + project: `libtmux-${port}`, + version: 'test', + uriFor: (s) => `reference/${port}/#${s.publicId ?? s.id}`, + }) + const dir = mkdtempSync(join(tmpdir(), 'libtmux-inv-')) + const file = join(dir, 'objects.inv') + writeFileSync(file, bytes) + + const script = ` +import json, sys +from sphinx.util.inventory import InventoryFile +with open(sys.argv[1], "rb") as fh: + inv = InventoryFile.load(fh, "https://libtmux.org/", lambda base, uri: base + uri) +count = sum(len(entries) for entries in inv.values()) +names = sorted({name for entries in inv.values() for name in entries}) +print(json.dumps({"count": count, "domains": sorted(inv), "sample": names[:3]})) +` + let out: string + try { + out = execFileSync( + join(here, '../../../.venv/bin/python'), + ['-c', script, file], + { encoding: 'utf8', timeout: 5_000 }, + ) + } finally { + rmSync(dir, { recursive: true, force: true }) + } + const result = JSON.parse(out.trim().split('\n').pop() ?? '{}') as { + count: number + domains: string[] + sample: string[] + } + + expect(result.count, `${port}: Sphinx read a different number of entries`).toBe( + model.symbols.length, + ) + expect(result.domains.length, `${port}: no domains`).toBeGreaterThan(0) + }) +}) diff --git a/packages/api-model/test/lisp.test.ts b/packages/api-model/test/lisp.test.ts new file mode 100644 index 000000000..649a1b4e0 --- /dev/null +++ b/packages/api-model/test/lisp.test.ts @@ -0,0 +1,201 @@ +import { describe, expect, it } from 'vitest' +import { extractCommonLisp } from '../src/languages/lisp.ts' +import { SymbolIndex } from '../src/link.ts' + +const revision = '1'.repeat(40) +const source = (file: string, line: number) => ({ file, line }) +const documentation = (summary: string, seeAlso: string[] = []) => ({ summary, seeAlso }) +const functionSymbol = (id: string, name: string, file: string, seeAlso: string[] = []) => ({ + id, name, kind: 'function', signature: `(${name} value)`, modifiers: [], generic: false, + documentation: documentation(`Call ${name.toUpperCase()}.`, seeAlso), source: source(file, 10), +}) + +const fixture = { + schema: 'libtmux.lisp.api/1', port: 'lisp', + library: { version: '0.1.0' }, + runtime: { implementation: 'SBCL', implementationVersion: '2.6.10', asdfVersion: '3.3.7' }, + source: { + repository: 'libtmux/libtmux-lisp', revision, dirty: false, + files: [ + { path: 'src/json.lisp', sha256: 'a'.repeat(64) }, + { path: 'src/model.lisp', sha256: 'b'.repeat(64) }, + { path: 'src/package.lisp', sha256: 'c'.repeat(64) }, + { path: 'src/query.lisp', sha256: 'd'.repeat(64) }, + { path: 'src/workspace-cli.lisp', sha256: 'e'.repeat(64) }, + { path: 'src/workspace.lisp', sha256: 'f'.repeat(64) }, + { path: 'tools/documentation.lisp', sha256: '0'.repeat(64) }, + ], + }, + exporter: { name: 'libtmux.documentation', version: 1, revision, dirty: false }, + packages: [ + { + name: 'libtmux', system: 'libtmux', product: 'core', + documentation: documentation('Native tmux observations.'), source: source('src/package.lisp', 1), + symbols: [ + functionSymbol('libtmux:session/function', 'session', 'src/model.lisp'), + { id: 'libtmux:session/type', name: 'session', kind: 'class', modifiers: ['opaque'], + supertypes: ['libtmux:entity'], documentation: documentation('A captured session.'), source: source('src/model.lisp', 25) }, + ], + }, + { name: 'libtmux.json', system: 'libtmux/json', product: 'core', documentation: documentation('Bounded JSON.'), + source: source('src/json.lisp', 1), symbols: [functionSymbol('libtmux.json:read-filter', 'read-filter', 'src/json.lisp')] }, + { name: 'libtmux.query', system: 'libtmux/query', product: 'core', documentation: documentation('Native queries.'), + source: source('src/query.lisp', 1), symbols: [functionSymbol('libtmux.query:compile-filter', 'compile-filter', 'src/query.lisp')] }, + { name: 'libtmux.workspace', system: 'libtmux/workspace', product: 'workspace', documentation: documentation('Owned workspaces.'), + source: source('src/workspace.lisp', 1), symbols: [functionSymbol('libtmux.workspace:apply-workspace', 'apply-workspace', 'src/workspace.lisp', ['libtmux.workspace:result-outcomes']), + functionSymbol('libtmux.workspace:result-outcomes', 'result-outcomes', 'src/workspace.lisp')] }, + { name: 'libtmux.workspace.cli', system: 'libtmux/workspace/cli', product: 'workspace', documentation: documentation('Workspace command adapter.'), + source: source('src/workspace-cli.lisp', 1), symbols: [functionSymbol('libtmux.workspace.cli:main', 'main', 'src/workspace-cli.lisp')] }, + ], +} + +describe('Common Lisp native API adapter', () => { + it('retains native packages, separate namespaces and authored links', () => { + const model = extractCommonLisp(fixture, revision) + expect(model).toMatchObject({ port: 'lisp', repo: fixture.source.repository, revision }) + expect(model.sources).toHaveLength(5) + expect(model.nativeProvenance?.exporter).toMatchObject({ name: 'libtmux.documentation', revision }) + expect(model.symbols.find((entry) => entry.id === 'libtmux:session/function')).toMatchObject({ + name: 'session', kind: 'function', qualifiedName: 'libtmux:session', parent: 'libtmux', + signatures: [{ raw: '(session value)', params: [{ name: 'value' }] }], + }) + expect(model.symbols.find((entry) => entry.id === 'libtmux:session/type')).toMatchObject({ + name: 'session', kind: 'class', qualifiedName: 'libtmux:session', modifiers: ['opaque'], + }) + expect(model.symbols.find((entry) => entry.id === 'libtmux.workspace:apply-workspace')?.doc?.seeAlso) + .toEqual(['libtmux.workspace:result-outcomes']) + }) + + it('extracts the optional public control package alongside existing systems', () => { + const input = structuredClone(fixture) + input.source.files.push({ path: 'src/control.lisp', sha256: '1'.repeat(64) }) + input.packages.splice(1, 0, { + name: 'libtmux.control', system: 'libtmux/control', product: 'core', + documentation: documentation('Scoped control connections.'), source: source('src/control.lisp', 1), + symbols: [functionSymbol('libtmux.control:open-connection', 'open-connection', 'src/control.lisp')], + }) + const model = extractCommonLisp(input, revision) + expect(model.sources).toHaveLength(6) + expect(model.symbols.find((entry) => entry.id === 'libtmux.control:open-connection')).toMatchObject({ + qualifiedName: 'libtmux.control:open-connection', parent: 'libtmux.control', product: 'core', + }) + input.packages[1]!.system = 'libtmux' + expect(() => extractCommonLisp(input, revision)).toThrow('public package inventory differs') + }) + + it('reads Common Lisp lambda-list roles without evaluating defaults', () => { + const input = structuredClone(fixture) + input.packages[0]!.symbols[0]!.signature = '(session required &optional (limit 10) &rest values &key ((:raw raw-p) nil))' + const signature = extractCommonLisp(input, revision).symbols + .find((entry) => entry.id === 'libtmux:session/function')!.signatures[0]! + expect(signature.params).toEqual([ + { name: 'required' }, + { name: 'limit', default: '10', optional: true }, + { name: 'values', variadic: 'positional' }, + { name: 'raw-p', default: 'nil', optional: true, keywordOnly: true }, + ]) + }) + + it('renders authored cross-package references as linked prose', () => { + const model = extractCommonLisp(fixture, revision) + const declaration = model.symbols.find((entry) => entry.id === 'libtmux.workspace:apply-workspace')! + const index = new SymbolIndex(model.symbols, (entry) => `/${entry.id}/`, 'lisp') + expect(declaration.doc?.body).toContain('See also: `libtmux.workspace:result-outcomes`') + expect(index.docSpans(declaration.doc!.body!, declaration)).toContainEqual(expect.objectContaining({ + kind: 'ref', link: expect.objectContaining({ href: '/libtmux.workspace:result-outcomes/' }), + })) + }) + + it('preserves native CLOS dispatch signatures and required parameter types', () => { + const input = structuredClone(fixture) + Object.assign(input.packages[0]!.symbols[0]!, { + generic: true, signature: '(session value &key raw)', + methods: [{ signature: '(session (value libtmux:session) &key (raw nil))', + qualifiers: [], specializers: ['libtmux:session/type'] }, + { signature: '(session :around (value libtmux:session) &key (raw nil))', + qualifiers: [':around'], specializers: ['libtmux:session/type'] }], + }) + const declaration = extractCommonLisp(input, revision).symbols + .find((entry) => entry.id === 'libtmux:session/function')! + expect(declaration.signatures).toHaveLength(3) + expect(declaration.signatures[1]).toMatchObject({ + raw: '(session (value libtmux:session) &key (raw nil))', methodKind: 'function', + params: [{ name: 'value', type: 'libtmux:session' }, + { name: 'raw', default: 'nil', optional: true, keywordOnly: true }], + }) + expect(declaration.signatures[1]!.identity).toContain('libtmux:session/type') + expect(declaration.signatures[2]!.params).toEqual(declaration.signatures[1]!.params) + expect(declaration.signatures[2]!.identity).not.toBe(declaration.signatures[1]!.identity) + expect(declaration.signatures[2]!.label).toBe(':around method: libtmux:session') + const index = new SymbolIndex(extractCommonLisp(input, revision).symbols, (entry) => `/${entry.id}/`, 'lisp') + const spans = index.linkType(declaration.signatures[2]!.raw!, declaration, declaration.signatures[2]) + expect(spans.filter((span) => span.link).map((span) => [span.text, span.link!.symbol?.id])) + .toEqual([['libtmux:session', 'libtmux:session/type']]) + }) + + it('links whole Lisp type names without linking lexical bindings or string defaults', () => { + const model = extractCommonLisp(fixture, revision) + for (const name of ['window', 'window-link']) model.symbols.push({ + id: `libtmux:${name}`, name, kind: 'class', modifiers: [], signatures: [], + namespace: 'libtmux', qualifiedName: `libtmux:${name}`, source: { file: 'src/model.lisp' }, + }) + const index = new SymbolIndex(model.symbols, (entry) => `/${entry.id}/`, 'lisp') + const signature = { raw: '(window-links (session libtmux:window-link) &key (label "libtmux:window"))', + params: [{ name: 'session', type: 'libtmux:window-link' }, + { name: 'label', default: '"libtmux:window"', optional: true, keywordOnly: true }] } + const declaration = { ...model.symbols[1]!, name: 'window-links', signatures: [signature] } + const spans = index.linkType(signature.raw, declaration, signature) + expect(spans.map((span) => span.text).join('')).toBe(signature.raw) + expect(spans.filter((span) => span.link).map((span) => [span.text, span.link!.symbol?.id])) + .toEqual([['libtmux:window-link', 'libtmux:window-link']]) + expect(index.linkType('libtmux:window-link').filter((span) => span.link)) + .toMatchObject([{ text: 'libtmux:window-link', link: { symbol: { id: 'libtmux:window-link' } } }]) + }) + + it('preserves required macro destructuring without inventing defaults', () => { + const input = structuredClone(fixture) + const declaration = input.packages[0]!.symbols[0]! + declaration.signature = '(with-client (name &rest options) &body body)' + const params = () => extractCommonLisp(input, revision).symbols + .find((entry) => entry.id === declaration.id)!.signatures[0]!.params + expect(params()).toEqual([ + { name: '(name &rest options)' }, + { name: 'body', variadic: 'positional' }, + ]) + }) + + it('retains printed string defaults, including empty strings and escapes', () => { + const input = structuredClone(fixture) + const declaration = input.packages[0]!.symbols[0]! + declaration.signature = '(open-client &key (program "tmux") (label "") (name "a\\\"b"))' + const params = extractCommonLisp(input, revision).symbols + .find((entry) => entry.id === declaration.id)!.signatures[0]!.params + expect(params).toEqual([ + { name: 'program', default: '"tmux"', optional: true, keywordOnly: true }, + { name: 'label', default: '""', optional: true, keywordOnly: true }, + { name: 'name', default: '"a\\\"b"', optional: true, keywordOnly: true }, + ]) + }) + + it.each([ + ['a dirty source', (input: typeof fixture) => { input.source.dirty = true }], + ['a dirty exporter', (input: typeof fixture) => { input.exporter.dirty = true }], + ['an unsupported schema', (input: typeof fixture) => { input.schema = 'libtmux.lisp.api/2' }], + ['a duplicate declaration', (input: typeof fixture) => { input.packages[0]!.symbols.push(input.packages[0]!.symbols[0]!) }], + ['a missing source line', (input: typeof fixture) => { input.packages[0]!.symbols[0]!.source.line = 0 }], + ['an unresolved cross-reference', (input: typeof fixture) => { input.packages[3]!.symbols[0]!.documentation.seeAlso = ['libtmux.workspace:missing'] }], + ['a generic without dispatch metadata', (input: typeof fixture) => { input.packages[0]!.symbols[0]!.generic = true }], + ['a private dispatch type', (input: typeof fixture) => { + Object.assign(input.packages[0]!.symbols[0]!, { generic: true, + methods: [{ signature: '(session (value private-class))', qualifiers: [], specializers: ['libtmux.internal:private-class'] }] }) + }], + ])('rejects %s', (_name, mutate) => { + const input = structuredClone(fixture) + mutate(input) + expect(() => extractCommonLisp(input, revision)).toThrow() + }) + + it('rejects an artifact exported from another checkout', () => { + expect(() => extractCommonLisp(fixture, '2'.repeat(40))).toThrow('selected checkout') + }) +}) diff --git a/packages/api-model/test/member-order.test.ts b/packages/api-model/test/member-order.test.ts index c122fe44e..04d7b92f2 100644 --- a/packages/api-model/test/member-order.test.ts +++ b/packages/api-model/test/member-order.test.ts @@ -45,9 +45,15 @@ function violations(compare: Compare): string[] { for (const concept of LISTINGS) { const listing = byId.get(CONCEPTS[concept]!.symbols[port] ?? '') if (!listing?.parent) continue - const rank = [...children.get(listing.parent)!].sort(cmp) - .filter((member) => memberTier(member, signals) !== 'parent').indexOf(listing) - if (rank >= TOP) found.push(`${port}: ${concept} is #${rank + 1} on ${listing.parent}`) + const ordered = [...children.get(listing.parent)!].sort(cmp) + .filter((member) => memberTier(member, signals) !== 'parent') + // Erlang's snapshot module has three physical listings and one shared + // relationship traversal for both session windows and window panes. + const top = port === 'erlang' + ? Math.max(TOP, ordered.filter((member) => memberTier(member, signals) === 'listing').length) + : TOP + const rank = ordered.indexOf(listing) + if (rank >= top) found.push(`${port}: ${concept} is #${rank + 1} on ${listing.parent}`) } for (const [owner, members] of children) { const sorted = [...members].sort(cmp) @@ -78,6 +84,7 @@ d('member order', () => { const found = violations(alphabetical) expect(found.some((v) => /^py: list-sessions is #\d+ on libtmux\.server\.Server$/.test(v))).toBe(true) expect(found.some((v) => /^py: __\w+__ ranks above public members/.test(v))).toBe(true) + expect(found.some((v) => /^erlang: list-(sessions|windows|panes) is #/.test(v))).toBe(true) }) it.each(PORTS)('puts %s listings and queries before creation and utility methods', (port) => { @@ -87,8 +94,16 @@ d('member order', () => { const groups = symbols .filter((symbol) => ['Server', 'Session', 'Window', 'Pane', 'Client', 'Snapshot'].includes(symbol.name)) .map((owner) => ({ id: owner.id, members: symbols.filter((symbol) => symbol.parent === owner.id) })) - // Cmdlets belong to their module; Julia's operations are free functions. + // Cmdlets and Common Lisp generic functions belong to their modules; + // Julia's operations are free functions. + // Erlang functions belong to native modules, not entity classes. + if (port === 'erlang') groups.push(...symbols.filter((owner) => owner.kind === 'module') + .map((owner) => ({ id: owner.id, members: symbols.filter((symbol) => symbol.parent === owner.id) }))) if (port === 'powershell') groups.push({ id: 'LibTmux', members: symbols.filter((symbol) => symbol.parent === 'LibTmux') }) + if (port === 'clojure') for (const id of ['libtmux.core', 'libtmux.data']) { + groups.push({ id, members: symbols.filter((symbol) => symbol.parent === id) }) + } + if (port === 'lisp') groups.push({ id: 'libtmux', members: symbols.filter((symbol) => symbol.parent === 'libtmux') }) if (port === 'julia') groups.push({ id: 'LibTmux free functions', members: symbols.filter((symbol) => !symbol.parent && symbol.kind === 'function' && symbol.id.startsWith('LibTmux.')), @@ -97,11 +112,11 @@ d('member order', () => { for (const { id, members } of groups) { const ordered = members.toSorted(compareMembers(signals)) const routine = members.filter((symbol) => ['New-TmuxSession', 'New-TmuxWindow', 'Remove-TmuxServer', 'Disconnect-TmuxControl', 'Base.close'].includes(symbol.name) || - /^(new_?session|new_?window|create_?session|create_?window|close|dispose|asjava|tostring|__enter__|kill_?server)$/.test( - symbol.name.replace(/\(.*$/, '').replace(/Async$/, '').toLowerCase())) + /^(new[-_]?session|new[-_]?window|create[-_]?session|create[-_]?window|close|dispose|asjava|tostring|__enter__|kill[-_]?server)$/.test( + symbol.name.replace(/\(.*$/, '').replace(/\/\d+$/, '').replace(/Async$/, '').replace(/[-!?]/g, '').toLowerCase())) const priority = members.filter((symbol) => symbol.doc?.deprecated === undefined && !symbol.modifiers?.includes('deprecated') && ( listingIds.has(symbol.publicId ?? symbol.id) || - /^(?:list_?|get)?(?:sessions|windows|panes|clients|buffers)$/.test(symbol.name.replace(/\(.*$/, '').replace(/Async$/, '').toLowerCase()) || + /^(?:list_?|get)?(?:sessions|windows|panes|clients|buffers)$/.test(symbol.name.replace(/\(.*$/, '').replace(/\/\d+$/, '').replace(/Async$/, '').replace(/[!?]$/, '').toLowerCase()) || /^(search-|snapshot$)/.test(signals.conceptIds.get(symbol.publicId ?? symbol.id) ?? ''))) for (const listing of priority) for (const helper of routine) { expect(ordered.indexOf(listing), `${id}: ${listing.name} before ${helper.name}`).toBeLessThan(ordered.indexOf(helper)) @@ -113,7 +128,11 @@ d('member order', () => { checked++ } } - expect(checked, `${port} must exercise at least one real listing or query`).toBeGreaterThan(0) + if (port === 'haskell') { + // The current public modules contain scalar values, with no entity graph or listing API. + expect(groups).toEqual([]) + expect([...listingIds].filter(Boolean)).toEqual([]) + } else expect(checked, `${port} must exercise at least one real listing or query`).toBeGreaterThan(0) }) it('leads a Lua Server, which has no sessions accessor, with its queries', () => { @@ -164,7 +183,8 @@ d('member order', () => { const parents = symbols.filter((symbol) => memberTier(symbol, signals) === 'parent') // F#/PowerShell use .NET handles; Julia's and Elixir's relationships are // read from a captured snapshot, not through accessors on an entity. - expect(parents.length > 0).toBe(!['fsharp', 'powershell', 'julia', 'elixir'].includes(port)) + // Haskell currently exposes scalar values without a public entity graph. + expect(parents.length > 0).toBe(!['fsharp', 'powershell', 'julia', 'elixir', 'erlang', 'haskell', 'clojure', 'lisp'].includes(port)) for (const parent of parents) { const siblings = symbols.filter((symbol) => symbol.parent === parent.parent).toSorted(compareMembers(signals)) for (const sibling of siblings.filter((symbol) => memberTier(symbol, signals) !== 'parent')) { @@ -231,6 +251,18 @@ d('member order', () => { } }) + it('leads the Erlang snapshot module with its physical listings and relationship traversal', () => { + const api = model('erlang') + const owner = api.symbols.find((symbol) => symbol.id === 'tmux_snapshot')! + expect(owner.kind).toBe('module') + const first = membersOf(api, owner).slice(0, 4) + expect(first.map((symbol) => symbol.name)).toEqual(['sessions/1', 'windows/1', 'panes/1', 'related/3']) + for (const symbol of first) { + expect(symbol.kind).toBe('function') + expect(symbol.parent).toBe(owner.id) + } + }) + it('does not promote scalar names, query fields, downward lookups, private or deprecated parents', () => { for (const [port, id] of [ ['go', 'tmux.Client.Session'], ['go', 'tmux.Pane.SessionID'], diff --git a/packages/api-model/test/mentions.test.ts b/packages/api-model/test/mentions.test.ts index ac7462dde..1b3b035ec 100644 --- a/packages/api-model/test/mentions.test.ts +++ b/packages/api-model/test/mentions.test.ts @@ -1,7 +1,7 @@ import { describe, expect, it } from 'vitest' import type { ApiModel } from '../src/model.ts' import { LinkedOwners, pageMentions, proseMentions, type LinkedOwner } from '../src/mentions.ts' -import { Resolver } from '../src/resolver.ts' +import { Resolver, notASymbol } from '../src/resolver.ts' import { parentInventory } from '../src/parent-inventory.ts' import { isLikelyReference, notApiInContext, notApiReason } from '../src/prose.ts' @@ -89,6 +89,17 @@ describe('prose mentions', () => { }) describe('spans that are code but not API', () => { + it('recognizes filenames and explicit data syntax without hiding qualified API names', () => { + for (const text of ['tmux.conf', 'tmux.sock', 'llms.txt', 'dist/libtmux-source.tar.gz', 'libtmux.asd', 'src/query.lisp']) { + expect(notASymbol(text), text).toBe('a filename') + } + for (const text of ['capture:0.0', '=work:editor', 'LC_ALL=C.UTF-8', 'libtmux.lisp.filter/1', '#()', '@[A-Za-z0-9_.-]+']) { + expect(notASymbol(text, 'lisp'), text).toBeTruthy() + } + for (const text of ['Nope.thing()', 'libtmux:fetch-snapshot', 'libtmux.query:compile-filter']) { + expect(notASymbol(text, 'lisp'), text).toBeUndefined() + } + }) it('names tmux releases and variable expressions, which otherwise read as references', () => { for (const text of ['3.3a', '3.8-rc2', '3.3a-rc', 'next-3.9', 'next-3.3a']) { expect(isLikelyReference(text), text).toBe(true) @@ -142,6 +153,8 @@ describe('a span its sentence says is not API', () => { it('reports the same spellings when the sentence says nothing of the kind', () => { expect(dangling('Type `Enter` to continue.')).toEqual(['Enter']) + expect(dangling('Use `send-keys` through `MissingApi`.')).toEqual(['MissingApi']) + expect(dangling('The screen contains `MissingApi()`.')).toEqual(['MissingApi()']) expect(dangling('The refusal is in `error.message`.')).toEqual(['error.message']) }) diff --git a/packages/api-model/test/nav-sidecar.test.ts b/packages/api-model/test/nav-sidecar.test.ts index 34151cac6..274b3826a 100644 --- a/packages/api-model/test/nav-sidecar.test.ts +++ b/packages/api-model/test/nav-sidecar.test.ts @@ -94,3 +94,65 @@ describe('existing port sidecars', () => { expect(`${JSON.stringify(navSidecar(port, model))}\n`).toBe(expected) }) }) + +describe('native export groups', () => { + const fixture = (): ApiModel => ({ + port: 'haskell', extractor: 'fixture', + exportGroups: [ + { owner: 'Module.Z', title: 'Types', members: ['Module.Z#t:Value'] }, + { owner: 'Module.Z', title: 'Read values', members: ['Module.Z#v:z', 'Module.Z#v:a'] }, + { owner: 'Module.A', title: 'Types', members: ['Module.A#t:Other'] }, + ], + symbols: [ + symbol('Module.Z', 'module'), symbol('Module.A', 'module'), + symbol('Module.Z#v:a', 'function', 'Module.Z'), + symbol('Module.Z#v:z', 'function', 'Module.Z'), + symbol('Module.Z#t:Value', 'typealias', 'Module.Z'), + symbol('Module.Z#v:Value', 'function', 'Module.Z#t:Value'), + symbol('Module.A#t:Other', 'typealias', 'Module.A'), + ].map((entry) => ({ ...entry, apiScope: 'exported' })), + }) + + it('preserves native module, group and declaration order without reparenting', () => { + const model = fixture() + const before = structuredClone(model) + const actual = navSidecar('haskell', model)! + expect(actual.buckets.map((bucket) => bucket.label)).toEqual(['Module.Z', 'Module.A']) + const [first, second] = actual.buckets + expect(first.children?.map((bucket) => bucket.label)).toEqual(['Types', 'Read values']) + expect(first.children![0].id).not.toBe(second.children![0].id) + expect(actual.assignments[first.children![1].id].map((entry) => entry.id)).toEqual(['Module.Z#v:z', 'Module.Z#v:a']) + expect(actual.assignments[first.id].map((entry) => entry.id)).toEqual(['Module.Z']) + expect(actual.placement).not.toHaveProperty('Module.Z#v:Value') + expect(actual.diagnostics).toEqual({ unmatched: [], deadBuckets: [], ambiguous: [], staleUnsettled: [] }) + expect(navSidecar('haskell', structuredClone(model))).toEqual(actual) + expect(model).toEqual(before) + }) + + it('excludes nonpublic declarations that are absent from the native export groups', () => { + const model = fixture() + model.symbols.push(symbol('private', 'function', 'Module.Z'), symbol('private.module', 'module')) + const actual = navSidecar('haskell', model)! + expect(actual.placement).not.toHaveProperty('private') + expect(actual.placement).not.toHaveProperty('private.module') + expect(actual.diagnostics.unmatched).toEqual([]) + }) + + it.each([ + ['missing direct declaration', (model: ApiModel) => model.exportGroups![1].members.pop()], + ['duplicate declaration', (model: ApiModel) => model.exportGroups![1].members.push('Module.Z#v:z')], + ['duplicate symbol identity', (model: ApiModel) => { model.symbols.push({ ...model.symbols[2] }) }], + ['unknown declaration', (model: ApiModel) => model.exportGroups![1].members.push('missing')], + ['nested constructor', (model: ApiModel) => model.exportGroups![0].members.push('Module.Z#v:Value')], + ['wrong owner', (model: ApiModel) => { model.exportGroups![0].owner = 'Module.A' }], + ['nonpublic declaration', (model: ApiModel) => { model.symbols[2].apiScope = 'internal' }], + ['ungrouped module', (model: ApiModel) => { model.exportGroups!.pop() }], + ['malformed group', (model: ApiModel) => { Object.assign(model.exportGroups!, { 0: null }) }], + ['no groups', (model: ApiModel) => { model.exportGroups = [] }], + ['no metadata', (model: ApiModel) => { delete model.exportGroups }], + ])('rejects %s before filtering navigation candidates', (_name, mutate) => { + const model = fixture() + mutate(model) + expect(() => navSidecar('haskell', model)).toThrow(/export group/i) + }) +}) diff --git a/packages/api-model/test/perl.test.ts b/packages/api-model/test/perl.test.ts new file mode 100644 index 000000000..f11491803 --- /dev/null +++ b/packages/api-model/test/perl.test.ts @@ -0,0 +1,98 @@ +import { describe, expect, it } from 'vitest' +import { SymbolIndex } from '../src/link.ts' +import { extractPerlArtifact } from '../src/languages/perl.ts' +import type { DocBlock } from '../src/model.ts' + +const revision = 'a'.repeat(40) +const source = { file: 'packages/core/lib/LibTmux/Selection.pm', line: 1, revision, repo: 'libtmux/libtmux-perl' } +const artifact = () => ({ + schema: 'libtmux.perl-api/v1', port: 'perl', repo: 'libtmux/libtmux-perl', revision, + nativeProvenance: { files: [{ path: source.file, sha256: 'b'.repeat(64) }], exporter: { repository: 'libtmux/libtmux-perl', revision: 'c'.repeat(40), working_tree: false } }, + sources: [{ package: 'LibTmux', product: 'core', revision, version: '0.001_001' }], + symbols: [ + { id: 'LibTmux::Selection', publicId: 'LibTmux::Selection', name: 'Selection', kind: 'class', modifiers: [], signatures: [], doc: { summary: 'Selection.' } as DocBlock, package: 'LibTmux', product: 'core', apiScope: 'exported', source }, + { id: 'LibTmux::Selection::grep', publicId: 'LibTmux::Selection::grep', name: 'grep', parent: 'LibTmux::Selection', kind: 'method', modifiers: [], signatures: [{ raw: 'sub grep($self, $callback)', receiver: { name: 'self' }, params: [{ name: 'callback' }] }], doc: { summary: 'See [Selection](pod:LibTmux::Selection).' }, package: 'LibTmux', product: 'core', apiScope: 'exported', source }, + ], +}) +describe('native Perl POD and signatures', () => { + it('links encoded and legacy POD sections to their exact rendered owner', () => { + for (const [section, component] of [ + ['VERIFICATION REPORT', 'VERIFICATION%20REPORT'], + ['État 100% / #', '%C3%89tat%20100%25%20%2F%20%23'], + ['REPORT )', 'REPORT%20%29'], + ]) { + for (const target of [component, ...(section === 'REPORT )' ? [] : [section])]) { + const input = artifact() + input.symbols[0].doc = { summary: 'Selection.', body: `## ${section}\n\nReport fields.` } + input.symbols[1].doc = { summary: `[report](pod:LibTmux::Selection/${target})` } + const model = extractPerlArtifact(input) + const index = new SymbolIndex(model.symbols, (symbol) => `/${symbol.id}/#declaration`, 'perl') + const spans = index.docSpans(model.symbols[1].doc!.summary, model.symbols[1]) + expect(spans).toContainEqual(expect.objectContaining({ kind: 'ref', link: expect.objectContaining({ + href: `/LibTmux::Selection/#${encodeURIComponent(`LibTmux::Selection.section.${component}`)}`, + }) })) + } + } + }) + it('rejects unknown, ambiguous, fenced and malformed POD section targets', () => { + for (const body of ['## OTHER\nText.', '## REPORT\nOne.\n## REPORT\nTwo.', '```perl\n## REPORT\n```']) { + const input = artifact() + input.symbols[0].doc = { summary: 'Selection.', body } + input.symbols[1].doc = { summary: '[report](pod:LibTmux::Selection/REPORT)' } + expect(() => extractPerlArtifact(input)).toThrow(/(?:Unresolved|Ambiguous) authored Perl POD target/) + } + const input = artifact() + input.symbols[1].doc = { summary: '[report](pod:LibTmux::Selection/%ZZ)' } + expect(() => extractPerlArtifact(input)).toThrow(/Malformed authored Perl POD target/) + }) + it('preserves declared signatures and resolves authored links to exact owners', () => { + const model = extractPerlArtifact(artifact(), revision) + expect(model.symbols[1].signatures[0].raw).toBe('sub grep($self, $callback)') + expect(model.symbols[1].doc?.summary).toContain(':obj:`Selection `') + expect(model.nativeProvenance?.exporter.revision).toBe('c'.repeat(40)) + }) + it('renders normalized POD links in its declared Perl dialect', () => { + const input = artifact() + input.symbols[1].doc = { summary: '`new(config => $hashref)` copies a `libtmux.workspace/v1` record. Use [Selection](pod:LibTmux::Selection) with [Future](pod:Future).' } + const model = extractPerlArtifact(input, revision) + const index = new SymbolIndex(model.symbols, (symbol) => `/${symbol.id}/`, 'perl') + const spans = index.docSpans(model.symbols[1].doc!.summary, model.symbols[1]) + expect(spans).toContainEqual({ kind: 'code', text: 'new(config => $hashref)' }) + expect(spans).toContainEqual({ kind: 'code', text: 'libtmux.workspace/v1' }) + expect(spans).toContainEqual(expect.objectContaining({ kind: 'link', text: 'Future', href: 'https://metacpan.org/pod/Future' })) + expect(spans).toContainEqual(expect.objectContaining({ kind: 'ref', link: expect.objectContaining({ href: '/LibTmux::Selection/' }) })) + }) + it('resolves a shared POD section to its unique declared method owner', () => { + const input = artifact() + const owner = { ...input.symbols[0], id: 'LibTmux::Selection::Child', publicId: 'LibTmux::Selection::Child', name: 'Child' } + const method = { ...input.symbols[1], id: `${owner.id}::cause`, publicId: `${owner.id}::cause`, name: 'cause', parent: owner.id } + input.symbols.push(owner, method) + input.symbols[1].doc = { summary: 'Retain the [cause](pod:LibTmux::Selection/cause).' } + expect(extractPerlArtifact(input).symbols[1].doc?.summary).toContain(`:obj:\`cause <${method.id}>\``) + + const secondOwner = { ...owner, id: 'LibTmux::Selection::Second', publicId: 'LibTmux::Selection::Second', name: 'Second' } + input.symbols.push(secondOwner, { ...method, id: `${secondOwner.id}::cause`, publicId: `${secondOwner.id}::cause`, parent: secondOwner.id }) + expect(() => extractPerlArtifact(input)).toThrow(/Ambiguous authored Perl POD target/) + input.symbols.pop() + input.symbols.pop() + method.source = { ...source, file: 'packages/core/lib/LibTmux/Other.pm' } + input.nativeProvenance.files.push({ path: method.source.file, sha256: 'd'.repeat(64) }) + expect(() => extractPerlArtifact(input)).toThrow(/Unresolved authored Perl POD target/) + }) + it('keeps public codec exceptions while excluding the private codec module', () => { + const input = artifact() + input.symbols.push({ ...input.symbols[0], id: 'LibTmux::X::Codec', publicId: 'LibTmux::X::Codec', name: 'Codec', kind: 'exception' }) + expect(extractPerlArtifact(input, revision).symbols.some(({ id }) => id === 'LibTmux::X::Codec')).toBe(true) + input.symbols.push({ ...input.symbols[0], id: 'LibTmux::Codec', publicId: 'LibTmux::Codec', name: 'Codec' }) + expect(() => extractPerlArtifact(input, revision)).toThrow(/public/) + }) + it('rejects stale/dirty identities and private or unresolved public targets', () => { + expect(() => extractPerlArtifact(artifact(), 'd'.repeat(40))).toThrow(/revision/) + const dirty = artifact(); dirty.nativeProvenance.exporter.working_tree = true + expect(() => extractPerlArtifact(dirty, revision)).toThrow(/committed/) + const broken = artifact(); broken.symbols[1].doc = { summary: '[Missing](pod:LibTmux::Missing)' } + expect(() => extractPerlArtifact(broken, revision)).toThrow(/Unresolved/) + const privateApi = artifact(); privateApi.symbols[1].name = '_read' + expect(() => extractPerlArtifact(privateApi, revision)).toThrow(/public/) + }) +}) diff --git a/packages/api-model/test/prose-audit.outer.test.ts b/packages/api-model/test/prose-audit.outer.test.ts new file mode 100644 index 000000000..66ba065a2 --- /dev/null +++ b/packages/api-model/test/prose-audit.outer.test.ts @@ -0,0 +1,45 @@ +// Outer: the real CLI loads the complete prose corpus in subprocesses. +import { spawnSync } from 'node:child_process' +import { mkdtempSync, rmSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { fileURLToPath } from 'node:url' +import { describe, expect, it } from 'vitest' + +const root = fileURLToPath(new URL('../../../', import.meta.url)) +const audit = (...args: string[]) => spawnSync(process.execPath, ['scripts/check-api-links.mjs', ...args, '--json'], { cwd: root, encoding: 'utf8' }) + +describe('product prose audit', () => { + it('audits native commands and dependency types without accepting invented commands', () => { + const scratch = mkdtempSync(join(tmpdir(), 'libtmux-powershell-audit-')) + const file = join(scratch, 'topic.md') + try { + writeFileSync(file, '---\ntitle: Snapshot\nport: powershell\n---\n\nUse `Get-TmuxSnapshot` with `LibTmux.Server`.\n') + expect(audit(file).status).toBe(0) + writeFileSync(file, '---\ntitle: Snapshot\nport: powershell\n---\n\nUse `Invent-TmuxSnapshot`.\n') + const result = audit(file) + expect(result.status).toBe(1) + expect(JSON.parse(result.stdout).unresolved.map((entry: { text: string }) => entry.text)).toEqual(['Invent-TmuxSnapshot']) + } finally { + rmSync(scratch, { recursive: true }) + } + }) + + it('checks the product collection by default', () => { + const result = audit() + expect(JSON.parse(result.stdout).pages).toContain('ports/ts/mcp/index.md') + }) + + it('does not let another language satisfy an authored port reference', () => { + const scratch = mkdtempSync(join(tmpdir(), 'libtmux-prose-audit-')) + const file = join(scratch, 'topic.md') + try { + writeFileSync(file, '---\ntitle: Capture\nport: ts\nproduct: mcp\n---\n\nUse `capture_pane()` for output.\n') + const result = audit(file) + expect(result.status).toBe(1) + expect(JSON.parse(result.stdout).unresolved.map((entry: { text: string }) => entry.text)).toEqual(['capture_pane()']) + } finally { + rmSync(scratch, { recursive: true }) + } + }) +}) diff --git a/packages/api-model/test/prose-audit.test.ts b/packages/api-model/test/prose-audit.test.ts index 91647e4ac..c3083ace5 100644 --- a/packages/api-model/test/prose-audit.test.ts +++ b/packages/api-model/test/prose-audit.test.ts @@ -1,8 +1,6 @@ -import { spawnSync } from 'node:child_process' import { mkdtempSync, rmSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' -import { fileURLToPath } from 'node:url' import { describe, expect, it } from 'vitest' import type { ApiModel, ApiSymbol } from '../src/model.ts' import { Resolver, notASymbol } from '../src/resolver.ts' @@ -13,44 +11,6 @@ import { builtinHref } from '../src/builtins.ts' import { extractWithSpec } from '../src/languages/spec.ts' import { GO } from '../src/languages/specs.ts' -const root = fileURLToPath(new URL('../../../', import.meta.url)) -const audit = (...args: string[]) => spawnSync(process.execPath, ['scripts/check-api-links.mjs', ...args, '--json'], { cwd: root, encoding: 'utf8' }) - -describe('product prose audit', () => { - it('audits native commands and dependency types without accepting invented commands', () => { - const scratch = mkdtempSync(join(tmpdir(), 'libtmux-powershell-audit-')) - const file = join(scratch, 'topic.md') - try { - writeFileSync(file, '---\ntitle: Snapshot\nport: powershell\n---\n\nUse `Get-TmuxSnapshot` with `LibTmux.Server`.\n') - expect(audit(file).status).toBe(0) - writeFileSync(file, '---\ntitle: Snapshot\nport: powershell\n---\n\nUse `Invent-TmuxSnapshot`.\n') - const result = audit(file) - expect(result.status).toBe(1) - expect(JSON.parse(result.stdout).unresolved.map((entry: { text: string }) => entry.text)).toEqual(['Invent-TmuxSnapshot']) - } finally { - rmSync(scratch, { recursive: true }) - } - }) - - it('checks the product collection by default', () => { - const result = audit() - expect(JSON.parse(result.stdout).pages).toContain('ports/ts/mcp/index.md') - }) - - it('does not let another language satisfy an authored port reference', () => { - const scratch = mkdtempSync(join(tmpdir(), 'libtmux-prose-audit-')) - const file = join(scratch, 'topic.md') - try { - writeFileSync(file, '---\ntitle: Capture\nport: ts\nproduct: mcp\n---\n\nUse `capture_pane()` for output.\n') - const result = audit(file) - expect(result.status).toBe(1) - expect(JSON.parse(result.stdout).unresolved.map((entry: { text: string }) => entry.text)).toEqual(['capture_pane()']) - } finally { - rmSync(scratch, { recursive: true }) - } - }) -}) - describe('product context in prose', () => { const symbols = [ { id: 'tmux.Window', name: 'Window', kind: 'struct', product: 'core' }, @@ -120,6 +80,7 @@ describe('product context in prose', () => { expect(portFromSentence('Python\'s checked wait is ')).toBe('py') expect(portFromSentence('In C++20 and ')).toBe('cxx') expect(portFromSentence('Go has ')).toBe('go') + expect(portFromSentence('In Clojure, ')).toBe('clojure') // JavaScript is not Java, an algorithm is not Go, and a trust is not Rust. expect(portFromSentence('JavaScript has a ')).toBeUndefined() expect(portFromSentence('An algorithm going to Google uses a trust of ')).toBeUndefined() @@ -220,22 +181,23 @@ describe('product context in prose', () => { }) }) -describe('a Java-only libtmux symbol on a Kotlin or Scala page', () => { +describe('a Java-only libtmux symbol on a JVM facade page', () => { const symbol = (id: string, name: string) => ({ id, name, kind: 'class', signatures: [], source: { file: `${name}.java` } }) const kotlin = { port: 'kotlin', version: '0', symbols: [symbol('io.example.Snapshot', 'Snapshot')] } as unknown as ApiModel const scala = { port: 'scala', version: '0', symbols: [symbol('io.example.Snapshot', 'Snapshot')] } as unknown as ApiModel + const clojure = { port: 'clojure', version: '0', symbols: [symbol('io.example.Snapshot', 'Snapshot')] } as unknown as ApiModel const java = { port: 'java', version: '0', symbols: [symbol('io.example.PaneState', 'PaneState'), symbol('io.example.Snapshot', 'Snapshot')], } as unknown as ApiModel - const models = { kotlin, scala, java } + const models = { kotlin, scala, clojure, java } const jdk = ['Phaser', 'Flow', 'Vector'].map((name) => ({ name, uri: `java.base/java/util/concurrent/${name}.html`, type: 'std:label', priority: 1, dispname: '-' })) - /** The inventories a Kotlin or Scala build holds: the parent library the port wraps, and the JDK's. The site and the generators name the first differently. */ + /** The parent library and JDK inventories, under the names the site and generators use. */ const resolverNamed = (parent: string) => { - const resolver = new Resolver([kotlin, scala, java]) - resolver.addInventory(parent, '', parentInventory(java, (entry) => `/reference/java/${entry.name}/`), ['kotlin', 'scala']) - resolver.addInventory('Java SE', 'https://docs.oracle.com/en/java/javase/21/docs/api/', jdk, ['java', 'kotlin', 'scala']) + const resolver = new Resolver([kotlin, scala, clojure, java]) + resolver.addInventory(parent, '', parentInventory(java, (entry) => `/reference/java/${entry.name}/`), ['kotlin', 'scala', 'clojure']) + resolver.addInventory('Java SE', 'https://docs.oracle.com/en/java/javase/21/docs/api/', jdk, ['java', 'kotlin', 'scala', 'clojure']) return resolver } const builds = ['Library API', 'libtmux Java'] @@ -243,14 +205,14 @@ describe('a Java-only libtmux symbol on a Kotlin or Scala page', () => { describe.each(builds)('where the parent library\'s inventory is named %s', (parent) => { const resolver = resolverNamed(parent) - it.each(['kotlin', 'scala'])('credits the symbol to Java when the %s sentence says Java: the page\'s port holds only an inventory entry for it', (pagePort) => { + it.each(['kotlin', 'scala', 'clojure'])('credits the symbol to Java when the %s sentence says Java: the page\'s port holds only an inventory entry for it', (pagePort) => { for (const before of ['returning the real Java ', 'Wraps Java\'s ']) { expect(decideMention('PaneState', { pagePort, before }, resolver, models), before) .toMatchObject({ kind: 'link', port: 'java', external: false }) } }) - it.each(['kotlin', 'scala'])('records the Java symbol as the %s page\'s backlink, and records nothing for a name Java lacks', (authoredPort) => { + it.each(['kotlin', 'scala', 'clojure'])('records the Java symbol as the %s page\'s backlink, and records nothing for a name Java lacks', (authoredPort) => { const mentioned = (body: string) => pageMentions({ body, portByLabel: {}, page: `/${authoredPort}/latest/guides/state/`, authoredPort, nativeTmux: false, resolver, models, authoredTarget: () => undefined, }).targets @@ -258,10 +220,11 @@ describe('a Java-only libtmux symbol on a Kotlin or Scala page', () => { expect(mentioned('Each call returns the real Java `Missing` for the pane.\n')).toEqual([]) }) - it.each(['kotlin', 'scala'])('leaves the %s page its own symbols and curated names, and sends the JDK\'s names to Java', (pagePort) => { + it.each(['kotlin', 'scala', 'clojure'])('leaves the %s page its own symbols and curated names, and sends the JDK\'s names to Java', (pagePort) => { const said = { pagePort, before: 'the real Java ' } expect(decideMention('Snapshot', said, resolver, models)).toMatchObject({ kind: 'link', port: pagePort }) expect(decideMention('Phaser', said, resolver, models)).toMatchObject({ kind: 'link', port: 'java' }) + if (pagePort === 'clojure') return // A curated name written as a call is still the port's, where the JDK's inventory holds the same word. const curated = pagePort === 'kotlin' ? 'Flow' : 'Vector' expect(decideMention(`${curated}()`, said, resolver, models)).toMatchObject({ kind: 'link', port: pagePort, href: builtinHref(pagePort, curated) }) diff --git a/packages/api-model/test/python-docs.test.ts b/packages/api-model/test/python-docs.test.ts index 4610cc0d2..ea702e09c 100644 --- a/packages/api-model/test/python-docs.test.ts +++ b/packages/api-model/test/python-docs.test.ts @@ -3,7 +3,8 @@ import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { describe, expect, it } from 'vitest' -import { parsePythonDoc, pythonDocBody } from '../src/doc/python.ts' +import { pythonDocBody } from '../src/doc/python.ts' +import { parsePythonDoc } from '@libtmux/api-model/reference' import { docSummaryText, referencesIn, tokenizeDoc } from '../src/doc/roles.ts' import { extractPython } from '../src/languages/python.ts' import { readInventory } from '../src/inventory.ts' diff --git a/packages/api-model/test/resolver-corpus.outer.test.ts b/packages/api-model/test/resolver-corpus.outer.test.ts new file mode 100644 index 000000000..cf3962a1d --- /dev/null +++ b/packages/api-model/test/resolver-corpus.outer.test.ts @@ -0,0 +1,50 @@ +// Outer: audit the source documentation corpus against all registered port models. +import { existsSync, readFileSync, readdirSync } from 'node:fs' +import { dirname, join, relative } from 'node:path' +import { fileURLToPath } from 'node:url' +import { it, expect } from 'vitest' +import { API_MODEL_PORTS } from '../../../site/src/lib/ports.ts' +import { Resolver } from '../src/resolver.ts' +import { readInventory } from '../src/inventory.ts' +import { proseMentions } from '../src/mentions.ts' +import { portFromSentence } from '../src/prose.ts' +import type { ApiModel } from '../src/model.ts' +const here = dirname(fileURLToPath(import.meta.url)) +const DATA = join(here, '../../../site/src/data/api') +const PORTS = API_MODEL_PORTS.map((port) => port.slug) +const r = new Resolver(PORTS.map((port) => JSON.parse(readFileSync(join(DATA, `${port}.json`), 'utf8')) as ApiModel)) +const inventory = join(here, '../../../site/src/data/inventories/python.inv') +if (existsSync(inventory)) r.addInventory('Python', 'https://docs.python.org/3/', readInventory(readFileSync(inventory)).entries) + +it('resolves most unlinked references in the real corpus', () => { + const LABEL: Record = { + Python: 'py', Ruby: 'ruby', Lua: 'lua', TypeScript: 'ts', Rust: 'rs', Go: 'go', + ...Object.fromEntries(API_MODEL_PORTS.map((port) => [port.language, port.slug])), '.NET': 'csharp', + } + const docs = join(here, '../../../site/src/content/docs') + const walk = (dir: string): string[] => + readdirSync(dir, { withFileTypes: true }).flatMap((e) => + e.isDirectory() ? walk(join(dir, e.name)) : e.name.endsWith('.md') ? [join(dir, e.name)] : []) + let linkable = 0 + let resolved = 0 + for (const f of walk(docs)) { + const [area, port] = relative(docs, f).replace(/^_staged[\\/]/, '').split(/[\\/]/) + const owner = ['ports', '_staged'].includes(area) && PORTS.some((entry) => entry === port) ? port : undefined + for (const mention of proseMentions(readFileSync(f, 'utf8'), LABEL, () => owner)) { + // Authored links already select a destination, which may be a protocol + // object or external API. The name resolver does not own those labels. + if (mention.linked) continue + const { text, before } = mention + const port = portFromSentence(before) ?? mention.port + if (!port) continue + if (!/^[A-Za-z_.][\w.]*(\s*\(|\.)/.test(text) && !/\(\)$/.test(text)) continue + const res = r.resolve(port, text) + if (res.how === 'not-a-symbol') continue + linkable++ + if (!['ambiguous', 'no-symbol'].includes(res.how)) resolved++ + } + } + expect(linkable).toBeGreaterThan(200) + // Floor, not a pin. 87% at the time of writing. + expect(resolved / linkable).toBeGreaterThan(0.8) + }) diff --git a/packages/api-model/test/resolver.test.ts b/packages/api-model/test/resolver.test.ts index 968b8d19a..e628e74ac 100644 --- a/packages/api-model/test/resolver.test.ts +++ b/packages/api-model/test/resolver.test.ts @@ -1,12 +1,10 @@ -import { existsSync, readFileSync, readdirSync } from 'node:fs' -import { homedir } from 'node:os' -import { dirname, join, relative } from 'node:path' +import { existsSync, readFileSync } from 'node:fs' +import { dirname, join } from 'node:path' import { fileURLToPath } from 'node:url' import { beforeAll, describe, expect, it } from 'vitest' import { readInventory } from '../src/inventory.ts' import type { ApiModel, ApiSymbol } from '../src/model.ts' import { Resolver, notASymbol, toPath } from '../src/resolver.ts' -import { proseMentions } from '../src/mentions.ts' import { portFromSentence } from '../src/prose.ts' /** @@ -94,6 +92,14 @@ d('resolver', () => { expect(notASymbol('pane.height')).toBeUndefined() }) + it('keeps OCaml filenames and numeric output labels out of API references', () => { + for (const text of ['main.ml', 'json/libtmux_json.mli', 'libtmux.opam']) expect(notASymbol(text), text).toBe('a filename') + for (const text of ['editor:2', 'logs:1']) expect(notASymbol(text), text).toBe('a numeric label') + for (const text of ['Seq.filter', 'Enum.map/2', 'LibTmux.Session.new_window/1', 'Server:new_session']) { + expect(notASymbol(text), text).toBeUndefined() + } + }) + it('preserves an exact Swift selector instead of resolving its same-named property', () => { for (const id of ['Snapshot.panes(of:)', 'Snapshot.panes']) { const result = r.resolve('swift', id) @@ -152,38 +158,7 @@ d('resolver', () => { expect('symbol' in rust ? rust.symbol.product : undefined).toBe('mcp') }) - it('resolves most unlinked references in the real corpus', () => { - const LABEL: Record = { - Python: 'py', Ruby: 'ruby', Lua: 'lua', TypeScript: 'ts', Rust: 'rs', Go: 'go', - Java: 'java', '.NET': 'csharp', 'C++': 'cxx', Swift: 'swift', - } - const docs = join(here, '../../../site/src/content/docs') - const walk = (dir: string): string[] => - readdirSync(dir, { withFileTypes: true }).flatMap((e) => - e.isDirectory() ? walk(join(dir, e.name)) : e.name.endsWith('.md') ? [join(dir, e.name)] : []) - let linkable = 0 - let resolved = 0 - for (const f of walk(docs)) { - const [area, port] = relative(docs, f).split(/[\\/]/) - const owner = ['ports', '_staged'].includes(area) && PORTS.some((entry) => entry === port) ? port : undefined - for (const mention of proseMentions(readFileSync(f, 'utf8'), LABEL, () => owner)) { - // Authored links already select a destination, which may be a protocol - // object or external API. The name resolver does not own those labels. - if (mention.linked) continue - const { text, before } = mention - const port = portFromSentence(before) ?? mention.port - if (!port) continue - if (!/^[A-Za-z_.][\w.]*(\s*\(|\.)/.test(text) && !/\(\)$/.test(text)) continue - const res = r.resolve(port, text) - if (res.how === 'not-a-symbol') continue - linkable++ - if (!['ambiguous', 'no-symbol'].includes(res.how)) resolved++ - } - } - expect(linkable).toBeGreaterThan(200) - // Floor, not a pin. 87% at the time of writing. - expect(resolved / linkable).toBeGreaterThan(0.8) - }) + }) describe('mention paths by port', () => { diff --git a/packages/api-model/test/test_haskell_export.py b/packages/api-model/test/test_haskell_export.py new file mode 100644 index 000000000..7142fb8ec --- /dev/null +++ b/packages/api-model/test/test_haskell_export.py @@ -0,0 +1,348 @@ +"""Native public declarations must survive the shared-site export boundary.""" + +from __future__ import annotations + +import importlib.util +import json +import subprocess +import tempfile +import unittest +from pathlib import Path +from unittest.mock import patch + +ROOT = Path(__file__).resolve().parents[1] +SPEC = importlib.util.spec_from_file_location("haskell_export", ROOT / "scripts/export-haskell.py") +EXPORT = importlib.util.module_from_spec(SPEC) +SPEC.loader.exec_module(EXPORT) +FIXTURE = ROOT / "test/fixtures/haskell-native" +REVISION = "9fb506c96772affa6ea23bee41218cd41a931d51" + + +def _native_inputs(): + meta = json.loads((FIXTURE / "provenance.json").read_text()) + pages = { + name: (FIXTURE / (name.replace(".", "-") + ".html")).read_text() for name in meta["modules"] + } + return [ + pages, + json.loads((FIXTURE / "installed.json").read_text()), + meta["modules"], + json.loads((FIXTURE / "source-anchors.json").read_text()), + REVISION, + ] + + +def _artifact(): + return EXPORT.extract_modules(*_native_inputs()) + + +class _NativeExportTest(unittest.TestCase): + def test_exporter_identity_requires_the_exact_committed_bytes(self): + with tempfile.TemporaryDirectory(prefix="libtmux-haskell-exporter-test-") as directory: + root = Path(directory) + script = root / "export.py" + script.write_text("# exporter fixture\n") + subprocess.run(["git", "init", "--quiet", str(root)], check=True) + commit = [ + "git", + "-C", + str(root), + "-c", + "core.hooksPath=/dev/null", + "-c", + "commit.gpgsign=false", + "-c", + "user.name=Fixture", + "-c", + "user.email=fixture@example.invalid", + "commit", + "--quiet", + "--allow-empty", + ] + subprocess.run([*commit, "-m", "fixture base"], check=True) + with patch.object(EXPORT, "__file__", str(script)): + with self.assertRaisesRegex(ValueError, "Commit the reviewed exporter"): + EXPORT._exporter_identity() + subprocess.run(["git", "-C", str(root), "add", "export.py"], check=True) + subprocess.run([*commit, "-m", "fixture exporter"], check=True) + identity = EXPORT._exporter_identity() + self.assertEqual(identity["path"], "export.py") + self.assertRegex(identity["revision"], r"^[a-f0-9]{40}$") + self.assertRegex(identity["sha256"], r"^[a-f0-9]{64}$") + script.write_text("# changed exporter fixture\n") + with self.assertRaisesRegex(ValueError, "bytes differ"): + EXPORT._exporter_identity() + + def test_unqualified_compilers_and_partial_source_refs_are_rejected(self): + with self.assertRaisesRegex(ValueError, "existing full commit"): + EXPORT.build_native(FIXTURE, "master") + + def old_toolchain(arguments, _cwd): + values = { + "ghc": "9.12.1", + "haddock": "Haddock version 2.33.0, fixture", + "cabal": "3.18.2.0", + } + return subprocess.CompletedProcess(arguments, 0, values[Path(arguments[0]).name], "") + + with ( + patch.object(EXPORT.shutil, "which", side_effect=lambda name: "/fixture/bin/" + name), + patch.object(EXPORT, "_git", return_value=REVISION), + patch.object(EXPORT, "_command", side_effect=old_toolchain), + self.assertRaisesRegex(ValueError, "qualified GHC"), + ): + EXPORT.build_native(FIXTURE, REVISION) + + def test_unhandled_native_layouts_are_rejected_instead_of_dropped(self): + cases = [ + ( + "argument docs", + '

' + '

', + '

', + ), + ( + "orphan instances", + '
', + '

orphan contract

', + ), + ( + "ordered prose", + '

Distinct session', + '

  1. first
  2. second

Distinct session', + ), + ( + "definition prose", + '

Distinct session', + '

term
meaning

Distinct session', + ), + ( + "type equation", + 'data type ", 1) + original = 'href="LibTmux-Id.html#t:IdError"' + self.assertIn(original, header) + inputs[0]["LibTmux.Id"] = ( + before + marker + header.replace(original, f'href="{href}"', 1) + "

" + after + ) + with self.assertRaisesRegex( + ValueError, "no public target|Unsupported documentation link scheme" + ): + EXPORT.extract_modules(*inputs) + + def test_opaque_ids_do_not_reveal_their_newtype_constructor(self): + symbols = {s["id"]: s for s in _artifact()["symbols"]} + self.assertIn("LibTmux.Id#t:PaneId", symbols) + pane = symbols["LibTmux.Id#t:PaneId"] + self.assertEqual(pane["signatures"][0]["raw"], "data PaneId") + self.assertIn("opaque", pane["modifiers"]) + self.assertNotIn("LibTmux.Id#v:PaneId", symbols) + self.assertNotIn("Word32", pane["signatures"][0]["raw"]) + + def test_fields_keep_strict_types_without_inventing_selectors(self): + symbols = {s["id"]: s for s in _artifact()["symbols"]} + self.assertIn("LibTmux.Id#v:expectedPrefix", symbols) + field = symbols["LibTmux.Id#v:expectedPrefix"] + self.assertEqual(field["kind"], "property") + self.assertEqual(field["parent"], "LibTmux.Id#t:IdError") + self.assertEqual(field["signatures"][0]["raw"], "expectedPrefix :: !Char") + self.assertEqual(field["source"]["line"], 64) + self.assertIn("LibTmux.Id#v:InvalidId", symbols) + + def test_native_module_prose_groups_links_and_repl_examples_survive(self): + result = _artifact() + symbols = {s["id"]: s for s in result["symbols"]} + self.assertIn("LibTmux.Id", symbols) + module = symbols["LibTmux.Id"] + self.assertIn("Parsing and rendering are pure", module["doc"]["body"]) + self.assertIn("LibTmux.Id#v:parsePaneId", module["doc"]["body"]) + self.assertIn(">>> fmap renderWindowId", module["doc"]["body"]) + self.assertIn( + "Parse external values", [group["title"] for group in result["modules"][0]["groups"]] + ) + parser = symbols["LibTmux.Id#v:parsePaneId"] + self.assertEqual( + parser["signatures"][0]["raw"], "parsePaneId :: Text -> Either IdError PaneId" + ) + self.assertEqual(parser["source"]["revision"], REVISION) + + +if __name__ == "__main__": + unittest.main() diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 764501d53..512bee62a 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -201,6 +201,10 @@ patchedDependencies: importers: .: + dependencies: + badge-maker: + specifier: 6.0.0 + version: 6.0.0 devDependencies: '@biomejs/biome': specifier: 'catalog:' @@ -238,6 +242,9 @@ importers: smol-toml: specifier: 1.9.1 version: 1.9.1 + tree-sitter-haskell: + specifier: 0.23.1 + version: 0.23.1 tree-sitter-scala: specifier: 0.24.0 version: 0.24.0 @@ -1632,6 +1639,9 @@ packages: resolution: {integrity: sha512-KLcsDhqf1XRrJmJr+9I/C0EX2K+sGrAGZFgkmd84c8TJO9zJBu+/kFInjazu1KfJWFhWDKdRWkpBzEs7s35DVA==} hasBin: true + anafanafo@2.0.0: + resolution: {integrity: sha512-Nlfq7NC4AOkTJerWRIZcOAiMNtIDVIGWGvQ98O7Jl6Kr2Dk0dX5u4MqN778kSRTy5KRqchpLdF2RtLFEz9FVkQ==} + ansi-regex@6.4.0: resolution: {integrity: sha512-KzTVk2tCWAHtYrvvvaP8bJKJq2pVinhLcGEQdtLIYPbmNGNyYe8QwNaTUYQp2J7/vIsUKt5QCqAfUkYyG9DkOw==} engines: {node: '>=12'} @@ -1681,12 +1691,20 @@ packages: resolution: {integrity: sha512-qIj0G9wZbMGNLjLmg1PT6v2mE9AH2zlnADJD/2tC6E00hgmhUOfEB6greHPAfLRSufHqROIUTkw6E+M3lH0PTQ==} engines: {node: '>= 0.4'} + badge-maker@6.0.0: + resolution: {integrity: sha512-+P5EsfmFWAR2cA9M0q20pa4OVOgnOXZkfRYUkQYHanECXCIg10ZnSBzelfBtEjt03b4Vac/yC1h55/wJPLmaOg==} + engines: {node: '>=20'} + hasBin: true + bail@2.0.2: resolution: {integrity: sha512-0xO6mYd7JB2YesxDKplafRpsiOzPt9V02ddPCLbY1xYGPOX24NTyN50qnUxgCPcSoYMhKpAuBTjQoRZCAkUDRw==} bcp-47-match@2.0.3: resolution: {integrity: sha512-JtTezzbAibu8G0R9op9zb3vcWZd9JF6M0xOYGPn0fNCd7wOpRB1mU2mH9T8gaBGbAAyIIVgB2G7xG0GP98zMAQ==} + binary-search@1.3.6: + resolution: {integrity: sha512-nbE1WxOTTrUWIfsfZ4aHGYu5DOuNkbxGokjV6Z2kxfJK3uaAb8zNK1muzOeipoLHZjInT4Br88BHpzevc681xA==} + boolbase@1.0.0: resolution: {integrity: sha512-JZOSA7Mo9sNGB8+UjSgzdLtokWAky1zbztM3WRLCbZ70/3cTANmQmOdR7y2g+J0e2WXywy1yS468tY+IruqEww==} @@ -1701,6 +1719,9 @@ packages: resolution: {integrity: sha512-XWAtwJ6OHO+tj0EKCs0Y2UamnyOxseZWltU4x2U2wh8g4AigdjwvtUjvLP2tqkA/avxHEtzxNaqGq/YGNwckKg==} engines: {node: '>=18'} + char-width-table-consumer@1.0.0: + resolution: {integrity: sha512-Fz4UD0LBpxPgL9i29CJ5O4KANwaMnX/OhhbxzvNa332h+9+nRKyeuLw4wA51lt/ex67+/AdsoBQJF3kgX2feYQ==} + character-entities-html4@2.1.0: resolution: {integrity: sha512-1v7fgQRj6hnSwFpq1Eu0ynr/CDEw0rXo2B61qXrLNdHZmPKgb7fqS1a2JwF0rISo9q77jDI8VMEHoApn8qDoZA==} @@ -1738,6 +1759,12 @@ packages: collapse-white-space@2.1.0: resolution: {integrity: sha512-loKTxY1zCOuG4j9f6EPnuyyYkf58RnhhWTvRoZEokgB+WbdXehfjFviyOVYkqzEWz1Q5kRiZdBYS5SwxbQYwzw==} + color-convert@0.5.3: + resolution: {integrity: sha512-RwBeO/B/vZR3dfKL1ye/vx8MHZ40ugzpyfeVG5GsiuGnrlMWe2o8wxBbLCpw9CsxV+wHuzYlCiWnybrIA0ling==} + + color-name@1.1.4: + resolution: {integrity: sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==} + comma-separated-tokens@2.0.3: resolution: {integrity: sha512-Fu4hJdvzeylCfQPp9SGWidpzrMs7tTrlu6Vb8XGaRGck8QSNZJJp538Wrb60Lax4fPwR64ViY468OIUTbRlGZg==} @@ -1759,6 +1786,9 @@ packages: crossws@0.3.5: resolution: {integrity: sha512-ojKiDvcmByhwa8YYqbQI/hg7MEU0NC03+pSdEq4ZUnZR9xXpwk7E43SMNGkn+JxJGPFtNvQ48+vV2p+P1ml5PA==} + css-color-converter@2.0.0: + resolution: {integrity: sha512-oLIG2soZz3wcC3aAl/7Us5RS8Hvvc6I8G8LniF/qfMmrm7fIKQ8RIDDRZeKyGL2SrWfNqYspuLShbnjBMVWm8g==} + css-select@6.0.0: resolution: {integrity: sha512-rZZVSLle8v0+EY8QAkDWrKhpgt6SA5OtHsgBnsj6ZaLb5dmDVOWUDtQitd9ydxxvEjhewNudS6eTVU7uOyzvXw==} @@ -1773,6 +1803,9 @@ packages: resolution: {integrity: sha512-X7sjQzceUhu1u7Y/ylrRZFU2FS6LRiFVp6rKLPg23y3x3c3DOKAwuXGDp+PAGjh6CSnCjYeAul8pcT8bAl+lSA==} engines: {node: ^10 || ^12.20.0 || ^14.13.0 || >=15.0.0} + css-unit-converter@1.1.2: + resolution: {integrity: sha512-IiJwMC8rdZE0+xiEZHeru6YoONC4rfPMqGm2W85jMIbkFvv5nFTwJVFHam2eFrN6txmoUYFAFXiv8ICVeTO0MA==} + css-what@7.0.0: resolution: {integrity: sha512-wD5oz5xibMOPHzy13CyGmogB3phdvcDaB5t0W/Nr5Z2O/agcB8YwOz6e2Lsp10pNDzBoDO9nVa3RGs/2BttpHQ==} engines: {node: '>= 6'} @@ -2849,6 +2882,14 @@ packages: peerDependencies: tslib: '2' + tree-sitter-haskell@0.23.1: + resolution: {integrity: sha512-qG4CYhejveu9DLMLEGBz/n9/TTeGSFLC6wniwOgG6m8/v7Dng8qR0ob0EVG7+XH+9WiOxohpGA23EhceWuxY4w==} + peerDependencies: + tree-sitter: ^0.21.1 + peerDependenciesMeta: + tree-sitter: + optional: true + tree-sitter-scala@0.24.0: resolution: {integrity: sha512-vkMuAUrBZ1zZz2XcGDQk18Kz73JkpgaeXzbNVobPke0G35sd9jH32aUxG6OLRKM7et0TbsfqkWf4DeJoGk4K1g==} peerDependencies: @@ -4373,6 +4414,10 @@ snapshots: dependencies: process-ancestry: 0.1.0 + anafanafo@2.0.0: + dependencies: + char-width-table-consumer: 1.0.0 + ansi-regex@6.4.0: {} ansi-styles@6.2.3: {} @@ -4490,10 +4535,17 @@ snapshots: axobject-query@4.1.0: {} + badge-maker@6.0.0: + dependencies: + anafanafo: 2.0.0 + css-color-converter: 2.0.0 + bail@2.0.2: {} bcp-47-match@2.0.3: {} + binary-search@1.3.6: {} + boolbase@1.0.0: {} buffer-image-size@0.6.4: @@ -4504,6 +4556,10 @@ snapshots: chai@6.3.0: {} + char-width-table-consumer@1.0.0: + dependencies: + binary-search: 1.3.6 + character-entities-html4@2.1.0: {} character-entities-legacy@3.0.0: {} @@ -4534,6 +4590,10 @@ snapshots: collapse-white-space@2.1.0: {} + color-convert@0.5.3: {} + + color-name@1.1.4: {} + comma-separated-tokens@2.0.3: {} commander@11.1.0: {} @@ -4548,6 +4608,12 @@ snapshots: dependencies: uncrypto: 0.1.3 + css-color-converter@2.0.0: + dependencies: + color-convert: 0.5.3 + color-name: 1.1.4 + css-unit-converter: 1.1.2 + css-select@6.0.0: dependencies: boolbase: 1.0.0 @@ -4568,6 +4634,8 @@ snapshots: mdn-data: 2.27.1 source-map-js: 1.2.2 + css-unit-converter@1.1.2: {} + css-what@7.0.0: {} cssesc@3.0.0: {} @@ -6115,6 +6183,11 @@ snapshots: dependencies: tslib: 2.8.1 + tree-sitter-haskell@0.23.1: + dependencies: + node-addon-api: 8.9.2 + node-gyp-build: 4.8.4 + tree-sitter-scala@0.24.0: dependencies: node-addon-api: 8.9.2 diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml index 80e9cd717..82f441a01 100644 --- a/pnpm-workspace.yaml +++ b/pnpm-workspace.yaml @@ -20,6 +20,7 @@ allowBuilds: sharp: true # The extractor loads this package's prebuilt WASM grammar. tree-sitter-scala: false + tree-sitter-haskell: false minimumReleaseAge: 4320 minimumReleaseAgeStrict: false patchedDependencies: diff --git a/pyproject.toml b/pyproject.toml index c498c9d77..76019d4cd 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -30,7 +30,11 @@ exclude-newer = "3 days" [tool.ruff] target-version = "py312" line-length = 100 -include = ["scripts/**/*.py"] +include = [ + "scripts/**/*.py", + "packages/api-model/scripts/**/*.py", + "packages/api-model/test/test_*.py", +] extend-exclude = ["output"] [tool.ruff.lint] @@ -55,7 +59,7 @@ convention = "numpy" python-version = "3.12" [tool.ty.src] -include = ["scripts"] +include = ["scripts", "packages/api-model/scripts"] [tool.ty.terminal] error-on-warning = true diff --git a/scripts/build-site.sh b/scripts/build-site.sh index b970b1aec..fa3453403 100755 --- a/scripts/build-site.sh +++ b/scripts/build-site.sh @@ -303,10 +303,13 @@ if [ -n "${LIBTMUX_DOCS_PORT:-}" ] && { [ "$LIBTMUX_DOCS_PORT" = ruby ] || [ "$L node "$script_dir/gen-api-model.mjs" --port "$LIBTMUX_DOCS_PORT" node "$script_dir/stage-port-docs.mjs" --port "$LIBTMUX_DOCS_PORT" elif [ -n "${LIBTMUX_DOCS_SOURCE_SHA:-}" ] && { [ "$LIBTMUX_DOCS_PORT" = powershell ] || [ "$LIBTMUX_DOCS_PORT" = julia ] || - [ "$LIBTMUX_DOCS_PORT" = elixir ]; }; then + [ "$LIBTMUX_DOCS_PORT" = elixir ] || [ "$LIBTMUX_DOCS_PORT" = ocaml ] || [ "$LIBTMUX_DOCS_PORT" = haskell ] || [ "$LIBTMUX_DOCS_PORT" = perl ] || [ "$LIBTMUX_DOCS_PORT" = lisp ] || [ "$LIBTMUX_DOCS_PORT" = erlang ]; }; then node "$script_dir/gen-api-model.mjs" --port "$LIBTMUX_DOCS_PORT" node "$script_dir/stage-port-docs.mjs" --port "$LIBTMUX_DOCS_PORT" --from-source node "$script_dir/gen-api-model.mjs" --port "$LIBTMUX_DOCS_PORT" --nav + if [ "$LIBTMUX_DOCS_PORT" = haskell ]; then + node "$script_dir/gen-tmux-usage.mjs" --ports "$LIBTMUX_DOCS_PORT" --source + fi elif [ -n "${LIBTMUX_DOCS_SOURCE_SHA:-}" ] && node --input-type=module -e ' const { PORT_BY_SLUG } = await import("file://'"$site_dir"'/src/lib/ports.ts"); process.exit(PORT_BY_SLUG[process.env.LIBTMUX_DOCS_PORT]?.parentLibrary ? 0 : 1); @@ -320,12 +323,23 @@ elif [ -n "${LIBTMUX_DOCS_SOURCE_SHA:-}" ]; then node "$script_dir/gen-api-model.mjs" --port "$LIBTMUX_DOCS_PORT" node "$script_dir/gen-api-model.mjs" --port "$LIBTMUX_DOCS_PORT" --nav fi +if [ "${LIBTMUX_DOCS_PORT:-}" = perl ] && [ -n "${LIBTMUX_DOCS_SOURCE_SHA:-}" ]; then + node "$script_dir/gen-tmux-usage.mjs" --ports perl +fi node "$script_dir/stage-port-docs.mjs" --wrappers if [ -n "${LIBTMUX_DOCS_SOURCE_SHA:-}" ]; then + if [ "$LIBTMUX_DOCS_PORT" = clojure ]; then + node "$script_dir/gen-tmux-usage.mjs" --ports clojure + fi # The selected API and wire contracts must come from the same product source. # Python's MCP product has its own checkout and revision. - node "$script_dir/gen-mcp-protocol.mjs" --port "$LIBTMUX_DOCS_PORT" --source-bound - node "$script_dir/gen-mcp-tools.mjs" --port "$LIBTMUX_DOCS_PORT" --source-bound + if node --input-type=module -e ' + const { PORT_BY_SLUG } = await import("file://'"$site_dir"'/src/lib/ports.ts"); + process.exit(PORT_BY_SLUG[process.env.LIBTMUX_DOCS_PORT]?.productAvailability?.mcp === "excluded" ? 1 : 0); + '; then + node "$script_dir/gen-mcp-protocol.mjs" --port "$LIBTMUX_DOCS_PORT" --source-bound + node "$script_dir/gen-mcp-tools.mjs" --port "$LIBTMUX_DOCS_PORT" --source-bound + fi fi node "$script_dir/gen-example-sources.mjs" node "$script_dir/gen-mentions.mjs" diff --git a/scripts/check-api-links.mjs b/scripts/check-api-links.mjs index 6015c8b25..b8d123d11 100755 --- a/scripts/check-api-links.mjs +++ b/scripts/check-api-links.mjs @@ -19,7 +19,7 @@ import { existsSync, globSync, readdirSync, readFileSync, statSync } from 'node:fs' import { dirname, join, relative, resolve } from 'node:path' import { fileURLToPath } from 'node:url' -import { Resolver, parentInventory, decideFilePath, decideMention, isLikelyReference, looksLikeApiMention, notASymbol, notApiReason, proseMentions, readInventory } from '../packages/api-model/src/index.ts' +import { Resolver, parentInventory, decideFilePath, decideMention, isLikelyReference, looksLikeApiMention, notASymbol, notApiReason, portFromSentence, proseMentions, readInventory } from '../packages/api-model/src/index.ts' import { decideMcpMention } from '../site/src/lib/mcp-catalog.ts' import { isTmuxProse } from '../site/src/lib/docs-paths.ts' @@ -101,7 +101,7 @@ const EXCEPTIONS = new Map() } } -const FILE_RE = /^[\w./@-]+\.(py|ts|tsx|js|rs|go|java|cs|cpp|hpp|h|swift|jl|ex|exs|ps1|psm1|psd1|md|toml|json|ya?ml|sh)$/ +const FILE_RE = /^[\w./@-]+\.(py|ts|tsx|js|rs|go|java|cs|cpp|hpp|h|swift|jl|ex|exs|ps1|psm1|psd1|ml|mli|opam|lisp|asd|md|toml|json|ya?ml|sh)$/ const PORT_BY_LABEL = Object.fromEntries(PORT_DEFS.map((port) => [port.name, port.slug])) PORT_BY_LABEL['C#'] = 'csharp' @@ -198,7 +198,7 @@ for (const file of targets) { // exists to agree with the build; applying one fewer of them made it // report 124 where the build reported 61, which is the disagreement it // was written to prevent. - if (notASymbol(text) || !looksLikeApiMention(text)) { tally.notASymbol++; continue } + if (notASymbol(text, portFromSentence(before ?? '') ?? pagePort) || !looksLikeApiMention(text)) { tally.notASymbol++; continue } const decisions = (pagePort ? [pagePort] : PORTS) @@ -208,7 +208,7 @@ for (const file of targets) { // `TMUX_TMPDIR` that happens to resolve is a link worth having; it simply // is not a dangling reference when it does not. if (decisions.some((decision) => decision.kind === 'link')) tally.willLink++ - else if (decisions.some((decision) => decision.kind === 'skip') || !isLikelyReference(text) || notApiReason(text) || EXCEPTIONS.has(text)) tally.notASymbol++ + else if (decisions.some((decision) => decision.kind === 'skip') || !isLikelyReference(text) || notApiReason(text, portFromSentence(before ?? '') ?? pagePort) || EXCEPTIONS.has(text)) tally.notASymbol++ else { tally.unresolved++; unresolved.push({ file, line, text }) } } } diff --git a/scripts/check-example-blocks.mjs b/scripts/check-example-blocks.mjs index f9b62e617..4f36bfdc8 100644 --- a/scripts/check-example-blocks.mjs +++ b/scripts/check-example-blocks.mjs @@ -123,7 +123,7 @@ if (['--port', '--checkout', '--revision'].some((name) => process.argv.includes( } /** Ports whose example pages are built up from excerpts; add a port as its pages convert. */ -const BUILT_UP_PORTS = ['go'] +const BUILT_UP_PORTS = ['go', 'lisp'] const pages = [ ...markdownIn(join(CONTENT, 'examples')), diff --git a/scripts/check-example-prose.py b/scripts/check-example-prose.py index 575149c0a..a765de0b7 100755 --- a/scripts/check-example-prose.py +++ b/scripts/check-example-prose.py @@ -66,6 +66,22 @@ def stop_process_group(process): process.wait() +def homepage_execution(home, example): + """Require agreement on the explicit native example execution profile.""" + profile = home.get("execution", "owned-tmux") + if profile not in ("owned-tmux", "pure-values") or profile != example.get( + "execution", "owned-tmux" + ): + msg = "Homepage execution profile differs from the verification record" + raise ValueError(msg) + if home.get("libraryRevision", home["sourceRevision"]) != example.get( + "libraryRevision", example["sourceRevision"] + ): + msg = "Homepage library revision differs from the verification record" + raise ValueError(msg) + return profile + + def main(): """Verify and execute one displayed program with its recorded setup.""" repo = Path(__file__).resolve().parent.parent @@ -114,6 +130,7 @@ def main(): ) example = examples[0] view = args.view or "full" + execution = "owned-tmux" if args.example == "home" and view != "full": example = dict(example, **example["variants"][view]) if args.api_model and args.example != "api": @@ -127,6 +144,7 @@ def main(): content = page.read_text() if args.example == "home": home = json.loads(content)[args.port] + execution = homepage_execution(home, example) if (home["sourceRevision"], home["sourceTree"]) != ( example["sourceRevision"], example["sourceTree"], @@ -210,7 +228,7 @@ def main(): if args.example in ("home", "program"): from example_tmux_sandbox import ExampleTmuxSandbox - sandbox = ExampleTmuxSandbox(output, env) + sandbox = ExampleTmuxSandbox(output, env, forbid_tmux=execution == "pure-values") if sandbox: env = sandbox.env results = [] @@ -256,7 +274,9 @@ def main(): "port": example["port"], "page": example["page"], "sourceRevision": example["sourceRevision"], - "tmuxVersion": subprocess.check_output(["tmux", "-V"], text=True).strip(), + "tmuxVersion": subprocess.check_output(["tmux", "-V"], text=True).strip() + if execution != "pure-values" + else None, "pageSha256": hashlib.sha256(page.read_bytes()).hexdigest(), "files": example["files"], "runs": results, @@ -266,6 +286,9 @@ def main(): if example.get("sourceProgramId"): report["sourceProgramId"] = example["sourceProgramId"] if sandbox is not None and cleanup is not None: + report["execution"] = execution + if args.example == "home": + report["libraryRevision"] = home.get("libraryRevision", home["sourceRevision"]) report["view"] = view report["cleanup"] = cleanup report["passed"] = passed = passed and cleanup["passed"] diff --git a/scripts/example_tmux_sandbox.py b/scripts/example_tmux_sandbox.py index 67b181f4f..b32c3c7ef 100644 --- a/scripts/example_tmux_sandbox.py +++ b/scripts/example_tmux_sandbox.py @@ -55,12 +55,13 @@ def wait_for_socket_exit(path, seconds=2): class ExampleTmuxSandbox: """Observe explicit tmux endpoints and retire only owned servers.""" - def __init__(self, output, env): + def __init__(self, output, env, *, forbid_tmux=False): + self.forbid_tmux = forbid_tmux binary = shutil.which("tmux", path=env["PATH"]) - if binary is None: + if binary is None and not forbid_tmux: msg = "tmux is required to verify native examples" raise FileNotFoundError(msg) - self.binary = str(Path(binary).resolve()) + self.binary = str(Path(binary).resolve()) if binary else "" self.directory = Path(tempfile.mkdtemp(prefix="ltx-example-")) self.trace = output / "tmux-commands.jsonl" bindir = output / "native-tools" @@ -70,6 +71,12 @@ def __init__(self, output, env): import json, os, sys from pathlib import Path +if {forbid_tmux!r}: + descriptor = os.open({str(self.trace)!r}, os.O_WRONLY | os.O_CREAT | os.O_APPEND, 0o600) + os.write(descriptor, (json.dumps(sys.argv[1:]) + '\\n').encode()) + os.close(descriptor) + sys.stderr.write('tmux is forbidden by this example execution profile\\n') + raise SystemExit(125) args = sys.argv[1:] endpoint = None i = 0 @@ -122,10 +129,21 @@ def __init__(self, output, env): TMUX_TMPDIR=str(self.directory), TMUX_BIN=str(wrapper), LIBTMUX_TMUX=str(wrapper), + LIBTMUX_NATIVE_TMUX=self.binary, ) def finish(self, require_cleanup): """Record cleanup and stop only servers created by this example.""" + if self.forbid_tmux: + invocations = self.trace.read_text().splitlines() if self.trace.exists() else [] + shutil.rmtree(self.directory) + return { + "required": False, + "endpoints": [], + "tmuxInvocations": len(invocations), + "passed": not invocations, + "scope": "Pure values profile: PATH tmux invocations are rejected before dispatch.", + } first: dict[str, SocketSelection] = {} if self.trace.exists(): for line in self.trace.read_text().splitlines(): diff --git a/scripts/gen-api-model-ocaml.negative.mjs b/scripts/gen-api-model-ocaml.negative.mjs new file mode 100644 index 000000000..daa90c979 --- /dev/null +++ b/scripts/gen-api-model-ocaml.negative.mjs @@ -0,0 +1,105 @@ +#!/usr/bin/env node +/** Exercise producer input ownership against an exported OCaml checkout. No tmux or network. */ +import assert from 'node:assert/strict' +import { execFileSync, spawnSync } from 'node:child_process' +import { chmodSync, copyFileSync, existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, symlinkSync, writeFileSync } from 'node:fs' +import { createHash } from 'node:crypto' +import { tmpdir } from 'node:os' +import { dirname, join, resolve } from 'node:path' +import { fileURLToPath } from 'node:url' + +const root = resolve(dirname(fileURLToPath(import.meta.url)), '..') +const args = process.argv.slice(2) +const option = (name) => args.includes(name) ? args[args.indexOf(name) + 1] : undefined +const checkout = resolve(option('--checkout') ?? process.env.LIBTMUX_DOCS_CHECKOUT_OCAML ?? '') +assert(option('--checkout') || process.env.LIBTMUX_DOCS_CHECKOUT_OCAML, 'Provide --checkout with an exported native checkout') +assert.equal(args.length % 2, 0, 'Each option requires a value') +assert(args.every((arg, index) => index % 2 ? !arg.startsWith('--') : ['--checkout', '--generator'].includes(arg)), 'Unknown argument') +const generator = resolve(option('--generator') ?? join(root, 'scripts/gen-api-model.mjs')) +const artifactPath = '_build/docs/ocaml.json' +const artifactBytes = readFileSync(join(checkout, artifactPath)) +const artifact = JSON.parse(artifactBytes) +assert.equal(artifact.schema, 'libtmux.ocaml-api/1') +assert.match(artifact.revision, /^[a-f0-9]{40}$/) +const digest = (bytes) => createHash('sha256').update(bytes).digest('hex') +const scratch = mkdtempSync(join(tmpdir(), 'libtmux-ocaml-producer-')) + +try { + const docs = join(scratch, 'docs') + const native = join(scratch, 'port') + mkdirSync(join(docs, 'scripts'), { recursive: true }) + mkdirSync(join(docs, 'site/src/data/api'), { recursive: true }) + mkdirSync(join(docs, 'site/src/lib'), { recursive: true }) + symlinkSync(join(root, 'packages'), join(docs, 'packages'), 'dir') + symlinkSync(join(root, 'node_modules'), join(docs, 'node_modules'), 'dir') + symlinkSync(join(root, 'scripts/lib'), join(docs, 'scripts/lib'), 'dir') + for (const name of readdirSync(join(root, 'site/src/lib'))) { + symlinkSync(join(root, 'site/src/lib', name), join(docs, 'site/src/lib', name)) + } + copyFileSync(generator, join(docs, 'scripts/gen-api-model.mjs')) + execFileSync('git', ['clone', '--quiet', '--shared', '--no-checkout', checkout, native], { stdio: 'pipe' }) + execFileSync('git', ['-C', native, 'checkout', '--quiet', '--detach', artifact.revision], { stdio: 'pipe' }) + for (const input of [...artifact.nativeProvenance.files, ...artifact.nativeProvenance.exporter.files]) { + assert(!input.path.startsWith('/') && !input.path.split('/').includes('..'), 'Input escapes checkout') + const destination = join(native, input.path) + mkdirSync(dirname(destination), { recursive: true }) + copyFileSync(join(checkout, input.path), destination) + // Dune installs read-only artifacts; only this owned copy is mutated. + chmodSync(destination, 0o600) + } + mkdirSync(dirname(join(native, artifactPath)), { recursive: true }) + writeFileSync(join(native, artifactPath), artifactBytes) + const env = { ...process.env, LIBTMUX_DOCS_PORT: 'ocaml', + LIBTMUX_DOCS_CHECKOUT_OCAML: native, LIBTMUX_DOCS_SOURCE_SHA: artifact.revision, + LIBTMUX_DOCS_SOURCE_REF: artifact.revision } + const run = () => spawnSync(process.execPath, [join(docs, 'scripts/gen-api-model.mjs'), '--port', 'ocaml'], { + cwd: docs, env, encoding: 'utf8', timeout: 30_000, maxBuffer: 4 * 1024 * 1024, + }) + const control = run() + assert.equal(control.status, 0, `Valid compiled inputs and native exporter must pass:\n${control.stderr}`) + assert.equal(JSON.parse(readFileSync(join(docs, 'site/src/data/api/ocaml.json'))).revision, artifact.revision) + console.log('ok installed compiler artifacts and native exporter produce the selected model') + const outputDirectory = join(docs, 'site/src/data/api') + const outputs = () => Object.fromEntries(readdirSync(outputDirectory).sort().map((name) => + [name, digest(readFileSync(join(outputDirectory, name)))])) + const baseline = outputs() + const rejected = (name, expected) => { + const result = run() + assert.ifError(result.error) + assert.equal(result.signal, null, name) + assert(Number.isInteger(result.status) && result.status !== 0, name) + assert.match(result.stderr, expected, name) + assert.deepEqual(outputs(), baseline, `${name}: output changed before rejection`) + console.log(`ok ${name}; output unchanged`) + } + const compiled = artifact.nativeProvenance.files.find((input) => input.path.endsWith('.cmti')) + assert(compiled, 'Export must include a compiled public interface') + const compiledPath = join(native, compiled.path) + const savedCompiled = readFileSync(compiledPath) + writeFileSync(compiledPath, Buffer.concat([savedCompiled, Buffer.from('changed')])) + rejected('altered installed compiler artifact', /native artifact source differs/) + writeFileSync(compiledPath, savedCompiled) + + const changedDigest = JSON.parse(artifactBytes) + const source = changedDigest.nativeProvenance.files.find((input) => !input.path.startsWith('_build/')) + assert(source, 'Export must include committed interface input') + source.sha256 = '0'.repeat(64) + writeFileSync(join(native, artifactPath), JSON.stringify(changedDigest)) + rejected('incorrect committed interface digest', /native artifact source differs/) + writeFileSync(join(native, artifactPath), artifactBytes) + + const toolPath = join(native, artifact.nativeProvenance.exporter.files[0].path) + const savedTool = readFileSync(toolPath) + writeFileSync(toolPath, Buffer.concat([savedTool, Buffer.from('changed')])) + rejected('altered native exporter bytes', /native artifact exporter is stale/) + writeFileSync(toolPath, savedTool) + + const changedRevision = JSON.parse(artifactBytes) + changedRevision.revision = '0'.repeat(40) + writeFileSync(join(native, artifactPath), JSON.stringify(changedRevision)) + rejected('incorrect selected library revision', /library revision mismatch/) +} finally { + rmSync(scratch, { recursive: true, force: true }) + assert(!existsSync(scratch), 'Temporary producer checkout remains') +} +console.log('gen-api-model-ocaml.negative: ownership and four rejection controls pass; temporary checkouts removed') diff --git a/scripts/gen-api-model.mjs b/scripts/gen-api-model.mjs index 804f74e23..6446cbac2 100644 --- a/scripts/gen-api-model.mjs +++ b/scripts/gen-api-model.mjs @@ -15,12 +15,20 @@ import { fileURLToPath } from 'node:url' import { PORTS as PORT_DEFS } from '../site/src/lib/ports.ts' import { extractDoxygen } from '../packages/api-model/src/languages/doxygen.ts' import { extractLua } from '../packages/api-model/src/languages/lua.ts' +import { extractPerlArtifact } from '../packages/api-model/src/languages/perl.ts' import { extractRuby } from '../packages/api-model/src/languages/ruby.ts' import { extractPowerShell } from '../packages/api-model/src/languages/powershell.ts' import { extractJulia } from '../packages/api-model/src/languages/julia.ts' +import { extractOcamlArtifact } from '../packages/api-model/src/languages/ocaml.ts' import { extractElixir } from '../packages/api-model/src/languages/elixir.ts' +import { extractHaskellArtifact } from '../packages/api-model/src/languages/haskell.ts' +import { extractClojure } from '../packages/api-model/src/languages/clojure.ts' +import { attachCompleteClojureExamples } from '../packages/api-model/src/languages/clojure-examples.ts' +import { extractCommonLisp } from '../packages/api-model/src/languages/lisp.ts' +import { extractErlang } from '../packages/api-model/src/languages/erlang.ts' import { attachCompleteGoExamples, readCompleteGoExamples } from '../packages/api-model/src/languages/go-examples.ts' import { attachCompleteCSharpExamples } from '../packages/api-model/src/languages/csharp-examples.ts' +import { attachCompleteOcamlExamples } from '../packages/api-model/src/languages/ocaml-examples.ts' import { attachCompleteFSharpExamples } from '../packages/api-model/src/languages/fsharp-examples.ts' import { attachCompleteRustExamples } from '../packages/api-model/src/languages/rust-examples.ts' import { attachNativeRustIdStructs } from '../packages/api-model/src/languages/rust-id-structs.ts' @@ -97,7 +105,7 @@ function packageVersion(checkout, port, product) { return /^version\s*=\s*"([^"]+)"/m.exec(read(`crates/${crate}/Cargo.toml`))?.[1] ?? /^version\s*=\s*"([^"]+)"/m.exec(read('Cargo.toml'))?.[1] } - if (['java', 'kotlin', 'scala'].includes(port)) return /^libtmuxVersion=(.+)$/m.exec(read('gradle.properties'))?.[1] + if (['java', 'kotlin', 'scala', 'clojure'].includes(port)) return /^libtmuxVersion=(.+)$/m.exec(read('gradle.properties'))?.[1] if (['csharp', 'fsharp'].includes(port)) { const props = read('Directory.Build.props') const prefix = /([^<]+) git(checkout, 'rev-parse', '--verify', '--quiet', r), @@ -219,6 +230,10 @@ const PORTS = { excludePaths: [/(^|\.)_vendor\./, /(^|\.)_compat\./], }, }, + perl: { + checkout: '~/work/libtmux/libtmux-perl-docs-site', root: '.', nativeArtifact: 'docs/_build/api.json', + repo: 'libtmux/libtmux-perl', options: {}, + }, ruby: { checkout: '~/work/libtmux/libtmux-ruby-docs', root: '.', @@ -236,6 +251,11 @@ const PORTS = { root: '.', nativeArtifact: 'docs/build/api.json', repo: 'libtmux/libtmux-julia', options: {}, }, + erlang: { + checkout: '~/work/libtmux/libtmux-erlang-docs-site', + root: '.', nativeArtifact: '_build/docs/api.json', + repo: 'libtmux/libtmux-erlang', options: {}, + }, // Written by packages/api-model/scripts/export-elixir.exs, run from the // checkout with `MIX_ENV=prod mix run --no-start

Local fixture

`) + } + }) + const localSockets = new Set() + local.on('connection', (socket) => { + localSockets.add(socket) + socket.once('close', () => localSockets.delete(socket)) + socket.on('error', () => socket.destroy()) + }) + local.on('upgrade', (request, socket) => { + const accept = createHash('sha1').update(request.headers['sec-websocket-key'] + '258EAFA5-E914-47DA-95CA-C5AB0DC85B11').digest('base64') + socket.write(`HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: ${accept}\r\n\r\n`) + socket.once('data', () => socket.end()) + }) + try { + local.listen(0, '127.0.0.1') + await once(local, 'listening') + const base = `http://127.0.0.1:${local.address().port}` + const sidebarAdmission = new Error('Sidebar context admitted') + await assert.rejects(checkSidebarDemo({ async newContext() { throw sidebarAdmission } }, base), + (error) => error === sidebarAdmission, 'The sidebar check passes its URL into the shared context factory') + for (const factory of ['page', 'context', 'redirect', 'continued']) { + const page = factory === 'page' + ? await newCheckPage(browser, base, { viewport: { width: 640, height: 480 } }) + : await (await newCheckContext(browser, base, { viewport: { width: 640, height: 480 } })).newPage() + const context = page.context() + context.setDefaultNavigationTimeout(5000) + context.on('requestfailed', (request) => { + if (new URL(request.url()).origin === remote) result.resolve('blocked') + }) + context.on('response', (response) => { + if (new URL(response.url()).origin === remote) result.resolve('blocked') + }) + try { + if (factory === 'continued') await page.route('**/*', (route) => route.continue()) + result = Promise.withResolvers() + let loaded = false + const navigation = page.goto(base + (factory === 'redirect' ? '/redirect-case' : '/'), { waitUntil: 'load' }).then(() => { loaded = true }, (error) => { result.reject(error) }) + const outcome = await result.promise + if (outcome === 'escaped') assert.equal(loaded, false, 'The held image delays document load') + assert.equal(outcome, 'blocked', `${factory}: held image reached the foreign server`) + await navigation + assert.equal(await page.title(), 'Local fixture') + assert.deepEqual(await page.evaluate(() => [window.localScript, getComputedStyle(document.querySelector('h1')).color]), [true, 'rgb(1, 2, 3)']) + assert.equal(page.viewportSize().width, 640, 'Browser options survive the request policy') + if (['page', 'context'].includes(factory)) { + assert.equal(await page.evaluate(async () => { + await Promise.all(Array.from(document.images, (image) => image.decode())) + return document.images[0].naturalWidth + }), 1, 'Off-origin image fixtures decode without contacting their server') + } + if (factory === 'context') { + assert.equal(await page.evaluate((url) => new Promise((resolve, reject) => { + const socket = new WebSocket(url) + socket.onopen = () => { socket.close(); resolve('open') } + socket.onerror = () => reject(new Error('The owned server WebSocket did not open')) + }), base.replace('http:', 'ws:') + '/socket'), 'open') + result = Promise.withResolvers() + const incoming = page.waitForEvent('popup') + await page.evaluate(() => window.open('/popup')) + const popup = await incoming + assert.equal(await result.promise, 'blocked', 'Popup requests inherit the context policy') + await popup.waitForLoadState('load') + assert.equal(await popup.title(), 'Local fixture') + assert.equal(await popup.evaluate(async () => { await document.images[0].decode(); return document.images[0].naturalWidth }), 1) + await popup.close() + result = Promise.withResolvers() + const fetched = context.request.get(`${remote}/api`, { timeout: 1000 }) + .then(() => 'responded', () => 'blocked') + assert.equal(await Promise.race([result.promise, fetched]), 'blocked', 'Context request/fetch cannot escape through a decorator') + } + assert.equal(escaped, 0, 'No off-origin request reached the held-image server') + } finally { + if (factory === 'page') await page.close() + else await context.close() + } + } + const page = await newCheckPage(browser, base) + try { + await page.goto(base) + const truncation = await page.evaluate(async () => { + const controller = new AbortController() + const limit = setTimeout(() => controller.abort(), 1000) + try { + const response = await fetch('/truncated', { signal: controller.signal }) + const reader = response.body.getReader() + await reader.read() + await fetch('/release-truncated') + try { + let chunk = await reader.read() + while (!chunk.done) chunk = await reader.read() + return { failed: false } + } + catch { return { failed: true, deadline: controller.signal.aborted } } + } finally { clearTimeout(limit) } + }) + assert.deepEqual(truncation, { failed: true, deadline: false }, 'Truncated upstream fails before the fixture deadline') + pendingClosed = Promise.withResolvers() + assert.equal(await page.evaluate(async () => { + const controller = new AbortController() + const response = await fetch('/pending', { signal: controller.signal }) + await response.body.getReader().read() + controller.abort() + return (await fetch('/pending-state', { signal: AbortSignal.timeout(1000) })).text() + }), 'closed', 'Cancelling a client closes its owned upstream request') + } finally { await page.close() } + const context = await newCheckContext(browser, base) + try { + const page = await context.newPage() + await page.goto(base) + await page.evaluate(async () => { await (await fetch('/pending')).body.getReader().read() }) + await Promise.all([once(local, 'pending-closed', { signal: AbortSignal.timeout(1000) }), context.close()]) + } finally { await context.close() } + const before = browser.contexts().length + const failure = new Error('Image policy registration failed') + const broken = { + async newContext(options) { + const context = await browser.newContext(options) + context.route = async () => { throw failure } + return context + }, + async newPage(options) { + const page = await browser.newPage(options) + page.context().route = async () => { throw failure } + return page + }, + } + await assert.rejects(newCheckContext(broken, base), (error) => error === failure) + assert.equal(browser.contexts().length, before, 'Failed context policy registration closes its context') + await assert.rejects(newCheckPage(broken, base), (error) => error === failure) + assert.equal(browser.contexts().length, before, 'Failed page policy registration closes its context') + const driver = browser.browserType() + const closed = await driver.launch(driver.name() === 'chromium' ? { channel: process.env.LIBTMUX_DOCS_BROWSER_CHANNEL } : {}) + await closed.close() + await assert.rejects(newCheckContext(closed, base)) + await assert.rejects(newCheckPage(closed, base)) + console.log('Browser network: local assets load; off-origin images, redirects, decorators and popup requests cannot escape') + } finally { + local.closeAllConnections() + foreign.closeAllConnections() + for (const socket of localSockets) socket.destroy() + await Promise.all([new Promise((resolve) => local.close(resolve)), new Promise((resolve) => foreign.close(resolve))]) + } +} + +if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) { + const browser = await chromium.launch() + try { await checkBrowserNetwork(browser) } finally { await browser.close() } +} diff --git a/site/scripts/check-clipboard.mjs b/site/scripts/check-clipboard.mjs index caecd5fbf..dcc1dfc31 100644 --- a/site/scripts/check-clipboard.mjs +++ b/site/scripts/check-clipboard.mjs @@ -1,4 +1,5 @@ #!/usr/bin/env node +import { newCheckPage } from './browser-context.mjs' import assert from 'node:assert/strict' import { createHash } from 'node:crypto' import { readFileSync } from 'node:fs' @@ -36,7 +37,7 @@ export function assertCompleteApiExample(rendered, example) { /** Inspect rendered API examples against their native execution receipts. */ export async function checkCompleteApiExamples(browser, base) { const examples = JSON.parse(readFileSync(new URL('../test/fixtures/api-examples.json', import.meta.url), 'utf8')).examples - const page = await browser.newPage() + const page = await newCheckPage(browser, base) try { for (const example of examples) { const path = example.page.replace(`ports/${example.port}/`, `${example.port}/latest/`) @@ -217,9 +218,10 @@ export async function checkClipboard(page, base) { if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) { const browser = await chromium.launch() try { - const page = await browser.newPage() + const base = (process.argv[2] ?? 'http://localhost:8080/en').replace(/\/$/, '') + const page = await newCheckPage(browser, base) page.setDefaultTimeout(1000) - await checkClipboard(page, (process.argv[2] ?? 'http://localhost:8080/en').replace(/\/$/, '')) + await checkClipboard(page, base) } finally { await browser.close() } diff --git a/site/scripts/check-color-scheme.mjs b/site/scripts/check-color-scheme.mjs index 78288b657..9a700fa22 100644 --- a/site/scripts/check-color-scheme.mjs +++ b/site/scripts/check-color-scheme.mjs @@ -1,12 +1,13 @@ +import { newCheckContext } from './browser-context.mjs' import assert from 'node:assert/strict' /** Compact cycling and wide radios share the same saved preference. */ export async function checkColorScheme(browser, base) { for (const blocked of [false, true]) { - const context = await browser.newContext({ viewport: { width: 596, height: 777 }, colorScheme: 'light', reducedMotion: 'reduce' }) + const context = await newCheckContext(browser, base, { viewport: { width: 596, height: 777 }, colorScheme: 'light', reducedMotion: 'reduce' }) try { if (blocked) { - await context.route('**/astro/runtime/client/dev-toolbar/entrypoint.js', (route) => route.fulfill({ contentType: 'application/javascript', body: 'export {}' })) + await context.route('**/astro/runtime/client/dev-toolbar/entrypoint.js', (route) => new URL(route.request().url()).origin !== new URL(base).origin ? route.fallback() : route.fulfill({ contentType: 'application/javascript', body: 'export {}' })) await context.addInitScript(() => Object.defineProperty(window, 'localStorage', { get() { throw new DOMException('Storage blocked', 'SecurityError') }, })) @@ -58,7 +59,7 @@ export async function checkColorScheme(browser, base) { await context.close() } } - const reader = await browser.newContext({ viewport: { width: 1062, height: 789 }, colorScheme: 'light', reducedMotion: 'reduce' }) + const reader = await newCheckContext(browser, base, { viewport: { width: 1062, height: 789 }, colorScheme: 'light', reducedMotion: 'reduce' }) try { const page = await reader.newPage() await page.goto(`${base}/code-tabs-probe/`) @@ -99,7 +100,7 @@ export async function checkColorScheme(browser, base) { } finally { await reader.close() } - const context = await browser.newContext({ javaScriptEnabled: false, viewport: { width: 596, height: 777 } }) + const context = await newCheckContext(browser, base, { javaScriptEnabled: false, viewport: { width: 596, height: 777 } }) try { const page = await context.newPage() await page.goto(`${base}/`) diff --git a/site/scripts/check-dev-sample.mjs b/site/scripts/check-dev-sample.mjs index f46b57c78..561c2733e 100644 --- a/site/scripts/check-dev-sample.mjs +++ b/site/scripts/check-dev-sample.mjs @@ -1,3 +1,4 @@ +import { newCheckContext } from './browser-context.mjs' import assert from 'node:assert/strict' import { checkHomeResponsiveLayout } from './check-home-launcher.mjs' import { checkPickerFilters } from './check-picker-filters.mjs' @@ -96,7 +97,7 @@ function revealedContrast(id) { export async function checkRowPermalinks(browser, base, pages = ROW_PERMALINK_PAGES) { let rows = 0 for (const colorScheme of ['light', 'dark']) { - const context = await browser.newContext({ colorScheme, reducedMotion: 'reduce' }) + const context = await newCheckContext(browser, base, { colorScheme, reducedMotion: 'reduce' }) const page = await context.newPage() page.setDefaultTimeout(process.env.CI ? 20000 : 10000) try { @@ -174,7 +175,7 @@ export async function checkDevSample(browser, base) { await checkKindBadgeLinks(browser, base, { sample: true }) await checkBlockLinksUndecorated(browser, base, { sample: true }) await checkTmuxKeys(browser, base) - const context = await browser.newContext({ reducedMotion: 'reduce' }) + const context = await newCheckContext(browser, base, { reducedMotion: 'reduce' }) const page = await context.newPage() const errors = [] page.on('pageerror', (error) => errors.push(error.message)) diff --git a/site/scripts/check-dev.mjs b/site/scripts/check-dev.mjs index e07ac0cf3..ce3498348 100644 --- a/site/scripts/check-dev.mjs +++ b/site/scripts/check-dev.mjs @@ -1,4 +1,5 @@ #!/usr/bin/env node +import { newCheckContext, newCheckPage } from './browser-context.mjs' import assert from 'node:assert/strict' import { cpSync, mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from 'node:fs' import { join } from 'node:path' @@ -24,6 +25,7 @@ import { checkBlockLinksUndecorated, checkKindBadgeLinks, checkKindBadgeLinksFai import { checkTypeParameters } from './check-type-parameters.mjs' import { checkTmuxKeys, TMUX_KEY_PAGES } from './check-tmux-keys.mjs' import { checkSidebarDemo } from './check-sidebar-demo.mjs' +import { checkGuideRedirect } from './check-navigation.mjs' const apiNavigationOnly = process.argv.includes('--api-navigation') const apiAnchorsOnly = process.argv.includes('--api-anchors') @@ -53,6 +55,8 @@ assert(requestedBrowserPort === undefined || /^\d+$/.test(requestedBrowserPort) && Number(requestedBrowserPort) >= 1 && Number(requestedBrowserPort) <= 65535, 'LIBTMUX_DOCS_BROWSER_PORT must be an integer from 1 to 65535') const documentationNavigationOnly = process.argv.includes('--documentation-navigation') +const guideRedirectOnly = process.argv.includes('--guide-redirect') +const sidebarDemoOnly = process.argv.includes('--sidebar-demo') const workspacePortCount = PORTS.filter((port) => productAvailable(port, 'workspace')).length Object.assign(process.env, { @@ -167,7 +171,9 @@ const entries = API_MODEL_PORTS.filter(({ slug }) => ${JSON.stringify(signatureP if (!symbol) { // Native method records can omit inferred return types, as Julia does. const native = model.symbols.filter((entry) => usesNativeSignatures(entry, port) && - entry.signatures.some((signature) => signature.params.length > 0) && + entry.signatures.some((signature) => signature.params.length > 0 || + (port === 'haskell' && entry.kind === 'function' && !signature.methodKind && + signature.raw?.includes(' :: ') && signature.raw.includes(' -> '))) && entry.signatures.every((signature) => typeof signature.raw === 'string' && signature.raw.trim())) symbol = native.find((entry) => entry.kind === 'function' && /capture/i.test(entry.name)) ?? native[0] } @@ -307,7 +313,7 @@ async function retryReload(check, page) { } async function checkSignatureLayouts(browser, base) { - const page = await browser.newPage({ javaScriptEnabled: false }) + const page = await newCheckPage(browser, base, { javaScriptEnabled: false }) try { await page.goto(`${base}/api-signature-probe/`, { waitUntil: 'load' }) const entries = page.locator('[data-signature-port]') @@ -448,7 +454,7 @@ async function checkSignatureLayouts(browser, base) { async function checkKeywordHelp(browser, base) { const fullMatrix = apiSignaturesOnly || keywordHelpOnly for (const javaScriptEnabled of [false, true]) { - const page = await browser.newPage({ javaScriptEnabled }) + const page = await newCheckPage(browser, base, { javaScriptEnabled }) const errors = [] page.on('pageerror', (error) => errors.push(error.message)) page.setDefaultTimeout(5000) @@ -540,7 +546,7 @@ async function checkMemberBodies(browser, base) { } async function checkReferenceAndHeroes(browser, base) { - const page = await browser.newPage({ reducedMotion: 'reduce' }) + const page = await newCheckPage(browser, base, { reducedMotion: 'reduce' }) page.setDefaultTimeout(process.env.CI ? 20000 : 10000) try { await page.goto(`${base}/api-body-probe/`) @@ -785,6 +791,8 @@ try { // Compile the initial pages during setup; navigation assertions measure // the running app. The outer loop still budgets this initial compilation. const firstPage = homeLauncherOnly || homeControlsOnly ? '/' + : sidebarDemoOnly ? '/demo/sidebar/' + : guideRedirectOnly ? '/ruby/latest/guides/overview/' : keywordHelpOnly ? '/kotlin/latest/reference/io-github-libtmux-kotlin-withserver/' : apiStickyOnly || permalinkRevealOnly ? '/swift/latest/reference/server/' : badgeCentringOnly ? '/py/v0.46.2/guides/attaching-to-tmux/' @@ -793,7 +801,7 @@ try { : apiNavigationOnly ? '/lua/latest/reference/libtmux-server/' : typeParametersOnly ? '/ts/latest/reference/selection-selection-where/' : '/tmux/concepts/server-session-window-pane/' const fullRun = ![homeLauncherOnly, homeControlsOnly, keywordHelpOnly, apiSignaturesOnly, referenceLayoutOnly, globalHeaderOnly, headerMenuSectionsOnly, statusBadgesOnly, badgeCentringOnly, referencePreviewsOnly, - referencePreferencesOnly, documentationNavigationOnly, apiNavigationOnly, apiAnchorsOnly, typeParametersOnly, permalinkRevealOnly, requiredAppearanceOnly].some(Boolean) + referencePreferencesOnly, documentationNavigationOnly, guideRedirectOnly, sidebarDemoOnly, apiNavigationOnly, apiAnchorsOnly, typeParametersOnly, permalinkRevealOnly, requiredAppearanceOnly].some(Boolean) const setupPages = sampleOnly ? [firstPage, '/demo/widgets/pickers/', ...TMUX_KEY_PAGES] : [firstPage, ...(fullRun ? TMUX_KEY_PAGES : [])] const ready = Promise.all(setupPages.map(async (path) => { @@ -863,10 +871,14 @@ try { } else if (referencePreferencesOnly) { await retryReload(() => checkReferencePreferences(browser, base)) await retryReload(() => checkGlobalHeader(browser, base)) + } else if (guideRedirectOnly) { + await checkGuideRedirect(browser, base) + } else if (sidebarDemoOnly) { + await checkSidebarDemo(browser, `${base}/demo/sidebar/`) } else if (documentationNavigationOnly) { await retryReload(() => checkDocumentationNavigation(browser, base, true)) } else if (apiNavigationOnly) { - const page = await browser.newPage({ reducedMotion: 'reduce' }) + const page = await newCheckPage(browser, base, { reducedMotion: 'reduce' }) page.setDefaultTimeout(process.env.CI ? 20000 : 10000) await retryReload(() => checkApiNavigation(page, base)) await checkApiNavigationFail(browser, base) @@ -912,15 +924,15 @@ try { // Cold API indexes occupy the same development server as the page walk. // Finish that initial compilation before starting timed browser navigation. await apiExamples - const page = await browser.newPage({ reducedMotion: 'reduce' }) + const page = await newCheckPage(browser, base, { reducedMotion: 'reduce' }) page.setDefaultTimeout(process.env.CI ? 20000 : 10000) const manifest = await page.request.get(`${base}/page-links.json`) assert(manifest.ok(), `Native navigation manifest: HTTP ${manifest.status()}`) assert.equal((await manifest.json()).schema, 1) - const clipboardPage = await browser.newPage() + const clipboardPage = await newCheckPage(browser, base) clipboardPage.setDefaultTimeout(process.env.CI ? 20000 : 10000) const clipboard = schedule(() => checkClipboard(clipboardPage, base).finally(() => clipboardPage.close())) - const navigationPage = await browser.newPage({ reducedMotion: 'reduce' }) + const navigationPage = await newCheckPage(browser, base, { reducedMotion: 'reduce' }) navigationPage.setDefaultTimeout(process.env.CI ? 20000 : 10000) const navigation = schedule(() => retryReload(() => checkNavigation(navigationPage, base)).finally(() => navigationPage.close()) .then(() => retryReload(() => checkMcpInstallRevisit(browser, base)))) @@ -938,7 +950,7 @@ try { .then(() => checkStatusBadgesFail(browser, base))) const homeLauncher = schedule(() => checkHomeLauncher(browser, base)) const documentationNavigation = schedule(() => retryReload(() => checkDocumentationNavigation(browser, base))) - const apiNavigationPage = await browser.newPage({ reducedMotion: 'reduce' }) + const apiNavigationPage = await newCheckPage(browser, base, { reducedMotion: 'reduce' }) apiNavigationPage.setDefaultTimeout(process.env.CI ? 20000 : 10000) const apiNavigation = schedule(() => retryReload(() => checkApiNavigation(apiNavigationPage, base)).then(() => checkApiNavigationFail(browser, base)).finally(() => apiNavigationPage.close())) const apiAnchors = schedule(() => retryReload(() => checkApiAnchorArrival(browser, base))) @@ -1196,7 +1208,7 @@ try { }) assert.equal(toolbar.background, toolbar.page, `${colorScheme}: toolbar uses the page surface before theme initialization`) assert.equal(toolbar.icon, toolbar.text, `${colorScheme}: toolbar icons use the page text color`) - const context = await browser.newContext({ javaScriptEnabled: false, colorScheme, viewport: { width: 390, height: 844 } }) + const context = await newCheckContext(browser, base, { javaScriptEnabled: false, colorScheme, viewport: { width: 390, height: 844 } }) const noScript = await context.newPage() await noScript.goto(`${base}/tmux/concepts/server-session-window-pane/`, { waitUntil: 'load' }) const checkContrast = async (scheme, selectors = ['h1', '.prose h2', '.prose p']) => { diff --git a/site/scripts/check-fonts.mjs b/site/scripts/check-fonts.mjs index da8033c40..770b3351b 100755 --- a/site/scripts/check-fonts.mjs +++ b/site/scripts/check-fonts.mjs @@ -22,6 +22,7 @@ * * Usage: node scripts/check-fonts.mjs [--site DIR] [--url BASE] [--json] */ +import { newCheckPage } from './browser-context.mjs' import { existsSync, readFileSync } from 'node:fs' import { globSync } from 'node:fs' import { dirname, join, resolve } from 'node:path' @@ -169,7 +170,7 @@ try { const browser = await chromium.launch() usage = [] for (const [name, path, ours] of ARCHETYPES) { - const page = await browser.newPage({ viewport: { width: 1440, height: 900 } }) + const page = await newCheckPage(browser, BASE, { viewport: { width: 1440, height: 900 } }) const response = await page.goto(BASE + path, { waitUntil: 'networkidle' }).catch(() => null) if (!response?.ok()) { failures.push(`${name}: ${path} returned ${response?.status() ?? 'no response'}`) diff --git a/site/scripts/check-header-menu-sections.mjs b/site/scripts/check-header-menu-sections.mjs index 2a384e772..dbbb6d2a6 100644 --- a/site/scripts/check-header-menu-sections.mjs +++ b/site/scripts/check-header-menu-sections.mjs @@ -1,3 +1,4 @@ +import { newCheckContext } from './browser-context.mjs' import assert from 'node:assert/strict' /** @@ -252,7 +253,7 @@ export async function checkHeaderMenuSections(browser, base, options = {}) { kinds = KINDS, behavior = true, sabotage } = options let menus = 0 for (const scheme of schemes) { - const context = await browser.newContext({ colorScheme: scheme, reducedMotion: 'reduce' }) + const context = await newCheckContext(browser, base, { colorScheme: scheme, reducedMotion: 'reduce' }) const page = await context.newPage() page.setDefaultTimeout(process.env.CI ? 20000 : 10000) // The first load of each port compiles its page in the development server. diff --git a/site/scripts/check-home-example-options.mjs b/site/scripts/check-home-example-options.mjs index 878374537..c0de63e69 100644 --- a/site/scripts/check-home-example-options.mjs +++ b/site/scripts/check-home-example-options.mjs @@ -1,13 +1,15 @@ +import { newCheckContext } from './browser-context.mjs' import assert from 'node:assert/strict' import { PORTS } from '../src/lib/ports.ts' +import HOME_EXAMPLES from '../src/data/home-examples.json' with { type: 'json' } import { chooseHomeTask } from './check-home-task-reset.mjs' export async function checkHomeExampleOptions(browser, base) { for (const blocked of [false, true]) { - const context = await browser.newContext({ viewport: { width: 944, height: 777 }, reducedMotion: 'reduce' }) + const context = await newCheckContext(browser, base, { viewport: { width: 944, height: 777 }, reducedMotion: 'reduce' }) try { if (blocked) { - await context.route('**/astro/runtime/client/dev-toolbar/entrypoint.js', (route) => route.fulfill({ contentType: 'application/javascript', body: 'export {}' })) + await context.route('**/astro/runtime/client/dev-toolbar/entrypoint.js', (route) => new URL(route.request().url()).origin !== new URL(base).origin ? route.fallback() : route.fulfill({ contentType: 'application/javascript', body: 'export {}' })) await context.addInitScript(() => Object.defineProperty(window, 'localStorage', { get() { throw new DOMException('Storage blocked', 'SecurityError') }, })) @@ -20,11 +22,19 @@ export async function checkHomeExampleOptions(browser, base) { const cleanup = active.locator('[data-example-cleanup]') const check = async (handling, cleaning) => { const actual = await page.locator('[data-home-example]').evaluateAll((examples) => examples.map((example) => ({ - handling: example.querySelector('[data-example-errors]').checked, - cleaning: example.querySelector('[data-example-cleanup]').checked, + port: example.dataset.homeExample, + singleView: example.hasAttribute('data-single-view'), + handling: example.querySelector('[data-example-errors]')?.checked ?? null, + cleaning: example.querySelector('[data-example-cleanup]')?.checked ?? null, }))) - assert.deepEqual(actual, PORTS.map(() => ({ handling, cleaning })), 'Every language shares both choices') - const view = handling ? (cleaning ? 'full' : 'errors') : (cleaning ? 'cleanup' : 'concise') + assert.deepEqual(actual, PORTS.map(({ slug }) => ({ + port: slug, singleView: Boolean(HOME_EXAMPLES[slug].singleView), + handling: HOME_EXAMPLES[slug].singleView ? null : handling, + cleaning: HOME_EXAMPLES[slug].singleView ? null : cleaning, + })), 'Selectable examples share both choices; single-view examples have no toggles') + const port = await active.getAttribute('data-home-language') + const view = HOME_EXAMPLES[port].singleView ? 'full' + : handling ? (cleaning ? 'full' : 'errors') : (cleaning ? 'cleanup' : 'concise') assert.equal(await active.locator('[data-home-view]:visible').getAttribute('data-home-view'), view) } await page.goto(`${base}/?port=rs&prompt=eval-sweep&from=a&from=b#program`) @@ -131,5 +141,5 @@ export async function checkHomeExampleOptions(browser, base) { await context.close() } } - console.log('Example options: shared across 13 ports, independent defaults, URL/storage/reload/history, explicit zero, uncheck removal, task and URL preservation, blocked storage PASS') + console.log('Example options: selectable and single-view programs, independent defaults, URL/storage/reload/history, explicit zero, uncheck removal, task and URL preservation, blocked storage PASS') } diff --git a/site/scripts/check-home-hover.mjs b/site/scripts/check-home-hover.mjs index c89b4b734..3b7dbc482 100644 --- a/site/scripts/check-home-hover.mjs +++ b/site/scripts/check-home-hover.mjs @@ -1,9 +1,11 @@ +import { newCheckContext } from './browser-context.mjs' import assert from 'node:assert/strict' import { PORTS } from '../src/lib/ports.ts' +import HOME_EXAMPLES from '../src/data/home-examples.json' with { type: 'json' } /** Real pointer events, with the clock advanced instead of sleeping per option. */ export async function checkHomeHover(browser, base) { - const context = await browser.newContext({ viewport: { width: 914, height: 777 }, colorScheme: 'light', reducedMotion: 'no-preference' }) + const context = await newCheckContext(browser, base, { viewport: { width: 914, height: 777 }, colorScheme: 'light', reducedMotion: 'no-preference' }) const page = await context.newPage() const errors = [] page.on('pageerror', (error) => errors.push(error.message)) @@ -40,7 +42,12 @@ export async function checkHomeHover(browser, base) { assert.equal(await language.locator('[aria-current]').getAttribute('data-port'), 'py', 'Only the committed menu option is checked') assert(await page.locator(`.home-examples > [data-home-language="${slug}"]`).isVisible()) assert.equal(await page.locator('.lm-agent-prompt [data-select="topic"]').inputValue(), 'session-switcher') - assert.match(await page.locator(`.lm-agent-prompt__panel[data-port="${slug}"] [data-prompt-text]`).innerText(), /Then build a tmux session switcher/) + const promptText = await page.locator(`.lm-agent-prompt__panel[data-port="${slug}"] [data-prompt-text]`).innerText() + if (HOME_EXAMPLES[slug].execution === 'pure-values') { + assert.match(promptText, /Availability/) + assert.match(promptText, /Report this missing API boundary and stop/) + assert.doesNotMatch(promptText, /Then build a tmux session switcher/) + } else assert.match(promptText, /Then build a tmux session switcher/) await leave() assert.equal((await read()).port, 'py', 'Leaving restores the committed language') } @@ -133,5 +140,5 @@ export async function checkHomeHover(browser, base) { } finally { await context.close() } - console.log('Homepage hover: all 13 languages, task sync, dwell, restore, commit, URL/storage, Auto/Light/Dark, reduced motion and documentation exclusion PASS') + console.log('Homepage hover: every language, task and availability sync, dwell, restore, commit, URL/storage, Auto/Light/Dark, reduced motion and documentation exclusion PASS') } diff --git a/site/scripts/check-home-launcher.mjs b/site/scripts/check-home-launcher.mjs index f2a10c598..bee4f12ab 100644 --- a/site/scripts/check-home-launcher.mjs +++ b/site/scripts/check-home-launcher.mjs @@ -1,6 +1,8 @@ +import { newCheckContext } from './browser-context.mjs' import assert from 'node:assert/strict' import { PORTS } from '../src/lib/ports.ts' import HOME_PROOF from '../test/fixtures/home-examples.json' with { type: 'json' } +import HOME_EXAMPLES from '../src/data/home-examples.json' with { type: 'json' } import { createHash } from 'node:crypto' import { checkHomeHover } from './check-home-hover.mjs' import { checkWorkspaceHover } from './check-workspace-hover.mjs' @@ -86,18 +88,24 @@ export async function checkHomeResponsiveLayout(page, width, port = null) { const example = document.querySelector('.home-examples > [data-home-language]:not([hidden]) [data-home-example]') const title = bounds(example.querySelector('.home-example-heading h2')) const panel = bounds(example.querySelector('.home-example-code')) - const options = bounds(example.querySelector('.home-example-toolbar')) + const toolbar = example.querySelector('.home-example-toolbar') + const options = toolbar ? bounds(toolbar) : null return { + singleView: example.hasAttribute('data-single-view'), + hasOptions: Boolean(options), overflow: document.documentElement.scrollWidth > innerWidth + 1, pickerRow: Math.abs(language.y - solution.y) < 1, pickerRight: solution.right, headerHeight: bounds(document.querySelector('.site-header__bar')).height, - optionsInPanel: options.left >= panel.left - 1 && options.right <= panel.right + 1 && options.bottom <= panel.bottom + 1, - optionsBelowTitle: options.top >= title.bottom, + optionsInPanel: !options || (options.left >= panel.left - 1 && options.right <= panel.right + 1 && options.bottom <= panel.bottom + 1), + optionsBelowTitle: !options || options.top >= title.bottom, } }) assert(!layout.overflow && layout.pickerRight <= width, `${width}: the header fits without page overflow`) assert(layout.pickerRow, `${width}: Port and Solution stay on the same row`) + const singleView = Boolean(HOME_EXAMPLES[port ?? PORTS[0].slug].singleView) + assert.equal(layout.singleView, singleView, `${port}: the example declares its available views`) + assert.equal(layout.hasOptions, !singleView, `${port}: only selectable examples offer detail toggles`) if (width >= 561) assert(layout.headerHeight <= 53, `${width}: the entire header fits on one row`) assert(layout.optionsInPanel && layout.optionsBelowTitle, `${width}: example options stay inside the code panel's bottom row`) } @@ -117,7 +125,7 @@ async function checkSolutionHome(page, solution, port) { /** Exercise the real homepage, including the prompt controlled by its picker. */ export async function checkHomeLauncher(browser, base) { - const context = await browser.newContext({ reducedMotion: 'reduce' }) + const context = await newCheckContext(browser, base, { reducedMotion: 'reduce' }) const page = await context.newPage() page.setDefaultTimeout(process.env.CI ? 20000 : 10000) const errors = [] @@ -302,9 +310,14 @@ export async function checkHomeLauncher(browser, base) { })) const hash = (text) => createHash('sha256').update(text).digest('hex') assert.deepEqual(rendered.commands, proof.shellRecipe, `${proof.port}: exact setup and run copy payloads`) - for (const view of ['concise', 'errors', 'cleanup', 'full']) { - await panel.locator('[data-example-errors]').setChecked(view === 'errors' || view === 'full') - await panel.locator('[data-example-cleanup]').setChecked(view === 'cleanup' || view === 'full') + const singleView = Boolean(HOME_EXAMPLES[proof.port].singleView) + assert.equal(await panel.locator('[data-single-view]').count(), singleView ? 1 : 0) + if (singleView) assert.equal(await panel.locator('.home-example-options').count(), 0) + for (const view of singleView ? ['full'] : ['concise', 'errors', 'cleanup', 'full']) { + if (!singleView) { + await panel.locator('[data-example-errors]').setChecked(view === 'errors' || view === 'full') + await panel.locator('[data-example-cleanup]').setChecked(view === 'cleanup' || view === 'full') + } const selected = panel.locator(`[data-home-view="${view}"]`) assert.equal(await panel.locator('[data-home-view]:visible').count(), 1, `${proof.port}/${view}: exactly one complete program is shown`) assert(await selected.isVisible(), `${proof.port}/${view}: the selected program is shown`) @@ -373,10 +386,10 @@ export async function checkHomeLauncher(browser, base) { } finally { await context.close() } - const blockedStorage = await browser.newContext() + const blockedStorage = await newCheckContext(browser, base) try { // Astro's development toolbar reads storage unguarded; it is absent from published pages. - await blockedStorage.route('**/astro/runtime/client/dev-toolbar/entrypoint.js', (route) => route.fulfill({ contentType: 'application/javascript', body: 'export {}' })) + await blockedStorage.route('**/astro/runtime/client/dev-toolbar/entrypoint.js', (route) => new URL(route.request().url()).origin !== new URL(base).origin ? route.fallback() : route.fulfill({ contentType: 'application/javascript', body: 'export {}' })) await blockedStorage.addInitScript(() => Object.defineProperty(window, 'localStorage', { get() { throw new DOMException('Storage blocked', 'SecurityError') }, })) @@ -397,7 +410,7 @@ export async function checkHomeLauncher(browser, base) { } finally { await blockedStorage.close() } - const noScript = await browser.newContext({ javaScriptEnabled: false, viewport: { width: 390, height: 777 } }) + const noScript = await newCheckContext(browser, base, { javaScriptEnabled: false, viewport: { width: 390, height: 777 } }) try { const page = await noScript.newPage() await page.goto(`${base}/`) @@ -426,5 +439,5 @@ export async function checkHomeLauncher(browser, base) { await checkColorScheme(browser, base) await checkLanguageIconScheme(browser, base) await checkHomeExampleOptions(browser, base) - console.log('Homepage: 13 languages, 52 complete selectable programs/copy, owned solutions, shared URLs, reset, blocked storage, prompt tasks/copy, shared themes, container sizing, keyboard and no-JS PASS') + console.log('Homepage: every language, complete programs/copy, owned solutions, shared URLs, reset, blocked storage, prompt tasks/copy, shared themes, container sizing, keyboard and no-JS PASS') } diff --git a/site/scripts/check-home-task-reset.mjs b/site/scripts/check-home-task-reset.mjs index 76cb8ba2a..a946b9374 100644 --- a/site/scripts/check-home-task-reset.mjs +++ b/site/scripts/check-home-task-reset.mjs @@ -1,3 +1,4 @@ +import { newCheckContext } from './browser-context.mjs' import assert from 'node:assert/strict' async function checkTaskFirstPaint(browser, base) { @@ -7,16 +8,19 @@ async function checkTaskFirstPaint(browser, base) { { slug: 'v0.1.0-alpha.12', label: 'v0.1.0-alpha.12', kind: 'prerelease', supported: true }, ] } } for (const width of [853, 390, 280]) { - const context = await browser.newContext({ viewport: { width, height: 789 }, reducedMotion: 'reduce' }) + const context = await newCheckContext(browser, base, { viewport: { width, height: 789 }, reducedMotion: 'reduce' }) let releaseWidget const widgetReady = new Promise((resolve) => { releaseWidget = resolve }) try { - await context.route('**/astro/runtime/client/dev-toolbar/entrypoint.js', (route) => route.fulfill({ contentType: 'application/javascript', body: 'export {}' })) + await context.route('**/astro/runtime/client/dev-toolbar/entrypoint.js', (route) => new URL(route.request().url()).origin === new URL(base).origin + ? route.fulfill({ contentType: 'application/javascript', body: 'export {}' }) : route.fallback()) await context.route('**/*AgentPrompt*', async (route) => { + if (new URL(route.request().url()).origin !== new URL(base).origin) return route.fallback() if (route.request().resourceType() === 'script') await widgetReady - await route.continue() + await route.fallback() }) - await context.route('**/versions.json', (route) => route.fulfill({ json: versions })) + await context.route('**/versions.json', (route) => new URL(route.request().url()).origin === new URL(base).origin + ? route.fulfill({ json: versions }) : route.fallback()) const page = await context.newPage() page.setDefaultTimeout(process.env.CI ? 20000 : 10000) const response = await page.goto(`${base}/?port=ts&errors=1&cleanup=1`, { waitUntil: 'commit' }) @@ -72,10 +76,11 @@ export async function chooseHomeTask(page, topic) { export async function checkHomeTaskReset(browser, base) { await checkTaskFirstPaint(browser, base) for (const blocked of [false, true]) { - const context = await browser.newContext({ viewport: { width: 914, height: 777 }, reducedMotion: 'reduce' }) + const context = await newCheckContext(browser, base, { viewport: { width: 914, height: 777 }, reducedMotion: 'reduce' }) try { if (blocked) { - await context.route('**/astro/runtime/client/dev-toolbar/entrypoint.js', (route) => route.fulfill({ contentType: 'application/javascript', body: 'export {}' })) + await context.route('**/astro/runtime/client/dev-toolbar/entrypoint.js', (route) => new URL(route.request().url()).origin === new URL(base).origin + ? route.fulfill({ contentType: 'application/javascript', body: 'export {}' }) : route.fallback()) await context.addInitScript(() => Object.defineProperty(window, 'localStorage', { get() { throw new DOMException('Storage blocked', 'SecurityError') }, })) diff --git a/site/scripts/check-language-icon-scheme.mjs b/site/scripts/check-language-icon-scheme.mjs index afff84c3f..7971c04ad 100644 --- a/site/scripts/check-language-icon-scheme.mjs +++ b/site/scripts/check-language-icon-scheme.mjs @@ -1,3 +1,4 @@ +import { newCheckContext } from './browser-context.mjs' import assert from 'node:assert/strict' import { PNG } from 'pngjs' @@ -56,7 +57,7 @@ export function readPlate(buffer) { async function readIcon(browser, url, icon, { device, site, css, replacement, forced = false, read = readMark }) { // A null site is a visit without JavaScript: no saved choice, so the page follows the device. - const context = await browser.newContext({ colorScheme: device, forcedColors: forced ? 'active' : 'none', reducedMotion: 'reduce', javaScriptEnabled: site !== null, viewport: { width: 1280, height: 777 } }) + const context = await newCheckContext(browser, url, { colorScheme: device, forcedColors: forced ? 'active' : 'none', reducedMotion: 'reduce', javaScriptEnabled: site !== null, viewport: { width: 1280, height: 777 } }) try { if (site !== null) await context.addInitScript((choice) => localStorage.setItem('color-scheme', choice), site) // Added before the page parses, so an image is first drawn with it. @@ -66,7 +67,7 @@ async function readIcon(browser, url, icon, { device, site, css, replacement, fo else new MutationObserver((_, observer) => { if (document.documentElement) { observer.disconnect(); add() } }).observe(document, { childList: true }) }, css) const page = await context.newPage() - if (replacement) await page.route('**/brand/languages/rs/icon.svg', (route) => route.fulfill({ contentType: 'image/svg+xml', body: replacement })) + if (replacement) await page.route('**/brand/languages/rs/icon.svg', (route) => new URL(route.request().url()).origin !== new URL(url).origin ? route.fallback() : route.fulfill({ contentType: 'image/svg+xml', body: replacement })) await page.goto(url) const image = page.locator(icon) await image.waitFor({ state: 'visible' }) diff --git a/site/scripts/check-mobile-nav.mjs b/site/scripts/check-mobile-nav.mjs index 8a1679183..840d45e8a 100755 --- a/site/scripts/check-mobile-nav.mjs +++ b/site/scripts/check-mobile-nav.mjs @@ -21,6 +21,7 @@ * * Usage: node scripts/check-mobile-nav.mjs [base-url] */ +import { newCheckContext } from './browser-context.mjs' import { chromium } from 'playwright' import { checkApiNavigation } from './check-navigation.mjs' const BASE = (process.argv[2] ?? 'http://localhost:8080').replace(/\/$/, '') @@ -28,7 +29,7 @@ const b = await chromium.launch() const fails = [], ok = [] const note = (pass, msg) => (pass ? ok : fails).push(msg) const WITH_TOC = '/tmux/topics/traversal/', NO_TOC = '/tmux/concepts/' -const ctx = await b.newContext() +const ctx = await newCheckContext(b, BASE) const apiPage = await ctx.newPage() try { await checkApiNavigation(apiPage, BASE) diff --git a/site/scripts/check-native-layout.mjs b/site/scripts/check-native-layout.mjs index 76f476f0e..2aeb6f02c 100644 --- a/site/scripts/check-native-layout.mjs +++ b/site/scripts/check-native-layout.mjs @@ -1,3 +1,4 @@ +import { newCheckPage } from './browser-context.mjs' import assert from 'node:assert/strict' /** Controls beside a signature may sit this far from the centre of its first line. */ @@ -198,7 +199,7 @@ const DECLARATION_SAMPLES = [ * names, or the check would pass without measuring anything. */ export async function checkDeclarationControlAlignment(browser, base, widths = [1440, 768, 500, 390]) { - const page = await browser.newPage({ javaScriptEnabled: false }) + const page = await newCheckPage(browser, base, { javaScriptEnabled: false }) const beside = new Map(widths.map((width) => [width, 0])) const measured = [] try { @@ -363,7 +364,8 @@ export async function checkNativeFirstPaint(page, url) { const delayedScript = new Promise((resolve) => { release = resolve }) const pendingRoutes = [] const routeScript = (route) => { - const pending = delayedScript.then(() => route.continue()) + if (new URL(route.request().url()).origin !== new URL(url).origin) return route.fallback() + const pending = delayedScript.then(() => route.fallback()) pendingRoutes.push(pending) return pending } @@ -480,7 +482,7 @@ const MEMBER_BODY_PAGES = [ /** A body's padding alone sets its inset: top and bottom match each other and the padding. */ export async function checkMemberBodyInsets(browser, base) { const tolerance = 1 - const page = await browser.newPage({ reducedMotion: 'reduce' }) + const page = await newCheckPage(browser, base, { reducedMotion: 'reduce' }) page.setDefaultTimeout(process.env.CI ? 20000 : 10000) const failures = [] let measured = 0 diff --git a/site/scripts/check-native-navigation.mjs b/site/scripts/check-native-navigation.mjs index 8d1f2f6ba..937b5cbee 100644 --- a/site/scripts/check-native-navigation.mjs +++ b/site/scripts/check-native-navigation.mjs @@ -1,4 +1,5 @@ #!/usr/bin/env node +import { newCheckContext } from './browser-context.mjs' import assert from 'node:assert/strict' import { chromium } from 'playwright' @@ -103,7 +104,7 @@ async function checkMetadata(page) { try { for (const [width, colorScheme, reducedMotion] of [[1027, 'light', 'no-preference'], [390, 'dark', 'reduce']]) { - const context = await browser.newContext({ viewport: { width, height: 900 }, colorScheme, reducedMotion, permissions: ['clipboard-read', 'clipboard-write'] }) + const context = await newCheckContext(browser, base, { viewport: { width, height: 900 }, colorScheme, reducedMotion, permissions: ['clipboard-read', 'clipboard-write'] }) try { const page = await context.newPage() const errors = [], documents = [] @@ -159,7 +160,7 @@ try { } finally { await context.close() } } for (const width of [1027, 390]) { - const context = await browser.newContext({ viewport: { width, height: 900 }, reducedMotion: 'reduce' }) + const context = await newCheckContext(browser, base, { viewport: { width, height: 900 }, reducedMotion: 'reduce' }) try { const page = await context.newPage() const current = 'internals/api/libtmux._internal.query_list/' @@ -172,7 +173,7 @@ try { } finally { await context.close() } } for (const javaScriptEnabled of [false, true]) { - const context = await browser.newContext({ javaScriptEnabled, viewport: { width: 1027, height: 1450 }, reducedMotion: 'reduce' }) + const context = await newCheckContext(browser, base, { javaScriptEnabled, viewport: { width: 1027, height: 1450 }, reducedMotion: 'reduce' }) try { const page = await context.newPage() await page.goto(root) diff --git a/site/scripts/check-native-shell.mjs b/site/scripts/check-native-shell.mjs index a961d2f01..c975032cc 100644 --- a/site/scripts/check-native-shell.mjs +++ b/site/scripts/check-native-shell.mjs @@ -1,4 +1,5 @@ #!/usr/bin/env node +import { newCheckContext, newCheckPage } from './browser-context.mjs' import assert from 'node:assert/strict' import { chromium } from 'playwright' import { checkNativeFirstPaint, checkNativeHeader } from './check-native-layout.mjs' @@ -8,7 +9,7 @@ const version = process.argv.find((arg) => arg.startsWith('--version='))?.slice( const browser = await chromium.launch({ channel: process.env.LIBTMUX_DOCS_BROWSER_CHANNEL }) try { for (const javaScriptEnabled of [true, false]) { - const context = await browser.newContext({ javaScriptEnabled, reducedMotion: 'reduce', viewport: { width: 390, height: 900 } }) + const context = await newCheckContext(browser, base, { javaScriptEnabled, reducedMotion: 'reduce', viewport: { width: 390, height: 900 } }) try { const page = await context.newPage() const id = 'libtmux._internal.query_list.QueryList' @@ -24,7 +25,7 @@ try { await context.close() } } - const page = await browser.newPage() + const page = await newCheckPage(browser, base) page.setDefaultTimeout(process.env.CI ? 20000 : 10000) const loaded = new Set() page.on('response', (response) => { diff --git a/site/scripts/check-navigation.mjs b/site/scripts/check-navigation.mjs index be7df6b38..9254c7e59 100644 --- a/site/scripts/check-navigation.mjs +++ b/site/scripts/check-navigation.mjs @@ -1,3 +1,5 @@ +import { newCheckContext, newCheckPage } from './browser-context.mjs' +import { checkBrowserNetwork } from './check-browser-network.mjs' import assert from 'node:assert/strict' import { PORTS, productAvailable, productStatus } from '../src/lib/ports.ts' import registry from '../src/data/registry.json' with { type: 'json' } @@ -7,9 +9,28 @@ import { checkPickerFilters } from './check-picker-filters.mjs' /** The version the dev build mounts a port's prose pages at: its default, as check-dev sets it. */ const defaultVersion = (port) => JSON.parse(process.env.LIBTMUX_DOCS_PORT_DEFAULTS || '{}')[port] ?? 'latest' +/** A legacy guide loads with third-party requests blocked by its context. */ +export async function checkGuideRedirect(browser, base) { + await checkBrowserNetwork(browser) + const page = await newCheckPage(browser, base, { reducedMotion: 'reduce' }) + page.setDefaultTimeout(process.env.CI ? 20000 : 10000) + try { + await page.goto(`${base}/ruby/latest/guides/overview/`, { waitUntil: 'load' }) + await page.waitForURL(`${base}/ruby/latest/guides/getting-started/`, { waitUntil: 'load' }) + await page.locator('html[data-page-readiness="ready"]').waitFor({ state: 'attached' }) + assert.equal((await page.locator('main h1').textContent()).trim(), 'Getting started') + assert(await page.locator('main h1').isVisible(), 'The loaded guide is readable') + assert.equal(await page.title(), 'Getting started | libtmux-ruby') + assert.equal(await page.evaluate(() => document.readyState), 'complete') + console.log('Guide redirect: the legacy Ruby URL loads its article without third-party requests') + } finally { + await page.close() + } +} + /** Optional scripts injected at the end of the body cannot gate navigation. */ export async function checkNavigationBeforeAnalytics(browser, base) { - const page = await browser.newPage({ viewport: { width: 390, height: 900 }, reducedMotion: 'reduce' }) + const page = await newCheckPage(browser, base, { viewport: { width: 390, height: 900 }, reducedMotion: 'reduce' }) page.setDefaultTimeout(5000) await page.clock.install({ time: 0 }) await page.clock.pauseAt(1000) @@ -178,7 +199,7 @@ export async function checkDocumentationNavigation(browser, base, complete = fal await checkPickerFilters(browser, base, complete) await checkNavigationBeforeAnalytics(browser, base) const ports = complete ? PORTS : PORTS.filter((port) => ['fsharp', 'ruby'].includes(port.slug)) - const page = await browser.newPage({ viewport: { width: 1440, height: 900 }, reducedMotion: 'reduce' }) + const page = await newCheckPage(browser, base, { viewport: { width: 1440, height: 900 }, reducedMotion: 'reduce' }) page.setDefaultTimeout(process.env.CI ? 20000 : 10000) await observeInitialPageLoad(page) const desktopPicker = (reader) => reader.locator('[data-documentation-context] [data-surface-picker]') @@ -297,8 +318,7 @@ export async function checkDocumentationNavigation(browser, base, complete = fal await page.waitForURL(`${base}/fsharp/latest/reference/?from=bookmark`) assert.equal((await page.locator('main h1').textContent()).trim(), 'API reference') assert.equal(await page.title(), 'F# API reference | libtmux-fsharp') - await page.goto(`${base}/ruby/latest/guides/overview/`, { waitUntil: 'load' }) - await page.waitForURL(`${base}/ruby/latest/guides/getting-started/`) + await checkGuideRedirect(browser, base) console.log(`Documentation surfaces: ${ports.length} ports retain real section links; Ruby/F# setup, cards and legacy links pass`) } finally { await page.close() @@ -307,7 +327,7 @@ export async function checkDocumentationNavigation(browser, base, complete = fal if (!complete) return for (const javaScriptEnabled of [true, false]) { for (const colorScheme of ['light', 'dark']) { - const context = await browser.newContext({ javaScriptEnabled, colorScheme, reducedMotion: 'reduce' }) + const context = await newCheckContext(browser, base, { javaScriptEnabled, colorScheme, reducedMotion: 'reduce' }) const reader = await context.newPage() reader.setDefaultTimeout(process.env.CI ? 20000 : 10000) try { @@ -540,7 +560,7 @@ export async function checkApiNavigation(page, base, { sabotage } = {}) { const nav = document.querySelector('.api-nav') sessionStorage.removeItem(`libtmux:api-tree:${nav.dataset.base}`) }) - await page.route('**/tree.json', (route) => route.fulfill({ status: 503, body: 'Unavailable' })) + await page.route('**/tree.json', (route) => new URL(route.request().url()).origin !== new URL(base).origin ? route.fallback() : route.fulfill({ status: 503, body: 'Unavailable' })) await page.reload({ waitUntil: 'commit' }) await page.waitForFunction(() => window.__docsPageLoaded) await page.locator('[data-api-nav-toggle]').click() @@ -604,7 +624,7 @@ export async function checkApiNavigation(page, base, { sabotage } = {}) { await page.keyboard.press('Escape') assert.equal(await page.locator('.api-nav').evaluate((nav) => nav.inert), true, 'The CLI drawer dismisses with Escape') await page.setViewportSize({ width: 1440, height: 900 }) - await page.route('**/tree.json', (route) => route.fulfill({ status: 503, body: 'Unavailable' })) + await page.route('**/tree.json', (route) => new URL(route.request().url()).origin !== new URL(base).origin ? route.fallback() : route.fulfill({ status: 503, body: 'Unavailable' })) await page.goto(`${base}/lua/latest/reference/`, { waitUntil: 'commit' }) await page.waitForFunction(() => window.__docsPageLoaded) assert.equal(await page.locator('.api-nav__tree [role="treeitem"][tabindex="0"]').count(), 1, 'The server-rendered index remains keyboard reachable when its inventory cannot load') @@ -615,7 +635,7 @@ export async function checkApiNavigation(page, base, { sabotage } = {}) { /** Public symbol fragments and earlier declaration links reach the same bar. */ export async function checkApiAnchorArrival(browser, base) { const paths = new Set([`${base}/py/latest/reference/libtmux-_internal-query_list-querylist/`]) - const catalog = await browser.newPage() + const catalog = await newCheckPage(browser, base) try { for (const port of PORTS) { await catalog.goto(`${base}/${port.slug}/latest/reference/`, { waitUntil: 'load' }) @@ -630,7 +650,7 @@ export async function checkApiAnchorArrival(browser, base) { [390, 'light', true], [1280, 'dark', true], [390, 'dark', false], [1280, 'light', false], ]) { - const context = await browser.newContext({ viewport: { width, height: 1000 }, colorScheme, + const context = await newCheckContext(browser, base, { viewport: { width, height: 1000 }, colorScheme, javaScriptEnabled, reducedMotion: 'reduce' }) const page = await context.newPage() page.setDefaultTimeout(process.env.CI ? 20000 : 10000) @@ -688,7 +708,7 @@ export async function checkPermalinkReveal(browser, base, { only, sabotage } = { ['a parameter line', 'ul.api-parameters > li[id] > p > a.api-heading-link']]], ] const open = async (options) => { - const context = await browser.newContext({ reducedMotion: 'reduce', ...options }) + const context = await newCheckContext(browser, base, { reducedMotion: 'reduce', ...options }) if (sabotage?.css) await context.addInitScript((css) => document.addEventListener('DOMContentLoaded', () => { document.head.append(Object.assign(document.createElement('style'), { textContent: css })) }), sabotage.css) @@ -921,7 +941,7 @@ export async function checkPermalinkRevealFail(browser, base) { /** The control for `checkApiNavigation`: a drawer whose close button does nothing must fail it. */ export async function checkApiNavigationFail(browser, base) { - const page = await browser.newPage({ reducedMotion: 'reduce' }) + const page = await newCheckPage(browser, base, { reducedMotion: 'reduce' }) try { await assert.rejects(() => checkApiNavigation(page, base, { sabotage: () => { document.addEventListener('click', (event) => { @@ -937,7 +957,7 @@ export async function checkApiNavigationFail(browser, base) { * style to the page, for the control below. */ export async function checkReferenceSidebarBounds(browser, base, { sabotage } = {}) { - const page = await browser.newPage({ viewport: { width: 1233, height: 1220 }, reducedMotion: 'reduce', colorScheme: 'dark' }) + const page = await newCheckPage(browser, base, { viewport: { width: 1233, height: 1220 }, reducedMotion: 'reduce', colorScheme: 'dark' }) try { await page.goto(`${base}/tmux/latest/manual/#options`) await page.locator('html[data-page-readiness="ready"]').waitFor() @@ -998,7 +1018,7 @@ export async function checkApiStickyHeadings(browser, base, { only, sabotage } = const timeout = process.env.CI ? 20000 : 10000 const wants = (scenario) => !only || only.includes(scenario) const open = async (viewport) => { - const context = await browser.newContext({ viewport }) + const context = await newCheckContext(browser, base, { viewport }) if (sabotage?.script) await context.addInitScript(sabotage.script) const page = await context.newPage() page.setDefaultTimeout(timeout) @@ -1354,7 +1374,7 @@ export async function checkNavigation(page, base) { await page.goto(`${legacy}?from=legacy#where-this-comes-from`, { waitUntil: 'load' }) await page.waitForURL(`${current}?from=legacy#where-this-comes-from`) assert.equal(await page.locator('#where-this-comes-from').count(), 1, 'Legacy section still exists') - const fallback = await page.context().browser().newContext({ javaScriptEnabled: false }) + const fallback = await newCheckContext(page.context().browser(), base, { javaScriptEnabled: false }) try { const reader = await fallback.newPage() await reader.goto(legacy, { waitUntil: 'load' }) @@ -1386,7 +1406,7 @@ export async function checkApiExampleOwnership(page, base, path = 'ts/latest/ref * attributes that snippet set on , so the widget has to restore them. */ export async function checkMcpInstallRevisit(browser, base) { - const page = await browser.newPage({ reducedMotion: 'reduce' }) + const page = await newCheckPage(browser, base, { reducedMotion: 'reduce' }) try { const shown = () => page.evaluate(() => [...document.querySelectorAll('.lm-mcp-install__panel')] .filter((panel) => panel.checkVisibility()).length) diff --git a/site/scripts/check-page-readiness.mjs b/site/scripts/check-page-readiness.mjs index 81a6ef95e..d49f7ba71 100644 --- a/site/scripts/check-page-readiness.mjs +++ b/site/scripts/check-page-readiness.mjs @@ -1,3 +1,4 @@ +import { newCheckContext, newCheckPage } from './browser-context.mjs' import assert from 'node:assert/strict' import pixelmatch from 'pixelmatch' import { PNG } from 'pngjs' @@ -56,7 +57,7 @@ async function observeAppearance(context) { /** Optional policy and beacon requests cannot hold browser lifecycle events. */ export async function checkWebAnalytics(browser, base) { for (const kind of ['beacon', 'policy', 'excluded']) { - const context = await browser.newContext({ viewport: { width: 390, height: 900 } }) + const context = await newCheckContext(browser, base, { viewport: { width: 390, height: 900 } }) await observeAppearance(context) const page = await context.newPage() const errors = [] @@ -65,6 +66,7 @@ export async function checkWebAnalytics(browser, base) { const held = new Promise((resolve) => { release = resolve }) try { await page.route('**/_shell/web-analytics.json', async (route) => { + if (new URL(route.request().url()).origin !== new URL(base).origin) return route.fallback() if (kind === 'policy') { requested = true await held @@ -123,13 +125,14 @@ export async function checkWebAnalytics(browser, base) { /** Reproduce a late beacon arriving between an Astro swap and script execution. */ export async function checkWebAnalyticsTransitions(browser, base) { for (const markHandled of [true, false]) { - const context = await browser.newContext({ reducedMotion: 'reduce', viewport: { width: 390, height: 900 } }) + const context = await newCheckContext(browser, base, { reducedMotion: 'reduce', viewport: { width: 390, height: 900 } }) const page = await context.newPage() page.setDefaultTimeout(process.env.CI ? 20000 : 10000) let release, requested = false const held = new Promise((resolve) => { release = resolve }) try { await page.route('**/_shell/web-analytics.json', async (route) => { + if (new URL(route.request().url()).origin !== new URL(base).origin) return route.fallback() const response = await route.fetch() await route.fulfill({ response, headers: { ...response.headers(), 'x-libtmux-analytics': 'allow' } }) }) @@ -186,7 +189,7 @@ export async function checkRequiredAppearance(browser, base) { ['module', '/java/latest/reference/io-github-libtmux-buffers-buffers-delete/', 1280], ['effect', '/prompts/?port=ts', 390], ]) { - const context = await browser.newContext({ viewport: { width, height: 900 }, reducedMotion: 'reduce' }) + const context = await newCheckContext(browser, base, { viewport: { width, height: 900 }, reducedMotion: 'reduce' }) await observeAppearance(context) const page = await context.newPage() page.setDefaultTimeout(process.env.CI ? 20000 : 10000) @@ -214,6 +217,7 @@ export async function checkRequiredAppearance(browser, base) { : request.url() === module const incoming = page.waitForRequest(required) await page.route('**/*', async (route) => { + if (new URL(route.request().url()).origin !== new URL(base).origin) return route.fallback() if (required(route.request())) { requested = true; await hold } if (kind === 'effect' && required(route.request())) { // Exercise insertion even when a new preview's actual manifest has @@ -225,7 +229,7 @@ export async function checkRequiredAppearance(browser, base) { await route.fulfill({ json: { schema: 1, ports: { py: entries, ts: entries } } }) return } - await route.continue() + await route.fallback() }) await page.goto(`${base}${path}`, { waitUntil: 'commit' }) await incoming @@ -273,11 +277,11 @@ export async function checkRequiredAppearance(browser, base) { } finally { release(); await context.close() } } - const context = await browser.newContext({ reducedMotion: 'reduce' }) + const context = await newCheckContext(browser, base, { reducedMotion: 'reduce' }) const page = await context.newPage() page.setDefaultTimeout(process.env.CI ? 20000 : 10000) try { - await page.route('**/*', (route) => route.request().resourceType() === 'font' ? route.abort() : route.continue()) + await page.route('**/*', (route) => route.request().resourceType() === 'font' ? route.abort() : route.fallback()) await page.goto(`${base}/`, { waitUntil: 'commit' }) await page.getByRole('alert').waitFor({ state: 'visible' }) assert.equal(await page.locator('html').getAttribute('data-page-readiness'), 'failed') @@ -288,7 +292,7 @@ export async function checkRequiredAppearance(browser, base) { await page.locator('html[data-page-readiness="ready"]').waitFor({ state: 'attached' }) assert(await page.locator('main h1').isVisible(), 'Reload recovers after the required resource becomes available') } finally { await context.close() } - const legacy = await browser.newPage() + const legacy = await newCheckPage(browser, base) try { const probe = `${base}/legacy-shell-probe/` await legacy.route(probe, (route) => route.fulfill({ contentType: 'text/html', body: @@ -461,7 +465,7 @@ async function addBadgeLinkFixtures(page) { * name's text, and leads it by about a quarter em. */ export async function checkKindBadgeLinks(browser, base, { sample = false, entries = BADGE_LINKS } = {}) { - const context = await browser.newContext({ reducedMotion: 'reduce', viewport: { width: 1600, height: 1000 } }) + const context = await newCheckContext(browser, base, { reducedMotion: 'reduce', viewport: { width: 1600, height: 1000 } }) const page = await context.newPage() page.setDefaultTimeout(process.env.CI ? 20000 : 10000) const failures = [] @@ -564,7 +568,7 @@ function dottedDecorations() { * line; only inline text runs carry the dotted underline. */ export async function checkBlockLinksUndecorated(browser, base, { sample = false } = {}) { - const context = await browser.newContext({ reducedMotion: 'reduce', viewport: { width: 1440, height: 1000 } }) + const context = await newCheckContext(browser, base, { reducedMotion: 'reduce', viewport: { width: 1440, height: 1000 } }) const page = await context.newPage() page.setDefaultTimeout(process.env.CI ? 20000 : 10000) const failures = [] @@ -676,7 +680,7 @@ async function functionLinkMarked(page) { * taken away, and a page that never had the section. */ export async function checkTmuxReferencePreviewsFail(browser, base) { - const context = await browser.newContext({ reducedMotion: 'reduce', viewport: { width: 1440, height: 1000 } }) + const context = await newCheckContext(browser, base, { reducedMotion: 'reduce', viewport: { width: 1440, height: 1000 } }) const page = await context.newPage() page.setDefaultTimeout(process.env.CI ? 20000 : 10000) try { @@ -700,7 +704,7 @@ const TMUX_FUNCTION_LINK = 'section.api-tmux-section:has(> #api-tmux-command) .t const TMUX_METHOD_PAGE = '/cxx/latest/reference/libtmux-server-panes/' export async function checkTmuxReferencePreviews(browser, base, { served: build } = {}) { - const context = await browser.newContext({ reducedMotion: 'reduce', viewport: { width: 1440, height: 1000 } }) + const context = await newCheckContext(browser, base, { reducedMotion: 'reduce', viewport: { width: 1440, height: 1000 } }) const page = await context.newPage() page.setDefaultTimeout(process.env.CI ? 20000 : 10000) const opened = () => page.evaluate(() => document.getElementById('reference-link-preview')?.matches(':popover-open') ?? false) diff --git a/site/scripts/check-picker-filters.mjs b/site/scripts/check-picker-filters.mjs index 3aa0c47bb..45eda7db9 100644 --- a/site/scripts/check-picker-filters.mjs +++ b/site/scripts/check-picker-filters.mjs @@ -1,3 +1,4 @@ +import { newCheckContext } from './browser-context.mjs' import assert from 'node:assert/strict' async function bounds(page, panel) { @@ -61,7 +62,7 @@ async function exercise(page, selector, query, count) { export async function checkPickerFilters(browser, base, complete = false) { const sizes = complete ? [{ width: 853, height: 789 }, { width: 320, height: 360 }, { width: 280, height: 320 }] : [{ width: 320, height: 360 }] for (const colorScheme of complete ? ['light', 'dark'] : ['light']) { - const context = await browser.newContext({ colorScheme, reducedMotion: 'reduce' }) + const context = await newCheckContext(browser, base, { colorScheme, reducedMotion: 'reduce' }) const page = await context.newPage() page.setDefaultTimeout(5000) try { @@ -77,10 +78,11 @@ export async function checkPickerFilters(browser, base, complete = false) { } if (!complete) return - const context = await browser.newContext({ viewport: { width: 853, height: 789 }, reducedMotion: 'reduce' }) + const context = await newCheckContext(browser, base, { viewport: { width: 853, height: 789 }, reducedMotion: 'reduce' }) let release const pending = new Promise((resolve) => { release = resolve }) await context.route('**/versions.json', async (route) => { + if (new URL(route.request().url()).origin !== new URL(base).origin) return route.fallback() await pending await route.fulfill({ contentType: 'application/json', body: JSON.stringify({ schema: 1, ports: { kotlin: [ { slug: 'latest', label: 'latest', kind: 'trunk', supported: true }, @@ -120,7 +122,7 @@ export async function checkPickerFilters(browser, base, complete = false) { assert.equal(new URL(page.url()).hash, '#demo-versions', 'Sample versions use their own destination after choosing a sample language') } finally { release(); await context.unrouteAll({ behavior: 'wait' }); await context.close() } - const noScript = await browser.newContext({ javaScriptEnabled: false, viewport: { width: 853, height: 789 } }) + const noScript = await newCheckContext(browser, base, { javaScriptEnabled: false, viewport: { width: 853, height: 789 } }) try { const page = await noScript.newPage() await page.goto(`${base}/demo/widgets/pickers/`) diff --git a/site/scripts/check-reference-preferences.mjs b/site/scripts/check-reference-preferences.mjs index b1da486c5..6d9e37c71 100644 --- a/site/scripts/check-reference-preferences.mjs +++ b/site/scripts/check-reference-preferences.mjs @@ -1,10 +1,11 @@ +import { newCheckContext } from './browser-context.mjs' import assert from 'node:assert/strict' /** Exercise native disclosures and fragment navigation on a short API page. */ export async function checkReferencePreferences(browser, base) { const path = '/java/latest/reference/io-github-libtmux-buffers-buffers-delete/' const key = 'libtmux-docs.api-source-details' - const context = await browser.newContext({ reducedMotion: 'reduce', viewport: { width: 784, height: 760 } }) + const context = await newCheckContext(browser, base, { reducedMotion: 'reduce', viewport: { width: 784, height: 760 } }) await context.addInitScript(() => { window.__sourceFrames = [] const seen = new WeakSet() @@ -82,7 +83,7 @@ export async function checkReferencePreferences(browser, base) { } for (const javaScriptEnabled of [false, true]) { - const fallback = await browser.newContext({ javaScriptEnabled, reducedMotion: 'reduce' }) + const fallback = await newCheckContext(browser, base, { javaScriptEnabled, reducedMotion: 'reduce' }) if (javaScriptEnabled) await fallback.addInitScript(() => { Object.defineProperty(window, 'localStorage', { get() { throw new Error('Storage blocked') } }) }) @@ -208,7 +209,7 @@ export async function checkHeaderLinks(page, path, width, scripted) { */ export async function checkHeaderLinksFail(browser, base) { const run = async ({ path = '/rs/latest/', width = 1440, css, script }) => { - const context = await browser.newContext({ javaScriptEnabled: true, reducedMotion: 'reduce' }) + const context = await newCheckContext(browser, base, { javaScriptEnabled: true, reducedMotion: 'reduce' }) const page = await context.newPage() page.setDefaultTimeout(process.env.CI ? 20000 : 10000) try { @@ -277,7 +278,7 @@ export async function checkHeaderLinksRender(browser, base, { path = '/rs/latest if ((script || css) && javaScript.includes(false)) throw new Error('checkHeaderLinksRender: script and css apply only where JavaScript is on') for (const colorScheme of schemes) for (const width of widths) for (const javaScriptEnabled of javaScript) { const where = `${path} at ${width}px, ${colorScheme}, ${javaScriptEnabled ? 'with' : 'without'} JavaScript` - const context = await browser.newContext({ viewport: { width, height: 900 }, colorScheme, javaScriptEnabled, reducedMotion: 'reduce' }) + const context = await newCheckContext(browser, base, { viewport: { width, height: 900 }, colorScheme, javaScriptEnabled, reducedMotion: 'reduce' }) if (javaScriptEnabled) { await context.addInitScript(() => { window.__headerShift = 0 @@ -405,7 +406,7 @@ export async function checkHeaderLinksRenderFail(browser, base) { /** The global header has no repeated destination strip, including without JS. */ export async function checkGlobalHeader(browser, base) { for (const javaScriptEnabled of [false, true]) { - const context = await browser.newContext({ javaScriptEnabled, reducedMotion: 'reduce' }) + const context = await newCheckContext(browser, base, { javaScriptEnabled, reducedMotion: 'reduce' }) const page = await context.newPage() const headerFrames = new Map() try { @@ -464,7 +465,7 @@ export async function checkScrollbarStability(browser, base) { }) try { for (const width of [280, 628, 1280]) for (const colorScheme of ['light', 'dark']) for (const javaScriptEnabled of [true, false]) { - const context = await classic.newContext({ viewport: { width, height: 900 }, colorScheme, javaScriptEnabled, reducedMotion: 'reduce' }) + const context = await newCheckContext(classic, base, { viewport: { width, height: 900 }, colorScheme, javaScriptEnabled, reducedMotion: 'reduce' }) const page = await context.newPage() const frame = () => page.evaluate(() => { const rect = (selector) => { diff --git a/site/scripts/check-ruby-lua.mjs b/site/scripts/check-ruby-lua.mjs index 558a7b533..2805915ca 100644 --- a/site/scripts/check-ruby-lua.mjs +++ b/site/scripts/check-ruby-lua.mjs @@ -1,5 +1,6 @@ #!/usr/bin/env node /** Browser coverage for the Ruby and Lua documentation surfaces. */ +import { newCheckContext } from './browser-context.mjs' import { chromium } from 'playwright' const BASE = (process.argv[2] ?? 'http://localhost:8080/en').replace(/\/$/, '') @@ -33,7 +34,7 @@ const check = (condition, message) => { for (const scheme of ['light', 'dark']) { for (const [viewport, width, height] of VIEWPORTS) { - const context = await browser.newContext({ + const context = await newCheckContext(browser, BASE, { viewport: { width, height }, colorScheme: scheme, }) diff --git a/site/scripts/check-sidebar-demo.mjs b/site/scripts/check-sidebar-demo.mjs index 3ceb43692..dc26afb5b 100644 --- a/site/scripts/check-sidebar-demo.mjs +++ b/site/scripts/check-sidebar-demo.mjs @@ -1,5 +1,6 @@ #!/usr/bin/env node // Outer loop: real browser interactions across sidebar modes, themes, and viewports. +import { newCheckContext } from './browser-context.mjs' import assert from 'node:assert/strict' import { mkdir } from 'node:fs/promises' import { resolve } from 'node:path' @@ -10,7 +11,7 @@ import { chromium } from 'playwright' export async function checkSidebarDemo(browser, url, options = {}) { const values = { url, screenshots: options.screenshots, 'negative-control': options.negativeControl } const started = performance.now() - const context = await browser.newContext({ viewport: { width: 1600, height: 1150 }, reducedMotion: 'reduce' }) + const context = await newCheckContext(browser, url, { viewport: { width: 1600, height: 1150 }, reducedMotion: 'reduce' }) const page = await context.newPage() page.setDefaultTimeout(1000) const navigationTimeout = process.env.CI ? 20000 : 10000 diff --git a/site/scripts/check-status-badges.mjs b/site/scripts/check-status-badges.mjs index 8b920199a..899986589 100644 --- a/site/scripts/check-status-badges.mjs +++ b/site/scripts/check-status-badges.mjs @@ -1,3 +1,4 @@ +import { newCheckContext } from './browser-context.mjs' import assert from 'node:assert/strict' import { CONCEPT_DESCRIPTION, PICKER_GROUP_SUMMARY, PORT_BY_SLUG, PRODUCT_STATUS_GUIDE, PRODUCT_STATUS_LINK, productStatusLine, productAvailable, productStatus } from '../src/lib/ports.ts' import registry from '../src/data/registry.json' with { type: 'json' } @@ -222,7 +223,7 @@ export async function checkStatusBadges(browser, base, options = {}) { touch = true, timeout, sabotage } = options let rows = 0 for (const scheme of schemes) { - const context = await browser.newContext({ colorScheme: scheme, reducedMotion: 'reduce' }) + const context = await newCheckContext(browser, base, { colorScheme: scheme, reducedMotion: 'reduce' }) const page = await context.newPage() page.setDefaultTimeout(timeout ?? (process.env.CI ? 20000 : 10000)) page.setDefaultNavigationTimeout(60000) @@ -269,7 +270,7 @@ export async function checkStatusBadges(browser, base, options = {}) { } } if (touch && !sabotage) { - const context = await browser.newContext({ viewport: { width: 390, height: 844 }, hasTouch: true, isMobile: true, reducedMotion: 'reduce' }) + const context = await newCheckContext(browser, base, { viewport: { width: 390, height: 844 }, hasTouch: true, isMobile: true, reducedMotion: 'reduce' }) const page = await context.newPage() page.setDefaultTimeout(process.env.CI ? 20000 : 10000) page.setDefaultNavigationTimeout(60000) diff --git a/site/scripts/check-style-parity.mjs b/site/scripts/check-style-parity.mjs index ead796b35..09c48e390 100755 --- a/site/scripts/check-style-parity.mjs +++ b/site/scripts/check-style-parity.mjs @@ -17,6 +17,7 @@ * * Usage: node scripts/check-style-parity.mjs [base-url] */ +import { newCheckPage } from './browser-context.mjs' import { chromium } from 'playwright' const base = process.argv[2] ?? 'http://localhost:8080' @@ -163,7 +164,7 @@ async function styles(page, url, cases, side) { } const browser = await chromium.launch() -const page = await browser.newPage({ viewport: { width: 1440, height: 900 } }) +const page = await newCheckPage(browser, base, { viewport: { width: 1440, height: 900 } }) const sphinx = await styles(page, SPHINX, CASES, 'sphinx') /* * Two visits, one array. diff --git a/site/scripts/check-tables.mjs b/site/scripts/check-tables.mjs index 254eea1f6..f5b5bb2c7 100644 --- a/site/scripts/check-tables.mjs +++ b/site/scripts/check-tables.mjs @@ -1,4 +1,5 @@ #!/usr/bin/env node +import { newCheckPage } from './browser-context.mjs' import assert from 'node:assert/strict' import { globSync, readFileSync } from 'node:fs' import { join } from 'node:path' @@ -31,7 +32,7 @@ const browser = await chromium.launch({ channel: process.env.LIBTMUX_DOCS_BROWSE let checked = 0 try { for (const width of [1440, 768, 390]) { - const page = await browser.newPage({ viewport: { width, height: 1000 } }) + const page = await newCheckPage(browser, base, { viewport: { width, height: 1000 } }) for (const path of paths) { const response = await page.goto(base + path) assert(response?.ok(), `${path}: HTTP ${response?.status()}`) diff --git a/site/scripts/check-tmux-keys.mjs b/site/scripts/check-tmux-keys.mjs index 20d3d05f0..fadc9d09c 100644 --- a/site/scripts/check-tmux-keys.mjs +++ b/site/scripts/check-tmux-keys.mjs @@ -1,3 +1,4 @@ +import { newCheckContext } from './browser-context.mjs' import assert from 'node:assert/strict' /** Contrast of a rendered element's text against what is painted behind it. */ @@ -53,7 +54,7 @@ export const TMUX_KEY_PAGES = [ */ export async function checkTmuxKeys(browser, base) { for (const colorScheme of ['light', 'dark']) { - const context = await browser.newContext({ colorScheme, reducedMotion: 'reduce' }) + const context = await newCheckContext(browser, base, { colorScheme, reducedMotion: 'reduce' }) const page = await context.newPage() page.setDefaultTimeout(process.env.CI ? 20000 : 10000) const errors = [] diff --git a/site/scripts/check-type-parameters.mjs b/site/scripts/check-type-parameters.mjs index a7ffe4637..d7bbbf330 100644 --- a/site/scripts/check-type-parameters.mjs +++ b/site/scripts/check-type-parameters.mjs @@ -1,3 +1,4 @@ +import { newCheckContext } from './browser-context.mjs' import assert from 'node:assert/strict' /** @@ -18,7 +19,7 @@ export const TYPE_PARAMETER_PAGES = [ * declaration exists on the owner's page, and the Markdown twin says the same. */ export async function checkTypeParameters(browser, base, pages = TYPE_PARAMETER_PAGES) { - const context = await browser.newContext({ viewport: { width: 1280, height: 1000 }, reducedMotion: 'reduce' }) + const context = await newCheckContext(browser, base, { viewport: { width: 1280, height: 1000 }, reducedMotion: 'reduce' }) const page = await context.newPage() page.setDefaultTimeout(process.env.CI ? 20000 : 10000) try { diff --git a/site/scripts/check-visual.mjs b/site/scripts/check-visual.mjs index 10e9e16da..9caa7b658 100755 --- a/site/scripts/check-visual.mjs +++ b/site/scripts/check-visual.mjs @@ -17,6 +17,7 @@ * * Usage: node scripts/check-visual.mjs [--update] [base-url] */ +import { newCheckPage } from './browser-context.mjs' import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs' import { dirname, join, resolve } from 'node:path' import { fileURLToPath } from 'node:url' @@ -60,7 +61,7 @@ let written = 0 for (const [scheme] of [['light'], ['dark']]) { for (const [vname, width, height] of VIEWPORTS) { - const page = await browser.newPage({ viewport: { width, height }, colorScheme: scheme }) + const page = await newCheckPage(browser, base, { viewport: { width, height }, colorScheme: scheme }) for (const [pname, path] of PAGES) { const name = `${pname}-${vname}-${scheme}.png` const file = join(dir, name) diff --git a/site/scripts/check-workspace-hover.mjs b/site/scripts/check-workspace-hover.mjs index 5bdcf5c6d..8ed8274fe 100644 --- a/site/scripts/check-workspace-hover.mjs +++ b/site/scripts/check-workspace-hover.mjs @@ -1,8 +1,9 @@ +import { newCheckContext } from './browser-context.mjs' import assert from 'node:assert/strict' /** Real pointer events on the preset picker, with the clock advanced instead of sleeping. */ export async function checkWorkspaceHover(browser, base) { - const context = await browser.newContext({ viewport: { width: 1280, height: 900 }, colorScheme: 'light' }) + const context = await newCheckContext(browser, base, { viewport: { width: 1280, height: 900 }, colorScheme: 'light' }) const page = await context.newPage() const errors = [] page.on('pageerror', (error) => errors.push(error.message)) diff --git a/site/scripts/check-workspace-shift.mjs b/site/scripts/check-workspace-shift.mjs index 3575d55f9..db8d68211 100644 --- a/site/scripts/check-workspace-shift.mjs +++ b/site/scripts/check-workspace-shift.mjs @@ -1,8 +1,9 @@ +import { newCheckContext } from './browser-context.mjs' import assert from 'node:assert/strict' /** A cold deep link into the preset picker lands in one scroll and shifts nothing. */ export async function checkWorkspaceShift(browser, base) { - const context = await browser.newContext({ viewport: { width: 1280, height: 900 }, colorScheme: 'light' }) + const context = await newCheckContext(browser, base, { viewport: { width: 1280, height: 900 }, colorScheme: 'light' }) const page = await context.newPage() const errors = [] page.on('pageerror', (error) => errors.push(error.message)) diff --git a/site/src/components/CoreHome.astro b/site/src/components/CoreHome.astro index c6edd4423..30b0f52cb 100644 --- a/site/src/components/CoreHome.astro +++ b/site/src/components/CoreHome.astro @@ -6,7 +6,7 @@ import { PORT_BY_SLUG } from '../lib/ports' import { CAPABILITY_GROUPS, coreLead, resolveCoreHome } from '../lib/core-home' import { portCapabilities, type CapabilityTable } from '../lib/core-capabilities' import { QUICKSTARTS } from '../lib/quickstarts' -import { installFor, registryFor } from '../lib/registry' +import { installFor, installsFor, installSelection, registryFor } from '../lib/registry' import { proseHref } from '../lib/docs-paths' import { SITE_ROOT } from '../lib/site-root' import CAPABILITY_TABLE from '../data/core-capabilities.json' @@ -34,7 +34,8 @@ const home = resolveCoreHome(port, version) const example = QUICKSTARTS[port]?.complete const showcase = portCapabilities(port, CAPABILITY_TABLE as CapabilityTable, SOURCES as Record) -const install = installFor(info) +const sourceInstall = home.modules.length ? installsFor(info, installSelection(info, [], process.env))[0] : undefined +const install = sourceInstall ?? installFor(info) const released = registryFor(info).version ?? '' const series = /^0\.(\d+)/.exec(released)?.[0] // The pin advice is the registry's own range syntax, for the registries whose syntax is settled. @@ -59,22 +60,36 @@ const rest = (group: keyof typeof CAPABILITY_GROUPS) => home.capabilities[group]

Install

+{sourceInstall?.note &&

{sourceInstall.note}

} {pin && series && <>

{info.packageName} {released} is pre-1.0 and can change between minor versions. Pin to a range:

}

At a glance

-

Server → Session → Window → Pane. Each level of the tmux hierarchy has its own entry in the {info.name} API, with the tmux object it wraps.

+{home.modules.length > 0 ?
+ + + {home.modules.map((module) => + + + )} +
ModuleProvides
{module.name}{module.summary}
+
: <> +

Server → Session → {home.association && <>{home.association.name} → }Window → Pane. Each level of the tmux hierarchy has its own entry in the {info.name} API, with the tmux object it wraps.

- + {home.objects.map((object) => - )} + )}{home.association && + + + }
TypeWraps
{home.objectLabel}Wraps
{object.name} {object.wraps}{object.tmuxId && <>, ID {object.tmuxId}n}
{home.association.name}A session-window association, with its index and active state
+}

What it does

{(example || showcase.length > 0) &&
} diff --git a/site/src/components/CoreShowcase.astro b/site/src/components/CoreShowcase.astro index 45f84d7b1..c5ab3c93f 100644 --- a/site/src/components/CoreShowcase.astro +++ b/site/src/components/CoreShowcase.astro @@ -34,14 +34,14 @@ interface Props { const { port, links = [] } = Astro.props as Props const programs = portCapabilities(port, TABLE as CapabilityTable, SOURCES as Record) const quickstart = QUICKSTARTS[port]?.complete +const quickstartCapability = CAPABILITIES.find((item) => item.id === (quickstart?.capability ?? 'typed-graph')) +if (!quickstartCapability) throw new Error(`CoreShowcase: ${port} names an unknown quickstart capability`) const quickstartCode = quickstart ? homeProgram(quickstart, 'full') : '' // A recording of this program, run for real, makes the first capability a player; without one the program stands alone. -const player = quickstart ? await playableCapability(port, 'typed-graph', quickstartCode) : undefined -// The first capability is the port's homepage quickstart, which already walks server, session, window and pane. -// So does each other capability whose recording is of the program its panel shows. +const player = quickstart ? await playableCapability(port, quickstartCapability.id, quickstartCode) : undefined const capabilityPlayers = new Map(await Promise.all(programs.map(async (item) => [item.id, await playableCapability(port, item.id, item.code)] as const))) const shown = [ - ...(quickstart ? [{ id: 'typed-graph', label: CAPABILITIES[0].label, quickstart: true as const, tmux: undefined as string | undefined }] : []), + ...(quickstart ? [{ ...quickstartCapability, quickstart: true as const, tmux: undefined as string | undefined }] : []), ...programs.map((item) => ({ ...item, quickstart: false as const })), ] const cachedSource = (id: CapabilityId) => { @@ -72,26 +72,26 @@ const apis = new Map(shown.map((item) => [item.id, apisUsed(port, CORE_APIS[port {player ? : } -
+ {apis.get(item.id)!.shown.length > 0 &&

APIs used

-
+
} :
{capabilityPlayers.get(item.id) ? : } -
+ {apis.get(item.id)!.shown.length > 0 &&

APIs used

-
+
}

{item.tmux && tmux {item.tmux}} The whole program, {item.file}. The port's CI runs it in {item.ci.workflow}{(item.ci.where ?? item.ci.directory) && <> from {item.ci.where ?? item.ci.directory}/}: {item.ci.command}. diff --git a/site/src/components/HomeExample.astro b/site/src/components/HomeExample.astro index 559390577..e3a0640d3 100644 --- a/site/src/components/HomeExample.astro +++ b/site/src/components/HomeExample.astro @@ -19,6 +19,7 @@ interface Props { views?: readonly (typeof HOME_VIEWS)[number][] } const { port, language, example, heading = true, fixed = false, options = true, run = true, views = HOME_VIEWS } = Astro.props +const shownViews = example.singleView ? ['full'] as const : views // A host that plays the program (`core/CorePlayer.astro`) fills `beside`, which sits next to the code, and `controls`, under both. const player = Astro.slots.has('beside') const Frame = player ? 'div' : Fragment @@ -26,7 +27,7 @@ const Stage = player ? 'div' : Fragment // The title and the hint share a row; a block with neither has no row. const headingRow = heading || Astro.slots.has('hint') --- -

+
{headingRow &&
{heading &&

Start with {language}

} @@ -34,7 +35,7 @@ const headingRow = heading || Astro.slots.has('hint')
- {views.map((view) => { + {shownViews.map((view) => { const code = homeProgram(example, view).replace(/\n$/, '') return
})} - {options &&
+ {options && !example.singleView &&
Example details @@ -60,9 +61,11 @@ const headingRow = heading || Astro.slots.has('hint')

{example.prerequisites}

Save the program above as {example.program} in a new directory, along with the files below.

+ {example.singleView ? example.singleView : <> {example.automaticCleanup ?? 'Cleanup is omitted; the private tmux server and its temporary files may remain. Select Cleanup to remove them when the program finishes.'} The program stops its private tmux server and removes any temporary files it created when it finishes. {' '}{example.withoutErrorHandling ?? 'Error handling adds diagnostics; every version checks required results and deadlines.'} + }

{example.files.filter((file) => file.name !== example.program).map((file) =>
@@ -164,6 +167,7 @@ const headingRow = heading || Astro.slots.has('hint') .home-example-toolbar input { margin: 0; } .home-example-options input { accent-color: var(--color-link); } .home-example-view { display: none; } + .home-example[data-single-view] [data-home-view="full"] { display: block; } .home-example[data-fixed] .home-example-view :global(.expressive-code pre) { height: calc(34rem - var(--home-toolbar-row, 0rem)); max-height: none; overflow: auto; tab-size: 8; scrollbar-gutter: stable; } .home-example:not(:has([data-example-errors]:checked)):not(:has([data-example-cleanup]:checked)) [data-home-view="concise"], .home-example:has([data-example-errors]:checked):not(:has([data-example-cleanup]:checked)) [data-home-view="errors"], diff --git a/site/src/components/HomeIntro.astro b/site/src/components/HomeIntro.astro index cdaaabea7..ba7314f86 100644 --- a/site/src/components/HomeIntro.astro +++ b/site/src/components/HomeIntro.astro @@ -8,6 +8,8 @@ import type { DocumentationSurface } from '../lib/documentation-navigation' import { defaultVersionFor } from '../lib/versions' import { branding } from '../lib/branding' import { withRoot } from '../lib/site-root' +import { documentationSectionsFor } from '../lib/port-documentation' +import { coreLead } from '../lib/core-home' interface Props { solutions: { port: string; version: string; surfaces: DocumentationSurface[] }[] @@ -32,7 +34,7 @@ const descriptions: Record = { @@ -41,12 +43,13 @@ const descriptions: Record = {
{PORTS.map((port, index) => { const snippet = QUICKSTARTS[port.slug] + const moreExamples = documentationSectionsFor(port.slug).includes('examples') return })}
diff --git a/site/src/components/PortLanding.astro b/site/src/components/PortLanding.astro index c9cb808e6..1f23e5c84 100644 --- a/site/src/components/PortLanding.astro +++ b/site/src/components/PortLanding.astro @@ -13,6 +13,7 @@ import { mcpShowcase, toolHeadings } from '../lib/mcp-showcase' import { loadCommand } from '../lib/workspace-links' import { landingExample, offersPicker, previewWindows, TOPICS, workspaceShowcase } from '../lib/workspace-showcase' import { QUICKSTARTS, homeCodeColumns } from '../lib/quickstarts' +import { documentationSectionsFor } from '../lib/port-documentation' import LANDING from '../data/landing-examples.json' import SOURCES from '../data/example-sources.json' @@ -51,9 +52,10 @@ const workspaceWindows = workspace && workspaceExample && !offersPicker(workspac const workspaceProgram = loadCommand(port.slug) const complete = QUICKSTARTS[port.slug]?.complete if (!complete) throw new Error(`PortLanding: ${port.slug} has no complete homepage example; add it to home-examples.json`) +const moreExamples = documentationSectionsFor(port.slug).includes('examples') const coreLinks = [ { href: portPageUrl(port, version, 'core'), label: 'Core Library documentation →' }, - { href: portPageUrl(port, version, 'examples'), label: `More ${port.name} examples →` }, + { href: portPageUrl(port, version, moreExamples ? 'examples' : 'guides'), label: moreExamples ? `More ${port.name} examples →` : `${port.name} guides →` }, ] const panelId = (product: string) => `landing-panel-${product}` --- diff --git a/site/src/components/PrereleaseNotice.astro b/site/src/components/PrereleaseNotice.astro index 33f1d10d5..c8c462889 100644 --- a/site/src/components/PrereleaseNotice.astro +++ b/site/src/components/PrereleaseNotice.astro @@ -1,6 +1,6 @@ --- /** - * The bar that says the libraries are released but still change between releases. + * Release status for the selected port, with the shared site's API notice. * * Sits directly under the header and scrolls away with the page rather than * pinning: the header is `sticky top-0`, and a second sticky strip would take @@ -21,19 +21,24 @@ * showing it twice is better than a dismiss button that silently does * nothing. */ +import { releaseMaturity, type Port } from '../lib/ports' +import { registryFor } from '../lib/registry' + interface Props { /** Match the root landing page's centered content column. */ centered?: boolean + port?: Port } -const { centered = false } = Astro.props +const { centered = false, port } = Astro.props +const unreleased = port && releaseMaturity(registryFor(port), port.tagGrammar) === 'unreleased' ---

- Early release + {unreleased ? 'Unreleased' : 'Early release'} - libtmux is released, and its APIs may still change between releases. + {unreleased ? `${port.packageName} has not been released. Its API may change during development.` : 'libtmux is released, and its APIs may still change between releases.'} This site's structure and URLs may change too.

diff --git a/site/src/components/ProseText.astro b/site/src/components/ProseText.astro index a7173ddac..e4f3356c4 100644 --- a/site/src/components/ProseText.astro +++ b/site/src/components/ProseText.astro @@ -1,5 +1,5 @@ --- -import { decideMention, notASymbol } from '@libtmux/api-model' +import { decideMention, notASymbol, portFromSentence } from '@libtmux/api-model/reference' import { productApiHref } from '../lib/product-api' import { PORT_BY_SLUG, referenceUrl } from '../lib/ports' import { defaultVersionFor } from '../lib/versions' @@ -43,10 +43,12 @@ const segments = text.split(/`([^`]+)`/).map((value, i) => ({ value, })) -const resolved = segments.map((seg) => { - if (!seg.code || notASymbol(seg.value)) return { ...seg, href: undefined, title: undefined } +const resolved = segments.map((seg, index) => { + const before = segments.slice(0, index).map(({ value }) => value).join('') + if (!seg.code || notASymbol(seg.value, portFromSentence(before) ?? port)) return { ...seg, href: undefined, title: undefined } const d = decideMention(seg.value, { pagePort: port, + before, // The same builders the rehype plugin injects: a reference URL carries a // port, a version and a package, none of which api-model can know. symbolHref: (target, symbol) => productApiHref(API_MODELS[target], symbol, defaultVersionFor(target)), diff --git a/site/src/components/api/ApiBadge.astro b/site/src/components/api/ApiBadge.astro index 6bc0496ca..3fb7d5431 100644 --- a/site/src/components/api/ApiBadge.astro +++ b/site/src/components/api/ApiBadge.astro @@ -8,7 +8,7 @@ * Beside a name in a list or a table it is the plain word. Modifiers are * outline-only words, so kind stays the loudest thing. */ -import { kindMark, markClass } from '../../lib/api-labels' +import { kindLabel, kindMark, kindPalette, markClass } from '../../lib/api-labels' import { apiGlossaryHref } from '../../lib/api-glossary' interface Props { label: string @@ -23,24 +23,25 @@ interface Props { preview?: boolean } const { label, variant, value, compact = false, plain = false, preview = true } = Astro.props as Props -const palette = value === 'cmdlet' ? 'function' : value -const text = compact ? kindMark(palette) : label +const palette = kindPalette(value) +const word = kindLabel(label) +const text = compact ? kindMark(value) : word // Cmdlets use the function palette but retain their PowerShell command kind. const href = compact || plain ? undefined : apiGlossaryHref(variant === 'kind' ? label : value, Astro.url.pathname) // Compact marks already sit inside navigation links. const Tag = href ? 'a' : 'span' const legend = variant === 'kind' && !compact && !plain -const mark = legend ? kindMark(palette) : undefined +const mark = legend ? kindMark(value) : undefined --- -{plain && variant === 'kind' && label && {label}} +{plain && variant === 'kind' && label && {word}} {legend && label && {mark && }{label}} + title={preview ? `${word} (kind)` : undefined} + aria-label={href ? `${word}: read the ${word} definition in the API glossary` : undefined} +>{mark && }{word}} {!plain && !legend && text && {text}} diff --git a/site/src/components/api/ApiCommandParameters.astro b/site/src/components/api/ApiCommandParameters.astro index fbf03c27c..7191282b5 100644 --- a/site/src/components/api/ApiCommandParameters.astro +++ b/site/src/components/api/ApiCommandParameters.astro @@ -1,5 +1,5 @@ --- -import { parameterId, type ApiSymbol, type Param, type SymbolIndex } from '@libtmux/api-model' +import { parameterId, type ApiSymbol, type Param, type SymbolIndex } from '@libtmux/api-model/reference' import { parameterBindingFacts, POWER_SHELL_COMMON_HELP, POWER_SHELL_COMMON_HELP_TITLE, powerShellCommonParameterHref, powerShellCommonParameterLabel } from '../../lib/api-sections' import ApiDoc from './ApiDoc.astro' import ApiType from './ApiType.astro' diff --git a/site/src/components/api/ApiDoc.astro b/site/src/components/api/ApiDoc.astro index d7ff727fc..07c687a9f 100644 --- a/site/src/components/api/ApiDoc.astro +++ b/site/src/components/api/ApiDoc.astro @@ -3,6 +3,7 @@ import type { ApiSymbol, SymbolIndex, LinkTarget } from '@libtmux/api-model' import { linkTmuxDoc } from '../../lib/tmux-links' import { plainMention, TMUX_KIND_TITLES } from '../../lib/mention-badge' import { formKind, isEnvironmentVariable, isWithin, writtenForm } from '../../lib/symbol-form' +import { nativeKind } from '../../lib/api-labels' /** * Doc-comment prose with its cross-references resolved. @@ -77,25 +78,26 @@ function mentionOf(link: LinkTarget | undefined, kind: string | undefined, title // A symbol is written the way its language's own documentation writes it: `kill()` in Python, `Server#kill` in Ruby. const owner = symbol && index.parentOf(symbol) // A tool is named on the wire, as a command is, and is not called by that name. - const label = symbol ? writtenForm({ + const label = symbol && span.code !== false ? writtenForm({ lang: index.language, kind: index.isMcpTool(symbol) ? 'command' : formKind(index.language, symbol, owner), symbol, owner, label: bare, chip, onOwnerPage: isWithin(context, owner, (scope) => index.parentOf(scope)), }) : bare const qualified = !chip && memberReference.test(label) && Boolean(span.link || parts.some((part) => part.link)) // The accessible name is the text a reader sees. - const mention = mentionOf(span.link, symbol?.kind, symbol?.command?.kind ?? symbol?.kind, label) - const name = {labelParts(label, qualified).map((text) => qualified && text === '#' ? {text} : text)} + const kind = symbol && nativeKind(symbol, index.language) + const mention = mentionOf(span.link, kind, symbol?.command?.kind ?? kind, label) + const name = span.code === false ? label : {labelParts(label, qualified).map((text) => qualified && text === '#' ? {text} : text)} if (span.link && mention) return ( {name} ) return span.link ? ( {name} - ) : ( + ) : span.code === false ? {label} : ( {parts.map((part) => { const separated = labelParts(part.text, qualified).map((text) => qualified && text === '#' ? {text} : text) if (!part.link) return separated // A name linked inside a longer literal is a mention like any other: its kind is its ink, and the literal keeps its frame. - const kind = part.link.symbol?.kind + const kind = part.link.symbol && nativeKind(part.link.symbol, index.language) const inside = mentionOf(part.link, kind, part.link.symbol?.command?.kind ?? kind, part.text) return {separated} })} diff --git a/site/src/components/api/ApiEntry.astro b/site/src/components/api/ApiEntry.astro index 9ca0a8037..088c2aff6 100644 --- a/site/src/components/api/ApiEntry.astro +++ b/site/src/components/api/ApiEntry.astro @@ -1,5 +1,5 @@ --- -import { boundLabel, parameterId, qualifiedNameOf, typeParameterId, typeParameterList, type ApiSymbol, type SymbolIndex, type SymbolKind } from '@libtmux/api-model' +import { boundLabel, parameterId, qualifiedNameOf, typeParameterId, typeParameterList, type ApiSymbol, type SymbolIndex, type SymbolKind } from '@libtmux/api-model/reference' import { apiInventoryAttributes } from '../../lib/inventory-targets' import { API_MODELS, mentionsOf, referenceAlternatives } from '../../lib/api-models' import { productApiIndex } from '../../lib/product-api' @@ -23,6 +23,7 @@ import ApiCommandParameters from './ApiCommandParameters.astro' import ApiSignatureParameters from './ApiSignatureParameters.astro' import { apiSignatureLayouts } from '../../lib/code-layout' import { pythonSignatureLayout } from '../../lib/python-code-layout' +import { nativeKind } from '../../lib/api-labels' /** * One documented symbol, in the shape gp-sphinx's stylesheet expects. @@ -209,13 +210,14 @@ const catalogEntries = !linkRows ? [] : catalogLinks ?? (port && !manualLinks ? const mentionSections = [...new Set(mentions.map((m) => m.section ?? 'docs'))].sort() const badges = [ - { label: symbol.command?.kind ?? kind, variant: 'kind' as const, value: kind }, + { label: symbol.command?.kind ?? nativeKind(symbol, language), variant: 'kind' as const, value: nativeKind(symbol, language) }, ...(symbol.package ? [{ label: symbol.package, variant: 'mod' as const, value: 'package' }] : []), - ...symbol.modifiers.map((m) => ({ label: m, variant: 'mod' as const, value: m })), + ...symbol.modifiers.filter((m) => port !== 'clojure' || m !== 'overload') + .map((m) => ({ label: m, variant: 'mod' as const, value: m })), ...(symbol.signatures.length > 1 && symbol.modifiers.includes('overload') ? [ { - label: `${symbol.signatures.length} overloads`, + label: `${symbol.signatures.length} ${port === 'clojure' ? 'arities' : 'overloads'}`, variant: 'mod' as const, value: 'overload', }, @@ -258,7 +260,7 @@ const folds = (sig: { params: unknown[] }) => sig.params.length >= FOLD_THRESHOL const foldable = symbol.signatures.some(folds) const { params, returns, raises, typeParameters } = apiEntryFields(symbol, language) -const methods = apiMethodDetails(symbol) +const methods = apiMethodDetails(symbol, language) const overloadTargets = new Map(methods.map((method) => [method.overloadLabel, method.id])) /** * Parameters declared by an enclosing type that this symbol's signature uses. @@ -341,9 +343,9 @@ const hasBody = {...signatureTargets[i]} tabindex={signatureLayouts.has(sig) ? '0' : undefined} role={signatureLayouts.has(sig) ? 'region' : undefined} - aria-label={signatureLayouts.has(sig) ? `Signature for ${symbol.name}${symbol.signatures.length > 1 ? `, overload ${symbol.signatures.indexOf(sig) + 1} of ${symbol.signatures.length}` : ''}` : undefined} + aria-label={signatureLayouts.has(sig) ? `Signature for ${symbol.name}${symbol.signatures.length > 1 ? `, ${port === 'clojure' ? 'arity' : 'overload'} ${symbol.signatures.indexOf(sig) + 1} of ${symbol.signatures.length}` : ''}` : undefined} data-code-columns={signatureLayouts.get(sig)?.limit} data-code-width-status={signatureLayouts.has(sig) ? (signatureLayouts.get(sig)!.failures.length ? 'unresolved' : 'fits') : undefined} data-code-width-failures={signatureLayouts.get(sig)?.failures.length ? JSON.stringify(signatureLayouts.get(sig)!.failures) : undefined}>{sig.label && sig.label !== '__AllParameterSets' && {sig.label}{sig.isDefault ? ' (default)' : ''}: } - )) : {anonymousDeclarationLabel(symbol)}) : <> + )) : {language === 'ocaml' && ['module', 'interface'].includes(symbol.kind) ? `${symbol.kind === 'interface' ? 'module type' : 'module'} ${symbol.name}` : anonymousDeclarationLabel(symbol)}) : <> {keyword && {keyword} } {prename && {prename}}{nameHref ? {symbol.name} : {symbol.name}}{alias?.typeParams && } { @@ -500,7 +502,7 @@ const hasBody = {apiCommandRelatedLinks(symbol, index).length > 0 && }
diff --git a/site/src/components/api/ApiGlossaryContent.astro b/site/src/components/api/ApiGlossaryContent.astro index f15b4295a..b1b7a0c91 100644 --- a/site/src/components/api/ApiGlossaryContent.astro +++ b/site/src/components/api/ApiGlossaryContent.astro @@ -11,7 +11,7 @@ const jsonHref = `${glossary.path.slice(0, -1)}.json`

{group.title}#

{group.description}

{group.terms.map((term) =>
-

{term.id}#

+

{term.label ?? term.id}#

{term.definition}

{term.detail &&

{term.detail}

}

References: {term.references.map((reference, index) => <> diff --git a/site/src/components/api/ApiMemberList.astro b/site/src/components/api/ApiMemberList.astro index e1194c8d6..0244b500c 100644 --- a/site/src/components/api/ApiMemberList.astro +++ b/site/src/components/api/ApiMemberList.astro @@ -4,6 +4,7 @@ import ApiBadge from './ApiBadge.astro' import ApiDoc from './ApiDoc.astro' import ApiType from './ApiType.astro' import { apiGlossaryHref } from '../../lib/api-glossary' +import { nativeKind } from '../../lib/api-labels' interface Props { groups: { id: string; label: string; members: ApiSymbol[] }[] @@ -11,10 +12,11 @@ interface Props { showGroups: boolean index: SymbolIndex hrefFor: (symbol: ApiSymbol) => string + language?: string /** Ids a member's inline entry used to carry, kept as anchors where the list replaces that entry. */ anchorsFor?: (symbol: ApiSymbol) => string[] } -const { groups, showGroups, index, hrefFor, anchorsFor } = Astro.props +const { groups, showGroups, index, hrefFor, anchorsFor, language } = Astro.props --- {groups.map((group) =>

{showGroups &&

{group.label}{group.members.length}#

} @@ -22,9 +24,9 @@ const { groups, showGroups, index, hrefFor, anchorsFor } = Astro.props {group.members.map((m) => (
  • {anchorsFor?.(m).map((id) => )} - {m.name}{m.type && : } + {m.name}{m.type && : } - + {m.inheritedFrom && inherited} {m.doc?.summary && ( diff --git a/site/src/components/api/ApiPageContents.astro b/site/src/components/api/ApiPageContents.astro index 55701fc4a..89a559458 100644 --- a/site/src/components/api/ApiPageContents.astro +++ b/site/src/components/api/ApiPageContents.astro @@ -90,6 +90,14 @@ const { sections, related } = Astro.props as Props } settleArrival() } + // Chrome on iOS shrinks innerHeight under the keyboard; while a field has focus keep the tallest height seen at this width. + let tallest = 0 + let tallestWidth = 0 + const viewportHeight = () => { + const editing = document.activeElement?.matches('textarea, select, [contenteditable]:not([contenteditable="false"]), input:not([type="button"], [type="checkbox"], [type="radio"], [type="submit"], [type="reset"], [type="range"], [type="color"], [type="file"])') + if (innerWidth !== tallestWidth || !editing) { tallestWidth = innerWidth; tallest = innerHeight } else tallest = Math.max(tallest, innerHeight) + return tallest + } const measureMembers = (readingTop) => { if (!memberHeading || !members) return memberHeight = Math.ceil(memberHeading.getBoundingClientRect().height) @@ -98,7 +106,7 @@ const { sections, related } = Astro.props as Props const fontSize = Number.parseFloat(getComputedStyle(root).fontSize) || 16 // Keep a reading area beside the stacked bars, scaled to text size and viewport. stickyMembers = memberHeight > 0 && - innerHeight - readingTop - memberHeight - groupHeight >= Math.max(fontSize * 6, innerHeight / 3) + viewportHeight() - readingTop - memberHeight - groupHeight >= Math.max(fontSize * 6, viewportHeight() / 3) members.toggleAttribute('data-api-sticky-members', stickyMembers) setLength(members, '--api-member-heading-height', memberHeight) const last = groupHeadings.at(-1) @@ -229,6 +237,10 @@ const { sections, related } = Astro.props as Props schedule() }, { signal }) window.addEventListener('resize', schedule, { signal }) + window.visualViewport?.addEventListener('resize', schedule, { signal }) + // Focus lands before the keyboard shrinks the frame: record the full height first. activeElement is still the old field during focusout, so recompute two frames later. + document.addEventListener('focusin', () => { viewportHeight() }, { signal }) + document.addEventListener('focusout', () => requestAnimationFrame(schedule), { signal }) this.observer = new ResizeObserver(schedule) if (header) this.observer.observe(header) if (row) this.observer.observe(row) diff --git a/site/src/components/api/ApiProse.astro b/site/src/components/api/ApiProse.astro index 7f770819b..dc90f2619 100644 --- a/site/src/components/api/ApiProse.astro +++ b/site/src/components/api/ApiProse.astro @@ -1,7 +1,7 @@ --- import type { ApiSymbol, SymbolIndex } from '@libtmux/api-model' import { Code } from 'astro-expressive-code/components' -import { parseApiProse, type ProseItem } from '../../lib/api-prose' +import { docSectionId, parseApiProse, type ProseItem } from '@libtmux/api-model/reference' import { groupDirectory, type DirectoryBlock } from '../../lib/api-directory' import { codeLang } from '../../lib/highlight' import ApiDoc from './ApiDoc.astro' @@ -14,7 +14,10 @@ interface Props { context?: ApiSymbol } const { text, items, index, context } = Astro.props as Props -const blocks: DirectoryBlock[] = items ? [{ kind: 'ul', items }] : groupDirectory(parseApiProse(text ?? ''), index.language) +const parsed = parseApiProse(text ?? '') +// Perl POD sections remain link targets even beside lists of references. +const blocks: DirectoryBlock[] = items ? [{ kind: 'ul', items }] + : index.language === 'perl' ? parsed : groupDirectory(parsed, index.language) const { self: ApiProse } = Astro --- @@ -56,7 +59,7 @@ const { self: ApiProse } = Astro return block.kind === 'code' ? (
    ) : block.kind === 'rubric' ? ( -

    {block.text}

    +

    {block.text}

    ) : block.kind === 'p' ? (

    diff --git a/site/src/components/api/ApiReference.astro b/site/src/components/api/ApiReference.astro index 434c53e35..95ffc4b2f 100644 --- a/site/src/components/api/ApiReference.astro +++ b/site/src/components/api/ApiReference.astro @@ -1,6 +1,6 @@ --- import type { ApiModel, ApiSymbol, SourceApiModel, SymbolIndex } from '@libtmux/api-model' -import { aliasMembersTarget, membersOf, pageMembersOf, memberTier, docSummaryText, memberSignals, parameterId, qualifiedNameOf, moduleOf, modulesIn, sourceUrl as apiSourceUrl, symbolsForProduct } from '@libtmux/api-model' +import { aliasMembersTarget, membersOf, pageMembersOf, memberTier, docSummaryText, memberSignals, parameterId, qualifiedNameOf, moduleOf, modulesIn, sourceUrl as apiSourceUrl, symbolsForProduct } from '@libtmux/api-model/reference' import mentionsData from '../../data/mentions.json' import ApiEntry from '../../components/api/ApiEntry.astro' import ApiTmuxSections from './ApiTmuxSections.astro' @@ -28,7 +28,8 @@ import { withRoot } from '../../lib/site-root' import { API_MODELS, API_NAV, PORT_NAME, indexFor, isMemberOwner, ownersOf, pageSlug, referenceAlternatives, topLevelTypesOf } from '../../lib/api-models' import { PORT_BY_SLUG, referenceUrl } from '../../lib/ports' import { productApiHref } from '../../lib/product-api' -import { nativeQualifiedName } from '../../lib/native-name' +import { nativeQualifiedName, nativeShortName } from '../../lib/native-name' +import { nativeKind } from '../../lib/api-labels' import { plainMention } from '../../lib/mention-badge' import { symbolSource } from '../../lib/markdown-twins' import { localeSourcePath } from '../../i18n/locales' @@ -203,7 +204,7 @@ const packageUrl = packageMeta?.registry ?? portMeta?.registry?.url ?? withRoot( * index actually has that anchor. */ const declaringType = owner?.parent ? model?.symbols.find((s) => s.id === owner.parent) : undefined -const declaringMention = declaringType ? plainMention(declaringType.kind, declaringType.name) : undefined +const declaringMention = declaringType ? plainMention(nativeKind(declaringType, language), declaringType.name) : undefined const ownerModule = owner ? moduleOf(declaringType ?? owner) : undefined const moduleAnchors = new Set(model ? modulesIn(model).map((m) => m.name) : []) const moduleLabel = ['java', 'kotlin', 'scala', 'go'].includes(port ?? '') ? 'Package' @@ -400,10 +401,14 @@ const title = glossary ? API_GLOSSARY_TITLE : owner ? source?.title ?? `${label} API reference` : 'API reference' const pageTitle = glossary ? API_GLOSSARY_TITLE : owner ? title : source?.title ?? 'API reference' -const displayName = owner ? (declaringType ? `${declaringType.name}.${owner.name}` : owner.name) : pageTitle +const displayName = owner ? (language === 'haskell' || language === 'erlang' ? nativeShortName(model, owner) + : language === 'clojure' || language === 'lisp' ? nativeQualifiedName(model, owner) + : declaringType ? `${declaringType.name}.${owner.name}` : owner.name) : pageTitle const breadcrumbs = source?.breadcrumbs ?? await pageBreadcrumbs(displayName, glossary ? 'reference/glossary' : slug ? `reference/${slug}` : 'reference', version, port) const pagePath = glossary ? 'reference/glossary' : source?.pagePath ?? (slug ? `reference/${slug}` : 'reference') -const description = glossary ? glossaryContext.description : source?.description ?? `Types, methods, and functions in libtmux for ${label}.` +const description = glossary ? glossaryContext.description : source?.description ?? (language === 'haskell' + ? 'Modules, data types, constructors, record fields and functions in libtmux for Haskell.' + : `Types, methods, and functions in libtmux for ${label}.`) const bases = owner && 'extends' in owner ? owner.extends ?? [] : [] --- @@ -476,7 +481,7 @@ const bases = owner && 'extends' in owner ? owner.extends ?? [] : []

    {owner &&
    - + {source?.model.project ?? portMeta?.projectName} {owner.doc?.since && Since {owner.doc.since}} {version} @@ -595,7 +600,7 @@ const bases = owner && 'extends' in owner ? owner.extends ?? [] : [] {[...mod.types, ...mod.free].map((o) => { const count = model.symbols.filter((symbol) => symbol.parent === o.id).length const kind = o.signatures.some((signature) => /\bannotation class\b/.test(signature.raw ?? '')) - ? 'annotation' : o.command?.kind ?? o.kind + ? 'annotation' : o.command?.kind ?? nativeKind(o, language) const context = indexContext(o) return (
    )}
    {o.name} - + {context && } @@ -709,7 +714,7 @@ const bases = owner && 'extends' in owner ? owner.extends ?? [] : [] {owner?.source?.file && (