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.
- package/CHANGELOG.md +75 -21
- package/README.md +1 -1
- package/package.json +4 -2
- package/src/agent-time/store.ts +2 -2
- package/src/assets/run-assets.ts +2 -2
- package/src/assets/server/studio-server.ts +27 -23
- package/src/check.ts +4 -4
- package/src/checks/SK001-package-json-shape.check.ts +8 -4
- package/src/checks/SK002-contracts-fulfillness.check.ts +2 -2
- package/src/checks/SK003-claude-md-shape.check.ts +20 -13
- package/src/checks/SK004-gitignore-policy.check.ts +45 -6
- package/src/checks/SK005-rvlib-versions.check.ts +2 -2
- package/src/checks/SK006-npm-publish-safety.check.ts +3 -3
- package/src/checks/SK007-github-visibility.check.ts +2 -2
- package/src/checks/SK008-reviewer-agent.check.ts +3 -3
- package/src/checks/SK010-undeclared-unit.check.ts +2 -2
- package/src/checks/SK011-sibling-unit-ranges.check.ts +2 -2
- package/src/checks/SK012-config-barrel-import.check.ts +2 -2
- package/src/checks/SK013-one-way-in-policy.check.ts +2 -2
- package/src/checks/SK015-nested-repo.check.ts +3 -3
- package/src/checks/SK016-legacy-check-shapes.check.ts +2 -2
- package/src/checks/SK017-vscode-hub-task.check.ts +2 -2
- package/src/checks/SK018-test-files-run.check.ts +2 -2
- package/src/checks/SK019-tests-run-in-units.check.ts +2 -2
- package/src/checks/SK020-self-spawning-check.check.ts +2 -2
- package/src/checks/SK022-machine-runs-the-pin.check.ts +2 -2
- package/src/checks/SK024-identity-colors.check.ts +1 -1
- package/src/checks/SK025-release-drift.check.ts +2 -2
- package/src/checks/SK026-asks-autoclose.check.ts +2 -2
- package/src/checks/SK027-agent-wiki-links.check.ts +8 -2
- package/src/checks/SK028-readme.check.ts +2 -2
- package/src/checks/SK029-explicit-check-files.check.ts +3 -3
- package/src/checks/SK030-cache-audit.check.ts +7 -5
- package/src/checks/SK031-trace-audit.check.ts +7 -7
- package/src/checks/SK032-ignored-inputs.check.ts +3 -3
- package/src/checks/SK033-global-contribution.check.ts +11 -4
- package/src/checks/SK034-commit-gates-armed.check.ts +2 -2
- package/src/checks/SK035-public-clean.check.ts +46 -0
- package/src/checks/SK036-draft-media-size.check.ts +28 -0
- package/src/checks/SK037-keyword-additions.check.ts +43 -0
- package/src/cli/cmd_Backup.ts +152 -0
- package/src/cli/cmd_Ci.ts +8 -11
- package/src/cli/cmd_Commands.ts +4 -4
- package/src/cli/cmd_ConfigKeys.ts +2 -2
- package/src/cli/cmd_Drill.ts +145 -0
- package/src/cli/cmd_Home.ts +50 -3
- package/src/cli/cmd_Init.ts +1 -1
- package/src/cli/cmd_Media.ts +10 -8
- package/src/cli/cmd_Mv.ts +14 -7
- package/src/cli/cmd_Review.ts +6 -4
- package/src/cli/cmd_Shot.ts +5 -2
- package/src/cli/cmd_Smoke.ts +5 -2
- package/src/cli/cmd_Social.ts +226 -0
- package/src/cli/cmd_Sound.ts +1 -1
- package/src/cli/cmd_Start.ts +1 -1
- package/src/cli/cmd_Time.ts +1 -1
- package/src/cli/cmd_TraceAudit.ts +6 -6
- package/src/cli/cmd_Trailer.ts +7 -4
- package/src/cli/cmd_Veille.ts +173 -0
- package/src/cli/cmd_When.ts +2 -2
- package/src/cli/family-pages.ts +19 -16
- package/src/cli/registry.ts +13 -2
- package/src/cli.ts +5 -2
- package/src/collections/actions.ts +1 -49
- package/src/collections/checks.ts +2 -1
- package/src/collections/collection-types.ts +12 -3
- package/src/collections/providers.ts +4 -4
- package/src/collections/review.ts +3 -2
- package/src/collections/tests.ts +19 -8
- package/src/comfy/comfy-panel.ts +2 -2
- package/src/contracts/apply-contracts.ts +1 -3
- package/src/contracts/contract-manifests.ts +2 -3
- package/src/contracts/contract-types.ts +0 -1
- package/src/contracts/contracts-engine.ts +0 -3
- package/src/contracts/manifests/discord.contract.ts +1 -1
- package/src/contracts/manifests/identity.contract.ts +1 -1
- package/src/contracts/manifests/itch.contract.ts +1 -1
- package/src/contracts/manifests/steam.contract.ts +1 -1
- package/src/core/agent-dir-at.ts +12 -0
- package/src/core/agent-dir.ts +16 -0
- package/src/core/app-icon.ts +9 -3
- package/src/core/budget.ts +1 -1
- package/src/core/bun-builtins.ts +2 -2
- package/src/core/canonical-scripts.ts +2 -2
- package/src/core/discover-checks.ts +38 -6
- package/src/core/fix-scope.ts +4 -2
- package/src/core/floor-resolve.ts +68 -48
- package/src/core/floor.ts +9 -0
- package/src/core/git-root.ts +24 -0
- package/src/core/global-contribution.ts +4 -1
- package/src/core/ignored-block.ts +1 -1
- package/src/core/ignored-inputs.ts +3 -2
- package/src/core/last-good.ts +3 -1
- package/src/core/layout.ts +8 -0
- package/src/core/log-stamp.ts +36 -0
- package/src/core/loop-watch.ts +93 -0
- package/src/core/machine-link.ts +134 -0
- package/src/core/memory-watch.ts +41 -0
- package/src/core/motherhome.ts +2 -2
- package/src/core/one-way-in-policy.ts +34 -26
- package/src/core/run-ci.ts +9 -11
- package/src/core/run-fixers.ts +9 -9
- package/src/core/runs-matrix.ts +1 -1
- package/src/core/slots.ts +30 -0
- package/src/core/trace-audit.ts +50 -9
- package/src/core/tree-rev.ts +60 -0
- package/src/core/unit-files.ts +42 -0
- package/src/drill/render.ts +140 -0
- package/src/drill/run.ts +269 -0
- package/src/fleet/scan-fleet.ts +6 -5
- package/src/home/daemon-jobs.ts +201 -0
- package/src/home/global-context.ts +44 -8
- package/src/home/gui-app/ShipkitGui.swift +91 -2
- package/src/home/home-routes.ts +22 -15
- package/src/home/hubs.ts +10 -3
- package/src/home/inbox-shape.ts +54 -5
- package/src/home/inbox.ts +17 -2
- package/src/home/lib-watch.ts +10 -3
- package/src/home/machine-stores.ts +15 -29
- package/src/home/pm-config.ts +4 -1
- package/src/home/pm-inputs.ts +2 -0
- package/src/home/resources.ts +7 -2
- package/src/home/run-daemon.ts +15 -18
- package/src/home/run-pm.ts +3 -1
- package/src/home/serve-daemon.ts +4 -3
- package/src/home/serve-web.ts +104 -1
- package/src/hooks/commit-message.ts +29 -20
- package/src/hooks/hook-gates.ts +1 -1
- package/src/hooks/leak-guard.ts +69 -9
- package/src/hooks/run-hooks.ts +18 -22
- package/src/identities/identities.ts +334 -0
- package/src/identities/machine-route.ts +126 -0
- package/src/identities/machine.ts +62 -0
- package/src/init-repo.ts +3 -3
- package/src/ledger/check-stats.ts +10 -9
- package/src/ledger/gate-checks.ts +32 -1
- package/src/ledger/record-kept.ts +112 -0
- package/src/ledger/repo-view.ts +10 -0
- package/src/ledger/run-log.ts +17 -12
- package/src/ledger/run-timeline.ts +8 -4
- package/src/ledger/store.ts +7 -0
- package/src/ledger/suite-log.ts +17 -13
- package/src/media-kinds.ts +3 -2
- package/src/media-store/backup/daemon.ts +73 -0
- package/src/media-store/backup/keys.ts +25 -0
- package/src/media-store/backup/manifest.ts +193 -0
- package/src/media-store/backup/restore.ts +192 -0
- package/src/media-store/backup/run.ts +278 -0
- package/src/media-store/backup/secret.ts +86 -0
- package/src/media-store/backup/snapshot.ts +64 -0
- package/src/media-store/backup/sources.ts +199 -0
- package/src/media-store/content.ts +1 -1
- package/src/media-store/daemon.ts +56 -70
- package/src/media-store/db.ts +1 -1
- package/src/media-store/fact.ts +1 -1
- package/src/media-store/hand.ts +1 -1
- package/src/media-store/kind.ts +1 -1
- package/src/media-store/purge.ts +1 -1
- package/src/media-store/put.ts +5 -3
- package/src/media-store/remote.ts +1 -1
- package/src/media-store/space.ts +24 -5
- package/src/mv/mv-md.ts +63 -22
- package/src/pages/forward.ts +35 -0
- package/src/pages/frame-client.ts +118 -0
- package/src/pages/routes.ts +29 -0
- package/src/pages/unit.ts +92 -0
- package/src/plan/planner.ts +12 -0
- package/src/plan/repo-source.ts +19 -5
- package/src/reflect/transcript.ts +35 -10
- package/src/release/public-clean.ts +319 -0
- package/src/release/published-here.ts +22 -0
- package/src/release/run-bump.ts +3 -2
- package/src/release/run-release.ts +7 -4
- package/src/repo-config.ts +71 -13
- package/src/review/anim.ts +1 -1
- package/src/review/auto.ts +1 -1
- package/src/review/cells.ts +15 -1
- package/src/review/format.ts +2 -2
- package/src/review/http.ts +16 -2
- package/src/review/marks.ts +1 -1
- package/src/review/media-kind.ts +1 -1
- package/src/review/media-read.ts +1 -1
- package/src/review/model.ts +27 -6
- package/src/review/notes.ts +125 -0
- package/src/review/previews.ts +1 -1
- package/src/review/project.ts +7 -39
- package/src/review/role.ts +1 -1
- package/src/review/routes.ts +18 -14
- package/src/review/store.ts +42 -2
- package/src/review/threads.ts +1 -1
- package/src/review/trailer-desk.ts +3 -3
- package/src/review/trailer-media.ts +8 -5
- package/src/review/trailer-model.ts +1 -1
- package/src/review/trailer-routes.ts +1 -1
- package/src/review/trailer-shots.ts +22 -5
- package/src/review/unit.ts +2 -2
- package/src/scaffold/files/agent-handoff.md +3 -0
- package/src/scaffold/files/agent-index.md +4 -12
- package/src/scaffold/files/tsconfig.json +1 -1
- package/src/scaffold/project-scaffold.ts +6 -5
- package/src/serve/embed.ts +2 -2
- package/src/serve/hub-app/check-words.ts +1 -1
- package/src/serve/hub-app/col-card.tsx +3 -17
- package/src/serve/hub-app/col-tables-view.tsx +2 -1
- package/src/serve/hub-app/cols-svc.ts +0 -13
- package/src/serve/hub-app/dock-st.ts +4 -2
- package/src/serve/hub-app/dock-view.tsx +2 -0
- package/src/serve/hub-app/frames-st.ts +35 -0
- package/src/serve/hub-app/hash-route.ts +64 -1
- package/src/serve/hub-app/home-st.ts +32 -8
- package/src/serve/hub-app/home-strip.css +9 -1
- package/src/serve/hub-app/home-strip.tsx +7 -6
- package/src/serve/hub-app/home.html +5 -0
- package/src/serve/hub-app/hub-app.tsx +51 -7
- package/src/serve/hub-app/hub.css +29 -11
- package/src/serve/hub-app/icons.tsx +16 -1
- package/src/serve/hub-app/identities-st.ts +210 -0
- package/src/serve/hub-app/identities-view.tsx +353 -0
- package/src/serve/hub-app/identities.css +48 -0
- package/src/serve/hub-app/identity-address.ts +52 -0
- package/src/serve/hub-app/inbox-st.ts +60 -7
- package/src/serve/hub-app/inbox-view.tsx +49 -7
- package/src/serve/hub-app/inbox.css +12 -1
- package/src/serve/hub-app/index.html +3 -0
- package/src/serve/hub-app/kept-cols.tsx +30 -0
- package/src/serve/hub-app/keys.ts +10 -2
- package/src/serve/hub-app/list-walk.ts +89 -0
- package/src/serve/hub-app/machine-st.ts +12 -0
- package/src/serve/hub-app/media-svc.ts +1 -1
- package/src/serve/hub-app/media-view.tsx +2 -1
- package/src/serve/hub-app/pages-frames.tsx +134 -0
- package/src/serve/hub-app/pages-svc.ts +111 -0
- package/src/serve/hub-app/palette-st.ts +18 -3
- package/src/serve/hub-app/palette-view.tsx +9 -2
- package/src/serve/hub-app/planned-view.tsx +2 -1
- package/src/serve/hub-app/project-list.css +18 -14
- package/src/serve/hub-app/project-list.tsx +88 -49
- package/src/serve/hub-app/projects-svc.ts +33 -3
- package/src/serve/hub-app/repo-sections.ts +19 -2
- package/src/serve/hub-app/repo-st.ts +76 -20
- package/src/serve/hub-app/review/review-board.tsx +1 -1
- package/src/serve/hub-app/review/review-cells.tsx +6 -5
- package/src/serve/hub-app/review/review-kit.ts +30 -7
- package/src/serve/hub-app/review/review-page.tsx +6 -5
- package/src/serve/hub-app/review/review-st.ts +34 -15
- package/src/serve/hub-app/review/review-thread.tsx +63 -14
- package/src/serve/hub-app/review/review-views.tsx +133 -51
- package/src/serve/hub-app/review/thread-st.ts +80 -37
- package/src/serve/hub-app/review/trailer-page.tsx +7 -5
- package/src/serve/hub-app/review/trailer-st.ts +1 -1
- package/src/serve/hub-app/review.css +26 -9
- package/src/serve/hub-app/site/site-part.tsx +173 -0
- package/src/serve/hub-app/site/site-st.ts +157 -0
- package/src/serve/hub-app/site.css +35 -0
- package/src/serve/hub-app/social/calendar.tsx +182 -0
- package/src/serve/hub-app/social/comms-page.tsx +330 -0
- package/src/serve/hub-app/social/kit.tsx +244 -0
- package/src/serve/hub-app/social/post-card.tsx +456 -0
- package/src/serve/hub-app/social/problems.tsx +60 -0
- package/src/serve/hub-app/social/social-model.ts +154 -0
- package/src/serve/hub-app/social/social-page.tsx +681 -0
- package/src/serve/hub-app/social/social-st.ts +1014 -0
- package/src/serve/hub-app/social.css +289 -0
- package/src/serve/hub-app/stores/stores-page.tsx +312 -0
- package/src/serve/hub-app/stores/stores-st.ts +286 -0
- package/src/serve/hub-app/stores.css +54 -0
- package/src/serve/hub-app/timeline-geometry.ts +1 -1
- package/src/serve/hub-app/timeline-view.tsx +3 -2
- package/src/serve/hub-app/tree-build.ts +6 -0
- package/src/serve/hub-app/tree-row.tsx +27 -4
- package/src/serve/hub-app/tree-svc.ts +18 -49
- package/src/serve/hub-app/veille/veille-page.tsx +515 -0
- package/src/serve/hub-app/veille/veille-st.ts +443 -0
- package/src/serve/hub-app/veille.css +84 -0
- package/src/serve/hub-runtime.ts +20 -11
- package/src/serve/project-gutter-route.ts +44 -12
- package/src/serve/run-lanes.ts +7 -4
- package/src/serve/same-origin.ts +1 -1
- package/src/serve/serve-hub.ts +20 -12
- package/src/serve/tracked-watch.ts +24 -3
- package/src/serve/warm-cell.ts +5 -1
- package/src/shipkit-files.ts +15 -4
- package/src/shipkit.ts +0 -1
- package/src/shot/box.ts +160 -0
- package/src/shot/browser-slot.ts +74 -0
- package/src/shot/client.ts +42 -7
- package/src/shot/clip-encoder.ts +108 -24
- package/src/shot/film-box.ts +292 -0
- package/src/shot/shooter.ts +71 -17
- package/src/shot/shot-ask.ts +10 -2
- package/src/shot/stepped-clip.ts +5 -4
- package/src/site/desk.ts +242 -0
- package/src/site/routes.ts +66 -0
- package/src/site/unit.ts +62 -0
- package/src/social/brands.ts +22 -0
- package/src/social/card-drafts.ts +24 -0
- package/src/social/compose.ts +97 -0
- package/src/social/desk-index.ts +123 -0
- package/src/social/desk-wire.ts +64 -0
- package/src/social/drafts.ts +183 -0
- package/src/social/house.ts +24 -0
- package/src/social/load.ts +332 -0
- package/src/social/md.ts +70 -0
- package/src/social/media-facts.ts +53 -0
- package/src/social/media-kind.ts +189 -0
- package/src/social/media-limit.ts +42 -0
- package/src/social/media-of.ts +30 -0
- package/src/social/migrate.ts +123 -0
- package/src/social/open.ts +17 -0
- package/src/social/post-url.ts +158 -0
- package/src/social/presence.ts +332 -0
- package/src/social/public-read.ts +53 -0
- package/src/social/publish/bluesky.ts +168 -0
- package/src/social/publish/discord.ts +76 -0
- package/src/social/publish/index.ts +24 -0
- package/src/social/publish/secret.ts +13 -0
- package/src/social/push.ts +37 -0
- package/src/social/richtext.ts +37 -0
- package/src/social/routes.ts +186 -0
- package/src/social/stats.ts +134 -0
- package/src/social/text.ts +267 -0
- package/src/social/tracker-route.ts +39 -0
- package/src/social/tracker.ts +255 -0
- package/src/social/unit.ts +53 -0
- package/src/social/writes.ts +130 -0
- package/src/start-repo.ts +14 -9
- package/src/stores/collection.ts +27 -0
- package/src/stores/desk.ts +336 -0
- package/src/stores/model.ts +187 -0
- package/src/stores/routes.ts +126 -0
- package/src/stores/unit.ts +57 -0
- package/src/suite/calibrate.ts +127 -0
- package/src/suite/core-counters.ts +91 -0
- package/src/suite/judge-suites.ts +95 -35
- package/src/suite/suite-cli.ts +44 -10
- package/src/suite/suite-cpu-preload.ts +34 -9
- package/src/trace/tracer.ts +12 -5
- package/src/trailer/adapter.ts +5 -1
- package/src/trailer/build.ts +45 -12
- package/src/trailer/ffmpeg.ts +11 -0
- package/src/trailer/footage.ts +30 -13
- package/src/trailer/grammar.ts +18 -2
- package/src/trailer/graph.ts +28 -6
- package/src/trailer/holes.ts +1 -1
- package/src/trailer/passage.ts +18 -6
- package/src/trailer/plan.ts +74 -3
- package/src/trailer/prune.ts +1 -1
- package/src/trailer/states.ts +1 -1
- package/src/trailer/stitch.ts +67 -26
- package/src/trailer/url.ts +1 -1
- package/src/trailer/versions.ts +24 -0
- package/src/trailer/words.ts +1 -1
- package/src/ts/gate-typecheck.ts +32 -0
- package/src/ts/typecheck-cli.ts +9 -11
- package/src/tui/run-tui.ts +1 -1
- package/src/tui/tui-app.tsx +0 -1
- package/src/tui/tui-store.ts +1 -1
- package/src/veille/asks.ts +155 -0
- package/src/veille/auto.ts +31 -0
- package/src/veille/batch.ts +27 -0
- package/src/veille/chrome.ts +127 -0
- package/src/veille/collection.ts +28 -0
- package/src/veille/desk.ts +242 -0
- package/src/veille/identity.ts +80 -0
- package/src/veille/import.ts +68 -0
- package/src/veille/log.ts +183 -0
- package/src/veille/platforms.ts +118 -0
- package/src/veille/reads.ts +66 -0
- package/src/veille/replied.ts +110 -0
- package/src/veille/routes.ts +185 -0
- package/src/veille/service.ts +81 -0
- package/src/veille/watch.ts +116 -0
- package/src/veille/worth.ts +46 -0
- package/src/wiki/scan-md.ts +18 -0
- package/src/collections/posts.ts +0 -142
- package/src/contracts/manifests/social.contract.ts +0 -20
- package/src/scaffold/files/agent-coding.md +0 -35
- package/src/ts/typecheck-cache.ts +0 -11
|
@@ -0,0 +1,332 @@
|
|
|
1
|
+
// what an identity posted, where and when (wiki tools/shipkit/social.md, `sk social`), and what comes next (the rhythm):
|
|
2
|
+
// every posted line of the drafts as one post, with its family and its moment, the moment's source said; the slots of
|
|
3
|
+
// the week and the drafts that take them. Pure over what loadSocial read and a `today` given, never the clock
|
|
4
|
+
import type { Topic } from './drafts.ts'
|
|
5
|
+
import { mkdirSync, readFileSync } from 'node:fs'
|
|
6
|
+
import { join } from 'node:path'
|
|
7
|
+
import { headCommit } from '../core/git-root.ts'
|
|
8
|
+
import { LAYOUT } from '../core/layout.ts'
|
|
9
|
+
import { atomicWrite } from '../core/locked-write.ts'
|
|
10
|
+
import { postTime } from './post-url.ts'
|
|
11
|
+
import type { Account } from '../identities/identities.ts'
|
|
12
|
+
import type { Desk, SocialPost } from './load.ts'
|
|
13
|
+
|
|
14
|
+
/** `feed`: the accounts of the group `short` (X, Threads, Bluesky, Mastodon, Discord); `shorts`: the group `vertical`
|
|
15
|
+
* (TikTok, Instagram, YouTube); `other`: every account outside both */
|
|
16
|
+
export type Family = 'feed' | 'shorts' | 'other'
|
|
17
|
+
export const FAMILIES: readonly Family[] = ['feed', 'shorts', 'other']
|
|
18
|
+
export const familyOf = (a: Pick<Account, 'group'>): Family => (a.group === 'short' ? 'feed' : a.group === 'vertical' ? 'shorts' : 'other')
|
|
19
|
+
|
|
20
|
+
/** where a moment came from: the post's id, the commit that recorded it, a devlog post's `date`, nowhere */
|
|
21
|
+
type Source = 'id' | 'commit' | 'page' | 'unknown'
|
|
22
|
+
|
|
23
|
+
/** one message on one account, posted */
|
|
24
|
+
export type Sent = {
|
|
25
|
+
platform: string
|
|
26
|
+
/** its key under `## Posted`, `<platform>[/<name>]` */
|
|
27
|
+
key: string
|
|
28
|
+
slug: string
|
|
29
|
+
url: string
|
|
30
|
+
kind: string
|
|
31
|
+
topics: Topic[]
|
|
32
|
+
tags: string[]
|
|
33
|
+
family: Family
|
|
34
|
+
/** ms since 1970, null when no source knows */
|
|
35
|
+
at: number | null
|
|
36
|
+
source: Source
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
type Draft = Desk['drafts'][number]
|
|
40
|
+
/** what the model reads of a draft */
|
|
41
|
+
export type DraftIn = Pick<Draft, 'slug' | 'kind' | 'topics' | 'status'> & {
|
|
42
|
+
article: Pick<NonNullable<Draft['article']>, 'draft' | 'date' | 'url'> | null
|
|
43
|
+
posts: readonly Pick<SocialPost, 'platform' | 'key' | 'posted' | 'tags'>[]
|
|
44
|
+
}
|
|
45
|
+
/** what the model reads of the social folder */
|
|
46
|
+
export type SocialIn = { accounts: readonly Pick<Account, 'id' | 'group'>[]; drafts: readonly DraftIn[] }
|
|
47
|
+
|
|
48
|
+
const POSTED_COMMIT = /^social: \S+ is posted, (\S+)$/
|
|
49
|
+
|
|
50
|
+
/** the posts' commits git found since a day, at the commit HEAD named then, per repo and day; kept in the repo's
|
|
51
|
+
* `.shipkit/cache/social-moments-<day>.json` too, so a process that starts walks only the commits since */
|
|
52
|
+
type Log = { since: string; head: string; at: Map<string, number> }
|
|
53
|
+
const logs = new Map<string, Log>()
|
|
54
|
+
const logFile = (repo: string, since: string): string => join(repo, LAYOUT.cache, `social-moments-${since}.json`)
|
|
55
|
+
|
|
56
|
+
function keptLog(repo: string, since: string): Log | null {
|
|
57
|
+
const mem = logs.get(`${repo}\0${since}`)
|
|
58
|
+
if (mem) return mem
|
|
59
|
+
try {
|
|
60
|
+
const f = JSON.parse(readFileSync(logFile(repo, since), 'utf8')) as { head: string; at: [string, number][] }
|
|
61
|
+
return { since, head: f.head, at: new Map(f.at) }
|
|
62
|
+
} catch {
|
|
63
|
+
return null
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
function keepLog(repo: string, log: Log): void {
|
|
68
|
+
logs.set(`${repo}\0${log.since}`, log)
|
|
69
|
+
try {
|
|
70
|
+
mkdirSync(join(repo, LAYOUT.cache), { recursive: true })
|
|
71
|
+
atomicWrite(logFile(repo, log.since), JSON.stringify({ head: log.head, at: [...log.at] }))
|
|
72
|
+
} catch {
|
|
73
|
+
// a cache: the next process walks the log again
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/** the posted commits since `since` from `range` (newest first), each url at its oldest commit */
|
|
78
|
+
function postedCommits(repo: string, since: string, range: string[]): Map<string, number> {
|
|
79
|
+
const r = Bun.spawnSync(['git', 'log', `--since=${since}`, '--format=%at %s', '--grep=^social: .* is posted, ', ...range], { cwd: repo, stdout: 'pipe', stderr: 'pipe' })
|
|
80
|
+
if (r.exitCode !== 0) throw new Error(`git log in ${repo}: ${r.stderr.toString().trim()}`)
|
|
81
|
+
const out = new Map<string, number>()
|
|
82
|
+
for (const line of r.stdout.toString().split('\n')) {
|
|
83
|
+
const i = line.indexOf(' ')
|
|
84
|
+
const url = POSTED_COMMIT.exec(line.slice(i + 1))?.[1]
|
|
85
|
+
if (url != null) out.set(url, Number(line.slice(0, i)) * 1000)
|
|
86
|
+
}
|
|
87
|
+
return out
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/** the moment of the first commit that recorded each post whose id holds no time: « social: <key>/<draft> is posted,
|
|
91
|
+
* <url> »; git walks only from the day before the oldest such draft was made, and not at all when none is. Kept per
|
|
92
|
+
* HEAD in a long lived process: a new HEAD walks only the commits it adds */
|
|
93
|
+
export function commitMoments(social: Pick<SocialIn, 'drafts'>, repo: string): Map<string, number> {
|
|
94
|
+
const made = social.drafts.filter((d) => d.posts.some((p) => p.posted !== '' && postTime(p.platform, p.posted) == null)).map((d) => d.slug.slice(0, 8))
|
|
95
|
+
if (made.length === 0) return new Map()
|
|
96
|
+
const first = made.sort()[0]!
|
|
97
|
+
const since = dayBefore(`${first.slice(0, 4)}-${first.slice(4, 6)}-${first.slice(6, 8)}`)
|
|
98
|
+
const head = headCommit(repo)
|
|
99
|
+
if (head == null) return postedCommits(repo, since, [])
|
|
100
|
+
const was = keptLog(repo, since)
|
|
101
|
+
if (was?.head === head) {
|
|
102
|
+
logs.set(`${repo}\0${since}`, was)
|
|
103
|
+
return was.at
|
|
104
|
+
}
|
|
105
|
+
// the commits HEAD adds are newer than every one held, so a url held keeps its older commit
|
|
106
|
+
const on = was != null && Bun.spawnSync(['git', 'merge-base', '--is-ancestor', was.head, head], { cwd: repo }).exitCode === 0
|
|
107
|
+
const at = on ? new Map([...postedCommits(repo, since, [head, `^${was.head}`]), ...was.at]) : postedCommits(repo, since, [head])
|
|
108
|
+
keepLog(repo, { since, head, at })
|
|
109
|
+
return at
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/** a draft's devlog post.md is posted on the site once out of draft; its day is the post's `date` */
|
|
113
|
+
const sitePost = (d: DraftIn): DraftIn['article'] => (d.article != null && !d.article.draft && /^\d{4}-\d{2}-\d{2}$/.test(d.article.date) ? d.article : null)
|
|
114
|
+
|
|
115
|
+
/** every posted message of every draft, oldest first; the undated last */
|
|
116
|
+
export function postedOf(social: SocialIn, moments: ReadonlyMap<string, number>): Sent[] {
|
|
117
|
+
const family = new Map(social.accounts.map((a) => [a.id, familyOf(a)]))
|
|
118
|
+
const out: Sent[] = []
|
|
119
|
+
for (const d of social.drafts) {
|
|
120
|
+
for (const p of d.posts) {
|
|
121
|
+
if (p.posted === '') continue
|
|
122
|
+
const fromId = postTime(p.platform, p.posted)
|
|
123
|
+
const fromCommit = moments.get(p.posted)
|
|
124
|
+
const [at, source]: [number | null, Source] = fromId != null ? [fromId, 'id'] : fromCommit != null ? [fromCommit, 'commit'] : [null, 'unknown']
|
|
125
|
+
out.push({ platform: p.platform, key: p.key, slug: d.slug, url: p.posted, kind: d.kind, topics: d.topics, tags: p.tags, family: family.get(p.platform) ?? 'other', at, source })
|
|
126
|
+
}
|
|
127
|
+
const a = sitePost(d)
|
|
128
|
+
if (a != null)
|
|
129
|
+
out.push({ platform: 'site', key: 'site', slug: d.slug, url: a.url, kind: d.kind, topics: d.topics, tags: [], family: family.get('site') ?? 'other', at: Date.parse(`${a.date}T12:00:00Z`), source: 'page' })
|
|
130
|
+
}
|
|
131
|
+
return out.sort((x, y) => (x.at ?? Infinity) - (y.at ?? Infinity) || x.platform.localeCompare(y.platform))
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/** the desk's days: Paris, where he posts from */
|
|
135
|
+
const DAY = new Intl.DateTimeFormat('en-CA', { timeZone: 'Europe/Paris', year: 'numeric', month: '2-digit', day: '2-digit' })
|
|
136
|
+
|
|
137
|
+
/** a moment's day, `YYYY-MM-DD`, in the desk's time zone */
|
|
138
|
+
export const dayOf = (ms: number): string => DAY.format(ms)
|
|
139
|
+
|
|
140
|
+
const dayMs = (day: string): number => Date.parse(`${day}T00:00:00Z`)
|
|
141
|
+
|
|
142
|
+
/** whole days from `a` to `b` */
|
|
143
|
+
export const daysBetween = (a: string, b: string): number => Math.round((dayMs(b) - dayMs(a)) / 86_400_000)
|
|
144
|
+
|
|
145
|
+
const dayBefore = (day: string): string => new Date(dayMs(day) - 86_400_000).toISOString().slice(0, 10)
|
|
146
|
+
|
|
147
|
+
/** every day from `a` to `b`, both in */
|
|
148
|
+
export function dayRange(a: string, b: string): string[] {
|
|
149
|
+
const out: string[] = []
|
|
150
|
+
for (let t = dayMs(a); t <= dayMs(b); t += 86_400_000) out.push(new Date(t).toISOString().slice(0, 10))
|
|
151
|
+
return out
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/** the weekday's letter of a day, M T W T F S S */
|
|
155
|
+
export const weekday = (day: string): string => 'SMTWTFS'[new Date(dayMs(day)).getUTCDay()]!
|
|
156
|
+
|
|
157
|
+
type Rhythm = {
|
|
158
|
+
/** the days with at least one post */
|
|
159
|
+
days: string[]
|
|
160
|
+
/** the run of days with a post that ends on `today`, or on the day before (today may still come) */
|
|
161
|
+
streak: number
|
|
162
|
+
/** the longest stretch of days with no post between two days with one, and its ends */
|
|
163
|
+
gap: { days: number; from: string; to: string } | null
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/** the days of the posts, and how they run up to `today` */
|
|
167
|
+
export function rhythm(sent: readonly Pick<Sent, 'at'>[], today: string): Rhythm {
|
|
168
|
+
const days = [...new Set(sent.flatMap((s) => (s.at == null ? [] : [dayOf(s.at)])))].sort()
|
|
169
|
+
const set = new Set(days)
|
|
170
|
+
let end = set.has(today) ? today : dayBefore(today)
|
|
171
|
+
let streak = 0
|
|
172
|
+
while (set.has(end)) {
|
|
173
|
+
streak++
|
|
174
|
+
end = dayBefore(end)
|
|
175
|
+
}
|
|
176
|
+
let gap: Rhythm['gap'] = null
|
|
177
|
+
for (let i = 1; i < days.length; i++) {
|
|
178
|
+
const quiet = daysBetween(days[i - 1]!, days[i]!) - 1
|
|
179
|
+
if (quiet > 0 && (gap == null || quiet > gap.days)) gap = { days: quiet, from: days[i - 1]!, to: days[i]! }
|
|
180
|
+
}
|
|
181
|
+
return { days, streak, gap }
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
/** how many of each key, the most first, then by name */
|
|
185
|
+
export function countBy<T>(items: readonly T[], keys: (t: T) => readonly string[]): [string, number][] {
|
|
186
|
+
const n = new Map<string, number>()
|
|
187
|
+
for (const t of items) for (const k of keys(t)) n.set(k, (n.get(k) ?? 0) + 1)
|
|
188
|
+
return [...n].sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]))
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
/** the drafts with no message posted anywhere, rejected ones aside; the newest first */
|
|
192
|
+
export const unposted = <D extends Pick<DraftIn, 'slug' | 'status'>>(social: { drafts: readonly D[] }, sent: readonly Pick<Sent, 'slug'>[]): D[] => {
|
|
193
|
+
const done = new Set(sent.map((s) => s.slug))
|
|
194
|
+
return social.drafts.filter((d) => d.status !== 'rejected' && !done.has(d.slug))
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
/** a topic's drafts: posted in each family (a draft counts once a family), written and posted nowhere */
|
|
198
|
+
type CoverageRow = { topic: Topic; families: Record<Family, number>; waiting: number }
|
|
199
|
+
|
|
200
|
+
export function coverage(social: { drafts: readonly DraftIn[]; topics: readonly Topic[] }, sent: readonly Sent[]): CoverageRow[] {
|
|
201
|
+
const waiting = unposted(social, sent)
|
|
202
|
+
return social.topics.map((topic) => {
|
|
203
|
+
const n = (f: Family): number => new Set(sent.filter((s) => s.family === f && s.topics.includes(topic)).map((s) => s.slug)).size
|
|
204
|
+
return { topic, families: { feed: n('feed'), shorts: n('shorts'), other: n('other') }, waiting: waiting.filter((d) => d.topics.includes(topic)).length }
|
|
205
|
+
})
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
const WEEKDAYS = ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday'] as const
|
|
209
|
+
type Weekday = (typeof WEEKDAYS)[number]
|
|
210
|
+
|
|
211
|
+
/** one row of `.shipkit/social/rhythm.md`: a slot of the week he wants, on a weekday or once in the week */
|
|
212
|
+
export type WeeklySlot = { tag: string; day: Weekday | 'week'; time: string; what: string }
|
|
213
|
+
/** a draft's frontmatter `slot`: the day it is planned for and the slot's tag */
|
|
214
|
+
export type Slot = { day: string; tag: string }
|
|
215
|
+
|
|
216
|
+
const SLOT_TAG = /^[a-z0-9-]+$/
|
|
217
|
+
const HOUR = /^(?:[01]\d|2[0-3]):[0-5]\d$/
|
|
218
|
+
|
|
219
|
+
const addDays = (day: string, n: number): string => new Date(dayMs(day) + n * 86_400_000).toISOString().slice(0, 10)
|
|
220
|
+
const isDay = (s: string): boolean => /^\d{4}-\d{2}-\d{2}$/.test(s) && !Number.isNaN(dayMs(s)) && addDays(s, 0) === s
|
|
221
|
+
const weekdayOf = (day: string): Weekday => WEEKDAYS[new Date(dayMs(day)).getUTCDay()]!
|
|
222
|
+
/** the Monday that opens a day's week */
|
|
223
|
+
export const mondayOf = (day: string): string => addDays(day, -((new Date(dayMs(day)).getUTCDay() + 6) % 7))
|
|
224
|
+
|
|
225
|
+
/** the `## Slots` table of rhythm.md, its body rows as cells (`tag`, `day`, `time`, `what`); a row that does not read
|
|
226
|
+
* is an error at its file */
|
|
227
|
+
export function weeklySlots(rows: readonly (readonly string[])[], file: string, errors: string[]): WeeklySlot[] {
|
|
228
|
+
const out: WeeklySlot[] = []
|
|
229
|
+
for (const [tag = '', day = '', time = '', what = ''] of rows) {
|
|
230
|
+
const d = day.toLowerCase()
|
|
231
|
+
const on = d === 'week' ? d : WEEKDAYS.find((w) => w === d)
|
|
232
|
+
const at = `${file}: slot "${tag}"`
|
|
233
|
+
if (!SLOT_TAG.test(tag)) errors.push(`${at}: its tag is not kebab case`)
|
|
234
|
+
else if (out.some((x) => x.tag === tag)) errors.push(`${at} twice`)
|
|
235
|
+
else if (on == null) errors.push(`${at}: day "${day}" is neither a weekday (monday … sunday) nor week`)
|
|
236
|
+
else if (time !== '' && !HOUR.test(time)) errors.push(`${at}: time "${time}" is not HH:MM`)
|
|
237
|
+
else out.push({ tag, day: on, time, what })
|
|
238
|
+
}
|
|
239
|
+
return out
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
/** a draft's `slot: <YYYY-MM-DD> <tag>`; null when unset or wrong, the wrong one an error at its file */
|
|
243
|
+
export function slotOf(v: string | undefined, file: string, weekly: readonly WeeklySlot[], errors: string[]): Slot | null {
|
|
244
|
+
if (v == null || v.trim() === '') return null
|
|
245
|
+
const m = /^(\S+)\s+(\S+)$/.exec(v.trim())
|
|
246
|
+
const at = `${file}: slot "${v.trim()}"`
|
|
247
|
+
if (m == null || !isDay(m[1]!)) {
|
|
248
|
+
errors.push(`${at} is not "<YYYY-MM-DD> <tag>"`)
|
|
249
|
+
return null
|
|
250
|
+
}
|
|
251
|
+
const [, day = '', tag = ''] = m
|
|
252
|
+
const w = weekly.find((x) => x.tag === tag)
|
|
253
|
+
if (w == null) errors.push(`${at}: no slot "${tag}" in .shipkit/social/rhythm.md (${weekly.map((x) => x.tag).join(', ') || 'none'})`)
|
|
254
|
+
else if (w.day !== 'week' && weekdayOf(day) !== w.day) errors.push(`${at}: ${day} is a ${weekdayOf(day)}, the slot is on ${w.day}`)
|
|
255
|
+
else return { day, tag }
|
|
256
|
+
return null
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
/** a slot of the rhythm on one day: a weekday slot on its day, a `week` slot on its week's Monday; the drafts taking it */
|
|
260
|
+
export type SlotDay = { day: string; slot: WeeklySlot; drafts: string[] }
|
|
261
|
+
type SlottedIn = Pick<DraftIn, 'slug' | 'status'> & { slot: Slot | null }
|
|
262
|
+
|
|
263
|
+
/** every slot the days from `from` to `to` hold, by day, a week's slot first on its Monday */
|
|
264
|
+
export function slotDays(weekly: readonly WeeklySlot[], drafts: readonly SlottedIn[], from: string, to: string): SlotDay[] {
|
|
265
|
+
const taking = (s: WeeklySlot, on: (d: Slot) => boolean): string[] => drafts.filter((d) => d.status !== 'rejected' && d.slot?.tag === s.tag && on(d.slot)).map((d) => d.slug)
|
|
266
|
+
const days = dayRange(from, to)
|
|
267
|
+
const out: SlotDay[] = []
|
|
268
|
+
for (const monday of new Set(days.map(mondayOf)))
|
|
269
|
+
for (const s of weekly) if (s.day === 'week') out.push({ day: monday, slot: s, drafts: taking(s, (x) => mondayOf(x.day) === monday) })
|
|
270
|
+
for (const day of days) for (const s of weekly) if (s.day === weekdayOf(day)) out.push({ day, slot: s, drafts: taking(s, (x) => x.day === day) })
|
|
271
|
+
return out.sort((a, b) => a.day.localeCompare(b.day) || Number(b.slot.day === 'week') - Number(a.slot.day === 'week'))
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
/** the week ahead: its slots, the slotted drafts whose day passed with nothing posted, the drafts ready with no slot
|
|
275
|
+
* (posted nowhere, not rejected), picked first, then the newest */
|
|
276
|
+
export type Plan = { from: string; to: string; slots: SlotDay[]; missed: string[]; ready: string[] }
|
|
277
|
+
|
|
278
|
+
export function planOf(social: { weekly: readonly WeeklySlot[]; drafts: readonly SlottedIn[] }, sent: readonly Pick<Sent, 'slug'>[], today: string, n = 7): Plan {
|
|
279
|
+
const to = addDays(today, n - 1)
|
|
280
|
+
const waiting = unposted(social, sent)
|
|
281
|
+
return {
|
|
282
|
+
from: today,
|
|
283
|
+
to,
|
|
284
|
+
slots: slotDays(social.weekly, social.drafts, today, to),
|
|
285
|
+
missed: waiting.filter((d) => d.slot != null && d.slot.day < today).map((d) => d.slug),
|
|
286
|
+
ready: waiting
|
|
287
|
+
.filter((d) => d.slot == null)
|
|
288
|
+
.sort((a, b) => Number(b.status === 'picked') - Number(a.status === 'picked') || b.slug.localeCompare(a.slug))
|
|
289
|
+
.map((d) => d.slug),
|
|
290
|
+
}
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
/** a dot of the calendar: a post on its day, or (planned) a slotted draft's message still to post, on its slot's day */
|
|
294
|
+
export type Mark = { day: string; slug: string; kind: string; planned: boolean }
|
|
295
|
+
type Topics = { topic: Topic; n: number }[]
|
|
296
|
+
/** the Communications desk's calendar (wiki tools/shipkit/social.md): four weeks a row an account, the slots, the topics of
|
|
297
|
+
* the last 14 days by family, the week ahead */
|
|
298
|
+
export type Timeline = { today: string; days: string[]; rows: { account: string; family: Family; marks: Mark[] }[]; slots: SlotDay[]; topics: Record<'all' | Family, Topics>; plan: Plan }
|
|
299
|
+
|
|
300
|
+
type TimelineIn = {
|
|
301
|
+
topics: readonly Topic[]
|
|
302
|
+
accounts: readonly Pick<Account, 'id' | 'group' | 'live'>[]
|
|
303
|
+
weekly: readonly WeeklySlot[]
|
|
304
|
+
drafts: readonly (SlottedIn & Pick<DraftIn, 'kind'> & { posts: readonly Pick<SocialPost, 'platform' | 'posted'>[] })[]
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
/** the 20 days before `today`, today and the 7 after */
|
|
308
|
+
export function timelineOf(social: TimelineIn, sent: readonly Sent[], today: string): Timeline {
|
|
309
|
+
const days = dayRange(addDays(today, -20), addDays(today, 7))
|
|
310
|
+
const inside = new Set(days)
|
|
311
|
+
const marks = new Map<string, Mark[]>()
|
|
312
|
+
const add = (platform: string, m: Mark): void => void marks.set(platform, [...(marks.get(platform) ?? []), m])
|
|
313
|
+
for (const s of sent) if (s.at != null && inside.has(dayOf(s.at))) add(s.platform, { day: dayOf(s.at), slug: s.slug, kind: s.kind, planned: false })
|
|
314
|
+
for (const d of social.drafts)
|
|
315
|
+
if (d.slot != null && d.status !== 'rejected' && inside.has(d.slot.day))
|
|
316
|
+
for (const p of d.posts) if (p.posted === '') add(p.platform, { day: d.slot.day, slug: d.slug, kind: d.kind, planned: true })
|
|
317
|
+
const rows = social.accounts
|
|
318
|
+
.filter((a) => marks.has(a.id) || (familyOf(a) !== 'other' && a.live !== ''))
|
|
319
|
+
.sort((a, b) => FAMILIES.indexOf(familyOf(a)) - FAMILIES.indexOf(familyOf(b)))
|
|
320
|
+
.map((a) => ({ account: a.id, family: familyOf(a), marks: marks.get(a.id) ?? [] }))
|
|
321
|
+
const recent = new Set(dayRange(addDays(today, -13), today))
|
|
322
|
+
const topics = (f: Family | null): Topics =>
|
|
323
|
+
social.topics.map((topic) => ({ topic, n: new Set(sent.filter((s) => s.at != null && recent.has(dayOf(s.at)) && (f == null || s.family === f) && s.topics.includes(topic)).map((s) => s.slug)).size }))
|
|
324
|
+
return {
|
|
325
|
+
today,
|
|
326
|
+
days,
|
|
327
|
+
rows,
|
|
328
|
+
slots: slotDays(social.weekly, social.drafts, days[0]!, days.at(-1)!).filter((x) => x.slot.day !== 'week'),
|
|
329
|
+
topics: { all: topics(null), feed: topics('feed'), shorts: topics('shorts'), other: topics('other') },
|
|
330
|
+
plan: planOf(social, sent, today),
|
|
331
|
+
}
|
|
332
|
+
}
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import type { Account } from '../identities/identities.ts'
|
|
2
|
+
|
|
3
|
+
// the public read APIs of Mastodon and Bluesky (wiki tools/shipkit/social.md, The post tracker): the account's latest
|
|
4
|
+
// posts, logged out, read only. Nothing here logs in, writes, or goes near the browser
|
|
5
|
+
|
|
6
|
+
export type PublicPost = { url: string; at: number }
|
|
7
|
+
|
|
8
|
+
/** after an open: the times the desk reads the account again, then never */
|
|
9
|
+
export const POLL_AT_MS = [20, 40, 60, 120, 180, 300, 420, 600].map((s) => s * 1000)
|
|
10
|
+
|
|
11
|
+
const TIMEOUT_MS = 5000
|
|
12
|
+
|
|
13
|
+
async function getJson<T>(url: string): Promise<T> {
|
|
14
|
+
const r = await fetch(url, { signal: AbortSignal.timeout(TIMEOUT_MS), headers: { accept: 'application/json' } })
|
|
15
|
+
if (!r.ok) throw new Error(`${new URL(url).host}: HTTP ${r.status}`)
|
|
16
|
+
return (await r.json()) as T
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
const mastodonIds = new Map<string, string>()
|
|
20
|
+
|
|
21
|
+
/** `@user@instance`: its own posts, no boost */
|
|
22
|
+
async function mastodon(handle: string): Promise<PublicPost[]> {
|
|
23
|
+
const [user = '', host = ''] = handle.replace(/^@/, '').split('@')
|
|
24
|
+
if (user === '' || host === '') throw new Error(`Mastodon handle ${handle}?`)
|
|
25
|
+
let id = mastodonIds.get(handle)
|
|
26
|
+
if (id == null) {
|
|
27
|
+
id = (await getJson<{ id: string }>(`https://${host}/api/v1/accounts/lookup?acct=${encodeURIComponent(user)}`)).id
|
|
28
|
+
mastodonIds.set(handle, id)
|
|
29
|
+
}
|
|
30
|
+
const list = await getJson<{ url: string; created_at: string; reblog: unknown }[]>(`https://${host}/api/v1/accounts/${id}/statuses?limit=10&exclude_reblogs=true`)
|
|
31
|
+
return list.filter((s) => s.reblog == null).map((s) => ({ url: s.url, at: Date.parse(s.created_at) }))
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
type BskyItem = { post: { uri: string; author: { handle: string }; record: { createdAt?: string } }; reason?: unknown }
|
|
35
|
+
|
|
36
|
+
/** its own posts, no repost, no reply */
|
|
37
|
+
async function bluesky(handle: string): Promise<PublicPost[]> {
|
|
38
|
+
const h = handle.replace(/^@/, '')
|
|
39
|
+
const r = await getJson<{ feed: BskyItem[] }>(`https://public.api.bsky.app/xrpc/app.bsky.feed.getAuthorFeed?actor=${encodeURIComponent(h)}&limit=10&filter=posts_no_replies`)
|
|
40
|
+
return r.feed
|
|
41
|
+
.filter((i) => i.reason == null && i.post.author.handle === h)
|
|
42
|
+
.map((i) => ({ url: `https://bsky.app/profile/${h}/post/${i.post.uri.split('/').pop() ?? ''}`, at: Date.parse(i.post.record.createdAt ?? '') }))
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** the platforms the desk reads on its own after an open */
|
|
46
|
+
const PUBLIC_READ: Readonly<Record<string, (handle: string) => Promise<PublicPost[]>>> = { mastodon, bluesky }
|
|
47
|
+
|
|
48
|
+
/** the account's latest posts, newest first as the platform gives them; null for a platform with no public read */
|
|
49
|
+
export function publicPosts(a: Pick<Account, 'id' | 'handle'>): Promise<PublicPost[]> | null {
|
|
50
|
+
return PUBLIC_READ[a.id]?.(a.handle) ?? null
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export const hasPublicRead = (platform: string): boolean => platform in PUBLIC_READ
|
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
// a draft's message posted to Bluesky as the identity's account (wiki tools/shipkit/social.md, Publishing): its links
|
|
2
|
+
// and #tags live, a picture shrunk under 1 MB or a clip through the video service the way Bluesky's own app sends one
|
|
3
|
+
import { mkdirSync, statSync } from 'node:fs'
|
|
4
|
+
import { tmpdir } from 'node:os'
|
|
5
|
+
import { join } from 'node:path'
|
|
6
|
+
import type { Account } from '../../identities/identities.ts'
|
|
7
|
+
import { probeMedia } from '../../trailer/ffmpeg.ts'
|
|
8
|
+
import { richText } from '../richtext.ts'
|
|
9
|
+
import type { SocialPost } from '../load.ts'
|
|
10
|
+
import { secret } from './secret.ts'
|
|
11
|
+
|
|
12
|
+
const PDS = 'https://bsky.social/xrpc'
|
|
13
|
+
const VIDEO = 'https://video.bsky.app/xrpc'
|
|
14
|
+
const VIDEO_DID = 'did:web:video.bsky.app'
|
|
15
|
+
/** Bluesky refuses an image blob over 1 000 000 bytes */
|
|
16
|
+
const MAX_IMAGE = 950_000
|
|
17
|
+
/** the video service's limits, as Bluesky's app holds them (src/lib/constants.ts there): 300 MB, 10 minutes */
|
|
18
|
+
const MAX_VIDEO = 300_000_000
|
|
19
|
+
const MAX_VIDEO_S = 600
|
|
20
|
+
/** a video's alt, at most (app.bsky.embed.video) */
|
|
21
|
+
const MAX_VIDEO_ALT = 1000
|
|
22
|
+
const IMAGE = /\.(png|jpe?g|webp)$/i
|
|
23
|
+
const CLIPS: Readonly<Record<string, string>> = { mp4: 'video/mp4', webm: 'video/webm', mov: 'video/quicktime', mpeg: 'video/mpeg' }
|
|
24
|
+
|
|
25
|
+
/** what the network calls go through: the real fetch and clock, or a test's */
|
|
26
|
+
export type Net = { fetch: (url: string, init?: RequestInit) => Promise<Response>; wait: (ms: number) => Promise<void> }
|
|
27
|
+
const NET: Net = { fetch: (url, init) => fetch(url, init), wait: (ms) => Bun.sleep(ms) }
|
|
28
|
+
|
|
29
|
+
export type Session = { did: string; accessJwt: string; handle: string; /** the account's own PDS, the audience of a service token */ pds: string }
|
|
30
|
+
|
|
31
|
+
async function call<T>(net: Net, url: string, init: RequestInit, timeout = 20_000): Promise<T> {
|
|
32
|
+
const r = await net.fetch(url, { ...init, signal: AbortSignal.timeout(timeout) })
|
|
33
|
+
if (!r.ok) throw new Error(`bluesky ${url.replace(/\?.*/, '')}: ${r.status} ${await r.text()}`)
|
|
34
|
+
return (await r.json()) as T
|
|
35
|
+
}
|
|
36
|
+
const xrpc = <T>(net: Net, method: string, body: BodyInit, headers: Record<string, string>, timeout?: number): Promise<T> =>
|
|
37
|
+
call<T>(net, `${PDS}/${method}`, { method: 'POST', body, headers }, timeout)
|
|
38
|
+
|
|
39
|
+
/** the account's session, and its PDS from its did document */
|
|
40
|
+
async function login(a: Account, net: Net = NET): Promise<Session> {
|
|
41
|
+
const handle = a.handle.replace(/^@/, '')
|
|
42
|
+
const s = await xrpc<{ did: string; accessJwt: string; didDoc?: { service?: { id: string; serviceEndpoint: string }[] } }>(
|
|
43
|
+
net,
|
|
44
|
+
'com.atproto.server.createSession',
|
|
45
|
+
JSON.stringify({ identifier: handle, password: await secret(a.secret, `${a.file}: secret`) }),
|
|
46
|
+
{ 'Content-Type': 'application/json' },
|
|
47
|
+
)
|
|
48
|
+
const pds = s.didDoc?.service?.find((x) => x.id === '#atproto_pds')?.serviceEndpoint
|
|
49
|
+
if (pds == null) throw new Error('bluesky: the session names no PDS in its did document')
|
|
50
|
+
return { did: s.did, accessJwt: s.accessJwt, handle, pds }
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** the picture as Bluesky takes it: as it is when small enough, else a jpeg shrunk until it fits */
|
|
54
|
+
function image(file: string): { data: Blob; mime: string; w: number; h: number } {
|
|
55
|
+
const size = (f: string): [number, number] => {
|
|
56
|
+
const p = Bun.spawnSync(['magick', 'identify', '-format', '%w %h', `${f}[0]`], { stdout: 'pipe', stderr: 'pipe' })
|
|
57
|
+
if (p.exitCode !== 0) throw new Error(`magick identify ${f}: ${p.stderr.toString()}`)
|
|
58
|
+
const [w = 0, h = 0] = p.stdout.toString().split(' ').map(Number)
|
|
59
|
+
return [w, h]
|
|
60
|
+
}
|
|
61
|
+
if (!IMAGE.test(file)) throw new Error(`bluesky: ${file} is no picture (png, jpg, webp)`)
|
|
62
|
+
const mime = /\.png$/i.test(file) ? 'image/png' : /\.webp$/i.test(file) ? 'image/webp' : 'image/jpeg'
|
|
63
|
+
if (statSync(file).size <= MAX_IMAGE) {
|
|
64
|
+
const [w, h] = size(file)
|
|
65
|
+
return { data: Bun.file(file), mime, w, h }
|
|
66
|
+
}
|
|
67
|
+
const dir = join(tmpdir(), 'shipkit-social')
|
|
68
|
+
mkdirSync(dir, { recursive: true })
|
|
69
|
+
const out = join(dir, `bluesky-upload-${process.pid}.jpg`)
|
|
70
|
+
for (const [edge, q] of [[2000, 90], [2000, 80], [1600, 80], [1200, 75]] as const) {
|
|
71
|
+
const p = Bun.spawnSync(['magick', file, '-resize', `${edge}x${edge}>`, '-quality', String(q), out], { stderr: 'pipe' })
|
|
72
|
+
if (p.exitCode !== 0) throw new Error(`magick ${file}: ${p.stderr.toString()}`)
|
|
73
|
+
if (statSync(out).size <= MAX_IMAGE) {
|
|
74
|
+
const [w, h] = size(out)
|
|
75
|
+
return { data: Bun.file(out), mime: 'image/jpeg', w, h }
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
throw new Error(`bluesky: ${file} stays over 1 MB even at 1200 px`)
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** a service token of the account for `aud`, good for the one method `lxm` */
|
|
82
|
+
async function serviceToken(net: Net, s: Session, aud: string, lxm: string): Promise<string> {
|
|
83
|
+
const q = new URLSearchParams({ aud, lxm, exp: String(Math.floor(Date.now() / 1000) + 30 * 60) })
|
|
84
|
+
const { token } = await call<{ token: string }>(net, `${PDS}/com.atproto.server.getServiceAuth?${q}`, { headers: { Authorization: `Bearer ${s.accessJwt}` } })
|
|
85
|
+
return token
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
type Job = { jobId: string; state: string; progress?: number; blob?: unknown; error?: string; message?: string }
|
|
89
|
+
|
|
90
|
+
/** a clip uploaded the way Bluesky's app does: the day's limits, the file to the video service, its job polled until
|
|
91
|
+
* the service stored the blob on the account's PDS; refused loud over any limit, before a byte is sent */
|
|
92
|
+
async function uploadClip(file: string, s: Session, net: Net = NET): Promise<{ blob: unknown; w: number; h: number }> {
|
|
93
|
+
const ext = file.split('.').pop()!.toLowerCase()
|
|
94
|
+
const mime = CLIPS[ext]
|
|
95
|
+
if (mime == null) throw new Error(`bluesky: ${file} is no clip Bluesky takes (${Object.keys(CLIPS).join(', ')})`)
|
|
96
|
+
const bytes = statSync(file).size
|
|
97
|
+
if (bytes > MAX_VIDEO) throw new Error(`bluesky: ${file} is ${(bytes / 1e6).toFixed(1)} MB, over the video service's 300 MB`)
|
|
98
|
+
const p = probeMedia(file)
|
|
99
|
+
if (p.video == null) throw new Error(`bluesky: ${file} holds no video stream`)
|
|
100
|
+
if (p.duration > MAX_VIDEO_S) throw new Error(`bluesky: ${file} lasts ${p.duration.toFixed(1)} s, over the video service's 10 minutes`)
|
|
101
|
+
|
|
102
|
+
const limitsToken = await serviceToken(net, s, VIDEO_DID, 'app.bsky.video.getUploadLimits')
|
|
103
|
+
const limits = await call<{ canUpload: boolean; remainingDailyVideos?: number; remainingDailyBytes?: number; message?: string; error?: string }>(
|
|
104
|
+
net,
|
|
105
|
+
`${VIDEO}/app.bsky.video.getUploadLimits`,
|
|
106
|
+
{ headers: { Authorization: `Bearer ${limitsToken}` } },
|
|
107
|
+
)
|
|
108
|
+
if (!limits.canUpload) throw new Error(`bluesky: no video upload allowed now: ${limits.message ?? limits.error ?? 'the day\'s limit is reached'}`)
|
|
109
|
+
if (limits.remainingDailyBytes != null && bytes > limits.remainingDailyBytes)
|
|
110
|
+
throw new Error(`bluesky: ${file} is ${bytes} bytes, over the ${limits.remainingDailyBytes} left today`)
|
|
111
|
+
|
|
112
|
+
const token = await serviceToken(net, s, `did:web:${new URL(s.pds).hostname}`, 'com.atproto.repo.uploadBlob')
|
|
113
|
+
const q = new URLSearchParams({ did: s.did, name: `${crypto.randomUUID()}.${ext}` })
|
|
114
|
+
const r = await net.fetch(`${VIDEO}/app.bsky.video.uploadVideo?${q}`, {
|
|
115
|
+
method: 'POST',
|
|
116
|
+
body: Bun.file(file),
|
|
117
|
+
headers: { Authorization: `Bearer ${token}`, 'Content-Type': mime },
|
|
118
|
+
signal: AbortSignal.timeout(300_000),
|
|
119
|
+
})
|
|
120
|
+
const body = (await r.json().catch(() => ({}))) as { jobStatus?: Job; jobId?: string; error?: string; message?: string }
|
|
121
|
+
// the same clip sent twice: the service answers 409 with the job it already holds
|
|
122
|
+
const jobId = body.jobStatus?.jobId ?? body.jobId
|
|
123
|
+
if (jobId == null || (!r.ok && r.status !== 409)) throw new Error(`bluesky uploadVideo: ${r.status} ${body.error ?? ''} ${body.message ?? ''}`.trim())
|
|
124
|
+
|
|
125
|
+
for (let i = 0; ; i++) {
|
|
126
|
+
const { jobStatus: j } = await call<{ jobStatus: Job }>(net, `${VIDEO}/app.bsky.video.getJobStatus?jobId=${encodeURIComponent(jobId)}`, {})
|
|
127
|
+
if (j.blob != null) return { blob: j.blob, w: p.video.width, h: p.video.height }
|
|
128
|
+
if (j.state === 'JOB_STATE_FAILED') throw new Error(`bluesky: the video service failed ${file}: ${j.error ?? ''} ${j.message ?? ''}`.trim())
|
|
129
|
+
if (i >= 200) throw new Error(`bluesky: ${file} still ${j.state} after 5 minutes (job ${jobId})`)
|
|
130
|
+
await net.wait(1500)
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/** the post's embed: its media uploaded, a picture or a clip, with the draft's alt; none without media */
|
|
135
|
+
export async function embedOf(post: Pick<SocialPost, 'media' | 'alt'>, s: Session, net: Net = NET): Promise<unknown> {
|
|
136
|
+
if (post.media == null) return undefined
|
|
137
|
+
const file = post.media.path
|
|
138
|
+
if (IMAGE.test(file)) {
|
|
139
|
+
const img = image(file)
|
|
140
|
+
const { blob } = await xrpc<{ blob: unknown }>(net, 'com.atproto.repo.uploadBlob', img.data, { Authorization: `Bearer ${s.accessJwt}`, 'Content-Type': img.mime })
|
|
141
|
+
return { $type: 'app.bsky.embed.images', images: [{ alt: post.alt, image: blob, aspectRatio: { width: img.w, height: img.h } }] }
|
|
142
|
+
}
|
|
143
|
+
const alt = [...new Intl.Segmenter().segment(post.alt)].length
|
|
144
|
+
if (alt > MAX_VIDEO_ALT) throw new Error(`bluesky: the alt is ${alt} characters, over a video's ${MAX_VIDEO_ALT}`)
|
|
145
|
+
const clip = await uploadClip(file, s, net)
|
|
146
|
+
return { $type: 'app.bsky.embed.video', video: clip.blob, alt: post.alt, aspectRatio: { width: clip.w, height: clip.h } }
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/** the record a draft's part posts: the message's composed text (the one « Copier » copies) with its facets, its embed */
|
|
150
|
+
async function recordOf(a: Account, post: SocialPost, s: Session, net: Net = NET): Promise<Record<string, unknown>> {
|
|
151
|
+
if (post.posted !== '') throw new Error(`${post.slug} is already posted: ${post.posted}`)
|
|
152
|
+
if (post.text === '') throw new Error(`${post.slug}: its ## ${post.from} is empty`)
|
|
153
|
+
if (a.max !== null && post.length > a.max) throw new Error(`${post.slug} is ${post.length} long, over ${a.max}`)
|
|
154
|
+
const embed = await embedOf(post, s, net)
|
|
155
|
+
const rich = richText(post.text)
|
|
156
|
+
return { $type: 'app.bsky.feed.post', text: rich.text, facets: rich.facets, langs: ['en'], createdAt: new Date().toISOString(), embed }
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/** posts a message on the identity's Bluesky account; its link, which the caller records */
|
|
160
|
+
export async function postBluesky(a: Account, post: SocialPost): Promise<string> {
|
|
161
|
+
const s = await login(a)
|
|
162
|
+
const record = await recordOf(a, post, s)
|
|
163
|
+
const { uri } = await xrpc<{ uri: string }>(NET, 'com.atproto.repo.createRecord', JSON.stringify({ repo: s.did, collection: 'app.bsky.feed.post', record }), {
|
|
164
|
+
Authorization: `Bearer ${s.accessJwt}`,
|
|
165
|
+
'Content-Type': 'application/json',
|
|
166
|
+
})
|
|
167
|
+
return `https://bsky.app/profile/${s.handle}/post/${uri.split('/').pop()}`
|
|
168
|
+
}
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
// a draft's message posted to Discord as the identity's bot (wiki tools/shipkit/social.md, Publishing): to the channel
|
|
2
|
+
// its place names, a `#name` of a channel made its link, its media attached, pinned when it asks; a message already
|
|
3
|
+
// posted is edited at its link. The server's layout is the project's own tool
|
|
4
|
+
import type { Account } from '../../identities/identities.ts'
|
|
5
|
+
import { withoutTags } from '../compose.ts'
|
|
6
|
+
import type { SocialPost } from '../load.ts'
|
|
7
|
+
import { secret } from './secret.ts'
|
|
8
|
+
|
|
9
|
+
const API = 'https://discord.com/api/v10'
|
|
10
|
+
const TEXT = 0
|
|
11
|
+
|
|
12
|
+
type Channel = { id: string; type: number; name: string }
|
|
13
|
+
|
|
14
|
+
async function call<T>(a: Account, method: string, path: string, body?: BodyInit, json = true): Promise<T> {
|
|
15
|
+
const auth = `Bot ${await secret(a.secret, `${a.file}: secret`)}`
|
|
16
|
+
for (;;) {
|
|
17
|
+
const r = await fetch(API + path, { method, headers: { Authorization: auth, ...(json && body != null ? { 'Content-Type': 'application/json' } : {}) }, body })
|
|
18
|
+
if (r.status === 429) {
|
|
19
|
+
const { retry_after } = (await r.json()) as { retry_after: number }
|
|
20
|
+
await Bun.sleep(Math.ceil(retry_after * 1000))
|
|
21
|
+
continue
|
|
22
|
+
}
|
|
23
|
+
if (!r.ok) throw new Error(`${method} ${path}: ${r.status} ${await r.text()}`)
|
|
24
|
+
return (r.status === 204 ? null : await r.json()) as T
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** a server not boosted takes files up to 10 MiB */
|
|
29
|
+
const MAX_FILE = 10 * 1024 * 1024
|
|
30
|
+
|
|
31
|
+
/** posts a message, with its media file attached when it has one (multipart: payload_json, then files[0]) */
|
|
32
|
+
async function postMessage(a: Account, channel: string, payload: Record<string, unknown>, file: string | null, alt: string): Promise<{ id: string }> {
|
|
33
|
+
if (file == null) return call<{ id: string }>(a, 'POST', `/channels/${channel}/messages`, JSON.stringify(payload))
|
|
34
|
+
const f = Bun.file(file)
|
|
35
|
+
if (!(await f.exists())) throw new Error(`discord: the media ${file} is missing`)
|
|
36
|
+
if (f.size > MAX_FILE) throw new Error(`discord: ${file} is ${(f.size / 1048576).toFixed(1)} MiB, over the server's 10 MiB a file`)
|
|
37
|
+
const name = file.split('/').pop()!
|
|
38
|
+
const form = new FormData()
|
|
39
|
+
form.append('payload_json', JSON.stringify({ ...payload, attachments: [{ id: 0, filename: name, description: alt.slice(0, 1024) }] }))
|
|
40
|
+
form.append('files[0]', f, name)
|
|
41
|
+
return call<{ id: string }>(a, 'POST', `/channels/${channel}/messages`, form, false)
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
const same = (x: string, y: string): boolean => x.toLowerCase() === y.toLowerCase()
|
|
45
|
+
|
|
46
|
+
/** a channel shows as `<emoji>・<name>`; its name alone is its key (a draft's place, a `#name` in a text) */
|
|
47
|
+
export const channelKey = (name: string): string => name.replace(/^[^\p{L}\p{N}]+/u, '')
|
|
48
|
+
|
|
49
|
+
/** a post's text as Discord shows it: a `#name` of a channel becomes its link, any other hashtag goes, and a line left
|
|
50
|
+
* empty by it goes too */
|
|
51
|
+
export function discordContent(text: string, channels: readonly Channel[]): string {
|
|
52
|
+
const linked = text.replace(/(^|\s)#([\p{L}\p{N}_-]+)/gu, (m, lead: string, name: string) => {
|
|
53
|
+
const c = channels.find((x) => x.type === TEXT && channelKey(x.name) === name)
|
|
54
|
+
return c == null ? m : `${lead}<#${c.id}>`
|
|
55
|
+
})
|
|
56
|
+
return withoutTags(linked)
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** posts a message on the identity's Discord server; its link, which the caller records */
|
|
60
|
+
export async function postDiscord(a: Account, post: SocialPost): Promise<string> {
|
|
61
|
+
if (a.guild === '') throw new Error(`${a.file}: no guild, the server's id`)
|
|
62
|
+
if (post.text === '') throw new Error(`${post.slug}: its ## ${post.from} is empty`)
|
|
63
|
+
const channels = await call<Channel[]>(a, 'GET', `/guilds/${a.guild}/channels`)
|
|
64
|
+
const content = discordContent(post.text, channels)
|
|
65
|
+
if (post.posted) {
|
|
66
|
+
const ids = new RegExp(`^https://discord\\.com/channels/${a.guild}/(\\d+)/(\\d+)$`).exec(post.posted)
|
|
67
|
+
if (ids == null) throw new Error(`${post.slug}: posted "${post.posted}" is no message link of the server`)
|
|
68
|
+
await call(a, 'PATCH', `/channels/${ids[1]}/messages/${ids[2]}`, JSON.stringify({ content, allowed_mentions: { parse: [] } }))
|
|
69
|
+
return post.posted
|
|
70
|
+
}
|
|
71
|
+
const target = channels.find((x) => x.type === TEXT && same(channelKey(x.name), post.place))
|
|
72
|
+
if (target == null) throw new Error(`${post.slug}: place "${post.place}" is no text channel of the server`)
|
|
73
|
+
const msg = await postMessage(a, target.id, { content, allowed_mentions: { parse: [] } }, post.media?.path ?? null, post.alt)
|
|
74
|
+
if (post.pin) await call(a, 'PUT', `/channels/${target.id}/pins/${msg.id}`)
|
|
75
|
+
return `https://discord.com/channels/${a.guild}/${target.id}/${msg.id}`
|
|
76
|
+
}
|