rvlib-shipkit 2.9.0 → 2.11.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.
- package/CHANGELOG.md +23 -0
- package/package.json +1 -1
- package/src/cli/cmd_Media.ts +164 -0
- package/src/cli/cmd_Review.ts +2 -1
- package/src/cli/family-pages.ts +1 -0
- package/src/cli/registry.ts +2 -0
- package/src/collections/pings.ts +6 -4
- package/src/core/app-icon.ts +17 -4
- package/src/core/scratch-objects.ts +56 -0
- package/src/core/trace-audit.ts +13 -1
- package/src/home/home-paths.ts +4 -0
- package/src/home/home-routes.ts +36 -2
- package/src/home/hubs.ts +5 -0
- package/src/home/inbox-shape.ts +182 -0
- package/src/home/inbox.ts +48 -0
- package/src/home/run-daemon.ts +12 -2
- package/src/home/serve-web.ts +155 -16
- package/src/ledger/git-scan.ts +73 -25
- package/src/ledger/repo-view.ts +2 -22
- package/src/media-kinds.ts +7 -0
- package/src/media-store/content.ts +51 -0
- package/src/media-store/daemon.ts +91 -0
- package/src/media-store/db.ts +74 -0
- package/src/media-store/fact.ts +9 -0
- package/src/media-store/kind.ts +44 -0
- package/src/media-store/purge.ts +139 -0
- package/src/media-store/remote.ts +93 -0
- package/src/media-store/space.ts +124 -0
- package/src/media-store/sync.ts +101 -0
- package/src/media-store/upload.ts +98 -0
- package/src/repo-config.ts +4 -0
- package/src/review/anim.ts +6 -5
- package/src/review/cells.ts +552 -0
- package/src/review/format.ts +1 -1
- package/src/review/media-kind.ts +84 -0
- package/src/review/media-read.ts +48 -0
- package/src/review/model.ts +43 -5
- package/src/review/previews.ts +153 -0
- package/src/review/routes.ts +105 -47
- package/src/review/store.ts +106 -45
- package/src/review/trailer-desk.ts +79 -46
- package/src/review/trailer-media.ts +163 -0
- package/src/review/trailer-routes.ts +5 -2
- package/src/serve/hub-app/home-st.ts +39 -9
- package/src/serve/hub-app/home.html +2 -1
- package/src/serve/hub-app/hub-app.tsx +7 -23
- package/src/serve/hub-app/icons.tsx +2 -0
- package/src/serve/hub-app/inbox-st.ts +144 -0
- package/src/serve/hub-app/inbox-view.tsx +205 -0
- package/src/serve/hub-app/inbox.css +73 -0
- package/src/serve/hub-app/item-view.tsx +19 -0
- package/src/serve/hub-app/keys.ts +4 -3
- package/src/serve/hub-app/palette-st.ts +2 -1
- package/src/serve/hub-app/project-list.tsx +1 -0
- package/src/serve/hub-app/projects-svc.ts +1 -1
- package/src/serve/hub-app/repo-st.ts +1 -1
- package/src/serve/hub-app/review/kind-view.tsx +21 -22
- package/src/serve/hub-app/review/kit.tsx +11 -12
- package/src/serve/hub-app/review/review-board.tsx +15 -13
- package/src/serve/hub-app/review/review-cells.tsx +241 -0
- package/src/serve/hub-app/review/review-kit.ts +79 -0
- package/src/serve/hub-app/review/review-list.tsx +87 -122
- package/src/serve/hub-app/review/review-page.tsx +22 -79
- package/src/serve/hub-app/review/review-st.ts +269 -698
- package/src/serve/hub-app/review/review-thread.tsx +302 -0
- package/src/serve/hub-app/review/review-views.tsx +322 -253
- package/src/serve/hub-app/review/thread-st.ts +770 -0
- package/src/serve/hub-app/review.css +235 -91
- package/src/serve/hub-runtime.ts +9 -4
- package/src/serve/serve-hub.ts +4 -1
- package/src/serve/warm-cell.ts +6 -1
- package/src/trailer/footage.ts +6 -2
- package/src/trailer/passage.ts +4 -2
- package/src/trailer/prune.ts +6 -10
- package/src/serve/hub-app/review/review-answer.tsx +0 -249
|
@@ -0,0 +1,182 @@
|
|
|
1
|
+
// the inbox as data (wiki build/shipkit/home.md, The inbox): everything that waits on the owner in every house repo,
|
|
2
|
+
// one list. Pure and browser safe: the daemon (inbox.ts), the page and the tests share it. Each repo gives what it
|
|
3
|
+
// already holds, never a store of its own: its review store's thread index and its hub's rows that need someone.
|
|
4
|
+
//
|
|
5
|
+
// the one constraint a reader breaks first: a row here is one ACT for the owner, so what an ask already owns
|
|
6
|
+
// (`askOwned`) and the review rows of the needs (the index says them with their thumbs) are left out, never twice
|
|
7
|
+
import { REVIEW_COL, type Resource } from '../collections/collection-types.ts'
|
|
8
|
+
import type { ThreadIndex, ThreadRow } from '../review/cells.ts'
|
|
9
|
+
import { STATUS_LABEL } from '../review/model.ts'
|
|
10
|
+
|
|
11
|
+
/** a card the owner answers, a question raised to him, an ask for his hands, a need of a repo, an item he or a player
|
|
12
|
+
* raised that the agents work on */
|
|
13
|
+
export type InboxKind = 'card' | 'question' | 'ask' | 'need' | 'raised'
|
|
14
|
+
/** the review hue, red broken, yellow can wait */
|
|
15
|
+
export type InboxTone = 'review' | 'red' | 'yellow'
|
|
16
|
+
/** the main list (what waits on him) or the folded one (what can wait, what he can only read) */
|
|
17
|
+
export type InboxList = 'main' | 'yellow'
|
|
18
|
+
|
|
19
|
+
export interface InboxRow {
|
|
20
|
+
/** `<repo>/<id>`, one per row of the whole inbox */
|
|
21
|
+
key: string
|
|
22
|
+
repo: string
|
|
23
|
+
kind: InboxKind
|
|
24
|
+
/** the item's id in its repo: a review thread's head, or a need's id */
|
|
25
|
+
id: string
|
|
26
|
+
/** a need's collection, the section of its repo's hub */
|
|
27
|
+
col?: string
|
|
28
|
+
/** the badge's word: card, choice, question, the ask's kind, the need's type */
|
|
29
|
+
tag: string
|
|
30
|
+
tone: InboxTone
|
|
31
|
+
title: string
|
|
32
|
+
/** one more line: the lane and the versions, the need's sentence */
|
|
33
|
+
sub?: string
|
|
34
|
+
/** epoch ms of its newest move, null when nothing dates it */
|
|
35
|
+
at: number | null
|
|
36
|
+
/** the review preview thumb, on the home's origin */
|
|
37
|
+
thumb: string | null
|
|
38
|
+
/** the inbox address that opens it */
|
|
39
|
+
open: string
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** what one repo gives the inbox */
|
|
43
|
+
export interface InboxSource {
|
|
44
|
+
repo: string
|
|
45
|
+
review: { tag: string; ix: ThreadIndex } | null
|
|
46
|
+
needs: Resource[]
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export interface InboxAnswer {
|
|
50
|
+
list: InboxList
|
|
51
|
+
rows: InboxRow[]
|
|
52
|
+
/** the rows of that list, every page */
|
|
53
|
+
total: number
|
|
54
|
+
offset: number
|
|
55
|
+
limit: number
|
|
56
|
+
counts: Record<InboxList, number>
|
|
57
|
+
/** per repo, the rows of each list: its own badges count the same */
|
|
58
|
+
repos: Record<string, Record<InboxList, number>>
|
|
59
|
+
/** a repo whose items are not here, and why (its hub is down, a read broke) */
|
|
60
|
+
missing: { repo: string; why: string }[]
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
export const INBOX_PAGE = 50
|
|
64
|
+
export const INBOX_MAX = 500
|
|
65
|
+
|
|
66
|
+
/** where a repo's hub answers on the home */
|
|
67
|
+
const hubOf = (repo: string): string => `/r/${encodeURIComponent(repo)}`
|
|
68
|
+
|
|
69
|
+
/** the inbox address that opens one item */
|
|
70
|
+
export const inboxAddress = (repo: string, id: string): string => `/inbox?open=${encodeURIComponent(`${repo}/${id}`)}`
|
|
71
|
+
|
|
72
|
+
/** an inbox address's item read back, or null for the list */
|
|
73
|
+
export function openOf(search: string): { repo: string; id: string } | null {
|
|
74
|
+
const v = new URLSearchParams(search).get('open')
|
|
75
|
+
const at = v?.indexOf('/') ?? -1
|
|
76
|
+
return v == null || at <= 0 || at === v.length - 1 ? null : { repo: v.slice(0, at), id: v.slice(at + 1) }
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** a review item's id (`YYYYMMDD-HHMMSS-<slug>`); a need's id starts with its kind (`check:`, `ask:`) */
|
|
80
|
+
export const isReviewId = (id: string): boolean => /^\d{8}-\d{6}-/.test(id)
|
|
81
|
+
|
|
82
|
+
const IMAGE = /\.(png|jpe?g|webp)$/i
|
|
83
|
+
|
|
84
|
+
function reviewRow(repo: string, r: ThreadRow, kind: InboxKind, tone: InboxTone): InboxRow {
|
|
85
|
+
const tag = kind === 'card' ? (r.choice ? 'choice' : 'card') : kind === 'question' ? (r.status === 'pending' ? 'question' : STATUS_LABEL[r.status]) : STATUS_LABEL[r.status]
|
|
86
|
+
const sub = [r.lane, r.versions > 1 ? `v${r.versions}` : null, r.unread ? 'unread words' : null].filter((x): x is string => x != null && x !== '').join(' · ')
|
|
87
|
+
const at = Date.parse(r.updated)
|
|
88
|
+
return {
|
|
89
|
+
key: `${repo}/${r.head}`,
|
|
90
|
+
repo,
|
|
91
|
+
kind,
|
|
92
|
+
id: r.head,
|
|
93
|
+
tag,
|
|
94
|
+
tone,
|
|
95
|
+
title: r.title,
|
|
96
|
+
...(sub !== '' ? { sub } : {}),
|
|
97
|
+
at: Number.isFinite(at) ? at : null,
|
|
98
|
+
thumb: r.thumb != null && IMAGE.test(r.thumb) ? `${hubOf(repo)}/api/review/${r.head}/preview/thumb/${r.thumb}` : null,
|
|
99
|
+
open: inboxAddress(repo, r.head),
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/** when a need moved: a check's last run, else what `dated` reads off its file (an ask's birth, a file's last write) */
|
|
104
|
+
export type Dated = (n: Resource) => number | null
|
|
105
|
+
|
|
106
|
+
function needRow(repo: string, n: Resource, dated: Dated): InboxRow {
|
|
107
|
+
const ask = n.collection === 'asks'
|
|
108
|
+
const title = n.title
|
|
109
|
+
const sub = n.text !== title ? n.text : n.slot
|
|
110
|
+
return {
|
|
111
|
+
key: `${repo}/${n.id}`,
|
|
112
|
+
repo,
|
|
113
|
+
kind: ask ? 'ask' : 'need',
|
|
114
|
+
id: n.id,
|
|
115
|
+
col: n.collection,
|
|
116
|
+
tag: ask ? (n.ask?.kind ?? 'ask') : n.type,
|
|
117
|
+
tone: n.severity === 'red' ? 'red' : 'yellow',
|
|
118
|
+
title,
|
|
119
|
+
...(sub != null && sub !== '' ? { sub } : {}),
|
|
120
|
+
at: n.check?.lastAt ?? dated(n),
|
|
121
|
+
thumb: null,
|
|
122
|
+
open: inboxAddress(repo, n.id),
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/** one repo's rows: the main list (the cards and questions waiting on him, the asks, what is red) and the folded one
|
|
127
|
+
* (what is yellow, the raised items in the agents' hands) */
|
|
128
|
+
export function repoRows(s: InboxSource, dated: Dated): Record<InboxList, InboxRow[]> {
|
|
129
|
+
const out: Record<InboxList, InboxRow[]> = { main: [], yellow: [] }
|
|
130
|
+
for (const { row } of s.review?.ix.entries ?? []) {
|
|
131
|
+
if (s.review!.ix.waiting.has(row.head)) out.main.push(reviewRow(s.repo, row, row.origin === 'agent' ? 'card' : 'question', 'review'))
|
|
132
|
+
else if (row.active && row.move === 'agents' && row.origin !== 'agent') out.yellow.push(reviewRow(s.repo, row, 'raised', 'yellow'))
|
|
133
|
+
}
|
|
134
|
+
for (const n of s.needs) {
|
|
135
|
+
if (n.severity == null || n.collection === REVIEW_COL || n.askOwned === true) continue
|
|
136
|
+
const r = needRow(s.repo, n, dated)
|
|
137
|
+
out[r.kind === 'ask' || r.tone === 'red' ? 'main' : 'yellow'].push(r)
|
|
138
|
+
}
|
|
139
|
+
return out
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
/** newest first; what nothing dates goes last, by repo and title */
|
|
143
|
+
export const byNewest = (a: InboxRow, b: InboxRow): number =>
|
|
144
|
+
(b.at ?? -Infinity) - (a.at ?? -Infinity) || a.repo.localeCompare(b.repo) || a.title.localeCompare(b.title)
|
|
145
|
+
|
|
146
|
+
/** every repo's rows, each list in its order; `dated` dates a need of that repo */
|
|
147
|
+
export function inboxRows<S extends InboxSource>(sources: readonly S[], dated: (s: S) => Dated): Record<InboxList, InboxRow[]> & { repos: InboxAnswer['repos'] } {
|
|
148
|
+
const main: InboxRow[] = []
|
|
149
|
+
const yellow: InboxRow[] = []
|
|
150
|
+
const repos: InboxAnswer['repos'] = {}
|
|
151
|
+
for (const s of sources) {
|
|
152
|
+
const r = repoRows(s, dated(s))
|
|
153
|
+
main.push(...r.main)
|
|
154
|
+
yellow.push(...r.yellow)
|
|
155
|
+
repos[s.repo] = { main: r.main.length, yellow: r.yellow.length }
|
|
156
|
+
}
|
|
157
|
+
return { main: main.sort(byNewest), yellow: yellow.sort(byNewest), repos }
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/** the query from a url's search: a value out of range is its default */
|
|
161
|
+
export function inboxQuery(p: URLSearchParams): { list: InboxList; offset: number; limit: number } {
|
|
162
|
+
const n = (k: string, d: number, max: number): number => {
|
|
163
|
+
const v = Number(p.get(k) || NaN)
|
|
164
|
+
return Number.isInteger(v) && v >= 0 ? Math.min(v, max) : d
|
|
165
|
+
}
|
|
166
|
+
return { list: p.get('list') === 'yellow' ? 'yellow' : 'main', offset: n('offset', 0, Number.MAX_SAFE_INTEGER), limit: Math.max(1, n('limit', INBOX_PAGE, INBOX_MAX)) }
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/** one page of one list */
|
|
170
|
+
export function inboxPage(all: ReturnType<typeof inboxRows>, q: ReturnType<typeof inboxQuery>, missing: InboxAnswer['missing']): InboxAnswer {
|
|
171
|
+
const rows = all[q.list]
|
|
172
|
+
return {
|
|
173
|
+
list: q.list,
|
|
174
|
+
rows: rows.slice(q.offset, q.offset + q.limit),
|
|
175
|
+
total: rows.length,
|
|
176
|
+
offset: q.offset,
|
|
177
|
+
limit: q.limit,
|
|
178
|
+
counts: { main: all.main.length, yellow: all.yellow.length },
|
|
179
|
+
repos: all.repos,
|
|
180
|
+
missing,
|
|
181
|
+
}
|
|
182
|
+
}
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
// the daemon's inbox route (wiki build/shipkit/home.md, The inbox): every loaded hub's review index and needing rows,
|
|
2
|
+
// shaped by inbox-shape.ts. It reads memory only (each store's thread index, each hub's warm rows) and a stat per
|
|
3
|
+
// dated file, so a poll answers in milliseconds; the whole answer's hash is its ETag
|
|
4
|
+
import { statSync } from 'fs'
|
|
5
|
+
import { join } from 'path'
|
|
6
|
+
import type { Resource } from '../collections/collection-types.ts'
|
|
7
|
+
import { storeIndex } from '../review/routes.ts'
|
|
8
|
+
import type { Hubs } from './hubs.ts'
|
|
9
|
+
import { inboxPage, inboxQuery, inboxRows, type Dated, type InboxAnswer, type InboxSource } from './inbox-shape.ts'
|
|
10
|
+
|
|
11
|
+
/** a need's file dated: an ask by its birth (its front matter keeps only the day), any other file by its last write */
|
|
12
|
+
export const datedIn = (root: string): Dated => (n: Resource) => {
|
|
13
|
+
if (n.virtual === true || n.path === '') return null
|
|
14
|
+
try {
|
|
15
|
+
const s = statSync(join(root, n.path))
|
|
16
|
+
return n.collection === 'asks' ? s.birthtimeMs : s.mtimeMs
|
|
17
|
+
} catch {
|
|
18
|
+
return null
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** what every hub that is up holds, read in parallel; a repo whose read broke is named, never dropped silently */
|
|
23
|
+
export async function inboxSources(hubs: Pick<Hubs, 'loaded'>): Promise<{ sources: (InboxSource & { root: string })[]; missing: InboxAnswer['missing'] }> {
|
|
24
|
+
const missing: InboxAnswer['missing'] = []
|
|
25
|
+
const read = await Promise.all(
|
|
26
|
+
hubs.loaded().map(async ({ repo, rt }) => {
|
|
27
|
+
try {
|
|
28
|
+
return { repo: repo.name, root: repo.path, review: storeIndex(repo.path), needs: await rt.handler.needs() }
|
|
29
|
+
} catch (e) {
|
|
30
|
+
missing.push({ repo: repo.name, why: `its items could not be read: ${(e as Error).message}` })
|
|
31
|
+
return null
|
|
32
|
+
}
|
|
33
|
+
}),
|
|
34
|
+
)
|
|
35
|
+
return { sources: read.filter((s) => s != null), missing }
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** one page of the inbox, 304 when the page holds this answer already; gzipped when the browser takes it */
|
|
39
|
+
export async function inboxResponse(req: Request, hubs: Pick<Hubs, 'loaded'>, down: InboxAnswer['missing']): Promise<Response> {
|
|
40
|
+
const { sources, missing } = await inboxSources(hubs)
|
|
41
|
+
const page = inboxPage(inboxRows(sources, (s) => datedIn(s.root)), inboxQuery(new URL(req.url).searchParams), [...down, ...missing])
|
|
42
|
+
const text = JSON.stringify(page)
|
|
43
|
+
const tag = `"${Bun.hash(text).toString(36)}"`
|
|
44
|
+
const headers = { 'Content-Type': 'application/json', ETag: tag, 'Cache-Control': 'no-cache', Vary: 'Accept-Encoding' }
|
|
45
|
+
if (req.headers.get('If-None-Match') === tag) return new Response(null, { status: 304, headers: { ETag: tag } })
|
|
46
|
+
if (text.length < 4096 || !/\bgzip\b/.test(req.headers.get('Accept-Encoding') ?? '')) return new Response(text, { headers })
|
|
47
|
+
return new Response(Bun.gzipSync(new TextEncoder().encode(text)), { headers: { ...headers, 'Content-Encoding': 'gzip' } })
|
|
48
|
+
}
|
package/src/home/run-daemon.ts
CHANGED
|
@@ -16,13 +16,16 @@ import { projectGutter } from '../serve/project-gutter-route.ts'
|
|
|
16
16
|
import { loadRepoConfig } from '../repo-config.ts'
|
|
17
17
|
import { ensureIdentity } from '../core/identity.ts'
|
|
18
18
|
import { homedir } from 'os'
|
|
19
|
-
import { daemonPort, homeDir, homePort, homeUp, hubBase, WORKER_ENV } from './home-paths.ts'
|
|
19
|
+
import { daemonPort, homeDir, homePort, homeUp, hubBase, publicHome, WORKER_ENV } from './home-paths.ts'
|
|
20
|
+
import { inboxAddress } from './inbox-shape.ts'
|
|
20
21
|
import { HomeState } from './home-state.ts'
|
|
21
22
|
import { Hubs } from './hubs.ts'
|
|
22
23
|
import { Planner } from '../plan/planner.ts'
|
|
23
24
|
import { machineCatchUp } from '../plan/catch-up.ts'
|
|
24
25
|
import { serveDaemon } from './serve-daemon.ts'
|
|
25
26
|
import { startSweeps } from './machine-stores.ts'
|
|
27
|
+
import { startMediaStore } from '../media-store/daemon.ts'
|
|
28
|
+
import { MEDIA_KINDS } from '../media-kinds.ts'
|
|
26
29
|
import { landMotherhome } from '../core/motherhome.ts'
|
|
27
30
|
import { Widgets } from './widgets.ts'
|
|
28
31
|
|
|
@@ -59,6 +62,7 @@ export async function runDaemon(root: string, io: HomeIo, o: { port?: number } =
|
|
|
59
62
|
const reclaimed = reclaimPreviousImage()
|
|
60
63
|
if (reclaimed.killed.length > 0) io.print(`ok: the daemon restarted in place: killed ${reclaimed.killed.length} check process(es) its previous image left running`)
|
|
61
64
|
const c = await loadRepoConfig(root)
|
|
65
|
+
const publicHost = c.serve?.publicHost
|
|
62
66
|
const dir = homeDir()
|
|
63
67
|
// the machine's one plan: every repo and check pair, ticked by the daemon.
|
|
64
68
|
// Its catch up window lives in the machine db, so a restart in place keeps it
|
|
@@ -87,6 +91,8 @@ export async function runDaemon(root: string, io: HomeIo, o: { port?: number } =
|
|
|
87
91
|
fresh: o.fresh,
|
|
88
92
|
// every gate is a detached job: a reload of this process never kills one
|
|
89
93
|
jobs: { cli: CLI },
|
|
94
|
+
// a ping opens the inbox on its item, or on the list for several
|
|
95
|
+
link: (fresh) => (publicHost == null ? undefined : `${publicHome(publicHost)}${fresh.length === 1 ? inboxAddress(repo.name, fresh[0]!.id) : '/inbox'}`),
|
|
90
96
|
})
|
|
91
97
|
hubIo.print(`${rt.name} hub → http://localhost:${port}${hubBase(repo.name)}/`)
|
|
92
98
|
return { ...rt, uses: rt.deps.uses ?? [] }
|
|
@@ -105,6 +111,7 @@ export async function runDaemon(root: string, io: HomeIo, o: { port?: number } =
|
|
|
105
111
|
plan,
|
|
106
112
|
only: onlyRepos(),
|
|
107
113
|
widgets: new Widgets(),
|
|
114
|
+
publicHost,
|
|
108
115
|
})
|
|
109
116
|
io.print(`daemon → http://127.0.0.1:${home.server.port} (the page: http://localhost:${port})`)
|
|
110
117
|
// nothing grows unbound: every store of every repo it loads, and the
|
|
@@ -115,7 +122,9 @@ export async function runDaemon(root: string, io: HomeIo, o: { port?: number } =
|
|
|
115
122
|
// the rows every gate filed land here, one commit a day at most
|
|
116
123
|
also: (now) => { for (const n of landMotherhome({ now })) io.printErr(n) },
|
|
117
124
|
})
|
|
118
|
-
|
|
125
|
+
// every kind's media into the machine index, up to the Space, purged when the owner turned it on
|
|
126
|
+
const media = startMediaStore({ roots: () => house.repos.filter((r) => only == null || only.has(r.name)).map((r) => r.path), kinds: MEDIA_KINDS, print: io.print, printErr: io.printErr })
|
|
127
|
+
const code = reloadOnOwnCode({ role: 'daemon', entry: fileURLToPath(import.meta.url), busy: () => hubs.busy(), before: () => { sweeps.stop(); media.stop(); home.stop() }, keep: true, io })
|
|
119
128
|
io.print(` ${house.repos.length} repos, state in ${dir}, reloads on ${code.files} lib files`)
|
|
120
129
|
for (const sig of ['SIGINT', 'SIGTERM'] as const)
|
|
121
130
|
process.on(sig, () => {
|
|
@@ -123,6 +132,7 @@ export async function runDaemon(root: string, io: HomeIo, o: { port?: number } =
|
|
|
123
132
|
// own process groups, and the next daemon adopts them
|
|
124
133
|
code.stop()
|
|
125
134
|
sweeps.stop()
|
|
135
|
+
media.stop()
|
|
126
136
|
home.stop()
|
|
127
137
|
process.exit(0)
|
|
128
138
|
})
|
package/src/home/serve-web.ts
CHANGED
|
@@ -1,20 +1,22 @@
|
|
|
1
1
|
// the web: ONE Bun.serve on the home port. It serves the one page bundle (the
|
|
2
|
-
// overview at `/`, the plan at `/planned`, the activity at `/activity`, a repo's hub page at
|
|
3
|
-
// all views of one app) and proxies every api,
|
|
2
|
+
// overview at `/`, the inbox at `/inbox`, the plan at `/planned`, the activity at `/activity`, a repo's hub page at
|
|
3
|
+
// `/r/<repo>/`, all views of one app) and proxies every api,
|
|
4
4
|
// graph and media request to the daemon, streams included, and /api/pm/* to
|
|
5
5
|
// pm. A browser only ever sees this origin.
|
|
6
6
|
//
|
|
7
7
|
// the one constraint a reader breaks first: the same origin guard runs HERE,
|
|
8
8
|
// against this origin, and the proxied request reaches the daemon with no
|
|
9
9
|
// origin header. The daemon's own guard then refuses any page that calls its
|
|
10
|
-
// port directly, and lets this door through.
|
|
10
|
+
// port directly, and lets this door through. The host guard runs here too: Bun's dev server, which bundles the page
|
|
11
|
+
// and drives its hot reload, answers only to a loopback Host, so it sits on a port of its own behind this one, and a
|
|
12
|
+
// request reaches it only once its Host is a loopback name or the tailnet name the house declares (serve.publicHost)
|
|
11
13
|
import { sameOrigin } from '../serve/same-origin.ts'
|
|
12
14
|
import { hubBase } from './home-paths.ts'
|
|
13
15
|
|
|
14
16
|
/** the page routes: ONE app for the overview, the plan, and the hub page of
|
|
15
17
|
* each known repo, which moves between them in place (home-st.ts) */
|
|
16
18
|
export function pageRoutes<T>(names: string[], page: T): Record<string, T> {
|
|
17
|
-
const out: Record<string, T> = { '/': page, '/planned': page, '/activity': page, '/archived': page, '/insights': page }
|
|
19
|
+
const out: Record<string, T> = { '/': page, '/inbox': page, '/planned': page, '/activity': page, '/archived': page, '/insights': page }
|
|
18
20
|
for (const n of names) out[`${hubBase(n)}/`] = page
|
|
19
21
|
return out
|
|
20
22
|
}
|
|
@@ -57,6 +59,59 @@ export const readsGit = (path: string): boolean => path === '/api/home/activity.
|
|
|
57
59
|
/** a run or a check run streams for minutes, and a silent one is never cut */
|
|
58
60
|
export const streams = (path: string): boolean => /\/api\/(run|check\/run)$/.test(path)
|
|
59
61
|
|
|
62
|
+
/** a Host header's name: its port, brackets and trailing dot gone, lowercase */
|
|
63
|
+
export function hostName(host: string): string {
|
|
64
|
+
const h = host.trim().toLowerCase()
|
|
65
|
+
const name = h.startsWith('[') ? h.slice(1, h.indexOf(']') < 0 ? undefined : h.indexOf(']')) : h.replace(/:\d+$/, '')
|
|
66
|
+
return name.replace(/\.$/, '')
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** the names a browser may reach the home by: this machine's loopback names, and the tailnet names the house
|
|
70
|
+
* declares. Any other name is a page of another site resolved to this machine (DNS rebinding), and is refused */
|
|
71
|
+
export function hostAllowed(host: string | null, names: ReadonlySet<string>): boolean {
|
|
72
|
+
if (host == null || host === '') return false
|
|
73
|
+
const n = hostName(host)
|
|
74
|
+
if (n === 'localhost' || n.endsWith('.localhost') || n === '::1' || /^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(n)) return true
|
|
75
|
+
return names.has(n)
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
export const hostRefusedText = (host: string | null): string =>
|
|
79
|
+
`refused: the home answers to localhost and to the tailnet name the house declares (serve.publicHost), never to ${host == null || host === '' ? 'a request with no Host' : host}`
|
|
80
|
+
|
|
81
|
+
/** the page's colours behind the app on a phone, the --bg tokens of hub.css */
|
|
82
|
+
const THEME = { dark: '#0d0e10', light: '#f6f7f9' } as const
|
|
83
|
+
|
|
84
|
+
/** the home as an app a phone installs from its share menu: no service worker, a phone needs none to install it */
|
|
85
|
+
export const MANIFEST = {
|
|
86
|
+
name: 'shipkit',
|
|
87
|
+
short_name: 'shipkit',
|
|
88
|
+
description: 'everything that waits on you, in every repo',
|
|
89
|
+
start_url: '/inbox',
|
|
90
|
+
scope: '/',
|
|
91
|
+
display: 'standalone',
|
|
92
|
+
background_color: THEME.dark,
|
|
93
|
+
theme_color: THEME.dark,
|
|
94
|
+
icons: [192, 512].map((px) => ({ src: `/api/home/icon/${px}.png`, sizes: `${px}x${px}`, type: 'image/png', purpose: 'any' })),
|
|
95
|
+
} as const
|
|
96
|
+
|
|
97
|
+
/** what the page's head carries for a phone, added as the web serves it: the bundler resolves every link of the
|
|
98
|
+
* page's file as a file to bundle, and these name routes of this server */
|
|
99
|
+
export const APP_HEAD = [
|
|
100
|
+
'<link rel="manifest" href="/manifest.webmanifest">',
|
|
101
|
+
'<link rel="apple-touch-icon" href="/api/home/icon/180.png">',
|
|
102
|
+
'<meta name="apple-mobile-web-app-capable" content="yes">',
|
|
103
|
+
'<meta name="mobile-web-app-capable" content="yes">',
|
|
104
|
+
'<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">',
|
|
105
|
+
'<meta name="apple-mobile-web-app-title" content="shipkit">',
|
|
106
|
+
`<meta name="theme-color" media="(prefers-color-scheme: dark)" content="${THEME.dark}">`,
|
|
107
|
+
`<meta name="theme-color" media="(prefers-color-scheme: light)" content="${THEME.light}">`,
|
|
108
|
+
].join('')
|
|
109
|
+
|
|
110
|
+
/** a page file the web gzips for a browser that takes it: the dev bundle is megabytes of text */
|
|
111
|
+
const ZIPS = /^(text\/|application\/(javascript|json)|image\/svg)/
|
|
112
|
+
/** the gzipped bodies kept, by path and etag: the bundle changes on an edit, not on a request */
|
|
113
|
+
const ZIP_KEEP = 64
|
|
114
|
+
|
|
60
115
|
export type WebDeps<T> = {
|
|
61
116
|
port: number
|
|
62
117
|
/** the daemon's url, e.g. http://127.0.0.1:4798 */
|
|
@@ -69,25 +124,36 @@ export type WebDeps<T> = {
|
|
|
69
124
|
repoMs?: number
|
|
70
125
|
/** one pace for the repo list, in place of LIST_RETRY_MS and LIST_EVERY_MS */
|
|
71
126
|
listEveryMs?: number
|
|
127
|
+
/** tailnet names allowed before the daemon names any (a test) */
|
|
128
|
+
hosts?: string[]
|
|
72
129
|
}
|
|
73
130
|
|
|
131
|
+
/** one browser socket to the page server's hot reload, piped to the same path there */
|
|
132
|
+
type Pipe = { path: string; up: WebSocket | null; queue: (string | Uint8Array<ArrayBuffer>)[] }
|
|
133
|
+
|
|
74
134
|
export function serveWeb<T extends Bun.HTMLBundle | Response>(d: WebDeps<T>) {
|
|
75
135
|
let known = ''
|
|
76
136
|
let wasDown = false
|
|
77
137
|
let stopped = false
|
|
78
138
|
let listTimer: ReturnType<typeof setTimeout> | null = null
|
|
79
|
-
/** the
|
|
80
|
-
|
|
139
|
+
/** the tailnet names the house declares, from the daemon's repo list */
|
|
140
|
+
let hosts = new Set((d.hosts ?? []).map(hostName))
|
|
141
|
+
/** every page route, as the page server holds them */
|
|
142
|
+
let pages = new Set(Object.keys(pageRoutes([], d.page)))
|
|
143
|
+
const zips = new Map<string, Uint8Array<ArrayBuffer>>()
|
|
144
|
+
/** the repo names the daemon knows and the tailnet names, or the reason it did not answer */
|
|
145
|
+
async function names(): Promise<{ repos: string[]; hosts: string[] } | Error> {
|
|
81
146
|
try {
|
|
82
147
|
const r = await fetch(`${d.daemon}/api/home/repos.json`, { signal: AbortSignal.timeout(3_000) })
|
|
83
148
|
if (!r.ok) return new Error(`${r.status} ${await r.text()}`)
|
|
84
|
-
|
|
149
|
+
const j = (await r.json()) as { repos: string[]; hosts?: string[] }
|
|
150
|
+
return { repos: j.repos, hosts: j.hosts ?? [] }
|
|
85
151
|
} catch (e) {
|
|
86
152
|
return e as Error
|
|
87
153
|
}
|
|
88
154
|
}
|
|
89
155
|
|
|
90
|
-
async function proxy(req: Request, url: URL, srv: Bun.Server<
|
|
156
|
+
async function proxy(req: Request, url: URL, srv: Bun.Server<Pipe>): Promise<Response> {
|
|
91
157
|
if (!sameOrigin(req)) return new Response('refused: a request that changes something must come from the home page', { status: 403 })
|
|
92
158
|
const headers = new Headers()
|
|
93
159
|
req.headers.forEach((v, k) => { if (!DROP.has(k)) headers.set(k, v) })
|
|
@@ -122,10 +188,53 @@ export function serveWeb<T extends Bun.HTMLBundle | Response>(d: WebDeps<T>) {
|
|
|
122
188
|
}
|
|
123
189
|
}
|
|
124
190
|
|
|
125
|
-
|
|
191
|
+
// the page and its bundle, served by Bun's dev server on a loopback port of its own: it bundles the page, serves
|
|
192
|
+
// its files under /_bun/ and drives the page's hot reload over /_bun/hmr
|
|
193
|
+
const notFound = (): Response => new Response('not found: the home page is at /', { status: 404 })
|
|
194
|
+
const inner = Bun.serve({ port: 0, hostname: '127.0.0.1', routes: pageRoutes([], d.page), fetch: notFound })
|
|
195
|
+
const innerAt = `127.0.0.1:${inner.port}`
|
|
196
|
+
|
|
197
|
+
/** a page request handed to the page server as a loopback request, its answer gzipped for a browser that takes
|
|
198
|
+
* it, the page itself given the app's head */
|
|
199
|
+
async function toPage(req: Request, url: URL): Promise<Response> {
|
|
200
|
+
if (!sameOrigin(req)) return new Response('refused: a request that changes something must come from the home page', { status: 403 })
|
|
201
|
+
const headers = new Headers()
|
|
202
|
+
req.headers.forEach((v, k) => { if (!DROP.has(k) && k !== 'accept-encoding') headers.set(k, v) })
|
|
203
|
+
const body = req.method === 'GET' || req.method === 'HEAD' ? undefined : await req.arrayBuffer()
|
|
204
|
+
const r = await fetch(`http://${innerAt}${url.pathname}${url.search}`, { method: req.method, headers, body, redirect: 'manual' })
|
|
205
|
+
const out = new Headers(r.headers)
|
|
206
|
+
out.delete('content-length')
|
|
207
|
+
out.delete('transfer-encoding')
|
|
208
|
+
out.delete('connection')
|
|
209
|
+
const type = out.get('content-type') ?? ''
|
|
210
|
+
if (r.status === 200 && type.startsWith('text/html')) {
|
|
211
|
+
const page = new Response(r.body, { status: r.status, headers: out })
|
|
212
|
+
return new HTMLRewriter().on('head', { element: (e) => { e.append(APP_HEAD, { html: true }) } }).transform(page)
|
|
213
|
+
}
|
|
214
|
+
const etag = out.get('etag')
|
|
215
|
+
if (r.status !== 200 || etag == null || !ZIPS.test(type) || !/\bgzip\b/.test(req.headers.get('accept-encoding') ?? '')) return new Response(r.body, { status: r.status, headers: out })
|
|
216
|
+
const key = `${url.pathname}${url.search}|${etag}`
|
|
217
|
+
let zipped = zips.get(key)
|
|
218
|
+
if (zipped == null) {
|
|
219
|
+
zipped = Bun.gzipSync(new Uint8Array(await r.arrayBuffer()))
|
|
220
|
+
if (zips.size >= ZIP_KEEP) zips.delete(zips.keys().next().value!)
|
|
221
|
+
zips.set(key, zipped)
|
|
222
|
+
} else await r.body?.cancel()
|
|
223
|
+
out.set('content-encoding', 'gzip')
|
|
224
|
+
out.set('vary', 'Accept-Encoding')
|
|
225
|
+
return new Response(zipped, { status: 200, headers: out })
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
const fetchFn = async (req: Request, srv: Bun.Server<Pipe>): Promise<Response | undefined> => {
|
|
229
|
+
const host = req.headers.get('host')
|
|
230
|
+
if (!hostAllowed(host, hosts)) return new Response(hostRefusedText(host), { status: 403, headers: { 'content-type': 'text/plain; charset=utf-8' } })
|
|
126
231
|
const url = new URL(req.url)
|
|
127
232
|
const path = url.pathname
|
|
233
|
+
if (path === '/_bun/hmr' && req.headers.get('upgrade')?.toLowerCase() === 'websocket')
|
|
234
|
+
return srv.upgrade(req, { data: { path: `${path}${url.search}`, up: null, queue: [] } }) ? undefined : new Response('the hot reload socket did not open', { status: 400 })
|
|
235
|
+
if (path === '/manifest.webmanifest') return Response.json(MANIFEST, { headers: { 'content-type': 'application/manifest+json', 'cache-control': 'no-cache' } })
|
|
128
236
|
if (proxied(path)) return proxy(req, url, srv)
|
|
237
|
+
if (pages.has(path) || path.startsWith('/_bun/')) return toPage(req, url)
|
|
129
238
|
const bare = /^\/r\/([^/]+)$/.exec(path)
|
|
130
239
|
if (bare != null) return Response.redirect(`${path}/${url.search}`, 308)
|
|
131
240
|
// a repo page the routes do not have yet: ask the daemon, set them, ask again
|
|
@@ -134,22 +243,51 @@ export function serveWeb<T extends Bun.HTMLBundle | Response>(d: WebDeps<T>) {
|
|
|
134
243
|
if (n instanceof Error) return new Response(downPage(daemonDownText(d.daemon, n.message)), { status: 503, headers: { 'content-type': 'text/html; charset=utf-8' } })
|
|
135
244
|
const name = decodeURIComponent(path.slice(3, -1))
|
|
136
245
|
// known: its route is set now (here, or by a list that landed meanwhile)
|
|
137
|
-
if (n.includes(name)) {
|
|
246
|
+
if (n.repos.includes(name)) {
|
|
138
247
|
sync(n)
|
|
139
248
|
return Response.redirect(`${path}${url.search}`, 307)
|
|
140
249
|
}
|
|
141
250
|
return new Response(`not a house repo: ${name}. The home lists its repos at /`, { status: 404 })
|
|
142
251
|
}
|
|
143
|
-
return
|
|
252
|
+
return notFound()
|
|
144
253
|
}
|
|
145
254
|
|
|
146
|
-
const server = Bun.serve({
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
255
|
+
const server = Bun.serve<Pipe>({
|
|
256
|
+
port: d.port,
|
|
257
|
+
hostname: '127.0.0.1',
|
|
258
|
+
fetch: fetchFn,
|
|
259
|
+
websocket: {
|
|
260
|
+
open(ws) {
|
|
261
|
+
const up = new WebSocket(`ws://${innerAt}${ws.data.path}`)
|
|
262
|
+
up.binaryType = 'arraybuffer'
|
|
263
|
+
ws.data.up = up
|
|
264
|
+
up.onopen = () => {
|
|
265
|
+
for (const m of ws.data.queue.splice(0)) up.send(m)
|
|
266
|
+
}
|
|
267
|
+
up.onmessage = (e) => ws.send(e.data as string | ArrayBuffer)
|
|
268
|
+
up.onclose = () => ws.close()
|
|
269
|
+
up.onerror = () => ws.close()
|
|
270
|
+
},
|
|
271
|
+
message(ws, m) {
|
|
272
|
+
const up = ws.data.up
|
|
273
|
+
const msg = typeof m === 'string' ? m : new Uint8Array(m)
|
|
274
|
+
if (up?.readyState === WebSocket.OPEN) up.send(msg)
|
|
275
|
+
else ws.data.queue.push(msg)
|
|
276
|
+
},
|
|
277
|
+
close(ws) {
|
|
278
|
+
ws.data.up?.close()
|
|
279
|
+
},
|
|
280
|
+
},
|
|
281
|
+
})
|
|
282
|
+
/** the page routes follow the daemon's repo list, and the allowed names its tailnet names; true when the routes changed */
|
|
283
|
+
function sync(list: { repos: string[]; hosts: string[] }): boolean {
|
|
284
|
+
hosts = new Set([...(d.hosts ?? []), ...list.hosts].map(hostName))
|
|
285
|
+
const sorted = [...list.repos].sort()
|
|
150
286
|
if (sorted.join('\0') === known) return false
|
|
151
287
|
known = sorted.join('\0')
|
|
152
|
-
|
|
288
|
+
const routes = pageRoutes(sorted, d.page)
|
|
289
|
+
pages = new Set(Object.keys(routes))
|
|
290
|
+
inner.reload({ routes, fetch: notFound })
|
|
153
291
|
return true
|
|
154
292
|
}
|
|
155
293
|
/** the routes follow the daemon's list: asked again soon while the
|
|
@@ -170,6 +308,7 @@ export function serveWeb<T extends Bun.HTMLBundle | Response>(d: WebDeps<T>) {
|
|
|
170
308
|
stopped = true
|
|
171
309
|
if (listTimer != null) clearTimeout(listTimer)
|
|
172
310
|
server.stop(true)
|
|
311
|
+
inner.stop(true)
|
|
173
312
|
},
|
|
174
313
|
}
|
|
175
314
|
}
|