ref0-git 0.2.0 → 0.3.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.
@@ -13,12 +13,15 @@ import {
13
13
  /**
14
14
  * How a text's references are looked up: each issue's page, whether a login exists, and each
15
15
  * commit's full SHA. `undefined` or `false` for one that doesn't exist; a lookup that can't say
16
- * throws.
16
+ * throws, as one aborted by `signal` does.
17
17
  */
18
18
  export interface Lookups {
19
19
  readonly issue: (reference: IssueReference) => Promise<'issues' | 'pull' | undefined>;
20
20
  readonly user: (login: string) => Promise<boolean>;
21
- readonly commit: (reference: CommitReference) => Promise<string | undefined>;
21
+ readonly commit: (
22
+ reference: CommitReference,
23
+ signal?: AbortSignal,
24
+ ) => Promise<string | undefined>;
22
25
  }
23
26
 
24
27
  /**
@@ -64,7 +67,7 @@ export const githubLookups: Lookups = {
64
67
  user: async (login) =>
65
68
  existing(await github.GET('/users/{username}', { params: { path: { username: login } } })) !==
66
69
  undefined,
67
- commit: async ({ repo, sha }) => {
70
+ commit: async ({ repo, sha }, signal) => {
68
71
  const written = sha.toLowerCase();
69
72
  const at = ownerAndName(repo);
70
73
  // A full SHA reads the commit alone; a short one asks for it as a ref, which a commit it
@@ -73,12 +76,14 @@ export const githubLookups: Lookups = {
73
76
  ? existing(
74
77
  await github.GET('/repos/{owner}/{repo}/git/commits/{commit_sha}', {
75
78
  params: { path: { ...at, commit_sha: written } },
79
+ signal: signal ?? null,
76
80
  }),
77
81
  )?.sha
78
82
  : shaOf(
79
83
  existing(
80
84
  await github.GET('/repos/{owner}/{repo}/commits/{ref}', {
81
85
  params: { path: { ...at, ref: written } },
86
+ signal: signal ?? null,
82
87
  }),
83
88
  ),
84
89
  );
@@ -45,6 +45,7 @@ import {
45
45
  useAllowedAt,
46
46
  useGroups,
47
47
  } from './rows.tsx';
48
+ import { paletteReads } from './server.ts';
48
49
  import { type ModeSymbol, symbols, type Typed, typedInto } from './targets.ts';
49
50
 
50
51
  export type { PaletteAt } from './rows.tsx';
@@ -211,18 +212,24 @@ function PaletteBody({
211
212
  const router = useRouter();
212
213
  const [typed, setTyped] = useState<Typed>({ symbol: undefined, text: '' });
213
214
  const commands = useCommands(at);
214
- const groups = useGroups(at, typed, commands, setTyped);
215
+ const groups = useGroups(at, typed, commands, setTyped, shown);
215
216
  const rows = groups.flatMap((group) => group.rows);
216
217
  const mode = typed.symbol ?? 'none';
217
- // Closed once the dialog starts closing, before its exit animation unmounts the body.
218
+ // Closed once the dialog starts closing, before its exit animation unmounts the body. Closing
219
+ // aborts a commit jump's lookup, as another jump taking its place does, and the palette's own
220
+ // reads still out, such as a `#` search.
221
+ const client = useQueryClient();
218
222
  const open = useRef(true);
223
+ const jump = useRef<AbortController | undefined>(undefined);
219
224
  useEffect(() => {
220
225
  open.current = shown;
221
226
 
222
227
  return () => {
223
228
  open.current = false;
229
+ jump.current?.abort();
230
+ void client.cancelQueries({ queryKey: paletteReads });
224
231
  };
225
- }, [shown]);
232
+ }, [client, shown]);
226
233
 
227
234
  const go = (href: string, newTab: boolean) => {
228
235
  if (newTab) {
@@ -261,15 +268,23 @@ function PaletteBody({
261
268
  };
262
269
 
263
270
  // A SHA names a commit only once the drop-in finds one it starts, as a comment's SHA does. A
264
- // palette closed before the answer comes goes nowhere, and a lookup that fails says so.
271
+ // palette closed, or another jump picked, before the answer comes stops its read and goes
272
+ // nowhere, and a lookup that fails says so.
265
273
  const jumpToCommit = async (
266
274
  commit: { readonly owner: string; readonly repo: string; readonly sha: string },
267
275
  newTab: boolean,
268
276
  ) => {
277
+ // A closing palette's input still takes keys until its exit animation ends: it starts none.
278
+ if (!open.current) return;
279
+
280
+ jump.current?.abort();
281
+ const lookup = new AbortController();
282
+ jump.current = lookup;
283
+
269
284
  const sha = await githubLookups
270
- .commit({ repo: `${commit.owner}/${commit.repo}`, sha: commit.sha })
285
+ .commit({ repo: `${commit.owner}/${commit.repo}`, sha: commit.sha }, lookup.signal)
271
286
  .catch(() => null);
272
- if (!open.current) return;
287
+ if (lookup.signal.aborted || !open.current) return;
273
288
 
274
289
  if (sha === null) {
275
290
  toast.error(`Couldn't look up ${commit.sha} in ${commit.owner}/${commit.repo}`);
@@ -294,7 +294,12 @@ const usePeople = (at: PaletteAt, text: string, asking: boolean): readonly Group
294
294
  ? undefined
295
295
  : { kind: 'searching' }
296
296
  : failed.length > 0
297
- ? { kind: 'failed', retry: () => failed.forEach((each) => void each.refetch()) }
297
+ ? {
298
+ kind: 'failed',
299
+ retry: () => {
300
+ if (asking) failed.forEach((each) => void each.refetch());
301
+ },
302
+ }
298
303
  : undefined;
299
304
 
300
305
  return [
@@ -308,10 +313,15 @@ const usePeople = (at: PaletteAt, text: string, asking: boolean): readonly Group
308
313
  };
309
314
 
310
315
  /** `#`: `#12` goes to that number, and other words search the page's repo once typing stops. */
311
- const useIssues = (at: PaletteAt, text: string, settled: string): readonly Group[] => {
316
+ const useIssues = (
317
+ at: PaletteAt,
318
+ text: string,
319
+ settled: string,
320
+ asking: boolean,
321
+ ): readonly Group[] => {
312
322
  const wanted = issueQueryOf(settled, at.here);
313
323
  const typing = issueQueryOf(text, at.here);
314
- const found = useQuery({ ...issueSearch(wanted ?? ''), enabled: wanted !== undefined });
324
+ const found = useQuery({ ...issueSearch(wanted ?? ''), enabled: asking && wanted !== undefined });
315
325
  const number = numberJump(text, at.here);
316
326
 
317
327
  const rows = (found.data?.items ?? []).map((item): Row => {
@@ -338,7 +348,12 @@ const useIssues = (at: PaletteAt, text: string, settled: string): readonly Group
338
348
  : typing !== wanted || found.isFetching
339
349
  ? { kind: 'searching' }
340
350
  : found.isError
341
- ? { kind: 'failed', retry: () => void found.refetch() }
351
+ ? {
352
+ kind: 'failed',
353
+ retry: () => {
354
+ if (asking) void found.refetch();
355
+ },
356
+ }
342
357
  : found.data?.incomplete === true
343
358
  ? { kind: 'incomplete' }
344
359
  : undefined;
@@ -356,18 +371,26 @@ const useIssues = (at: PaletteAt, text: string, settled: string): readonly Group
356
371
  ];
357
372
  };
358
373
 
359
- /** `/`: the page's repo's files, from Go to file's own read of its default branch. */
374
+ /**
375
+ * `/`: the page's repo's files, from Go to file's own read of its default branch. Neither read
376
+ * retries by itself, as the palette's own don't: `enabled` can't stop a retry already waiting, so
377
+ * one would ask again while the palette closes, and a failure shows Retry at once instead. A
378
+ * query retries as the observer whose fetch runs says, so Go to file's own tree read keeps its
379
+ * retries.
380
+ */
360
381
  const useFiles = (at: PaletteAt, text: string, asking: boolean): readonly Group[] => {
361
382
  const place = placeOf(at.here);
362
383
  const branch = at.here.defaultBranch;
363
384
  const head = useQuery({
364
385
  ...headCommit(place ?? { owner: '', repo: '' }, { kind: 'branch', name: branch ?? '' }),
365
386
  enabled: asking && place !== undefined && branch !== undefined,
387
+ retry: false,
366
388
  });
367
389
  const tree = head.data?.tree;
368
390
  const files = useQuery({
369
391
  ...allFiles(place ?? { owner: '', repo: '' }, tree ?? ''),
370
392
  enabled: asking && place !== undefined && tree !== undefined,
393
+ retry: false,
371
394
  });
372
395
 
373
396
  if (place === undefined || branch === undefined) {
@@ -379,7 +402,12 @@ const useFiles = (at: PaletteAt, text: string, asking: boolean): readonly Group[
379
402
  const failed = head.isError ? head : files.isError ? files : undefined;
380
403
  const status: Status | undefined =
381
404
  failed !== undefined
382
- ? { kind: 'failed', retry: () => void failed.refetch() }
405
+ ? {
406
+ kind: 'failed',
407
+ retry: () => {
408
+ if (asking) void failed.refetch();
409
+ },
410
+ }
383
411
  : head.isPending || (tree !== undefined && files.isPending)
384
412
  ? { kind: 'searching' }
385
413
  : files.data?.truncated === true
@@ -414,21 +442,25 @@ const helpRows = (switchTo: (typed: Typed) => void): readonly Row[] =>
414
442
  /**
415
443
  * The groups for `typed`: with no mode, what's local; with one, its own. A mode that asks the
416
444
  * drop-in asks only once typing has stopped for `typingWait`, and only for what was typed then.
445
+ * A palette no longer `shown`, whose input takes keys until its exit animation ends, asks nothing,
446
+ * and its retries ask nothing either.
417
447
  */
418
448
  export const useGroups = (
419
449
  at: PaletteAt,
420
450
  typed: Typed,
421
451
  commands: readonly Row[],
422
452
  switchTo: (typed: Typed) => void,
453
+ shown: boolean,
423
454
  ): readonly Group[] => {
424
455
  const settled = useSettled(typed.text) ?? '';
425
- const people = usePeople(at, typed.text, typed.symbol === '@');
456
+ const people = usePeople(at, typed.text, shown && typed.symbol === '@');
426
457
  const issues = useIssues(
427
458
  at,
428
459
  typed.symbol === '#' ? typed.text : '',
429
460
  typed.symbol === '#' ? settled : '',
461
+ shown,
430
462
  );
431
- const files = useFiles(at, typed.text, typed.symbol === '/');
463
+ const files = useFiles(at, typed.text, shown && typed.symbol === '/');
432
464
  const found = useFound(at, typed.symbol === undefined ? typed.text : '');
433
465
 
434
466
  switch (typed.symbol) {
@@ -15,6 +15,9 @@ export const resultsMost = 8;
15
15
  /** How long typing must stop before a mode asks the drop-in. */
16
16
  export const typingWait = 150;
17
17
 
18
+ /** The key every read of the palette's own starts with, which closing it cancels. */
19
+ export const paletteReads = ['palette'] as const;
20
+
18
21
  /** An answer kept for the session: a search typed again shows at once. */
19
22
  const forTheSession = { staleTime: Infinity, gcTime: Infinity, retry: false } as const;
20
23
 
@@ -44,7 +47,7 @@ const repoOfUrl = (url: string) => {
44
47
  /** The issues and pull requests `GET /search/issues` finds for `q`, at most `resultsMost`. */
45
48
  export const issueSearch = (q: string) =>
46
49
  queryOptions({
47
- queryKey: ['palette', 'issues', q],
50
+ queryKey: [...paletteReads, 'issues', q],
48
51
  queryFn: async ({ signal }): Promise<Found<FoundIssue>> => {
49
52
  const answer = await github.GET('/search/issues', {
50
53
  params: { query: { q, per_page: resultsMost } },
@@ -75,7 +78,7 @@ export const issueSearch = (q: string) =>
75
78
  */
76
79
  export const orgMembers = (org: string) =>
77
80
  queryOptions({
78
- queryKey: ['palette', 'members', org],
81
+ queryKey: [...paletteReads, 'members', org],
79
82
  queryFn: async ({ signal }): Promise<readonly string[]> => {
80
83
  const answer = await github.GET('/orgs/{org}/members', {
81
84
  params: { path: { org }, query: { per_page: 100 } },
@@ -595,6 +595,12 @@ export const hostRules: readonly HostRule[] = [
595
595
  },
596
596
  ];
597
597
 
598
+ /**
599
+ * Git's `identify`, as the approval page asks it. A host's `git.ts` gives its callback this return
600
+ * type, since `createGitServer`'s type is inferred from options that name `git`.
601
+ */
602
+ export type Identify = StarterApprovalOptions['identify'];
603
+
598
604
  /** The device flow's approval page: the person signed in approves a device for themselves. */
599
605
  export const approvalPage = (options: Omit<StarterApprovalOptions, 'tokenDays'>) =>
600
606
  starterApprovalPage({ ...options, tokenDays });
@@ -14,9 +14,9 @@ import type { PrivateRepos } from './policy.ts';
14
14
  * Its store calls stay within what the search leaves the hook, `most` and 6 more: the signed-out
15
15
  * list reads the record of each public name in its page, one call a name, and of the name past
16
16
  * it; the host's list reads its created rows and their entries, two; the public index, one; and a
17
- * server's first sealed cursor reads its key, once for each list that races to it, two
18
- * (`listPublic` and `listCreated` in Git's `store/catalogue.ts`, `cursorSeal` in
19
- * `store/cursor-seal.ts`).
17
+ * server's first sealed cursor reads its key, one, and adds it when none is stored yet, one more.
18
+ * A server that holds the key reads nothing for it (`listPublic` and `listCreated` in Git's
19
+ * `store/catalogue.ts`, `cursorSeal` in `store/cursor-seal.ts`).
20
20
  */
21
21
  export const privateReposOf =
22
22
  (git: Pick<GitServer, 'repos'>): PrivateRepos =>
@@ -1,14 +1,6 @@
1
- import type {
2
- CreatedToken,
3
- GitAdapter,
4
- GitError,
5
- Oid,
6
- RefName,
7
- RepoId,
8
- Result,
9
- Signature,
10
- } from '@ref0/git';
1
+ import type { CreatedToken, GitError, Oid, RefName, RepoId, Result, Signature } from '@ref0/git';
11
2
  import { createRestClient } from '@ref0/git/rest';
3
+ import type { Store } from '@ref0/infra/promises';
12
4
  import type { RestClient } from '@ref0/git/rest';
13
5
  import * as Schema from 'effect/Schema';
14
6
 
@@ -46,8 +38,6 @@ type Progress = typeof Progress.Type;
46
38
 
47
39
  const decodeProgress = Schema.decodeUnknownSync(Progress);
48
40
 
49
- type Store = GitAdapter['store'];
50
-
51
41
  /** The `app/seed` record, in a scope of the app's own, apart from Git's `git/` scopes. */
52
42
  const progressScope = 'app';
53
43
 
package/dist/cli/git.mjs CHANGED
@@ -1,5 +1,6 @@
1
1
  import { stopMs } from "./child.mjs";
2
2
  import * as Effect from "effect/Effect";
3
+ import * as Data from "effect/Data";
3
4
  import * as Stream from "effect/Stream";
4
5
  import * as ChildProcess from "effect/process/ChildProcess";
5
6
  import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
@@ -7,10 +8,29 @@ import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
7
8
  const notRun = {
8
9
  status: null,
9
10
  stdout: "",
10
- stderr: ""
11
+ stderr: "",
12
+ overflowed: false
13
+ };
14
+ const overflowed = {
15
+ ...notRun,
16
+ overflowed: true
11
17
  };
12
18
  /** A stream's bytes as text. */
13
19
  const textOf = (stream) => stream.pipe(Stream.decodeText(), Stream.mkString);
20
+ var StdoutOverflow = class extends Data.TaggedError("StdoutOverflow") {};
21
+ /** A stream's bytes as text, failing as soon as they pass `most`, which stops the reading. */
22
+ const textUpTo = (stream, most) => Stream.runFoldEffect(stream, () => ({
23
+ chunks: [],
24
+ size: 0
25
+ }), (read, chunk) => {
26
+ const size = read.size + chunk.length;
27
+ if (size > most) return Effect.fail(new StdoutOverflow());
28
+ read.chunks.push(chunk);
29
+ return Effect.succeed({
30
+ chunks: read.chunks,
31
+ size
32
+ });
33
+ }).pipe(Effect.map(({ chunks }) => new TextDecoder().decode(Buffer.concat(chunks))));
14
34
  /**
15
35
  * `git <args>` in `cwd`, given `input` on its stdin, with its stdout kept. Its stderr is kept too,
16
36
  * so Git's own messages stay out of the CLI's streams and a caller says what failed in its own
@@ -33,7 +53,7 @@ const gitRun = Effect.fnUntraced(function* (args, options = {}) {
33
53
  return yield* Effect.scoped(Effect.gen(function* () {
34
54
  const child = yield* spawner.spawn(command);
35
55
  const [stdout, stderr, status] = yield* Effect.all([
36
- textOf(child.stdout),
56
+ options.stdoutMost === void 0 ? textOf(child.stdout) : textUpTo(child.stdout, options.stdoutMost),
37
57
  options.stderr === "inherit" ? Effect.succeed("") : textOf(child.stderr),
38
58
  child.exitCode
39
59
  ], { concurrency: "unbounded" });
@@ -41,8 +61,9 @@ const gitRun = Effect.fnUntraced(function* (args, options = {}) {
41
61
  return {
42
62
  status,
43
63
  stdout,
44
- stderr
64
+ stderr,
65
+ overflowed: false
45
66
  };
46
- })).pipe(Effect.catch(() => Effect.succeed(notRun)));
67
+ })).pipe(Effect.catchTag("StdoutOverflow", () => Effect.succeed(overflowed)), Effect.catch(() => Effect.succeed(notRun)));
47
68
  });
48
69
  export { gitRun };
@@ -1,43 +1,176 @@
1
+ import { failure } from "./failure.mjs";
1
2
  import { gitRun } from "./git.mjs";
2
3
  import { node } from "./node.mjs";
3
4
  import * as Effect from "effect/Effect";
4
5
  import * as FileSystem from "effect/FileSystem";
5
6
  // src/cli/helpers.ts
6
7
  /**
7
- * Which of Git's credential helpers keep a host's secret, as Git itself chooses them: a traced
8
- * `git credential fill` for a username no helper keeps, so Git asks every helper it would store
9
- * with, matching each `credential.<url>` section by its own rules, wildcards and resets included.
10
- */
11
- /** A helper that writes the secret to a file as plain text. */
12
- const plaintext = /* @__PURE__ */ new Set(["store"]);
13
- /** A username no helper keeps, so a `fill` for it runs every helper and finds nothing. */
14
- const probeUser = "ref0-git-helper-probe";
15
- /**
16
- * A helper's name from the command Git's trace says it ran: `git credential-store --file x get`
17
- * is `store`, as is `/usr/lib/git-core/git-credential-store get`; any other command is itself.
18
- */
19
- const helperName = (ran) => {
20
- const command = ran.replace(/ get$/, "").replaceAll(/["']/g, "");
21
- const word = command.replace(/^git credential-/, "git-credential-").split(/\s+/)[0] ?? "";
22
- const program = word.split("/").at(-1) ?? word;
23
- return program.startsWith("git-credential-") ? program.slice(15) : command;
24
- };
25
- /** The helpers Git asks for `origin`'s credential, in order. */
26
- const credentialHelpers = (origin) => gitRun([
27
- "-c",
28
- "credential.interactive=false",
29
- "credential",
30
- "fill"
31
- ], {
32
- input: `url=${origin}/\nusername=${probeUser}\n\n`,
33
- env: {
34
- GIT_TRACE: "1",
35
- GIT_TERMINAL_PROMPT: "0",
36
- GIT_ASKPASS: "",
37
- SSH_ASKPASS: ""
8
+ * Which of Git's credential helpers `git credential approve` stores a host's token with, read from
9
+ * Git's config, never by running a helper: Git's approve stores with every `credential.helper`
10
+ * whose section matches the URL, in config order, an empty value clearing those before it. The
11
+ * match here is ref0-git's own and counts too many rather than too few: it ignores a section's
12
+ * user, port and path, and honours a clearing value only where Git surely applies it, so a drift
13
+ * from Git can only refuse a helper that was safe.
14
+ */
15
+ /**
16
+ * At most how many bytes of credential config, and how many of its entries, login reads. Past
17
+ * either it refuses: a list cut short could leave out a plain-text helper.
18
+ */
19
+ const credentialConfigBytes = 65536;
20
+ /** The helpers that keep a secret in memory or in the platform's encrypted store, never a file. */
21
+ const safeHelpers = /* @__PURE__ */ new Set([
22
+ "cache",
23
+ "osxkeychain",
24
+ "wincred",
25
+ "libsecret",
26
+ "manager",
27
+ "manager-core"
28
+ ]);
29
+ /** Git Credential Manager's names, whose store `credential.credentialStore` sets, `plaintext` among them. */
30
+ const storeSetByConfig = /* @__PURE__ */ new Set(["manager", "manager-core"]);
31
+ /** Where a config entry comes from, as a person finds it: a file's path, or `command line`. */
32
+ const originOf = (shown) => {
33
+ if (shown.startsWith("file:")) return shown.slice(5);
34
+ return shown.endsWith(":") ? shown.slice(0, -1) : shown;
35
+ };
36
+ /**
37
+ * Each entry of `git config -z --show-origin --get-regexp`'s output, which is the origin, a NUL,
38
+ * the key, then a line break and the value where there is one, and a NUL; `undefined` when the
39
+ * output isn't in that shape. Git lowercases the section and the key, never the subsection.
40
+ */
41
+ const entriesOf = (listed) => {
42
+ const fields = listed.split("\0");
43
+ if (fields.pop() !== "" || fields.length % 2 !== 0) return void 0;
44
+ const entries = [];
45
+ for (let at = 0; at < fields.length; at += 2) {
46
+ const [origin = "", item = ""] = fields.slice(at, at + 2);
47
+ const keyEnd = item.indexOf("\n");
48
+ const name = keyEnd === -1 ? item : item.slice(0, keyEnd);
49
+ if (!name.startsWith("credential.")) return void 0;
50
+ const rest = name.slice(11);
51
+ const dot = rest.lastIndexOf(".");
52
+ entries.push({
53
+ origin: originOf(origin),
54
+ section: dot === -1 ? void 0 : rest.slice(0, dot),
55
+ key: dot === -1 ? rest : rest.slice(dot + 1),
56
+ value: keyEnd === -1 ? void 0 : item.slice(keyEnd + 1)
57
+ });
58
+ }
59
+ return entries;
60
+ };
61
+ /** `text` with its `%XX` escapes decoded, or as it is where one doesn't decode. */
62
+ const decoded = (text) => {
63
+ try {
64
+ return decodeURIComponent(text);
65
+ } catch {
66
+ return text;
67
+ }
68
+ };
69
+ /**
70
+ * A host as Git's urlmatch compares it: in lower case, one trailing dot dropped, so
71
+ * `GIT.Acme.dev.` names `git.acme.dev`.
72
+ */
73
+ const gitHost = (host) => host.toLowerCase().replace(/\.$/, "");
74
+ /**
75
+ * The scheme and host a `credential.<url>` section names, either left out where it names none,
76
+ * which matches any. Git reads a full URL or a partial one, as `git.acme.dev` or `https://`; this
77
+ * reads both alike, decodes the host's `%XX` escapes and drops the user, port and path.
78
+ */
79
+ const sectionUrl = (section) => {
80
+ const schemeEnd = section.indexOf("://");
81
+ const scheme = schemeEnd > 0 ? section.slice(0, schemeEnd).toLowerCase() : void 0;
82
+ const rest = schemeEnd === -1 ? section : section.slice(schemeEnd + 3);
83
+ const authorityEnd = rest.search(/[/?#]/);
84
+ const authority = authorityEnd === -1 ? rest : rest.slice(0, authorityEnd);
85
+ const hostPort = authority.slice(authority.lastIndexOf("@") + 1);
86
+ const host = hostPort.startsWith("[") ? hostPort.slice(0, hostPort.indexOf("]") + 1) : hostPort.replace(/:[^:]*$/, "");
87
+ return {
88
+ scheme,
89
+ host: host === "" ? void 0 : gitHost(decoded(host))
90
+ };
91
+ };
92
+ /** Whether `pattern` names `host`, label by label, a `*` label standing for any one label. */
93
+ const hostMatches = (pattern, host) => {
94
+ const patterns = pattern.split(".");
95
+ const labels = host.split(".");
96
+ return patterns.length === labels.length && patterns.every((label, at) => label === "*" || label === labels[at]);
97
+ };
98
+ /** Whether Git may apply an entry of `section` to `login`'s URL: unscoped, or naming its scheme and host. */
99
+ const mayApply = (section, login) => {
100
+ if (section === void 0) return true;
101
+ const { scheme, host } = sectionUrl(section);
102
+ return (scheme === void 0 || scheme === login.scheme) && (host === void 0 || hostMatches(host, login.host));
103
+ };
104
+ /**
105
+ * Whether Git surely applies a clearing `helper =` of `section` to `login`'s URL: unscoped, or
106
+ * naming exactly its origin, with no user or path, so it can't clear a helper Git keeps.
107
+ */
108
+ const surelyApplies = (section, login) => section === void 0 || section.replace(/\/$/, "") === login.origin;
109
+ /**
110
+ * The program a helper's value runs, by the name Git's own and the platform helpers have: `cache`
111
+ * for `cache --timeout=3600`, `libsecret` for `/usr/lib/git-core/git-credential-libsecret`.
112
+ * `undefined` for a `!` command, any word a shell would read as more than a plain word, a value
113
+ * holding a tab, a line break or another control character, or a path that isn't a
114
+ * `git-credential-*` program, since ref0-git can't tell what that keeps. A path is trusted by the
115
+ * name it gives, as Git's config names it.
116
+ */
117
+ const programOf = (value) => /^(?:([A-Za-z0-9][A-Za-z0-9-]*)|\/(?:[\w.+,@%~-]+\/)*git-credential-([A-Za-z0-9-]+))(?: +[\w./=:+,@%~-]+)*(?![\s\S])/.exec(value)?.slice(1).find((name) => name !== void 0);
118
+ /**
119
+ * What a refusal names a helper `programOf` can't name by: a plain word's or a path's first word,
120
+ * without its arguments, or `a ! command` or `a shell command`, never the command itself.
121
+ */
122
+ const labelOf = (value) => {
123
+ if (value === void 0) return "(no value)";
124
+ if (value.startsWith("!")) return "a ! command";
125
+ return /^[\w./+,@%~-]+(?= |(?![\s\S]))/.exec(value)?.[0] ?? "a shell command";
126
+ };
127
+ /** The helpers approve stores `origin`'s credential with, as `entries` set them, in order. */
128
+ const helpersFor = (entries, origin) => {
129
+ const url = new URL(origin);
130
+ const login = {
131
+ scheme: url.protocol.slice(0, -1),
132
+ host: gitHost(url.hostname),
133
+ origin: url.origin
134
+ };
135
+ const applying = entries.filter((entry) => mayApply(entry.section, login));
136
+ const plaintextStore = node.process.env["GCM_CREDENTIAL_STORE"]?.toLowerCase() === "plaintext" || applying.some((entry) => entry.key === "credentialstore" && entry.value?.toLowerCase() === "plaintext");
137
+ let helpers = [];
138
+ for (const entry of applying) {
139
+ if (entry.key !== "helper") continue;
140
+ if (entry.value === "") {
141
+ if (surelyApplies(entry.section, login)) helpers = [];
142
+ continue;
143
+ }
144
+ const program = entry.value === void 0 ? void 0 : programOf(entry.value);
145
+ const safe = program !== void 0 && safeHelpers.has(program) && !(plaintextStore && storeSetByConfig.has(program));
146
+ helpers.push({
147
+ label: program ?? labelOf(entry.value),
148
+ origin: entry.origin,
149
+ plaintext: !safe
150
+ });
38
151
  }
39
- }).pipe(Effect.map((ran) => [...ran.stderr.matchAll(/trace: run_command: '([^']*(?:'\\[!']'[^']*)* get)'$/gm)].map((match) => helperName((match[1] ?? "").replaceAll(/'\\([!'])'/g, "$1")))));
40
- const isPlaintext = (helper) => plaintext.has(helper) || /\bgit(?:\s+|-)credential-store\b/.test(helper);
152
+ return helpers;
153
+ };
154
+ /**
155
+ * The helpers `git credential approve` stores `origin`'s credential with, as Git's config sets
156
+ * them, read by the same Git, in the same folder and environment, as approve, so an `includeIf`
157
+ * resolves alike. It refuses config it can't read, or past `credentialConfigBytes` or
158
+ * `credentialConfigEntries`.
159
+ */
160
+ const credentialHelpers = Effect.fnUntraced(function* (origin) {
161
+ const listed = yield* gitRun([
162
+ "config",
163
+ "-z",
164
+ "--show-origin",
165
+ "--get-regexp",
166
+ String.raw`^credential\..*(helper|credentialstore)$`
167
+ ], { stdoutMost: credentialConfigBytes });
168
+ if (listed.overflowed) return yield* failure("credential_config_too_large", `Can't check Git's credential helpers. Its credential config passes ${credentialConfigBytes / 1024} KiB`, "Remove the credential entries you no longer use from your Git config, then sign in again");
169
+ const entries = listed.status === 1 && listed.stdout === "" ? [] : entriesOf(listed.stdout);
170
+ if (listed.status === null || listed.status > 1 || entries === void 0) return yield* failure("credential_config_unread", `Couldn't read Git's credential config: ${listed.stderr.trim().split("\n")[0] || "git config failed"}`, "Fix the config Git names, as `git config --list` shows it, then sign in again");
171
+ if (entries.length > 128) return yield* failure("credential_config_too_large", `Can't check Git's credential helpers. Its config holds more than 128 credential entries`, "Remove the credential entries you no longer use from your Git config, then sign in again");
172
+ return helpersFor(entries, origin);
173
+ });
41
174
  /** The helper to set up where none is, for this machine's platform. */
42
175
  const platformHelpers = /* @__PURE__ */ new Map([["darwin", "osxkeychain"], ["win32", "manager"]]);
43
176
  const suggestedHelper = () => platformHelpers.get(node.process.platform) ?? "libsecret";
@@ -48,4 +181,4 @@ const onPath = Effect.fnUntraced(function* (program) {
48
181
  for (const folder of folders) if (yield* fs.exists(`${folder}/${program}`).pipe(Effect.orElseSucceed(() => false))) return true;
49
182
  return false;
50
183
  });
51
- export { credentialHelpers, isPlaintext, onPath, suggestedHelper };
184
+ export { credentialConfigBytes, credentialHelpers, onPath, suggestedHelper };
@@ -96,7 +96,7 @@ const signInCommands = [
96
96
  Command.make("login", {
97
97
  host: Argument.String("HOST").pipe(Argument.withDescription("The host, as git.acme.dev, git.acme.dev/git where Git is under a path, or http://localhost:5173")),
98
98
  withToken: Flag.Boolean("with-token").pipe(Flag.withDescription("Read a token from stdin instead of signing in in the browser"), Flag.withDefault(false)),
99
- allowPlaintext: Flag.Boolean("allow-plaintext").pipe(Flag.withDescription("Store the token even where Git's helper keeps it as plain text"), Flag.withDefault(false))
99
+ allowPlaintext: Flag.Boolean("allow-plaintext").pipe(Flag.withDescription("Store the token even with a helper ref0-git can't tell keeps it encrypted"), Flag.withDefault(false))
100
100
  }, Effect.fnUntraced(function* ({ host, withToken, allowPlaintext }) {
101
101
  const named = yield* hostOf(host);
102
102
  const helpers = yield* checkedHelpers(named, allowPlaintext);
@@ -1,8 +1,10 @@
1
1
  import { BrokenField, approveCredential, breaksField, fillCredential, rejectCredential } from "./credentials.mjs";
2
- import { failure, unsafeCredential, usageFailure } from "./failure.mjs";
2
+ import { CliFailure, failure, unsafeCredential } from "./failure.mjs";
3
3
  import { gitRun } from "./git.mjs";
4
- import { credentialHelpers, isPlaintext, onPath, suggestedHelper } from "./helpers.mjs";
4
+ import { shellWord } from "../init/shell.mjs";
5
+ import { credentialHelpers, onPath, suggestedHelper } from "./helpers.mjs";
5
6
  import { forgetHost, globalConfig, hostName, recordHost, signedInHosts } from "./hosts.mjs";
7
+ import { printable } from "./output.mjs";
6
8
  import * as Effect from "effect/Effect";
7
9
  import * as Redacted from "effect/Redacted";
8
10
  // src/cli/sign-ins.ts
@@ -14,16 +16,36 @@ import * as Redacted from "effect/Redacted";
14
16
  /** Git's config key that sends `origin`'s pushes through `git-remote-ref0`. */
15
17
  const pushKey = (origin) => `url.ref0::${origin}/.pushInsteadOf`;
16
18
  /**
17
- * Where Git's helpers stand for `origin`: the helpers, refused when there's none, when one keeps
18
- * plain text and `allowPlaintext` isn't set, or when Git asks them by repo path, which a host's
19
- * one sign-in can't answer.
19
+ * The refusal of `plain`, the helpers that may keep the token as plain text, each named with
20
+ * where Git's config sets it, which `--json` also carries as its `data`.
21
+ */
22
+ const plaintextRefused = (plain) => {
23
+ const named = plain.map(({ label, origin }) => `${label} (${origin})`).join(", ");
24
+ return new CliFailure({
25
+ class: "usage",
26
+ reason: "plaintext_helper",
27
+ headline: `Git's ${named} credential ${plain.length === 1 ? "helper" : "helpers"} may keep the token as plain text`,
28
+ next: {
29
+ says: `Use a helper that keeps it encrypted, as \`git config --global credential.helper ${suggestedHelper()}\`, in their place, or sign in with --allow-plaintext, which stores the token with every helper Git runs, these too`,
30
+ run: []
31
+ },
32
+ data: { helpers: plain.map(({ label, origin }) => ({
33
+ helper: label,
34
+ origin
35
+ })) }
36
+ });
37
+ };
38
+ /**
39
+ * Where Git's helpers stand for `origin`: their labels, refused when there's none, when one may
40
+ * keep plain text and `allowPlaintext` isn't set, or when Git asks them by repo path, which a
41
+ * host's one sign-in can't answer.
20
42
  */
21
43
  const checkedHelpers = Effect.fnUntraced(function* (host, allowPlaintext) {
22
44
  const { origin } = host;
23
45
  const helpers = yield* credentialHelpers(origin);
24
46
  if (helpers.length === 0) return yield* failure("no_credential_helper", "Git has no credential helper to keep the token in", `Set one up: \`git config --global credential.helper ${suggestedHelper()}\`, then sign in again`);
25
- const plain = helpers.filter(isPlaintext);
26
- if (plain.length > 0 && !allowPlaintext) return yield* usageFailure("plaintext_helper", `Git's ${plain.join(", ")} helper keeps the token as plain text in a file`, `Use a secure helper, as \`git config --global credential.helper ${suggestedHelper()}\`, or sign in with --allow-plaintext`);
47
+ const plain = helpers.filter((helper) => helper.plaintext);
48
+ if (plain.length > 0 && !allowPlaintext) return yield* plaintextRefused(plain);
27
49
  if ((yield* gitRun([
28
50
  "config",
29
51
  "--type=bool",
@@ -31,13 +53,47 @@ const checkedHelpers = Effect.fnUntraced(function* (host, allowPlaintext) {
31
53
  "credential.useHttpPath",
32
54
  `${origin}/`
33
55
  ])).stdout.trim() === "true") return yield* failure("credential_by_path", `Git asks for ${hostName(host)}'s credentials by repo, with credential.useHttpPath, so one sign-in can't reach its repos`, `Turn it off for this host: \`git config --global credential.${origin}/.useHttpPath false\`, then sign in again`);
34
- return helpers;
56
+ return helpers.map(({ label }) => label);
57
+ });
58
+ /** At most how many earlier sign-ins login erases one at a time, each by its username, before it stores. */
59
+ const earlierSignIns = 8;
60
+ /**
61
+ * A command, ready to copy, that erases `username`'s entry for `url` from each of Git's helpers,
62
+ * or `undefined` when printing would change the username, as a line break or a NUL, so the command
63
+ * wouldn't name it. Each value is a word of its own, never part of `printf`'s format.
64
+ */
65
+ const eraseCommand = (url, username) => {
66
+ if (printable(username) !== username) return void 0;
67
+ return `printf 'protocol=%s\\nhost=%s\\nusername=%s\\n\\n' ${[
68
+ url.protocol.slice(0, -1),
69
+ url.host,
70
+ username
71
+ ].map(shellWord).join(" ")} | git credential reject`;
72
+ };
73
+ /**
74
+ * Erases each sign-in Git's helpers still keep for `url` once it's erased with no username, one at
75
+ * a time by its username and token, since a helper may erase only an exact username's entry. Each
76
+ * has a username: `fillCredential` takes an entry only with a username and a password, and Git's
77
+ * fill exits 128, "unable to get password from user", when a helper answers a password alone. Its
78
+ * fills never ask at the terminal. Past `earlierSignIns`, one still kept fails as
79
+ * `credential_not_erased`, before anything is stored.
80
+ */
81
+ const eraseEarlier = Effect.fnUntraced(function* (host, url, helpers) {
82
+ for (let erased = 0; erased < earlierSignIns; erased++) {
83
+ const kept = yield* fillCredential(url);
84
+ if (kept === void 0) return;
85
+ yield* rejectCredential(url, kept);
86
+ }
87
+ const still = yield* fillCredential(url);
88
+ if (still === void 0) return;
89
+ const command = eraseCommand(url, still.username);
90
+ return yield* failure("credential_not_erased", `Git's ${helpers.join(", ")} helper keeps an earlier token for ${hostName(host)}`, command === void 0 ? "Erase it with the helper's own tool, since its username holds a character ref0-git won't print, then sign in again" : `Erase it with \`${command}\`, then sign in again`);
35
91
  });
36
92
  /** The records of `host`'s origin, its own among them when it's recorded. */
37
93
  const recordsOf = (host) => Effect.map(signedInHosts, (hosts) => hosts.filter((one) => one.origin === host.origin));
38
94
  /**
39
- * Stores `credential` as `host`'s origin's one sign-in, refusing a line break a host could use to
40
- * store it for another host, and forgets a host it just recorded when the helpers don't give it
95
+ * Stores `credential` as `host`'s origin's one sign-in, once every earlier one is erased, refusing a
96
+ * line break a host could use to store it for another host, and forgets a host it just recorded when the helpers don't give it
41
97
  * back. Once it's kept, the origin's other records go: the token they named is this one now.
42
98
  */
43
99
  const storeSignIn = Effect.fnUntraced(function* (host, credential, helpers) {
@@ -50,6 +106,7 @@ const storeSignIn = Effect.fnUntraced(function* (host, credential, helpers) {
50
106
  if (!known) yield* recordHost(host);
51
107
  const stored = Effect.gen(function* () {
52
108
  yield* rejectCredential(url);
109
+ yield* eraseEarlier(host, url, helpers);
53
110
  yield* approveCredential(url, credential);
54
111
  const kept = yield* fillCredential(url);
55
112
  if (kept === void 0 || Redacted.value(kept.password) !== Redacted.value(credential.password)) return yield* failure("credential_not_kept", `Git's ${helpers.join(", ")} helper didn't keep the token`, "Check the helper works, as `git credential fill` does, then sign in again");
package/dist/init/app.mjs CHANGED
@@ -139,7 +139,7 @@ const nodeHead = (choices) => {
139
139
  const packs = choices.objects === "packs";
140
140
  const queue = choices.queue === "on";
141
141
  const dialect = dialectOn[choices.records];
142
- return lines(firstImports(choices, false), dialect !== false && `${dialect}\n`, gitServerImport(choices), queue && "import type { MergeInput, MergePlan } from '@ref0/git';", "import { tokens } from '@ref0/git/auth';", "import { engine } from '@ref0/git/engine';", "import { xdiff } from '@ref0/git/node';", "import { createRestHandler } from '@ref0/git/rest';", "import { createGitHubHandler } from '@ref0/github';", infraImports(choices), "", `import { env${partsOf(choices).length > 0 ? ", need" : ""} } from './env.ts';`, "import { admin, approvalPage, hostPolicy, hostRules } from './policy.ts';", "import { privateReposOf } from './private-repos.ts';", "import { readyAdapter, readyAuth, starterAuth } from './signin/auth.ts';", "import { avatars } from './signin/avatars.ts';", "import { clientIpHeader } from './signin/client-ip.ts';", "import { appAuth } from './signin/host-session.ts';", "import { orgsOver } from './signin/orgs.ts';", "import { sealKey } from './signin/seal.ts';", "", "/** What the app reads from `.env`, as the server's entry reads it here. */", "export { env };", "", storeLines(choices), bucketLines(choices), "", "/** Git's jobs, which `server/plugins/jobs.ts` runs in this process. */", "export const jobs = createJobQueue({ store });", "", `/** Git's records, jobs${packs ? " and packs" : ""}, whose store also keeps the local seed's progress. */`, `export const adapter = { store, ${packs ? "bucket, " : ""}jobs };`, "", peopleOn[choices.records], "");
142
+ return lines(firstImports(choices, false), dialect !== false && `${dialect}\n`, gitServerImport(choices), queue && "import type { MergeInput, MergePlan } from '@ref0/git';", "import { tokens } from '@ref0/git/auth';", "import { engine } from '@ref0/git/engine';", "import { xdiff } from '@ref0/git/node';", "import { createRestHandler } from '@ref0/git/rest';", "import { createGitHubHandler } from '@ref0/github';", infraImports(choices), "", `import { env${partsOf(choices).length > 0 ? ", need" : ""} } from './env.ts';`, "import { admin, approvalPage, hostPolicy, hostRules, type Identify } from './policy.ts';", "import { privateReposOf } from './private-repos.ts';", "import { readyAdapter, readyAuth, starterAuth } from './signin/auth.ts';", "import { avatars } from './signin/avatars.ts';", "import { clientIpHeader } from './signin/client-ip.ts';", "import { appAuth } from './signin/host-session.ts';", "import { orgsOver } from './signin/orgs.ts';", "import { sealKey } from './signin/seal.ts';", "", "/** What the app reads from `.env`, as the server's entry reads it here. */", "export { env };", "", storeLines(choices), bucketLines(choices), "", "/** Git's jobs, which `server/plugins/jobs.ts` runs in this process. */", "export const jobs = createJobQueue({ store });", "", `/** Git's records, jobs${packs ? " and packs" : ""}, whose store also keeps the local seed's progress. */`, `export const adapter = { store, ${packs ? "bucket, " : ""}jobs };`, "", peopleOn[choices.records], "");
143
143
  };
144
144
  /** The app's `src/git.ts` on Node: `apps/github`'s own past its head, Node's head and parts in Cloudflare's place. */
145
145
  const nodeGit = (choices) => filled(templates.appGitNode, {
@@ -8,7 +8,7 @@ import * as Schema from "effect/Schema";
8
8
  /** The create commands' packages, at the versions each was run at on 20 Nov, as `init.md` lists. */
9
9
  const creators = {
10
10
  next: "create-next-app@16.4.6",
11
- sveltekit: "sv@1.7.0",
11
+ sveltekit: "sv@1.7.1",
12
12
  nuxt: "create-nuxt@4.1.0"
13
13
  };
14
14
  /** The values `--framework` takes, in the table's order. */
@@ -5,9 +5,14 @@ import * as Predicate from "effect/Predicate";
5
5
  // src/init/files.ts
6
6
  /** The parts that are strings, one a line: a part that's `false` is left out. */
7
7
  const lines = (...parts) => parts.filter(Predicate.isString).join("\n");
8
+ /** An import of `names` from `from`, on one line, or one name a line past the formatter's width. */
9
+ const importLine = (names, from) => {
10
+ const line = `import { ${names.join(", ")} } from '${from}';`;
11
+ return line.length <= 100 ? line : lines("import {", ...names.map((name) => ` ${name},`), `} from '${from}';`);
12
+ };
8
13
  /** `names` as a sentence lists them: `a, b and c`. */
9
14
  const listed = (names) => names.length < 2 ? names.join("") : `${names.slice(0, -1).join(", ")} and ${names[names.length - 1] ?? ""}`;
10
- /** `head` and `body` on one line when it fits in 100 columns, as the formatter leaves it, else two. */
15
+ /** `head` and `body` on one line when it fits the formatter's width, as it leaves them, else two. */
11
16
  const fitted = (head, body) => head.length + body.length < 100 ? `${head} ${body}` : `${head}\n ${body}`;
12
17
  /** The served parts' words, for the files' first lines. */
13
18
  const served = {
@@ -72,4 +77,4 @@ const withCreatedTypes = (created) => (text) => {
72
77
  if (created !== true || major >= 22) return text;
73
78
  return withValue(text, ["devDependencies", "@types/node"], nodePackages["@types/node"]);
74
79
  };
75
- export { fitted, ignoring, lines, listed, served, withCli, withCreatedTypes, withDependencies, withLines };
80
+ export { fitted, ignoring, importLine, lines, listed, served, withCli, withCreatedTypes, withDependencies, withLines };
@@ -1,6 +1,6 @@
1
1
  // src/init/metadata.ts
2
2
  /** The version `ref0-git`, `create-ref0-git` and Git's packages release at, all at once (Q738). */
3
- const release = "0.2.0";
3
+ const release = "0.3.0";
4
4
  /** The packages the app depends on, by their folder in a checkout's `packages/`. */
5
5
  const appPackages = [
6
6
  "infra",
@@ -25,12 +25,10 @@ const importOf = (from, to) => {
25
25
  return `${"../".repeat(ups)}${to.replace(/\.ts$/, "")}`;
26
26
  };
27
27
  const loaded = ["// Loaded on the first request, so `next build`, which loads each route to read its options, opens", "// no database and needs no secret."];
28
- /** The formatter's width, which the lines `init` writes keep to, as its own source does. */
29
- const printWidth = 100;
30
28
  /** The route's handler over `call`, on one line where it fits, as the formatter breaks it. */
31
29
  const handlerLine = (call) => {
32
30
  const head = "const git = async (request: Request) =>";
33
- return `${head} ${call}`.length > printWidth ? `${head}\n ${call}` : `${head} ${call}`;
31
+ return `${head} ${call}`.length > 100 ? `${head}\n ${call}` : `${head} ${call}`;
34
32
  };
35
33
  /** Next.js's folders for each parameter a route ends with. */
36
34
  const nextTails = {
@@ -1,4 +1,4 @@
1
- import { ignoring, lines, withCli, withCreatedTypes, withDependencies, withLines } from "./files.mjs";
1
+ import { ignoring, importLine, lines, withCli, withCreatedTypes, withDependencies, withLines } from "./files.mjs";
2
2
  import { frameworkPackages, nodePackages } from "./metadata.mjs";
3
3
  import { adminLines, gitImports, gitPackages, handlerLines, header, mergeLines, serveExport, serverLines } from "./git-module.mjs";
4
4
  import { parseJsonc, stringAt, withEntries } from "./jsonc.mjs";
@@ -37,13 +37,15 @@ const firstImports = (choices, loadsEnv) => {
37
37
  };
38
38
  /** infra's import: one line from its promise entry, naming what the choices take. */
39
39
  const infraImports = (choices) => {
40
- return `import { ${[
40
+ const names = [
41
41
  "createJobQueue",
42
+ "layerOf",
42
43
  ...choices.bucket === "disk" ? ["disk"] : [],
43
44
  ...recordsOf(choices) === void 0 ? [] : ["poller"],
44
45
  ...choices.records === "sqlite" ? ["sqlite"] : [],
45
46
  ...partsOf(choices).flatMap((part) => part.infra)
46
- ].join(", ")} } from '@ref0/infra/promises';`;
47
+ ];
48
+ return importLine(names, "@ref0/infra/promises");
47
49
  };
48
50
  /** The store, as chosen: a shared one woken by a poller, or SQLite's file. */
49
51
  const storeLines = (choices) => {
@@ -78,7 +80,7 @@ const nodeModule = (choices, jobs) => {
78
80
  line: "import { xdiff } from '@ref0/git/node';",
79
81
  last: false
80
82
  }), infraImports(choices), "", framework && loadEnvLines, needHelper(".env"), "", adminLines, storeLines(choices), bucketLines(choices), "", jobsSays[jobs], "export const jobs = createJobQueue({ store });", jobs === "on-import" && startedOnImport, "", mergeLines(choices), serverLines(choices, {
81
- adapter: ` adapter: { store, ${packs ? "bucket, " : ""}jobs },`,
83
+ adapter: ` adapter: layerOf({ store, ${packs ? "bucket, " : ""}jobs }),`,
82
84
  engine: "engine({ xdiff: await xdiff() })",
83
85
  uploads: choices.bucket === "s3",
84
86
  token: "need('ADMIN_TOKEN')"
@@ -15,7 +15,7 @@ var templates_default = {
15
15
  "slot": "infraImport",
16
16
  "text": "import { cloudflare, jobObject, r2, recordsObject } from '@ref0/infra/cloudflare';"
17
17
  },
18
- "\nimport { env as bindings } from 'cloudflare:workers';\n\nimport type { Env } from './env.ts';\nimport { admin, approvalPage, hostPolicy, hostRules } from './policy.ts';\nimport { privateReposOf } from './private-repos.ts';\nimport { readyAdapter, readyAuth, starterAuth } from './signin/auth.ts';\nimport { avatars } from './signin/avatars.ts';\nimport { appAuth } from './signin/host-session.ts';\nimport { orgsOver } from './signin/orgs.ts';\nimport { sealKey } from './signin/seal.ts';\n\n// SAFETY: `wrangler.jsonc` ",
18
+ "\nimport { layerOf } from '@ref0/infra/promises';\nimport { env as bindings } from 'cloudflare:workers';\n\nimport type { Env } from './env.ts';\nimport { admin, approvalPage, hostPolicy, hostRules, type Identify } from './policy.ts';\nimport { privateReposOf } from './private-repos.ts';\nimport { readyAdapter, readyAuth, starterAuth } from './signin/auth.ts';\nimport { avatars } from './signin/avatars.ts';\nimport { appAuth } from './signin/host-session.ts';\nimport { orgsOver } from './signin/orgs.ts';\nimport { sealKey } from './signin/seal.ts';\n\n// SAFETY: `wrangler.jsonc` ",
19
19
  {
20
20
  "slot": "safety",
21
21
  "text": "binds the objects, the bucket and D1"
@@ -39,7 +39,7 @@ var templates_default = {
39
39
  "slot": "queueMerge",
40
40
  "text": "/**\n * How the queue writes an entry's link onto `main`: a merge commit, by the person who added it, as\n * a pull request's merge button writes one, and titled as GitHub titles it for a pull request's\n * entry, keyed `pr-<number>`.\n */\nconst queueMerge = ({ entry }: MergeInput): MergePlan => {\n const [owner = ''] = entry.repo.split('/');\n const branch = entry.source.replace(/^refs\\/heads\\//, '');\n const pull = /^pr-([1-9]\\d*)$/.exec(entry.key)?.[1];\n const title =\n pull === undefined ? `Merge ${branch}` : `Merge pull request #${pull} from ${owner}/${branch}`;\n const login = entry.subject?.id ?? entry.actor.id;\n const hostname = new URL(env.APP_ORIGIN).hostname;\n\n return {\n method: 'merge',\n message: `${title}\\n`,\n author: { name: login, email: `${login}@users.noreply.${hostname}`, at: Date.now(), offset: 0 },\n };\n};\n\n"
41
41
  },
42
- "/** The key sessions and host sessions are sealed under, derived once an isolate from its secret. */\nexport const sessionKey = sealKey(env.SESSION_SECRET);\n\n/**\n * Who owns what, and the drop-in's people and orgs, over Better Auth's tables, which `auth` makes\n * at the first request that reads them.\n */\nexport const directory = orgsOver(async () => readyAdapter(await auth()));\n\n/** People's, orgs' and repos' pictures, in Better Auth's database, as `directory` reads it. */\nexport const pictures = avatars(async () => readyAdapter(await auth()));\n\nexport const policy = hostPolicy(directory, {\n origin: env.APP_ORIGIN,\n avatars: pictures,\n privateRepos: async (prefix, most, host) => privateReposOf(git)(prefix, most, host),\n});\n\n/** Git, with the device flow's sign-in for `gh` and `ref0-git login`. */\nexport const git = createGitServer({\n adapter,\n",
42
+ "/** The key sessions and host sessions are sealed under, derived once an isolate from its secret. */\nexport const sessionKey = sealKey(env.SESSION_SECRET);\n\n/**\n * Who owns what, and the drop-in's people and orgs, over Better Auth's tables, which `auth` makes\n * at the first request that reads them.\n */\nexport const directory = orgsOver(async () => readyAdapter(await auth()));\n\n/** People's, orgs' and repos' pictures, in Better Auth's database, as `directory` reads it. */\nexport const pictures = avatars(async () => readyAdapter(await auth()));\n\nexport const policy = hostPolicy(directory, {\n origin: env.APP_ORIGIN,\n avatars: pictures,\n privateRepos: async (prefix, most, host) => privateReposOf(git)(prefix, most, host),\n});\n\n/** Git, with the device flow's sign-in for `gh` and `ref0-git login`. */\nexport const git = createGitServer({\n adapter: layerOf(adapter),\n",
43
43
  {
44
44
  "slot": "objects",
45
45
  "text": " objects: packs(),"
@@ -54,18 +54,18 @@ var templates_default = {
54
54
  "slot": "queue",
55
55
  "text": " // Each repo's `main` has a merge queue, beside the merge button: its protection still takes a\n // direct merge, as GitHub's does on a branch whose rules don't ask for the queue.\n queue: mergeQueue({ target: 'refs/heads/main', merge: queueMerge }),\n"
56
56
  },
57
- " // Git's events go to the drop-in, which follows each push: a pull request's head, its queue.\n events: (input) => github.events(input),\n rules: { push: hostRules.map((each) => each.rule) },\n // The page decides in the person's session, from the Better Auth below and Git's own `identify`.\n signIn: {\n approvalPage: approvalPage({\n auth: () => auth(),\n sealKey: sessionKey,\n identify: (request) => git.identify(request),\n origin: env.APP_ORIGIN,\n }),\n },\n});\n\n/**\n * Better Auth, made at a request that needs it, not the isolate's start: who signs up and in, in\n * `AUTH_DB`, each session with a Git token of its own. It's kept once a request's check settles.\n */\nexport const auth = readyAuth(() => {\n const tokens = git.tokens;\n if (tokens === undefined) throw new Error('Sessions mint Git tokens: pass tokens() to Git');\n\n return starterAuth({\n database: env.AUTH_DB,\n secret: env.SESSION_SECRET,\n origin: env.APP_ORIGIN,\n signUp: env.SIGN_UP !== 'closed',\n key: sessionKey,\n tokens,\n // Cloudflare's own, which it sets on every request in place of any the caller sent.\n ipHeader: 'cf-connecting-ip',\n ownsRepos: async (login) => {\n const listed = await git.repos.list({\n actor: admin,\n prefix: `${login}/`,\n page: { limit: 1 },\n });\n\n return listed.kind !== 'success' || listed.value.items.length > 0;\n },\n });\n});\n\n/**\n * The drop-in, joined to `git` here, before its first request, with the host's directory, and the\n * owner index, so `org:` and `user:` search an owner's repos, its private ones by the hook.\n */\nexport const github = createGitHubHandler(git, {\n authorize: policy.authorizeGitHub,\n people: policy.people,\n ownerIndex: { readableRepos: policy.readableRepos },\n});\n\n/** Git's REST, whose `route` serves Git's own URLs too: Smart HTTP and sign-in. */\nexport const rest = createRestHandler(git);\n\n/** The records objects, one per scope, as `wrangler.jsonc`'s `class_name`s name them. */\nexport const Records = recordsObject(adapter);\n\n/** The job objects, one per scope and job, which a records object's alarm rings. */\nexport const Jobs = jobObject(adapter);\n"
57
+ " // Git's events go to the drop-in, which follows each push: a pull request's head, its queue.\n events: (input) => github.events(input),\n rules: { push: hostRules.map((each) => each.rule) },\n // The page decides in the person's session, from the Better Auth below and Git's own `identify`.\n signIn: {\n approvalPage: approvalPage({\n auth: () => auth(),\n sealKey: sessionKey,\n identify: (request): ReturnType<Identify> => git.identify(request),\n origin: env.APP_ORIGIN,\n }),\n },\n});\n\n/**\n * Better Auth, made at a request that needs it, not the isolate's start: who signs up and in, in\n * `AUTH_DB`, each session with a Git token of its own. It's kept once a request's check settles.\n */\nexport const auth = readyAuth(() => {\n const tokens = git.tokens;\n if (tokens === undefined) throw new Error('Sessions mint Git tokens: pass tokens() to Git');\n\n return starterAuth({\n database: env.AUTH_DB,\n secret: env.SESSION_SECRET,\n origin: env.APP_ORIGIN,\n signUp: env.SIGN_UP !== 'closed',\n key: sessionKey,\n tokens,\n // Cloudflare's own, which it sets on every request in place of any the caller sent.\n ipHeader: 'cf-connecting-ip',\n ownsRepos: async (login) => {\n const listed = await git.repos.list({\n actor: admin,\n prefix: `${login}/`,\n page: { limit: 1 },\n });\n\n return listed.kind !== 'success' || listed.value.items.length > 0;\n },\n });\n});\n\n/**\n * The drop-in, joined to `git` here, in the tick that made it, with the host's directory, and the\n * owner index, so `org:` and `user:` search an owner's repos, its private ones by the hook.\n */\nexport const github = createGitHubHandler(git, {\n authorize: policy.authorizeGitHub,\n people: policy.people,\n ownerIndex: { readableRepos: policy.readableRepos },\n});\n\n/** Git's REST, whose `route` serves Git's own URLs too: Smart HTTP and sign-in. */\nexport const rest = createRestHandler(git);\n\n/** The records objects, one per scope, as `wrangler.jsonc`'s `class_name`s name them. */\nexport const Records = recordsObject(adapter);\n\n/** The job objects, one per scope and job, which a records object's alarm rings. */\nexport const Jobs = jobObject(adapter);\n"
58
58
  ],
59
59
  appGitNode: [
60
60
  {
61
61
  "slot": "head",
62
- "text": "import { createGitServer, mergeQueue, packs } from '@ref0/git';\nimport type { MergeInput, MergePlan } from '@ref0/git';\nimport { tokens } from '@ref0/git/auth';\nimport { engine } from '@ref0/git/engine';\nimport { createRestHandler } from '@ref0/git/rest';\nimport xdiff from '@ref0/git/xdiff.wasm';\nimport { createGitHubHandler } from '@ref0/github';\nimport { cloudflare, jobObject, r2, recordsObject } from '@ref0/infra/cloudflare';\nimport { env as bindings } from 'cloudflare:workers';\n\nimport type { Env } from './env.ts';\nimport { admin, approvalPage, hostPolicy, hostRules } from './policy.ts';\nimport { privateReposOf } from './private-repos.ts';\nimport { readyAdapter, readyAuth, starterAuth } from './signin/auth.ts';\nimport { avatars } from './signin/avatars.ts';\nimport { appAuth } from './signin/host-session.ts';\nimport { orgsOver } from './signin/orgs.ts';\nimport { sealKey } from './signin/seal.ts';\n\n// SAFETY: `wrangler.jsonc` binds the objects, the bucket and D1 and sets `APP_ORIGIN`; the\n// secrets come from `wrangler secret put`, or `.dev.vars` locally.\nexport const env = bindings as Env;\n\nconst {\n R2_ACCOUNT_ID: accountId,\n R2_ACCESS_KEY_ID: accessKeyId,\n R2_SECRET_ACCESS_KEY: secretAccessKey,\n} = env;\n\n// With R2's S3 credentials, a push's pack uploads to the bucket in parts, past Workers' 100 MB body.\nconst bucket =\n accountId === undefined || accessKeyId === undefined || secretAccessKey === undefined\n ? r2(env.PACKS)\n : r2(env.PACKS, {\n signing: { accountId, bucket: env.PACKS_BUCKET, accessKeyId, secretAccessKey },\n });\n\n/** Git's records, jobs and packs, whose store also keeps the local seed's progress. */\nexport const adapter = cloudflare({ records: env.RECORDS, jobs: env.JOBS, bucket });\n\n"
62
+ "text": "import { createGitServer, mergeQueue, packs } from '@ref0/git';\nimport type { MergeInput, MergePlan } from '@ref0/git';\nimport { tokens } from '@ref0/git/auth';\nimport { engine } from '@ref0/git/engine';\nimport { createRestHandler } from '@ref0/git/rest';\nimport xdiff from '@ref0/git/xdiff.wasm';\nimport { createGitHubHandler } from '@ref0/github';\nimport { cloudflare, jobObject, r2, recordsObject } from '@ref0/infra/cloudflare';\nimport { layerOf } from '@ref0/infra/promises';\nimport { env as bindings } from 'cloudflare:workers';\n\nimport type { Env } from './env.ts';\nimport { admin, approvalPage, hostPolicy, hostRules, type Identify } from './policy.ts';\nimport { privateReposOf } from './private-repos.ts';\nimport { readyAdapter, readyAuth, starterAuth } from './signin/auth.ts';\nimport { avatars } from './signin/avatars.ts';\nimport { appAuth } from './signin/host-session.ts';\nimport { orgsOver } from './signin/orgs.ts';\nimport { sealKey } from './signin/seal.ts';\n\n// SAFETY: `wrangler.jsonc` binds the objects, the bucket and D1 and sets `APP_ORIGIN`; the\n// secrets come from `wrangler secret put`, or `.dev.vars` locally.\nexport const env = bindings as Env;\n\nconst {\n R2_ACCOUNT_ID: accountId,\n R2_ACCESS_KEY_ID: accessKeyId,\n R2_SECRET_ACCESS_KEY: secretAccessKey,\n} = env;\n\n// With R2's S3 credentials, a push's pack uploads to the bucket in parts, past Workers' 100 MB body.\nconst bucket =\n accountId === undefined || accessKeyId === undefined || secretAccessKey === undefined\n ? r2(env.PACKS)\n : r2(env.PACKS, {\n signing: { accountId, bucket: env.PACKS_BUCKET, accessKeyId, secretAccessKey },\n });\n\n/** Git's records, jobs and packs, whose store also keeps the local seed's progress. */\nexport const adapter = cloudflare({ records: env.RECORDS, jobs: env.JOBS, bucket });\n\n"
63
63
  },
64
64
  {
65
65
  "slot": "queueMerge",
66
66
  "text": "/**\n * How the queue writes an entry's link onto `main`: a merge commit, by the person who added it, as\n * a pull request's merge button writes one, and titled as GitHub titles it for a pull request's\n * entry, keyed `pr-<number>`.\n */\nconst queueMerge = ({ entry }: MergeInput): MergePlan => {\n const [owner = ''] = entry.repo.split('/');\n const branch = entry.source.replace(/^refs\\/heads\\//, '');\n const pull = /^pr-([1-9]\\d*)$/.exec(entry.key)?.[1];\n const title =\n pull === undefined ? `Merge ${branch}` : `Merge pull request #${pull} from ${owner}/${branch}`;\n const login = entry.subject?.id ?? entry.actor.id;\n const hostname = new URL(env.APP_ORIGIN).hostname;\n\n return {\n method: 'merge',\n message: `${title}\\n`,\n author: { name: login, email: `${login}@users.noreply.${hostname}`, at: Date.now(), offset: 0 },\n };\n};\n\n"
67
67
  },
68
- "/** The key sessions and host sessions are sealed under, derived once an isolate from its secret. */\nexport const sessionKey = sealKey(env.SESSION_SECRET);\n\n/**\n * Who owns what, and the drop-in's people and orgs, over Better Auth's tables, which `auth` makes\n * at the first request that reads them.\n */\nexport const directory = orgsOver(async () => readyAdapter(await auth()));\n\n/** People's, orgs' and repos' pictures, in Better Auth's database, as `directory` reads it. */\nexport const pictures = avatars(async () => readyAdapter(await auth()));\n\nexport const policy = hostPolicy(directory, {\n origin: env.APP_ORIGIN,\n avatars: pictures,\n privateRepos: async (prefix, most, host) => privateReposOf(git)(prefix, most, host),\n});\n\n/** Git, with the device flow's sign-in for `gh` and `ref0-git login`. */\nexport const git = createGitServer({\n adapter,\n",
68
+ "/** The key sessions and host sessions are sealed under, derived once an isolate from its secret. */\nexport const sessionKey = sealKey(env.SESSION_SECRET);\n\n/**\n * Who owns what, and the drop-in's people and orgs, over Better Auth's tables, which `auth` makes\n * at the first request that reads them.\n */\nexport const directory = orgsOver(async () => readyAdapter(await auth()));\n\n/** People's, orgs' and repos' pictures, in Better Auth's database, as `directory` reads it. */\nexport const pictures = avatars(async () => readyAdapter(await auth()));\n\nexport const policy = hostPolicy(directory, {\n origin: env.APP_ORIGIN,\n avatars: pictures,\n privateRepos: async (prefix, most, host) => privateReposOf(git)(prefix, most, host),\n});\n\n/** Git, with the device flow's sign-in for `gh` and `ref0-git login`. */\nexport const git = createGitServer({\n adapter: layerOf(adapter),\n",
69
69
  {
70
70
  "slot": "objects",
71
71
  "text": " objects: packs(),"
@@ -85,7 +85,7 @@ var templates_default = {
85
85
  "slot": "queue",
86
86
  "text": " // Each repo's `main` has a merge queue, beside the merge button: its protection still takes a\n // direct merge, as GitHub's does on a branch whose rules don't ask for the queue.\n queue: mergeQueue({ target: 'refs/heads/main', merge: queueMerge }),\n"
87
87
  },
88
- " // Git's events go to the drop-in, which follows each push: a pull request's head, its queue.\n events: (input) => github.events(input),\n rules: { push: hostRules.map((each) => each.rule) },\n // The page decides in the person's session, from the Better Auth below and Git's own `identify`.\n signIn: {\n approvalPage: approvalPage({\n auth: () => auth(),\n sealKey: sessionKey,\n identify: (request) => git.identify(request),\n origin: env.APP_ORIGIN,\n }),\n },\n});\n\n/**\n * Better Auth, made at a request that needs it, not the isolate's start: who signs up and in, in\n * `AUTH_DB`, each session with a Git token of its own. It's kept once a request's check settles.\n */\nexport const auth = readyAuth(() => {\n const tokens = git.tokens;\n if (tokens === undefined) throw new Error('Sessions mint Git tokens: pass tokens() to Git');\n\n return starterAuth({\n",
88
+ " // Git's events go to the drop-in, which follows each push: a pull request's head, its queue.\n events: (input) => github.events(input),\n rules: { push: hostRules.map((each) => each.rule) },\n // The page decides in the person's session, from the Better Auth below and Git's own `identify`.\n signIn: {\n approvalPage: approvalPage({\n auth: () => auth(),\n sealKey: sessionKey,\n identify: (request): ReturnType<Identify> => git.identify(request),\n origin: env.APP_ORIGIN,\n }),\n },\n});\n\n/**\n * Better Auth, made at a request that needs it, not the isolate's start: who signs up and in, in\n * `AUTH_DB`, each session with a Git token of its own. It's kept once a request's check settles.\n */\nexport const auth = readyAuth(() => {\n const tokens = git.tokens;\n if (tokens === undefined) throw new Error('Sessions mint Git tokens: pass tokens() to Git');\n\n return starterAuth({\n",
89
89
  {
90
90
  "slot": "database",
91
91
  "text": " database: env.AUTH_DB,"
@@ -95,7 +95,7 @@ var templates_default = {
95
95
  "slot": "ipHeader",
96
96
  "text": " // Cloudflare's own, which it sets on every request in place of any the caller sent.\n ipHeader: 'cf-connecting-ip',\n"
97
97
  },
98
- " ownsRepos: async (login) => {\n const listed = await git.repos.list({\n actor: admin,\n prefix: `${login}/`,\n page: { limit: 1 },\n });\n\n return listed.kind !== 'success' || listed.value.items.length > 0;\n },\n });\n});\n\n/**\n * The drop-in, joined to `git` here, before its first request, with the host's directory, and the\n * owner index, so `org:` and `user:` search an owner's repos, its private ones by the hook.\n */\nexport const github = createGitHubHandler(git, {\n authorize: policy.authorizeGitHub,\n people: policy.people,\n ownerIndex: { readableRepos: policy.readableRepos },\n});\n\n/** Git's REST, whose `route` serves Git's own URLs too: Smart HTTP and sign-in. */\nexport const rest = createRestHandler(git);\n",
98
+ " ownsRepos: async (login) => {\n const listed = await git.repos.list({\n actor: admin,\n prefix: `${login}/`,\n page: { limit: 1 },\n });\n\n return listed.kind !== 'success' || listed.value.items.length > 0;\n },\n });\n});\n\n/**\n * The drop-in, joined to `git` here, in the tick that made it, with the host's directory, and the\n * owner index, so `org:` and `user:` search an owner's repos, its private ones by the hook.\n */\nexport const github = createGitHubHandler(git, {\n authorize: policy.authorizeGitHub,\n people: policy.people,\n ownerIndex: { readableRepos: policy.readableRepos },\n});\n\n/** Git's REST, whose `route` serves Git's own URLs too: Smart HTTP and sign-in. */\nexport const rest = createRestHandler(git);\n",
99
99
  {
100
100
  "slot": "classes",
101
101
  "text": "\n/** The records objects, one per scope, as `wrangler.jsonc`'s `class_name`s name them. */\nexport const Records = recordsObject(adapter);\n\n/** The job objects, one per scope and job, which a records object's alarm rings. */\nexport const Jobs = jobObject(adapter);\n"
@@ -172,7 +172,7 @@ var templates_default = {
172
172
  "slot": "infraImport",
173
173
  "text": "import { cloudflare, jobObject, r2, recordsObject } from '@ref0/infra/cloudflare';"
174
174
  },
175
- "\nimport { env as bindings } from 'cloudflare:workers';\n\nimport type { Env } from ",
175
+ "\nimport { layerOf } from '@ref0/infra/promises';\nimport { env as bindings } from 'cloudflare:workers';\n\nimport type { Env } from ",
176
176
  {
177
177
  "slot": "envFile",
178
178
  "text": "'./env.ts'"
@@ -197,7 +197,7 @@ var templates_default = {
197
197
  "slot": "merge",
198
198
  "text": "/** How the queue writes an entry onto `main`: a merge commit, by whoever added it. */\nconst merge = ({ entry }: MergeInput): MergePlan => ({\n method: 'merge',\n message: `Merge ${entry.source.replace(/^refs\\/heads\\//, '')}\\n`,\n author: {\n name: entry.actor.id,\n email: `${entry.actor.id}@users.noreply.git`,\n at: Date.now(),\n offset: 0,\n },\n});\n\n"
199
199
  },
200
- "export const git = createGitServer({\n adapter,\n",
200
+ "export const git = createGitServer({\n adapter: layerOf(adapter),\n",
201
201
  {
202
202
  "slot": "objects",
203
203
  "text": " objects: packs(),"
@@ -1,7 +1,7 @@
1
1
  import { serveExport } from "./git-module.mjs";
2
2
  import { vercelPackages } from "./metadata.mjs";
3
3
  import { dropInPrefixes } from "./routes.mjs";
4
- import { ignoring, lines, served, withCli, withCreatedTypes, withDependencies, withLines } from "./files.mjs";
4
+ import { ignoring, importLine, lines, served, withCli, withCreatedTypes, withDependencies, withLines } from "./files.mjs";
5
5
  import { envExample, needHelper, needsOf, recordsPart, s3Part } from "./stores.mjs";
6
6
  import { inline, insertInto, itemsAt, nodeAt, parseJsonc, stringAt, withEntries } from "./jsonc.mjs";
7
7
  import { nextConfigOutput, nextJobFiles, nextJobRoutes, nextRouteFiles, nextSweepPath } from "./next.mjs";
@@ -62,13 +62,14 @@ const vercelGitModule = (choices, next) => {
62
62
  const github = choices.serve === "github";
63
63
  const queue = choices.queue === "on";
64
64
  const { maxDuration } = limitsOf(choices);
65
- return lines(`// Git on Vercel's functions, ${served[choices.serve]}${queue ? ", with a merge queue on `main`" : ""}: records and jobs`, `// in ${postgres ? "Postgres" : "Turso"}, packs in ${blob ? "Vercel Blob" : "S3"}, and jobs woken by Vercel Queues. Written by \`ref0-git init\`, and`, "// yours to change: `init` rewrites it only while it reads as written, and `ref0-git doctor`", "// checks it.", choices.serve === "git" && "// Nothing here makes a repo over HTTP: make one from code, as `git.repos.create({ id: 'acme/app' })`.", ...records.external, "", `import { accept, createGitServer, ${queue ? "mergeQueue, " : ""}packs, reject } from '@ref0/git';`, queue && "import type { MergeInput, MergePlan } from '@ref0/git';", "import { bearer, tokens } from '@ref0/git/auth';", "import { engine } from '@ref0/git/engine';", "import { xdiff } from '@ref0/git/node';", choices.serve !== "git" && "import { createRestHandler } from '@ref0/git/rest';", github && "import { createGitHubHandler } from '@ref0/github';", `import { ${[
65
+ return lines(`// Git on Vercel's functions, ${served[choices.serve]}${queue ? ", with a merge queue on `main`" : ""}: records and jobs`, `// in ${postgres ? "Postgres" : "Turso"}, packs in ${blob ? "Vercel Blob" : "S3"}, and jobs woken by Vercel Queues. Written by \`ref0-git init\`, and`, "// yours to change: `init` rewrites it only while it reads as written, and `ref0-git doctor`", "// checks it.", choices.serve === "git" && "// Nothing here makes a repo over HTTP: make one from code, as `git.repos.create({ id: 'acme/app' })`.", ...records.external, "", `import { accept, createGitServer, ${queue ? "mergeQueue, " : ""}packs, reject } from '@ref0/git';`, queue && "import type { MergeInput, MergePlan } from '@ref0/git';", "import { bearer, tokens } from '@ref0/git/auth';", "import { engine } from '@ref0/git/engine';", "import { xdiff } from '@ref0/git/node';", choices.serve !== "git" && "import { createRestHandler } from '@ref0/git/rest';", github && "import { createGitHubHandler } from '@ref0/github';", importLine([
66
66
  "createJobQueue",
67
+ "layerOf",
67
68
  ...records.infra,
68
69
  ...bucket?.infra ?? [],
69
70
  ...blob ? ["vercelBlob"] : [],
70
71
  "vercelQueues"
71
- ].join(", ")} } from '@ref0/infra/promises';`, "", needHelper("the project's Environment Variables"), "", "/** Who `ADMIN_TOKEN` signs in as: it makes repos and tokens, and never pushes. */", "const admin = { id: '_admin' };", "", "// Functions don't run between requests: a commit that saves a job sends a queue message, and the", "// cron in `vercel.json` sweeps for any message that was lost.", `const wake = vercelQueues({ topic: '${topic}' });`, "", records.code, "", `/** The job queue: \`${jobsRoute}\` runs what its messages and the cron's calls name. */`, "export const jobs = createJobQueue({ store });", "", bucket !== void 0 && lines(bucket.code, ""), queue && lines("/** How the queue writes an entry onto `main`: a merge commit, by whoever added it. */", "const merge = ({ entry }: MergeInput): MergePlan => ({", " method: 'merge',", " message: `Merge ${entry.source.replace(/^refs\\/heads\\//, '')}\\n`,", " author: {", " name: entry.actor.id,", " email: `${entry.actor.id}@users.noreply.git`,", " at: Date.now(),", " offset: 0,", " },", "});", ""), "export const git = createGitServer({", " // The functions' `maxDuration`, from `vercel.json`: a clone that would outrun it ends first, with", " // Git's own message.", ` adapter: { store, bucket: ${blob ? "vercelBlob()" : "bucket"}, jobs, maxDuration: '${maxDuration} seconds' },`, " objects: packs(),", " engine: engine({ xdiff: await xdiff() }),", " tokens: tokens(),", ` // Vercel refuses a body over 4.5 MB, so a larger push uploads its pack to ${blob ? "Blob" : "the bucket"}.`, " pushes: { upload: { above: 4 * 1024 * 1024 } },", choices.basePath !== "/" && ` // Git's URLs, Smart HTTP, sign-in and REST, under this path.\n basePath: '${choices.basePath.replace(/\/$/, "")}',`, " auth: bearer({ token: need('ADMIN_TOKEN'), actor: admin }),", " authorize: ({ actor, operation }) => {", " if (actor.anonymous === true) return reject({ message: 'Sign in first' });", "", " if (actor.id === admin.id && operation.kind === 'push') {", " return reject({", " message: \"The admin token can't push\",", " hint: 'Make a write token for yourself: npx ref0-git tokens create --help',", " });", " }", "", " return accept();", " },", queue && " queue: mergeQueue({ target: 'refs/heads/main', merge }),", github && " // Git's events go to the drop-in, which follows each push: a pull request's head, its queue.\n events: (input) => github.events(input),", "});", "", github && "/** GitHub's REST, GraphQL, webhooks and Event Streams, so `gh` and Octokit work. */\nexport const github = createGitHubHandler(git);\n", choices.serve !== "git" && "/** Git's REST, whose `route` and `fetch` serve Git's protocol and sign-in too. */\nexport const rest = createRestHandler(git);\n", next !== void 0 && serveExport(choices));
72
+ ], "@ref0/infra/promises"), "", needHelper("the project's Environment Variables"), "", "/** Who `ADMIN_TOKEN` signs in as: it makes repos and tokens, and never pushes. */", "const admin = { id: '_admin' };", "", "// Functions don't run between requests: a commit that saves a job sends a queue message, and the", "// cron in `vercel.json` sweeps for any message that was lost.", `const wake = vercelQueues({ topic: '${topic}' });`, "", records.code, "", `/** The job queue: \`${jobsRoute}\` runs what its messages and the cron's calls name. */`, "export const jobs = createJobQueue({ store });", "", bucket !== void 0 && lines(bucket.code, ""), queue && lines("/** How the queue writes an entry onto `main`: a merge commit, by whoever added it. */", "const merge = ({ entry }: MergeInput): MergePlan => ({", " method: 'merge',", " message: `Merge ${entry.source.replace(/^refs\\/heads\\//, '')}\\n`,", " author: {", " name: entry.actor.id,", " email: `${entry.actor.id}@users.noreply.git`,", " at: Date.now(),", " offset: 0,", " },", "});", ""), "export const git = createGitServer({", ` adapter: layerOf({ store, bucket: ${blob ? "vercelBlob()" : "bucket"}, jobs }),`, " // The functions' `maxDuration`, from `vercel.json`: a clone that would outrun it ends first, with", " // Git's own message.", ` maxDuration: '${maxDuration} seconds',`, " objects: packs(),", " engine: engine({ xdiff: await xdiff() }),", " tokens: tokens(),", ` // Vercel refuses a body over 4.5 MB, so a larger push uploads its pack to ${blob ? "Blob" : "the bucket"}.`, " pushes: { upload: { above: 4 * 1024 * 1024 } },", choices.basePath !== "/" && ` // Git's URLs, Smart HTTP, sign-in and REST, under this path.\n basePath: '${choices.basePath.replace(/\/$/, "")}',`, " auth: bearer({ token: need('ADMIN_TOKEN'), actor: admin }),", " authorize: ({ actor, operation }) => {", " if (actor.anonymous === true) return reject({ message: 'Sign in first' });", "", " if (actor.id === admin.id && operation.kind === 'push') {", " return reject({", " message: \"The admin token can't push\",", " hint: 'Make a write token for yourself: npx ref0-git tokens create --help',", " });", " }", "", " return accept();", " },", queue && " queue: mergeQueue({ target: 'refs/heads/main', merge }),", github && " // Git's events go to the drop-in, which follows each push: a pull request's head, its queue.\n events: (input) => github.events(input),", "});", "", github && "/** GitHub's REST, GraphQL, webhooks and Event Streams, so `gh` and Octokit work. */\nexport const github = createGitHubHandler(git);\n", choices.serve !== "git" && "/** Git's REST, whose `route` and `fetch` serve Git's protocol and sign-in too. */\nexport const rest = createRestHandler(git);\n", next !== void 0 && serveExport(choices));
72
73
  };
73
74
  /** What `api/git.ts` answers each method with, for what it serves. */
74
75
  const handlers = {
@@ -28,5 +28,5 @@ const packedPath = (name) => {
28
28
  * the release, or the tarball `--from-checkout` names for that package. One it wrote moves to this
29
29
  * run's spec; any other is the person's, a tarball of their own in `vendor/` too, and stays.
30
30
  */
31
- const initWrote = (name, spec) => spec === "0.2.0" || spec !== void 0 && packedPath(name).test(spec);
31
+ const initWrote = (name, spec) => spec === "0.3.0" || spec !== void 0 && packedPath(name).test(spec);
32
32
  export { catalog, frameworkPackages, initWrote, nodeAppPackages, nodePackages, release, specOf, storePackages, vercelPackages };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ref0-git",
3
- "version": "0.2.0",
3
+ "version": "0.3.0",
4
4
  "private": false,
5
5
  "description": "ref0-git, the CLI for a Git host built on @ref0/git, and git-remote-ref0, its remote helper",
6
6
  "license": "Apache-2.0",
@@ -24,8 +24,8 @@
24
24
  },
25
25
  "dependencies": {
26
26
  "@effect/platform-node-shared": "4.1.4",
27
- "@ref0/git": "0.2.0",
28
- "@ref0/infra": "0.2.0",
27
+ "@ref0/git": "0.3.0",
28
+ "@ref0/infra": "0.3.0",
29
29
  "diff": "9.0.0",
30
30
  "effect": "4.1.4"
31
31
  },
@@ -34,7 +34,7 @@
34
34
  "@effect/vitest": "4.1.4",
35
35
  "@libsql/client": "0.18.0",
36
36
  "@libsql/kysely-libsql": "0.4.1",
37
- "@ref0/github": "0.2.0",
37
+ "@ref0/github": "0.3.0",
38
38
  "@tanstack/react-start": "1.169.5",
39
39
  "@types/node": "24.19.2",
40
40
  "@types/pg": "8.23.1",