rvlib-shipkit 2.12.0 → 2.13.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 (290) hide show
  1. package/CHANGELOG.md +48 -13
  2. package/README.md +1 -1
  3. package/package.json +4 -2
  4. package/src/agent-time/store.ts +2 -2
  5. package/src/check.ts +1 -1
  6. package/src/checks/SK001-package-json-shape.check.ts +4 -0
  7. package/src/checks/SK003-claude-md-shape.check.ts +1 -1
  8. package/src/checks/SK004-gitignore-policy.check.ts +27 -2
  9. package/src/checks/SK005-rvlib-versions.check.ts +1 -1
  10. package/src/checks/SK008-reviewer-agent.check.ts +2 -2
  11. package/src/checks/SK012-config-barrel-import.check.ts +1 -1
  12. package/src/checks/SK015-nested-repo.check.ts +1 -1
  13. package/src/checks/SK035-public-clean.check.ts +46 -0
  14. package/src/checks/SK036-draft-media-size.check.ts +28 -0
  15. package/src/cli/cmd_Backup.ts +152 -0
  16. package/src/cli/cmd_Ci.ts +8 -11
  17. package/src/cli/cmd_Drill.ts +145 -0
  18. package/src/cli/cmd_Home.ts +50 -3
  19. package/src/cli/cmd_Media.ts +7 -5
  20. package/src/cli/cmd_Review.ts +4 -2
  21. package/src/cli/cmd_Shot.ts +5 -2
  22. package/src/cli/cmd_Smoke.ts +4 -1
  23. package/src/cli/cmd_Social.ts +226 -0
  24. package/src/cli/cmd_Start.ts +1 -1
  25. package/src/cli/cmd_Time.ts +1 -1
  26. package/src/cli/cmd_Trailer.ts +5 -2
  27. package/src/cli/cmd_Veille.ts +173 -0
  28. package/src/cli/family-pages.ts +3 -0
  29. package/src/cli/registry.ts +13 -2
  30. package/src/cli.ts +5 -2
  31. package/src/collections/actions.ts +1 -49
  32. package/src/collections/checks.ts +2 -1
  33. package/src/collections/collection-types.ts +11 -2
  34. package/src/collections/providers.ts +4 -4
  35. package/src/collections/review.ts +2 -1
  36. package/src/collections/tests.ts +19 -8
  37. package/src/contracts/apply-contracts.ts +1 -3
  38. package/src/contracts/contract-manifests.ts +2 -3
  39. package/src/contracts/contract-types.ts +0 -1
  40. package/src/contracts/contracts-engine.ts +0 -3
  41. package/src/core/app-icon.ts +9 -3
  42. package/src/core/bun-builtins.ts +2 -2
  43. package/src/core/discover-checks.ts +37 -5
  44. package/src/core/fix-scope.ts +4 -2
  45. package/src/core/floor-resolve.ts +68 -48
  46. package/src/core/floor.ts +9 -0
  47. package/src/core/git-root.ts +24 -0
  48. package/src/core/last-good.ts +3 -1
  49. package/src/core/layout.ts +8 -0
  50. package/src/core/log-stamp.ts +36 -0
  51. package/src/core/loop-watch.ts +93 -0
  52. package/src/core/machine-link.ts +134 -0
  53. package/src/core/memory-watch.ts +41 -0
  54. package/src/core/one-way-in-policy.ts +27 -19
  55. package/src/core/run-ci.ts +6 -8
  56. package/src/core/run-fixers.ts +9 -9
  57. package/src/core/slots.ts +21 -0
  58. package/src/core/tree-rev.ts +60 -0
  59. package/src/core/unit-files.ts +42 -0
  60. package/src/drill/render.ts +140 -0
  61. package/src/drill/run.ts +269 -0
  62. package/src/fleet/scan-fleet.ts +6 -5
  63. package/src/home/daemon-jobs.ts +201 -0
  64. package/src/home/global-context.ts +34 -1
  65. package/src/home/home-routes.ts +22 -15
  66. package/src/home/hubs.ts +10 -3
  67. package/src/home/inbox-shape.ts +53 -4
  68. package/src/home/inbox.ts +16 -1
  69. package/src/home/lib-watch.ts +10 -3
  70. package/src/home/machine-stores.ts +15 -29
  71. package/src/home/run-daemon.ts +15 -18
  72. package/src/home/run-pm.ts +2 -0
  73. package/src/home/serve-daemon.ts +4 -3
  74. package/src/home/serve-web.ts +104 -1
  75. package/src/hooks/commit-message.ts +28 -19
  76. package/src/hooks/leak-guard.ts +10 -3
  77. package/src/hooks/run-hooks.ts +2 -6
  78. package/src/identities/identities.ts +334 -0
  79. package/src/identities/machine-route.ts +126 -0
  80. package/src/identities/machine.ts +62 -0
  81. package/src/init-repo.ts +1 -1
  82. package/src/ledger/check-stats.ts +10 -9
  83. package/src/ledger/gate-checks.ts +32 -1
  84. package/src/ledger/record-kept.ts +112 -0
  85. package/src/ledger/repo-view.ts +10 -0
  86. package/src/ledger/run-log.ts +17 -12
  87. package/src/ledger/run-timeline.ts +8 -4
  88. package/src/ledger/store.ts +7 -0
  89. package/src/ledger/suite-log.ts +17 -13
  90. package/src/media-kinds.ts +2 -1
  91. package/src/media-store/backup/daemon.ts +73 -0
  92. package/src/media-store/backup/keys.ts +25 -0
  93. package/src/media-store/backup/manifest.ts +193 -0
  94. package/src/media-store/backup/restore.ts +192 -0
  95. package/src/media-store/backup/run.ts +278 -0
  96. package/src/media-store/backup/secret.ts +86 -0
  97. package/src/media-store/backup/snapshot.ts +64 -0
  98. package/src/media-store/backup/sources.ts +199 -0
  99. package/src/media-store/daemon.ts +56 -70
  100. package/src/media-store/put.ts +4 -2
  101. package/src/media-store/space.ts +23 -4
  102. package/src/pages/forward.ts +35 -0
  103. package/src/pages/frame-client.ts +118 -0
  104. package/src/pages/routes.ts +29 -0
  105. package/src/pages/unit.ts +92 -0
  106. package/src/plan/planner.ts +12 -0
  107. package/src/plan/repo-source.ts +19 -5
  108. package/src/reflect/transcript.ts +35 -10
  109. package/src/release/public-clean.ts +301 -0
  110. package/src/release/published-here.ts +22 -0
  111. package/src/release/run-bump.ts +2 -1
  112. package/src/release/run-release.ts +4 -1
  113. package/src/repo-config.ts +53 -2
  114. package/src/review/http.ts +16 -2
  115. package/src/review/model.ts +15 -4
  116. package/src/review/notes.ts +77 -0
  117. package/src/review/project.ts +6 -38
  118. package/src/review/routes.ts +4 -12
  119. package/src/review/store.ts +41 -1
  120. package/src/review/trailer-media.ts +7 -4
  121. package/src/review/trailer-shots.ts +21 -4
  122. package/src/review/unit.ts +1 -1
  123. package/src/scaffold/files/agent-handoff.md +3 -0
  124. package/src/scaffold/files/agent-index.md +4 -12
  125. package/src/scaffold/project-scaffold.ts +5 -4
  126. package/src/serve/embed.ts +1 -1
  127. package/src/serve/hub-app/col-card.tsx +3 -17
  128. package/src/serve/hub-app/col-tables-view.tsx +2 -1
  129. package/src/serve/hub-app/cols-svc.ts +0 -13
  130. package/src/serve/hub-app/dock-st.ts +4 -2
  131. package/src/serve/hub-app/dock-view.tsx +2 -0
  132. package/src/serve/hub-app/frames-st.ts +35 -0
  133. package/src/serve/hub-app/hash-route.ts +64 -1
  134. package/src/serve/hub-app/home-st.ts +31 -7
  135. package/src/serve/hub-app/home-strip.css +9 -1
  136. package/src/serve/hub-app/home-strip.tsx +7 -6
  137. package/src/serve/hub-app/home.html +5 -0
  138. package/src/serve/hub-app/hub-app.tsx +49 -5
  139. package/src/serve/hub-app/hub.css +29 -11
  140. package/src/serve/hub-app/icons.tsx +16 -1
  141. package/src/serve/hub-app/identities-st.ts +210 -0
  142. package/src/serve/hub-app/identities-view.tsx +352 -0
  143. package/src/serve/hub-app/identities.css +48 -0
  144. package/src/serve/hub-app/identity-address.ts +52 -0
  145. package/src/serve/hub-app/inbox-st.ts +59 -6
  146. package/src/serve/hub-app/inbox-view.tsx +48 -6
  147. package/src/serve/hub-app/inbox.css +12 -1
  148. package/src/serve/hub-app/index.html +3 -0
  149. package/src/serve/hub-app/keys.ts +10 -2
  150. package/src/serve/hub-app/list-walk.ts +89 -0
  151. package/src/serve/hub-app/machine-st.ts +12 -0
  152. package/src/serve/hub-app/media-view.tsx +2 -1
  153. package/src/serve/hub-app/pages-frames.tsx +134 -0
  154. package/src/serve/hub-app/pages-svc.ts +111 -0
  155. package/src/serve/hub-app/palette-st.ts +18 -3
  156. package/src/serve/hub-app/palette-view.tsx +9 -2
  157. package/src/serve/hub-app/planned-view.tsx +2 -1
  158. package/src/serve/hub-app/project-list.css +18 -14
  159. package/src/serve/hub-app/project-list.tsx +88 -49
  160. package/src/serve/hub-app/projects-svc.ts +33 -3
  161. package/src/serve/hub-app/repo-sections.ts +19 -2
  162. package/src/serve/hub-app/repo-st.ts +75 -19
  163. package/src/serve/hub-app/review/review-cells.tsx +3 -3
  164. package/src/serve/hub-app/review/review-kit.ts +30 -7
  165. package/src/serve/hub-app/review/review-page.tsx +1 -1
  166. package/src/serve/hub-app/review/review-st.ts +19 -8
  167. package/src/serve/hub-app/review/review-thread.tsx +11 -9
  168. package/src/serve/hub-app/review/review-views.tsx +84 -19
  169. package/src/serve/hub-app/review/thread-st.ts +1 -10
  170. package/src/serve/hub-app/review/trailer-page.tsx +2 -1
  171. package/src/serve/hub-app/review.css +17 -8
  172. package/src/serve/hub-app/site/site-part.tsx +173 -0
  173. package/src/serve/hub-app/site/site-st.ts +157 -0
  174. package/src/serve/hub-app/site.css +35 -0
  175. package/src/serve/hub-app/social/calendar.tsx +182 -0
  176. package/src/serve/hub-app/social/comms-page.tsx +306 -0
  177. package/src/serve/hub-app/social/kit.tsx +244 -0
  178. package/src/serve/hub-app/social/post-card.tsx +456 -0
  179. package/src/serve/hub-app/social/problems.tsx +60 -0
  180. package/src/serve/hub-app/social/social-model.ts +154 -0
  181. package/src/serve/hub-app/social/social-page.tsx +674 -0
  182. package/src/serve/hub-app/social/social-st.ts +986 -0
  183. package/src/serve/hub-app/social.css +289 -0
  184. package/src/serve/hub-app/stores/stores-page.tsx +311 -0
  185. package/src/serve/hub-app/stores/stores-st.ts +286 -0
  186. package/src/serve/hub-app/stores.css +54 -0
  187. package/src/serve/hub-app/timeline-geometry.ts +1 -1
  188. package/src/serve/hub-app/timeline-view.tsx +3 -2
  189. package/src/serve/hub-app/tree-build.ts +6 -0
  190. package/src/serve/hub-app/tree-row.tsx +27 -4
  191. package/src/serve/hub-app/tree-svc.ts +18 -49
  192. package/src/serve/hub-app/veille/veille-page.tsx +514 -0
  193. package/src/serve/hub-app/veille/veille-st.ts +443 -0
  194. package/src/serve/hub-app/veille.css +84 -0
  195. package/src/serve/hub-runtime.ts +14 -9
  196. package/src/serve/project-gutter-route.ts +44 -12
  197. package/src/serve/run-lanes.ts +7 -4
  198. package/src/serve/same-origin.ts +1 -1
  199. package/src/serve/serve-hub.ts +20 -12
  200. package/src/serve/tracked-watch.ts +24 -3
  201. package/src/serve/warm-cell.ts +5 -1
  202. package/src/shipkit-files.ts +15 -4
  203. package/src/shipkit.ts +0 -1
  204. package/src/shot/box.ts +162 -0
  205. package/src/shot/browser-slot.ts +62 -0
  206. package/src/shot/client.ts +43 -7
  207. package/src/shot/clip-encoder.ts +93 -12
  208. package/src/shot/film-box.ts +188 -0
  209. package/src/shot/shooter.ts +50 -15
  210. package/src/shot/shot-ask.ts +10 -2
  211. package/src/shot/stepped-clip.ts +5 -4
  212. package/src/site/desk.ts +242 -0
  213. package/src/site/routes.ts +66 -0
  214. package/src/site/unit.ts +62 -0
  215. package/src/social/brands.ts +22 -0
  216. package/src/social/compose.ts +97 -0
  217. package/src/social/desk-index.ts +123 -0
  218. package/src/social/desk-wire.ts +64 -0
  219. package/src/social/drafts.ts +183 -0
  220. package/src/social/house.ts +24 -0
  221. package/src/social/load.ts +319 -0
  222. package/src/social/md.ts +70 -0
  223. package/src/social/media-facts.ts +53 -0
  224. package/src/social/media-kind.ts +189 -0
  225. package/src/social/media-limit.ts +42 -0
  226. package/src/social/media-of.ts +30 -0
  227. package/src/social/migrate.ts +123 -0
  228. package/src/social/open.ts +17 -0
  229. package/src/social/post-url.ts +158 -0
  230. package/src/social/presence.ts +332 -0
  231. package/src/social/public-read.ts +53 -0
  232. package/src/social/publish/bluesky.ts +168 -0
  233. package/src/social/publish/discord.ts +76 -0
  234. package/src/social/publish/index.ts +24 -0
  235. package/src/social/publish/secret.ts +13 -0
  236. package/src/social/push.ts +31 -0
  237. package/src/social/richtext.ts +37 -0
  238. package/src/social/routes.ts +180 -0
  239. package/src/social/stats.ts +134 -0
  240. package/src/social/text.ts +267 -0
  241. package/src/social/tracker-route.ts +39 -0
  242. package/src/social/tracker.ts +255 -0
  243. package/src/social/unit.ts +53 -0
  244. package/src/social/writes.ts +130 -0
  245. package/src/start-repo.ts +14 -9
  246. package/src/stores/collection.ts +27 -0
  247. package/src/stores/desk.ts +336 -0
  248. package/src/stores/model.ts +187 -0
  249. package/src/stores/routes.ts +126 -0
  250. package/src/stores/unit.ts +57 -0
  251. package/src/suite/calibrate.ts +127 -0
  252. package/src/suite/core-counters.ts +91 -0
  253. package/src/suite/judge-suites.ts +94 -34
  254. package/src/suite/suite-cli.ts +44 -10
  255. package/src/suite/suite-cpu-preload.ts +34 -9
  256. package/src/trailer/adapter.ts +4 -0
  257. package/src/trailer/build.ts +42 -11
  258. package/src/trailer/ffmpeg.ts +11 -0
  259. package/src/trailer/footage.ts +30 -13
  260. package/src/trailer/grammar.ts +18 -2
  261. package/src/trailer/graph.ts +28 -6
  262. package/src/trailer/passage.ts +17 -5
  263. package/src/trailer/plan.ts +74 -3
  264. package/src/trailer/stitch.ts +67 -26
  265. package/src/trailer/url.ts +1 -1
  266. package/src/trailer/versions.ts +24 -0
  267. package/src/ts/gate-typecheck.ts +32 -0
  268. package/src/ts/typecheck-cli.ts +9 -11
  269. package/src/tui/tui-app.tsx +0 -1
  270. package/src/veille/asks.ts +155 -0
  271. package/src/veille/auto.ts +31 -0
  272. package/src/veille/batch.ts +27 -0
  273. package/src/veille/chrome.ts +127 -0
  274. package/src/veille/collection.ts +28 -0
  275. package/src/veille/desk.ts +242 -0
  276. package/src/veille/identity.ts +80 -0
  277. package/src/veille/import.ts +68 -0
  278. package/src/veille/log.ts +183 -0
  279. package/src/veille/platforms.ts +118 -0
  280. package/src/veille/reads.ts +66 -0
  281. package/src/veille/replied.ts +110 -0
  282. package/src/veille/routes.ts +185 -0
  283. package/src/veille/service.ts +81 -0
  284. package/src/veille/watch.ts +116 -0
  285. package/src/veille/worth.ts +46 -0
  286. package/src/wiki/scan-md.ts +18 -0
  287. package/src/collections/posts.ts +0 -142
  288. package/src/contracts/manifests/social.contract.ts +0 -20
  289. package/src/scaffold/files/agent-coding.md +0 -35
  290. package/src/ts/typecheck-cache.ts +0 -11
@@ -12,11 +12,12 @@
12
12
  // request reaches it only once its Host is a loopback name or the tailnet name the house declares (serve.publicHost)
13
13
  import { sameOrigin } from '../serve/same-origin.ts'
14
14
  import { hubBase } from './home-paths.ts'
15
+ import { forwardPage, pagePath } from '../pages/forward.ts'
15
16
 
16
17
  /** the page routes: ONE app for the overview, the plan, and the hub page of
17
18
  * each known repo, which moves between them in place (home-st.ts) */
18
19
  export function pageRoutes<T>(names: string[], page: T): Record<string, T> {
19
- const out: Record<string, T> = { '/': page, '/inbox': page, '/planned': page, '/activity': page, '/archived': page, '/insights': page }
20
+ const out: Record<string, T> = { '/': page, '/inbox': page, '/planned': page, '/activity': page, '/archived': page, '/insights': page, '/identities': page }
20
21
  for (const n of names) out[`${hubBase(n)}/`] = page
21
22
  return out
22
23
  }
@@ -52,6 +53,8 @@ export const REPO_ANSWER_MS = 30_000
52
53
  /** how often the web asks the daemon's repo list once it has one, and while it has none */
53
54
  export const LIST_EVERY_MS = 30_000
54
55
  export const LIST_RETRY_MS = 1_000
56
+ /** how long the web keeps a repo's page urls before it asks the daemon again */
57
+ export const PAGE_URLS_MS = 10_000
55
58
 
56
59
  /** the home answers that can wait on git: the activity page's first read of a window, a repo's git page, and the insights page's read of every manifest */
57
60
  export const readsGit = (path: string): boolean => path === '/api/home/activity.json' || path === '/api/home/git.json' || path === '/api/home/insights.json'
@@ -112,6 +115,56 @@ const ZIPS = /^(text\/|application\/(javascript|json)|image\/svg)/
112
115
  /** the gzipped bodies kept, by path and etag: the bundle changes on an edit, not on a request */
113
116
  const ZIP_KEEP = 64
114
117
 
118
+ /** past this wait on the daemon, a GET the web holds a copy of answers that copy, the request still running */
119
+ export const STALE_AFTER_MS = 1_500
120
+ /** the copies kept: by count, and a copy past this size is never kept */
121
+ const LAST_GOOD_MAX = 400
122
+ const LAST_GOOD_BYTES = 2 * 1024 * 1024
123
+
124
+ /** why the web answered its copy: the daemon did not answer at all (a restart), or not yet (a held loop) */
125
+ export type StaleWhy = 'restarting' | 'slow'
126
+
127
+ /** the last good answer of each GET the page reads from the daemon: a JSON answer of status 200, by path, query and
128
+ * encoding, its body as the daemon sent it. A restart of the daemon or a held loop then answers the page from here
129
+ * (wiki build/shipkit/home.md, How it stays up: a restart never blanks the page) */
130
+ export class LastGood {
131
+ private held = new Map<string, { body: Uint8Array<ArrayBuffer>; headers: [string, string][]; at: number }>()
132
+
133
+ /** the key of a request whose answer may be kept, null for any other */
134
+ key(req: Request, url: URL): string | null {
135
+ if (req.method !== 'GET' || streams(url.pathname) || toPm(url.pathname)) return null
136
+ return `${url.pathname}${url.search}|${/\bgzip\b/.test(req.headers.get('accept-encoding') ?? '') ? 'gz' : ''}`
137
+ }
138
+
139
+ has(key: string): boolean {
140
+ return this.held.has(key)
141
+ }
142
+
143
+ /** the daemon's answer, kept when it is a JSON 200 small enough: what the browser gets is the same bytes */
144
+ async keep(key: string, r: Response, headers: Headers): Promise<Response> {
145
+ if (r.status !== 200 || !/^application\/json\b/.test(headers.get('content-type') ?? '')) return new Response(r.body, { status: r.status, statusText: r.statusText, headers })
146
+ const body = new Uint8Array(await r.arrayBuffer())
147
+ if (body.length <= LAST_GOOD_BYTES) {
148
+ this.held.delete(key)
149
+ this.held.set(key, { body, headers: [...headers], at: Date.now() })
150
+ if (this.held.size > LAST_GOOD_MAX) this.held.delete(this.held.keys().next().value!)
151
+ }
152
+ return new Response(body, { status: 200, headers })
153
+ }
154
+
155
+ /** the copy, tagged with why it is served; a 304 when the browser holds it already */
156
+ answer(key: string, req: Request, why: StaleWhy): Response | null {
157
+ const h = this.held.get(key)
158
+ if (h == null) return null
159
+ const headers = new Headers(h.headers)
160
+ headers.set('x-shipkit-daemon', why)
161
+ headers.set('x-shipkit-daemon-at', String(h.at))
162
+ const tag = headers.get('etag')
163
+ if (tag != null && req.headers.get('if-none-match') === tag) return new Response(null, { status: 304, headers })
164
+ return new Response(h.body, { status: 200, headers })
165
+ }
166
+ }
167
+
115
168
  export type WebDeps<T> = {
116
169
  port: number
117
170
  /** the daemon's url, e.g. http://127.0.0.1:4798 */
@@ -126,6 +179,8 @@ export type WebDeps<T> = {
126
179
  listEveryMs?: number
127
180
  /** tailnet names allowed before the daemon names any (a test) */
128
181
  hosts?: string[]
182
+ /** in place of STALE_AFTER_MS (a test) */
183
+ staleAfterMs?: number
129
184
  }
130
185
 
131
186
  /** one browser socket to the page server's hot reload, piped to the same path there */
@@ -141,6 +196,8 @@ export function serveWeb<T extends Bun.HTMLBundle | Response>(d: WebDeps<T>) {
141
196
  /** every page route, as the page server holds them */
142
197
  let pages = new Set(Object.keys(pageRoutes([], d.page)))
143
198
  const zips = new Map<string, Uint8Array<ArrayBuffer>>()
199
+ const lastGood = new LastGood()
200
+ const inflight = new Map<string, Promise<Response>>()
144
201
  /** the repo names the daemon knows and the tailnet names, or the reason it did not answer */
145
202
  async function names(): Promise<{ repos: string[]; hosts: string[] } | Error> {
146
203
  try {
@@ -153,8 +210,23 @@ export function serveWeb<T extends Bun.HTMLBundle | Response>(d: WebDeps<T>) {
153
210
  }
154
211
  }
155
212
 
213
+ /** a GET with a copy never waits past STALE_AFTER_MS: past it, or with the daemon down, the copy answers and the
214
+ * request runs on, its answer the next copy */
156
215
  async function proxy(req: Request, url: URL, srv: Bun.Server<Pipe>): Promise<Response> {
157
216
  if (!sameOrigin(req)) return new Response('refused: a request that changes something must come from the home page', { status: 403 })
217
+ const key = lastGood.key(req, url)
218
+ if (key == null || !lastGood.has(key)) return forward(req, url, srv, key)
219
+ // one request a key at a time while the daemon is slow: a poll never piles up behind a held loop
220
+ if (inflight.has(key)) return lastGood.answer(key, req, 'slow') ?? forward(req, url, srv, key)
221
+ const live = forward(req, url, srv, key).finally(() => inflight.delete(key))
222
+ inflight.set(key, live)
223
+ const first = await Promise.race([live, Bun.sleep(d.staleAfterMs ?? STALE_AFTER_MS).then(() => null)])
224
+ if (first != null && first.headers.get('x-shipkit-daemon') !== 'down') return first
225
+ if (first == null) void live.then((r) => r.body?.cancel()).catch(() => {})
226
+ return lastGood.answer(key, req, first == null ? 'slow' : 'restarting') ?? (first ?? live)
227
+ }
228
+
229
+ async function forward(req: Request, url: URL, srv: Bun.Server<Pipe>, key: string | null): Promise<Response> {
158
230
  const headers = new Headers()
159
231
  req.headers.forEach((v, k) => { if (!DROP.has(k)) headers.set(k, v) })
160
232
  // a run or a live stream can stay silent for minutes
@@ -178,6 +250,7 @@ export function serveWeb<T extends Bun.HTMLBundle | Response>(d: WebDeps<T>) {
178
250
  out.delete('content-length')
179
251
  out.delete('transfer-encoding')
180
252
  out.delete('connection')
253
+ if (key != null) return await lastGood.keep(key, r, out)
181
254
  return new Response(r.body, { status: r.status, statusText: r.statusText, headers: out })
182
255
  } catch (e) {
183
256
  if (timer != null) clearTimeout(timer)
@@ -188,6 +261,31 @@ export function serveWeb<T extends Bun.HTMLBundle | Response>(d: WebDeps<T>) {
188
261
  }
189
262
  }
190
263
 
264
+ /** each repo's pages, by id: where its process serves it, asked of the daemon and kept a while */
265
+ const pageUrls = new Map<string, { at: number; pages: Map<string, { url: string; process?: string }> }>()
266
+ /** a repo page's request straight to the repo's process, the daemon left out of the path: a busy daemon held a page's
267
+ * html 2.5 s (wiki build/shipkit/project-pages.md, The proxy). null: the daemon answers it (a redirect, an unknown page) */
268
+ async function toPageProcess(req: Request, repo: string, rest: string, srv: Bun.Server<Pipe>): Promise<Response | null> {
269
+ const at = pagePath(rest)
270
+ if (at == null || at.rest === null) return null
271
+ let known = pageUrls.get(repo)
272
+ if (known == null || Date.now() - known.at > PAGE_URLS_MS) {
273
+ try {
274
+ const r = await fetch(`${d.daemon}${hubBase(repo)}/api/pages.json`, { signal: AbortSignal.timeout(3_000) })
275
+ const j = (await r.json()) as { pages: { id: string; url: string; process?: string }[] }
276
+ known = { at: Date.now(), pages: new Map(j.pages.map((p) => [p.id, { url: p.url, ...(p.process ? { process: p.process } : {}) }])) }
277
+ pageUrls.set(repo, known)
278
+ } catch {
279
+ // the daemon restarts: the list it gave last still says where the page process serves
280
+ if (known == null) return null
281
+ }
282
+ }
283
+ const p = known.pages.get(at.id)
284
+ if (p == null) return null
285
+ if (!sameOrigin(req)) return new Response('refused: a request that changes something must come from the home page', { status: 403 })
286
+ return forwardPage(req, `${p.url}${at.rest}`, at.id, p.process, srv)
287
+ }
288
+
191
289
  // the page and its bundle, served by Bun's dev server on a loopback port of its own: it bundles the page, serves
192
290
  // its files under /_bun/ and drives the page's hot reload over /_bun/hmr
193
291
  const notFound = (): Response => new Response('not found: the home page is at /', { status: 404 })
@@ -239,6 +337,11 @@ export function serveWeb<T extends Bun.HTMLBundle | Response>(d: WebDeps<T>) {
239
337
  if (path === '/_bun/hmr' && req.headers.get('upgrade')?.toLowerCase() === 'websocket')
240
338
  return srv.upgrade(req, { data: { path: `${path}${url.search}`, up: null, queue: [] } }) ? undefined : new Response('the hot reload socket did not open', { status: 400 })
241
339
  if (path === '/manifest.webmanifest') return Response.json(MANIFEST, { headers: { 'content-type': 'application/manifest+json', 'cache-control': 'no-cache' } })
340
+ const page = /^\/r\/([^/]+)(\/page\/.+)$/.exec(path)
341
+ if (page != null) {
342
+ const direct = await toPageProcess(req, decodeURIComponent(page[1]!), page[2]!, srv)
343
+ if (direct != null) return direct
344
+ }
242
345
  if (proxied(path)) return proxy(req, url, srv)
243
346
  if (pages.has(path) || path.startsWith('/_bun/')) return toPage(req, url)
244
347
  const bare = /^\/r\/([^/]+)$/.exec(path)
@@ -1,35 +1,44 @@
1
1
  // the commit-message predicate of the commit-msg hook, which blocks at write
2
2
  // time. mechanical text rules only, so this stays publishable.
3
+ //
4
+ // an inline " - " in a commit body is math or a key name ((1 - s), "+ and -")
5
+ // far more often than a separator, so a body blocks only the em dash (the
6
+ // tell) and an en dash outside a number range, and the subject " - " too.
7
+ // an accented proper noun is a name, not a language choice, so French needs
8
+ // two signals on one line.
3
9
 
4
10
  export type OffenseKind = 'dash' | 'language'
5
11
  export type Offense = { line: number; text: string; kind: OffenseKind; why: string }
6
12
 
7
- /** git surfaces are English, always (identity/writing-voice.md). cheap French
8
- * detector: an accented letter, or two distinct French function words on one
9
- * line. quoted spans are exempt: they carry product copy under discussion
10
- * ("Modification refusée"), not the message's own voice. single quotes stay
11
- * in (they are French apostrophes: stripping l'écran would hide the French).
12
- * `languageAllow` (repo.config hooks) exempts listed words, for proper nouns
13
- * that carry accents without being a language choice. */
13
+ /** quoted spans carry product copy or code under discussion ("Modification
14
+ * refusée", `a - b`), not the message's own voice. single quotes stay in
15
+ * (they are French apostrophes: stripping l'écran would hide the French). */
14
16
  const QUOTED_SPANS = /`[^`\n]*`|"[^"\n]*"|“[^”\n]*”|«[^»\n]*»/g
15
- const FRENCH_ACCENTS = /[àâçéèêëîïôùûœÀÂÇÉÈÊËÎÏÔÙÛŒ]/
17
+ const EM_DASH = /—/
18
+ /** an en dash between digits is a range (⌥1–6, 2026–2027), not punctuation */
19
+ const EN_DASH_PUNCT = /(?<!\d\s?)–|–(?!\s?\d)/
20
+ const ACCENTED_WORDS = /[\p{L}'’]*[àâçéèêëîïôùûœÀÂÇÉÈÊËÎÏÔÙÛŒ][\p{L}'’]*/gu
21
+ // unicode boundaries: with \b an accent is a boundary, so Hélène would hide "ne"
16
22
  const FRENCH_STOPWORDS =
17
- /\b(?:le|la|les|un|une|des|du|au|aux|et|est|sont|avec|pour|dans|sur|pas|que|qui|ne|se|ce|cette|ces|chaque|tout|toute|tous|toutes|jamais|toujours|mais|donc|sans|sous|vers|chez|depuis|encore|aussi|devient|deviennent|nouvelle|ancienne)\b/gi
23
+ /(?<!\p{L})(?:le|la|les|un|une|des|du|au|aux|et|est|sont|avec|pour|dans|sur|pas|que|qui|ne|se|ce|cette|ces|chaque|tout|toute|tous|toutes|jamais|toujours|mais|donc|sans|sous|vers|chez|depuis|encore|aussi|devient|deviennent|nouvelle|ancienne)(?!\p{L})/giu
18
24
 
19
25
  const escapeRe = (s: string): string => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
20
26
 
27
+ /** French = two distinct signals on one line: French function words and
28
+ * accented words. one accented name (Zoé, Hélène) or one stray "et" is not a
29
+ * language. `languageAllow` (repo.config hooks) drops listed words first. */
21
30
  export function frenchHits(line: string, languageAllow: string[] = []): boolean {
22
31
  let prose = line.replace(QUOTED_SPANS, ' ')
23
32
  for (const word of languageAllow) prose = prose.replace(new RegExp(`(?:^|(?<=[^\\p{L}]))${escapeRe(word)}(?:'s)?(?=$|[^\\p{L}])`, 'giu'), ' ')
24
- if (FRENCH_ACCENTS.test(prose)) return true
25
- const words = new Set<string>()
33
+ const signals = new Set<string>()
34
+ for (const m of prose.matchAll(ACCENTED_WORDS)) signals.add(m[0].toLowerCase().replace(/['’]s$/, ''))
26
35
  // an ALL-CAPS token is an acronym (UN, EST, CE), not a French word
27
36
  for (const m of prose.matchAll(FRENCH_STOPWORDS)) {
28
37
  const w = m[0]
29
38
  if (w.length > 1 && w === w.toUpperCase()) continue
30
- words.add(w.toLowerCase())
39
+ signals.add(w.toLowerCase())
31
40
  }
32
- return words.size >= 2
41
+ return signals.size >= 2
33
42
  }
34
43
 
35
44
  /** everything below git's scissors line is the verbose-mode diff, which git
@@ -41,18 +50,18 @@ export function stripNonMessage(message: string): string {
41
50
 
42
51
  /** offenses in ONE commit message (or one commit body from `git log`).
43
52
  * `#` comment lines never land in the message and are ignored; a `Revert "…"`
44
- * title quotes the reverted subject verbatim and is exempt; a line-start
45
- * `- ` bullet is a list marker, not punctuation. */
53
+ * title quotes the reverted subject verbatim and is exempt. */
46
54
  export function commitMessageOffenses(message: string, opts?: { languageAllow?: string[] }): Offense[] {
47
55
  const offenses: Offense[] = []
48
56
  stripNonMessage(message).split('\n').forEach((raw, i) => {
49
57
  if (raw.startsWith('#')) return
50
58
  if (i === 0 && /^Revert "/.test(raw)) return
51
- if (/[—–]/.test(raw))
59
+ const prose = raw.replace(QUOTED_SPANS, ' ')
60
+ if (EM_DASH.test(prose) || EN_DASH_PUNCT.test(prose))
52
61
  offenses.push({ line: i + 1, text: raw, kind: 'dash', why: 'em/en dash: use a comma, a period, parentheses, or a new sentence' })
53
- const body = raw.replace(/^\s*[-*] /, '')
54
- if (body.includes(' - '))
55
- offenses.push({ line: i + 1, text: raw, kind: 'dash', why: 'inline " - " separator: same fix' })
62
+ // the subject is a title, where " - " is a separator and never math
63
+ else if (i === 0 && prose.includes(' - '))
64
+ offenses.push({ line: i + 1, text: raw, kind: 'dash', why: 'inline " - " separator in the subject: use a comma or a colon' })
56
65
  if (frenchHits(raw, opts?.languageAllow))
57
66
  offenses.push({ line: i + 1, text: raw, kind: 'language', why: 'French: git surfaces are English, always (identity/writing-voice.md); quote product copy in "…" or `…` to exempt it' })
58
67
  })
@@ -84,6 +84,10 @@ const escapeRegex = (s: string): string => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$
84
84
  * or `desk-lamp-...` is a word that ends in `sk`, never a key */
85
85
  export const SK_KEY_ROW = 're:(?<![A-Za-z0-9_-])sk-[A-Za-z0-9_-]{20,}'
86
86
 
87
+ /** the generic secret shapes: a private key, an AWS key id, an sk- key, a GitHub token, a Slack token. The starter of
88
+ * every keyword file, and the rows the backup refuses a file on (media-store/backup/secret.ts) */
89
+ export const SECRET_ROWS: readonly string[] = ['re:-----BEGIN [A-Z ]*PRIVATE KEY-----', 're:AKIA[0-9A-Z]{16}', SK_KEY_ROW, 're:ghp_[A-Za-z0-9]{36}', 're:xox[baprs]-[A-Za-z0-9-]{10,}']
90
+
87
91
  /** rows the hooks seeded before their shape was fixed, read as the fixed
88
92
  * shape. Their id stays the seeded row, so a waiver written against its
89
93
  * fingerprint keeps working */
@@ -132,15 +136,18 @@ const substringRegex = (s: string): RegExp => {
132
136
  }
133
137
 
134
138
  /** every occurrence of every pattern, keyed by the id a hit reports. */
135
- function occurrences(haystack: string, p: ParsedPatterns): Map<string, Span[]> {
139
+ export function occurrences(haystack: string, p: ParsedPatterns): Map<string, Span[]> {
136
140
  const found = new Map<string, Span[]>()
137
141
  const push = (id: string, span: Span): void => {
138
142
  const prev = found.get(id)
139
143
  if (prev == null) found.set(id, [span])
140
144
  else prev.push(span)
141
145
  }
142
- for (const s of p.substrings) for (const m of haystack.matchAll(substringRegex(s))) push(s, [m.index, m.index + m[0].length])
143
- for (const w of p.words) for (const m of haystack.matchAll(w.re)) push(w.word, [m.index, m.index + m[0].length])
146
+ // a cheap prefilter before each regex: a row whose lowercase text the lowercased haystack lacks cannot match, so a
147
+ // scan over a whole tarball pays one regex per row that is there, not one per row
148
+ const lower = haystack.toLowerCase()
149
+ for (const s of p.substrings) if (lower.includes(s)) for (const m of haystack.matchAll(substringRegex(s))) push(s, [m.index, m.index + m[0].length])
150
+ for (const w of p.words) if (lower.includes(w.word)) for (const m of haystack.matchAll(w.re)) push(w.word, [m.index, m.index + m[0].length])
144
151
  for (const r of p.regexes) {
145
152
  const g = new RegExp(r.re.source, r.re.flags.includes('g') ? r.re.flags : r.re.flags + 'g')
146
153
  for (const m of haystack.matchAll(g)) push(r.row, [m.index, m.index + m[0].length])
@@ -8,7 +8,7 @@ import { dirname, join, relative } from 'path'
8
8
  import { fileURLToPath } from 'url'
9
9
  import { KEYWORD_FILE, LAYOUT } from '../core/layout.ts'
10
10
  import { commitMessageOffenses } from './commit-message.ts'
11
- import { globalAllowFile, globalKeywordFile, maskPattern, patternFingerprint, runLeakGuard, SK_KEY_ROW, type LeakAllowEntry, type LeakHit, type LeakWaiver } from './leak-guard.ts'
11
+ import { globalAllowFile, globalKeywordFile, maskPattern, patternFingerprint, runLeakGuard, SECRET_ROWS, type LeakAllowEntry, type LeakHit, type LeakWaiver } from './leak-guard.ts'
12
12
  import { runRootIdentity } from './root-identity.ts'
13
13
  import { readStaged } from './staged.ts'
14
14
  import { ALLOW_MASS_DELETE, runTreeShrink } from './tree-shrink.ts'
@@ -161,11 +161,7 @@ export const KEYWORD_STARTER = `# banned-keywords — the leak guard greps every
161
161
  # re:<regex>. add repo-specific names here; machine-wide private names go in
162
162
  # ~/.shipkit/private/banned-keywords.txt, read automatically alongside this file.
163
163
  # this file is gitignored on purpose: the list itself is private.
164
- re:-----BEGIN [A-Z ]*PRIVATE KEY-----
165
- re:AKIA[0-9A-Z]{16}
166
- ${SK_KEY_ROW}
167
- re:ghp_[A-Za-z0-9]{36}
168
- re:xox[baprs]-[A-Za-z0-9-]{10,}
164
+ ${SECRET_ROWS.join('\n')}
169
165
  `
170
166
 
171
167
  /** seed the configured keyword file with the generic starter so the guard is
@@ -0,0 +1,334 @@
1
+ // the identities, who speaks (wiki build/shipkit/social.md, Identities): one folder an identity in the house repo,
2
+ // `.shipkit/identities/<id>/`, its profile, brand, accounts and their places, and a company's legal rows. Read from
3
+ // the disk as it is on every call; the one constraint: never in the npm package, a project names its identity
4
+ import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs'
5
+ import { homedir } from 'node:os'
6
+ import { isAbsolute, join } from 'node:path'
7
+ import { LAYOUT } from '../core/layout.ts'
8
+ import { parseFrontmatter, rows, section, table, type ProfileRow } from '../social/md.ts'
9
+
10
+ const SLUG = /^[a-z0-9-]+$/
11
+
12
+ /** the place `me` is the account's own profile, never a file */
13
+ export const ME = 'me'
14
+
15
+ export type Place = {
16
+ id: string
17
+ name: string
18
+ order: number
19
+ kind: string
20
+ url: string
21
+ write: string
22
+ /** the day or the thread it is for */
23
+ when: string
24
+ /** the label a post there must carry */
25
+ flair: string
26
+ /** absolute */
27
+ file: string
28
+ rules: string
29
+ notes: string
30
+ }
31
+
32
+ /** a `## Setup` step: one bullet of the checklist */
33
+ export type Step = { text: string; done: boolean }
34
+
35
+ export type Account = {
36
+ id: string
37
+ /** the identity it belongs to */
38
+ identity: string
39
+ name: string
40
+ order: number
41
+ handle: string
42
+ profile: string
43
+ /** the profile URL he pasted: the account exists; empty, it is still to create */
44
+ live: string
45
+ write: string
46
+ inbox: string
47
+ stats: string
48
+ max: number | null
49
+ /** the field a message's text goes in: description, comment; empty, the post's own text */
50
+ text: string
51
+ /** the word the accounts that take the same messages share, or empty */
52
+ group: string
53
+ /** where a group's message lands on it, a place id; empty, its own profile */
54
+ place: string
55
+ /** its line's label in the vertical's footer of links; empty, not in it */
56
+ footer: string
57
+ /** live, free, paid, limited or none */
58
+ automation: string
59
+ /** with `automation: live`, the secret name of its token, read through the house's `credsReadCommand` */
60
+ secret: string
61
+ /** Discord: the server's id, its messages' links and the bot's posts */
62
+ guild: string
63
+ /** absolute */
64
+ file: string
65
+ dir: string
66
+ /** the identity's rows with the account's own over them */
67
+ rows: ProfileRow[]
68
+ automationText: string
69
+ steps: Step[]
70
+ notes: string
71
+ places: Place[]
72
+ }
73
+
74
+ export type Picture = { file: string; w: number | null; h: number | null }
75
+
76
+ /** a company as the forms ask it: `legal.md`, and the private rows of the gitignored `legal.local.md` */
77
+ export type Legal = {
78
+ rows: (ProfileRow & { private: boolean })[]
79
+ platforms: { platform: string; payout: string; tax: string }[]
80
+ open: string
81
+ }
82
+
83
+ export type Identity = {
84
+ id: string
85
+ name: string
86
+ order: number
87
+ /** it speaks for a repo that names none */
88
+ default: boolean
89
+ site: string
90
+ siteRepo: string
91
+ /** the folder its picture paths are relative to, absolute: its `files`, else its own folder */
92
+ files: string | null
93
+ dir: string
94
+ /** `identity.md`, absolute */
95
+ file: string
96
+ rows: ProfileRow[]
97
+ brand: ProfileRow[]
98
+ pictures: Picture[]
99
+ legal: Legal | null
100
+ accounts: Account[]
101
+ }
102
+
103
+ export type Identities = { dir: string | null; identities: Identity[]; errors: string[] }
104
+
105
+ const read = (abs: string): string => readFileSync(abs, 'utf8')
106
+ const home = (p: string): string => (p.startsWith('~/') ? join(homedir(), p.slice(2)) : p)
107
+
108
+ /** the folder of every identity: `SHIPKIT_IDENTITIES_DIR`, else the house repo's; null when this machine has no house */
109
+ export async function identitiesDir(cwd = process.cwd()): Promise<string | null> {
110
+ const env = process.env['SHIPKIT_IDENTITIES_DIR']
111
+ if (env) return env
112
+ const { houseRootOf } = await import('../home/home-start.ts')
113
+ const house = houseRootOf(cwd)
114
+ return house == null ? null : join(house, LAYOUT.identities)
115
+ }
116
+
117
+ /** the words a `write` link fills from a message (`fillLink`) */
118
+ const FILLED = ['text', 'url', 'title']
119
+
120
+ /** a page that is set and no https address, a `write` that fills a word no message gives: one error line each */
121
+ function linkErrors(file: string, meta: Record<string, string>, keys: readonly string[], errors: string[]): void {
122
+ for (const k of keys) {
123
+ const v = meta[k] ?? ''
124
+ if (v === '' || (k === 'write' && v === '{url}')) continue
125
+ if (!/^https:\/\/\S+$/.test(v)) errors.push(`${file}: ${k} "${v}" is no https address`)
126
+ else if (k === 'write')
127
+ for (const [, w] of v.matchAll(/\{([^}]*)\}/g))
128
+ if (!FILLED.includes(w!)) errors.push(`${file}: write "${v}" fills {${w}}, never one of ${FILLED.map((f) => `{${f}}`).join(', ')}`)
129
+ }
130
+ }
131
+
132
+ function merged(shared: ProfileRow[], own: ProfileRow[]): ProfileRow[] {
133
+ const mine = new Map(own.map((r) => [r.field, r]))
134
+ return [...shared.map((r) => mine.get(r.field) ?? r), ...own.filter((r) => !shared.some((s) => s.field === r.field))]
135
+ }
136
+
137
+ function places(dir: string, errors: string[]): Place[] {
138
+ const at = join(dir, 'places')
139
+ if (!existsSync(at)) return []
140
+ const out: Place[] = []
141
+ for (const f of readdirSync(at).sort()) {
142
+ if (!f.endsWith('.md')) continue
143
+ const id = f.slice(0, -3)
144
+ const abs = join(at, f)
145
+ if (!SLUG.test(id) || id === ME) {
146
+ errors.push(`${abs}: name must be <place>.md, kebab case, never ${ME}`)
147
+ continue
148
+ }
149
+ const { meta, body } = parseFrontmatter(read(abs))
150
+ linkErrors(abs, meta, ['url', 'write'], errors)
151
+ out.push({
152
+ id,
153
+ name: meta.name ?? id,
154
+ order: Number(meta.order ?? 99),
155
+ kind: meta.kind ?? '',
156
+ url: meta.url ?? '',
157
+ write: meta.write ?? '',
158
+ when: meta.when ?? '',
159
+ flair: meta.flair ?? '',
160
+ file: abs,
161
+ rules: section(body, 'Rules') ?? '',
162
+ notes: section(body, 'Notes') ?? '',
163
+ })
164
+ }
165
+ return out.sort((a, b) => a.order - b.order || a.id.localeCompare(b.id))
166
+ }
167
+
168
+ export const STEP = /^- (?:\[( |x)\] )?(.*)$/
169
+
170
+ /** the bullets of `## Setup`, an indented line joining the step above it */
171
+ function steps(body: string): Step[] {
172
+ const out: Step[] = []
173
+ for (const line of (section(body, 'Setup') ?? '').split('\n')) {
174
+ const m = STEP.exec(line)
175
+ if (m) out.push({ text: m[2]!, done: m[1] === 'x' })
176
+ else if (line.trim() !== '' && out.length > 0) out[out.length - 1]!.text += ` ${line.trim()}`
177
+ }
178
+ return out
179
+ }
180
+
181
+ /** a png's or a jpg's size from its header (a jpg's first frame marker); null for any other file */
182
+ function imageSize(abs: string): { w: number | null; h: number | null } {
183
+ try {
184
+ if (abs.endsWith('.png')) {
185
+ const b = readFileSync(abs).subarray(16, 24)
186
+ return { w: b.readUInt32BE(0), h: b.readUInt32BE(4) }
187
+ }
188
+ if (!abs.endsWith('.jpg')) return { w: null, h: null }
189
+ const b = readFileSync(abs)
190
+ for (let i = 2; i + 9 < b.length; i += 2 + b.readUInt16BE(i + 2)) {
191
+ const m = b[i + 1] ?? 0
192
+ if (b[i] !== 0xff) break
193
+ // SOF0 to SOF15, past DHT (c4), JPG (c8) and DAC (cc)
194
+ if (m >= 0xc0 && m <= 0xcf && m !== 0xc4 && m !== 0xc8 && m !== 0xcc) return { w: b.readUInt16BE(i + 7), h: b.readUInt16BE(i + 5) }
195
+ }
196
+ } catch {
197
+ // an unreadable picture shows with no size
198
+ }
199
+ return { w: null, h: null }
200
+ }
201
+
202
+ /** the pictures of each `pictures` folder, each folder the largest first: a folder under `files`, or a `~/…` or
203
+ * absolute one elsewhere on the disk (a repo's own files the identity names), its pictures named by that path */
204
+ function pictures(files: string | null, dirs: string, file: string, errors: string[]): Picture[] {
205
+ if (files == null) return []
206
+ const out: Picture[] = []
207
+ for (const dir of dirs.split(',').map((d) => d.trim()).filter(Boolean)) {
208
+ const abs = dir.startsWith('~/') || isAbsolute(dir) ? home(dir) : join(files, dir)
209
+ if (!existsSync(abs)) {
210
+ errors.push(`${file}: pictures "${dir}" is no folder on this disk`)
211
+ continue
212
+ }
213
+ const here: Picture[] = []
214
+ for (const f of readdirSync(abs).sort()) if (/\.(png|jpg|webp|mp4)$/.test(f)) here.push({ file: `${dir}/${f}`, ...imageSize(join(abs, f)) })
215
+ out.push(...here.sort((x, y) => (y.w ?? 0) * (y.h ?? 0) - (x.w ?? 0) * (x.h ?? 0)))
216
+ }
217
+ return out
218
+ }
219
+
220
+ function legal(dir: string, files: string | null): Legal | null {
221
+ const at = (f: string): string | null => (existsSync(join(dir, f)) ? parseFrontmatter(read(join(dir, f))).body : null)
222
+ const pub = at('legal.md')
223
+ if (pub == null) return null
224
+ return {
225
+ rows: [...rows(pub, 'Legal', files).map((r) => ({ ...r, private: false })), ...rows(at('legal.local.md') ?? '', 'Legal', files).map((r) => ({ ...r, private: true }))],
226
+ platforms: table(pub, 'Platforms').map(([platform = '', payout = '', tax = '']) => ({ platform, payout, tax })),
227
+ open: section(pub, 'Open') ?? '',
228
+ }
229
+ }
230
+
231
+ function account(identity: string, id: string, dir: string, shared: ProfileRow[], files: string | null, errors: string[]): Account {
232
+ const file = join(dir, 'account.md')
233
+ const { meta, body } = parseFrontmatter(read(file))
234
+ linkErrors(file, meta, ['profile', 'live', 'write', 'inbox', 'stats'], errors)
235
+ return {
236
+ id,
237
+ identity,
238
+ name: meta.name ?? id,
239
+ order: Number(meta.order ?? 99),
240
+ handle: meta.handle ?? '',
241
+ profile: meta.profile ?? '',
242
+ live: meta.live ?? '',
243
+ write: meta.write ?? '',
244
+ inbox: meta.inbox ?? '',
245
+ stats: meta.stats ?? '',
246
+ max: meta.max ? Number(meta.max) : null,
247
+ text: meta.text ?? '',
248
+ group: meta.group ?? '',
249
+ place: meta.place ?? '',
250
+ footer: meta.footer ?? '',
251
+ automation: meta.automation ?? 'none',
252
+ secret: meta.secret ?? '',
253
+ guild: meta.guild ?? '',
254
+ file,
255
+ dir,
256
+ rows: merged(shared, rows(body, 'Profile', files)),
257
+ automationText: section(body, 'Automation') ?? '',
258
+ steps: steps(body),
259
+ notes: section(body, 'Notes') ?? '',
260
+ places: places(dir, errors),
261
+ }
262
+ }
263
+
264
+ function identity(id: string, dir: string, errors: string[]): Identity {
265
+ const file = join(dir, 'identity.md')
266
+ const { meta, body } = parseFrontmatter(read(file))
267
+ const files = meta.files ? home(meta.files) : dir
268
+ if (!isAbsolute(files) || !existsSync(files)) errors.push(`${file}: files "${meta.files}" is no folder on this disk`)
269
+ const shared = rows(body, 'Profile', files)
270
+ const at = join(dir, 'accounts')
271
+ const accounts: Account[] = []
272
+ if (existsSync(at))
273
+ for (const a of readdirSync(at).sort()) {
274
+ const adir = join(at, a)
275
+ if (!statSync(adir).isDirectory()) continue
276
+ if (!SLUG.test(a)) errors.push(`${adir}: an account folder is kebab case`)
277
+ else if (!existsSync(join(adir, 'account.md'))) errors.push(`${adir}: no account.md`)
278
+ else accounts.push(account(id, a, adir, shared, files, errors))
279
+ }
280
+ accounts.sort((a, b) => a.order - b.order || a.id.localeCompare(b.id))
281
+ for (const a of accounts) if (a.automation === 'live' && a.secret === '') errors.push(`${a.file}: automation live names no secret (its token name)`)
282
+ return {
283
+ id,
284
+ name: meta.name ?? id,
285
+ order: Number(meta.order ?? 99),
286
+ default: meta.default === 'true',
287
+ site: meta.site ?? '',
288
+ siteRepo: meta.siteRepo ?? '',
289
+ files,
290
+ dir,
291
+ file,
292
+ rows: shared,
293
+ brand: rows(body, 'Brand', files),
294
+ pictures: pictures(files, meta.pictures ?? '', file, errors),
295
+ legal: legal(dir, files),
296
+ accounts,
297
+ }
298
+ }
299
+
300
+ /** every identity in its order; a broken folder is an error line, never a silence */
301
+ export function readIdentities(dir: string | null): Identities {
302
+ const errors: string[] = []
303
+ if (dir == null) return { dir, identities: [], errors: ['no house repo on this machine: the identities live in its .shipkit/identities/'] }
304
+ if (!existsSync(dir)) return { dir, identities: [], errors: [`${dir}: no identities folder`] }
305
+ const out: Identity[] = []
306
+ for (const id of readdirSync(dir).sort()) {
307
+ const idir = join(dir, id)
308
+ if (!statSync(idir).isDirectory()) continue
309
+ if (!SLUG.test(id)) errors.push(`${idir}: an identity id is kebab case`)
310
+ else if (!existsSync(join(idir, 'identity.md'))) errors.push(`${idir}: no identity.md`)
311
+ else out.push(identity(id, idir, errors))
312
+ }
313
+ out.sort((a, b) => a.order - b.order || a.id.localeCompare(b.id))
314
+ const defaults = out.filter((i) => i.default)
315
+ if (out.length > 0 && defaults.length !== 1) errors.push(`${dir}: ${defaults.length === 0 ? 'no identity is' : `${defaults.map((i) => i.id).join(' and ')} are each`} marked default: true; one speaks for a repo that names none`)
316
+ return { dir, identities: out, errors }
317
+ }
318
+
319
+ export async function loadIdentities(o: { dir?: string | null; cwd?: string } = {}): Promise<Identities> {
320
+ return readIdentities(o.dir !== undefined ? o.dir : await identitiesDir(o.cwd))
321
+ }
322
+
323
+ /** the identity a repo speaks as: its `speaksAs`, else the default one; null with no identity at all */
324
+ export function speakerOf(speaksAs: string | undefined, ids: Identities): Identity | null {
325
+ if (speaksAs != null) return ids.identities.find((i) => i.id === speaksAs) ?? null
326
+ return ids.identities.find((i) => i.default) ?? ids.identities[0] ?? null
327
+ }
328
+
329
+ /** one identity by id, or a loud error naming the ones there are */
330
+ export function identityOf(id: string, ids: Identities): Identity {
331
+ const i = ids.identities.find((x) => x.id === id)
332
+ if (i == null) throw new Error(`no identity "${id}" (${ids.identities.map((x) => x.id).join(', ') || 'none'}) in ${ids.dir ?? 'no house repo'}`)
333
+ return i
334
+ }