rvlib-shipkit 2.17.1 → 2.19.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 (64) hide show
  1. package/CHANGELOG.md +27 -0
  2. package/package.json +1 -1
  3. package/src/asks/asks-queue.ts +63 -10
  4. package/src/checks/SK039-vscode-watch-generated.check.ts +119 -0
  5. package/src/cli/cmd_Asks.ts +3 -1
  6. package/src/cli/cmd_GlobalProcesses.ts +34 -11
  7. package/src/cli/cmd_Home.ts +38 -2
  8. package/src/cli/cmd_Secret.ts +4 -30
  9. package/src/cli/cmd_Social.ts +40 -1
  10. package/src/cli/cmd_Trailer.ts +15 -3
  11. package/src/cli/registry.ts +2 -1
  12. package/src/collections/actions.ts +29 -1
  13. package/src/collections/collection-types.ts +2 -0
  14. package/src/collections/providers.ts +1 -1
  15. package/src/home/home-paths.ts +5 -1
  16. package/src/home/home-start.ts +12 -12
  17. package/src/home/run-daemon.ts +11 -2
  18. package/src/home/run-pm.ts +9 -1
  19. package/src/home/supervise.ts +3 -1
  20. package/src/identities/identities.ts +22 -5
  21. package/src/review/http.ts +7 -2
  22. package/src/review/store.ts +81 -19
  23. package/src/scaffold/files/vscode-settings.json +9 -1
  24. package/src/secrets/manager.ts +59 -0
  25. package/src/secrets/name.ts +2 -0
  26. package/src/serve/hub-app/auto-text.tsx +6 -1
  27. package/src/serve/hub-app/col-card.tsx +10 -0
  28. package/src/serve/hub-app/cols-svc.ts +37 -6
  29. package/src/serve/hub-app/hub.css +1 -0
  30. package/src/serve/hub-app/review/review-st.ts +12 -2
  31. package/src/serve/hub-app/review/review-thread.tsx +1 -1
  32. package/src/serve/hub-app/review/thread-st.ts +17 -1
  33. package/src/serve/hub-app/social/identity-pictures.ts +74 -0
  34. package/src/serve/hub-app/social/kit.tsx +3 -3
  35. package/src/serve/hub-app/social/post-card.tsx +2 -1
  36. package/src/serve/hub-app/social/social-page.tsx +77 -37
  37. package/src/serve/hub-app/social.css +9 -4
  38. package/src/serve/hub-app/stores/stores-page.tsx +4 -3
  39. package/src/serve/hub-app/veille/veille-page.tsx +2 -1
  40. package/src/serve/serve-hub.ts +16 -6
  41. package/src/serve/warm-cell.ts +63 -1
  42. package/src/shot/box.ts +23 -8
  43. package/src/shot/browser-slot.ts +8 -1
  44. package/src/shot/client.ts +9 -4
  45. package/src/shot/clip-encoder.ts +5 -2
  46. package/src/shot/job-store.ts +167 -0
  47. package/src/shot/shooter.ts +8 -3
  48. package/src/social/discord-layout.ts +239 -0
  49. package/src/social/md.ts +14 -6
  50. package/src/social/publish/discord.ts +3 -2
  51. package/src/social/routes.ts +3 -3
  52. package/src/stores/routes.ts +2 -2
  53. package/src/suite/judge-suites.ts +1 -1
  54. package/src/suite/select.ts +32 -6
  55. package/src/suite/suite-cli.ts +5 -5
  56. package/src/trailer/build.ts +75 -50
  57. package/src/trailer/draft.ts +28 -0
  58. package/src/trailer/footage.ts +4 -2
  59. package/src/trailer/grammar.ts +11 -9
  60. package/src/trailer/graph.ts +41 -12
  61. package/src/trailer/profile.ts +35 -0
  62. package/src/trailer/prune.ts +15 -10
  63. package/src/trailer/stitch.ts +22 -10
  64. package/src/trailer/titles.ts +47 -2
@@ -11,7 +11,8 @@ import { pageOf, searchWiki } from 'rvlib-shipkit/src/wiki/graph-pages.ts'
11
11
  import { graphRoutes } from 'rvlib-shipkit/src/wiki/serve-graph.ts'
12
12
  import type { StudioRoutes } from '../assets/server/studio-server.ts'
13
13
  import { comfyBoxUp, type ComfyBox, type ComfyPanelUp } from '../comfy/comfy-panel.ts'
14
- import { appendAskRemark, appendAssetNote, askDone, askProof } from '../collections/actions.ts'
14
+ import { appendAskRemark, appendAssetNote, askDone, askProof, askSecret } from '../collections/actions.ts'
15
+ import { managerStore, type SecretStore } from '../secrets/manager.ts'
15
16
  import { brokenRow, projectResources, type Collection, type Instance, type NeedItem, type Resource } from '../collections/collection-types.ts'
16
17
  import type { CheckEvent } from '../core/run-check.ts'
17
18
  import { configDirty, readGateBlock, writeGateBlock, type GateEdit } from '../core/when-block.ts'
@@ -32,7 +33,7 @@ import { projectGutter } from './project-gutter-route.ts'
32
33
  import { sameOrigin } from './same-origin.ts'
33
34
  import { LAYOUT } from '../core/layout.ts'
34
35
  import { heldNow, heldText } from '../core/last-good.ts'
35
- import { WarmCell } from './warm-cell.ts'
36
+ import { WarmCell, warmQueue } from './warm-cell.ts'
36
37
  import { resourcesAnswer, testRunsAnswer } from './resources-wire.ts'
37
38
  import { readmeRoutes } from './readme-route.ts'
38
39
  import { reviewRoutes } from '../review/routes.ts'
@@ -110,6 +111,9 @@ export type HubDeps = {
110
111
  collections: () => Collection[]
111
112
  /** asks dir (repo-root-relative) for the act-in-place ask verbs */
112
113
  asksDir: string
114
+ /** where a value pasted under a credential ask goes; absent = the repo's
115
+ * `credsCommand`, as `sk secret set` runs it */
116
+ storeSecret?: SecretStore
113
117
  /** the comfy panel; null when the repo declares no workflow module, which
114
118
  * is also when the comfy section is absent from the page */
115
119
  comfy: ComfyDeps | null
@@ -185,15 +189,15 @@ export function hubHandler(d: HubDeps, o: { base?: string; projects?: Gutter } =
185
189
  const projects = o.projects ?? projectGutter({ root: d.root })
186
190
  // the answers a page waits on when a repo shows, kept warm in memory: a
187
191
  // request answers from here and never walks the repo (warm-cell.ts)
188
- const warmOpts = { stamp: d.stamp, maxAgeMs: WARM_MAX_AGE_MS }
192
+ const warmOpts = { stamp: d.stamp, maxAgeMs: WARM_MAX_AGE_MS, queue: warmQueue }
189
193
  const rows = new WarmCell<Rows>(async () => {
190
194
  await d.refresh?.()
191
195
  const cols = d.collections()
192
196
  return { collections: cols.map((c) => ({ id: c.id, title: c.title, media: c.media })), resources: await projectResources(cols, d.hubProblems?.collector) }
193
197
  }, { ...warmOpts, what: `warm rows: ${d.name}` })
194
198
  // the run record and the config are all it reads, and the stamp sees both
195
- const timeline = d.timeline == null ? null : new WarmCell(d.timeline, { stamp: d.stamp, what: `warm timeline: ${d.name}` })
196
- const graphs = new Map(d.graphs.map((g) => [g.id, new WarmCell(async () => g.load(), { maxAgeMs: WARM_MAX_AGE_MS, what: `warm graph ${g.id}: ${d.name}` })]))
199
+ const timeline = d.timeline == null ? null : new WarmCell(d.timeline, { stamp: d.stamp, queue: warmQueue, what: `warm timeline: ${d.name}` })
200
+ const graphs = new Map(d.graphs.map((g) => [g.id, new WarmCell(async () => g.load(), { maxAgeMs: WARM_MAX_AGE_MS, queue: warmQueue, what: `warm graph ${g.id}: ${d.name}` })]))
197
201
  const fresh = (req: Request): boolean => new URL(req.url).searchParams.get('fresh') === '1'
198
202
  /** the last gzipped list, answered again to the next page while it holds */
199
203
  let zipped: Parameters<typeof resourcesAnswer>[3] = null
@@ -276,8 +280,14 @@ export function hubHandler(d: HubDeps, o: { base?: string; projects?: Gutter } =
276
280
  if (path.startsWith('/api/act/') && req.method === 'POST') {
277
281
  // act-in-place verbs — every mutation hits a git-tracked truth
278
282
  // file; errors surface as 400 text the card shows verbatim
283
+ // a parse error quotes the body, which can carry a pasted secret
284
+ const b = (await req.json().catch(() => null)) as Record<string, string> | null
285
+ if (b == null || typeof b !== 'object') return new Response('the body is not a json object', { status: 400 })
279
286
  try {
280
- const b = (await req.json()) as Record<string, string>
287
+ if (path === '/api/act/ask-secret') {
288
+ const value = typeof b.value === 'string' ? b.value : ''
289
+ return Response.json(await askSecret({ root: d.root, asksDir: d.asksDir, file: b.file ?? '', name: b.name ?? '', value, store: d.storeSecret ?? managerStore(d.root) }))
290
+ }
281
291
  if (path === '/api/act/ask-done') askDone(d.root, d.asksDir, b.file ?? '')
282
292
  else if (path === '/api/act/ask-proof') askProof(d.root, d.asksDir, b.file ?? '', b.url ?? '')
283
293
  else if (path === '/api/act/remark') {
@@ -19,7 +19,66 @@ export const WARM_WATCH_MS = 30_000
19
19
  * after it ended: a 1.5s answer at most every 15s, a 50ms one at once */
20
20
  export const WARM_SPACING = 10
21
21
 
22
+ /** a background recompute of the queue waits this many times the last one's length after it ended, whichever cell
23
+ * it was: however many repos one process serves, their background warms hold its loop a quarter of the time at most */
24
+ export const WARM_GAP = 3
25
+
26
+ /** the background recomputes of every cell given it, one at a time, spaced by WARM_GAP times the last one's length.
27
+ * Per cell spacing alone let fourteen watched repos, each a tenth of the time, hold the daemon's loop more than all
28
+ * of it on a loaded machine. A reader waiting on an answer never queues: only the recomputes behind a served answer */
29
+ export class WarmQueue {
30
+ private waiting: { key: object; go: () => Promise<unknown> }[] = []
31
+ private busy = false
32
+ private nextAt = 0
33
+ private timer: ReturnType<typeof setTimeout> | null = null
34
+
35
+ constructor(private readonly gap = WARM_GAP, private readonly now: () => number = () => performance.now()) {}
36
+
37
+ /** `go` in its turn; a key already waiting keeps its place and is not queued twice */
38
+ add(key: object, go: () => Promise<unknown>): void {
39
+ if (this.waiting.some((w) => w.key === key)) return
40
+ this.waiting.push({ key, go })
41
+ this.pump()
42
+ }
43
+
44
+ get length(): number {
45
+ return this.waiting.length
46
+ }
47
+
48
+ private pump(): void {
49
+ if (this.busy || this.timer != null) return
50
+ const next = this.waiting[0]
51
+ if (next == null) return
52
+ const wait = this.nextAt - this.now()
53
+ if (wait > 0) {
54
+ this.timer = setTimeout(() => {
55
+ this.timer = null
56
+ this.pump()
57
+ }, wait)
58
+ this.timer.unref?.()
59
+ return
60
+ }
61
+ this.waiting.shift()
62
+ this.busy = true
63
+ const start = this.now()
64
+ void next
65
+ .go()
66
+ .catch(() => {})
67
+ .finally(() => {
68
+ const end = this.now()
69
+ this.nextAt = end + this.gap * (end - start)
70
+ this.busy = false
71
+ this.pump()
72
+ })
73
+ }
74
+ }
75
+
76
+ /** the process's one queue: every hub of the daemon gives its warm cells this one */
77
+ export const warmQueue = new WarmQueue()
78
+
22
79
  export type WarmCellOpts = {
80
+ /** the queue its background recomputes take turns in; none, each runs at once */
81
+ queue?: WarmQueue
23
82
  /** a cheap fingerprint of what the answer reads (file stats): a new one
24
83
  * marks the answer stale */
25
84
  stamp?: () => string
@@ -78,7 +137,10 @@ export class WarmCell<T> {
78
137
  * kicks again. On a failure the last answer stays */
79
138
  private kick(): void {
80
139
  if (this.last != null && this.now() < this.last.end + WARM_SPACING * this.last.ms) return
81
- void this.run().catch(() => {})
140
+ const q = this.o.queue
141
+ if (q == null) return void this.run().catch(() => {})
142
+ // in its turn, only when the answer still needs it: a reader may have computed it meanwhile
143
+ q.add(this, () => (this.stale || this.gen !== this.runGen ? this.run() : Promise.resolve()))
82
144
  }
83
145
 
84
146
  /** a reader asked within WARM_WATCH_MS */
package/src/shot/box.ts CHANGED
@@ -11,10 +11,16 @@ import { createHash } from 'crypto'
11
11
  import { readFileSync } from 'fs'
12
12
  import { browserCap, browserSlot, filmBox, HERE_ENV } from './browser-slot.ts'
13
13
  import { CDP_PORT } from './film-box.ts'
14
+ import { JOB_STORE_END, jobId, jobStoreScript } from './job-store.ts'
14
15
 
15
16
 
16
17
  /** the slice of playwright the route drives: a browser to connect to, its default context, a page's viewport */
17
- type PwPage = { setViewportSize(v: { width: number; height: number }): Promise<void>; addInitScript(s: { content: string }): Promise<void>; close(): Promise<void> }
18
+ type PwPage = {
19
+ setViewportSize(v: { width: number; height: number }): Promise<void>
20
+ addInitScript(s: { content: string }): Promise<void>
21
+ evaluate(expression: string): Promise<unknown>
22
+ close(): Promise<void>
23
+ }
18
24
  type PwContext = {
19
25
  newPage(): Promise<PwPage>
20
26
  newCDPSession(p: PwPage): Promise<{ send(m: string, p?: Record<string, unknown>): Promise<unknown> }>
@@ -76,21 +82,30 @@ async function forward(box: string, spec: string[], own: { p: ReturnType<typeof
76
82
 
77
83
  const LOCAL = new Set(['localhost', '127.0.0.1', '[::1]'])
78
84
 
85
+ /** whose local store a box page sees: its context's own (job-store.ts), or the origin's one store every job shares */
86
+ export type BoxStore = 'job' | 'shared'
87
+
88
+ /** a page's store removed before it closes; a page that does not answer (frozen, gone) is let go after END_MS, its
89
+ * leftovers swept later by the stale beat rule */
90
+ const END_MS = 500
91
+ const closed = (p: PwPage): Promise<void> =>
92
+ Promise.race([p.evaluate(JOB_STORE_END).catch(() => undefined), Bun.sleep(END_MS)]).then(() => p.close().catch(() => undefined))
93
+
79
94
  /** the box's default context as a launched browser's newContext: each context a set of pages there, the viewport set
80
- * per page; one context because only it keeps the profile's HTTP cache */
81
- function asLaunched(b: PwBrowser, all: PwPage[]) {
95
+ * per page, its own local store unless `store` is 'shared'; one context because only it keeps the profile's HTTP cache */
96
+ export function asLaunched(b: PwBrowser, all: PwPage[], store: BoxStore = 'job') {
82
97
  return {
83
98
  isConnected: () => b.isConnected(),
84
99
  on: (e: 'disconnected', cb: () => void) => b.on(e, cb),
85
100
  close: async () => {
86
- await Promise.all(all.splice(0).map((p) => p.close().catch(() => undefined)))
101
+ await Promise.all(all.splice(0).map(closed))
87
102
  await b.close()
88
103
  },
89
104
  async newContext(o: { viewport: { width: number; height: number }; deviceScaleFactor: number }) {
90
105
  const ctx = b.contexts()[0]
91
106
  if (ctx == null) throw new Error('the box browser has no default context')
92
107
  const pages: PwPage[] = []
93
- const scripts: string[] = []
108
+ const scripts: string[] = store === 'job' ? [jobStoreScript(jobId())] : []
94
109
  return {
95
110
  async newPage() {
96
111
  const p = await ctx.newPage()
@@ -111,7 +126,7 @@ function asLaunched(b: PwBrowser, all: PwPage[]) {
111
126
  for (const p of pages) await p.addInitScript(s)
112
127
  },
113
128
  async close() {
114
- await Promise.all(pages.splice(0).map((p) => p.close().catch(() => undefined)))
129
+ await Promise.all(pages.splice(0).map(closed))
115
130
  },
116
131
  }
117
132
  },
@@ -120,7 +135,7 @@ function asLaunched(b: PwBrowser, all: PwPage[]) {
120
135
 
121
136
  /** a browser for `who` of the repo at `root`: on its box from a Mac (filmBox), else launched here; one of the repo's
122
137
  * browser slots held until close */
123
- export async function openBrowser<B>(pw: Pw, o: { root?: string; who: string; args: string[]; say?: (l: string) => void }): Promise<Opened<B>> {
138
+ export async function openBrowser<B>(pw: Pw, o: { root?: string; who: string; args: string[]; say?: (l: string) => void; store?: BoxStore }): Promise<Opened<B>> {
124
139
  const say = o.say ?? ((l: string) => console.error(l))
125
140
  const cap = await browserCap(o.root)
126
141
  const box = filmBox(cap)
@@ -142,7 +157,7 @@ export async function openBrowser<B>(pw: Pw, o: { root?: string; who: string; ar
142
157
  say(`${o.who}: filming on ${box} (${state.split(' ').slice(0, 2).join(' ')}, ${Math.round(performance.now() - t)} ms to its browser)`)
143
158
  const reached = new Set<number>()
144
159
  const pages: PwPage[] = []
145
- const browser = asLaunched(b, pages)
160
+ const browser = asLaunched(b, pages, o.store)
146
161
  return {
147
162
  browser: browser as B,
148
163
  where: box,
@@ -52,6 +52,13 @@ export function browserRefusal(c: Pick<BrowserCap, 'repo' | 'box'>, who: string,
52
52
  return `${who}: ${c.repo} films on ${c.box.host} (repo.config.ts browsers.box), so no browser of it starts on this Mac: a browser goes through shot/box.ts openBrowser (${HERE_ENV}=1 films here for one run, the owner's call)`
53
53
  }
54
54
 
55
+ /** a slot holder as a waiter names it: its pid, what it runs, how long it has held the slot */
56
+ export function holderWords(h: { pid: number; check: string; since: number }, now = Date.now()): string {
57
+ const min = Math.floor((now - h.since) / 60_000)
58
+ const age = min < 1 ? 'under a minute' : min < 60 ? `${min} min` : `${Math.floor(min / 60)} h ${String(min % 60).padStart(2, '0')} min`
59
+ return `pid ${h.pid} (${h.check}, held ${age})`
60
+ }
61
+
55
62
  /** wait for one of the repo's browser slots and hold it until the returned release (or this process ends), saying
56
63
  * once whom it waits on; outside any repo there is no cap and nothing is held. `onBox`: the browser runs on the
57
64
  * repo's box, this Mac only drives it */
@@ -67,7 +74,7 @@ export async function browserSlot(who: string, o: { root?: string; say?: (l: str
67
74
  const got = await takeSlot(pool, { repo: c.repo, check: who }, {
68
75
  pollMs: o.pollMs ?? 250,
69
76
  onWait: (held) =>
70
- say(`${who}: waiting for a browser of ${c.repo}${box ? ` on ${box.host}` : ''}, all ${cap} held (repo.config.ts ${key}): ${held.map((h) => `pid ${h.pid} (${h.check})`).join(', ') || 'a holder starting'}`),
77
+ say(`${who}: waiting for a browser of ${c.repo}${box ? ` on ${box.host}` : ''}, all ${cap} held (repo.config.ts ${key}): ${held.map((h) => holderWords(h)).join(', ') || 'a holder starting'}`),
71
78
  })
72
79
  if (got == null) throw new Error(`${who}: the browser slot wait of ${c.repo} stopped with no slot`)
73
80
  return got.release
@@ -3,7 +3,7 @@
3
3
  // and shoot in process only when the machine has no pm (CI, SHIPKIT_NO_HOME). A repo filmed by its box films there
4
4
  // from a Mac (box.ts), on a Shooter of this process.
5
5
  // `sk shot` and the trailer's `url` film both call these.
6
- import { DEFAULT_FPS, DEFAULT_VIEWPORT, DEFAULT_WAIT_MS, type ClipAsk, type ShotAsk, shotUrlBase, type Viewport } from './shot-ask.ts'
6
+ import { capMsOf, DEFAULT_FPS, DEFAULT_VIEWPORT, DEFAULT_WAIT_MS, type ClipAsk, type ShotAsk, shotUrlBase, type Viewport } from './shot-ask.ts'
7
7
  import type { ShotDone } from './shooter.ts'
8
8
 
9
9
  /** the global process id pm knows the service by (shot.shipkit.ts) */
@@ -77,11 +77,16 @@ async function held<T>(who: string, i: ShotInput, log: (l: string) => void, run:
77
77
  }
78
78
 
79
79
  /** null when nothing listens (start it), else the service's answer; a refusal throws its reason */
80
- async function post(route: string, a: ShotAsk): Promise<ShotDone | null> {
80
+ /** how long an ask may wait on the service: its own cap, and as long again for the asks queued before it */
81
+ export const serviceWaitMs = (a: ShotAsk | ClipAsk): number => 2 * capMsOf(a)
82
+
83
+ async function post(route: string, a: ShotAsk | ClipAsk): Promise<ShotDone | null> {
81
84
  let r: Response
85
+ const ms = serviceWaitMs(a)
82
86
  try {
83
- r = await fetch(`${shotUrlBase()}${route}`, { method: 'POST', body: JSON.stringify(a), headers: { 'content-type': 'application/json' } })
84
- } catch {
87
+ r = await fetch(`${shotUrlBase()}${route}`, { method: 'POST', body: JSON.stringify(a), headers: { 'content-type': 'application/json' }, signal: AbortSignal.timeout(ms) })
88
+ } catch (e) {
89
+ if (e instanceof Error && e.name === 'TimeoutError') throw new Error(`the shot service on ${shotUrlBase()} did not answer ${route} of ${a.url} in ${Math.round(ms / 1000)} s: sk gp restart ${SHOT_PROCESS}`)
85
90
  return null
86
91
  }
87
92
  if (!r.ok) throw new Error(await r.text())
@@ -221,7 +221,9 @@ export async function installClip(a: PageClipAsk): Promise<string | null> {
221
221
  /** IN THE PAGE: the stream made since the last take, at most `max` bytes (whole chunks, one at least), base64; '' when
222
222
  * none waits */
223
223
  export async function takeClip(max: number): Promise<string> {
224
- const st = (window as unknown as { __skClip: ClipState }).__skClip
224
+ const st = (window as unknown as { __skClip?: ClipState }).__skClip
225
+ // the page is a new document: it reloaded mid film (a dev server's hot reload when a file is saved)
226
+ if (st == null) throw new Error('the page reloaded while it was filmed (a dev server reloads on a save): film a page that holds still, a build or a server no lane writes to')
225
227
  if (st.failed) throw new Error(st.failed)
226
228
  const from = st.next
227
229
  let bytes = 0
@@ -239,7 +241,8 @@ export async function takeClip(max: number): Promise<string> {
239
241
  }
240
242
 
241
243
  /** IN THE PAGE: resolves once the film ran and the encoder flushed */
242
- export const clipDone = (): Promise<PageClipDone> => (window as unknown as { __skClip: ClipState }).__skClip.done
244
+ export const clipDone = (): Promise<PageClipDone> =>
245
+ (window as unknown as { __skClip?: ClipState }).__skClip?.done ?? Promise.reject(new Error('the page reloaded while it was filmed (a dev server reloads on a save): film a page that holds still, a build or a server no lane writes to'))
243
246
 
244
247
  /** the most stream one take carries, bytes: its base64 is a third more */
245
248
  export const TAKE = 8 << 20
@@ -0,0 +1,167 @@
1
+ // a box context's own store (box.ts asLaunched): every job on the box shares its browser's one default context for the
2
+ // HTTP cache, so an init script gives each context its own view of an origin's localStorage and IndexedDB, keys and
3
+ // databases prefixed `shipkit.job.<id>:` in the real store, the way a launched browser's context starts empty and stays
4
+ // its own. sessionStorage stays native (per tab already). Page: wiki/tools/shipkit/home-unit-files.md, `shot`.
5
+ //
6
+ // The one constraint a reader breaks first: `installJobStore` runs in the page as its own source text (toString), so it
7
+ // closes over nothing from this module and calls the native methods it captured, never the patched ones.
8
+
9
+ /** a job's pages write their beat this often; another job's page sweeps a namespace whose beat is older than STALE_MS */
10
+ const BEAT_MS = 30_000
11
+ const STALE_MS = 10 * 60_000
12
+ /** where the page half keeps its end, for the close */
13
+ const END = 'shipkit.job-store'
14
+
15
+ /** a new context's id: no `:`, so a prefixed key splits once */
16
+ export const jobId = (): string => crypto.randomUUID().replaceAll('-', '').slice(0, 12)
17
+
18
+ /** the page half: localStorage and indexedDB seen through the job's prefix, other jobs' storage events dropped, the
19
+ * stale namespaces of dead jobs removed */
20
+ function installJobStore(id: string, beatMs: number, staleMs: number, end: string): void {
21
+ const PREFIX = 'shipkit.job.'
22
+ const NS = `${PREFIX}${id}:`
23
+ const BEAT = `${PREFIX}${id}`
24
+ const w = window as unknown as Record<PropertyKey, unknown> & Window
25
+ let real: Storage
26
+ try {
27
+ real = w.localStorage
28
+ } catch {
29
+ return // an opaque origin (about:blank, data:) has no store
30
+ }
31
+ const SP = Storage.prototype
32
+ const { getItem, setItem, removeItem, key } = SP
33
+ const length = Object.getOwnPropertyDescriptor(SP, 'length')!.get!
34
+ const all = (): string[] => {
35
+ const out: string[] = []
36
+ for (let i = 0, n = length.call(real) as number; i < n; i++) {
37
+ const k = key.call(real, i)
38
+ if (k != null) out.push(k)
39
+ }
40
+ return out
41
+ }
42
+ const own = (): string[] => all().flatMap((k) => (k.startsWith(NS) ? [k.slice(NS.length)] : []))
43
+ const item = (k: PropertyKey): string | null => getItem.call(real, NS + String(k))
44
+ const put = (k: PropertyKey, v: unknown): void => setItem.call(real, NS + String(k), String(v))
45
+ const drop = (k: PropertyKey): void => removeItem.call(real, NS + String(k))
46
+ const api: Record<string, unknown> = {
47
+ getItem: item,
48
+ setItem: put,
49
+ removeItem: drop,
50
+ clear: () => own().forEach(drop),
51
+ key: (i: number) => own()[i] ?? null,
52
+ }
53
+ const builtin = (p: PropertyKey) => typeof p === 'symbol' || p in SP
54
+ // a Storage as the page reads it: methods, length, and named items (`localStorage.foo`, Object.keys, JSON.stringify)
55
+ const store = new Proxy(Object.create(SP) as Storage, {
56
+ get(_, p, receiver) {
57
+ if (p === 'length') return own().length
58
+ if (typeof p === 'string' && Object.hasOwn(api, p)) return api[p]
59
+ if (builtin(p)) return Reflect.get(SP, p, receiver)
60
+ return item(p) ?? undefined
61
+ },
62
+ set(_, p, v) {
63
+ if (typeof p === 'symbol') return false
64
+ put(p, v)
65
+ return true
66
+ },
67
+ has: (_, p) => builtin(p) || item(p) !== null,
68
+ deleteProperty(_, p) {
69
+ if (typeof p === 'string') drop(p)
70
+ return true
71
+ },
72
+ ownKeys: () => own(),
73
+ getOwnPropertyDescriptor(_, p) {
74
+ const v = typeof p === 'string' ? item(p) : null
75
+ return v === null ? undefined : { value: v, writable: true, enumerable: true, configurable: true }
76
+ },
77
+ defineProperty(_, p, d) {
78
+ if (typeof p === 'symbol' || !('value' in d) || d.configurable === false) return false
79
+ put(p, d.value)
80
+ return true
81
+ },
82
+ getPrototypeOf: () => SP,
83
+ })
84
+ Object.defineProperty(w, 'localStorage', { get: () => store, configurable: true, enumerable: true })
85
+
86
+ // a storage event of the real store reaches the page only when it is this job's, its key without the prefix
87
+ const ours = new WeakSet<Event>()
88
+ w.addEventListener(
89
+ 'storage',
90
+ (e) => {
91
+ if (ours.has(e) || e.storageArea !== real) return
92
+ e.stopImmediatePropagation()
93
+ if (e.key == null || !e.key.startsWith(NS)) return
94
+ const again = new StorageEvent('storage', { key: e.key.slice(NS.length), oldValue: e.oldValue, newValue: e.newValue, url: e.url })
95
+ Object.defineProperty(again, 'storageArea', { value: store })
96
+ ours.add(again)
97
+ w.dispatchEvent(again)
98
+ },
99
+ true,
100
+ )
101
+
102
+ const F = w.indexedDB != null ? IDBFactory.prototype : null
103
+ const open = F?.open
104
+ const del = F?.deleteDatabase
105
+ const dbs = F?.databases
106
+ if (F && open && del) {
107
+ F.open = function (this: IDBFactory, name: string, ...rest: [number?]) {
108
+ return open.call(this, NS + String(name), ...rest)
109
+ }
110
+ F.deleteDatabase = function (this: IDBFactory, name: string) {
111
+ return del.call(this, NS + String(name))
112
+ }
113
+ if (dbs)
114
+ F.databases = async function (this: IDBFactory) {
115
+ return (await dbs.call(this)).flatMap((d) => (d.name?.startsWith(NS) ? [{ ...d, name: d.name.slice(NS.length) }] : []))
116
+ }
117
+ const name = Object.getOwnPropertyDescriptor(IDBDatabase.prototype, 'name')!.get!
118
+ Object.defineProperty(IDBDatabase.prototype, 'name', {
119
+ get(this: IDBDatabase) {
120
+ const n = name.call(this) as string
121
+ return n.startsWith(NS) ? n.slice(NS.length) : n
122
+ },
123
+ configurable: true,
124
+ enumerable: true,
125
+ })
126
+ }
127
+
128
+ const beat = () => {
129
+ try {
130
+ setItem.call(real, BEAT, String(Date.now()))
131
+ } catch {}
132
+ }
133
+ beat()
134
+ const beating = setInterval(beat, beatMs)
135
+
136
+ // the dead jobs' leftovers: a namespace whose beat is stale or gone (the jobs that run beat, this one just did)
137
+ const jobOf = (k: string): string | null => (k.startsWith(PREFIX) ? k.slice(PREFIX.length).split(':')[0]! : null)
138
+ const keys = all()
139
+ const live = new Set(keys.filter((k) => jobOf(k) === k.slice(PREFIX.length) && Date.now() - Number(getItem.call(real, k)) < staleMs).map(jobOf))
140
+ for (const k of keys) {
141
+ const j = jobOf(k)
142
+ if (j != null && !live.has(j)) removeItem.call(real, k)
143
+ }
144
+ const idb = w.indexedDB
145
+ if (dbs && del)
146
+ void dbs
147
+ .call(idb)
148
+ .then((list) => {
149
+ for (const d of list) if (d.name && jobOf(d.name) != null && !live.has(jobOf(d.name))) del.call(idb, d.name)
150
+ })
151
+ .catch(() => undefined)
152
+
153
+ Object.defineProperty(w, Symbol.for(end), {
154
+ configurable: true,
155
+ value: async () => {
156
+ clearInterval(beating)
157
+ for (const k of all()) if (k === BEAT || k.startsWith(NS)) removeItem.call(real, k)
158
+ if (dbs && del) for (const d of await dbs.call(idb)) if (d.name?.startsWith(NS)) del.call(idb, d.name)
159
+ },
160
+ })
161
+ }
162
+
163
+ /** the init script of the context `id`, added to each of its pages before any other */
164
+ export const jobStoreScript = (id: string): string => `(${installJobStore.toString()})(${JSON.stringify(id)}, ${BEAT_MS}, ${STALE_MS}, ${JSON.stringify(END)})`
165
+
166
+ /** run in a page of the context before it closes: its keys and databases on the page's origin go */
167
+ export const JOB_STORE_END = `globalThis[Symbol.for(${JSON.stringify(END)})]?.()`
@@ -82,6 +82,8 @@ export const LIVE_MS = 10_000
82
82
  export const BROWSER_IDLE_MS = 60_000
83
83
  /** the niceness of the process that launches the browser: chromium inherits it */
84
84
  export const SHOT_NICE = 10
85
+ /** a browser close that has not answered in this long (a stalled box route) is left behind, so its slot frees */
86
+ export const CLOSE_MS = 5000
85
87
  /** a page that paints nothing once the screencast starts is filmed from one still taken after this */
86
88
  const FIRST_FRAME_MS = 1000
87
89
 
@@ -155,12 +157,15 @@ export class Shooter {
155
157
  if (s) await this.#keep(s.ctx)
156
158
  const b = this.#browser
157
159
  this.#browser = null
158
- await b?.close().catch(() => undefined)
159
- this.#free()
160
+ try {
161
+ if (b) await withCap('closing the browser', CLOSE_MS, b.close()).catch(() => undefined)
162
+ } finally {
163
+ this.#free()
164
+ }
160
165
  }
161
166
 
162
167
  async #keep(ctx: Context): Promise<void> {
163
- this.#jar = await ctx.cookies().catch(() => this.#jar)
168
+ this.#jar = await withCap('reading the cookies', CLOSE_MS, ctx.cookies()).catch(() => this.#jar)
164
169
  }
165
170
 
166
171
  #free(): void {