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
@@ -0,0 +1,80 @@
1
+ import { existsSync, readFileSync } from 'node:fs'
2
+ import { join } from 'node:path'
3
+ import { LAYOUT } from '../core/layout.ts'
4
+ import { houseRootOf } from '../home/home-start.ts'
5
+ import { homeDir } from '../home/home-paths.ts'
6
+ import { type Identity, speakerOf } from '../identities/identities.ts'
7
+ import { identityCache } from '../identities/machine.ts'
8
+
9
+ // who scrolls (wiki build/shipkit/veille.md, Identities): what the Veille needs of an identity of the identity model
10
+ // (identities/identities.ts), its Chrome profile's email, its own accounts' handles, its watch list beside its files
11
+ // and its log in shipkit's home
12
+
13
+ export type VeilleIdentity = {
14
+ id: string
15
+ name: string
16
+ /** the email its Chrome profile is signed in with: the profile the extension says it runs in, where a page opens */
17
+ email: string
18
+ /** its own accounts, their posts never in its feed */
19
+ accounts: { platform: string; handle: string }[]
20
+ /** its watch list, absent when it has no Veille */
21
+ watchFile: string
22
+ /** its log, on this machine only */
23
+ logDir: string
24
+ }
25
+
26
+ /** the identities folder: `SHIPKIT_IDENTITIES_DIR`, else the house repo's, found from `cwd` */
27
+ export const identitiesRoot = (cwd = process.cwd()): string | null => {
28
+ const env = process.env.SHIPKIT_IDENTITIES_DIR
29
+ if (env) return env
30
+ const house = houseRootOf(cwd)
31
+ return house == null ? null : join(house, LAYOUT.identities)
32
+ }
33
+
34
+ /** an identity's log folder in shipkit's home */
35
+ export const veilleLogDir = (id: string, home = homeDir()): string => join(home, 'veille', id)
36
+
37
+ /** `<platform>:<handle>` the way an author is compared: no `@`, no instance, lowercase */
38
+ export const handleKey = (platform: string, handle: string): string => `${platform}:${handle.replace(/^@/, '').split('@')[0]!.toLowerCase()}`
39
+
40
+ const veilleOfIdentity = (x: Identity): VeilleIdentity => ({
41
+ id: x.id,
42
+ name: x.name,
43
+ email: x.rows.find((r) => r.field === 'email')?.value ?? '',
44
+ accounts: x.accounts.filter((a) => a.handle !== '').map((a) => ({ platform: a.id, handle: a.handle })),
45
+ watchFile: join(x.dir, 'veille.md'),
46
+ logDir: veilleLogDir(x.id),
47
+ })
48
+
49
+ /** the identities, read again once an identity.md moved: every hub's tree asks on each refresh, and a read measures
50
+ * every picture */
51
+ const identitiesOf = identityCache()
52
+
53
+ /** every identity, the model's order */
54
+ export const identities = (root = identitiesRoot()): VeilleIdentity[] => identitiesOf(root).identities.map(veilleOfIdentity)
55
+
56
+ export const identityOf = (id: string, root = identitiesRoot()): VeilleIdentity | null => identities(root).find((x) => x.id === id) ?? null
57
+
58
+ export const hasVeille = (x: VeilleIdentity): boolean => existsSync(x.watchFile)
59
+
60
+ /** the identity a Chrome profile is signed in as, by its email; null when none is */
61
+ export const identityOfProfile = (email: string, root = identitiesRoot()): VeilleIdentity | null =>
62
+ email === '' ? null : (identities(root).find((x) => x.email.toLowerCase() === email.toLowerCase()) ?? null)
63
+
64
+ /** the `asks:` line of a watch list, read without parsing the rest */
65
+ function asksOf(file: string): string | null {
66
+ try {
67
+ return /^asks:\s*(\S+)\s*$/m.exec(/^---\n([\s\S]*?)\n---/.exec(readFileSync(file, 'utf8'))?.[1] ?? '')?.[1] ?? null
68
+ } catch {
69
+ return null
70
+ }
71
+ }
72
+
73
+ /** the Veille a repo shows: the identity it speaks as (its `speaksAs`, else the default one), else the one whose watch
74
+ * list names it in `asks:` */
75
+ export function veilleOfRepo(repo: string, speaksAs: string | null, root = identitiesRoot()): VeilleIdentity | null {
76
+ const ids = identitiesOf(root)
77
+ const own = speakerOf(speaksAs ?? undefined, ids)
78
+ if (own != null && hasVeille(veilleOfIdentity(own))) return veilleOfIdentity(own)
79
+ return ids.identities.map(veilleOfIdentity).find((x) => hasVeille(x) && asksOf(x.watchFile) === repo) ?? null
80
+ }
@@ -0,0 +1,68 @@
1
+ import { copyFileSync, existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from 'node:fs'
2
+ import { join } from 'node:path'
3
+ import { VeilleLog } from './log.ts'
4
+ import type { Kept } from './platforms.ts'
5
+
6
+ // an older log brought into an identity's (wiki build/shipkit/veille.md, The log): the day files merged line by line in
7
+ // the order they were seen, every mark kept, the target's own answer winning where both hold one. The posts are counted
8
+ // before and after: a post of either side missing after is a failure, never a silence
9
+
10
+ const DAY_FILE = /^\d{4}-\d{2}-\d{2}\.jsonl$/
11
+ const MAPS = ['handled.json', 'passed.json', 'replied.json'] as const
12
+
13
+ export type ImportReport = { source: number; targetBefore: number; targetAfter: number; days: number; marks: Record<string, number>; replies: number; missing: string[] }
14
+
15
+ const readJson = <T>(f: string, empty: T): T => {
16
+ try {
17
+ return JSON.parse(readFileSync(f, 'utf8')) as T
18
+ } catch {
19
+ return empty
20
+ }
21
+ }
22
+
23
+ const lastOf = (line: string): number => {
24
+ try {
25
+ return (JSON.parse(line) as Kept).last ?? 0
26
+ } catch {
27
+ return 0
28
+ }
29
+ }
30
+
31
+ export function importLog(from: string, to: string): ImportReport {
32
+ if (!existsSync(from)) throw new Error(`no log at ${from}`)
33
+ const source = new VeilleLog(from).posts()
34
+ const before = new VeilleLog(to).posts()
35
+ const keys = new Set([...source.keys(), ...before.keys()])
36
+ mkdirSync(to, { recursive: true })
37
+ const days = readdirSync(from).filter((f) => DAY_FILE.test(f))
38
+ for (const f of days) {
39
+ const theirs = readFileSync(join(from, f), 'utf8').split('\n').filter(Boolean)
40
+ const ours = existsSync(join(to, f)) ? readFileSync(join(to, f), 'utf8').split('\n').filter(Boolean) : []
41
+ // one day of both: every line once, in the order it was seen, so the last line of a post stays its latest state
42
+ const merged = [...new Set([...theirs, ...ours])].map((line, i) => ({ line, i, last: lastOf(line) })).sort((a, b) => a.last - b.last || a.i - b.i)
43
+ writeFileSync(join(to, f), `${merged.map((x) => x.line).join('\n')}\n`)
44
+ }
45
+ const marks: Record<string, number> = {}
46
+ for (const m of MAPS) {
47
+ const all = { ...readJson<Record<string, unknown>>(join(from, m), {}), ...readJson<Record<string, unknown>>(join(to, m), {}) }
48
+ marks[m] = Object.keys(all).length
49
+ if (marks[m] > 0) writeFileSync(join(to, m), JSON.stringify(all))
50
+ }
51
+ type Author = { followers: number; at: number }
52
+ const authors = readJson<Record<string, Author>>(join(from, 'authors.json'), {})
53
+ for (const [k, a] of Object.entries(readJson<Record<string, Author>>(join(to, 'authors.json'), {}))) if ((authors[k]?.at ?? 0) <= a.at) authors[k] = a
54
+ if (Object.keys(authors).length > 0) writeFileSync(join(to, 'authors.json'), JSON.stringify(authors))
55
+ const off = [...new Set([...readJson<{ off?: string[] }>(join(from, 'platforms.json'), {}).off ?? [], ...readJson<{ off?: string[] }>(join(to, 'platforms.json'), {}).off ?? []])]
56
+ if (off.length > 0) writeFileSync(join(to, 'platforms.json'), `${JSON.stringify({ off })}\n`)
57
+ if (existsSync(join(from, 'reads.json')) && !existsSync(join(to, 'reads.json'))) copyFileSync(join(from, 'reads.json'), join(to, 'reads.json'))
58
+ let replies = 0
59
+ if (existsSync(join(from, 'replies'))) {
60
+ mkdirSync(join(to, 'replies'), { recursive: true })
61
+ for (const f of readdirSync(join(from, 'replies'))) {
62
+ if (!existsSync(join(to, 'replies', f))) copyFileSync(join(from, 'replies', f), join(to, 'replies', f))
63
+ replies++
64
+ }
65
+ }
66
+ const after = new VeilleLog(to).posts()
67
+ return { source: source.size, targetBefore: before.size, targetAfter: after.size, days: days.length, marks, replies, missing: [...keys].filter((k) => !after.has(k)) }
68
+ }
@@ -0,0 +1,183 @@
1
+ import { appendFileSync, existsSync, mkdirSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs'
2
+ import { join } from 'node:path'
3
+ import { isPlatform, keyOf, type Kept, type Platform, type Read } from './platforms.ts'
4
+
5
+ // the Veille's log (wiki build/shipkit/veille.md, The log): one identity's posts the extension read, on this machine
6
+ // only. One JSONL file a day (the day in Paris), each line a post's whole state, the last line of a post wins; capped in
7
+ // bytes, the oldest days dropped first
8
+
9
+ const CAP_BYTES = 20 * 1024 * 1024
10
+ /** a post seen again with the same counts gets a new line this long after its last one */
11
+ const REWRITE_MS = 15 * 60_000
12
+ const AUTHORS_KEPT = 5000
13
+
14
+ const DAY = new Intl.DateTimeFormat('en-CA', { timeZone: 'Europe/Paris', year: 'numeric', month: '2-digit', day: '2-digit' })
15
+ /** a moment's day, `YYYY-MM-DD`, in Paris */
16
+ export const dayOf = (ms: number): string => DAY.format(ms)
17
+
18
+ /** `page`: the path and query of the page read, empty when the extension did not say */
19
+ export type Batch = { platform: Platform; posts: Read[]; authors: { author: string; followers: number }[]; page: string }
20
+
21
+ /** a post's key as a file name */
22
+ export const fileKey = (key: string): string => key.replace(':', '-')
23
+
24
+ const ID = /^[A-Za-z0-9_-]{1,64}$/
25
+ const num = (v: unknown): number | null => (typeof v === 'number' && Number.isFinite(v) && v >= 0 ? Math.round(v) : null)
26
+ const str = (v: unknown, max: number): string => (typeof v === 'string' ? v.slice(0, max) : '')
27
+
28
+ /** a batch from the extension, every field checked and capped; a string says what is wrong */
29
+ export function parseBatch(body: unknown): Batch | string {
30
+ if (typeof body !== 'object' || body == null) return 'a JSON object is expected'
31
+ const b = body as { platform?: unknown; posts?: unknown; authors?: unknown; page?: unknown }
32
+ if (!isPlatform(b.platform)) return `platform ${String(b.platform)}?`
33
+ const platform = b.platform
34
+ const posts: Read[] = []
35
+ for (const raw of Array.isArray(b.posts) ? b.posts.slice(0, 100) : []) {
36
+ const p = raw as Record<string, unknown>
37
+ const id = str(p.id, 64)
38
+ const url = str(p.url, 300)
39
+ if (p.platform !== platform || !ID.test(id) || !/^https:\/\/\S+$/.test(url)) continue
40
+ posts.push({
41
+ platform,
42
+ id,
43
+ url,
44
+ author: str(p.author, 80),
45
+ name: str(p.name, 80),
46
+ text: str(p.text, 500),
47
+ place: str(p.place, 80),
48
+ at: num(p.at),
49
+ likes: num(p.likes),
50
+ reposts: num(p.reposts),
51
+ replies: num(p.replies),
52
+ views: num(p.views),
53
+ followers: num(p.followers),
54
+ media: p.media === 'image' || p.media === 'video' ? p.media : null,
55
+ ...(typeof p.replyTo === 'string' && p.replyTo !== '' ? { replyTo: p.replyTo.slice(0, 80) } : {}),
56
+ })
57
+ }
58
+ const authors = (Array.isArray(b.authors) ? b.authors.slice(0, 50) : []).flatMap((raw) => {
59
+ const a = raw as Record<string, unknown>
60
+ const followers = num(a.followers)
61
+ return typeof a.author === 'string' && a.author !== '' && followers != null ? [{ author: a.author.slice(0, 80), followers }] : []
62
+ })
63
+ return { platform, posts, authors, page: str(b.page, 300) }
64
+ }
65
+
66
+ const DAY_FILE = /^\d{4}-\d{2}-\d{2}\.jsonl$/
67
+ const counts = (p: Read): string => [p.likes, p.reposts, p.replies, p.views, p.followers].join(',')
68
+
69
+ export class VeilleLog {
70
+ private index: Map<string, Kept> | null = null
71
+ /** the day files as last read, names and sizes: another process that wrote a line moves it */
72
+ private shape = ''
73
+ private written = new Map<string, number>()
74
+ private authorsMap: Record<string, { followers: number; at: number }> | null = null
75
+ /** moves at every write: the page fetches the feed again */
76
+ stamp = 0
77
+
78
+ constructor(
79
+ readonly dir: string,
80
+ readonly cap = CAP_BYTES,
81
+ ) {}
82
+
83
+ /** the day files, oldest first */
84
+ days(): string[] {
85
+ return existsSync(this.dir) ? readdirSync(this.dir).filter((f) => DAY_FILE.test(f)).sort() : []
86
+ }
87
+
88
+ bytes(): number {
89
+ return this.days().reduce((n, f) => n + statSync(join(this.dir, f)).size, 0)
90
+ }
91
+
92
+ private filesShape(): string {
93
+ return this.days()
94
+ .map((f) => `${f}:${statSync(join(this.dir, f)).size}`)
95
+ .join(',')
96
+ }
97
+
98
+ /** every post, the last line of each; read again when another process wrote to the log */
99
+ posts(): Map<string, Kept> {
100
+ const shape = this.filesShape()
101
+ if (this.index && shape === this.shape) return this.index
102
+ this.written.clear()
103
+ this.shape = shape
104
+ const index = new Map<string, Kept>()
105
+ for (const f of this.days())
106
+ for (const line of readFileSync(join(this.dir, f), 'utf8').split('\n')) {
107
+ if (line === '') continue
108
+ try {
109
+ const p = JSON.parse(line) as Kept
110
+ index.set(keyOf(p), p)
111
+ this.written.set(keyOf(p), p.last)
112
+ } catch {
113
+ // a line cut by a crash: the next one of that post wins anyway
114
+ }
115
+ }
116
+ this.index = index
117
+ return index
118
+ }
119
+
120
+ /** the followers last read for each author, by `<platform>:<author>` */
121
+ authors(): Record<string, { followers: number; at: number }> {
122
+ if (this.authorsMap) return this.authorsMap
123
+ try {
124
+ this.authorsMap = JSON.parse(readFileSync(join(this.dir, 'authors.json'), 'utf8')) as Record<string, { followers: number; at: number }>
125
+ } catch {
126
+ this.authorsMap = {}
127
+ }
128
+ return this.authorsMap
129
+ }
130
+
131
+ /** one batch merged: a post new, its counts moved, or its last line old gets a line in today's file */
132
+ add(batch: Batch, now = Date.now()): { lines: number } {
133
+ const index = this.posts()
134
+ const authors = this.authors()
135
+ if (batch.authors.length > 0) {
136
+ for (const a of batch.authors) authors[`${batch.platform}:${a.author.toLowerCase()}`] = { followers: a.followers, at: now }
137
+ const kept = Object.entries(authors).sort((x, y) => y[1].at - x[1].at).slice(0, AUTHORS_KEPT)
138
+ this.authorsMap = Object.fromEntries(kept)
139
+ mkdirSync(this.dir, { recursive: true })
140
+ writeFileSync(join(this.dir, 'authors.json'), JSON.stringify(this.authorsMap))
141
+ }
142
+ const lines: string[] = []
143
+ for (const read of batch.posts) {
144
+ const key = keyOf(read)
145
+ const was = index.get(key)
146
+ const followers = read.followers ?? this.authorsMap?.[`${read.platform}:${read.author.toLowerCase()}`]?.followers ?? was?.followers ?? null
147
+ const via = read.via || was?.via
148
+ const next: Kept = { ...read, followers, at: read.at ?? was?.at ?? null, first: was?.first ?? now, last: now, seen: (was?.seen ?? 0) + 1, ...(via ? { via } : {}) }
149
+ index.set(key, next)
150
+ if (was == null || counts(was) !== counts(next) || next.via !== was.via || now - (this.written.get(key) ?? 0) >= REWRITE_MS) {
151
+ lines.push(JSON.stringify(next))
152
+ this.written.set(key, now)
153
+ }
154
+ }
155
+ if (lines.length > 0) {
156
+ mkdirSync(this.dir, { recursive: true })
157
+ appendFileSync(join(this.dir, `${dayOf(now)}.jsonl`), `${lines.join('\n')}\n`)
158
+ this.rotate(now)
159
+ if (this.index) this.shape = this.filesShape()
160
+ }
161
+ if (lines.length > 0 || batch.authors.length > 0) this.stamp++
162
+ return { lines: lines.length }
163
+ }
164
+
165
+ /** past the cap, the oldest days deleted, today's never; the posts then read again from the days kept */
166
+ rotate(now = Date.now()): string[] {
167
+ const today = `${dayOf(now)}.jsonl`
168
+ const files = this.days().map((f) => ({ f, size: statSync(join(this.dir, f)).size }))
169
+ let total = files.reduce((n, x) => n + x.size, 0)
170
+ const dropped: string[] = []
171
+ for (const x of files) {
172
+ if (total <= this.cap || x.f === today) break
173
+ rmSync(join(this.dir, x.f))
174
+ total -= x.size
175
+ dropped.push(x.f)
176
+ }
177
+ if (dropped.length > 0) {
178
+ this.index = null
179
+ this.written.clear()
180
+ }
181
+ return dropped
182
+ }
183
+ }
@@ -0,0 +1,118 @@
1
+ // the Veille's words the page and the server share (wiki build/shipkit/veille.md), pure: no node import, the page
2
+ // bundles it. A reply opens prefilled where the platform has an intent, else he pastes it
3
+
4
+ export const PLATFORMS = ['x', 'threads', 'bluesky', 'mastodon', 'instagram', 'tiktok', 'reddit'] as const
5
+ export type Platform = (typeof PLATFORMS)[number]
6
+ export const isPlatform = (s: unknown): s is Platform => PLATFORMS.some((p) => p === s)
7
+
8
+ /** each platform's column, in the order they stand, with its reply limit */
9
+ export const COLUMNS: readonly { platform: Platform; label: string; max: number }[] = [
10
+ { platform: 'x', label: 'X', max: 280 },
11
+ { platform: 'bluesky', label: 'Bluesky', max: 300 },
12
+ { platform: 'reddit', label: 'Reddit', max: 10000 },
13
+ { platform: 'threads', label: 'Threads', max: 500 },
14
+ { platform: 'mastodon', label: 'Mastodon', max: 500 },
15
+ { platform: 'instagram', label: 'Instagram', max: 2200 },
16
+ { platform: 'tiktok', label: 'TikTok', max: 150 },
17
+ ]
18
+
19
+ /** what a reader sends for one post */
20
+ export type Read = {
21
+ platform: Platform
22
+ id: string
23
+ url: string
24
+ author: string
25
+ name: string
26
+ text: string
27
+ /** where it was posted, when the platform says (a subreddit: `r/IndieDev`); empty else */
28
+ place: string
29
+ at: number | null
30
+ likes: number | null
31
+ reposts: number | null
32
+ replies: number | null
33
+ views: number | null
34
+ followers: number | null
35
+ media: 'image' | 'video' | null
36
+ /** the search query that read it, when his search kept it (His search is his intent); empty else */
37
+ via?: string
38
+ /** X's « Replying to @author » over it, the author's handle */
39
+ replyTo?: string
40
+ }
41
+ /** a post as the log keeps it: its last read, when he first and last saw it, how many reads */
42
+ export type Kept = Read & { first: number; last: number; seen: number }
43
+
44
+ export type Parts = { fresh: number; traction: number; niche: number; seen: number; promo: number }
45
+ export type Group = 'now' | 'maybe' | 'done'
46
+ export type Reply = { text: string; media: string | null; at: number; by: 'agent' | 'owner' }
47
+ export type Replied = { url: string; at: number; how: 'text' | 'page' | 'context' | 'api' }
48
+ /** where an item of the Veille stands in the review store: its id, its state, the lane that claimed it */
49
+ export type Interaction = { id: string; state: string; worker: string | null }
50
+
51
+ export type FeedRow = Kept & {
52
+ key: string
53
+ worth: number
54
+ parts: Parts
55
+ group: Group
56
+ handled: boolean
57
+ passed: string | null
58
+ reply: Reply | null
59
+ /** our reply, detected (His replies, detected) */
60
+ replied: Replied | null
61
+ asked: Interaction | null
62
+ tags: string[]
63
+ }
64
+
65
+ export type Dropped = { url: string; author: string; text: string; at: number }
66
+ export type PlatformReads = {
67
+ read: number
68
+ kept: number
69
+ dropped: number
70
+ /** the last batch: when, and the search that read it (null: a timeline) */
71
+ last: number
72
+ search: string | null
73
+ /** the last dropped posts, newest first */
74
+ droppedPosts: Dropped[]
75
+ }
76
+ /** a page worth scrolling, a button on its column; `day` (0 Sunday to 6) lights it that weekday */
77
+ export type Explore = { platform: string; label: string; url: string; day: number | null }
78
+ /** a file of the project's drafts a reply could lend: repo relative, the draft it comes from, the words it shares */
79
+ export type MediaPick = { path: string; draft: string; words: number }
80
+
81
+ /** what the feed route answers: the rows of each platform on by group, best first, its counts, when its reader last
82
+ * sent; the platforms off and the one review */
83
+ export type VeilleFeed = {
84
+ now: number
85
+ identity: { id: string; name: string }
86
+ /** the platforms he switched off: no column of theirs comes */
87
+ off: Platform[]
88
+ /** the review of every column in the review store while open */
89
+ review: Interaction | null
90
+ /** the one he starts the lane's agent with, and the repo it runs in */
91
+ command: string
92
+ asksRepo: string
93
+ /** `reads`: what its reader did today; `expired`: its posts of the window under `maybe`, never handled nor passed;
94
+ * `explore`: its buttons */
95
+ columns: {
96
+ platform: Platform
97
+ rows: FeedRow[]
98
+ counts: Record<Group, number>
99
+ lastRead: number | null
100
+ reads: PlatformReads | null
101
+ expired: number
102
+ explore: Explore[]
103
+ }[]
104
+ }
105
+ export type VeillePost = { row: FeedRow; media: MediaPick[] }
106
+
107
+ /** the platform's reply page with the text in it; null where none exists (he pastes it on the post) */
108
+ export function replyUrl(row: Pick<FeedRow, 'platform' | 'id'>, text: string): string | null {
109
+ if (row.platform === 'x') return `https://x.com/intent/tweet?in_reply_to=${row.id}&text=${encodeURIComponent(text)}`
110
+ return null
111
+ }
112
+
113
+ /** a reader silent this long shows in orange: its platform's page may have moved */
114
+ export const READER_QUIET_MS = 24 * 3600_000
115
+
116
+ export const keyOf = (p: { platform: string; id: string }): string => `${p.platform}:${p.id}`
117
+ /** a post key as the routes take it */
118
+ export const KEY = /^[a-z]+:[A-Za-z0-9_-]+$/
@@ -0,0 +1,66 @@
1
+ import { mkdirSync, readFileSync, writeFileSync } from 'node:fs'
2
+ import { join } from 'node:path'
3
+ import { dayOf } from './log.ts'
4
+ import type { Platform, PlatformReads } from './platforms.ts'
5
+
6
+ // what each platform's reader did today (wiki build/shipkit/veille.md, Every missing post is explained): the posts read, kept
7
+ // and dropped by the watch list, each counted once a day, the last batch's page, the last dropped posts. On this machine
8
+ // only, the identity's `reads.json`; a new day starts from zero
9
+
10
+ const DROPPED_KEPT = 30
11
+ const IDS_KEPT = 5000
12
+
13
+ type Store = { day: string; platforms: Partial<Record<Platform, PlatformReads & { ids: { read: string[]; kept: string[] } }>> }
14
+
15
+ export class Reads {
16
+ private store: Store | null = null
17
+
18
+ constructor(readonly file: string) {}
19
+
20
+ private load(now: number): Store {
21
+ const day = dayOf(now)
22
+ if (this.store == null)
23
+ try {
24
+ this.store = JSON.parse(readFileSync(this.file, 'utf8')) as Store
25
+ } catch {
26
+ this.store = { day, platforms: {} }
27
+ }
28
+ if (this.store.day !== day) this.store = { day, platforms: {} }
29
+ return this.store
30
+ }
31
+
32
+ /** one batch: what it read, what the watch list kept, from which search */
33
+ add(platform: Platform, read: readonly { id: string; url: string; author: string; text: string }[], keptIds: ReadonlySet<string>, search: string | null, now = Date.now()): void {
34
+ const s = this.load(now)
35
+ const p = (s.platforms[platform] ??= { read: 0, kept: 0, dropped: 0, last: 0, search: null, droppedPosts: [], ids: { read: [], kept: [] } })
36
+ const seen = new Set(p.ids.read)
37
+ const kept = new Set(p.ids.kept)
38
+ for (const x of read) {
39
+ const wasKept = kept.has(x.id)
40
+ if (!seen.has(x.id)) {
41
+ seen.add(x.id)
42
+ p.read++
43
+ }
44
+ if (keptIds.has(x.id) && !wasKept) {
45
+ kept.add(x.id)
46
+ p.kept++
47
+ }
48
+ }
49
+ for (const x of read)
50
+ if (!keptIds.has(x.id) && !p.droppedPosts.some((d) => d.url === x.url))
51
+ p.droppedPosts = [{ url: x.url, author: x.author, text: x.text.slice(0, 160), at: now }, ...p.droppedPosts].slice(0, DROPPED_KEPT)
52
+ p.dropped = [...seen].filter((id) => !kept.has(id)).length
53
+ p.ids = { read: [...seen].slice(-IDS_KEPT), kept: [...kept].slice(-IDS_KEPT) }
54
+ p.last = now
55
+ p.search = search
56
+ mkdirSync(join(this.file, '..'), { recursive: true })
57
+ writeFileSync(this.file, JSON.stringify(s))
58
+ }
59
+
60
+ /** today's reads of one platform, none when its reader sent nothing today */
61
+ of(platform: Platform, now = Date.now()): PlatformReads | null {
62
+ const p = this.load(now).platforms[platform]
63
+ if (p == null) return null
64
+ return { read: p.read, kept: p.kept, dropped: p.dropped, last: p.last, search: p.search, droppedPosts: p.droppedPosts }
65
+ }
66
+ }
@@ -0,0 +1,110 @@
1
+ import type { Kept, Platform, Read, Replied } from './platforms.ts'
2
+
3
+ // his replies, detected (wiki build/shipkit/veille.md, His replies, detected): our own posts the readers saw, matched to the
4
+ // post they answer by a draft's text, the page they sit under, or « Replying to @author »; and the public reads of our
5
+ // Bluesky and Mastodon accounts. Read only: nothing here acts on a platform
6
+
7
+ /** the post a page is about: X `/<user>/status/<id>`, Threads `/@user/post/<code>`, Bluesky `/profile/<h>/post/<rkey>`,
8
+ * Mastodon `/@user/<id>`; null on any other page */
9
+ export function targetOf(platform: Platform, page: string): string | null {
10
+ const path = page.split(/[?#]/)[0] ?? ''
11
+ const re: Partial<Record<Platform, RegExp>> = {
12
+ x: /^\/[^/]+\/status\/(\d+)/,
13
+ threads: /^\/@[^/]+\/post\/([A-Za-z0-9_-]+)/,
14
+ bluesky: /^\/profile\/[^/]+\/post\/([a-z0-9]+)/,
15
+ mastodon: /^\/@[^/]+\/(\d+)\/?$/,
16
+ }
17
+ return re[platform]?.exec(path)?.[1] ?? null
18
+ }
19
+
20
+ /** a text as a reply compares: no link, no case, one space, no trailing ellipsis */
21
+ const norm = (s: string): string =>
22
+ s
23
+ .replace(/https?:\/\/\S+/g, ' ')
24
+ .replace(/[’‘]/g, "'")
25
+ .toLowerCase()
26
+ .replace(/\s+/g, ' ')
27
+ .replace(/[\s.…]+$/, '')
28
+ .trim()
29
+
30
+ /** the same reply: equal, or one the start of the other (a reader clips, a platform shortens) past 20 characters */
31
+ export function sameText(a: string, b: string): boolean {
32
+ const x = norm(a)
33
+ const y = norm(b)
34
+ if (x === '' || y === '') return false
35
+ if (x === y) return true
36
+ const [short, long] = x.length < y.length ? [x, y] : [y, x]
37
+ return short.length >= 20 && long.startsWith(short)
38
+ }
39
+
40
+ const keyOf = (platform: string, id: string): string => `${platform}:${id}`
41
+
42
+ /** the posts our own posts of one batch answer, each once, the first way that finds it */
43
+ export function detect(
44
+ mine: readonly Read[],
45
+ page: string,
46
+ log: ReadonlyMap<string, Kept>,
47
+ drafts: Readonly<Record<string, { text: string }>>,
48
+ now: number,
49
+ ): { key: string; replied: Replied }[] {
50
+ const out = new Map<string, Replied>()
51
+ for (const p of mine) {
52
+ const add = (key: string | undefined, how: Replied['how']): void => {
53
+ if (key && key !== keyOf(p.platform, p.id) && !out.has(key)) out.set(key, { url: p.url, at: p.at ?? now, how })
54
+ }
55
+ const byText = Object.entries(drafts).find(([k, d]) => k.startsWith(`${p.platform}:`) && sameText(d.text, p.text))?.[0]
56
+ if (byText) {
57
+ add(byText, 'text')
58
+ continue
59
+ }
60
+ const target = targetOf(p.platform, page)
61
+ if (target && target !== p.id && log.has(keyOf(p.platform, target))) {
62
+ add(keyOf(p.platform, target), 'page')
63
+ continue
64
+ }
65
+ if (p.replyTo) {
66
+ const of = [...log.values()].filter((x) => x.platform === p.platform && x.author.toLowerCase() === p.replyTo!.toLowerCase())
67
+ const drafted = of.filter((x) => drafts[keyOf(x.platform, x.id)] != null)
68
+ const pick = drafted.length > 0 ? drafted : of
69
+ if (pick.length === 1) add(keyOf(pick[0]!.platform, pick[0]!.id), 'context')
70
+ }
71
+ }
72
+ return [...out].map(([key, replied]) => ({ key, replied }))
73
+ }
74
+
75
+ const TIMEOUT_MS = 5000
76
+
77
+ async function getJson<T>(url: string): Promise<T> {
78
+ const r = await fetch(url, { signal: AbortSignal.timeout(TIMEOUT_MS), headers: { accept: 'application/json' } })
79
+ if (!r.ok) throw new Error(`${new URL(url).host}: HTTP ${r.status}`)
80
+ return (await r.json()) as T
81
+ }
82
+
83
+ type BskyItem = { post: { uri: string; author: { handle: string }; record: { createdAt?: string; reply?: { parent?: { uri?: string } } } } }
84
+
85
+ /** our Bluesky account's last posts with their replies: each parent's key and our reply */
86
+ export async function blueskyReplies(handle: string): Promise<{ key: string; replied: Replied }[]> {
87
+ const h = handle.replace(/^@/, '')
88
+ const r = await getJson<{ feed: BskyItem[] }>(`https://public.api.bsky.app/xrpc/app.bsky.feed.getAuthorFeed?actor=${encodeURIComponent(h)}&limit=50&filter=posts_with_replies`)
89
+ return r.feed.flatMap((i) => {
90
+ const parent = i.post.record.reply?.parent?.uri?.split('/').pop()
91
+ if (parent == null || i.post.author.handle !== h) return []
92
+ const rkey = i.post.uri.split('/').pop() ?? ''
93
+ return [{ key: keyOf('bluesky', parent), replied: { url: `https://bsky.app/profile/${h}/post/${rkey}`, at: Date.parse(i.post.record.createdAt ?? '') || Date.now(), how: 'api' as const } }]
94
+ })
95
+ }
96
+
97
+ const mastodonIds = new Map<string, string>()
98
+
99
+ /** our Mastodon account's last statuses: each `in_reply_to_id` (an id of our instance, the one the reader reads) */
100
+ export async function mastodonReplies(handle: string): Promise<{ key: string; replied: Replied }[]> {
101
+ const [user = '', host = ''] = handle.replace(/^@/, '').split('@')
102
+ if (user === '' || host === '') throw new Error(`handle Mastodon ${handle}?`)
103
+ let id = mastodonIds.get(handle)
104
+ if (id == null) {
105
+ id = (await getJson<{ id: string }>(`https://${host}/api/v1/accounts/lookup?acct=${encodeURIComponent(user)}`)).id
106
+ mastodonIds.set(handle, id)
107
+ }
108
+ const list = await getJson<{ url: string; created_at: string; in_reply_to_id: string | null }[]>(`https://${host}/api/v1/accounts/${id}/statuses?limit=40&exclude_reblogs=true`)
109
+ return list.flatMap((s) => (s.in_reply_to_id ? [{ key: keyOf('mastodon', s.in_reply_to_id), replied: { url: s.url, at: Date.parse(s.created_at), how: 'api' as const } }] : []))
110
+ }