rvlib-shipkit 2.18.0 → 2.20.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 +31 -0
- package/package.json +1 -1
- package/src/annex/annex.ts +227 -0
- package/src/annex/offload.ts +279 -0
- package/src/asks/asks-queue.ts +63 -10
- package/src/checks/SK040-release-words.check.ts +43 -0
- package/src/checks/SK041-annex-links.check.ts +28 -0
- package/src/checks/SK042-post-kinds.check.ts +73 -0
- package/src/cli/cmd_Annex.ts +179 -0
- package/src/cli/cmd_Asks.ts +3 -1
- package/src/cli/cmd_Commands.ts +4 -1
- package/src/cli/cmd_GlobalProcesses.ts +34 -11
- package/src/cli/cmd_Home.ts +41 -4
- package/src/cli/cmd_Messages.ts +155 -0
- package/src/cli/cmd_Releases.ts +48 -0
- package/src/cli/cmd_Review.ts +161 -6
- package/src/cli/cmd_Secret.ts +4 -30
- package/src/cli/cmd_Shot.ts +4 -4
- package/src/cli/cmd_Social.ts +179 -3
- package/src/cli/cmd_Trailer.ts +15 -3
- package/src/cli/family-pages.ts +2 -0
- package/src/cli/kit/index.ts +1 -1
- package/src/cli/kit/verb.ts +11 -3
- package/src/cli/registry.ts +8 -2
- package/src/collections/actions.ts +29 -1
- package/src/collections/collection-types.ts +10 -1
- package/src/collections/providers.ts +5 -2
- package/src/commands/model.ts +36 -0
- package/src/commands/registry.ts +49 -0
- package/src/commands/routes.ts +59 -0
- package/src/commands/runner.ts +35 -0
- package/src/commands/runs.ts +112 -0
- package/src/core/app-icon.ts +4 -3
- package/src/core/icon-type.ts +8 -0
- package/src/core/jobs.ts +4 -3
- package/src/core/layout.ts +5 -2
- package/src/core/squircle.ts +95 -0
- package/src/home/daemon-jobs.ts +26 -2
- package/src/home/global-units.ts +3 -0
- package/src/home/gui-app/ShipkitGui.swift +302 -5
- package/src/home/gui-app.ts +63 -33
- package/src/home/hmr-keep.ts +134 -0
- package/src/home/home-paths.ts +5 -1
- package/src/home/home-start.ts +14 -14
- package/src/home/lib-watch.ts +21 -11
- package/src/home/pm.ts +1 -1
- package/src/home/process-apps.ts +181 -0
- package/src/home/resources.ts +3 -3
- package/src/home/run-daemon.ts +11 -2
- package/src/home/run-pm.ts +9 -1
- package/src/home/run-web.ts +7 -4
- package/src/home/serve-web.ts +64 -14
- package/src/home/supervise.ts +3 -1
- package/src/identities/collection.ts +49 -0
- package/src/identities/identities.ts +130 -11
- package/src/identities/machine.ts +4 -3
- package/src/identities/rating.ts +33 -0
- package/src/identities/shown.ts +170 -0
- package/src/identities/steps.ts +5 -0
- package/src/media-store/purge.ts +15 -1
- package/src/media-store/remote.ts +22 -6
- package/src/messages/brief.ts +117 -0
- package/src/messages/collection.ts +40 -0
- package/src/messages/model.ts +171 -0
- package/src/messages/routes.ts +15 -0
- package/src/messages/score.ts +180 -0
- package/src/messages/tabs.ts +13 -0
- package/src/release/notes.ts +130 -0
- package/src/release/run-bump.ts +41 -18
- package/src/release/run-release.ts +22 -4
- package/src/release/run-releases.ts +17 -15
- package/src/release/unit-resolve.ts +9 -0
- package/src/releases/add.ts +66 -0
- package/src/releases/collection.ts +36 -0
- package/src/releases/from-card.ts +66 -0
- package/src/releases/model.ts +267 -0
- package/src/releases/pictures.ts +89 -0
- package/src/releases/routes.ts +36 -0
- package/src/releases/store.ts +71 -0
- package/src/repo-config.ts +5 -0
- package/src/review/cells.ts +0 -11
- package/src/review/format.ts +10 -6
- package/src/review/http.ts +7 -2
- package/src/review/model.ts +92 -3
- package/src/review/notes.ts +2 -48
- package/src/review/routes.ts +28 -10
- package/src/review/stage-card.ts +197 -0
- package/src/review/stage-routes.ts +123 -0
- package/src/review/store.ts +117 -19
- package/src/review/trailer-card.ts +99 -0
- package/src/review/trailer-desk.ts +57 -4
- package/src/review/trailer-model.ts +41 -7
- package/src/review/trailer-notes.ts +45 -0
- package/src/review/trailer-routes.ts +22 -13
- package/src/secrets/manager.ts +59 -0
- package/src/secrets/name.ts +2 -0
- package/src/serve/hub-app/app-bridge.ts +71 -0
- package/src/serve/hub-app/col-card.tsx +10 -0
- package/src/serve/hub-app/cols-svc.ts +37 -6
- package/src/serve/hub-app/commands/commands-page.tsx +122 -0
- package/src/serve/hub-app/commands/commands-st.ts +177 -0
- package/src/serve/hub-app/commands.css +24 -0
- package/src/serve/hub-app/hash-route.ts +40 -1
- package/src/serve/hub-app/home-st.ts +11 -2
- package/src/serve/hub-app/home.html +3 -0
- package/src/serve/hub-app/hub-app.tsx +6 -0
- package/src/serve/hub-app/hub.css +1 -0
- package/src/serve/hub-app/icons.tsx +5 -0
- package/src/serve/hub-app/identities-view.tsx +4 -1
- package/src/serve/hub-app/identities.css +1 -0
- package/src/serve/hub-app/index.html +3 -0
- package/src/serve/hub-app/keys.ts +2 -2
- package/src/serve/hub-app/machine-st.ts +41 -10
- package/src/serve/hub-app/messages/messages-page.tsx +354 -0
- package/src/serve/hub-app/messages/messages-st.ts +74 -0
- package/src/serve/hub-app/messages.css +35 -0
- package/src/serve/hub-app/releases/releases-page.tsx +94 -0
- package/src/serve/hub-app/releases/releases-st.ts +69 -0
- package/src/serve/hub-app/releases.css +25 -0
- package/src/serve/hub-app/repo-sections.ts +15 -1
- package/src/serve/hub-app/repo-st.ts +56 -5
- package/src/serve/hub-app/review/clip-st.ts +31 -3
- package/src/serve/hub-app/review/note-place.ts +31 -0
- package/src/serve/hub-app/review/review-cells.tsx +27 -3
- package/src/serve/hub-app/review/review-st.ts +77 -2
- package/src/serve/hub-app/review/review-thread.tsx +9 -31
- package/src/serve/hub-app/review/review-views.tsx +164 -58
- package/src/serve/hub-app/review/thread-st.ts +108 -41
- package/src/serve/hub-app/review/trailer-card.tsx +187 -0
- package/src/serve/hub-app/review/trailer-page.tsx +62 -31
- package/src/serve/hub-app/review/trailer-st.ts +138 -26
- package/src/serve/hub-app/review/trailer-timeline.tsx +39 -26
- package/src/serve/hub-app/review.css +49 -6
- package/src/serve/hub-app/social/comms-page.tsx +55 -23
- package/src/serve/hub-app/social/identity-pictures.ts +112 -0
- package/src/serve/hub-app/social/kit.tsx +9 -6
- package/src/serve/hub-app/social/post-card.tsx +10 -2
- package/src/serve/hub-app/social/social-model.ts +37 -3
- package/src/serve/hub-app/social/social-page.tsx +236 -82
- package/src/serve/hub-app/social/social-st.ts +79 -26
- package/src/serve/hub-app/social/stage-popup.tsx +268 -0
- package/src/serve/hub-app/social/stage-st.ts +310 -0
- package/src/serve/hub-app/social/step-layout.ts +42 -0
- package/src/serve/hub-app/social.css +68 -4
- package/src/serve/hub-app/tree-build.ts +38 -1
- package/src/serve/hub-app/tree-svc.ts +10 -3
- package/src/serve/project-gutter-route.ts +4 -2
- package/src/serve/same-origin.ts +24 -1
- package/src/serve/serve-hub.ts +27 -3
- package/src/shipkit-files.ts +9 -7
- package/src/shot/shooter.ts +3 -3
- package/src/shot/shot-ask.ts +14 -3
- package/src/shot/shot.shipkit.ts +1 -1
- package/src/social/discord-layout.ts +282 -0
- package/src/social/fit.ts +84 -0
- package/src/social/identity-words.ts +74 -0
- package/src/social/kind-pages.ts +41 -0
- package/src/social/kinds.ts +92 -0
- package/src/social/load.ts +105 -9
- package/src/social/md.ts +14 -6
- package/src/social/media-limit.ts +63 -2
- package/src/social/presence.ts +1 -1
- package/src/social/publish/bluesky.ts +58 -19
- package/src/social/publish/discord.ts +3 -2
- package/src/social/publish/index.ts +31 -5
- package/src/social/reach.ts +49 -0
- package/src/social/release-stage.ts +173 -0
- package/src/social/routes.ts +44 -9
- package/src/social/stage.ts +227 -0
- package/src/social/strip.ts +85 -0
- package/src/social/text.ts +6 -2
- package/src/social/unit.ts +57 -1
- package/src/social/writes.ts +11 -0
- package/src/stores/routes.ts +2 -2
- package/src/suite/judge-suites.ts +1 -1
- package/src/suite/suite-cli.ts +5 -5
- package/src/trailer/build.ts +90 -52
- package/src/trailer/draft.ts +28 -0
- package/src/trailer/footage.ts +4 -2
- package/src/trailer/grammar.ts +25 -13
- package/src/trailer/graph.ts +32 -9
- package/src/trailer/profile.ts +35 -0
- package/src/trailer/prune.ts +15 -10
- package/src/trailer/public-words.ts +41 -0
- package/src/trailer/stitch.ts +22 -10
- package/src/trailer/titles.ts +47 -2
package/src/serve/serve-hub.ts
CHANGED
|
@@ -11,7 +11,8 @@ import { pageOf, searchWiki } from 'rvlib-shipkit/src/wiki/graph-pages.ts'
|
|
|
11
11
|
import { graphRoutes } from 'rvlib-shipkit/src/wiki/serve-graph.ts'
|
|
12
12
|
import type { StudioRoutes } from '../assets/server/studio-server.ts'
|
|
13
13
|
import { comfyBoxUp, type ComfyBox, type ComfyPanelUp } from '../comfy/comfy-panel.ts'
|
|
14
|
-
import { appendAskRemark, appendAssetNote, askDone, askProof } from '../collections/actions.ts'
|
|
14
|
+
import { appendAskRemark, appendAssetNote, askDone, askProof, askSecret } from '../collections/actions.ts'
|
|
15
|
+
import { managerStore, type SecretStore } from '../secrets/manager.ts'
|
|
15
16
|
import { brokenRow, projectResources, type Collection, type Instance, type NeedItem, type Resource } from '../collections/collection-types.ts'
|
|
16
17
|
import type { CheckEvent } from '../core/run-check.ts'
|
|
17
18
|
import { configDirty, readGateBlock, writeGateBlock, type GateEdit } from '../core/when-block.ts'
|
|
@@ -38,6 +39,10 @@ import { readmeRoutes } from './readme-route.ts'
|
|
|
38
39
|
import { reviewRoutes } from '../review/routes.ts'
|
|
39
40
|
import { veilleRoutes } from '../veille/routes.ts'
|
|
40
41
|
import { storesRoutes } from '../stores/routes.ts'
|
|
42
|
+
import { messagesRoutes } from '../messages/routes.ts'
|
|
43
|
+
import { releasesRoutes } from '../releases/routes.ts'
|
|
44
|
+
import { commandsRoutes } from '../commands/routes.ts'
|
|
45
|
+
import { noCli } from '../commands/registry.ts'
|
|
41
46
|
import { socialRoutes } from '../social/routes.ts'
|
|
42
47
|
import { embedRoute } from './embed.ts'
|
|
43
48
|
import { pagesRoutes } from '../pages/routes.ts'
|
|
@@ -110,6 +115,9 @@ export type HubDeps = {
|
|
|
110
115
|
collections: () => Collection[]
|
|
111
116
|
/** asks dir (repo-root-relative) for the act-in-place ask verbs */
|
|
112
117
|
asksDir: string
|
|
118
|
+
/** where a value pasted under a credential ask goes; absent = the repo's
|
|
119
|
+
* `credsCommand`, as `sk secret set` runs it */
|
|
120
|
+
storeSecret?: SecretStore
|
|
113
121
|
/** the comfy panel; null when the repo declares no workflow module, which
|
|
114
122
|
* is also when the comfy section is absent from the page */
|
|
115
123
|
comfy: ComfyDeps | null
|
|
@@ -219,7 +227,8 @@ export function hubHandler(d: HubDeps, o: { base?: string; projects?: Gutter } =
|
|
|
219
227
|
// editor: only the server knows where this repo sits on disk
|
|
220
228
|
// `uses` tells the home which machine resources this repo needs,
|
|
221
229
|
// `base` where this hub's page sits on the server that answers
|
|
222
|
-
|
|
230
|
+
// `cli`: the repo has a project CLI, so its commands section is no greyed row
|
|
231
|
+
if (path === '/hub.json') return Response.json({ hub: 'shipkit', name: d.name, root: d.root, base, tools, uses: d.uses ?? [], cli: noCli(d.root) == null })
|
|
223
232
|
if (path.startsWith('/api/projects')) return (await projects.handle(req, path)) ?? new Response('not found', { status: 404 })
|
|
224
233
|
// where the machine's home serves, and whether it does: a rail
|
|
225
234
|
// click opens the home on that repo, or VS Code while none runs
|
|
@@ -276,8 +285,14 @@ export function hubHandler(d: HubDeps, o: { base?: string; projects?: Gutter } =
|
|
|
276
285
|
if (path.startsWith('/api/act/') && req.method === 'POST') {
|
|
277
286
|
// act-in-place verbs — every mutation hits a git-tracked truth
|
|
278
287
|
// file; errors surface as 400 text the card shows verbatim
|
|
288
|
+
// a parse error quotes the body, which can carry a pasted secret
|
|
289
|
+
const b = (await req.json().catch(() => null)) as Record<string, string> | null
|
|
290
|
+
if (b == null || typeof b !== 'object') return new Response('the body is not a json object', { status: 400 })
|
|
279
291
|
try {
|
|
280
|
-
|
|
292
|
+
if (path === '/api/act/ask-secret') {
|
|
293
|
+
const value = typeof b.value === 'string' ? b.value : ''
|
|
294
|
+
return Response.json(await askSecret({ root: d.root, asksDir: d.asksDir, file: b.file ?? '', name: b.name ?? '', value, store: d.storeSecret ?? managerStore(d.root) }))
|
|
295
|
+
}
|
|
281
296
|
if (path === '/api/act/ask-done') askDone(d.root, d.asksDir, b.file ?? '')
|
|
282
297
|
else if (path === '/api/act/ask-proof') askProof(d.root, d.asksDir, b.file ?? '', b.url ?? '')
|
|
283
298
|
else if (path === '/api/act/remark') {
|
|
@@ -357,6 +372,15 @@ export function hubHandler(d: HubDeps, o: { base?: string; projects?: Gutter } =
|
|
|
357
372
|
// the store pages' desk (stores/routes.ts)
|
|
358
373
|
const stores = await storesRoutes(d.root, req, path)
|
|
359
374
|
if (stores != null) return stores
|
|
375
|
+
// the release files and their private pictures (releases/routes.ts)
|
|
376
|
+
const releases = await releasesRoutes(d.root, req, path)
|
|
377
|
+
if (releases != null) return releases
|
|
378
|
+
// the project CLI run from the page (commands/routes.ts)
|
|
379
|
+
const commands = await commandsRoutes(d.root, req, path)
|
|
380
|
+
if (commands != null) return commands
|
|
381
|
+
// the messages store, read whole (messages/routes.ts)
|
|
382
|
+
const messages = messagesRoutes(d.root, req, path)
|
|
383
|
+
if (messages != null) return messages
|
|
360
384
|
// the Communications and Social desks (social/routes.ts)
|
|
361
385
|
const social = await socialRoutes(d.root, req, path)
|
|
362
386
|
if (social != null) return social
|
package/src/shipkit-files.ts
CHANGED
|
@@ -25,12 +25,13 @@
|
|
|
25
25
|
import { check, type CheckDef } from './check.ts'
|
|
26
26
|
import { review, type AutoRule, type KindDef, type ReviewDef, type ReviewSource, type ReviewUnit } from './review/unit.ts'
|
|
27
27
|
import { site, type SiteDef, type SiteUnit } from './site/unit.ts'
|
|
28
|
-
import { social, type SocialDef, type SocialUnit } from './social/unit.ts'
|
|
28
|
+
import { social, type GuardInput, type ReleaseHeading, type SocialDef, type SocialUnit, type SuggestedLine } from './social/unit.ts'
|
|
29
29
|
import { stores, type StoresDef, type StoresUnit } from './stores/unit.ts'
|
|
30
30
|
import { trailer, type TrailerDef, type TrailerUnit } from './trailer/adapter.ts'
|
|
31
|
+
import { ICON_IMAGE_TYPES, iconImageType } from './core/icon-type.ts'
|
|
31
32
|
|
|
32
33
|
export { check, review, site, social, stores, trailer }
|
|
33
|
-
export type { AutoRule, KindDef, ReviewDef, ReviewSource, ReviewUnit, SiteDef, SiteUnit, SocialDef, SocialUnit, StoresDef, StoresUnit, TrailerDef, TrailerUnit }
|
|
34
|
+
export type { AutoRule, GuardInput, KindDef, ReleaseHeading, ReviewDef, ReviewSource, ReviewUnit, SiteDef, SiteUnit, SocialDef, SocialUnit, StoresDef, StoresUnit, SuggestedLine, TrailerDef, TrailerUnit }
|
|
34
35
|
|
|
35
36
|
/** one button beside a global process: a command, or a function of the file */
|
|
36
37
|
export type ProcessAction = {
|
|
@@ -48,6 +49,10 @@ export type GlobalProcessDef = {
|
|
|
48
49
|
id: string
|
|
49
50
|
/** the name on the switch (default the id) */
|
|
50
51
|
label?: string
|
|
52
|
+
/** the name of its macOS app in ~/Applications, where Spotlight and
|
|
53
|
+
* Launchpad find it (default the label). Only a process with a url has
|
|
54
|
+
* one; the daemon builds it, and removes it when the process goes */
|
|
55
|
+
app?: string
|
|
51
56
|
/** one line: what it is for */
|
|
52
57
|
description?: string
|
|
53
58
|
/** the machine it runs on, as a hint beside the switch */
|
|
@@ -93,11 +98,7 @@ const KEBAB = /^[a-z0-9][a-z0-9-]*$/
|
|
|
93
98
|
const words = (v: unknown): boolean => Array.isArray(v) && v.length > 0 && v.every((w) => typeof w === 'string')
|
|
94
99
|
const httpUrl = (v: unknown): boolean => typeof v === 'string' && /^https?:\/\//.test(v)
|
|
95
100
|
|
|
96
|
-
|
|
97
|
-
export const ICON_IMAGE_TYPES: Record<string, string> = { png: 'image/png', svg: 'image/svg+xml', ico: 'image/x-icon', jpg: 'image/jpeg', jpeg: 'image/jpeg', webp: 'image/webp' }
|
|
98
|
-
|
|
99
|
-
/** the image an icon names (its extension), or null when it is text */
|
|
100
|
-
export const iconImageType = (icon: string): string | null => ICON_IMAGE_TYPES[/\.([a-z]+)$/i.exec(icon)?.[1]?.toLowerCase() ?? ''] ?? null
|
|
101
|
+
export { ICON_IMAGE_TYPES, iconImageType }
|
|
101
102
|
|
|
102
103
|
function iconProblem(icon: unknown): string | null {
|
|
103
104
|
if (typeof icon !== 'string' || icon.trim() === '') return 'icon is an emoji or a repo relative image path'
|
|
@@ -113,6 +114,7 @@ export function globalProcessProblem(d: GlobalProcessDef): string | null {
|
|
|
113
114
|
if (!words(d.cmd)) return `${at}: cmd is a list of words`
|
|
114
115
|
if (d.down != null && !words(d.down)) return `${at}: down is a list of words`
|
|
115
116
|
if (d.url != null && !httpUrl(d.url)) return `${at}: url must be an http url`
|
|
117
|
+
if (d.app !== undefined && (typeof d.app !== 'string' || d.app.trim() === '' || /^\.|[/:]/.test(d.app))) return `${at}: app is a file name: not empty, no leading dot, no / or :`
|
|
116
118
|
if (d.probe != null && !httpUrl(d.probe)) return `${at}: probe must be an http url`
|
|
117
119
|
if (d.down != null && d.probe == null && d.url == null) return `${at}: a bring-up (one with down) needs probe or url, the only truth of whether it is up`
|
|
118
120
|
if (d.icon !== undefined) {
|
package/src/shot/shooter.ts
CHANGED
|
@@ -27,7 +27,7 @@ import { loadPlaywright } from '../smoke/run-smoke.ts'
|
|
|
27
27
|
import { CLIP_INIT, CLIP_QUANTIZER, clipDone, installClip, KEY_EVERY, muxArgs, type PageClipAsk, type PageClipDone, TAKE, takeClip } from './clip-encoder.ts'
|
|
28
28
|
import { type ClipPath, clipPathOf, domEncodeArgs, FrameTimeline, largestCanvas, screencastParams } from './dom-clip.ts'
|
|
29
29
|
import { openBrowser, type PwBrowser } from './box.ts'
|
|
30
|
-
import { capMsOf, type ClipAsk, pageMove, readMark, type ShotAsk, slotKey, Turns, waitReady } from './shot-ask.ts'
|
|
30
|
+
import { capMsOf, type ClipAsk, pageMove, readMark, type ShotAsk, slotKey, stillFormat, Turns, waitReady } from './shot-ask.ts'
|
|
31
31
|
|
|
32
32
|
/** the slice of playwright the shots touch, so the lib types nothing it does not ship */
|
|
33
33
|
type Cdp = {
|
|
@@ -139,7 +139,7 @@ export class Shooter {
|
|
|
139
139
|
return { browser: this.#browser?.isConnected() === true, url: this.#slot?.url ?? null, waiting: this.#turns.waiting }
|
|
140
140
|
}
|
|
141
141
|
|
|
142
|
-
/** a
|
|
142
|
+
/** a still of the url, written at `a.out`, encoded by its extension (stillFormat) */
|
|
143
143
|
shot(a: ShotAsk): Promise<ShotDone> {
|
|
144
144
|
return this.#turns.run(() => withCap(`the shot of ${a.url}`, capMsOf(a), this.#shot(a)).finally(() => this.#touch()))
|
|
145
145
|
}
|
|
@@ -291,7 +291,7 @@ export class Shooter {
|
|
|
291
291
|
phases['step'] = ms(t)
|
|
292
292
|
}
|
|
293
293
|
t = performance.now()
|
|
294
|
-
const r = await slot.cdp.send('Page.captureScreenshot', {
|
|
294
|
+
const r = await slot.cdp.send('Page.captureScreenshot', { ...stillFormat(a.out), optimizeForSpeed: true })
|
|
295
295
|
phases['capture'] = ms(t)
|
|
296
296
|
mkdirSync(dirname(a.out), { recursive: true })
|
|
297
297
|
await Bun.write(a.out, Buffer.from(String(r['data']), 'base64'))
|
package/src/shot/shot-ask.ts
CHANGED
|
@@ -65,8 +65,19 @@ export function normalizeUrl(s: string): string {
|
|
|
65
65
|
throw new Error(`'${s}' is not a url: give http://host:port/path, localhost:5173/path or :5173/path`)
|
|
66
66
|
}
|
|
67
67
|
|
|
68
|
-
/**
|
|
69
|
-
|
|
68
|
+
/** a still's quality as webp or jpeg: the page's text stays sharp at about an eighth of the png's bytes (a 1280x800
|
|
69
|
+
* page: png 1004 KB, webp 126 KB) */
|
|
70
|
+
export const STILL_QUALITY = 90
|
|
71
|
+
/** a still's encoding by its file's extension: webp and jpeg at STILL_QUALITY, png (lossless) for anything else */
|
|
72
|
+
export function stillFormat(out: string): { format: 'webp' | 'jpeg'; quality: number } | { format: 'png' } {
|
|
73
|
+
if (/\.webp$/i.test(out)) return { format: 'webp', quality: STILL_QUALITY }
|
|
74
|
+
if (/\.jpe?g$/i.test(out)) return { format: 'jpeg', quality: STILL_QUALITY }
|
|
75
|
+
return { format: 'png' }
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** the file a shot lands in when no `--out` is given: under the repo's local scratch, named after the url; a still
|
|
79
|
+
* is a webp */
|
|
80
|
+
export function defaultOut(url: string, ext: 'webp' | 'mp4'): string {
|
|
70
81
|
const u = new URL(url)
|
|
71
82
|
const slug = `${u.hostname}-${u.port || (u.protocol === 'https:' ? '443' : '80')}${u.pathname}${u.search}${u.hash}`
|
|
72
83
|
.replace(/[^\w.-]+/g, '-')
|
|
@@ -113,7 +124,7 @@ export function askOf(f: ShotFlags, cwd: string): ShotAsk | ClipAsk {
|
|
|
113
124
|
url,
|
|
114
125
|
viewport: f.viewport == null ? DEFAULT_VIEWPORT : parseViewport(f.viewport),
|
|
115
126
|
dpr: f.dpr == null ? 1 : positive('--dpr', f.dpr, 4),
|
|
116
|
-
out: resolve(cwd, f.out ?? defaultOut(url, seconds == null ? '
|
|
127
|
+
out: resolve(cwd, f.out ?? defaultOut(url, seconds == null ? 'webp' : 'mp4')),
|
|
117
128
|
reload: f.reload === true,
|
|
118
129
|
waitMs: f.wait == null ? DEFAULT_WAIT_MS : f.wait === '0' ? 0 : positive('--wait', f.wait, 60_000),
|
|
119
130
|
}
|
package/src/shot/shot.shipkit.ts
CHANGED
|
@@ -7,7 +7,7 @@ import { shotUrlBase } from './shot-ask.ts'
|
|
|
7
7
|
export default globalProcess({
|
|
8
8
|
id: 'shot',
|
|
9
9
|
label: 'shots',
|
|
10
|
-
description: 'warm headless browser: sk shot <url> gives a
|
|
10
|
+
description: 'warm headless browser: sk shot <url> gives a webp, --video a clip, for every repo',
|
|
11
11
|
cmd: ['bun', join(import.meta.dir, 'serve-shot.ts')],
|
|
12
12
|
probe: `${shotUrlBase()}/health`,
|
|
13
13
|
icon: '📸',
|
|
@@ -0,0 +1,282 @@
|
|
|
1
|
+
// an identity's Discord server as data (wiki tools/shipkit/social-identities.md, The server's layout): `layout.md`
|
|
2
|
+
// beside its discord account.md, made true through the account's bot. Nothing is deleted unless asked, and never a
|
|
3
|
+
// channel that holds a message; a server that already matches gets no call but the reads. Its stale picture rows
|
|
4
|
+
// (icon, banner, invite splash) are set with it (What each account shows)
|
|
5
|
+
import { existsSync, readFileSync } from 'node:fs'
|
|
6
|
+
import { join } from 'node:path'
|
|
7
|
+
import type { Account } from '../identities/identities.ts'
|
|
8
|
+
import { DISCORD_ROWS, recordPushed, toPush, type PushReport } from '../identities/shown.ts'
|
|
9
|
+
import { parseFrontmatter } from './md.ts'
|
|
10
|
+
import { call, channelKey } from './publish/discord.ts'
|
|
11
|
+
|
|
12
|
+
export type ChannelDef = { name: string; emoji: string; topic: string; readOnly: boolean; voice: boolean; ageRestricted: boolean; only: string[] }
|
|
13
|
+
export type CategoryDef = { name: string; was: string[]; channels: ChannelDef[] }
|
|
14
|
+
export type RoleDef = { name: string; color: number; hoist: boolean; mentionable: boolean; owner: boolean }
|
|
15
|
+
/** a member by its Discord username, and the roles the apply gives it */
|
|
16
|
+
export type MemberDef = { name: string; roles: string[] }
|
|
17
|
+
export type DiscordLayout = { file: string; name: string; roles: RoleDef[]; members: MemberDef[]; categories: CategoryDef[] }
|
|
18
|
+
|
|
19
|
+
const ROLE_FLAGS = new Set(['hoist', 'mentionable', 'owner'])
|
|
20
|
+
const CHANNEL_FLAGS = new Set(['read only', 'voice', 'age restricted'])
|
|
21
|
+
|
|
22
|
+
const cells = (chunk: string): string[][] =>
|
|
23
|
+
chunk
|
|
24
|
+
.split('\n')
|
|
25
|
+
.filter((l) => /^\|.*\|$/.test(l.trim()))
|
|
26
|
+
.map((l) => l.trim().slice(1, -1).split('|').map((c) => c.trim()))
|
|
27
|
+
.slice(2)
|
|
28
|
+
|
|
29
|
+
const list = (cell: string | undefined): string[] => (cell ?? '').split(',').map((x) => x.trim()).filter((x) => x !== '')
|
|
30
|
+
|
|
31
|
+
/** a layout page read and checked: every bad row is one error line, thrown together */
|
|
32
|
+
export function parseLayout(raw: string, file: string): DiscordLayout {
|
|
33
|
+
const { meta, body } = parseFrontmatter(raw)
|
|
34
|
+
const errors: string[] = []
|
|
35
|
+
if (!meta.name) errors.push('front matter names no server name (name:)')
|
|
36
|
+
const roles: RoleDef[] = []
|
|
37
|
+
const members: MemberDef[] = []
|
|
38
|
+
const categories: CategoryDef[] = []
|
|
39
|
+
for (const chunk of body.split(/^## /m).slice(1)) {
|
|
40
|
+
const head = chunk.slice(0, chunk.indexOf('\n') === -1 ? chunk.length : chunk.indexOf('\n')).trim()
|
|
41
|
+
if (head === 'Roles') {
|
|
42
|
+
for (const [name = '', colour = '', flags] of cells(chunk)) {
|
|
43
|
+
const f = list(flags)
|
|
44
|
+
for (const x of f) if (!ROLE_FLAGS.has(x)) errors.push(`role ${name}: unknown flag "${x}" (${[...ROLE_FLAGS].join(', ')})`)
|
|
45
|
+
if (!/^#[0-9a-f]{6}$/i.test(colour)) errors.push(`role ${name}: colour "${colour}" is no #rrggbb`)
|
|
46
|
+
roles.push({ name, color: Number.parseInt(colour.slice(1), 16), hoist: f.includes('hoist'), mentionable: f.includes('mentionable'), owner: f.includes('owner') })
|
|
47
|
+
}
|
|
48
|
+
continue
|
|
49
|
+
}
|
|
50
|
+
if (head === 'Members') {
|
|
51
|
+
for (const [name = '', given] of cells(chunk)) {
|
|
52
|
+
if (!/^[a-z0-9_.]{2,32}$/.test(name)) errors.push(`member ${name}: a Discord username is 2 to 32 of a-z, 0-9, _ and .`)
|
|
53
|
+
members.push({ name, roles: list(given) })
|
|
54
|
+
}
|
|
55
|
+
continue
|
|
56
|
+
}
|
|
57
|
+
const m = /^(.+?)(?: \(was (.+)\))?$/.exec(head)!
|
|
58
|
+
const channels: ChannelDef[] = []
|
|
59
|
+
for (const [name = '', emoji = '', topic = '', flags, only] of cells(chunk)) {
|
|
60
|
+
const f = list(flags)
|
|
61
|
+
for (const x of f) if (!CHANNEL_FLAGS.has(x)) errors.push(`#${name}: unknown flag "${x}" (${[...CHANNEL_FLAGS].join(', ')})`)
|
|
62
|
+
if (!/^[\p{L}\p{N}][\p{L}\p{N}_-]*$/u.test(name)) errors.push(`#${name}: a channel name is letters, digits, - and _`)
|
|
63
|
+
channels.push({ name, emoji, topic, readOnly: f.includes('read only'), voice: f.includes('voice'), ageRestricted: f.includes('age restricted'), only: list(only) })
|
|
64
|
+
}
|
|
65
|
+
categories.push({ name: m[1]!, was: list(m[2]), channels })
|
|
66
|
+
}
|
|
67
|
+
// a text and a voice channel may share a name: each is found by its own type
|
|
68
|
+
const names = categories.flatMap((c) => c.channels.map((x) => `${x.voice ? 'voice ' : '#'}${x.name.toLowerCase()}`))
|
|
69
|
+
for (const n of new Set(names)) if (names.filter((x) => x === n).length > 1) errors.push(`${n}: named twice`)
|
|
70
|
+
for (const c of categories) for (const x of c.channels) for (const r of x.only) if (!roles.some((d) => d.name === r)) errors.push(`#${x.name}: only "${r}", no such role under ## Roles`)
|
|
71
|
+
for (const x of members) for (const r of x.roles) if (!roles.some((d) => d.name === r)) errors.push(`member ${x.name}: role "${r}", no such role under ## Roles`)
|
|
72
|
+
if (errors.length > 0) throw new Error(`${file}:\n ${errors.join('\n ')}`)
|
|
73
|
+
return { file, name: meta.name!, roles, members, categories }
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** the layout of a discord account, `layout.md` beside its account.md */
|
|
77
|
+
export function layoutOf(a: Account): DiscordLayout {
|
|
78
|
+
const file = join(a.dir, 'layout.md')
|
|
79
|
+
if (!existsSync(file)) throw new Error(`${a.identity}: no ${file}, the server's layout`)
|
|
80
|
+
return parseLayout(readFileSync(file, 'utf8'), file)
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** every channel name of a layout, its key in a draft's place and a `#name` of a text */
|
|
84
|
+
export const layoutChannels = (l: DiscordLayout): string[] => l.categories.flatMap((c) => c.channels.map((x) => x.name))
|
|
85
|
+
|
|
86
|
+
const TEXT = 0
|
|
87
|
+
const VOICE = 2
|
|
88
|
+
const CATEGORY = 4
|
|
89
|
+
/** send messages, create public and private threads, send in threads */
|
|
90
|
+
const WRITE = String((1n << 11n) | (1n << 35n) | (1n << 36n) | (1n << 38n))
|
|
91
|
+
const VIEW = String(1n << 10n)
|
|
92
|
+
|
|
93
|
+
type Overwrite = { id: string; type: number; allow: string; deny: string }
|
|
94
|
+
type Channel = { id: string; type: number; name: string; parent_id: string | null; topic?: string | null; nsfw?: boolean; position: number; permission_overwrites?: Overwrite[] }
|
|
95
|
+
type Role = { id: string; name: string; color: number; hoist: boolean; mentionable: boolean; managed: boolean }
|
|
96
|
+
|
|
97
|
+
const same = (a: string, b: string): boolean => a.toLowerCase() === b.toLowerCase()
|
|
98
|
+
|
|
99
|
+
/** a channel shows as `<emoji>・<name>`; its name alone is its key */
|
|
100
|
+
const shown = (def: ChannelDef): string => (def.emoji === '' ? def.name : `${def.emoji}・${def.name}`)
|
|
101
|
+
|
|
102
|
+
/** the overwrites a channel wants: the everyone role is the guild's own id */
|
|
103
|
+
export function overwritesOf(def: ChannelDef, guild: string, roleIds: ReadonlyMap<string, string>): Overwrite[] {
|
|
104
|
+
return [
|
|
105
|
+
...(def.readOnly ? [{ id: guild, type: 0, allow: '0', deny: WRITE }] : []),
|
|
106
|
+
...(def.only.length === 0 ? [] : [{ id: guild, type: 0, allow: '0', deny: VIEW }]),
|
|
107
|
+
...def.only.flatMap((name) => {
|
|
108
|
+
const id = roleIds.get(name)
|
|
109
|
+
return id == null ? [] : [{ id, type: 0, allow: VIEW, deny: '0' }]
|
|
110
|
+
}),
|
|
111
|
+
]
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
const overwriteKey = (o: readonly Overwrite[]): string =>
|
|
115
|
+
o.map((x) => `${x.id}:${x.type}:${x.allow}:${x.deny}`).sort().join(',')
|
|
116
|
+
|
|
117
|
+
/** what differs between a channel and what it wants, by name; empty, it matches */
|
|
118
|
+
export function channelChanges(ch: Channel, want: { name: string; parent_id: string; topic?: string; nsfw: boolean; permission_overwrites: Overwrite[] }): string[] {
|
|
119
|
+
const out: string[] = []
|
|
120
|
+
if (ch.name !== want.name) out.push(`name ${want.name}`)
|
|
121
|
+
if (ch.parent_id !== want.parent_id) out.push('category')
|
|
122
|
+
if (want.topic != null && (ch.topic ?? '') !== want.topic) out.push('topic')
|
|
123
|
+
if ((ch.nsfw ?? false) !== want.nsfw) out.push(want.nsfw ? 'age restricted' : 'not age restricted')
|
|
124
|
+
if (overwriteKey(ch.permission_overwrites ?? []) !== overwriteKey(want.permission_overwrites)) out.push('permissions')
|
|
125
|
+
return out
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
export type ApplyReport = PushReport
|
|
129
|
+
|
|
130
|
+
/** what the bot's calls go through: the real api, or a test's */
|
|
131
|
+
export type Send = <T>(a: Account, method: string, path: string, body?: BodyInit) => Promise<T>
|
|
132
|
+
|
|
133
|
+
/** the guild features a server needs before its banner or invite splash takes a picture */
|
|
134
|
+
const NEEDS: Readonly<Record<string, string>> = { banner: 'BANNER', splash: 'INVITE_SPLASH' }
|
|
135
|
+
|
|
136
|
+
/** a picture as a data uri, the way Discord's api takes an image */
|
|
137
|
+
const dataUri = (abs: string): string => `data:${/\.png$/i.test(abs) ? 'image/png' : /\.webp$/i.test(abs) ? 'image/webp' : /\.gif$/i.test(abs) ? 'image/gif' : 'image/jpeg'};base64,${readFileSync(abs).toString('base64')}`
|
|
138
|
+
|
|
139
|
+
/** the server's stale picture rows (icon, banner, invite splash) set through the bot in one call, each recorded in
|
|
140
|
+
* shown.md; a banner or splash its boost level does not allow is left with the reason, still stale */
|
|
141
|
+
export async function pushServerPictures(a: Account, o: { dry: boolean }, send: Send = call, guild?: { features: string[] }): Promise<PushReport> {
|
|
142
|
+
const out: PushReport = { changes: [], left: [], recorded: [] }
|
|
143
|
+
const stale = toPush(a.uploads, 'discord')
|
|
144
|
+
if (stale.length === 0 || a.guild === '') return out
|
|
145
|
+
const g = guild ?? (await send<{ features: string[] }>(a, 'GET', `/guilds/${a.guild}`))
|
|
146
|
+
const body: Record<string, string> = {}
|
|
147
|
+
const sent: typeof stale = []
|
|
148
|
+
for (const u of stale) {
|
|
149
|
+
const key = DISCORD_ROWS[u.field]!
|
|
150
|
+
const need = NEEDS[key]
|
|
151
|
+
if (need != null && !g.features.includes(need)) {
|
|
152
|
+
out.left.push(`${u.field}: the server's boost level allows none yet (no ${need}), still stale`)
|
|
153
|
+
continue
|
|
154
|
+
}
|
|
155
|
+
body[key] = dataUri(u.abs[0]!)
|
|
156
|
+
sent.push(u)
|
|
157
|
+
}
|
|
158
|
+
if (sent.length === 0) return out
|
|
159
|
+
const words = sent.map((u) => `${u.field} (${u.files[0]})`).join(', ')
|
|
160
|
+
out.changes.push(o.dry ? `would set the server's ${words}` : `set the server's ${words}`)
|
|
161
|
+
if (o.dry) return out
|
|
162
|
+
await send(a, 'PATCH', `/guilds/${a.guild}`, JSON.stringify(body))
|
|
163
|
+
for (const u of sent) out.recorded.push(recordPushed(a, u))
|
|
164
|
+
return out
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/** makes the account's server match its layout and its picture rows; what it did (or would do, dry), what it left
|
|
168
|
+
* alone, the shown.md it wrote */
|
|
169
|
+
export async function applyLayout(a: Account, o: { dry: boolean; prune: boolean }): Promise<ApplyReport> {
|
|
170
|
+
const layout = layoutOf(a)
|
|
171
|
+
if (a.guild === '') {
|
|
172
|
+
const guilds = await call<{ id: string; name: string }[]>(a, 'GET', '/users/@me/guilds')
|
|
173
|
+
throw new Error(`${a.file}: no guild, the server's id; the bot is in ${guilds.map((g) => `${g.id} (${g.name})`).join(', ') || 'no server yet'}`)
|
|
174
|
+
}
|
|
175
|
+
const G = a.guild
|
|
176
|
+
const changes: string[] = []
|
|
177
|
+
const left: string[] = []
|
|
178
|
+
const json = (b: unknown): string => JSON.stringify(b)
|
|
179
|
+
const act = async (what: string, run: () => Promise<unknown>): Promise<void> => {
|
|
180
|
+
changes.push(o.dry ? `would ${what}` : what)
|
|
181
|
+
if (!o.dry) await run()
|
|
182
|
+
}
|
|
183
|
+
const guild = await call<{ name: string; owner_id: string; features: string[] }>(a, 'GET', `/guilds/${G}`)
|
|
184
|
+
if (guild.name !== layout.name) await act(`rename the server « ${layout.name} »`, () => call(a, 'PATCH', `/guilds/${G}`, json({ name: layout.name })))
|
|
185
|
+
const pictures = await pushServerPictures(a, o, call, guild)
|
|
186
|
+
changes.push(...pictures.changes)
|
|
187
|
+
left.push(...pictures.left)
|
|
188
|
+
|
|
189
|
+
const roles = await call<Role[]>(a, 'GET', `/guilds/${G}/roles`)
|
|
190
|
+
const roleIds = new Map<string, string>()
|
|
191
|
+
for (const def of layout.roles) {
|
|
192
|
+
const want = { name: def.name, color: def.color, hoist: def.hoist, mentionable: def.mentionable }
|
|
193
|
+
let role = roles.find((r) => !r.managed && same(r.name, def.name))
|
|
194
|
+
if (role == null) {
|
|
195
|
+
await act(`create the role ${def.name}`, async () => {
|
|
196
|
+
role = await call<Role>(a, 'POST', `/guilds/${G}/roles`, json({ ...want, permissions: '0' }))
|
|
197
|
+
})
|
|
198
|
+
} else if (role.name !== def.name || role.color !== def.color || role.hoist !== def.hoist || role.mentionable !== def.mentionable) {
|
|
199
|
+
const id = role.id
|
|
200
|
+
await act(`update the role ${def.name}`, () => call(a, 'PATCH', `/guilds/${G}/roles/${id}`, json(want)))
|
|
201
|
+
}
|
|
202
|
+
if (role != null) roleIds.set(def.name, role.id)
|
|
203
|
+
if (def.owner && role != null) {
|
|
204
|
+
const member = await call<{ roles: string[] }>(a, 'GET', `/guilds/${G}/members/${guild.owner_id}`)
|
|
205
|
+
const id = role.id
|
|
206
|
+
if (!member.roles.includes(id)) await act(`give the owner the role ${def.name}`, () => call(a, 'PUT', `/guilds/${G}/members/${guild.owner_id}/roles/${id}`))
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
for (const def of layout.members) {
|
|
211
|
+
const found = await call<{ user: { username: string; id: string }; roles: string[] }[]>(a, 'GET', `/guilds/${G}/members/search?query=${encodeURIComponent(def.name)}&limit=10`)
|
|
212
|
+
const member = found.find((x) => x.user.username === def.name)
|
|
213
|
+
if (member == null) {
|
|
214
|
+
left.push(`member ${def.name} (not in the server yet)`)
|
|
215
|
+
continue
|
|
216
|
+
}
|
|
217
|
+
for (const r of def.roles) {
|
|
218
|
+
const id = roleIds.get(r)
|
|
219
|
+
if (id == null) changes.push(`would give ${def.name} the role ${r}`)
|
|
220
|
+
else if (!member.roles.includes(id)) await act(`give ${def.name} the role ${r}`, () => call(a, 'PUT', `/guilds/${G}/members/${member.user.id}/roles/${id}`))
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
const channels = await call<Channel[]>(a, 'GET', `/guilds/${G}/channels`)
|
|
225
|
+
const kept = new Set<string>()
|
|
226
|
+
const moves: { id: string; position: number; label: string }[] = []
|
|
227
|
+
// Discord numbers positions across the whole server, one count per type (categories, text, voice), in the order shown
|
|
228
|
+
const next = new Map<number, number>()
|
|
229
|
+
const slot = (type: number): number => {
|
|
230
|
+
const n = next.get(type) ?? 0
|
|
231
|
+
next.set(type, n + 1)
|
|
232
|
+
return n
|
|
233
|
+
}
|
|
234
|
+
const place = (ch: Channel | undefined, type: number, label: string): void => {
|
|
235
|
+
const position = slot(type)
|
|
236
|
+
if (ch == null) return
|
|
237
|
+
kept.add(ch.id)
|
|
238
|
+
if (ch.position !== position) moves.push({ id: ch.id, position, label })
|
|
239
|
+
}
|
|
240
|
+
for (const cat of layout.categories) {
|
|
241
|
+
let c = channels.find((x) => x.type === CATEGORY && [cat.name, ...cat.was].some((n) => same(n, x.name)))
|
|
242
|
+
if (c == null) {
|
|
243
|
+
await act(`create the category ${cat.name}`, async () => {
|
|
244
|
+
c = await call<Channel>(a, 'POST', `/guilds/${G}/channels`, json({ name: cat.name, type: CATEGORY }))
|
|
245
|
+
})
|
|
246
|
+
} else if (c.name !== cat.name) {
|
|
247
|
+
const id = c.id
|
|
248
|
+
await act(`rename the category ${c.name} → ${cat.name}`, () => call(a, 'PATCH', `/channels/${id}`, json({ name: cat.name })))
|
|
249
|
+
}
|
|
250
|
+
place(c, CATEGORY, `the category ${cat.name}`)
|
|
251
|
+
if (c == null) {
|
|
252
|
+
for (const def of cat.channels) {
|
|
253
|
+
slot(def.voice ? VOICE : TEXT)
|
|
254
|
+
changes.push(`would create #${def.name} in ${cat.name}`)
|
|
255
|
+
}
|
|
256
|
+
continue
|
|
257
|
+
}
|
|
258
|
+
for (const def of cat.channels) {
|
|
259
|
+
const type = def.voice ? VOICE : TEXT
|
|
260
|
+
const want = { name: shown(def), parent_id: c.id, ...(def.voice ? {} : { topic: def.topic }), nsfw: def.ageRestricted, permission_overwrites: overwritesOf(def, G, roleIds) }
|
|
261
|
+
let ch = channels.find((x) => x.type === type && same(channelKey(x.name), def.name))
|
|
262
|
+
if (ch == null) {
|
|
263
|
+
await act(`create #${def.name} in ${cat.name}`, async () => {
|
|
264
|
+
ch = await call<Channel>(a, 'POST', `/guilds/${G}/channels`, json({ ...want, type }))
|
|
265
|
+
})
|
|
266
|
+
} else {
|
|
267
|
+
const diff = channelChanges(ch, want)
|
|
268
|
+
const id = ch.id
|
|
269
|
+
if (diff.length > 0) await act(`set #${def.name} (${cat.name}): ${diff.join(', ')}`, () => call(a, 'PATCH', `/channels/${id}`, json(want)))
|
|
270
|
+
}
|
|
271
|
+
place(ch, type, `#${def.name}`)
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
if (moves.length > 0) await act(`move ${moves.map((m) => m.label).join(', ')}`, () => call(a, 'PATCH', `/guilds/${G}/channels`, json(moves.map(({ id, position }) => ({ id, position })))))
|
|
275
|
+
|
|
276
|
+
for (const x of channels.filter((x) => !kept.has(x.id))) {
|
|
277
|
+
const empty = x.type !== TEXT || (await call<unknown[]>(a, 'GET', `/channels/${x.id}/messages?limit=1`)).length === 0
|
|
278
|
+
if (o.prune && empty && x.type === TEXT) await act(`delete #${x.name} (empty)`, () => call(a, 'DELETE', `/channels/${x.id}`))
|
|
279
|
+
else left.push(`${x.type === CATEGORY ? 'category ' : '#'}${x.name}${x.type === TEXT ? (empty ? ' (empty, --prune deletes it)' : ' (holds messages)') : ''}`)
|
|
280
|
+
}
|
|
281
|
+
return { changes, left, recorded: pictures.recorded }
|
|
282
|
+
}
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
// a staged media cut or shrunk before it is copied into a draft (wiki tools/shipkit/social.md, A post staged): a clip's
|
|
2
|
+
// passage between his in and out, and « fit », one copy within the tightest limits of the venues it goes to (the
|
|
3
|
+
// seconds first, then the bytes: a lower bitrate, a smaller frame). Each writes a new file in a scratch folder; the
|
|
4
|
+
// stage then copies it clean like any media. ffmpeg on the CPU, never the GPU
|
|
5
|
+
import { mkdtempSync, statSync } from 'node:fs'
|
|
6
|
+
import { tmpdir } from 'node:os'
|
|
7
|
+
import { extname, join } from 'node:path'
|
|
8
|
+
import sharp from 'sharp'
|
|
9
|
+
import type { MediaLimits } from '../identities/identities.ts'
|
|
10
|
+
import { mp4Seconds } from './media-limit.ts'
|
|
11
|
+
|
|
12
|
+
const VIDEO = /\.(mp4|m4v|mov|webm)$/i
|
|
13
|
+
const IMAGE = /\.(png|jpe?g|webp)$/i
|
|
14
|
+
|
|
15
|
+
const scratch = (name: string): string => join(mkdtempSync(join(tmpdir(), 'stage-fit-')), name)
|
|
16
|
+
|
|
17
|
+
function ffmpeg(args: string[]): void {
|
|
18
|
+
const r = Bun.spawnSync(['ffmpeg', '-v', 'error', '-y', ...args], { stdout: 'ignore', stderr: 'pipe' })
|
|
19
|
+
if (r.exitCode !== 0) throw new Error(`ffmpeg: ${r.stderr.toString().trim().split('\n').at(-1) ?? `exit ${r.exitCode}`}`)
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** a clip's length in seconds: its mvhd box, else ffprobe */
|
|
23
|
+
export function secondsOf(file: string): number {
|
|
24
|
+
const s = /\.(mp4|m4v|mov)$/i.test(file) ? mp4Seconds(file) : null
|
|
25
|
+
if (s != null) return s
|
|
26
|
+
const r = Bun.spawnSync(['ffprobe', '-v', 'error', '-show_entries', 'format=duration', '-of', 'default=nw=1:nk=1', file], { stdout: 'pipe', stderr: 'ignore' })
|
|
27
|
+
const d = Number(r.stdout.toString().trim())
|
|
28
|
+
if (!Number.isFinite(d)) throw new Error(`${file}: no length ffprobe reads`)
|
|
29
|
+
return d
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** the passage of a clip from `from` to `to` seconds, encoded again so it starts on its first frame: an mp4 */
|
|
33
|
+
export function cutPassage(file: string, from: number, to: number): string {
|
|
34
|
+
if (!VIDEO.test(file)) throw new Error(`a passage is cut from a clip, not ${extname(file)}`)
|
|
35
|
+
const len = secondsOf(file)
|
|
36
|
+
if (!(from >= 0 && to > from && from < len)) throw new Error(`passage ${from} s to ${to} s: in a clip of ${len.toFixed(2)} s, in before out`)
|
|
37
|
+
const out = scratch('passage.mp4')
|
|
38
|
+
ffmpeg(['-ss', String(from), '-to', String(Math.min(to, len)), '-i', file, '-c:v', 'libx264', '-crf', '18', '-preset', 'veryfast', '-pix_fmt', 'yuv420p', '-c:a', 'aac', '-b:a', '128k', '-movflags', '+faststart', out])
|
|
39
|
+
return out
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** the tightest of several venues' limits: each bound the smallest one any venue names */
|
|
43
|
+
export function tightest(all: readonly MediaLimits[]): MediaLimits {
|
|
44
|
+
const min = (k: keyof MediaLimits): number | undefined => {
|
|
45
|
+
const v = all.flatMap((l) => (l[k] == null ? [] : [l[k]!]))
|
|
46
|
+
return v.length ? Math.min(...v) : undefined
|
|
47
|
+
}
|
|
48
|
+
const out: MediaLimits = {}
|
|
49
|
+
for (const k of ['imageBytes', 'videoBytes', 'videoSeconds'] as const) {
|
|
50
|
+
const v = min(k)
|
|
51
|
+
if (v != null) out[k] = v
|
|
52
|
+
}
|
|
53
|
+
return out
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** one copy within the limits, or the file itself when it already fits; a clip: its first seconds up to the bound, then
|
|
57
|
+
* a bitrate that lands under the bytes with a margin; an image: a jpeg whose quality steps down until it fits */
|
|
58
|
+
export async function fitTo(file: string, l: MediaLimits): Promise<string> {
|
|
59
|
+
const size = statSync(file).size
|
|
60
|
+
if (IMAGE.test(file)) {
|
|
61
|
+
if (l.imageBytes == null || size <= l.imageBytes) return file
|
|
62
|
+
for (const [q, w] of [[90, 4096], [82, 2560], [74, 2048], [66, 1600], [58, 1280]] as const) {
|
|
63
|
+
const out = scratch(`fit-${q}.jpg`)
|
|
64
|
+
await sharp(file).rotate().resize({ width: w, height: w, fit: 'inside', withoutEnlargement: true }).jpeg({ quality: q, mozjpeg: true }).toFile(out)
|
|
65
|
+
if (statSync(out).size <= l.imageBytes) return out
|
|
66
|
+
}
|
|
67
|
+
throw new Error(`${file}: no jpeg under ${(l.imageBytes / 1e6).toFixed(1)} MB down to 1280 px`)
|
|
68
|
+
}
|
|
69
|
+
if (!VIDEO.test(file)) return file
|
|
70
|
+
const len = secondsOf(file)
|
|
71
|
+
const secs = l.videoSeconds != null && len > l.videoSeconds ? l.videoSeconds : len
|
|
72
|
+
if (secs === len && (l.videoBytes == null || size <= l.videoBytes)) return file
|
|
73
|
+
const out = scratch('fit.mp4')
|
|
74
|
+
const kbps = l.videoBytes == null ? null : Math.floor(((l.videoBytes * 8 * 0.9) / secs - 128_000) / 1000)
|
|
75
|
+
if (kbps != null && kbps < 300) throw new Error(`${file}: ${secs.toFixed(1)} s under ${(l.videoBytes! / 1e6).toFixed(0)} MB leaves ${kbps} kb/s, too few for a clip worth posting: cut a passage`)
|
|
76
|
+
ffmpeg([
|
|
77
|
+
'-i', file, '-t', String(secs),
|
|
78
|
+
'-c:v', 'libx264', '-preset', 'veryfast', '-pix_fmt', 'yuv420p',
|
|
79
|
+
...(kbps == null ? ['-crf', '20'] : ['-b:v', `${kbps}k`, '-maxrate', `${kbps}k`, '-bufsize', `${kbps * 2}k`]),
|
|
80
|
+
'-vf', 'scale=w=min(1920\\,iw):h=-2',
|
|
81
|
+
'-c:a', 'aac', '-b:a', '128k', '-movflags', '+faststart', out,
|
|
82
|
+
])
|
|
83
|
+
return out
|
|
84
|
+
}
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
// an identity's public words and pictures through the guard of each repo that speaks as it (wiki
|
|
2
|
+
// tools/shipkit/social-identities.md, The guard on the rows): its profile rows and each account's own (a text, or the
|
|
3
|
+
// pictures a row names), its Discord server's name, roles, categories, channels and topics. The desk reads them with its
|
|
4
|
+
// repo's guard; a push to a venue reads them with the guard of every repo speaking as the identity, before any call
|
|
5
|
+
import { existsSync } from 'node:fs'
|
|
6
|
+
import { join } from 'node:path'
|
|
7
|
+
import type { Identity } from '../identities/identities.ts'
|
|
8
|
+
import { layoutOf } from './discord-layout.ts'
|
|
9
|
+
import { guardWith, type GuardInput, type SocialUnit } from './unit.ts'
|
|
10
|
+
|
|
11
|
+
/** one public word or picture of an identity, `where` its file and row as a problem line names them */
|
|
12
|
+
export type IdentityWord = { where: string; input: Partial<GuardInput> }
|
|
13
|
+
|
|
14
|
+
/** every row once (an account's row it inherits is the identity's), then the server's layout */
|
|
15
|
+
export function identityWords(i: Identity): IdentityWord[] {
|
|
16
|
+
const out: IdentityWord[] = []
|
|
17
|
+
const seen = new Set<string>()
|
|
18
|
+
const base = i.files ?? i.dir
|
|
19
|
+
const row = (file: string, r: { field: string; value: string; files: string[] }): void => {
|
|
20
|
+
const key = JSON.stringify([r.field, r.value])
|
|
21
|
+
if (seen.has(key)) return
|
|
22
|
+
seen.add(key)
|
|
23
|
+
const files = r.files.map((f) => join(base, f)).filter((f) => existsSync(f))
|
|
24
|
+
out.push({ where: `${file}: row ${r.field}`, input: r.files.length > 0 ? { files } : { texts: [r.value] } })
|
|
25
|
+
}
|
|
26
|
+
for (const r of i.rows) row(i.file, r)
|
|
27
|
+
for (const a of i.accounts) for (const r of a.rows) row(a.file, r)
|
|
28
|
+
const discord = i.accounts.find((a) => a.id === 'discord')
|
|
29
|
+
if (discord != null && existsSync(join(discord.dir, 'layout.md'))) {
|
|
30
|
+
// a layout that does not parse is the layout's own error line, said where it is read
|
|
31
|
+
const l = (() => {
|
|
32
|
+
try {
|
|
33
|
+
return layoutOf(discord)
|
|
34
|
+
} catch {
|
|
35
|
+
return null
|
|
36
|
+
}
|
|
37
|
+
})()
|
|
38
|
+
if (l != null) {
|
|
39
|
+
out.push({ where: `${l.file}: the server's name`, input: { texts: [l.name] } })
|
|
40
|
+
// a role's name shows beside each member it is given
|
|
41
|
+
for (const r of l.roles) out.push({ where: `${l.file}: role ${r.name}`, input: { texts: [r.name] } })
|
|
42
|
+
for (const c of l.categories) {
|
|
43
|
+
out.push({ where: `${l.file}: category ${c.name}`, input: { texts: [c.name] } })
|
|
44
|
+
for (const ch of c.channels) out.push({ where: `${l.file}: channel ${ch.name}`, input: { texts: [ch.name, ch.topic].filter((t) => t.trim() !== '') } })
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
return out
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** what the guards refuse of an identity's words, one line each, `<file>: row <field>: <problem>` */
|
|
52
|
+
export function identityProblems(units: readonly (SocialUnit | null)[], i: Identity): string[] {
|
|
53
|
+
const words = identityWords(i)
|
|
54
|
+
return [...new Set(units.flatMap((u) => words.flatMap((w) => guardWith(u, w.input).map((p) => `${w.where}: ${p}`))))]
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** the social units of the house repos that speak as `id`: the guards a push of its words to a venue passes */
|
|
58
|
+
export async function speakersUnits(id: string, cwd = process.cwd()): Promise<SocialUnit[]> {
|
|
59
|
+
const { houseRepoRoots } = await import('./house.ts')
|
|
60
|
+
const { loadSocialUnit } = await import('./unit.ts')
|
|
61
|
+
const out: SocialUnit[] = []
|
|
62
|
+
for (const r of await houseRepoRoots(cwd)) {
|
|
63
|
+
if (r.speaksAs !== id) continue
|
|
64
|
+
const u = await loadSocialUnit(r.path)
|
|
65
|
+
if (u != null) out.push(u)
|
|
66
|
+
}
|
|
67
|
+
return out
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** the push of an identity's words to a venue, refused while a guard of a repo speaking as it names a problem */
|
|
71
|
+
export async function refuseUnguarded(i: Identity, cwd = process.cwd()): Promise<void> {
|
|
72
|
+
const problems = identityProblems(await speakersUnits(i.id, cwd), i)
|
|
73
|
+
if (problems.length > 0) throw new Error(`the guard of a repo speaking as ${i.id} refuses ${problems.length === 1 ? 'one of its words' : `${problems.length} of its words`}, so nothing is pushed:\n ${problems.join('\n ')}`)
|
|
74
|
+
}
|