@coderook/cli 0.49.0 → 0.50.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -2,7 +2,7 @@
2
2
  "name": "coderook",
3
3
  "displayName": "CodeRook",
4
4
  "description": "Save, browse and restore whole-snapshot versions of a project on CodeRook, with cbx or plain git, from Claude Code.",
5
- "version": "0.49.0",
5
+ "version": "0.50.0",
6
6
  "author": {
7
7
  "name": "ACCA Gaming Productions",
8
8
  "url": "https://coderook.com"
package/README.md CHANGED
@@ -23,7 +23,7 @@ That is why the names do not match everywhere, and the mismatch is on purpose:
23
23
  | --- | --- |
24
24
  | `cbx …` | the tool — what you type |
25
25
  | `coderook.com`, `@coderook/cli` | the service, and the package it ships in |
26
- | `coderook://project` | a remote URL, which names the host it points at |
26
+ | `https://coderook.com/<owner>/<project>.git` | a project's git address, which names the host it points at |
27
27
  | `CODEROOK_TOKEN`, `%APPDATA%\CodeRook` | credentials for a CodeRook account |
28
28
 
29
29
  It uses the same engines as the desktop application — the same scanner, the
@@ -350,7 +350,8 @@ becomes a version and every branch a line, so it takes a while on a long
350
350
  history — the commit count and an estimate are printed before it starts.
351
351
 
352
352
  **It goes through the public route on purpose.** The history is published by
353
- running `git push` against the CodeRook remote, exactly as you would by hand.
353
+ plain git pushes to the project's git address, exactly as `git push` does
354
+ after `coderook git setup`, and commit ids arrive unchanged.
354
355
  A transfer that used a private path would prove only that a private path
355
356
  exists.
356
357
 
@@ -374,74 +375,64 @@ the absence to be discovered later.
374
375
 
375
376
  ## Using git instead
376
377
 
377
- Installing the CLI also installs `git-remote-coderook`, so git talks to
378
- CodeRook directly — both ways:
378
+ CodeRook speaks plain git, so every project has a git address and git works
379
+ with it as with any host — no plugin, no special remote:
379
380
 
380
381
  ```
381
- git clone coderook://my-project # the remote is called origin
382
- git remote add coderook coderook://my-project # or add it to a repository you have
383
- git push coderook main
384
- git fetch coderook
382
+ git clone https://coderook.com/<owner>/<project>.git
383
+ git pull
384
+ git push
385
385
  ```
386
386
 
387
- If your folder is a git repository, use this rather than `cbx submit`: each
388
- commit arrives with its own message, and every editor's built-in git panel
389
- works with CodeRook without a plugin. `cbx submit` is the tool for folders
390
- that are not git repositories. The helper is installed by
391
- `npm install --global @coderook/cli`; the Claude Code plugin and `npx` do not
392
- put it on your `PATH`.
393
-
394
- **A project you started with `cbx submit`.** Its saves did not come from git,
395
- so the first push from your repository is refused rather than replaying your
396
- history on top of them. If the repository holds that project, adopt it once:
387
+ Without this package, sign in with a CodeRook access token as the password
388
+ (any username). With it, run this once:
397
389
 
398
390
  ```
399
- git push -o adopt coderook main
391
+ coderook git setup
400
392
  ```
401
393
 
402
- The project's saves stay as they are, your current commit is saved on top as
403
- one save, and from then on every push sends one save per commit. Or start
404
- from the project instead: `git clone coderook://my-project` and carry on in
405
- the clone.
394
+ and git signs in with this machine's CodeRook sign-in, and **a push of any
395
+ size works**. Cloudflare, in front of CodeRook, refuses any single request
396
+ over 100 MB, and plain git sends a whole push as one request; after setup a
397
+ push goes as plain git while it fits, and past that its large files go beside
398
+ it in pieces (only the pieces CodeRook does not hold already) and a long
399
+ history goes in steps. Either way the commits arrive exactly as git made them:
400
+ the commit ids on CodeRook are the ones on your machine.
401
+
402
+ `coderook git undo` takes it out again. It only touches git's settings for
403
+ CodeRook's own addresses.
404
+
405
+ Use whichever suits the folder, and mix them on one project: a save made with
406
+ `cbx submit` arrives in `git pull` as a commit, and a commit pushed with git
407
+ arrives in `cbx get` as a save.
408
+
409
+ **A project you started with `cbx submit`.** Its saves did not come from your
410
+ git repository, so bring them in once before the first push, as you would
411
+ with any host that already holds work:
412
+
413
+ ```
414
+ git remote add coderook https://coderook.com/<owner>/<project>.git
415
+ git pull coderook main --allow-unrelated-histories
416
+ git push coderook main
417
+ ```
406
418
 
407
- **Pushing.** Each commit becomes a version, oldest first, with its message
408
- kept. Later pushes send only what is new, so the usual case — a few commits —
409
- is quick; a first push of a long history is not, and the helper says how many
410
- commits it is about to publish before it starts. Branches become lines, and a
411
- branch pushed for the first time starts from the commit it forked at rather
412
- than from wherever the project happens to be.
419
+ Or start from the project instead: `git clone` it and carry on in the clone.
413
420
 
414
- **Cloning and fetching.** Every version becomes a commit, keeping its message,
415
- its date and who published it. This works on any project, including one that
416
- has never been near git — a project built entirely with `cbx submit`
417
- clones into a normal git history. A fetch only downloads versions this clone
418
- does not already have.
421
+ **Pushing.** Each new commit becomes a version on the line its branch names,
422
+ with its message kept, and its commit id unchanged. A branch pushed for the
423
+ first time becomes a line. A push is refused with "fetch first" when the line
424
+ has moved on since you pulled, as any git host refuses it.
419
425
 
420
426
  **What it does not do:**
421
427
 
422
428
  | | |
423
429
  | --- | --- |
424
- | Tag kind | A lightweight tag comes back annotated. CodeRook records a name, not which sort of tag made it. |
430
+ | Tags | Refused: CodeRook names a version with a release. Use `cbx release v1.0`, or the website. `cbx transfer` turns a repository's tags into releases for you. |
425
431
  | Force pushes, branch deletion | Refused — versions are immutable, so there is nothing to rewind to. |
426
- | Submodules | Skipped on push, and it says which paths. |
427
- | The executable bit | Kept: a script pushed as `100755` clones back executable, with `cbx clone` and `git clone` alike. Versions saved before 0.33 recorded every file as not executable. |
428
-
429
- **On round trips.** Push then clone gives you back the same *files*, not the
430
- same *commit ids*. A commit id covers its author, committer and timestamps,
431
- and CodeRook records who published a version rather than the original stamps —
432
- so the history you get back is a faithful copy of the contents and an honest
433
- approximation of the commits. Two people cloning the same project do get
434
- identical ids as each other.
435
-
436
- Merges are asymmetric for the same reason. A publish states one base version,
437
- so pushing a git merge records one parent and the fork is lost — the merged
438
- tree is exact, the shape is not. Reading back is richer: a version that really
439
- has two parents is rebuilt as a real git merge.
440
-
441
- Each version records the commit it came from, so a colleague pushing the same
442
- project does not republish history the project already holds. Pushing a git
443
- history into a project whose versions came from somewhere else is refused
444
- rather than interleaved, unless you adopt it with `-o adopt` as above.
432
+ | Submodules, symbolic links | Refused, naming the path: CodeRook stores files. |
433
+
434
+ `coderook://` remotes from CLI versions before 0.50 are retired. A fetch
435
+ through one prints the command that moves it to the plain git address.
445
436
 
446
437
  ### The names are the same
447
438
 
@@ -461,45 +452,28 @@ names still work and mean the same thing. The one exception is a folder with
461
452
  a history of its own (`cbx init`): there `log`, `switch`, `merge`, `push`
462
453
  and `pull` work on that history.
463
454
 
464
- That is also what the git remote does. `git push` performs the operation
465
- `cbx push` performs — the same code decides what changed, the same code
466
- publishes it. The remote is a way to reach these commands from git, not a
467
- second implementation of them that happens to agree.
468
-
469
455
  **What does not appear on that list**, because git has no such idea and
470
456
  inventing one would be pretending: `projects`, `delete`, `people`, `watch`,
471
457
  `issues`, `propose`, `proposals`, `actions`, `runs`, `logs`, `runner`,
472
458
  `tokens`, `licence`, `ai`. Use
473
459
  them by name; nothing about them changes when a version arrives through git.
474
460
 
475
- `git commit` has no CodeRook equivalent either, and should not: it is local to
476
- git, and a version is not made until something is published.
461
+ ### Releases
477
462
 
478
- ### Tags and releases
479
-
480
- `git push --tags` publishes each tag as a release, because that is the same
481
- statement in the other vocabulary — the service puts it plainly: *"a release
482
- is a Version with a name on it, not a different kind of object."*
463
+ A release is a version with a name on it, not a different kind of object:
483
464
 
484
465
  ```
485
- git tag -a v1.0 -m "First stable release"
486
- git push coderook v1.0
466
+ cbx release v1.0
467
+ cbx notes 41 --edit
487
468
  ```
488
469
 
489
- The tag names the version its commit already became; it does not publish
490
- anything, so push the branch first. An annotated tag's message becomes the
491
- release notes and a lightweight tag brings none — the commit's own message is
492
- deliberately *not* used, since nobody wrote it about the release.
493
-
494
- Cloning reverses it: every release comes back as a tag on the right commit.
495
-
496
- From the command line, `cbx release v1.0` names the newest save the same way,
497
- and `cbx notes 41 --edit` writes its release notes.
470
+ `cbx release v1.0` names the newest save, and `cbx notes 41 --edit` writes its
471
+ release notes.
498
472
 
499
473
  Assets are separate and unaffected. They attach to a version from a run's
500
- artifacts or with `cbx attach <file>`, so a release made by pushing a tag
501
- simply has none until something adds them — which is what a release without a
502
- build has always looked like.
474
+ artifacts or with `cbx attach <file>`, so a release simply has none until
475
+ something adds them — which is what a release without a build has always
476
+ looked like.
503
477
 
504
478
  ## Actions
505
479
 
@@ -44,6 +44,7 @@ const issue_command_js_1 = require("./issue_command.js");
44
44
  const verify_command_js_1 = require("./verify_command.js");
45
45
  const community_command_js_1 = require("./community_command.js");
46
46
  const pr_command_js_1 = require("./pr_command.js");
47
+ const git_setup_js_1 = require("./git_setup.js");
47
48
  const settings_commands_js_1 = require("./settings_commands.js");
48
49
  const project_commands_js_1 = require("./project_commands.js");
49
50
  const track_commands_js_1 = require("./track_commands.js");
@@ -925,7 +926,7 @@ async function commandImport(parsed) {
925
926
  function noteGitRoute(folder, slug) {
926
927
  try {
927
928
  const config = (0, node_fs_1.readFileSync)(node_path_1.default.join(folder, ".git", "config"), "utf8");
928
- if (/coderook:/.test(config))
929
+ if (/coderook:|coderook\.com/.test(config))
929
930
  return;
930
931
  }
931
932
  catch {
@@ -933,8 +934,9 @@ function noteGitRoute(folder, slug) {
933
934
  }
934
935
  const name = slug ?? "<project>";
935
936
  console.log(dim("This is a git repository. To save each commit with its message instead of snapshots: ") +
936
- accent(`git remote add coderook coderook://${name}`) + dim(" then ") +
937
- accent("git push -o adopt coderook main") + dim(" once, and plain git push after."));
937
+ accent("coderook git setup") + dim(", ") +
938
+ accent(`git remote add coderook https://coderook.com/<your-name>/${name}.git`) + dim(", ") +
939
+ accent("git pull coderook main --allow-unrelated-histories") + dim(" once, then plain git push."));
938
940
  }
939
941
  /** A file's SHA-256, streamed; null when it cannot be read. */
940
942
  async function digestOfFile(full) {
@@ -4616,6 +4618,21 @@ const SPECS = [
4616
4618
  examples: ["cbx doctor"],
4617
4619
  run: () => commandDoctor(),
4618
4620
  },
4621
+ {
4622
+ name: "git",
4623
+ group: "Getting started",
4624
+ summary: "set git up for CodeRook: sign-in, and pushes of any size",
4625
+ usage: "git setup|undo",
4626
+ detail: "CodeRook speaks plain git: git clone https://coderook.com/<owner>/<project>.git\n" +
4627
+ "works anywhere, with an access token as the password. `coderook git setup`\n" +
4628
+ "makes it seamless: git signs in with this machine's CodeRook sign-in, and\n" +
4629
+ "pushes to CodeRook send large files beside the push, in pieces, so a push\n" +
4630
+ "is never refused for size. Commit ids stay exactly the ones git made.\n" +
4631
+ "Only git's settings for CodeRook's own addresses change; `coderook git undo`\n" +
4632
+ "takes them out again.",
4633
+ examples: ["coderook git setup", "coderook git undo"],
4634
+ run: parsed => (0, git_setup_js_1.commandGit)(parsed.positional[0], parsed.positional[1]),
4635
+ },
4619
4636
  ];
4620
4637
  /*
4621
4638
  `push` and `pull` mean the local history in a folder that has one, and
@@ -0,0 +1,346 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.remoteRefs = remoteRefs;
4
+ exports.bridgePush = bridgePush;
5
+ /**
6
+ * Pushing to CodeRook over git with no size limit.
7
+ *
8
+ * Plain git over HTTPS works with CodeRook as it does with any host, except
9
+ * that Cloudflare, in front of the service, refuses any request body over
10
+ * 100 MB, and git sends a whole push as one request. So this sends a push
11
+ * the way git would, with one difference: each file of `bigBytes` or more
12
+ * goes first, in pieces cut the way cbx cuts them (only the pieces the
13
+ * project lacks), and is declared by its git id (backend/src/git/bridge.ts).
14
+ * The push itself then carries everything else, the commits and trees
15
+ * exactly as git made them, so commit ids never change and a clone over
16
+ * plain git gets the very commits that were pushed.
17
+ *
18
+ * Git hands a push here because `coderook git setup` points pushes to
19
+ * CodeRook at this helper (git-remote-coderook, git_remote.ts). Fetches and
20
+ * clones never come here: they are plain git.
21
+ */
22
+ const node_child_process_1 = require("node:child_process");
23
+ const node_crypto_1 = require("node:crypto");
24
+ const chunking_js_1 = require("../../cbx/src/shared/chunking.js");
25
+ const ZERO = "0".repeat(40);
26
+ const encoder = new TextEncoder();
27
+ const decoder = new TextDecoder();
28
+ /* What one request of pieces may carry; the service takes up to 48 MiB. */
29
+ const BATCH_BYTES = 40 * 1024 * 1024;
30
+ function git(args, cwd, input) {
31
+ const result = (0, node_child_process_1.spawnSync)("git", args, { cwd, input, maxBuffer: 1024 * 1024 * 1024, windowsHide: true });
32
+ if (result.status !== 0)
33
+ throw new Error(`git ${args[0]} failed: ${String(result.stderr ?? "").trim() || `exit ${result.status}`}`);
34
+ return result.stdout;
35
+ }
36
+ /* Runs git and collects what it writes; null as soon as that passes `most` bytes, and git is stopped. */
37
+ function gitStream(args, cwd, input, most) {
38
+ return new Promise((done, fail) => {
39
+ const child = (0, node_child_process_1.spawn)("git", args, { cwd, windowsHide: true });
40
+ const parts = [];
41
+ let size = 0;
42
+ let over = false;
43
+ let err = "";
44
+ child.stdout.on("data", (d) => {
45
+ if (over)
46
+ return;
47
+ size += d.length;
48
+ if (size > most) {
49
+ over = true;
50
+ parts.length = 0;
51
+ child.kill();
52
+ return;
53
+ }
54
+ parts.push(d);
55
+ });
56
+ child.stderr.on("data", (d) => (err += d));
57
+ child.on("error", fail);
58
+ child.stdin.on("error", () => undefined);
59
+ child.on("close", (code) => {
60
+ if (over)
61
+ done(null);
62
+ else if (code === 0)
63
+ done(Buffer.concat(parts));
64
+ else
65
+ fail(new Error(`git ${args[0]} failed: ${err.trim() || `exit ${code}`}`));
66
+ });
67
+ child.stdin.end(input);
68
+ });
69
+ }
70
+ function pkt(text) {
71
+ const body = encoder.encode(text);
72
+ const out = new Uint8Array(body.length + 4);
73
+ out.set(encoder.encode((body.length + 4).toString(16).padStart(4, "0")));
74
+ out.set(body, 4);
75
+ return out;
76
+ }
77
+ /* Every pkt-line in `bytes` from `at`; a flush is an empty entry. */
78
+ function pktLines(bytes) {
79
+ const out = [];
80
+ let at = 0;
81
+ while (at + 4 <= bytes.length) {
82
+ const size = parseInt(decoder.decode(bytes.subarray(at, at + 4)), 16);
83
+ if (Number.isNaN(size))
84
+ break;
85
+ if (size === 0) {
86
+ out.push(new Uint8Array(0));
87
+ at += 4;
88
+ continue;
89
+ }
90
+ out.push(bytes.subarray(at + 4, at + size));
91
+ at += size;
92
+ }
93
+ return out;
94
+ }
95
+ function amount(bytes) {
96
+ return bytes < 10 * 1048576 ? `${Math.ceil(bytes / 1024)} KiB` : `${Math.round(bytes / 1048576)} MiB`;
97
+ }
98
+ function authorization(token) {
99
+ return `Basic ${Buffer.from(`x:${token}`).toString("base64")}`;
100
+ }
101
+ /** The project's branches as the service has them, and what its receive side offers. */
102
+ async function remoteRefs(options) {
103
+ const response = await fetch(`${options.url}/info/refs?service=git-receive-pack`, {
104
+ headers: { authorization: authorization(options.token), "user-agent": options.agent ?? "coderook-cli" },
105
+ });
106
+ if (!response.ok)
107
+ throw new Error((await response.text()).trim() || `CodeRook answered ${response.status}`);
108
+ const refs = new Map();
109
+ for (const line of pktLines(new Uint8Array(await response.arrayBuffer()))) {
110
+ const text = decoder.decode(line).replace(/\n$/, "");
111
+ if (text.startsWith("ERR "))
112
+ throw new Error(text.slice(4));
113
+ const [main] = text.split("\0");
114
+ const [sha, ref] = (main ?? "").split(" ");
115
+ if (sha && ref && /^[0-9a-f]{40}$/.test(sha) && sha !== ZERO && ref.startsWith("refs/"))
116
+ refs.set(ref, sha);
117
+ }
118
+ return refs;
119
+ }
120
+ async function call(options, path, init) {
121
+ const response = await fetch(`${options.url}/coderook/${path}`, {
122
+ ...init,
123
+ headers: { authorization: authorization(options.token), "user-agent": options.agent ?? "coderook-cli", ...init.headers },
124
+ });
125
+ const body = (await response.json().catch(() => ({})));
126
+ if (!response.ok)
127
+ throw new Error((body.error?.message) ?? `CodeRook answered ${response.status}`);
128
+ return body;
129
+ }
130
+ /** Sends one large file in pieces (only those missing) and declares it by its git id. */
131
+ async function sendLargeFile(options, gitId) {
132
+ const data = git(["cat-file", "blob", gitId], options.cwd);
133
+ const bounds = (0, chunking_js_1.chunkBoundaries)(data, options.profile ?? chunking_js_1.MICRO_CHUNK_PROFILE);
134
+ const pieces = [];
135
+ let from = 0;
136
+ for (const to of bounds) {
137
+ const piece = data.subarray(from, to);
138
+ pieces.push({ sha256: (0, node_crypto_1.createHash)("sha256").update(piece).digest("hex"), data: piece });
139
+ from = to;
140
+ }
141
+ const missing = new Set((await call(options, "pieces/missing", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ pieces: pieces.map((p) => p.sha256) }) })).missing ?? []);
142
+ const send = pieces.filter((p, i) => missing.has(p.sha256) && pieces.findIndex((q) => q.sha256 === p.sha256) === i);
143
+ let sent = 0;
144
+ for (let at = 0; at < send.length;) {
145
+ const batch = [];
146
+ let bytes = 0;
147
+ while (at < send.length && (batch.length === 0 || bytes + send[at].data.length <= BATCH_BYTES) && batch.length < 256) {
148
+ batch.push(send[at]);
149
+ bytes += send[at].data.length;
150
+ at++;
151
+ }
152
+ await call(options, "pieces", {
153
+ method: "POST",
154
+ headers: { "content-type": "application/octet-stream", "x-coderook-pieces": batch.map((p) => `${p.sha256}:${p.data.length}`).join(",") },
155
+ body: Buffer.concat(batch.map((p) => p.data)),
156
+ });
157
+ sent += bytes;
158
+ options.say?.(` ${gitId.slice(0, 7)}: sent ${amount(sent)} of ${amount(send.reduce((n, p) => n + p.data.length, 0))} that changed`);
159
+ }
160
+ if (!send.length)
161
+ options.say?.(` ${gitId.slice(0, 7)}: nothing to send, every piece is there already`);
162
+ await call(options, "files", {
163
+ method: "POST",
164
+ headers: { "content-type": "application/json" },
165
+ body: JSON.stringify({ gitId, size: data.length, sha256: (0, node_crypto_1.createHash)("sha256").update(data).digest("hex"), pieces: pieces.map((p) => p.sha256) }),
166
+ });
167
+ return { bytes: data.length, sent };
168
+ }
169
+ /** A push that would pass the request limit even with its large files sent beside it. */
170
+ class TooBig extends Error {
171
+ }
172
+ /* What the service already has and this repository knows: never sent again. */
173
+ function known(shas, cwd) {
174
+ return [...new Set(shas)].filter((sha) => sha !== ZERO && (0, node_child_process_1.spawnSync)("git", ["cat-file", "-e", `${sha}^{commit}`], { cwd, windowsHide: true }).status === 0);
175
+ }
176
+ /* One receive-pack request for these commands. */
177
+ async function pushOnce(commands, haves, options, declared) {
178
+ const say = options.say ?? (() => undefined);
179
+ const results = new Map();
180
+ const revs = [...commands.map((c) => c.neu), ...haves.map((sha) => `^${sha}`)].join("\n") + "\n";
181
+ const mostPush = options.mostPushBytes ?? 95 * 1024 * 1024;
182
+ let big = options.bigBytes ?? 8 * 1024 * 1024;
183
+ /*
184
+ First as plain git would: one pack, with git's own deltas, so an edit
185
+ inside a large file the service already holds goes as only the change
186
+ (72 KiB for a 64 KiB edit to 200 MiB, where pieces sent 4.2 MiB,
187
+ 30 November 2026). Given up the moment it passes the limit; then the
188
+ large files go beside it.
189
+ */
190
+ let pack = await gitStream(["pack-objects", "--stdout", "--revs", "--thin", "--delta-base-offset", "-q"], options.cwd, revs, mostPush);
191
+ if (!pack)
192
+ for (;;) {
193
+ /* The files left out of the pack at this size, which go beside it. */
194
+ const listed = git(["rev-list", "--objects", `--filter=blob:limit=${big}`, "--filter-print-omitted", "--stdin"], options.cwd, revs).toString();
195
+ const large = listed.split("\n").filter((line) => line.startsWith("~")).map((line) => line.slice(1).split(" ")[0]);
196
+ for (const gitId of large) {
197
+ if (declared.has(gitId))
198
+ continue;
199
+ say(`Sending ${gitId.slice(0, 7)} beside the push, in pieces`);
200
+ await sendLargeFile(options, gitId);
201
+ declared.add(gitId);
202
+ }
203
+ pack = await gitStream(["pack-objects", "--stdout", "--revs", "--thin", "--delta-base-offset", "-q", `--filter=blob:limit=${big}`], options.cwd, revs, mostPush);
204
+ if (pack)
205
+ break;
206
+ if (big <= 64 * 1024)
207
+ throw new TooBig(`this push is over ${Math.round(mostPush / 1048576)} MB even without its large files`);
208
+ /* Many middling files: send more of them beside the push. */
209
+ big = Math.max(64 * 1024, Math.floor(big / 8));
210
+ }
211
+ const head = commands.map((c, i) => pkt(`${c.old} ${c.neu} ${c.ref}${i === 0 ? `\0report-status side-band-64k agent=${options.agent ?? "coderook-cli"}` : ""}\n`));
212
+ const body = Buffer.concat([...head.map((p) => Buffer.from(p)), Buffer.from("0000"), pack]);
213
+ say(`Pushing ${commands.length === 1 ? "1 line" : `${commands.length} lines`} (${Math.max(1, Math.round(pack.length / 1024))} KiB)`);
214
+ const response = await fetch(`${options.url}/git-receive-pack`, {
215
+ method: "POST",
216
+ headers: {
217
+ authorization: authorization(options.token),
218
+ "content-type": "application/x-git-receive-pack-request",
219
+ accept: "application/x-git-receive-pack-result",
220
+ "user-agent": options.agent ?? "coderook-cli",
221
+ },
222
+ body,
223
+ });
224
+ if (!response.ok) {
225
+ const text = (await response.text()).trim() || `CodeRook answered ${response.status}`;
226
+ for (const c of commands)
227
+ results.set(c.ref, text);
228
+ return results;
229
+ }
230
+ /* Side-band: 1 carries the report, 2 progress, 3 a fatal error. */
231
+ const report = [];
232
+ let fatal = "";
233
+ for (const line of pktLines(new Uint8Array(await response.arrayBuffer()))) {
234
+ if (!line.length)
235
+ continue;
236
+ const band = line[0];
237
+ if (band === 1)
238
+ report.push(line.subarray(1));
239
+ else if (band === 2) {
240
+ for (const text of decoder.decode(line.subarray(1)).split(/[\r\n]+/))
241
+ if (text.trim())
242
+ say(`remote: ${text.trim()}`);
243
+ }
244
+ else if (band === 3)
245
+ fatal += decoder.decode(line.subarray(1));
246
+ }
247
+ const statuses = pktLines(Buffer.concat(report.map((r) => Buffer.from(r)))).map((l) => decoder.decode(l).replace(/\n$/, ""));
248
+ const unpack = statuses.find((s) => s.startsWith("unpack "));
249
+ for (const c of commands) {
250
+ const line = statuses.find((s) => s === `ok ${c.ref}` || s.startsWith(`ng ${c.ref} `));
251
+ if (line === `ok ${c.ref}`)
252
+ results.set(c.ref, undefined);
253
+ else if (line)
254
+ results.set(c.ref, line.slice(`ng ${c.ref} `.length));
255
+ else
256
+ results.set(c.ref, fatal.trim() || (unpack && unpack !== "unpack ok" ? unpack : "CodeRook did not say whether this line was saved"));
257
+ }
258
+ return results;
259
+ }
260
+ /*
261
+ A long or heavy line in steps along its first-parent chain, each step a
262
+ push of its own that the next builds on: every request stays under the
263
+ limit, a version is made for each commit as it always is, and an
264
+ interrupted transfer starts again from the last step that landed.
265
+ */
266
+ async function pushInSteps(command, haves, options, declared) {
267
+ const say = options.say ?? (() => undefined);
268
+ const chain = git(["rev-list", "--first-parent", "--reverse", command.neu, ...haves.map((sha) => `^${sha}`)], options.cwd).toString().split("\n").filter(Boolean);
269
+ if (!chain.length)
270
+ return (await pushOnce([command], haves, options, declared)).get(command.ref);
271
+ const most = options.mostCommits ?? 100;
272
+ let old = command.old;
273
+ let done = 0;
274
+ let step = Math.min(most, chain.length);
275
+ while (done < chain.length) {
276
+ const target = chain[Math.min(done + step, chain.length) - 1];
277
+ try {
278
+ const result = (await pushOnce([{ old, neu: target, ref: command.ref }], known([...haves, old], options.cwd), options, declared)).get(command.ref);
279
+ if (result)
280
+ return result;
281
+ old = target;
282
+ done = Math.min(done + step, chain.length);
283
+ if (chain.length > step)
284
+ say(`${command.ref.replace(/^refs\/heads\//, "")}: ${done} of ${chain.length} commits`);
285
+ step = Math.min(most, step * 2);
286
+ }
287
+ catch (error) {
288
+ if (!(error instanceof TooBig))
289
+ throw error;
290
+ if (step === 1)
291
+ return `${error.message}, in a single commit`;
292
+ step = Math.max(1, Math.floor(step / 4));
293
+ }
294
+ }
295
+ return undefined;
296
+ }
297
+ /** Pushes `requests` to the service, large files beside the push. One result per request. */
298
+ async function bridgePush(requests, options) {
299
+ const remote = await remoteRefs(options);
300
+ const commands = [];
301
+ const results = new Map();
302
+ for (const request of requests) {
303
+ if (!request.src) {
304
+ results.set(request.dst, "deleting a line over git is not supported; archive it on CodeRook");
305
+ continue;
306
+ }
307
+ let neu;
308
+ try {
309
+ neu = git(["rev-parse", "--verify", `${request.src}^{commit}`], options.cwd).toString().trim();
310
+ }
311
+ catch {
312
+ results.set(request.dst, `${request.src} is not a commit`);
313
+ continue;
314
+ }
315
+ commands.push({ old: remote.get(request.dst) ?? ZERO, neu, ref: request.dst });
316
+ }
317
+ if (commands.length) {
318
+ const haves = known(remote.values(), options.cwd);
319
+ const declared = new Set();
320
+ const most = options.mostCommits ?? 100;
321
+ const count = (c) => Number(git(["rev-list", "--count", c.neu, ...haves.map((sha) => `^${sha}`)], options.cwd).toString().trim() || "0");
322
+ let together = commands.every((c) => count(c) <= most);
323
+ if (together) {
324
+ try {
325
+ for (const [ref, error] of await pushOnce(commands, haves, options, declared))
326
+ results.set(ref, error);
327
+ }
328
+ catch (error) {
329
+ if (!(error instanceof TooBig))
330
+ throw error;
331
+ together = false;
332
+ }
333
+ }
334
+ if (!together) {
335
+ /* One line at a time, each in steps; a line already pushed is a base for the next. */
336
+ const landed = [];
337
+ for (const command of commands) {
338
+ const error = await pushInSteps(command, known([...haves, ...landed], options.cwd), options, declared);
339
+ results.set(command.ref, error);
340
+ if (!error)
341
+ landed.push(command.neu);
342
+ }
343
+ }
344
+ }
345
+ return requests.map((r) => ({ dst: r.dst, error: results.get(r.dst) }));
346
+ }