ply
Zero-dependency git smart-HTTP client that edits one file in a remote repo in O(1) memory and pushes the change as a delta. Runs anywhere with fetch, CompressionStream, crypto.getRandomValues and Uint8Array (Node ≥ 20, Workers, browsers behind a CORS proxy).
Every byte and every roundtrip is recorded as an OTLP span. The test suite is a property/fuzz harness that uses real git as the oracle and the spans as the coverage map that steers generation.
The hosted HTTP API and the public repository viewer live in ply-web (the Cloudflare Worker ply). This repository is the git client.
Install
ply is not on npm (the npm name ply belongs to another package). Install it from GitHub; npm builds dist/ on install:
npm install github:ivarvong/ply # the default branch, as of now
npm install github:ivarvong/ply#<commit-sha> # recommended: pin a commit for reproducible buildsIt installs as ply, so imports read from 'ply' and from 'ply/<subpath>' (ply/edit, ply/read, ply/tree, ply/checkout-node, …). Types ship with it (dist/*.d.ts); JavaScript and TypeScript use the same calls.
ply is ESM-only: there is no CommonJS build and no require export condition. The Node floor is 20 (engines.node is >=20; all 19 entry points import on 20.17.0). From a CommonJS file, await import('ply') works on every supported Node. require('ply') depends on the Node version: it works where Node loads an ES module with require() by default, which is Node 20.19.0 and later on the 20 line (Node's changelog for 20.19.0: "require(esm) is now enabled by default"; measured on 20.19.0 and 20.20.2) and Node 22.12 and later (measured on 22.15.0, 24.2.0, 24.16.0, 24.18.0 and 25.2.1). Before that it throws ERR_REQUIRE_ESM: on Node 20.18 and earlier (measured on 20.17.0, 20.18.0 and 20.18.3) and on Node 22 before 22.12 (Node's documented boundary, not measured here). CI job pack packs the tarball, installs it with --ignore-scripts into an empty project, and checks every import and this require() behaviour under Node 20, 22 and 24 (npm run check:pack, test/pack-install.test.js).
The git install above needs the package manager to run ply's prepare script: dist/ is not in git, and prepare builds it (npm first installs ply's dev tools in a temporary clone). Not every package manager runs it, and none of them fails when it does not run. Measured in an empty project at commit 77048fb:
| package manager | default | --ignore-scripts |
|---|---|---|
| npm 11.16.0 | builds dist/; imports work | exits 0, no dist/ |
| pnpm 8.15.9 | builds dist/; imports work; installs the whole repository (7.8 MB), where npm installs files only (1.7 MB) | exits 0 with the warning has to be built but the build scripts were ignored, no dist/ |
| yarn 1.22.22 | exits 0 without running prepare, no dist/ | exits 0, no dist/ |
| bun 1.2.18 | exits 0 with Blocked 1 postinstall, no dist/; bun pm trust ply then fails (tsc: command not found) | exits 0, no dist/ |
With no dist/, every import fails with ERR_MODULE_NOT_FOUND. So the git install works with npm and with pnpm 8, scripts on; it does not work with yarn 1 or bun 1.2, or with scripts off. pnpm, yarn and bun were given github:ivarvong/ply#<sha>, npm a local clone of the same commit (git+file://); pnpm 9 and later and yarn 2 and later were not measured. The packed tarball contains dist/ and installs with scripts off (measured with npm; CI job pack). CI uploads it as the workflow artifact ply-tarball, which needs a GitHub login and expires; there is no install URL for it yet.
Beta
ply is pre-1.0 (0.2.0). The API can change between commits without a deprecation period, and there are no tagged releases yet: pin a commit sha, read the commit log before moving the pin, and let your type checker or tests catch a changed signature. Span names and attributes are a stated contract (see Telemetry contract).
Requirements
- Runtime: Node ≥ 20, Cloudflare Workers, or any runtime with
fetch,CompressionStream/DecompressionStream,crypto.getRandomValuesandUint8Array(a browser works behind a CORS proxy).ply/tree-node,ply/checkout-nodeandply/repo-nodeare Node only (node:fs). - TypeScript (optional): the shipped declarations compile with
skipLibCheck: falseunderlib: ["ES2022"]with@types/node20, 22 or 24, under theDOMlib, and under@cloudflare/workers-types.npm run check:distandtest/dist-types.test.jscompile each of those five consumers (pinned:@types/node20.19.43, 22.20.5 and 24.19.2,@cloudflare/workers-types5.20260916.1, TypeScript 7.0.2,nodenextresolution) and fail when a type package is missing; none is skipped. They need the web globals one of those provides (ReadableStream,Response,AbortSignal,URL);lib: ["ES2022"]with no types package is not enough. - A git smart-HTTP server: GitHub, GitLab, Gitea/Forgejo, Cloudflare Artifacts, or self-hosted
git http-backend(http.receivepack trueto push; nothing else). A stock git server works: withoutuploadpack.allowFilterits advertisement has nofilter, and ply learns that from the server (quirks.treeFilter = 'none', learned once per remote: see the Artifacts notes below) and fetches unfiltered: the same results, with more bytes per read. The quick start below runs on both. ply speaks protocol v2 for reads and receive-pack for pushes; SHA-1 repositories only. A server that answers only v0/v1 is refused asunsupported(what: 'protocol version') on the first ls-refs. - Auth, per call in
opts.auth:{ token }(HTTP Basic with userx-access-token, which GitHub tokens use),{ token, user }(a host that wants a username: GitLaboauth2for an OAuth token, your Gitea/Forgejo user),{ bearer }, or{ header }(anAuthorizationvalue sent as is). Or userinfo in the URL (https://<token>@host/…), sent as git sends it. Noauthand no userinfo: anonymous. Credentials never reach a span or an error message; redirects are not followed. Details in "Credentials" under More detail.
What ply does not do: create or delete repositories (that is the host's API, or git init --bare on your server: ply needs one to exist, empty or not); SSH transport (removed; HTTPS only); Git LFS content (an LFS pointer is refused by edits, see Guards); pull requests, issues or any other host API object; a working tree or index (there is no clone: every call reads what it needs over the wire).
Quick start: a repo end to end
Every call takes (url, spec, opts) (opts is optional: auth, limits, signal, and tracer, a new Tracer({ exporter }) to export spans; without one they are dropped), and returns a Result: { ok: true, value } or { ok: false, error }, never a throw. The blocks below run in order against one repository that starts empty (they are executed as written, against git http-backend with and without uploadpack.allowFilter, by test/e2e-customer.test.js, and type-checked as TypeScript by test/types/readme.typetest.ts). A ref that is written is a full name (refs/heads/main; a tag's name may be short); a ref that is only read (readCommit's ref, createBranch's from, createTag's target) may also be a short name (main, v1.3.0) or a commit id.
// quick-start: setup
const url = 'https://git.example.com/acme/site.git'; // an existing repository, empty or not
const opts = { auth: { token: process.env['GIT_TOKEN'] } }; // add tracer: new Tracer({ exporter }) to export spans
const author = { name: 'Release Bot', email: 'bot@example.com' }; // time defaults to now, tz to +0000
const outDir = './site-checkout'; // checkoutDir writes here; it must be absent or emptyFirst commit into an empty repository. pushTree commits exactly files as the tree. A branch that does not exist yet is created as a root commit.
// quick-start: first-commit
import { pushTree } from 'ply';
const first = await pushTree(url, {
ref: 'refs/heads/main',
files: {
'README.md': '# site\n',
'src/config.ts': 'export const VERSION = "1.2.3";\n',
'bin/build': { data: '#!/bin/sh\necho build\n', mode: '100755' },
},
author, message: 'Initial commit',
}, opts);
if (!first.ok) throw first.error;
console.log(first.value.newCommit); // the commit id main now points atRead a commit, a directory, and a file (streamed, hash-checked as it is read).
// quick-start: read
import { readCommit, listTree, readFile } from 'ply';
const head = await readCommit(url, { ref: 'main' }, opts);
if (!head.ok) throw head.error;
if ('empty' in head.value) throw new Error('main has no commits yet');
console.log(head.value.oid, head.value.tree, head.value.parents, head.value.message);
const listing = await listTree(url, { ref: 'main', path: 'src' }, opts);
if (!listing.ok) throw listing.error;
for (const e of listing.value.entries) console.log(e.mode, e.type, e.oid, e.name); // as git ls-tree prints them
const file = await readFile(url, { ref: 'main', path: 'src/config.ts' }, opts);
if (!file.ok) throw file.error;
const config = await new Response(file.value.stream).text(); // read the stream to the end (or cancel it)
console.log(file.value.size, config);Edit one file: find exactly one occurrence and replace it. The blob streams through; the push is a delta.
// quick-start: edit
import { editFile } from 'ply';
const bump = await editFile(url, {
ref: 'refs/heads/main', path: 'src/config.ts',
find: 'VERSION = "1.2.3"', replace: 'VERSION = "1.2.4"',
author, message: 'Bump version to 1.2.4',
}, opts);
if (!bump.ok) throw bump.error; // match_count when find is not there exactly once
console.log(bump.value.newCommit, bump.value.noop); // noop: find === replace, nothing pushedSeveral changes in one commit, applied in order.
// quick-start: commit-changes
import { commitChanges } from 'ply';
const change = await commitChanges(url, {
ref: 'refs/heads/main',
changes: [
{ kind: 'create', path: 'docs/intro.md', content: '# Intro\n' }, // refuses a path that exists
{ kind: 'write', path: 'README.md', content: '# site\n\nHello.\n' }, // creates or overwrites
{ kind: 'edit', path: 'src/config.ts', find: '1.2.4', replace: '1.3.0' }, // exactly one match
{ kind: 'delete', path: 'bin/build' }, // a file or a whole directory
{ kind: 'rename', from: 'docs/intro.md', to: 'docs/index.md' },
],
author, message: 'Docs; version 1.3.0',
}, opts);
if (!change.ok) throw change.error;
console.log(change.value.outcome, change.value.oid); // 'commit', or 'noop' when the tree did not changeBranches: create one at a commit (a ref name or a 40-hex commit id), commit to it, merge it back. mergeBranch fast-forwards when it can and otherwise writes a merge commit (git's merge-ort result for clean merges; merge_conflict with the paths otherwise).
// quick-start: branch-merge
import { createBranch, mergeBranch } from 'ply';
const feature = await createBranch(url, { ref: 'refs/heads/feature', from: 'main' }, opts);
if (!feature.ok) throw feature.error; // cas_conflict when the branch already exists
const work = await commitChanges(url, {
ref: 'refs/heads/feature',
changes: [{ kind: 'create', path: 'src/feature.ts', content: 'export const feature = true;\n' }],
author, message: 'Add feature flag',
}, opts);
if (!work.ok) throw work.error;
const hotfix = await editFile(url, { // main moves on meanwhile
ref: 'refs/heads/main', path: 'README.md', find: 'Hello.', replace: 'Hello, world.', author, message: 'Fix greeting',
}, opts);
if (!hotfix.ok) throw hotfix.error;
const merged = await mergeBranch(url, { ref: 'refs/heads/main', from: 'refs/heads/feature', author }, opts);
if (!merged.ok) throw merged.error;
console.log(merged.value.outcome, merged.value.oid); // 'merge': a commit with parents [main, feature]Tags: lightweight (the ref names the commit) or annotated (a tag object with a tagger and message).
// quick-start: tag
import { createTag } from 'ply';
const release = await createTag(url, { name: 'v1.3.0', target: 'refs/heads/main' }, opts);
if (!release.ok) throw release.error;
const notes = await createTag(url, { name: 'v1.3.0-notes', target: release.value.commit, message: 'Release 1.3.0', tagger: author }, opts);
if (!notes.ok) throw notes.error;
console.log(notes.value.oid, notes.value.commit); // the tag object, and the commit it namesRebase, cherry-pick, revert. Each replays commits with the same three-way merge and pushes with the old tip as the compare-and-swap.
// quick-start: rebase-pick-revert
import { rebaseBranch, cherryPick, revertCommit } from 'ply';
const topic = await createBranch(url, { ref: 'refs/heads/topic', from: 'refs/heads/main' }, opts);
if (!topic.ok) throw topic.error;
const onTopic = await commitChanges(url, { ref: 'refs/heads/topic', changes: [{ kind: 'create', path: 'src/topic.ts', content: 'export const topic = 1;\n' }], author, message: 'Add topic' }, opts);
if (!onTopic.ok) throw onTopic.error;
const onMain = await commitChanges(url, { ref: 'refs/heads/main', changes: [{ kind: 'create', path: 'CHANGELOG.md', content: '1.3.0\n' }], author, message: 'Changelog' }, opts);
if (!onMain.ok) throw onMain.error;
const rebased = await rebaseBranch(url, { ref: 'refs/heads/topic', onto: 'refs/heads/main', committer: author }, opts);
if (!rebased.ok) throw rebased.error; // topic's commits replayed onto main's tip
const picked = await cherryPick(url, { ref: 'refs/heads/main', commit: rebased.value.oid, committer: author }, opts);
if (!picked.ok) throw picked.error; // outcome 'ok', or 'empty' when main already has the change (nothing written)
const reverted = await revertCommit(url, { ref: 'refs/heads/main', commit: picked.value.oid, committer: author }, opts);
if (!reverted.ok) throw reverted.error; // a 'Revert "Add topic"' commit on mainHistory, first parent, newest first (git log --first-parent).
// quick-start: history
import { readLog } from 'ply';
const log = await readLog(url, { ref: 'refs/heads/main', limit: 10 }, opts);
if (!log.ok) throw log.error;
for (const c of log.value.commits) console.log(c.oid.slice(0, 7), c.parents.length, c.message.split('\n')[0]);Check out a whole tree: as streams (Workers-safe), or into a directory (Node, laid out as git clone would, without .git).
// quick-start: checkout
import { checkoutTree } from 'ply';
import { checkoutDir } from 'ply/checkout-node';
const tree = await checkoutTree(url, { ref: 'v1.3.0' }, opts);
if (!tree.ok) throw tree.error;
for await (const f of tree.value.files) {
if (f.stream) console.log(f.path, f.mode, (await new Response(f.stream).arrayBuffer()).byteLength); // read each stream
}
const written = await checkoutDir(url, { dir: outDir, ref: 'main' }, opts);
if (!written.ok) throw written.error;
console.log(written.value.written.files); // files written under outDirDelete a branch. Without expected the tip ls-refs reports is the compare-and-swap; with expected: '<oid>' the delete happens only from that tip. The branch the remote's HEAD names is refused by the server (push_rejected).
// quick-start: refs
import { listRefs, deleteBranch, deleteTag } from 'ply';
const refs = await listRefs(url, {}, opts); // branches and tags; { prefixes: ['refs/heads/'] } for branches only
if (!refs.ok) throw refs.error;
console.log(refs.value.head, refs.value.refs.map(r => r.name)); // 'refs/heads/main', [ 'refs/heads/feature', … ]
const gone = await deleteBranch(url, { ref: 'refs/heads/feature', expected: work.value.oid }, opts);
if (!gone.ok) throw gone.error; // cas_conflict when feature moved off that commit; not_found when it is gone
const untagged = await deleteTag(url, { name: 'v1.3.0-notes' }, opts);
if (!untagged.ok) throw untagged.error;Errors. error.code is a closed union, so a switch with assertNever in default is checked exhaustive by TypeScript (a new code in ply fails your build, not your users). What to do with each:
// quick-start: errors
import { assertNever } from 'ply';
const stale = await editFile(url, {
ref: 'refs/heads/main', path: 'src/config.ts', find: 'VERSION = "9.9.9"', replace: 'VERSION = "10.0.0"', author, message: 'Bump',
}, opts);
if (!stale.ok) {
const e = stale.error;
switch (e.code) {
case 'cas_conflict': // the ref moved between read and push (editFile already redid it once): read again, redo
console.warn('moved', e.expected, e.actual); break;
case 'match_count': // find matched e.matches times, not once: the file is not what you expected
console.warn('matches', e.matches); break;
case 'not_found': // e.miss.kind: 'ref' | 'path' | 'repository' | 'head_unborn' | 'commit' | …
console.warn('missing', e.miss.kind); break;
case 'auth': // 401/403: the credential is missing, wrong, or lacks write access
console.warn('auth'); break;
case 'limit_exceeded': // a limits.* bound (e.what, e.got, e.max): raise it with withLimits, or do less per call
console.warn('limit', e.what, e.got, e.max); break;
case 'ambiguous': // the push was sent and may have landed: read the ref back before doing anything else
console.warn('unknown outcome'); break;
case 'network': case 'timeout': case 'rate_limited': case 'upstream_5xx': case 'protocol': case 'pack_corrupt':
console.warn('transient: retry with backoff', e.code); break; // isRetryable(e) is true for exactly these
case 'merge_conflict': case 'not_fast_forward': case 'not_linear': case 'unrelated_histories':
console.warn('history needs a human', e.code); break;
case 'push_rejected': case 'push_partial': case 'remote_error': // a hook, branch protection, or the server said no
console.warn('refused', e.message); break;
case 'bad_request': case 'unsupported': case 'lfs_pointer': case 'http': case 'not_git': case 'aborted': case 'internal':
console.warn('fix the call or the setup', e.code, e.message); break;
default:
assertNever(e);
}
}retryPolicy(error) gives the same advice as data (yes, fresh, read, no), and CODE_DOCS[code] a one-line description. Every option an entry takes is in its section below.
More detail
inflate(buf, pos = 0, opts) reads the zlib member at buf[pos..] and reports the bytes it consumed. pos is a position in buf: a non-negative safe integer no greater than buf.length (at the very end there are no bytes, so the member is cut: pack_corrupt). Any other value (negative, fractional, NaN, past the end, a string) is bad_request before a byte is read; it used to be passed to subarray, which reads a negative offset from the end of the buffer, and NaN threw.
Sha1 is an incremental hasher: update(bytes) any number of times, and digest() (20 bytes) or hex() (an Oid) is a snapshot of the bytes fed so far. It leaves the hasher as it was, so it can be called repeatedly (same input, same value) and update() may continue afterwards, which is what a running pack checksum needs. A second digest() used to return the hash of the message plus its padding. streamingSha1().hex() may also be awaited more than once (the same value); on Workers it ends the native DigestStream, so there an update after hex() rejects.
resolvePack(parsed, external, limits) resolves every delta of a parsed pack (parsePack's value, or { objects } built by hand) and returns { objects, stats }. objects is a Map from id to object, and its iteration order promises one thing: every base that is in the pack comes before the objects built on it (an id the pack holds twice has the place of the copy that …