@zabaca/zbc 0.20.0 → 0.21.1

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.
Files changed (55) hide show
  1. package/package.json +1 -1
  2. package/templates/apps/walgit/CONTEXT.md +37 -0
  3. package/templates/apps/walgit/README.md +193 -4
  4. package/templates/apps/walgit/e2e/harness.ts +2 -2
  5. package/templates/apps/walgit/e2e/scenarios.ts +302 -2
  6. package/templates/apps/walgit/package.json +5 -1
  7. package/templates/apps/walgit/registry.json +1 -1
  8. package/templates/apps/walgit/shared/browse.ts +733 -0
  9. package/templates/apps/walgit/shared/capabilities.ts +17 -0
  10. package/templates/apps/walgit/shared/container-env.ts +9 -0
  11. package/templates/apps/walgit/shared/landing.ts +8 -27
  12. package/templates/apps/walgit/shared/llms.ts +41 -0
  13. package/templates/apps/walgit/shared/mcp.ts +286 -0
  14. package/templates/apps/walgit/shared/policy.ts +21 -0
  15. package/templates/apps/walgit/shared/pooled.ts +31 -0
  16. package/templates/apps/walgit/shared/protocol.ts +140 -0
  17. package/templates/apps/walgit/shared/repo-list.ts +478 -0
  18. package/templates/apps/walgit/shared/store.ts +307 -0
  19. package/templates/apps/walgit/shared/telemetry.ts +79 -6
  20. package/templates/apps/walgit/shared/wal-index.ts +249 -0
  21. package/templates/apps/walgit/shared/web.ts +46 -0
  22. package/templates/apps/walgit/src/announce-main.ts +1 -1
  23. package/templates/apps/walgit/src/announce.ts +1 -1
  24. package/templates/apps/walgit/src/append-only.ts +5 -8
  25. package/templates/apps/walgit/src/browse.ts +230 -0
  26. package/templates/apps/walgit/src/cache.ts +4 -4
  27. package/templates/apps/walgit/src/compact.ts +6 -12
  28. package/templates/apps/walgit/src/delete-repo.ts +4 -3
  29. package/templates/apps/walgit/src/expire.ts +3 -3
  30. package/templates/apps/walgit/src/gc.ts +4 -3
  31. package/templates/apps/walgit/src/git.ts +127 -10
  32. package/templates/apps/walgit/src/hook-main.ts +1 -1
  33. package/templates/apps/walgit/src/http.ts +386 -3
  34. package/templates/apps/walgit/src/limits.ts +1 -1
  35. package/templates/apps/walgit/src/materialize.bench.ts +4 -10
  36. package/templates/apps/walgit/src/materialize.ts +11 -4
  37. package/templates/apps/walgit/src/orphans.ts +3 -3
  38. package/templates/apps/walgit/src/pending.ts +1 -1
  39. package/templates/apps/walgit/src/private.ts +1 -1
  40. package/templates/apps/walgit/src/proposals.ts +3 -3
  41. package/templates/apps/walgit/src/push-cert.ts +10 -1
  42. package/templates/apps/walgit/src/push.ts +11 -9
  43. package/templates/apps/walgit/src/reconcile.ts +4 -3
  44. package/templates/apps/walgit/src/server.ts +29 -2
  45. package/templates/apps/walgit/src/signers.ts +9 -3
  46. package/templates/apps/walgit/src/store-env.ts +8 -21
  47. package/templates/apps/walgit/src/store.ts +12 -241
  48. package/templates/apps/walgit/src/sync.ts +2 -2
  49. package/templates/apps/walgit/src/usage.ts +4 -18
  50. package/templates/apps/walgit/src/verify.ts +2 -2
  51. package/templates/apps/walgit/src/wal-index.ts +20 -239
  52. package/templates/apps/walgit/worker/index.ts +278 -1
  53. package/templates/apps/walgit/worker/mcp.ts +281 -0
  54. /package/templates/apps/walgit/{src → shared}/keys.ts +0 -0
  55. /package/templates/apps/walgit/{src → shared}/ulid.ts +0 -0
@@ -0,0 +1,307 @@
1
+ /**
2
+ * The object-store seam.
3
+ *
4
+ * Everything walgit persists goes through this interface, because the store is
5
+ * the source of truth and swapping it must not be a rewrite: R2 in production,
6
+ * an in-memory implementation in tests, S3/MinIO/Tigris for portability. See
7
+ * this repository's docs/adr/0007-walgit-object-storage-holds-the-log.md.
8
+ *
9
+ * It lives in the Shared Kernel because the bucket is not the container's
10
+ * private resource: the edge reads the same objects, and a second client would
11
+ * be a second set of rules about what a conditional write means (docs/adr/0010).
12
+ * `FileStore` is the one implementation that stays in `src/store.ts` — it is
13
+ * the local disk, which only the container has.
14
+ *
15
+ * The interface is deliberately narrow — five operations, exactly what the WAL
16
+ * needs. In particular it exposes CONDITIONAL writes as a first-class result
17
+ * rather than an exception, because losing a compare-and-swap is a normal
18
+ * outcome on the push path, not an error: two pushes raced and one has to be
19
+ * told to try again.
20
+ */
21
+
22
+ /** A conditional precondition on a write. */
23
+ export type PutCondition =
24
+ /** Write only if the object's current ETag matches (compare-and-swap). */
25
+ | { ifMatch: string }
26
+ /** Write only if the object does not exist yet. */
27
+ | { ifAbsent: true }
28
+
29
+ export type PutResult =
30
+ | { ok: true; etag: string }
31
+ /** The precondition failed: someone else wrote first. Not an error. */
32
+ | { ok: false; reason: 'precondition-failed' }
33
+
34
+ export type GetResult = { body: Uint8Array; etag: string } | null
35
+
36
+ /** Result of a conditional read — the cheap "am I current?" check. */
37
+ export type ConditionalGetResult =
38
+ | { status: 'not-modified' }
39
+ | { status: 'ok'; body: Uint8Array; etag: string }
40
+ | { status: 'absent' }
41
+
42
+ export interface ObjectStore {
43
+ get(key: string): Promise<GetResult>
44
+ /**
45
+ * Read only if the caller's ETag is stale. A `not-modified` answer is a
46
+ * metadata-only round trip, which is what makes "is my cached repo current?"
47
+ * cheap enough to do on every request.
48
+ */
49
+ getIfNoneMatch(key: string, etag: string): Promise<ConditionalGetResult>
50
+ /** Unconditional when `condition` is omitted. */
51
+ put(key: string, body: Uint8Array, condition?: PutCondition): Promise<PutResult>
52
+ delete(key: string): Promise<void>
53
+ /** Keys under a prefix, lexicographically ascending. */
54
+ list(prefix: string): Promise<string[]>
55
+ /**
56
+ * Immediate child prefixes under `prefix`, delimited by `/`.
57
+ *
58
+ * Optional because it is an optimisation, not a capability: a store without
59
+ * it is enumerated by `list` and derivation (see `listRepoIds`). It exists
60
+ * because "which repositories exist?" is one question the bucket can answer
61
+ * in a handful of round trips, and answering it by listing every packfile in
62
+ * the log would make a read-only report the most expensive command walgit
63
+ * has.
64
+ */
65
+ listPrefixes?(prefix: string): Promise<string[]>
66
+ }
67
+
68
+ // ── In-memory implementation ────────────────────────────────────────────────
69
+
70
+ /**
71
+ * For tests. Faithful about the one property that matters: a conditional put
72
+ * evaluates its precondition and swaps atomically with respect to other
73
+ * in-flight puts.
74
+ *
75
+ * `yieldBeforeWrite` exists because JavaScript would otherwise make this test
76
+ * nothing. Without a suspension point between reading the current ETag and
77
+ * writing, every put runs to completion uninterrupted and a broken CAS
78
+ * implementation would still pass. The hook forces the interleaving that a real
79
+ * network round trip would produce.
80
+ */
81
+ export class MemoryStore implements ObjectStore {
82
+ private objects = new Map<string, { body: Uint8Array; etag: string }>()
83
+ private counter = 0
84
+
85
+ constructor(private readonly yieldBeforeWrite: () => Promise<void> = async () => {}) {}
86
+
87
+ private nextEtag(): string {
88
+ this.counter += 1
89
+ return `"mem-${this.counter}"`
90
+ }
91
+
92
+ async get(key: string): Promise<GetResult> {
93
+ const found = this.objects.get(key)
94
+ return found ? { body: found.body, etag: found.etag } : null
95
+ }
96
+
97
+ async getIfNoneMatch(key: string, etag: string): Promise<ConditionalGetResult> {
98
+ const found = this.objects.get(key)
99
+ if (!found) return { status: 'absent' }
100
+ if (found.etag === etag) return { status: 'not-modified' }
101
+ return { status: 'ok', body: found.body, etag: found.etag }
102
+ }
103
+
104
+ async put(key: string, body: Uint8Array, condition?: PutCondition): Promise<PutResult> {
105
+ // Read the precondition's subject, then suspend — this is the window a
106
+ // real store has, and the window a wrong implementation loses data in.
107
+ const before = this.objects.get(key)
108
+ await this.yieldBeforeWrite()
109
+
110
+ // Re-read after the suspension: the check and the swap must both see the
111
+ // same state, which is the whole contract being modelled.
112
+ const current = this.objects.get(key)
113
+ if (condition) {
114
+ if ('ifAbsent' in condition && current) return { ok: false, reason: 'precondition-failed' }
115
+ if ('ifMatch' in condition && current?.etag !== condition.ifMatch) {
116
+ return { ok: false, reason: 'precondition-failed' }
117
+ }
118
+ // A racing writer that landed during the suspension invalidates a
119
+ // precondition that was true when we started.
120
+ if (current?.etag !== before?.etag) return { ok: false, reason: 'precondition-failed' }
121
+ }
122
+
123
+ const etag = this.nextEtag()
124
+ this.objects.set(key, { body, etag })
125
+ return { ok: true, etag }
126
+ }
127
+
128
+ async delete(key: string): Promise<void> {
129
+ this.objects.delete(key)
130
+ }
131
+
132
+ async list(prefix: string): Promise<string[]> {
133
+ return [...this.objects.keys()].filter((k) => k.startsWith(prefix)).sort()
134
+ }
135
+ }
136
+
137
+ // ── S3-compatible implementation (R2, S3, MinIO, Tigris) ────────────────────
138
+
139
+ export interface S3StoreOptions {
140
+ /** e.g. `https://<account>.r2.cloudflarestorage.com` */
141
+ endpoint: string
142
+ bucket: string
143
+ /** Signs each request. `aws4fetch`'s `AwsClient.fetch` satisfies this. */
144
+ fetch: (input: string, init?: RequestInit) => Promise<Response>
145
+ }
146
+
147
+ /**
148
+ * Conditional writes were verified against R2 on 2026-08-20 — 16 concurrent
149
+ * writers against one ETag produced exactly one 200 and fifteen 412s, with no
150
+ * torn writes. See docs/research/walgit-m0-spike/.
151
+ *
152
+ * Portability caveat worth carrying: Tigris honours the same headers but only
153
+ * evaluates them safely on Multi-region or Single-region buckets. Its Global
154
+ * and Dual-region types are strong same-region and eventual cross-region, and a
155
+ * sub-second replication window is exactly wide enough to lose a push race and
156
+ * never reproduce it.
157
+ */
158
+ export class S3Store implements ObjectStore {
159
+ constructor(private readonly opts: S3StoreOptions) {}
160
+
161
+ private url(key: string): string {
162
+ return `${this.opts.endpoint}/${this.opts.bucket}/${key}`
163
+ }
164
+
165
+ async get(key: string): Promise<GetResult> {
166
+ const res = await this.opts.fetch(this.url(key))
167
+ if (res.status === 404) return null
168
+ if (!res.ok) throw new Error(`GET ${key}: HTTP ${res.status}`)
169
+ return { body: new Uint8Array(await res.arrayBuffer()), etag: res.headers.get('etag') ?? '' }
170
+ }
171
+
172
+ async getIfNoneMatch(key: string, etag: string): Promise<ConditionalGetResult> {
173
+ const res = await this.opts.fetch(this.url(key), { headers: { 'If-None-Match': etag } })
174
+ if (res.status === 304) return { status: 'not-modified' }
175
+ if (res.status === 404) return { status: 'absent' }
176
+ if (!res.ok) throw new Error(`GET ${key}: HTTP ${res.status}`)
177
+ return {
178
+ status: 'ok',
179
+ body: new Uint8Array(await res.arrayBuffer()),
180
+ etag: res.headers.get('etag') ?? '',
181
+ }
182
+ }
183
+
184
+ async put(key: string, body: Uint8Array, condition?: PutCondition): Promise<PutResult> {
185
+ const headers: Record<string, string> = {}
186
+ if (condition && 'ifMatch' in condition) headers['If-Match'] = condition.ifMatch
187
+ if (condition && 'ifAbsent' in condition) headers['If-None-Match'] = '*'
188
+
189
+ // `Uint8Array` is a valid BodyInit at runtime; the cast is only to bridge
190
+ // TS 5.7's `Uint8Array<ArrayBufferLike>` against lib.dom's narrower
191
+ // `BodyInit`, which does not accept the generic form.
192
+ const res = await this.opts.fetch(this.url(key), {
193
+ method: 'PUT',
194
+ body: body as unknown as BodyInit,
195
+ headers,
196
+ })
197
+ // 412 is the documented precondition failure. 409 is included because
198
+ // S3-compatible stores have historically used it for the same condition
199
+ // under concurrent load; treating it as an error would surface a normal
200
+ // race as an outage.
201
+ if (res.status === 412 || res.status === 409)
202
+ return { ok: false, reason: 'precondition-failed' }
203
+ if (!res.ok) throw new Error(`PUT ${key}: HTTP ${res.status}`)
204
+ return { ok: true, etag: res.headers.get('etag') ?? '' }
205
+ }
206
+
207
+ async delete(key: string): Promise<void> {
208
+ const res = await this.opts.fetch(this.url(key), { method: 'DELETE' })
209
+ if (!res.ok && res.status !== 404) throw new Error(`DELETE ${key}: HTTP ${res.status}`)
210
+ }
211
+
212
+ async list(prefix: string): Promise<string[]> {
213
+ const keys: string[] = []
214
+ let token: string | undefined
215
+ do {
216
+ const params = new URLSearchParams({ 'list-type': '2', prefix })
217
+ if (token) params.set('continuation-token', token)
218
+ const res = await this.opts.fetch(`${this.opts.endpoint}/${this.opts.bucket}?${params}`)
219
+ if (!res.ok) throw new Error(`LIST ${prefix}: HTTP ${res.status}`)
220
+ const xml = await res.text()
221
+ for (const m of xml.matchAll(/<Key>([^<]+)<\/Key>/g)) keys.push(m[1]!)
222
+ token = xml.match(/<NextContinuationToken>([^<]+)<\/NextContinuationToken>/)?.[1]
223
+ } while (token)
224
+ return keys.sort()
225
+ }
226
+
227
+ /**
228
+ * `delimiter=/` makes the store roll every key sharing a child prefix into a
229
+ * single `CommonPrefixes` entry, so a bucket holding a million WAL objects
230
+ * still answers "which repositories are there?" in one page per thousand
231
+ * repositories.
232
+ */
233
+ async listPrefixes(prefix: string): Promise<string[]> {
234
+ const prefixes: string[] = []
235
+ let token: string | undefined
236
+ do {
237
+ const params = new URLSearchParams({ 'list-type': '2', prefix, delimiter: '/' })
238
+ if (token) params.set('continuation-token', token)
239
+ const res = await this.opts.fetch(`${this.opts.endpoint}/${this.opts.bucket}?${params}`)
240
+ if (!res.ok) throw new Error(`LIST ${prefix}: HTTP ${res.status}`)
241
+ const xml = await res.text()
242
+ for (const block of xml.matchAll(/<CommonPrefixes>([\s\S]*?)<\/CommonPrefixes>/g)) {
243
+ const found = /<Prefix>([^<]+)<\/Prefix>/.exec(block[1]!)
244
+ if (found) prefixes.push(found[1]!)
245
+ }
246
+ token = xml.match(/<NextContinuationToken>([^<]+)<\/NextContinuationToken>/)?.[1]
247
+ } while (token)
248
+ return prefixes.sort()
249
+ }
250
+ }
251
+
252
+ /**
253
+ * The S3 half of "build the store from the environment".
254
+ *
255
+ * Both halves need it and neither may own it: the container reads it out of
256
+ * `process.env` (`src/store-env.ts`, which also has the `WALGIT_STORE_DIR`
257
+ * disk branch only it can serve), and the Worker reads it off a binding object
258
+ * to answer the web view at the edge (`worker/index.ts`). It was written twice,
259
+ * including the one comment that is genuinely hard-won — R2 ignores the region
260
+ * but SigV4 does not, and an absent one signs differently and 403s with nothing
261
+ * useful in the body (docs/adr/0010).
262
+ *
263
+ * `null` means "not configured", which the two halves read differently on
264
+ * purpose: the push path treats it as fatal (there is nowhere to persist to, so
265
+ * nothing may be acknowledged) while a read path treats it as "there is no log
266
+ * to read".
267
+ *
268
+ * The signer is injected rather than imported so this module keeps importing no
269
+ * runtime — `aws4fetch`'s `AwsClient` is fetch-based and works in both halves,
270
+ * but the dependency belongs to the caller that has one.
271
+ */
272
+ export function s3StoreFrom(
273
+ env: {
274
+ WALGIT_S3_ENDPOINT?: string | undefined
275
+ WALGIT_S3_BUCKET?: string | undefined
276
+ WALGIT_S3_ACCESS_KEY_ID?: string | undefined
277
+ WALGIT_S3_SECRET_ACCESS_KEY?: string | undefined
278
+ WALGIT_S3_REGION?: string | undefined
279
+ },
280
+ /** Builds a request signer for these credentials — `new AwsClient({…})`. */
281
+ signer: (credentials: {
282
+ accessKeyId: string
283
+ secretAccessKey: string
284
+ service: 's3'
285
+ region: string
286
+ }) => { fetch: (input: string, init?: RequestInit) => Promise<Response> },
287
+ ): ObjectStore | null {
288
+ const endpoint = env.WALGIT_S3_ENDPOINT
289
+ const bucket = env.WALGIT_S3_BUCKET
290
+ const accessKeyId = env.WALGIT_S3_ACCESS_KEY_ID
291
+ const secretAccessKey = env.WALGIT_S3_SECRET_ACCESS_KEY
292
+ if (!endpoint || !bucket || !accessKeyId || !secretAccessKey) return null
293
+
294
+ const client = signer({
295
+ accessKeyId,
296
+ secretAccessKey,
297
+ service: 's3',
298
+ // R2 ignores the region but the SigV4 signature does not: an absent region
299
+ // signs differently and every request 403s with nothing useful in the body.
300
+ region: env.WALGIT_S3_REGION ?? 'auto',
301
+ })
302
+ return new S3Store({
303
+ endpoint: endpoint.replace(/\/$/, ''),
304
+ bucket,
305
+ fetch: (input, init) => client.fetch(input, init),
306
+ })
307
+ }
@@ -25,12 +25,15 @@
25
25
 
26
26
  import {
27
27
  HEALTH_PATH,
28
+ MCP_PATH,
28
29
  PROVENANCE_PATH,
29
30
  REJECT_HEADER,
30
31
  REPO_ID,
32
+ REPOS_PATH,
31
33
  SERVED_HEADER,
32
34
  SMART_HTTP,
33
35
  normalizeReject,
36
+ wantsBrowse,
34
37
  type RejectKind,
35
38
  } from './protocol'
36
39
 
@@ -65,6 +68,23 @@ export type RequestKind =
65
68
  // bucket and these are requests walgit now answers — and because the count
66
69
  // is the measure of what the route absorbed.
67
70
  | 'favicon'
71
+ // The repository list (`shared/repo-list.ts`), answered at the edge off the
72
+ // log. Its own kind for the reason `mcp` and `provenance` are — `other` is
73
+ // the unroutable bucket and this is a request walgit answers — and counted
74
+ // separately from `landing` because the two measure different things: the
75
+ // page is what a stranger reads, the list is what somebody who has decided
76
+ // to look around reads. It is recorded even on a deployment with the
77
+ // capability off, where the path falls through to a container that does not
78
+ // route it: the row is then a 404, which is the honest reading and a useful
79
+ // one (it is demand for a switch nobody has flipped).
80
+ | 'list'
81
+ // One of the two repository pages (`shared/browse.ts`). Its own kind for the
82
+ // reason `list` is — `other` is the unroutable bucket and this is a request
83
+ // walgit answers — and, unlike the list, it NAMES a repository, because it is
84
+ // about exactly one. It is recorded even on a deployment with the capability
85
+ // off, where the path falls through to a container that does not route it:
86
+ // the row is then a 404, which is the honest reading and a useful one.
87
+ | 'browse'
68
88
  | 'health'
69
89
  // Someone asking who pushed (docs/adr/0011). Its own kind rather than
70
90
  // `other`, because `other` is the unroutable bucket and a provenance read is
@@ -72,6 +92,13 @@ export type RequestKind =
72
92
  // demand for the feature and any refusal it produces, and would lose the
73
93
  // repository name with them.
74
94
  | 'provenance'
95
+ // An MCP client calling a tool (`shared/mcp.ts`), answered at the edge like
96
+ // the documents above. Its own kind rather than `other` for the reason
97
+ // `provenance` is, and one kind for the whole endpoint rather than one per
98
+ // tool: the tool and the repository it names are inside a JSON-RPC body, and
99
+ // a classifier that read request bodies to label a row would be buffering
100
+ // every push to count it.
101
+ | 'mcp'
75
102
  | 'other'
76
103
 
77
104
  export type Outcome = 'ok' | 'reject'
@@ -143,6 +170,11 @@ export function otherBucket(pathname: string): OtherBucket {
143
170
  */
144
171
  export function classifyRequest(method: string, pathname: string, search: string): RequestFacts {
145
172
  if (pathname === HEALTH_PATH) return { kind: 'health', repo: '' }
173
+ // No repository: the name a tool acts on travels in the JSON-RPC body, and
174
+ // the body is not something this function reads (see `RequestKind`).
175
+ if (pathname === MCP_PATH) return { kind: 'mcp', repo: '' }
176
+ // No repository: the list is about all of them.
177
+ if (pathname === REPOS_PATH) return { kind: 'list', repo: '' }
146
178
  if (pathname === '/' && (method === 'GET' || method === 'HEAD')) {
147
179
  return { kind: 'instructions', repo: '' }
148
180
  }
@@ -159,7 +191,25 @@ export function classifyRequest(method: string, pathname: string, search: string
159
191
  }
160
192
 
161
193
  const route = SMART_HTTP.exec(pathname)
162
- if (!route) return { kind: 'other', repo: '', bucket: otherBucket(pathname) }
194
+ if (!route) {
195
+ // `/<name>` and `/<name>/tree/…` — read through the same `wantsBrowse` the
196
+ // edge routes on (`shared/protocol.ts`), so a path one claimed and the
197
+ // other did not cannot become a metric describing traffic that never
198
+ // happened. Below `SMART_HTTP` because a clone URL is not a browse URL and
199
+ // the git grammar is the one that must win.
200
+ //
201
+ // A path whose SHAPE already has a name keeps it. `/wp-login.php` and
202
+ // `/.env` are repository-shaped — a repository may be called `wp-login.php`
203
+ // — but they are the scanner baseline those buckets exist to measure, and
204
+ // counting them as people reading a repository page would put the noise
205
+ // into the one number a launch is read by. The edge still routes them: a
206
+ // browse of a name the log has no Index for is a 404 either way.
207
+ const bucket = otherBucket(pathname)
208
+ const browse =
209
+ bucket === 'bare-name' || bucket === 'else' ? wantsBrowse(method, pathname) : null
210
+ if (browse) return { kind: 'browse', repo: browse.repo }
211
+ return { kind: 'other', repo: '', bucket }
212
+ }
163
213
  const repo = route[1]!
164
214
 
165
215
  if (route[2] === 'git-upload-pack') return { kind: 'clone', repo }
@@ -190,14 +240,37 @@ export function classifyOutcome(
190
240
  status: number,
191
241
  headers: { get(name: string): string | null },
192
242
  ): { outcome: Outcome; reject: RejectKind | '' } {
193
- const declared = headers.get(REJECT_HEADER)
194
- if (declared) return { outcome: 'reject', reject: normalizeReject(declared) }
195
- if (status < 400) return { outcome: 'ok', reject: '' }
196
- if (headers.get(SERVED_HEADER) === null) return { outcome: 'reject', reject: 'edge' }
197
- return { outcome: 'reject', reject: fromStatus(status) }
243
+ return outcomeOf({
244
+ status,
245
+ declared: headers.get(REJECT_HEADER),
246
+ served: headers.get(SERVED_HEADER) !== null,
247
+ })
248
+ }
249
+
250
+ /**
251
+ * The same judgement, from the two facts rather than from a `Headers`.
252
+ *
253
+ * Some callers have already read the stamps into values — the browse page
254
+ * carries them back from the container as `{ served, reject }`
255
+ * (`shared/browse.ts`), because `shared/` has no `Headers` to hand around. They
256
+ * ask this directly rather than building a stand-in object for the reader
257
+ * above to take apart again.
258
+ */
259
+ export function outcomeOf(answer: {
260
+ status: number
261
+ /** `REJECT_HEADER`'s value, or `null`/`''` where the layer named no kind. */
262
+ declared: string | null
263
+ /** The container stamped it (`SERVED_HEADER`). */
264
+ served: boolean
265
+ }): { outcome: Outcome; reject: RejectKind | '' } {
266
+ if (answer.declared) return { outcome: 'reject', reject: normalizeReject(answer.declared) }
267
+ if (answer.status < 400) return { outcome: 'ok', reject: '' }
268
+ if (!answer.served) return { outcome: 'reject', reject: 'edge' }
269
+ return { outcome: 'reject', reject: fromStatus(answer.status) }
198
270
  }
199
271
 
200
272
  function fromStatus(status: number): RejectKind {
273
+ if (status === 400) return 'invalid'
201
274
  if (status === 401 || status === 403) return 'unauthorized'
202
275
  if (status === 404) return 'not-found'
203
276
  if (status === 409) return 'collision'