@zabaca/zbc 0.21.0 → 0.22.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.
Files changed (52) hide show
  1. package/package.json +6 -1
  2. package/templates/apps/walgit/CONTEXT.md +25 -0
  3. package/templates/apps/walgit/README.md +152 -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/shared/browse.ts +733 -0
  7. package/templates/apps/walgit/shared/capabilities.ts +17 -0
  8. package/templates/apps/walgit/shared/container-env.ts +9 -0
  9. package/templates/apps/walgit/shared/landing.ts +8 -27
  10. package/templates/apps/walgit/shared/llms.ts +25 -0
  11. package/templates/apps/walgit/shared/policy.ts +21 -0
  12. package/templates/apps/walgit/shared/pooled.ts +31 -0
  13. package/templates/apps/walgit/shared/protocol.ts +120 -0
  14. package/templates/apps/walgit/shared/repo-list.ts +478 -0
  15. package/templates/apps/walgit/shared/store.ts +307 -0
  16. package/templates/apps/walgit/shared/telemetry.ts +68 -6
  17. package/templates/apps/walgit/shared/wal-index.ts +249 -0
  18. package/templates/apps/walgit/shared/web.ts +46 -0
  19. package/templates/apps/walgit/src/announce-main.ts +1 -1
  20. package/templates/apps/walgit/src/announce.ts +1 -1
  21. package/templates/apps/walgit/src/append-only.ts +5 -8
  22. package/templates/apps/walgit/src/browse.ts +230 -0
  23. package/templates/apps/walgit/src/cache.ts +4 -4
  24. package/templates/apps/walgit/src/compact.ts +6 -12
  25. package/templates/apps/walgit/src/delete-repo.ts +4 -3
  26. package/templates/apps/walgit/src/expire.ts +3 -3
  27. package/templates/apps/walgit/src/gc.ts +4 -3
  28. package/templates/apps/walgit/src/git.ts +127 -10
  29. package/templates/apps/walgit/src/hook-main.ts +1 -1
  30. package/templates/apps/walgit/src/http.ts +386 -3
  31. package/templates/apps/walgit/src/limits.ts +1 -1
  32. package/templates/apps/walgit/src/materialize.bench.ts +4 -10
  33. package/templates/apps/walgit/src/materialize.ts +11 -4
  34. package/templates/apps/walgit/src/orphans.ts +3 -3
  35. package/templates/apps/walgit/src/pending.ts +1 -1
  36. package/templates/apps/walgit/src/private.ts +1 -1
  37. package/templates/apps/walgit/src/proposals.ts +3 -3
  38. package/templates/apps/walgit/src/push-cert.ts +10 -1
  39. package/templates/apps/walgit/src/push.ts +11 -9
  40. package/templates/apps/walgit/src/reconcile.ts +4 -3
  41. package/templates/apps/walgit/src/server.ts +29 -2
  42. package/templates/apps/walgit/src/signers.ts +9 -3
  43. package/templates/apps/walgit/src/store-env.ts +8 -21
  44. package/templates/apps/walgit/src/store.ts +12 -241
  45. package/templates/apps/walgit/src/sync.ts +2 -2
  46. package/templates/apps/walgit/src/usage.ts +4 -18
  47. package/templates/apps/walgit/src/verify.ts +2 -2
  48. package/templates/apps/walgit/src/wal-index.ts +20 -239
  49. package/templates/apps/walgit/worker/index.ts +232 -1
  50. package/templates/infra/modules/cloudflare-zone/index.ts +83 -9
  51. /package/templates/apps/walgit/{src → shared}/keys.ts +0 -0
  52. /package/templates/apps/walgit/{src → shared}/ulid.ts +0 -0
@@ -0,0 +1,733 @@
1
+ /**
2
+ * Browsing a repository: the rules both halves obey, and the two pages.
3
+ *
4
+ * The container answers `/_walgit/browse` (`src/http.ts`) because a tree is
5
+ * read from git objects and only the Cache holds those — the Index carries the
6
+ * full ref state and not one commit, so unlike the repository list this cannot
7
+ * be answered at the edge off the log. What IS shared is everything around that
8
+ * read: which ref a URL names, where a ref ends and a path begins, which branch
9
+ * is the default, and what the answer looks like as a page.
10
+ *
11
+ * ── the ref rules live here, not in the URL ─────────────────────────────────
12
+ *
13
+ * A branch name may contain slashes, so `/<name>/tree/feature/x/src` says
14
+ * nothing about where the ref ends. The Index is the only thing that knows, so
15
+ * the split is LONGEST-PREFIX against the refs it holds (`splitRefPath`), and
16
+ * the endpoint takes the remainder whole. A ref is an Index key or a full oid
17
+ * and nothing else: not a `HEAD`, not a rev-parse expression, not `main^{}`.
18
+ * That is a security property as much as a product one — whatever is accepted
19
+ * here reaches `git ls-tree` as an operand.
20
+ *
21
+ * ── the default branch comes from the Index ─────────────────────────────────
22
+ *
23
+ * `main`, else `master`, else the first branch by name. Never the Cache's
24
+ * `HEAD`: the Cache is disposable and a freshly Materialized one has whatever
25
+ * `init` left behind, which is a different answer on a cold node than on a warm
26
+ * one for the same repository (ADR-0007).
27
+ *
28
+ * ── a value, not a Response ─────────────────────────────────────────────────
29
+ *
30
+ * Like `shared/repo-list.ts`: this module states the status, the headers and the
31
+ * body, the Worker owns the `Response`, and `shared/` imports no runtime
32
+ * (ADR-0010). The one thing it cannot do for itself is reach the container, so
33
+ * that arrives as `ask` — which is also what lets the e2e suite drive the very
34
+ * same renderer against a real node.
35
+ */
36
+
37
+ import type { Capabilities } from './capabilities'
38
+ import { escapeHtml, describeHours } from './landing'
39
+ import { REPOS_PATH, type BrowseKind, type BrowseRoute } from './protocol'
40
+ import type { EdgeResponse } from './repo-list'
41
+ import { WEB_STYLE, webCacheControl } from './web'
42
+
43
+ /** A full object id, as git writes one. The one ref spelling that is not a ref. */
44
+ export const OID = /^[0-9a-f]{40}$/
45
+
46
+ /** One entry in a tree, as one level of `ls-tree` reports it. */
47
+ export interface TreeEntry {
48
+ name: string
49
+ /**
50
+ * What it is, in the four kinds a browser has to render differently. git's
51
+ * own vocabulary is `blob`/`tree`/`commit` plus a mode, and a reader cannot
52
+ * see a mode — so a symlink and a gitlink are kinds here rather than
53
+ * footnotes on `blob` and `commit`.
54
+ */
55
+ kind: 'tree' | 'blob' | 'symlink' | 'submodule'
56
+ oid: string
57
+ /** Bytes, for a blob. `null` for everything git does not weigh. */
58
+ size: number | null
59
+ /** A symlink's target, and nothing else's. */
60
+ target?: string
61
+ }
62
+
63
+ /** One ref, as the Index holds it. Full names only: `main` is not a ref. */
64
+ export interface BrowseRef {
65
+ name: string
66
+ oid: string
67
+ }
68
+
69
+ /** What `op=refs` answers: the repository, without touching the Cache. */
70
+ export interface BrowseRefsAnswer {
71
+ repo: string
72
+ /** The full ref name, or `null` for a repository holding no branch. */
73
+ defaultBranch: string | null
74
+ refs: BrowseRef[]
75
+ /** ISO instant of the newest push entry, or `null` when there is none. */
76
+ lastPush: string | null
77
+ }
78
+
79
+ /** What `op=tree` answers: the same, plus one level of one directory. */
80
+ export interface BrowseTreeAnswer extends BrowseRefsAnswer {
81
+ /** The ref this tree was read at — a full ref name, or an oid. */
82
+ ref: string
83
+ /** The directory, with no leading or trailing slash. `''` is the root. */
84
+ path: string
85
+ entries: TreeEntry[]
86
+ /** The README this directory holds, at the root only. */
87
+ readme?: Readme
88
+ }
89
+
90
+ /**
91
+ * How much of a file walgit will put on a page: 1 MiB.
92
+ *
93
+ * The cap is asked of `cat-file -s` BEFORE the content is read, so a file above
94
+ * it never reaches the container's memory — this is a bound on work done in the
95
+ * one process that is also serving pushes, not just on bytes shipped. Above it
96
+ * the page offers the raw link and nothing else, and raw has no cap of its own:
97
+ * a download is what a file too big to render is for.
98
+ */
99
+ export const BLOB_MAX_BYTES = 1024 * 1024
100
+
101
+ /** What `op=blob` answers: the repository, and one file at one ref. */
102
+ export interface BrowseBlobAnswer extends BrowseRefsAnswer {
103
+ ref: string
104
+ /** The file, with no leading slash. Never `''` — a blob has a name. */
105
+ path: string
106
+ /** Bytes, as git weighs the object. Always known, even when the text is not. */
107
+ size: number
108
+ /**
109
+ * The content, or `null` when there is deliberately none: a file over
110
+ * `BLOB_MAX_BYTES` (never read) or one holding a NUL byte (read, and not
111
+ * something a page can show). Both offer the raw link instead.
112
+ */
113
+ text: string | null
114
+ binary: boolean
115
+ oversize: boolean
116
+ }
117
+
118
+ /** A README under a tree, shown as text and never rendered as markup. */
119
+ export interface Readme {
120
+ name: string
121
+ text: string
122
+ }
123
+
124
+ /** One commit, as the history page shows one. */
125
+ export interface Commit {
126
+ oid: string
127
+ /** `Name <email>`, as git records it. */
128
+ author: string
129
+ /** ISO 8601, from git's `%aI`. */
130
+ date: string
131
+ subject: string
132
+ }
133
+
134
+ /** What `op=log` answers: one page of history, and where the next begins. */
135
+ export interface BrowseLogAnswer extends BrowseRefsAnswer {
136
+ ref: string
137
+ commits: Commit[]
138
+ /**
139
+ * The oid the next page starts at, or `null` at the end of the history.
140
+ *
141
+ * The LAST commit on this page rather than the one after it: the cursor is a
142
+ * commit walgit has named, so a next page is built from what the reader was
143
+ * shown rather than from an object nobody has seen.
144
+ */
145
+ next: string | null
146
+ }
147
+
148
+ /**
149
+ * The README a directory listing holds, by the fixed preference order.
150
+ *
151
+ * `README`, then `README.md`, then `README.txt`, case-insensitively — the names
152
+ * GitHub made a convention, and only those three. A repository holding two of
153
+ * them gets the first by THIS order rather than by tree order, so the same
154
+ * repository shows the same file wherever it is read.
155
+ */
156
+ export function readmeEntry(entries: TreeEntry[]): TreeEntry | null {
157
+ for (const wanted of ['readme', 'readme.md', 'readme.txt']) {
158
+ const found = entries.find(
159
+ (entry) => entry.kind === 'blob' && entry.name.toLowerCase() === wanted,
160
+ )
161
+ if (found) return found
162
+ }
163
+ return null
164
+ }
165
+
166
+ /**
167
+ * The default branch, from the Index.
168
+ *
169
+ * `main`, else `master`, else the first branch by name — and only ever a
170
+ * BRANCH: a repository holding nothing but tags and `refs/walgit/*` has no
171
+ * default, which is `null` rather than a tag pretending to be one.
172
+ */
173
+ export function defaultBranch(refs: Record<string, string>): string | null {
174
+ // `sort` on the array `filter` just made, not `toSorted`: `shared/` is
175
+ // compiled against the Workers runtime's lib as well as bun's, and that one
176
+ // is below es2023.
177
+ const branches = Object.keys(refs)
178
+ .filter((name) => name.startsWith('refs/heads/'))
179
+ .sort()
180
+ if (branches.includes('refs/heads/main')) return 'refs/heads/main'
181
+ if (branches.includes('refs/heads/master')) return 'refs/heads/master'
182
+ return branches[0] ?? null
183
+ }
184
+
185
+ /**
186
+ * The full ref name a reader's spelling means, or `null`.
187
+ *
188
+ * An Index key, with `refs/heads/` or `refs/tags/` allowed to be left off —
189
+ * which is what makes `main` and `v1` work in a URL — or a full oid, which is
190
+ * returned verbatim because there is no ref to name it by.
191
+ */
192
+ export function resolveRef(refs: Record<string, string>, requested: string): string | null {
193
+ if (requested === '') return null
194
+ if (OID.test(requested)) return requested
195
+ for (const candidate of [requested, `refs/heads/${requested}`, `refs/tags/${requested}`]) {
196
+ if (refs[candidate] !== undefined) return candidate
197
+ }
198
+ return null
199
+ }
200
+
201
+ /** Where a ref ends and a path begins, in one run-together URL remainder. */
202
+ export interface RefPath {
203
+ /** A full ref name, or an oid. */
204
+ ref: string
205
+ path: string
206
+ }
207
+
208
+ /**
209
+ * Split `feature/x/src/lib` into the ref that resolves and the path that is
210
+ * left, LONGEST prefix first.
211
+ *
212
+ * Longest rather than shortest because a repository may hold both `feature/x`
213
+ * and `feature/x/deeper`, and the deeper one is the ref the URL names when it
214
+ * is there. `null` when no prefix resolves, which is a 404 and never a guess.
215
+ */
216
+ export function splitRefPath(refs: Record<string, string>, rest: string): RefPath | null {
217
+ const segments = rest.split('/').filter((segment) => segment !== '')
218
+ for (let take = segments.length; take > 0; take--) {
219
+ const ref = resolveRef(refs, segments.slice(0, take).join('/'))
220
+ if (ref !== null) return { ref, path: segments.slice(take).join('/') }
221
+ }
222
+ return null
223
+ }
224
+
225
+ /**
226
+ * The path a reader asked for, cleaned — or `null` when it is one walgit will
227
+ * not carry.
228
+ *
229
+ * `..` is refused rather than resolved: a path here is DATA about a git tree
230
+ * and `..` means nothing inside one, so the only reason to send it is to find
231
+ * out what this code does with it. A segment beginning `-` is refused for the
232
+ * reason `src/git.ts` fences operands at all — git reads an argument starting
233
+ * with `-` as an option wherever one is allowed, and defence in depth is what
234
+ * keeps that a fact about two layers rather than one.
235
+ */
236
+ export function cleanPath(raw: string): string | null {
237
+ const segments = raw.split('/').filter((segment) => segment !== '')
238
+ for (const segment of segments) {
239
+ if (segment === '..' || segment === '.') return null
240
+ if (segment.startsWith('-')) return null
241
+ }
242
+ return segments.join('/')
243
+ }
244
+
245
+ // ── The edge ────────────────────────────────────────────────────────────────
246
+
247
+ /** The container's answer to one browse query, as the edge sees it. */
248
+ export interface ContainerAnswer {
249
+ status: number
250
+ /** The body, verbatim: JSON when the container answered, text when it refused. */
251
+ text: string
252
+ /** `content-type`, so a refusal is passed through as what it is. */
253
+ contentType: string
254
+ /** The container stamped it (`SERVED_HEADER`) — not something in front of it. */
255
+ served: boolean
256
+ /** What kind of refusal the container named (`REJECT_HEADER`), or `''`. */
257
+ reject: string
258
+ /** The refusal's own headers that a client must see — the two challenges. */
259
+ challenges: string[]
260
+ }
261
+
262
+ export interface BrowseDeps {
263
+ /** Ask the container. The query is the whole `?…` string. */
264
+ ask: (query: string) => Promise<ContainerAnswer>
265
+ /** What this deployment offers — the cache rule and the window read from it. */
266
+ caps: Capabilities
267
+ /** The clock the retention line is measured on, injectable for a test. */
268
+ now?: () => number
269
+ }
270
+
271
+ /**
272
+ * What the Worker knows about the request, and nothing about its runtime.
273
+ *
274
+ * The verb is deliberately absent: `wantsBrowse` has already settled that this
275
+ * is a GET or a HEAD, and the difference between them is dropping the body,
276
+ * which is the Worker's job because a body is a runtime thing.
277
+ */
278
+ export interface BrowseRequest {
279
+ /** The `Accept` header, verbatim. HTML for a browser, anything else is JSON. */
280
+ accept: string
281
+ /**
282
+ * The history cursor from the URL's query, or `null`.
283
+ *
284
+ * The one thing a browse URL carries outside its path. Passed through rather
285
+ * than validated here: a cursor is a fact about git's history, so the
286
+ * container is where it is judged (and refused).
287
+ */
288
+ before: string | null
289
+ }
290
+
291
+ /** A browse answered, plus what the container said about answering it. */
292
+ export interface BrowseEdgeResponse extends EdgeResponse {
293
+ upstream: Pick<ContainerAnswer, 'status' | 'served' | 'reject'>
294
+ }
295
+
296
+ /**
297
+ * One browse page, as a status, headers and a body.
298
+ *
299
+ * The container is asked exactly once — `op=tree` carries the ref list too, so
300
+ * the page that shows both is one round trip rather than two — and a refusal is
301
+ * passed through verbatim, challenges included, because a 401 a browser cannot
302
+ * answer is a page nobody can open.
303
+ */
304
+ export async function browseResponse(
305
+ route: BrowseRoute,
306
+ request: BrowseRequest,
307
+ deps: BrowseDeps,
308
+ ): Promise<BrowseEdgeResponse> {
309
+ // One `op` per page kind, and the remainder passed whole — only the Index
310
+ // knows where the ref ends. `raw` never arrives here: it is bytes rather than
311
+ // a page, so the Worker streams it from the container instead (`worker/`).
312
+ const op = route.kind === 'commits' ? 'log' : route.kind
313
+ const query =
314
+ `?repo=${encodeURIComponent(route.repo)}&op=${op}` +
315
+ (route.rest === '' ? '' : `&ref=${encodeURIComponent(route.rest)}`) +
316
+ (request.before === null ? '' : `&before=${encodeURIComponent(request.before)}`)
317
+ const answer = await deps.ask(query)
318
+ const upstream = { status: answer.status, served: answer.served, reject: answer.reject }
319
+
320
+ const wantsHtml = request.accept.toLowerCase().includes('text/html')
321
+
322
+ if (answer.status >= 400) {
323
+ // Verbatim, and that includes the two `WWW-Authenticate` lines a Private
324
+ // repository is refused with: the browse gate IS the clone gate
325
+ // (ADR-0013), and rewriting the refusal here would be a second one.
326
+ const headers: Record<string, string> = {
327
+ 'content-type': answer.contentType || 'text/plain; charset=utf-8',
328
+ 'cache-control': 'no-store',
329
+ 'x-robots-tag': 'noindex',
330
+ }
331
+ if (answer.challenges.length > 0) headers['www-authenticate'] = answer.challenges.join(', ')
332
+ return { status: answer.status, headers, body: answer.text, upstream }
333
+ }
334
+
335
+ if (!wantsHtml) {
336
+ return {
337
+ status: answer.status,
338
+ headers: {
339
+ 'content-type': 'application/json; charset=utf-8',
340
+ 'cache-control': webCacheControl(deps.caps),
341
+ 'x-robots-tag': 'noindex',
342
+ },
343
+ body: answer.text,
344
+ upstream,
345
+ }
346
+ }
347
+
348
+ let parsed: unknown
349
+ try {
350
+ parsed = JSON.parse(answer.text)
351
+ } catch {
352
+ // The container answered 200 with something this page cannot render. A 502
353
+ // rather than a broken page, and counted as the edge refusal it is.
354
+ return {
355
+ status: 502,
356
+ headers: { 'content-type': 'text/plain; charset=utf-8', 'cache-control': 'no-store' },
357
+ body: 'walgit: the browse answer could not be read\n',
358
+ upstream,
359
+ }
360
+ }
361
+
362
+ return {
363
+ status: 200,
364
+ headers: {
365
+ 'content-type': 'text/html; charset=utf-8',
366
+ 'cache-control': webCacheControl(deps.caps),
367
+ // A repository page is not one anyone should reach from a search engine,
368
+ // and on a credentialed deployment it is not one a crawler can read at
369
+ // all. Stated in the header as well as the document, exactly as the list
370
+ // states it, because a crawler that fetched it before reading the markup
371
+ // has already been told.
372
+ 'x-robots-tag': 'noindex',
373
+ // There is no script on this page and no resource to load: nothing may
374
+ // load, nothing may connect, nothing may post.
375
+ 'content-security-policy':
376
+ "default-src 'none'; style-src 'unsafe-inline'; img-src data:; " +
377
+ "base-uri 'none'; form-action 'none'",
378
+ },
379
+ body:
380
+ route.kind === 'blob'
381
+ ? renderBlob(parsed as BrowseBlobAnswer, deps.caps, deps.now?.())
382
+ : route.kind === 'commits'
383
+ ? renderLog(parsed as BrowseLogAnswer, deps.caps, deps.now?.())
384
+ : renderBrowse(parsed as BrowseTreeAnswer, deps.caps, deps.now?.()),
385
+ upstream,
386
+ }
387
+ }
388
+
389
+ // ── The page ────────────────────────────────────────────────────────────────
390
+
391
+ /**
392
+ * What is left of the window, in the landing page's own words.
393
+ *
394
+ * `describeHours` and the same arithmetic the sweeper runs on the same fact —
395
+ * hours since the last push — so a page cannot promise a repository a lifetime
396
+ * the sweeper does not honour. Rounded UP, because "expires in 0 hours" on a
397
+ * repository that has 50 minutes left reads as gone.
398
+ */
399
+ export function expiresIn(lastPush: string | null, caps: Capabilities, now: number): string | null {
400
+ if (caps.retentionHours === null || lastPush === null) return null
401
+ const at = Date.parse(lastPush)
402
+ if (!Number.isFinite(at)) return null
403
+ const left = Math.ceil((at + caps.retentionHours * 3_600_000 - now) / 3_600_000)
404
+ return left <= 0 ? 'expires at any moment' : `expires in ${describeHours(left)}`
405
+ }
406
+
407
+ /** A directory's parent path, or `null` at the root. */
408
+ function parentOf(path: string): string | null {
409
+ if (path === '') return null
410
+ const cut = path.lastIndexOf('/')
411
+ return cut === -1 ? '' : path.slice(0, cut)
412
+ }
413
+
414
+ /**
415
+ * `/<name>/tree/<ref>/<path>`, encoded for a URL and then escaped for an
416
+ * attribute.
417
+ *
418
+ * BOTH, and in that order. Escaping alone is the bug this had: a branch or a
419
+ * file may legally contain `#`, `?` or `%`, and each of those ends or rewrites
420
+ * a URL rather than a markup attribute — a link to a file called `a#b` would
421
+ * quietly resolve to a different path. Each SEGMENT is encoded separately so
422
+ * the slashes that make the path a path survive, which is also why a ref and a
423
+ * path arrive here already split.
424
+ */
425
+ function browseHref(repo: string, kind: BrowseKind, ref: string, path: string): string {
426
+ const parts = [repo, kind, ...ref.split('/'), ...path.split('/').filter((p) => p !== '')]
427
+ return escapeHtml(`/${parts.map((part) => encodeURIComponent(part)).join('/')}`)
428
+ }
429
+
430
+ /** `/<name>/tree/<ref>/<path>` — the shape every directory link takes. */
431
+ function treeHref(repo: string, ref: string, path: string): string {
432
+ return browseHref(repo, 'tree', ref, path)
433
+ }
434
+
435
+ /** `/<name>`, encoded and escaped for the same reason `treeHref` is. */
436
+ function repoHref(repo: string): string {
437
+ return escapeHtml(`/${encodeURIComponent(repo)}`)
438
+ }
439
+
440
+ /** How a ref is SHOWN: `refs/heads/` dropped, everything else kept whole. */
441
+ export function shortRef(ref: string): string {
442
+ return ref.startsWith('refs/heads/') ? ref.slice('refs/heads/'.length) : ref
443
+ }
444
+
445
+ function entryRow(repo: string, ref: string, path: string, entry: TreeEntry): string {
446
+ const name = escapeHtml(entry.name)
447
+ const here = path === '' ? entry.name : `${path}/${entry.name}`
448
+ // A directory and a file each link to their own page; a symlink and a
449
+ // submodule do not, because neither names something this repository holds at
450
+ // that path — a link to one would be a 404 found by clicking.
451
+ const shown =
452
+ entry.kind === 'tree'
453
+ ? `<a href="${treeHref(repo, ref, here)}">${name}/</a>`
454
+ : entry.kind === 'blob'
455
+ ? `<a href="${browseHref(repo, 'blob', ref, here)}">${name}</a>`
456
+ : name
457
+ const note =
458
+ entry.kind === 'symlink'
459
+ ? `<span class="tag">→ ${escapeHtml(entry.target ?? '')}</span>`
460
+ : entry.kind === 'submodule'
461
+ ? `<span class="tag">submodule @ ${escapeHtml(entry.oid.slice(0, 8))}</span>`
462
+ : ''
463
+ return ` <tr>
464
+ <td class="n">${shown} ${note}</td>
465
+ <td class="f">${entry.size === null ? '' : entry.size}</td>
466
+ </tr>`
467
+ }
468
+
469
+ /** What every page's chrome needs: the repository, the ref and the ref list. */
470
+ type PageCommon = Pick<BrowseRefsAnswer, 'repo' | 'refs' | 'lastPush'> & { ref?: string }
471
+
472
+ function refList(answer: PageCommon): string {
473
+ if (answer.refs.length === 0) return ''
474
+ const links = answer.refs.map((ref) => {
475
+ const current = ref.name === answer.ref ? ' class="here"' : ''
476
+ return `<a href="${treeHref(answer.repo, shortRef(ref.name), '')}"${current}>${escapeHtml(
477
+ shortRef(ref.name),
478
+ )}</a>`
479
+ })
480
+ return ` <nav class="refs">${links.join(' ')}</nav>\n`
481
+ }
482
+
483
+ /**
484
+ * The heading every path-bearing page wears: the repository, the ref, and each
485
+ * directory above the thing being shown.
486
+ *
487
+ * `leaf` is what separates a file from a directory, and it is the only
488
+ * difference there ever was between the two: a directory page ends in a link to
489
+ * itself (the last crumb is a directory like the ones before it), a file page
490
+ * ends in the file's name as plain text, because a blob has no `tree` URL and a
491
+ * link to one would be a 404 found by clicking.
492
+ */
493
+ function breadcrumb(answer: PageCommon & { path?: string }, leaf?: string): string {
494
+ const ref = shortRef(answer.ref ?? '')
495
+ const crumbs = [
496
+ `<a href="${repoHref(answer.repo)}">${escapeHtml(answer.repo)}</a>`,
497
+ `<span class="at">at ${escapeHtml(ref)}</span>`,
498
+ ]
499
+ let walked = ''
500
+ for (const segment of (answer.path ?? '').split('/').filter((s) => s !== '')) {
501
+ walked = walked === '' ? segment : `${walked}/${segment}`
502
+ crumbs.push(`<a href="${treeHref(answer.repo, ref, walked)}">${escapeHtml(segment)}</a>`)
503
+ }
504
+ if (leaf !== undefined) crumbs.push(escapeHtml(leaf))
505
+ return crumbs.join(' <span class="sep">/</span> ')
506
+ }
507
+
508
+ /**
509
+ * The retention line every page carries, in the landing page's own words.
510
+ */
511
+ function fineprint(answer: PageCommon, caps: Capabilities, now: number): string {
512
+ const expiry = expiresIn(answer.lastPush, caps, now)
513
+ return [
514
+ answer.lastPush === null ? '' : `last push ${escapeHtml(answer.lastPush.slice(0, 10))}`,
515
+ expiry === null ? '' : escapeHtml(expiry),
516
+ ]
517
+ .filter((part) => part !== '')
518
+ .join(' · ')
519
+ }
520
+
521
+ /**
522
+ * The document every browse page is, around whatever that page shows.
523
+ *
524
+ * No framework, no build step, no script and no request beyond the document
525
+ * itself — one inline stylesheet, which is all the CSP permits. Four pages
526
+ * share it because they are one product a reader clicks through, and four
527
+ * copies of a `<head>` is four places a token rename has to land.
528
+ */
529
+ function shell(title: string, heading: string, body: string, footer: string): string {
530
+ return `<!doctype html>
531
+ <html lang="en">
532
+ <head>
533
+ <meta charset="utf-8">
534
+ <meta name="viewport" content="width=device-width, initial-scale=1">
535
+ <meta name="robots" content="noindex">
536
+ <title>${escapeHtml(title)}</title>
537
+ <style>
538
+ ${WEB_STYLE}
539
+ .refs { display: flex; flex-wrap: wrap; gap: .75rem; margin-bottom: 1rem; }
540
+ .refs .here { text-decoration: underline; }
541
+ .sep, .at { color: var(--muted); }
542
+ .tag { border: 0; padding: 0; }
543
+ .file, .readme { overflow-x: auto; }
544
+ .file td.ln { text-align: right; color: var(--muted); user-select: none; width: 1%;
545
+ white-space: nowrap; }
546
+ .file td { border: 0; padding: 0 .5rem; }
547
+ .file pre, .readme pre { margin: 0; white-space: pre; font: inherit; }
548
+ .readme { border: 1px solid color-mix(in srgb, var(--muted) 30%, transparent);
549
+ border-radius: 3px; padding: .75rem; margin-top: 1.5rem; }
550
+ .readme h2 { font-size: .85rem; font-weight: 600; color: var(--muted); margin: 0 0 .5rem; }
551
+ .log td.w { white-space: nowrap; color: var(--muted); }
552
+ </style>
553
+ </head>
554
+ <body>
555
+ <main>
556
+ <h1>${heading}</h1>
557
+ ${body} <p class="note">${footer}</p>
558
+ </main>
559
+ </body>
560
+ </html>
561
+ `
562
+ }
563
+
564
+ /** Where every page points back to: the deployment, and what walgit is. */
565
+ function footerLinks(fine: string, extra = ''): string {
566
+ return `${fine}${fine === '' ? '' : ' · '}${extra}<a href="${REPOS_PATH}">all repositories</a> · <a href="/">what this is</a>`
567
+ }
568
+
569
+ /**
570
+ * The tree page, as a string.
571
+ *
572
+ * The repository page and a directory page are the same document: a directory
573
+ * is the root one with a path, and giving them two renderers would be two
574
+ * places a ref link has to be spelled.
575
+ */
576
+ export function renderBrowse(
577
+ answer: BrowseTreeAnswer,
578
+ caps: Capabilities,
579
+ now = Date.now(),
580
+ ): string {
581
+ const parent = parentOf(answer.path)
582
+ const rows =
583
+ answer.entries.length === 0
584
+ ? ' <p class="note">Nothing here.</p>\n'
585
+ : ` <table>
586
+ <thead><tr><th>name</th><th class="f">size</th></tr></thead>
587
+ <tbody>
588
+ ${answer.entries.map((entry) => entryRow(answer.repo, shortRef(answer.ref), answer.path, entry)).join('\n')}
589
+ </tbody>
590
+ </table>
591
+ `
592
+ const up =
593
+ parent === null
594
+ ? ''
595
+ : ` <p class="note"><a href="${treeHref(
596
+ answer.repo,
597
+ shortRef(answer.ref),
598
+ parent,
599
+ )}">..</a></p>\n`
600
+
601
+ const empty =
602
+ answer.refs.length === 0
603
+ ? ' <p class="note">No refs yet. The first push creates one.</p>\n'
604
+ : ''
605
+
606
+ // The README, as TEXT. There is no markdown renderer here and no sanitiser
607
+ // walgit owns, and the one thing a repository page must never do is turn
608
+ // bytes somebody pushed into markup on walgit's own origin.
609
+ const readme =
610
+ answer.readme === undefined
611
+ ? ''
612
+ : ` <section class="readme"><h2>${escapeHtml(
613
+ answer.readme.name,
614
+ )}</h2><pre>${escapeHtml(answer.readme.text)}</pre></section>\n`
615
+
616
+ // History is reachable from the tree rather than only from a URL someone
617
+ // knows to type — but only where there IS a ref to walk.
618
+ const history =
619
+ answer.ref === ''
620
+ ? ''
621
+ : `<a href="${browseHref(answer.repo, 'commits', shortRef(answer.ref), '')}">history</a> · `
622
+
623
+ return shell(
624
+ answer.repo,
625
+ breadcrumb(answer),
626
+ `${refList(answer)}${empty}${up}${rows}${readme}`,
627
+ footerLinks(fineprint(answer, caps, now), history),
628
+ )
629
+ }
630
+
631
+ /**
632
+ * The file page: the bytes, escaped, one numbered row per line.
633
+ *
634
+ * A table rather than a `<pre>` with numbers in it, because a line number a
635
+ * reader can select is a line number they paste into a message by accident.
636
+ * Three files never show content: one over `BLOB_MAX_BYTES` (never read), one
637
+ * holding a NUL byte, and — implicitly — one the container refused. Each offers
638
+ * the raw link instead, which is the same read without a page around it.
639
+ */
640
+ export function renderBlob(answer: BrowseBlobAnswer, caps: Capabilities, now = Date.now()): string {
641
+ const ref = shortRef(answer.ref)
642
+ const raw = browseHref(answer.repo, 'raw', ref, answer.path)
643
+ const rawLink = `<a href="${raw}">raw</a>`
644
+
645
+ let body: string
646
+ if (answer.oversize) {
647
+ body = ` <p class="note">${answer.size} bytes — too large to show. ${rawLink}</p>\n`
648
+ } else if (answer.binary) {
649
+ body = ` <p class="note">${answer.size} bytes of binary. ${rawLink}</p>\n`
650
+ } else {
651
+ // A trailing newline ends the last line rather than starting an empty one,
652
+ // which is what every editor shows and what `wc -l` counts.
653
+ const text = answer.text ?? ''
654
+ const lines = text === '' ? [] : text.replace(/\n$/, '').split('\n')
655
+ const rows = lines
656
+ .map(
657
+ (line, i) =>
658
+ ` <tr><td class="ln">${i + 1}</td><td><pre>${escapeHtml(line)}</pre></td></tr>`,
659
+ )
660
+ .join('\n')
661
+ body = ` <table class="file">
662
+ <tbody>
663
+ ${rows}
664
+ </tbody>
665
+ </table>
666
+ `
667
+ }
668
+
669
+ const fine = fineprint(answer, caps, now)
670
+ const shown = answer.oversize || answer.binary ? '' : `${answer.size} bytes · ${rawLink} · `
671
+ // The directory the file is in, with the file itself as the last crumb.
672
+ const segments = answer.path.split('/')
673
+ return shell(
674
+ `${answer.path} · ${answer.repo}`,
675
+ breadcrumb({ ...answer, path: segments.slice(0, -1).join('/') }, segments.at(-1) ?? ''),
676
+ body,
677
+ footerLinks(fine, shown),
678
+ )
679
+ }
680
+
681
+ /**
682
+ * The history page: one page of commits, and a link to the next.
683
+ *
684
+ * The date is shown as the day rather than the instant: a history is read for
685
+ * its order, and a full ISO timestamp per row is noise in a column a reader
686
+ * scans. The full value stays in the answer for anyone reading the JSON.
687
+ */
688
+ export function renderLog(answer: BrowseLogAnswer, caps: Capabilities, now = Date.now()): string {
689
+ const ref = shortRef(answer.ref)
690
+ const rows = answer.commits
691
+ .map(
692
+ (commit) => ` <tr>
693
+ <td class="w">${escapeHtml(commit.oid.slice(0, 8))}</td>
694
+ <td>${escapeHtml(commit.subject)}</td>
695
+ <td class="w">${escapeHtml(commit.author)}</td>
696
+ <td class="w">${escapeHtml(commit.date.slice(0, 10))}</td>
697
+ </tr>`,
698
+ )
699
+ .join('\n')
700
+ const table =
701
+ answer.commits.length === 0
702
+ ? ' <p class="note">No history here yet.</p>\n'
703
+ : ` <table class="log">
704
+ <thead><tr><th>commit</th><th>subject</th><th>author</th><th>date</th></tr></thead>
705
+ <tbody>
706
+ ${rows}
707
+ </tbody>
708
+ </table>
709
+ `
710
+ // The next page, as a link the reader can follow — the cursor is the last
711
+ // commit THIS page showed, and the container drops it from the next one.
712
+ const next =
713
+ answer.next === null
714
+ ? ''
715
+ : ` <p class="note"><a href="${browseHref(
716
+ answer.repo,
717
+ 'commits',
718
+ ref,
719
+ '',
720
+ )}?before=${escapeHtml(encodeURIComponent(answer.next))}">older</a></p>\n`
721
+
722
+ const heading = [
723
+ `<a href="${repoHref(answer.repo)}">${escapeHtml(answer.repo)}</a>`,
724
+ `<span class="at">history of ${escapeHtml(ref === '' ? 'nothing' : ref)}</span>`,
725
+ ].join(' <span class="sep">/</span> ')
726
+
727
+ return shell(
728
+ `history · ${answer.repo}`,
729
+ heading,
730
+ `${refList(answer)}${table}${next}`,
731
+ footerLinks(fineprint(answer, caps, now)),
732
+ )
733
+ }