rvlib-shipkit 2.12.0 → 2.14.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 (378) hide show
  1. package/CHANGELOG.md +75 -21
  2. package/README.md +1 -1
  3. package/package.json +4 -2
  4. package/src/agent-time/store.ts +2 -2
  5. package/src/assets/run-assets.ts +2 -2
  6. package/src/assets/server/studio-server.ts +27 -23
  7. package/src/check.ts +4 -4
  8. package/src/checks/SK001-package-json-shape.check.ts +8 -4
  9. package/src/checks/SK002-contracts-fulfillness.check.ts +2 -2
  10. package/src/checks/SK003-claude-md-shape.check.ts +20 -13
  11. package/src/checks/SK004-gitignore-policy.check.ts +45 -6
  12. package/src/checks/SK005-rvlib-versions.check.ts +2 -2
  13. package/src/checks/SK006-npm-publish-safety.check.ts +3 -3
  14. package/src/checks/SK007-github-visibility.check.ts +2 -2
  15. package/src/checks/SK008-reviewer-agent.check.ts +3 -3
  16. package/src/checks/SK010-undeclared-unit.check.ts +2 -2
  17. package/src/checks/SK011-sibling-unit-ranges.check.ts +2 -2
  18. package/src/checks/SK012-config-barrel-import.check.ts +2 -2
  19. package/src/checks/SK013-one-way-in-policy.check.ts +2 -2
  20. package/src/checks/SK015-nested-repo.check.ts +3 -3
  21. package/src/checks/SK016-legacy-check-shapes.check.ts +2 -2
  22. package/src/checks/SK017-vscode-hub-task.check.ts +2 -2
  23. package/src/checks/SK018-test-files-run.check.ts +2 -2
  24. package/src/checks/SK019-tests-run-in-units.check.ts +2 -2
  25. package/src/checks/SK020-self-spawning-check.check.ts +2 -2
  26. package/src/checks/SK022-machine-runs-the-pin.check.ts +2 -2
  27. package/src/checks/SK024-identity-colors.check.ts +1 -1
  28. package/src/checks/SK025-release-drift.check.ts +2 -2
  29. package/src/checks/SK026-asks-autoclose.check.ts +2 -2
  30. package/src/checks/SK027-agent-wiki-links.check.ts +8 -2
  31. package/src/checks/SK028-readme.check.ts +2 -2
  32. package/src/checks/SK029-explicit-check-files.check.ts +3 -3
  33. package/src/checks/SK030-cache-audit.check.ts +7 -5
  34. package/src/checks/SK031-trace-audit.check.ts +7 -7
  35. package/src/checks/SK032-ignored-inputs.check.ts +3 -3
  36. package/src/checks/SK033-global-contribution.check.ts +11 -4
  37. package/src/checks/SK034-commit-gates-armed.check.ts +2 -2
  38. package/src/checks/SK035-public-clean.check.ts +46 -0
  39. package/src/checks/SK036-draft-media-size.check.ts +28 -0
  40. package/src/checks/SK037-keyword-additions.check.ts +43 -0
  41. package/src/cli/cmd_Backup.ts +152 -0
  42. package/src/cli/cmd_Ci.ts +8 -11
  43. package/src/cli/cmd_Commands.ts +4 -4
  44. package/src/cli/cmd_ConfigKeys.ts +2 -2
  45. package/src/cli/cmd_Drill.ts +145 -0
  46. package/src/cli/cmd_Home.ts +50 -3
  47. package/src/cli/cmd_Init.ts +1 -1
  48. package/src/cli/cmd_Media.ts +10 -8
  49. package/src/cli/cmd_Mv.ts +14 -7
  50. package/src/cli/cmd_Review.ts +6 -4
  51. package/src/cli/cmd_Shot.ts +5 -2
  52. package/src/cli/cmd_Smoke.ts +5 -2
  53. package/src/cli/cmd_Social.ts +226 -0
  54. package/src/cli/cmd_Sound.ts +1 -1
  55. package/src/cli/cmd_Start.ts +1 -1
  56. package/src/cli/cmd_Time.ts +1 -1
  57. package/src/cli/cmd_TraceAudit.ts +6 -6
  58. package/src/cli/cmd_Trailer.ts +7 -4
  59. package/src/cli/cmd_Veille.ts +173 -0
  60. package/src/cli/cmd_When.ts +2 -2
  61. package/src/cli/family-pages.ts +19 -16
  62. package/src/cli/registry.ts +13 -2
  63. package/src/cli.ts +5 -2
  64. package/src/collections/actions.ts +1 -49
  65. package/src/collections/checks.ts +2 -1
  66. package/src/collections/collection-types.ts +12 -3
  67. package/src/collections/providers.ts +4 -4
  68. package/src/collections/review.ts +3 -2
  69. package/src/collections/tests.ts +19 -8
  70. package/src/comfy/comfy-panel.ts +2 -2
  71. package/src/contracts/apply-contracts.ts +1 -3
  72. package/src/contracts/contract-manifests.ts +2 -3
  73. package/src/contracts/contract-types.ts +0 -1
  74. package/src/contracts/contracts-engine.ts +0 -3
  75. package/src/contracts/manifests/discord.contract.ts +1 -1
  76. package/src/contracts/manifests/identity.contract.ts +1 -1
  77. package/src/contracts/manifests/itch.contract.ts +1 -1
  78. package/src/contracts/manifests/steam.contract.ts +1 -1
  79. package/src/core/agent-dir-at.ts +12 -0
  80. package/src/core/agent-dir.ts +16 -0
  81. package/src/core/app-icon.ts +9 -3
  82. package/src/core/budget.ts +1 -1
  83. package/src/core/bun-builtins.ts +2 -2
  84. package/src/core/canonical-scripts.ts +2 -2
  85. package/src/core/discover-checks.ts +38 -6
  86. package/src/core/fix-scope.ts +4 -2
  87. package/src/core/floor-resolve.ts +68 -48
  88. package/src/core/floor.ts +9 -0
  89. package/src/core/git-root.ts +24 -0
  90. package/src/core/global-contribution.ts +4 -1
  91. package/src/core/ignored-block.ts +1 -1
  92. package/src/core/ignored-inputs.ts +3 -2
  93. package/src/core/last-good.ts +3 -1
  94. package/src/core/layout.ts +8 -0
  95. package/src/core/log-stamp.ts +36 -0
  96. package/src/core/loop-watch.ts +93 -0
  97. package/src/core/machine-link.ts +134 -0
  98. package/src/core/memory-watch.ts +41 -0
  99. package/src/core/motherhome.ts +2 -2
  100. package/src/core/one-way-in-policy.ts +34 -26
  101. package/src/core/run-ci.ts +9 -11
  102. package/src/core/run-fixers.ts +9 -9
  103. package/src/core/runs-matrix.ts +1 -1
  104. package/src/core/slots.ts +30 -0
  105. package/src/core/trace-audit.ts +50 -9
  106. package/src/core/tree-rev.ts +60 -0
  107. package/src/core/unit-files.ts +42 -0
  108. package/src/drill/render.ts +140 -0
  109. package/src/drill/run.ts +269 -0
  110. package/src/fleet/scan-fleet.ts +6 -5
  111. package/src/home/daemon-jobs.ts +201 -0
  112. package/src/home/global-context.ts +44 -8
  113. package/src/home/gui-app/ShipkitGui.swift +91 -2
  114. package/src/home/home-routes.ts +22 -15
  115. package/src/home/hubs.ts +10 -3
  116. package/src/home/inbox-shape.ts +54 -5
  117. package/src/home/inbox.ts +17 -2
  118. package/src/home/lib-watch.ts +10 -3
  119. package/src/home/machine-stores.ts +15 -29
  120. package/src/home/pm-config.ts +4 -1
  121. package/src/home/pm-inputs.ts +2 -0
  122. package/src/home/resources.ts +7 -2
  123. package/src/home/run-daemon.ts +15 -18
  124. package/src/home/run-pm.ts +3 -1
  125. package/src/home/serve-daemon.ts +4 -3
  126. package/src/home/serve-web.ts +104 -1
  127. package/src/hooks/commit-message.ts +29 -20
  128. package/src/hooks/hook-gates.ts +1 -1
  129. package/src/hooks/leak-guard.ts +69 -9
  130. package/src/hooks/run-hooks.ts +18 -22
  131. package/src/identities/identities.ts +334 -0
  132. package/src/identities/machine-route.ts +126 -0
  133. package/src/identities/machine.ts +62 -0
  134. package/src/init-repo.ts +3 -3
  135. package/src/ledger/check-stats.ts +10 -9
  136. package/src/ledger/gate-checks.ts +32 -1
  137. package/src/ledger/record-kept.ts +112 -0
  138. package/src/ledger/repo-view.ts +10 -0
  139. package/src/ledger/run-log.ts +17 -12
  140. package/src/ledger/run-timeline.ts +8 -4
  141. package/src/ledger/store.ts +7 -0
  142. package/src/ledger/suite-log.ts +17 -13
  143. package/src/media-kinds.ts +3 -2
  144. package/src/media-store/backup/daemon.ts +73 -0
  145. package/src/media-store/backup/keys.ts +25 -0
  146. package/src/media-store/backup/manifest.ts +193 -0
  147. package/src/media-store/backup/restore.ts +192 -0
  148. package/src/media-store/backup/run.ts +278 -0
  149. package/src/media-store/backup/secret.ts +86 -0
  150. package/src/media-store/backup/snapshot.ts +64 -0
  151. package/src/media-store/backup/sources.ts +199 -0
  152. package/src/media-store/content.ts +1 -1
  153. package/src/media-store/daemon.ts +56 -70
  154. package/src/media-store/db.ts +1 -1
  155. package/src/media-store/fact.ts +1 -1
  156. package/src/media-store/hand.ts +1 -1
  157. package/src/media-store/kind.ts +1 -1
  158. package/src/media-store/purge.ts +1 -1
  159. package/src/media-store/put.ts +5 -3
  160. package/src/media-store/remote.ts +1 -1
  161. package/src/media-store/space.ts +24 -5
  162. package/src/mv/mv-md.ts +63 -22
  163. package/src/pages/forward.ts +35 -0
  164. package/src/pages/frame-client.ts +118 -0
  165. package/src/pages/routes.ts +29 -0
  166. package/src/pages/unit.ts +92 -0
  167. package/src/plan/planner.ts +12 -0
  168. package/src/plan/repo-source.ts +19 -5
  169. package/src/reflect/transcript.ts +35 -10
  170. package/src/release/public-clean.ts +319 -0
  171. package/src/release/published-here.ts +22 -0
  172. package/src/release/run-bump.ts +3 -2
  173. package/src/release/run-release.ts +7 -4
  174. package/src/repo-config.ts +71 -13
  175. package/src/review/anim.ts +1 -1
  176. package/src/review/auto.ts +1 -1
  177. package/src/review/cells.ts +15 -1
  178. package/src/review/format.ts +2 -2
  179. package/src/review/http.ts +16 -2
  180. package/src/review/marks.ts +1 -1
  181. package/src/review/media-kind.ts +1 -1
  182. package/src/review/media-read.ts +1 -1
  183. package/src/review/model.ts +27 -6
  184. package/src/review/notes.ts +125 -0
  185. package/src/review/previews.ts +1 -1
  186. package/src/review/project.ts +7 -39
  187. package/src/review/role.ts +1 -1
  188. package/src/review/routes.ts +18 -14
  189. package/src/review/store.ts +42 -2
  190. package/src/review/threads.ts +1 -1
  191. package/src/review/trailer-desk.ts +3 -3
  192. package/src/review/trailer-media.ts +8 -5
  193. package/src/review/trailer-model.ts +1 -1
  194. package/src/review/trailer-routes.ts +1 -1
  195. package/src/review/trailer-shots.ts +22 -5
  196. package/src/review/unit.ts +2 -2
  197. package/src/scaffold/files/agent-handoff.md +3 -0
  198. package/src/scaffold/files/agent-index.md +4 -12
  199. package/src/scaffold/files/tsconfig.json +1 -1
  200. package/src/scaffold/project-scaffold.ts +6 -5
  201. package/src/serve/embed.ts +2 -2
  202. package/src/serve/hub-app/check-words.ts +1 -1
  203. package/src/serve/hub-app/col-card.tsx +3 -17
  204. package/src/serve/hub-app/col-tables-view.tsx +2 -1
  205. package/src/serve/hub-app/cols-svc.ts +0 -13
  206. package/src/serve/hub-app/dock-st.ts +4 -2
  207. package/src/serve/hub-app/dock-view.tsx +2 -0
  208. package/src/serve/hub-app/frames-st.ts +35 -0
  209. package/src/serve/hub-app/hash-route.ts +64 -1
  210. package/src/serve/hub-app/home-st.ts +32 -8
  211. package/src/serve/hub-app/home-strip.css +9 -1
  212. package/src/serve/hub-app/home-strip.tsx +7 -6
  213. package/src/serve/hub-app/home.html +5 -0
  214. package/src/serve/hub-app/hub-app.tsx +51 -7
  215. package/src/serve/hub-app/hub.css +29 -11
  216. package/src/serve/hub-app/icons.tsx +16 -1
  217. package/src/serve/hub-app/identities-st.ts +210 -0
  218. package/src/serve/hub-app/identities-view.tsx +353 -0
  219. package/src/serve/hub-app/identities.css +48 -0
  220. package/src/serve/hub-app/identity-address.ts +52 -0
  221. package/src/serve/hub-app/inbox-st.ts +60 -7
  222. package/src/serve/hub-app/inbox-view.tsx +49 -7
  223. package/src/serve/hub-app/inbox.css +12 -1
  224. package/src/serve/hub-app/index.html +3 -0
  225. package/src/serve/hub-app/kept-cols.tsx +30 -0
  226. package/src/serve/hub-app/keys.ts +10 -2
  227. package/src/serve/hub-app/list-walk.ts +89 -0
  228. package/src/serve/hub-app/machine-st.ts +12 -0
  229. package/src/serve/hub-app/media-svc.ts +1 -1
  230. package/src/serve/hub-app/media-view.tsx +2 -1
  231. package/src/serve/hub-app/pages-frames.tsx +134 -0
  232. package/src/serve/hub-app/pages-svc.ts +111 -0
  233. package/src/serve/hub-app/palette-st.ts +18 -3
  234. package/src/serve/hub-app/palette-view.tsx +9 -2
  235. package/src/serve/hub-app/planned-view.tsx +2 -1
  236. package/src/serve/hub-app/project-list.css +18 -14
  237. package/src/serve/hub-app/project-list.tsx +88 -49
  238. package/src/serve/hub-app/projects-svc.ts +33 -3
  239. package/src/serve/hub-app/repo-sections.ts +19 -2
  240. package/src/serve/hub-app/repo-st.ts +76 -20
  241. package/src/serve/hub-app/review/review-board.tsx +1 -1
  242. package/src/serve/hub-app/review/review-cells.tsx +6 -5
  243. package/src/serve/hub-app/review/review-kit.ts +30 -7
  244. package/src/serve/hub-app/review/review-page.tsx +6 -5
  245. package/src/serve/hub-app/review/review-st.ts +34 -15
  246. package/src/serve/hub-app/review/review-thread.tsx +63 -14
  247. package/src/serve/hub-app/review/review-views.tsx +133 -51
  248. package/src/serve/hub-app/review/thread-st.ts +80 -37
  249. package/src/serve/hub-app/review/trailer-page.tsx +7 -5
  250. package/src/serve/hub-app/review/trailer-st.ts +1 -1
  251. package/src/serve/hub-app/review.css +26 -9
  252. package/src/serve/hub-app/site/site-part.tsx +173 -0
  253. package/src/serve/hub-app/site/site-st.ts +157 -0
  254. package/src/serve/hub-app/site.css +35 -0
  255. package/src/serve/hub-app/social/calendar.tsx +182 -0
  256. package/src/serve/hub-app/social/comms-page.tsx +330 -0
  257. package/src/serve/hub-app/social/kit.tsx +244 -0
  258. package/src/serve/hub-app/social/post-card.tsx +456 -0
  259. package/src/serve/hub-app/social/problems.tsx +60 -0
  260. package/src/serve/hub-app/social/social-model.ts +154 -0
  261. package/src/serve/hub-app/social/social-page.tsx +681 -0
  262. package/src/serve/hub-app/social/social-st.ts +1014 -0
  263. package/src/serve/hub-app/social.css +289 -0
  264. package/src/serve/hub-app/stores/stores-page.tsx +312 -0
  265. package/src/serve/hub-app/stores/stores-st.ts +286 -0
  266. package/src/serve/hub-app/stores.css +54 -0
  267. package/src/serve/hub-app/timeline-geometry.ts +1 -1
  268. package/src/serve/hub-app/timeline-view.tsx +3 -2
  269. package/src/serve/hub-app/tree-build.ts +6 -0
  270. package/src/serve/hub-app/tree-row.tsx +27 -4
  271. package/src/serve/hub-app/tree-svc.ts +18 -49
  272. package/src/serve/hub-app/veille/veille-page.tsx +515 -0
  273. package/src/serve/hub-app/veille/veille-st.ts +443 -0
  274. package/src/serve/hub-app/veille.css +84 -0
  275. package/src/serve/hub-runtime.ts +20 -11
  276. package/src/serve/project-gutter-route.ts +44 -12
  277. package/src/serve/run-lanes.ts +7 -4
  278. package/src/serve/same-origin.ts +1 -1
  279. package/src/serve/serve-hub.ts +20 -12
  280. package/src/serve/tracked-watch.ts +24 -3
  281. package/src/serve/warm-cell.ts +5 -1
  282. package/src/shipkit-files.ts +15 -4
  283. package/src/shipkit.ts +0 -1
  284. package/src/shot/box.ts +160 -0
  285. package/src/shot/browser-slot.ts +74 -0
  286. package/src/shot/client.ts +42 -7
  287. package/src/shot/clip-encoder.ts +108 -24
  288. package/src/shot/film-box.ts +292 -0
  289. package/src/shot/shooter.ts +71 -17
  290. package/src/shot/shot-ask.ts +10 -2
  291. package/src/shot/stepped-clip.ts +5 -4
  292. package/src/site/desk.ts +242 -0
  293. package/src/site/routes.ts +66 -0
  294. package/src/site/unit.ts +62 -0
  295. package/src/social/brands.ts +22 -0
  296. package/src/social/card-drafts.ts +24 -0
  297. package/src/social/compose.ts +97 -0
  298. package/src/social/desk-index.ts +123 -0
  299. package/src/social/desk-wire.ts +64 -0
  300. package/src/social/drafts.ts +183 -0
  301. package/src/social/house.ts +24 -0
  302. package/src/social/load.ts +332 -0
  303. package/src/social/md.ts +70 -0
  304. package/src/social/media-facts.ts +53 -0
  305. package/src/social/media-kind.ts +189 -0
  306. package/src/social/media-limit.ts +42 -0
  307. package/src/social/media-of.ts +30 -0
  308. package/src/social/migrate.ts +123 -0
  309. package/src/social/open.ts +17 -0
  310. package/src/social/post-url.ts +158 -0
  311. package/src/social/presence.ts +332 -0
  312. package/src/social/public-read.ts +53 -0
  313. package/src/social/publish/bluesky.ts +168 -0
  314. package/src/social/publish/discord.ts +76 -0
  315. package/src/social/publish/index.ts +24 -0
  316. package/src/social/publish/secret.ts +13 -0
  317. package/src/social/push.ts +37 -0
  318. package/src/social/richtext.ts +37 -0
  319. package/src/social/routes.ts +186 -0
  320. package/src/social/stats.ts +134 -0
  321. package/src/social/text.ts +267 -0
  322. package/src/social/tracker-route.ts +39 -0
  323. package/src/social/tracker.ts +255 -0
  324. package/src/social/unit.ts +53 -0
  325. package/src/social/writes.ts +130 -0
  326. package/src/start-repo.ts +14 -9
  327. package/src/stores/collection.ts +27 -0
  328. package/src/stores/desk.ts +336 -0
  329. package/src/stores/model.ts +187 -0
  330. package/src/stores/routes.ts +126 -0
  331. package/src/stores/unit.ts +57 -0
  332. package/src/suite/calibrate.ts +127 -0
  333. package/src/suite/core-counters.ts +91 -0
  334. package/src/suite/judge-suites.ts +95 -35
  335. package/src/suite/suite-cli.ts +44 -10
  336. package/src/suite/suite-cpu-preload.ts +34 -9
  337. package/src/trace/tracer.ts +12 -5
  338. package/src/trailer/adapter.ts +5 -1
  339. package/src/trailer/build.ts +45 -12
  340. package/src/trailer/ffmpeg.ts +11 -0
  341. package/src/trailer/footage.ts +30 -13
  342. package/src/trailer/grammar.ts +18 -2
  343. package/src/trailer/graph.ts +28 -6
  344. package/src/trailer/holes.ts +1 -1
  345. package/src/trailer/passage.ts +18 -6
  346. package/src/trailer/plan.ts +74 -3
  347. package/src/trailer/prune.ts +1 -1
  348. package/src/trailer/states.ts +1 -1
  349. package/src/trailer/stitch.ts +67 -26
  350. package/src/trailer/url.ts +1 -1
  351. package/src/trailer/versions.ts +24 -0
  352. package/src/trailer/words.ts +1 -1
  353. package/src/ts/gate-typecheck.ts +32 -0
  354. package/src/ts/typecheck-cli.ts +9 -11
  355. package/src/tui/run-tui.ts +1 -1
  356. package/src/tui/tui-app.tsx +0 -1
  357. package/src/tui/tui-store.ts +1 -1
  358. package/src/veille/asks.ts +155 -0
  359. package/src/veille/auto.ts +31 -0
  360. package/src/veille/batch.ts +27 -0
  361. package/src/veille/chrome.ts +127 -0
  362. package/src/veille/collection.ts +28 -0
  363. package/src/veille/desk.ts +242 -0
  364. package/src/veille/identity.ts +80 -0
  365. package/src/veille/import.ts +68 -0
  366. package/src/veille/log.ts +183 -0
  367. package/src/veille/platforms.ts +118 -0
  368. package/src/veille/reads.ts +66 -0
  369. package/src/veille/replied.ts +110 -0
  370. package/src/veille/routes.ts +185 -0
  371. package/src/veille/service.ts +81 -0
  372. package/src/veille/watch.ts +116 -0
  373. package/src/veille/worth.ts +46 -0
  374. package/src/wiki/scan-md.ts +18 -0
  375. package/src/collections/posts.ts +0 -142
  376. package/src/contracts/manifests/social.contract.ts +0 -20
  377. package/src/scaffold/files/agent-coding.md +0 -35
  378. package/src/ts/typecheck-cache.ts +0 -11
@@ -0,0 +1,332 @@
1
+ // a repo's social folder read with every identity (wiki tools/shipkit/social.md, contract v3): its drafts, one folder a
2
+ // message, each platform's part handed to its speaker's account; the rhythm; the load's errors. Read from the disk as
3
+ // it is on every call: the desks and `sk social` never hold a stale copy
4
+ import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs'
5
+ import { join, relative } from 'node:path'
6
+ import { LAYOUT } from '../core/layout.ts'
7
+ import { speakerOf, type Account, type Identities, type Identity } from '../identities/identities.ts'
8
+ import { fileList, groupKeys, mediaNames, parseDraft, renderedTrailer, resolveMedia, tagList, topicList, type Topic } from './drafts.ts'
9
+ import { compose, fillLink, messageLength } from './compose.ts'
10
+ import { parseFrontmatter, table } from './md.ts'
11
+ import { type Family, familyOf, type Slot, slotOf, type WeeklySlot, weeklySlots } from './presence.ts'
12
+ import { purgedAt } from './media-facts.ts'
13
+ import { heavyMedia, mbOf, MEDIA_MAX_BYTES } from './media-limit.ts'
14
+ import { pushFailure } from './push.ts'
15
+ import type { SocialUnit } from './unit.ts'
16
+
17
+ /** a draft's folder name: the moment it was made, then its topic */
18
+ export const DRAFT_NAME = /^\d{8}-\d{6}-[a-z0-9-]+$/
19
+
20
+ /** the files the social folder holds beside `drafts/` */
21
+ const FOLDER_FILES = new Set(['rhythm.md', 'README.md'])
22
+
23
+ export const draftsDir = (root: string): string => join(root, LAYOUT.social, 'drafts')
24
+
25
+ /** a draft's `review:`, the card it was asked from: a review item id, never checked against the store (gitignored, a
26
+ * fresh clone has none) */
27
+ function reviewOf(raw: string | undefined, file: string, errors: string[]): string | null {
28
+ const v = raw?.trim() ?? ''
29
+ if (v === '') return null
30
+ if (DRAFT_NAME.test(v)) return v
31
+ errors.push(`${file}: review "${v}" is no review card id (YYYYMMDD-HHMMSS-<slug>)`)
32
+ return null
33
+ }
34
+
35
+ /** a media as the draft names it, and where it is on the disk: its folder, the repo, or anywhere */
36
+ export type Media = { name: string; path: string }
37
+
38
+ /** one account's part of a draft: what its card shows and what a publisher sends */
39
+ export type SocialPost = {
40
+ slug: string
41
+ /** the speaker's identity */
42
+ identity: string
43
+ platform: string
44
+ /** the account, or `<account>/<name>` for one of several messages there: its key under `## Posted` */
45
+ key: string
46
+ /** the message's name among several on one account; empty when alone */
47
+ name: string
48
+ /** the draft's file, from the repo's root */
49
+ file: string
50
+ status: string
51
+ /** the URL of its line under `## Posted`; empty, it waits */
52
+ posted: string
53
+ kind: string
54
+ title: string
55
+ angle: string
56
+ text: string
57
+ length: number
58
+ media: Media | null
59
+ alt: string
60
+ /** the place it goes to, a file of places/; empty, the account's own profile */
61
+ place: string
62
+ /** the account's write page, prefilled when it takes {text}; null when it names none */
63
+ href: string | null
64
+ pin: boolean
65
+ /** the key of the heading its text comes from: its own, or its group's (`short`, `short/<name>`) */
66
+ from: string
67
+ /** the links under a vertical message's text, counted and copied with it; empty elsewhere */
68
+ footer: string
69
+ /** the heading's own text, as he writes it; `text` is it composed for the account */
70
+ body: string
71
+ tags: string[]
72
+ /** X's links, out of its text: the first reply under the post; empty elsewhere */
73
+ reply: string
74
+ /** its write page takes the text (`{text}`); else « Open » copies it first */
75
+ prefilled: boolean
76
+ }
77
+
78
+ /** a draft's post.md: a long article of the identity's site */
79
+ export type Article = { title: string; description: string; date: string; draft: boolean; url: string; file: string }
80
+
81
+ export type Draft = {
82
+ slug: string
83
+ /** from the repo's root */
84
+ file: string
85
+ /** absolute */
86
+ path: string
87
+ dir: string
88
+ /** who speaks: its own `speaksAs`, else the repo's */
89
+ identity: string
90
+ title: string
91
+ kind: string
92
+ topics: Topic[]
93
+ slot: Slot | null
94
+ status: string
95
+ angle: string
96
+ media: Media[]
97
+ alt: string
98
+ posts: SocialPost[]
99
+ article: Article | null
100
+ /** the review card it was asked from (« 📣 post »), any id of its thread; null when none */
101
+ review: string | null
102
+ }
103
+
104
+ /** an identity's account with the repo's messages to it */
105
+ export type DeskAccount = Account & { family: Family; posts: SocialPost[] }
106
+ export type DeskIdentity = Omit<Identity, 'accounts'> & { accounts: DeskAccount[] }
107
+
108
+ export type Desk = {
109
+ root: string
110
+ /** the repo's own identity, null when none resolves */
111
+ speaksAs: string | null
112
+ identities: DeskIdentity[]
113
+ drafts: Draft[]
114
+ weekly: WeeklySlot[]
115
+ /** the topics a draft may take: the unit's, else every one the drafts name */
116
+ topics: Topic[]
117
+ errors: string[]
118
+ }
119
+
120
+ const read = (abs: string): string => readFileSync(abs, 'utf8')
121
+
122
+ /** the group whose messages need a compiled 9:16 video */
123
+ export const VERTICAL = 'vertical'
124
+ /** the name of a compiled vertical video */
125
+ export const VERTICAL_FILE = /-vertical\.mp4$/
126
+
127
+ /** what one message breaks on its account: a text past the account's max, a `## vertical` message without its video */
128
+ export function messageErrors(post: Pick<SocialPost, 'file' | 'from' | 'length' | 'media'>, a: Pick<Account, 'name' | 'max'>): string[] {
129
+ const out: string[] = []
130
+ if (a.max !== null && post.length > a.max) out.push(`${post.file}: ## ${post.from} is ${post.length} on ${a.name}, over its ${a.max}`)
131
+ if (post.from.split('/')[0] === VERTICAL && !VERTICAL_FILE.test(post.media?.name ?? ''))
132
+ out.push(`${post.file}: ## ${post.from} goes to ${a.name} without its vertical video (media: media/<name>-vertical.mp4)`)
133
+ return out
134
+ }
135
+
136
+ /** the vertical's footer: each online account with a `footer` label, in their order, `<label>: <profile>` */
137
+ export const footerOf = (accounts: readonly Pick<Account, 'footer' | 'live'>[]): string =>
138
+ accounts
139
+ .filter((a) => a.footer !== '' && a.live !== '')
140
+ .map((a) => `${a.footer}: ${a.live}`)
141
+ .join('\n')
142
+
143
+ function weekly(root: string, errors: string[]): WeeklySlot[] {
144
+ const abs = join(root, LAYOUT.social, 'rhythm.md')
145
+ return existsSync(abs) ? weeklySlots(table(parseFrontmatter(read(abs)).body, 'Slots'), relative(root, abs), errors) : []
146
+ }
147
+
148
+ function article(dir: string, root: string, unit: SocialUnit | null): Article | null {
149
+ const abs = join(dir, 'post.md')
150
+ if (!existsSync(abs)) return null
151
+ const { meta } = parseFrontmatter(read(abs))
152
+ let url = ''
153
+ try {
154
+ url = unit?.article?.(dir).url ?? ''
155
+ } catch {
156
+ url = ''
157
+ }
158
+ return { title: meta.title ?? '', description: meta.description ?? '', date: meta.date ?? '', draft: meta.draft === 'true', url, file: relative(root, abs) }
159
+ }
160
+
161
+ /** the v2 channel files left in the folder: each one an error naming the command that moves it */
162
+ function v2Left(root: string, errors: string[]): void {
163
+ const at = join(root, LAYOUT.social)
164
+ if (!existsSync(at)) return
165
+ for (const e of readdirSync(at)) {
166
+ if (e === 'drafts' || FOLDER_FILES.has(e) || e.startsWith('.')) continue
167
+ const abs = join(at, e)
168
+ if (statSync(abs).isDirectory() && readdirSync(abs).some((f) => f.endsWith('.md'))) errors.push(`${relative(root, abs)}/: a v2 channel folder; sk social migrate makes its posts drafts`)
169
+ else errors.push(`${relative(root, abs)}: the social folder holds drafts/, rhythm.md and README.md only`)
170
+ }
171
+ }
172
+
173
+ /** the desk of a repo: every identity with its accounts, the repo's drafts on them, the newest first */
174
+ export function loadDesk(root: string, ids: Identities, o: { speaksAs?: string | undefined; unit?: SocialUnit | null; now?: Date } = {}): Desk {
175
+ const errors = [...ids.errors]
176
+ const unit = o.unit ?? null
177
+ const own = speakerOf(o.speaksAs, ids)
178
+ if (o.speaksAs != null && own == null) errors.push(`repo.config.ts: speaksAs '${o.speaksAs}' is no identity (${ids.identities.map((i) => i.id).join(', ') || 'none'})`)
179
+ const identities: DeskIdentity[] = ids.identities.map((i) => ({ ...i, accounts: i.accounts.map((a) => ({ ...a, family: familyOf(a), posts: [] })) }))
180
+ const pushed = pushFailure(root)
181
+ if (pushed != null) errors.push(pushed)
182
+ const week = weekly(root, errors)
183
+ v2Left(root, errors)
184
+ const dir = draftsDir(root)
185
+ const drafts: Draft[] = []
186
+ const named = new Set<string>()
187
+ // the Saturday tag joins on the Mac's Saturday
188
+ const saturday = (o.now ?? new Date()).getDay() === 6
189
+ for (const slug of existsSync(dir) ? readdirSync(dir).sort().reverse() : []) {
190
+ if (slug.startsWith('.')) continue
191
+ const ddir = join(dir, slug)
192
+ const abs = join(ddir, 'draft.md')
193
+ const file = relative(root, abs)
194
+ if (!DRAFT_NAME.test(slug) || !statSync(ddir).isDirectory()) {
195
+ errors.push(`${relative(root, ddir)}: a draft is a folder <YYYYMMDD-HHMMSS>-<topic>/ holding draft.md`)
196
+ continue
197
+ }
198
+ if (!existsSync(abs)) {
199
+ errors.push(`${relative(root, ddir)}: no draft.md`)
200
+ continue
201
+ }
202
+ const raw = read(abs)
203
+ const head = parseFrontmatter(raw).meta
204
+ const speaker = head.speaksAs ? ids.identities.find((i) => i.id === head.speaksAs) : own
205
+ if (speaker == null) {
206
+ errors.push(`${file}: ${head.speaksAs ? `speaksAs '${head.speaksAs}' is no identity` : 'no identity speaks for this repo'} (sk identities)`)
207
+ continue
208
+ }
209
+ named.add(speaker.id)
210
+ const accounts = identities.find((i) => i.id === speaker.id)!.accounts
211
+ const groups = new Map([...new Set(accounts.map((a) => a.group).filter((g) => g !== ''))].map((g) => [g, accounts.filter((a) => a.group === g).map((a) => a.id)]))
212
+ const d = parseDraft(raw, file, groups)
213
+ errors.push(...d.errors)
214
+ const media = new Map<string, Media>()
215
+ for (const name of mediaNames(d)) {
216
+ const path = resolveMedia(name, ddir, root) ?? (renderedTrailer(name, raw, relative(root, ddir)) ? join(ddir, name) : null) ?? purgedAt(root, ddir, name)
217
+ if (path == null) errors.push(`${file}: media "${name}" is in neither its folder, the repo, at that path, nor in the Space`)
218
+ else media.set(name, { name, path })
219
+ }
220
+ for (const h of heavyMedia(root, [...media.values()].map((m) => m.path))) errors.push(`${file}: media "${relative(ddir, h.path)}" is ${mbOf(h.size)}, over the ${mbOf(MEDIA_MAX_BYTES)} GitHub takes: shrink it, name it *-trailer.mp4 when its command renders it, or keep it with sk media put`)
221
+ const pick = (list: string | undefined): Media[] => fileList(list).flatMap((n) => media.get(n) ?? [])
222
+ const ownMedia = pick(d.meta.media)
223
+ const draft: Draft = {
224
+ slug,
225
+ file,
226
+ path: abs,
227
+ dir: ddir,
228
+ identity: speaker.id,
229
+ title: d.meta.title ?? '',
230
+ kind: d.meta.kind ?? '',
231
+ topics: topicList(d.meta.topics, file, errors, unit?.topics ?? null),
232
+ slot: slotOf(d.meta.slot, file, week, errors),
233
+ status: d.meta.status ?? 'draft',
234
+ angle: d.angle,
235
+ media: [...media.values()],
236
+ alt: d.meta.alt ?? '',
237
+ posts: [],
238
+ article: article(ddir, root, unit),
239
+ review: reviewOf(d.meta.review, file, errors),
240
+ }
241
+ const footerText = footerOf(accounts)
242
+ // each account heading's message, then a group heading's on every account of the group the draft gives no heading
243
+ const sends: { s: (typeof d.sections)[number]; a: DeskAccount; key: string; from: string }[] = []
244
+ for (const s of d.sections) {
245
+ if (groups.has(s.platform)) continue
246
+ const a = accounts.find((x) => x.id === s.platform)
247
+ if (a == null) {
248
+ errors.push(`${file}: ## ${s.platform} names neither a group nor an account of ${speaker.name}`)
249
+ continue
250
+ }
251
+ sends.push({ s, a, key: s.key, from: s.key })
252
+ }
253
+ for (const s of d.sections)
254
+ for (const key of groupKeys(s, groups)) {
255
+ if (d.sections.some((x) => x.key === key)) continue
256
+ const b = accounts.find((x) => x.id === key.split('/')[0])
257
+ if (b) sends.push({ s, a: b, key, from: s.key })
258
+ }
259
+ for (const { s, a, key, from } of sends) {
260
+ // a place belongs to its account: a group's message lands on the account's own place
261
+ const place = from === key ? (s.options.place ?? '') : a.place
262
+ const footer = from.split('/')[0] === VERTICAL ? footerText : ''
263
+ const tags = tagList(s.options.tags)
264
+ const made = compose(a.id, { text: s.text, tags, footer }, { max: a.max, saturday })
265
+ const at = a.places.find((x) => x.id === place)
266
+ // a Discord place is a channel of the server, checked when the bot posts
267
+ if (place !== '' && at == null && a.id !== 'discord') errors.push(`${file}: ## ${a.id} place "${place}" is no file of ${a.id}/places/`)
268
+ const title = s.options.title ?? ''
269
+ const write = at?.write || a.write
270
+ const post: SocialPost = {
271
+ slug,
272
+ identity: speaker.id,
273
+ platform: a.id,
274
+ key,
275
+ name: s.options.name ?? '',
276
+ file,
277
+ status: draft.status,
278
+ posted: d.posted.get(key) ?? '',
279
+ kind: draft.kind,
280
+ title,
281
+ angle: d.angle,
282
+ text: made.text,
283
+ body: s.text,
284
+ tags,
285
+ reply: made.reply,
286
+ length: messageLength(a.id, made.text),
287
+ media: (s.options.media == null ? ownMedia : pick(s.options.media))[0] ?? null,
288
+ alt: draft.alt,
289
+ place,
290
+ href: write === '' ? null : fillLink(write, { url: '', title, text: made.text }),
291
+ prefilled: write.includes('{text}'),
292
+ pin: s.options.pin === 'true',
293
+ from,
294
+ footer,
295
+ }
296
+ errors.push(...messageErrors(post, a))
297
+ a.posts.push(post)
298
+ draft.posts.push(post)
299
+ }
300
+ draft.posts.sort((x, y) => accounts.findIndex((a) => a.id === x.platform) - accounts.findIndex((a) => a.id === y.platform))
301
+ drafts.push(draft)
302
+ }
303
+ // a step's [[row]] names a profile row; its [[draft:<slug>]] a draft, checked where the repo speaks as the account's
304
+ for (const i of identities)
305
+ for (const a of i.accounts)
306
+ for (const st of a.steps)
307
+ for (const [, ref] of st.text.matchAll(/\[\[([^\]]+)\]\]/g)) {
308
+ const slug = /^draft:(.+)$/.exec(ref!)?.[1]
309
+ if (slug == null) {
310
+ if (!a.rows.some((r) => r.field === ref)) errors.push(`${a.file}: [[${ref}]] names no profile row`)
311
+ } else if (i.id === own?.id && !a.posts.some((x) => x.slug === slug)) errors.push(`${a.file}: [[${ref}]] names no draft with a message to ${a.name} in this repo`)
312
+ }
313
+ const topics = unit?.topics ? [...unit.topics] : [...new Set(drafts.flatMap((d) => d.topics))].sort()
314
+ return { root, speaksAs: own?.id ?? null, identities, drafts, weekly: week, topics, errors }
315
+ }
316
+
317
+ /** one account of an identity, loud when absent */
318
+ export function accountOf(desk: Desk, identity: string, account: string): DeskAccount {
319
+ const i = desk.identities.find((x) => x.id === identity)
320
+ const a = i?.accounts.find((x) => x.id === account)
321
+ if (a == null) throw new Error(i == null ? `no identity "${identity}"` : `no account "${account}" of ${i.name}`)
322
+ return a
323
+ }
324
+
325
+ /** one message of a draft by its key, `<account>` or `<account>/<name>` */
326
+ export function draftPost(desk: Desk, slug: string, key: string): SocialPost {
327
+ const d = desk.drafts.find((x) => x.slug === slug)
328
+ if (d == null) throw new Error(`no draft ${slug} in ${LAYOUT.social}/drafts/`)
329
+ const p = d.posts.find((x) => x.key === key)
330
+ if (p == null) throw new Error(`no message ## ${key} in ${d.file}`)
331
+ return p
332
+ }
@@ -0,0 +1,70 @@
1
+ // the markdown shapes every social file is written in: `key: value` front matter, `## <name>` sections, the
2
+ // `| field | value |` tables of a profile
3
+ import { existsSync } from 'node:fs'
4
+ import { isAbsolute, join } from 'node:path'
5
+
6
+ /** `key: value` lines only, no nesting */
7
+ export function parseFrontmatter(raw: string): { meta: Record<string, string>; body: string } {
8
+ const m = raw.match(/^---\n([\s\S]*?)\n---\n?/)
9
+ if (m == null) return { meta: {}, body: raw }
10
+ const meta: Record<string, string> = {}
11
+ for (const line of m[1]!.split('\n')) {
12
+ const i = line.indexOf(':')
13
+ if (i === -1) continue
14
+ meta[line.slice(0, i).trim()] = line.slice(i + 1).trim()
15
+ }
16
+ return { meta, body: raw.slice(m[0].length) }
17
+ }
18
+
19
+ /** a frontmatter key set in place, added at the end of the block when absent */
20
+ export function setMeta(raw: string, key: string, value: string): string {
21
+ const m = raw.match(/^---\n([\s\S]*?)\n---\n?/)
22
+ if (m == null) throw new Error(`no frontmatter to set ${key} in`)
23
+ const lines = m[1]!.split('\n')
24
+ const i = lines.findIndex((l) => l.startsWith(`${key}:`))
25
+ const line = value === '' ? `${key}:` : `${key}: ${value}`
26
+ if (i === -1) lines.push(line)
27
+ else lines[i] = line
28
+ return `---\n${lines.join('\n')}\n---\n${raw.slice(m[0].length)}`
29
+ }
30
+
31
+ /** a `## <name>` section of a contract post file, trimmed; `## Post` runs to `## Feedback` so a post may hold `##` headings */
32
+ export function section(body: string, name: string): string | null {
33
+ const start = body.search(new RegExp(`^## ${name}[ \\t]*$`, 'm'))
34
+ if (start === -1) return null
35
+ const rest = body.slice(start).replace(/^.*\n?/, '')
36
+ const end = name === 'Post' ? rest.search(/^## Feedback[ \t]*$/m) : rest.search(/^## /m)
37
+ return (end === -1 ? rest : rest.slice(0, end)).trim()
38
+ }
39
+
40
+ export type ProfileRow = {
41
+ field: string
42
+ value: string
43
+ /** the value names files under the identity's `files` folder, a comma between two: their paths there, the
44
+ * pictures to upload; empty, a text */
45
+ files: string[]
46
+ }
47
+
48
+ /** the rows of the `| field | value |` table of a `## Profile` (or another) section; `filesRoot` the folder a picture
49
+ * path is relative to, null when the rows name none */
50
+ export function rows(body: string, name = 'Profile', filesRoot: string | null = null): ProfileRow[] {
51
+ const out: ProfileRow[] = []
52
+ for (const line of (section(body, name) ?? '').split('\n')) {
53
+ const m = /^\|\s*(.+?)\s*\|\s*(.*?)\s*\|$/.exec(line.trim())
54
+ if (m == null || m[1] === 'field' || /^-+$/.test(m[1]!)) continue
55
+ const value = m[2]!
56
+ const parts = value.split(',').map((x) => x.trim())
57
+ const files = filesRoot != null && parts.every((x) => /\.\w+$/.test(x) && !isAbsolute(x) && existsSync(join(filesRoot, x))) ? parts : []
58
+ out.push({ field: m[1]!, value, files })
59
+ }
60
+ return out
61
+ }
62
+
63
+ /** the body rows of a markdown table in a section, each a list of its cells */
64
+ export function table(body: string, name: string): string[][] {
65
+ return (section(body, name) ?? '')
66
+ .split('\n')
67
+ .filter((l) => /^\|.*\|$/.test(l.trim()))
68
+ .map((l) => l.trim().slice(1, -1).split('|').map((c) => c.trim()))
69
+ .slice(2)
70
+ }
@@ -0,0 +1,53 @@
1
+ // the facts of a repo's draft media (wiki tools/shipkit/social.md, Media): one local json, `.shipkit/social-media.json`,
2
+ // each file of the drafts folder by `<slug>/<name>` with its sha, size, type and the mtime it was hashed at. The media
3
+ // store's `social` kind writes it; a file the disk let go keeps its key here, so the desk still finds it
4
+ import { readFileSync } from 'node:fs'
5
+ import { join, relative, resolve } from 'node:path'
6
+ import { LAYOUT } from '../core/layout.ts'
7
+ import { atomicWrite } from '../core/locked-write.ts'
8
+ import { mediaKey } from '../media-store/content.ts'
9
+ import type { MediaFact } from '../media-store/fact.ts'
10
+ import { isUp } from '../media-store/remote.ts'
11
+
12
+ export const SOCIAL_KIND = 'social'
13
+
14
+ export type FileFact = MediaFact & { mtime: number }
15
+
16
+ export interface Facts {
17
+ v: 1
18
+ files: Record<string, FileFact>
19
+ }
20
+
21
+ export const factsFile = (root: string): string => join(root, LAYOUT.socialMedia)
22
+ export const draftsOf = (root: string): string => join(root, LAYOUT.social, 'drafts')
23
+ /** the repo of a drafts folder: `<root>/.shipkit/social/drafts` */
24
+ export const rootOfDrafts = (store: string): string => resolve(store, '..', '..', '..')
25
+
26
+ export function readFacts(root: string): Facts {
27
+ try {
28
+ const f = JSON.parse(readFileSync(factsFile(root), 'utf8')) as Facts
29
+ if (f.v === 1 && f.files != null && typeof f.files === 'object') return f
30
+ } catch {}
31
+ return { v: 1, files: {} }
32
+ }
33
+
34
+ export const writeFacts = (root: string, f: Facts): void => atomicWrite(factsFile(root), `${JSON.stringify(f, null, 1)}\n`)
35
+
36
+ /** the key the Space keeps a draft file under */
37
+ export const socialKey = (f: Pick<MediaFact, 'sha'>, name: string): string => mediaKey(SOCIAL_KIND, f, name)
38
+
39
+ /** the fact of the file at `path` inside the drafts folder, null outside it or when none was ever taken */
40
+ export function factAt(root: string, path: string, facts = readFacts(root)): { id: string; fact: FileFact } | null {
41
+ const id = relative(draftsOf(root), path)
42
+ if (id === '' || id.startsWith('..')) return null
43
+ const fact = facts.files[id]
44
+ return fact ? { id, fact } : null
45
+ }
46
+
47
+ /** a media a draft names that the disk let go and the Space holds: its place in the draft's folder, else null */
48
+ export function purgedAt(root: string, dir: string, name: string): string | null {
49
+ if (name.startsWith('~/') || name.startsWith('/')) return null
50
+ const path = join(dir, name)
51
+ const at = factAt(root, path)
52
+ return at && isUp(socialKey(at.fact, path)) ? path : null
53
+ }
@@ -0,0 +1,189 @@
1
+ // the social drafts as a kind of the media store (wiki tools/shipkit/social.md, Media): every media file of every
2
+ // draft folder, and every file a draft names inside the drafts folder, by its facts (media-facts.ts). Every one goes up.
3
+ // A file git tracks, or would commit, never leaves the disk: a purge would read as a deletion in git. Only a file git
4
+ // ignores (a rendered trailer, a public repo's drafts) may go, and the desk then serves it from the Space
5
+ import { readdirSync, readFileSync, statSync, type Dirent } from 'node:fs'
6
+ import { extname, join, relative } from 'node:path'
7
+ import { gitBin } from '../core/git-bin.ts'
8
+ import { shaOf, shaOfKey, typeOf } from '../media-store/content.ts'
9
+ import { mediaDb } from '../media-store/db.ts'
10
+ import type { MediaKind, MediaRow } from '../media-store/kind.ts'
11
+ import { fetchBack, signedUrl } from '../media-store/remote.ts'
12
+ import { mediaNames, parseDraft, resolveMedia } from './drafts.ts'
13
+ import { draftsOf, factAt, readFacts, rootOfDrafts, SOCIAL_KIND, socialKey, writeFacts, type FileFact } from './media-facts.ts'
14
+
15
+ /** a file of a draft folder that is media, whether or not its draft names it */
16
+ const MEDIA_EXT = new Set(['.png', '.jpg', '.jpeg', '.webp', '.gif', '.avif', '.svg', '.mp4', '.webm', '.mov', '.m4v', '.wav', '.mp3', '.flac', '.ogg', '.opus', '.m4a', '.aac'])
17
+
18
+ const entries = (dir: string): Dirent[] => {
19
+ try {
20
+ return readdirSync(dir, { withFileTypes: true })
21
+ } catch {
22
+ return []
23
+ }
24
+ }
25
+
26
+ /** every media file under a draft folder, as `<name>` relative to it; dot files and the draft's text never */
27
+ function mediaFiles(dir: string, at = ''): string[] {
28
+ return entries(join(dir, at)).flatMap((e) => {
29
+ if (e.name.startsWith('.')) return []
30
+ const rel = at === '' ? e.name : `${at}/${e.name}`
31
+ if (e.isDirectory()) return mediaFiles(dir, rel)
32
+ return e.isFile() && MEDIA_EXT.has(extname(e.name).toLowerCase()) ? [rel] : []
33
+ })
34
+ }
35
+
36
+ const slugs = (store: string): string[] => entries(store).filter((e) => e.isDirectory() && !e.name.startsWith('.')).map((e) => e.name).sort()
37
+
38
+ /** every `<slug>/<name>` the drafts folder holds or names, the paths on the disk */
39
+ function named(store: string): Set<string> {
40
+ const root = rootOfDrafts(store)
41
+ const out = new Set<string>()
42
+ for (const slug of slugs(store)) {
43
+ const dir = join(store, slug)
44
+ for (const f of mediaFiles(dir)) out.add(`${slug}/${f}`)
45
+ let raw: string
46
+ try {
47
+ raw = readFileSync(join(dir, 'draft.md'), 'utf8')
48
+ } catch {
49
+ continue
50
+ }
51
+ for (const n of mediaNames(parseDraft(raw, ''))) {
52
+ const p = resolveMedia(n, dir, root)
53
+ const id = p == null ? '' : relative(store, p)
54
+ if (id !== '' && !id.startsWith('..') && id.includes('/')) out.add(id)
55
+ }
56
+ }
57
+ return out
58
+ }
59
+
60
+ const split = (id: string): { item: string; name: string } => {
61
+ const at = id.indexOf('/')
62
+ return { item: id.slice(0, at), name: id.slice(at + 1) }
63
+ }
64
+
65
+ /** the files under the store git ignores and does not track: the only ones a purge may take. null: git did not answer */
66
+ function ignoredOf(store: string): Set<string> | null {
67
+ const r = Bun.spawnSync([gitBin(), 'ls-files', '-z', '-o', '-i', '--exclude-standard', '--', '.'], { cwd: store, stdout: 'pipe', stderr: 'ignore' })
68
+ if (r.exitCode !== 0) return null
69
+ return new Set(r.stdout.toString().split('\0').filter((l) => l !== ''))
70
+ }
71
+
72
+ /** the index's own rows of the store: the keys of files the record lost (a record deleted, a machine restored) */
73
+ function indexed(store: string): Map<string, { key: string; size: number }> {
74
+ const p = `${SOCIAL_KIND}/`
75
+ const rows = (mediaDb()?.query('select item, name, key, size from files where store = ? and substr(key, 1, ?) = ?').all(store, p.length, p) ?? []) as { item: string; name: string; key: string; size: number }[]
76
+ return new Map(rows.map((r) => [`${r.item}/${r.name}`, { key: r.key, size: r.size }]))
77
+ }
78
+
79
+ export const socialMedia: MediaKind = {
80
+ kind: SOCIAL_KIND,
81
+ storeOf: (root) => draftsOf(root),
82
+ stamp(store) {
83
+ const parts: string[] = []
84
+ for (const slug of slugs(store)) {
85
+ const dir = join(store, slug)
86
+ for (const f of ['draft.md', ...mediaFiles(dir)]) {
87
+ const s = statSync(join(dir, f), { throwIfNoEntry: false })
88
+ parts.push(`${slug}/${f}:${s?.size ?? '-'}:${s?.mtimeMs ?? '-'}`)
89
+ }
90
+ }
91
+ return Bun.hash(parts.join('\n')).toString(36)
92
+ },
93
+ async scan(store, o) {
94
+ const root = rootOfDrafts(store)
95
+ const facts = readFacts(root)
96
+ const ids = named(store)
97
+ let budget = o.fill
98
+ let filled = 0
99
+ let left = 0
100
+ let moved = false
101
+ const rows: MediaRow[] = []
102
+ for (const id of ids) {
103
+ const path = join(store, id)
104
+ const s = statSync(path, { throwIfNoEntry: false })
105
+ const held = facts.files[id]
106
+ if (!s?.isFile()) continue
107
+ if (held && held.size === s.size && held.mtime === s.mtimeMs) {
108
+ rows.push({ ...split(id), fact: held, local: true })
109
+ continue
110
+ }
111
+ if (budget <= 0) {
112
+ left++
113
+ // its key kept while it waits for a hash, never uploaded nor purged on a fact the disk may have moved past
114
+ if (held) rows.push({ ...split(id), fact: held, local: false })
115
+ continue
116
+ }
117
+ budget--
118
+ filled++
119
+ const fact: FileFact = { sha: await shaOf(path), size: s.size, type: typeOf(path), mtime: s.mtimeMs }
120
+ facts.files[id] = fact
121
+ moved = true
122
+ rows.push({ ...split(id), fact, local: true })
123
+ }
124
+ // a file off the disk keeps its row while its draft folder stands: purged, or deleted by hand, its key stays
125
+ const off = (id: string): boolean => !statSync(join(store, id), { throwIfNoEntry: false })?.isFile()
126
+ const alive = new Set(slugs(store))
127
+ for (const [id, fact] of Object.entries(facts.files)) {
128
+ if (ids.has(id)) continue
129
+ if (!off(id)) {
130
+ // on the disk and no media of a draft any more: the disk holds it, the record needs it no more
131
+ delete facts.files[id]
132
+ moved = true
133
+ continue
134
+ }
135
+ // its draft folder gone (deleted, renamed): no row, the record keeps its key for a restore
136
+ if (alive.has(split(id).item)) rows.push({ ...split(id), fact, local: false })
137
+ }
138
+ // the record lost a file the index still keys: taken back into it
139
+ for (const [id, r] of indexed(store)) {
140
+ const sha = shaOfKey(r.key)
141
+ if (facts.files[id] || !sha || !off(id) || !alive.has(split(id).item)) continue
142
+ const fact: FileFact = { sha, size: r.size, type: typeOf(id), mtime: 0 }
143
+ facts.files[id] = fact
144
+ moved = true
145
+ rows.push({ ...split(id), fact, local: false })
146
+ }
147
+ if (moved) writeFacts(root, facts)
148
+ return { rows, filled, left }
149
+ },
150
+ async holds(store) {
151
+ const ignored = ignoredOf(store)
152
+ return (row) => {
153
+ const id = `${row.item}/${row.name}`
154
+ const mtime = Math.max(statSync(join(store, id), { throwIfNoEntry: false })?.mtimeMs ?? 0, statSync(join(store, row.item, 'draft.md'), { throwIfNoEntry: false })?.mtimeMs ?? 0)
155
+ return { pinned: ignored == null || !ignored.has(id), used: mtime || undefined }
156
+ }
157
+ },
158
+ async beforePurge(store, _space, row) {
159
+ const path = join(store, row.item, row.name)
160
+ // asked again at the last moment: a file git tracks, or would commit, never leaves the disk
161
+ const ig = Bun.spawnSync([gitBin(), 'check-ignore', '-q', '--', join(row.item, row.name)], { cwd: store, stdout: 'ignore', stderr: 'ignore' })
162
+ if (ig.exitCode !== 0) throw new Error(`${path} is not ignored by git: kept`)
163
+ if ((await shaOf(path)) !== shaOfKey(row.key)) throw new Error(`${path} does not hash to its key ${row.key}: kept`)
164
+ },
165
+ }
166
+
167
+ /** a signed URL for a draft file the disk let go, null when it is on the disk or the Space lacks it */
168
+ export async function socialMediaUrl(root: string, path: string): Promise<string | null> {
169
+ const at = factAt(root, path)
170
+ return at ? signedUrl(socialKey(at.fact, path), at.fact.size) : null
171
+ }
172
+
173
+ /** the file at `path`, fetched back from the Space when the disk let it go; the path itself when the record knows none */
174
+ export async function socialMediaBack(root: string, path: string): Promise<string> {
175
+ const at = factAt(root, path)
176
+ if (!at) return path
177
+ const { item, name } = split(at.id)
178
+ const back = await fetchBack(path, socialKey(at.fact, path), at.fact, { store: draftsOf(root), item, name })
179
+ if (back == null) return path
180
+ // the bytes are checked by their sha: the record takes the new mtime, so no scan hashes them again
181
+ const facts = readFacts(root)
182
+ const f = facts.files[at.id]
183
+ const mtime = statSync(back, { throwIfNoEntry: false })?.mtimeMs
184
+ if (f && mtime != null && f.sha === at.fact.sha) {
185
+ facts.files[at.id] = { ...f, mtime }
186
+ writeFacts(root, facts)
187
+ }
188
+ return back
189
+ }