diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 3d63434..aa7da1d 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -195,3 +195,114 @@ jobs: --generate-notes \ artifacts/* fi + + # -- registries ------------------------------------------------------------- + # + # Both jobs authenticate by trusted publishing: the runner proves who it is + # with a short-lived OIDC token and the registry hands back a credential that + # expires with the run. There is no long-lived secret in either, which is why + # `id-token: write` appears and `secrets` does not. + # + # Each registry has to be told to trust this workflow, and *neither* can be + # configured for a package that does not exist yet. The first publish of any + # new package is therefore a manual one from a laptop; every release after it + # goes through here. + + crate: + name: publish to crates.io + needs: build + if: github.ref_type == 'tag' + runs-on: ubuntu-latest + environment: Packaging + permissions: + contents: read + id-token: write + steps: + - uses: actions/checkout@v4 + + # A crates.io version can never be republished, not even after a yank, so + # a tag that disagrees with Cargo.toml must stop the release here rather + # than burn the version number it would have gone out under. + - name: The tag and Cargo.toml must agree + run: | + WANT="${GITHUB_REF_NAME#v}" + HAVE="$(grep -m1 '^version = ' Cargo.toml | cut -d'"' -f2)" + if [ "$WANT" != "$HAVE" ]; then + echo "tag says $WANT, Cargo.toml says $HAVE" + exit 1 + fi + shell: bash + + - name: Install toolchain + run: | + rustup toolchain install stable --profile minimal --no-self-update + rustup default stable + shell: bash + + # Re-tagging is a normal thing to do while a project is young, and the + # release job above is built for it. `cargo publish` is not: it fails + # outright on a version the registry already has, which would redden a + # rerun whose only crime is that it already succeeded. + - name: Has crates.io got this version already? + id: need + run: | + WANT="${GITHUB_REF_NAME#v}" + CODE="$(curl -sS -o /dev/null -w '%{http_code}' \ + -A "tread-release" "https://crates.io/api/v1/crates/tread/$WANT")" + if [ "$CODE" = "200" ]; then + echo "tread $WANT is already on crates.io; nothing to publish" + echo "publish=no" >> "$GITHUB_OUTPUT" + else + echo "publish=yes" >> "$GITHUB_OUTPUT" + fi + shell: bash + + - uses: rust-lang/crates-io-auth-action@v1 + id: auth + if: steps.need.outputs.publish == 'yes' + + - run: cargo publish --locked + if: steps.need.outputs.publish == 'yes' + env: + CARGO_REGISTRY_TOKEN: ${{ steps.auth.outputs.token }} + + npm: + name: publish to npm + # Not `needs: build`. The launcher this publishes downloads its binary from + # the GitHub release at first run, so publishing it before the release + # exists would ship a package that cannot work until the next job finishes. + needs: publish + if: github.ref_type == 'tag' + runs-on: ubuntu-latest + environment: Packaging + permissions: + contents: read + id-token: write + steps: + - uses: actions/checkout@v4 + + - uses: actions/setup-node@v4 + with: + node-version: 22 + registry-url: https://registry.npmjs.org + + # Trusted publishing needs a newer npm than the runner image ships. + - run: npm install -g npm@latest && npm --version + + # The published version is the tag, always. package.json carries 0.0.0 in + # the repository so there is no second place to forget to bump. + - name: Stamp the version from the tag + working-directory: npm + run: npm version "${GITHUB_REF_NAME#v}" --no-git-tag-version --allow-same-version + + # Same reasoning as the crate job: a rerun of a tag that already shipped + # must be a no-op, not a red run. + - name: Publish + working-directory: npm + run: | + WANT="${GITHUB_REF_NAME#v}" + if npm view "@viict/tread@$WANT" version > /dev/null 2>&1; then + echo "@viict/tread $WANT is already on npm; nothing to publish" + exit 0 + fi + npm publish --access public --provenance diff --git a/CLAUDE.md b/CLAUDE.md index 19f41ed..bedc75e 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -89,6 +89,7 @@ corpus of linked documents. Crate `tread`, binary `tread`. | `src/pager/` | viewport, scrolling, collapse tree, search | | `src/nav/` | document stack, index parsing, link resolution; `external.rs` is the *policy*: the scheme allowlist (`http`, `https`, `mailto`), the refusal that names the offending scheme, and `vetted()` — the one constructor in the crate of the `sys::browser::Vetted` token that `open` requires | | `src/select/` | visual selection, yank text | +| `npm/` | the npm package (SPEC.md §"Installing from a package manager"): `package.json`, one launcher and `lib/unpack.js`, no binary and no dependencies. It resolves the platform, fetches on first run **the same `.tar.gz` or `.zip` the releases page already publishes** — the release is never asked to carry a second, npm-shaped copy of every binary — verifies it against `SHA256SUMS` and only then reads the binary out of it, which is what `unpack.js` is for: node has `zlib` and no archive reader, so a tar walk and a zip central-directory walk cost a hundred lines where a dependency would cost the package its one rule, and hands the terminal over with stdio inherited so raw mode and drag-select reach the real program. `TREAD_BINARY` skips the lot. The version in `package.json` is `0.0.0` in the repository and stamped from the tag by `release.yml`, so there is no second place to bump — which also means the launcher only works from a published package, never from a checkout. Its data-directory table mirrors `src/plat/dirs.rs`; change one and change the other | Keep platform FFI inside a backend under `src/sys/`; everything above `sys` is platform-agnostic, and every `cfg(target_os)`-shaped *convention* (path syntax, diff --git a/Cargo.toml b/Cargo.toml index 9ec0f26..3f41b19 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -9,6 +9,7 @@ license = "MIT OR Apache-2.0" readme = "README.md" keywords = ["pager", "markdown", "csv", "json", "code"] categories = ["command-line-utilities", "text-processing"] +exclude = ["trajectory.json", "tools/__pycache__", ".claude", "CLAUDE.md", ".github"] [[bin]] name = "tread" diff --git a/README.md b/README.md index 61b5cf9..19ac777 100644 --- a/README.md +++ b/README.md @@ -52,6 +52,19 @@ $env:INSTALL_PATH = 'C:\tools'; irm https://raw.githubusercontent.com/viict/trea $env:VERSION = 'v0.1.0'; irm https://raw.githubusercontent.com/viict/tread/master/install.ps1 | iex ``` +From a package manager, if you already have one: + +```sh +cargo install tread # crates.io; builds from source +npx @viict/tread README.md # npm; fetches the build for your machine once +``` + +The unscoped `tread` on npm is an unrelated package, so the scope is not +optional. `npm install -g @viict/tread` puts the binary on your `PATH` under its +own name. Set `TREAD_BINARY` to a `tread` you already have and the npm launcher +downloads nothing at all — which is what one global install shared by several +accounts, or a CI runner with no route out, wants. + Prefer not to pipe the internet into a shell? Read [`install.sh`](install.sh) or [`install.ps1`](install.ps1) first, or take a `.tar.gz` — a `.zip` on Windows — from the diff --git a/SPEC.md b/SPEC.md index 87d7840..d0d64db 100644 --- a/SPEC.md +++ b/SPEC.md @@ -639,6 +639,69 @@ does not match, and install to a per-user location on `PATH` (`%LOCALAPPDATA%\Programs\tread` by default, `$env:INSTALL_PATH` to change it). It reports how to add the directory to `PATH` when it is not already there. +## Installing from a package manager + +Two registries carry `tread`, and neither changes what the program is: the +binary they deliver is the same static build the releases page holds, and +nothing installed from a registry ever reaches the network again. + +```sh +cargo install tread # crates.io, built from source +npx @viict/tread README.md # npm +npm install -g @viict/tread +``` + +The npm scope is not optional: the unscoped `tread` on npm is an unrelated +package that has been there since 2016, and `npx tread` fetches *that*. The +README says so above the fold, because it is the one mistake a new user makes +without any way to tell they have made it. + +**The npm package is a launcher, not a copy of the program.** It carries no +binary. On first run it fetches, from that version's GitHub release, the very +`.tar.gz` or `.zip` a person would download by hand and `install.sh` already +verifies — the release publishes one shape of each binary, not a second one cut +for npm — checks it against the release's `SHA256SUMS`, and only then reads the +binary out of it and puts it where it can be executed. An archive whose checksum +does not match is never opened; the run fails, saying so. Nothing unverified is +ever run, and nothing is left behind for a later run to pick up. + +Reading the archives is the launcher's own work, because node has `zlib` built +in and no archive reader: a tar is 512-byte headers each followed by its file, +and a zip is a central directory of deflate streams. Walking both costs about a +hundred lines and keeps the package's dependency count where the rest of the +project keeps it. + +The choice not to download at *install* time is deliberate. A `postinstall` +script is dead weight under `npm ci --ignore-scripts` and under pnpm's default +script blocking — the package would install and the binary would silently never +arrive. Fetching at first run costs a moment once and works everywhere. + +The binary is state, not cache, so it lives under the platform's data directory +rather than its cache directory: a cache is something the OS is entitled to +delete, and a `tread` that evaporates leaves an offline machine unable to read +anything. An explicitly set `XDG_DATA_HOME` wins on every platform, including +macOS, by the same reasoning `src/plat/dirs.rs` gives for caches. + +| Platform | Location | +| --- | --- | +| Linux | `$XDG_DATA_HOME/tread//`, else `~/.local/share/tread//` | +| macOS | `~/Library/Application Support/tread//` | +| Windows | `%LOCALAPPDATA%\tread\\` | + +A version is a directory, so upgrading needs no invalidation rule: a new version +writes a new directory, and the others are removed once the new binary has run. + +`TREAD_BINARY` points at a `tread` that already exists and skips all of it — +what one global install shared by several accounts wants, and what a runner with +no route out of the network needs. It is honoured exactly: if it names something +that is not there, the run fails rather than quietly downloading a second copy. + +What this costs, stated plainly: `npm ci` no longer reproduces the whole tool +from the lockfile. The lockfile pins the launcher; the binary is fetched +afterwards and vouched for by its checksum instead. Anyone who needs the +stronger guarantee should install from crates.io, from `install.sh`, or from the +releases page — all three deliver the program itself. + ## Directories A directory is something to read, not an error. `tread some/dir` lists it, and a diff --git a/npm/README.md b/npm/README.md new file mode 100644 index 0000000..6c9f046 --- /dev/null +++ b/npm/README.md @@ -0,0 +1,60 @@ +# tread + +A terminal reader for markdown, CSV, JSON and source code — `less`, but it +understands what it is showing: collapsible headings, real tables, colored +links, and navigation across a corpus of linked documents. + +```sh +npx @viict/tread README.md +``` + +Or install it so the binary is on your `PATH` as `tread`: + +```sh +npm install -g @viict/tread +``` + +## What this package is + +`tread` is a Rust program with no dependencies. This package is a small launcher +that downloads the build for your machine on first run, verifies its SHA-256 +against the checksums published with the release, and then gets out of the way. +Nothing is downloaded at install time, so `npm ci --ignore-scripts` and pnpm's +default script blocking are not a problem. + +The binary is kept per version under your platform's data directory: + +| Platform | Location | +| --- | --- | +| Linux | `$XDG_DATA_HOME/tread//`, else `~/.local/share/tread//` | +| macOS | `~/Library/Application Support/tread//` | +| Windows | `%LOCALAPPDATA%\tread\\` | + +Older versions are removed once a new one has been fetched. + +## Using a binary you already have + +Set `TREAD_BINARY` and nothing is ever downloaded: + +```sh +export TREAD_BINARY=/usr/local/bin/tread +``` + +That is the right answer for a machine with several user accounts sharing one +install, and for a CI runner with no route to the internet. If `TREAD_BINARY` +names something that is not there, the run fails — it never falls back to +downloading a second copy behind your back. + +## Other ways to install + +```sh +cargo install tread # from crates.io, builds from source +``` + +Prebuilt archives for every supported platform, and the `SHA256SUMS` this +launcher verifies against, are on the +[releases page](https://github.com/viict/tread/releases). + +## Licence + +MIT OR Apache-2.0. diff --git a/npm/bin/tread.js b/npm/bin/tread.js new file mode 100755 index 0000000..8ae6a56 --- /dev/null +++ b/npm/bin/tread.js @@ -0,0 +1,253 @@ +#!/usr/bin/env node +"use strict"; + +// The npm entry point for tread. +// +// This file is a launcher, not the program. `tread` is a Rust binary with no +// dependencies; npm carries a five-kilobyte shim that finds the right build for +// this machine, fetches it once, and hands the terminal over to it. +// +// Three rules shape everything below: +// +// * Nothing runs that was not verified. The archive's SHA-256 is checked +// against the SHA256SUMS published with the release before the file is put +// anywhere it could be executed. A download that does not match is deleted +// and the run fails loudly. +// * The binary is state, not cache. It lives under the platform's *data* +// directory, because a cache is something the OS may delete — macOS purges +// ~/Library/Caches under disk pressure — and a binary that vanishes leaves +// an offline machine unable to run tread at all. The table below mirrors +// src/plat/dirs.rs; if one changes, change both. +// * A version is a directory. Upgrading needs no invalidation logic: a new +// version writes a new directory and the old ones are pruned once the new +// binary has run. +// +// TREAD_BINARY points at a tread you already have and skips all of it, which is +// what a single global install on a multi-user machine wants, and what a locked +// down CI runner needs. It is honoured exactly: if it names something that is +// not there, the run fails rather than quietly downloading a second copy. +// +// Zero dependencies here too — only node's own https, crypto and fs, plus the +// archive reader in ../lib/unpack.js. The launcher reads the very archives the +// releases page publishes and `install.sh` verifies; the release is not asked +// to carry a second, npm-shaped copy of every binary. + +const { spawnSync } = require("child_process"); +const crypto = require("crypto"); +const fs = require("fs"); +const https = require("https"); +const os = require("os"); +const path = require("path"); + +const { extract } = require("../lib/unpack.js"); + +const VERSION = require("../package.json").version; +const REPO = "viict/tread"; +const MAX_BYTES = 32 * 1024 * 1024; +const MAX_REDIRECTS = 5; + +/// node's platform-arch pair to the Rust target its release asset is named for. +const TARGETS = { + "linux-x64": "x86_64-unknown-linux-musl", + "linux-arm64": "aarch64-unknown-linux-musl", + "darwin-x64": "x86_64-apple-darwin", + "darwin-arm64": "aarch64-apple-darwin", + "win32-x64": "x86_64-pc-windows-msvc", + "win32-arm64": "aarch64-pc-windows-msvc", +}; + +function die(message) { + console.error(`tread: ${message}`); + process.exit(1); +} + +/// Where downloaded binaries live, before the version is appended. +/// +/// An explicitly set XDG_DATA_HOME wins everywhere, including macOS: a user who +/// exports it has said where their data goes. +function dataRoot() { + const xdg = process.env.XDG_DATA_HOME; + if (xdg) { + return path.join(xdg, "tread"); + } + if (process.platform === "win32") { + // %LOCALAPPDATA%, never %APPDATA%: the roaming half of a Windows profile is + // synced to the domain server, and a machine-specific binary must not + // travel to a machine it was not built for. + const local = + process.env.LOCALAPPDATA || path.join(os.homedir(), "AppData", "Local"); + return path.join(local, "tread"); + } + if (process.platform === "darwin") { + return path.join(os.homedir(), "Library", "Application Support", "tread"); + } + return path.join(os.homedir(), ".local", "share", "tread"); +} + +function exeName() { + return process.platform === "win32" ? "tread.exe" : "tread"; +} + +/// GET `url` and buffer the body, following the redirect GitHub sends to its +/// asset store. Bounded: a body that will not fit in memory is not a release. +function get(url, redirects = 0) { + return new Promise((resolve, reject) => { + const req = https.get( + url, + { headers: { "user-agent": `tread-npm/${VERSION}` } }, + (res) => { + const { statusCode, headers } = res; + if (statusCode >= 300 && statusCode < 400 && headers.location) { + res.resume(); + if (redirects >= MAX_REDIRECTS) { + reject(new Error("too many redirects")); + return; + } + resolve(get(new URL(headers.location, url).toString(), redirects + 1)); + return; + } + if (statusCode !== 200) { + res.resume(); + reject(new Error(`HTTP ${statusCode} for ${url}`)); + return; + } + const chunks = []; + let size = 0; + res.on("data", (c) => { + size += c.length; + if (size > MAX_BYTES) { + req.destroy(); + reject(new Error("response is larger than a release could be")); + return; + } + chunks.push(c); + }); + res.on("end", () => resolve(Buffer.concat(chunks))); + } + ); + req.on("error", reject); + req.setTimeout(60_000, () => { + req.destroy(); + reject(new Error("timed out")); + }); + }); +} + +/// The SHA-256 the release published for `asset`, as lower-case hex. +/// +/// SHA256SUMS is the concatenation of `sha256sum` output, one ` ` +/// line per artifact. An asset missing from it is a release we refuse to trust, +/// not one we install anyway. +function sumFor(sums, asset) { + for (const line of sums.toString("utf8").split("\n")) { + const [hex, name] = line.trim().split(/\s+/); + if (name === asset && /^[0-9a-f]{64}$/.test(hex)) { + return hex; + } + } + return null; +} + +/// Fetch, verify and unpack the binary for this platform into `dir`. +/// +/// The write is atomic by rename from a pid-named temporary, so two first runs +/// racing each other both succeed and one of them wins the rename. No lock file +/// is needed and none is left behind if a run is killed mid-download. +async function install(dir, target) { + const win = process.platform === "win32"; + const asset = `tread-v${VERSION}-${target}${win ? ".zip" : ".tar.gz"}`; + const base = `https://github.com/${REPO}/releases/download/v${VERSION}`; + process.stderr.write(`tread: fetching ${asset}\n`); + + const [sums, packed] = await Promise.all([ + get(`${base}/SHA256SUMS`), + get(`${base}/${asset}`), + ]); + + const want = sumFor(sums, asset); + if (!want) { + throw new Error(`${asset} is not listed in SHA256SUMS`); + } + const got = crypto.createHash("sha256").update(packed).digest("hex"); + if (got !== want) { + throw new Error(`checksum mismatch for ${asset}: expected ${want}, got ${got}`); + } + + // Only now, with the archive proven to be the one the release published, is + // anything read out of it. + const binary = extract(asset, packed, exeName()); + if (!binary) { + throw new Error(`${asset} does not contain ${exeName()}`); + } + + fs.mkdirSync(dir, { recursive: true }); + const tmp = path.join(dir, `.tread-${process.pid}`); + fs.writeFileSync(tmp, binary, { mode: 0o755 }); + fs.renameSync(tmp, path.join(dir, exeName())); +} + +/// Drop every version directory but this one, once this one is known good. +function prune(root, keep) { + let entries = []; + try { + entries = fs.readdirSync(root); + } catch { + return; + } + for (const name of entries) { + if (name !== keep) { + fs.rmSync(path.join(root, name), { recursive: true, force: true }); + } + } +} + +/// Hand the terminal to the binary: stdio is inherited, so raw mode, resize and +/// the terminal's own drag-select all reach it untouched, and tread's exit code +/// is this process's exit code. +function run(bin) { + const r = spawnSync(bin, process.argv.slice(2), { stdio: "inherit" }); + if (r.error) { + die(`could not run ${bin}: ${r.error.message}`); + } + process.exit(r.status === null ? 1 : r.status); +} + +async function main() { + const override = process.env.TREAD_BINARY; + if (override) { + if (!fs.existsSync(override)) { + die(`TREAD_BINARY is set to ${override}, which does not exist`); + } + run(override); + } + + const key = `${process.platform}-${process.arch}`; + const target = TARGETS[key]; + if (!target) { + die( + `no published build for ${key}. Install from source with ` + + `\`cargo install tread\`, or point TREAD_BINARY at a tread you built.` + ); + } + + const root = dataRoot(); + const dir = path.join(root, VERSION); + const bin = path.join(dir, exeName()); + + if (!fs.existsSync(bin)) { + try { + await install(dir, target); + } catch (e) { + die( + `could not install the ${target} build: ${e.message}\n` + + ` tread was not downloaded, so nothing unverified has been run.\n` + + ` Offline or behind a proxy? Install it yourself and set TREAD_BINARY.` + ); + } + prune(root, VERSION); + } + + run(bin); +} + +main().catch((e) => die(e.message)); diff --git a/npm/lib/unpack.js b/npm/lib/unpack.js new file mode 100644 index 0000000..8559d77 --- /dev/null +++ b/npm/lib/unpack.js @@ -0,0 +1,136 @@ +"use strict"; + +// Pulling one file out of a release archive, with node's zlib and nothing else. +// +// The release publishes a `.tar.gz` per unix target and a `.zip` per Windows +// one, each holding the binary beside the README, the licences and `docs/`. +// Those archives are what `install.sh` verifies and what a person downloads by +// hand, so the npm launcher reads the same bytes rather than asking the release +// to carry a second, npm-shaped copy of every binary. +// +// node has `zlib` built in and no archive reader. Both formats are simple +// enough to walk directly: a tar is 512-byte headers each followed by its +// file's bytes, and a zip is a central directory of entries pointing at +// deflate streams `zlib.inflateRawSync` already understands. That is about a +// hundred lines here against a dependency in a package that has none — and +// against three megabytes of duplicated binary on every release. +// +// Both readers are handed an archive whose SHA-256 has *already* been checked +// against the release's `SHA256SUMS` (see `bin/tread.js`), so this code parses +// bytes that are known to be the ones the release published. It is deliberately +// strict anyway: unknown shapes return null rather than guessing, and nothing +// here writes to disk or follows a path out of the archive — the caller asks +// for one base name and gets bytes back. + +const zlib = require("zlib"); + +/// A NUL-terminated fixed-width field, as tar writes them. +function cstr(buf) { + const end = buf.indexOf(0); + return buf.toString("utf8", 0, end === -1 ? buf.length : end); +} + +/// The last path component, for either separator. +function base(name) { + const cut = Math.max(name.lastIndexOf("/"), name.lastIndexOf("\\")); + return cut === -1 ? name : name.slice(cut + 1); +} + +/// The bytes of the file named `want` inside a gzipped tar, or null. +/// +/// Only regular files are considered: type `0`, or a NUL for the pre-POSIX +/// spelling of the same thing. Every other entry — directories, long-name +/// extensions, anything unrecognised — is skipped rather than interpreted. +function fromTarGz(packed, want) { + const tar = zlib.gunzipSync(packed); + let at = 0; + while (at + 512 <= tar.length) { + const head = tar.subarray(at, at + 512); + if (head[0] === 0) { + return null; // the two zero blocks that end an archive + } + const name = cstr(head.subarray(0, 100)); + const size = parseInt(cstr(head.subarray(124, 136)).trim() || "0", 8); + if (!Number.isFinite(size) || size < 0 || at + 512 + size > tar.length) { + return null; + } + const type = head[156]; + const body = at + 512; + if ((type === 0x30 || type === 0) && base(name) === want) { + return tar.subarray(body, body + size); + } + at = body + Math.ceil(size / 512) * 512; + } + return null; +} + +/// Offset of the end-of-central-directory record, searching from the end. +/// +/// The record is 22 bytes plus a comment of up to 64 KiB, so the search window +/// is bounded by the format rather than by the file. +function endOfDirectory(buf) { + const floor = Math.max(0, buf.length - (22 + 0xffff)); + for (let at = buf.length - 22; at >= floor; at--) { + if (buf.readUInt32LE(at) === 0x06054b50) { + return at; + } + } + return -1; +} + +/// The bytes of the file named `want` inside a zip, or null. +/// +/// Stored (method 0) and deflated (method 8) entries are read; anything else is +/// skipped. Sizes come from the central directory, which is authoritative even +/// when the local header defers them to a data descriptor. +function fromZip(buf, want) { + const eocd = endOfDirectory(buf); + if (eocd === -1) { + return null; + } + const count = buf.readUInt16LE(eocd + 10); + let at = buf.readUInt32LE(eocd + 16); + for (let i = 0; i < count; i++) { + if (at + 46 > buf.length || buf.readUInt32LE(at) !== 0x02014b50) { + return null; + } + const method = buf.readUInt16LE(at + 10); + const packed = buf.readUInt32LE(at + 20); + const nameLen = buf.readUInt16LE(at + 28); + const extraLen = buf.readUInt16LE(at + 30); + const commentLen = buf.readUInt16LE(at + 32); + const local = buf.readUInt32LE(at + 42); + const name = buf.toString("utf8", at + 46, at + 46 + nameLen); + if (base(name) === want && (method === 0 || method === 8)) { + return inflateAt(buf, local, packed, method); + } + at += 46 + nameLen + extraLen + commentLen; + } + return null; +} + +/// Read one entry's data, given where its *local* header sits. The local +/// header repeats the name and extra fields at its own lengths, which are the +/// only way to know where the data starts. +function inflateAt(buf, local, packed, method) { + if (local + 30 > buf.length || buf.readUInt32LE(local) !== 0x04034b50) { + return null; + } + const nameLen = buf.readUInt16LE(local + 26); + const extraLen = buf.readUInt16LE(local + 28); + const from = local + 30 + nameLen + extraLen; + if (from + packed > buf.length) { + return null; + } + const raw = buf.subarray(from, from + packed); + return method === 0 ? raw : zlib.inflateRawSync(raw); +} + +/// Pull `want` out of whichever archive shape `asset` names. +function extract(asset, bytes, want) { + return asset.endsWith(".zip") + ? fromZip(bytes, want) + : fromTarGz(bytes, want); +} + +module.exports = { extract, fromTarGz, fromZip }; diff --git a/npm/package.json b/npm/package.json new file mode 100644 index 0000000..005fe28 --- /dev/null +++ b/npm/package.json @@ -0,0 +1,34 @@ +{ + "name": "@viict/tread", + "version": "0.3.0", + "private": false, + "description": "A terminal reader for markdown, CSV, JSON and source code. Zero dependencies.", + "keywords": [ + "pager", + "markdown", + "csv", + "json", + "terminal", + "less", + "cli" + ], + "homepage": "https://github.com/viict/tread#readme", + "repository": { + "type": "git", + "url": "git+https://github.com/viict/tread.git" + }, + "bugs": "https://github.com/viict/tread/issues", + "license": "MIT OR Apache-2.0", + "type": "commonjs", + "bin": { + "tread": "bin/tread.js" + }, + "files": [ + "bin/tread.js", + "lib/unpack.js", + "README.md" + ], + "engines": { + "node": ">=16" + } +}