rvlib-shipkit 2.20.0 → 2.22.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (156) hide show
  1. package/CHANGELOG.md +35 -0
  2. package/package.json +1 -1
  3. package/src/asks/asks-queue.ts +8 -7
  4. package/src/assets/kits/identity-kit.ts +158 -2
  5. package/src/checks/SK004-gitignore-policy.check.ts +6 -3
  6. package/src/cli/cmd_Bump.ts +3 -3
  7. package/src/cli/cmd_GlobalProcesses.ts +2 -107
  8. package/src/cli/cmd_Home.ts +1 -1
  9. package/src/cli/cmd_Overview.ts +2 -1
  10. package/src/cli/cmd_Rec.ts +349 -0
  11. package/src/cli/cmd_Releases.ts +42 -3
  12. package/src/cli/cmd_Review.ts +22 -13
  13. package/src/cli/cmd_Secret.ts +10 -3
  14. package/src/cli/cmd_Sign.ts +24 -0
  15. package/src/cli/cmd_Social.ts +57 -8
  16. package/src/cli/cmd_Sound.ts +17 -4
  17. package/src/cli/cmd_Trailer.ts +67 -1
  18. package/src/cli/family-pages.ts +1 -0
  19. package/src/cli/registry.ts +6 -1
  20. package/src/collections/collection-types.ts +1 -1
  21. package/src/collections/review.ts +23 -4
  22. package/src/core/agent-spawn.ts +4 -17
  23. package/src/core/code-lines.ts +49 -0
  24. package/src/core/discover-checks.ts +27 -3
  25. package/src/core/hard-reset.ts +34 -0
  26. package/src/core/layout.ts +6 -0
  27. package/src/core/raw-access.ts +3 -13
  28. package/src/core/throwaway-worktree.ts +72 -0
  29. package/src/home/app-sign.ts +98 -0
  30. package/src/home/gui-app/ShipkitGui.swift +35 -0
  31. package/src/home/gui-app.ts +31 -11
  32. package/src/home/home-routes.ts +6 -0
  33. package/src/home/pm-switch.ts +112 -0
  34. package/src/home/serve-web.ts +1 -1
  35. package/src/identities/identities.ts +17 -6
  36. package/src/media-kinds.ts +5 -3
  37. package/src/media-store/forget.ts +54 -0
  38. package/src/media-store/put.ts +4 -3
  39. package/src/media-store/space.ts +63 -24
  40. package/src/messages/brief.ts +3 -3
  41. package/src/messages/score.ts +2 -0
  42. package/src/recordings/delete.ts +19 -0
  43. package/src/recordings/edit.ts +231 -0
  44. package/src/recordings/load.ts +37 -0
  45. package/src/recordings/marks-draw.ts +111 -0
  46. package/src/recordings/marks-png.ts +25 -0
  47. package/src/recordings/marks.ts +138 -0
  48. package/src/recordings/media-kind.ts +67 -0
  49. package/src/recordings/model.ts +170 -0
  50. package/src/recordings/open.ts +33 -0
  51. package/src/recordings/place.ts +89 -0
  52. package/src/recordings/presets.ts +99 -0
  53. package/src/recordings/recorder-app/Capture.swift +510 -0
  54. package/src/recordings/recorder-app/Clip.swift +107 -0
  55. package/src/recordings/recorder-app/Editor.swift +39 -0
  56. package/src/recordings/recorder-app/Tray.swift +298 -0
  57. package/src/recordings/recorder-app/main.swift +859 -0
  58. package/src/recordings/recorder-app.ts +46 -0
  59. package/src/recordings/recorder.shipkit.ts +11 -0
  60. package/src/recordings/routes.ts +140 -0
  61. package/src/recordings/run-recorder.ts +40 -0
  62. package/src/recordings/share.ts +107 -0
  63. package/src/recordings/take.ts +146 -0
  64. package/src/recordings/view.ts +40 -0
  65. package/src/release/gate-checkout.ts +74 -0
  66. package/src/release/release-scope.ts +35 -26
  67. package/src/release/run-bump.ts +79 -37
  68. package/src/release/run-release.ts +67 -53
  69. package/src/releases/add.ts +38 -5
  70. package/src/releases/before.ts +31 -0
  71. package/src/releases/from-card.ts +105 -20
  72. package/src/releases/model.ts +100 -18
  73. package/src/releases/pictures.ts +29 -8
  74. package/src/repo-config.ts +7 -3
  75. package/src/review/http.ts +1 -1
  76. package/src/review/model.ts +12 -2
  77. package/src/review/stage-card.ts +1 -1
  78. package/src/review/store.ts +12 -2
  79. package/src/review/trailer-desk.ts +20 -0
  80. package/src/review/trailer-model.ts +67 -0
  81. package/src/review/trailer-routes.ts +98 -1
  82. package/src/review/trailer-voices.ts +144 -0
  83. package/src/review/watchers.ts +58 -1
  84. package/src/secrets/manager.ts +18 -1
  85. package/src/serve/hub-app/benign-errors.ts +22 -0
  86. package/src/serve/hub-app/hash-route.ts +27 -15
  87. package/src/serve/hub-app/home-st.ts +23 -5
  88. package/src/serve/hub-app/home.html +1 -0
  89. package/src/serve/hub-app/hub-app.tsx +8 -1
  90. package/src/serve/hub-app/icons.tsx +2 -0
  91. package/src/serve/hub-app/palette-st.ts +1 -0
  92. package/src/serve/hub-app/project-list.css +7 -2
  93. package/src/serve/hub-app/project-list.tsx +10 -0
  94. package/src/serve/hub-app/projects-svc.ts +17 -7
  95. package/src/serve/hub-app/recordings-st.ts +641 -0
  96. package/src/serve/hub-app/recordings-view.tsx +504 -0
  97. package/src/serve/hub-app/recordings.css +82 -0
  98. package/src/serve/hub-app/releases/releases-page.tsx +121 -28
  99. package/src/serve/hub-app/releases/releases-st.ts +46 -4
  100. package/src/serve/hub-app/releases.css +30 -3
  101. package/src/serve/hub-app/repo-sections.ts +1 -1
  102. package/src/serve/hub-app/repo-st.ts +16 -11
  103. package/src/serve/hub-app/review/clip-st.ts +3 -1
  104. package/src/serve/hub-app/review/kit.tsx +3 -3
  105. package/src/serve/hub-app/review/trailer-page.tsx +32 -6
  106. package/src/serve/hub-app/review/trailer-st.ts +184 -8
  107. package/src/serve/hub-app/review/trailer-timeline.tsx +39 -4
  108. package/src/serve/hub-app/review/trailer-voices-st.ts +370 -0
  109. package/src/serve/hub-app/review/trailer-voices.tsx +574 -0
  110. package/src/serve/hub-app/review.css +90 -0
  111. package/src/serve/hub-app/social/comms-page.tsx +10 -5
  112. package/src/serve/hub-app/social/next-release.tsx +118 -0
  113. package/src/serve/hub-app/social/post-card.tsx +31 -3
  114. package/src/serve/hub-app/social/social-model.ts +6 -0
  115. package/src/serve/hub-app/social/social-st.ts +50 -1
  116. package/src/serve/hub-app/social.css +12 -0
  117. package/src/serve/hub-app/tree-build.ts +2 -0
  118. package/src/serve/project-gutter-route.ts +8 -0
  119. package/src/serve/project-gutter.ts +4 -2
  120. package/src/shipkit.ts +2 -2
  121. package/src/shot/box.ts +49 -22
  122. package/src/shot/browser-slot.ts +13 -3
  123. package/src/shot/client.ts +1 -1
  124. package/src/shot/film-box.ts +193 -117
  125. package/src/shot/shooter.ts +20 -8
  126. package/src/smoke/run-smoke.ts +8 -6
  127. package/src/social/compose.ts +14 -0
  128. package/src/social/desk-index.ts +49 -8
  129. package/src/social/discord-layout.ts +6 -2
  130. package/src/social/drafts.ts +1 -1
  131. package/src/social/kinds.ts +3 -2
  132. package/src/social/load.ts +42 -9
  133. package/src/social/publish/index.ts +27 -10
  134. package/src/social/publish/secret.ts +12 -4
  135. package/src/social/release-card.ts +69 -0
  136. package/src/social/release-stage.ts +173 -30
  137. package/src/social/routes.ts +7 -1
  138. package/src/social/stage.ts +45 -22
  139. package/src/trailer/bed.ts +111 -0
  140. package/src/trailer/build.ts +81 -38
  141. package/src/trailer/ffmpeg.ts +14 -0
  142. package/src/trailer/grammar.ts +32 -4
  143. package/src/trailer/graph.ts +12 -1
  144. package/src/trailer/look.ts +7 -0
  145. package/src/trailer/shot-plan.ts +75 -0
  146. package/src/trailer/shot-state.ts +191 -0
  147. package/src/trailer/sound/audio.ts +28 -0
  148. package/src/trailer/sound/brand.ts +53 -3
  149. package/src/trailer/sound/gen.ts +61 -2
  150. package/src/trailer/sound/index.ts +25 -11
  151. package/src/trailer/sound/presets.ts +86 -5
  152. package/src/trailer/sound/run.ts +1 -1
  153. package/src/trailer/sound/takes.ts +94 -0
  154. package/src/trailer/titles.ts +36 -0
  155. package/src/trailer/url.ts +1 -1
  156. package/src/veille/chrome.ts +6 -3
@@ -0,0 +1,72 @@
1
+ // a throwaway checkout of a repo's commit: a linked worktree under the temp
2
+ // dir, kept between runs and brought back to the commit asked for, so a build
3
+ // or a gate writes only what changed. Every other tree may hold someone's
4
+ // unsaved work, so this module is the ONE place a working tree is wiped to a
5
+ // commit (tests/no-hard-reset.test.ts allows it here only), and it wipes only
6
+ // a folder it can prove it made: a linked worktree of that repo, at the path
7
+ // this module derives, carrying the mark it wrote into the worktree's own git
8
+ // dir. Anything else at that path is refused and left as it is.
9
+ import { existsSync, lstatSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'fs'
10
+ import { tmpdir } from 'os'
11
+ import { join } from 'path'
12
+ import { gitBin } from './git-bin.ts'
13
+
14
+ const git = (cwd: string, args: string[]): { code: number; out: string } => {
15
+ const p = Bun.spawnSync([gitBin(), ...args], { cwd, stdout: 'pipe', stderr: 'pipe' })
16
+ return { code: p.exitCode, out: `${p.stdout.toString()}${p.stderr.toString()}`.trim() }
17
+ }
18
+
19
+ const MARK = 'shipkit-throwaway'
20
+
21
+ /** where `repo`'s throwaway checkout for `purpose` lives: one per checkout of a repo and purpose */
22
+ export function throwawayDir(repo: string, purpose: string): string {
23
+ const hash = new Bun.CryptoHasher('sha256').update(realpathSync(repo)).digest('hex').slice(0, 10)
24
+ return join(realpathSync(tmpdir()), `shipkit-throwaway-${purpose}-${hash}`)
25
+ }
26
+
27
+ /** the git dir of `dir` when it is a linked worktree of `repo` carrying this module's mark, else why not */
28
+ function ownGitDir(repo: string, dir: string): { gitDir: string } | { refuse: string } {
29
+ const dotGit = join(dir, '.git')
30
+ if (!existsSync(dotGit) || !lstatSync(dotGit).isFile()) return { refuse: 'it is not a linked worktree' }
31
+ const r = git(dir, ['rev-parse', '--path-format=absolute', '--show-toplevel', '--git-dir', '--git-common-dir'])
32
+ const [top, gitDir, common] = r.out.split('\n')
33
+ if (r.code !== 0 || top == null || gitDir == null || common == null) return { refuse: `git cannot read it (${r.out.split('\n')[0]})` }
34
+ const repoCommon = git(repo, ['rev-parse', '--path-format=absolute', '--git-common-dir']).out
35
+ const real = (p: string): string => { try { return realpathSync(p) } catch { return p } }
36
+ if (real(top) !== real(dir)) return { refuse: `its checkout is ${top}` }
37
+ if (real(gitDir) === real(common)) return { refuse: 'it is a main worktree' }
38
+ if (real(common) !== real(repoCommon)) return { refuse: `it belongs to the repo at ${common}` }
39
+ const mark = join(gitDir, MARK)
40
+ if (!existsSync(mark) || readFileSync(mark, 'utf8') !== real(dir)) return { refuse: 'shipkit did not make it' }
41
+ return { gitDir }
42
+ }
43
+
44
+ /** `repo` at `sha` in its throwaway checkout for `purpose`, every untracked and ignored file removed:
45
+ * made when absent, brought back when it is one this module made, refused when anything else holds the path */
46
+ export function throwawayCheckout(repo: string, purpose: string, sha: string): { dir: string } | { error: string } {
47
+ if (!/^[a-z0-9][a-z0-9-]*$/.test(purpose)) return { error: `throwaway purpose '${purpose}': lowercase letters, digits and dashes only` }
48
+ const dir = throwawayDir(repo, purpose)
49
+ if (existsSync(dir)) {
50
+ const own = ownGitDir(repo, dir)
51
+ if ('refuse' in own) return { error: `${dir} exists and is not a throwaway checkout shipkit made (${own.refuse}), so nothing in it was touched. fix: move it away (mv ${dir} ${dir}.old), then run again` }
52
+ // the only reset of a working tree to a commit in this toolkit: a proven throwaway
53
+ const back = git(dir, ['reset', '--hard', '--quiet', sha])
54
+ if (back.code !== 0) {
55
+ rmSync(dir, { recursive: true, force: true })
56
+ git(repo, ['worktree', 'prune'])
57
+ }
58
+ }
59
+ if (!existsSync(dir)) {
60
+ git(repo, ['worktree', 'prune'])
61
+ const add = git(repo, ['worktree', 'add', '--detach', '--quiet', dir, sha])
62
+ if (add.code !== 0) return { error: `cannot make the throwaway checkout at ${dir}: ${add.out}` }
63
+ const gitDir = git(dir, ['rev-parse', '--path-format=absolute', '--git-dir'])
64
+ if (gitDir.code !== 0) return { error: `cannot read the git dir of ${dir}: ${gitDir.out}` }
65
+ writeFileSync(join(gitDir.out, MARK), realpathSync(dir))
66
+ const own = ownGitDir(repo, dir)
67
+ if ('refuse' in own) return { error: `the throwaway checkout at ${dir} fails its own proof (${own.refuse})` }
68
+ }
69
+ const clean = git(dir, ['clean', '-ffdxq'])
70
+ if (clean.code !== 0) return { error: `cannot clean the throwaway checkout at ${dir}: ${clean.out}` }
71
+ return { dir }
72
+ }
@@ -0,0 +1,98 @@
1
+ // the machine's own code signing identity for shipkit's apps (wiki tools/shipkit/home-pages.md, Signing): an ad hoc
2
+ // signature names the binary's hash, so macOS forgets a permission (Screen Recording, Accessibility) at every rebuild;
3
+ // an identity's certificate names the app across rebuilds. Made once by `sk sign-setup`: a self signed code signing
4
+ // certificate in a keychain of its own, its random password kept in the login keychain (never in a file), trusted
5
+ // for code signing by the owner's one password prompt. Absent or not trusted: the apps stay ad hoc, said once
6
+ import { existsSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'
7
+ import { tmpdir } from 'node:os'
8
+ import { join } from 'node:path'
9
+ import { homeDir } from './home-paths.ts'
10
+
11
+ export const SIGN_NAME = 'Shipkit Local Signing'
12
+ const PW_SERVICE = 'shipkit-signing-keychain'
13
+ export const signingKeychain = (): string => process.env.SHIPKIT_SIGNING_KEYCHAIN ?? join(homeDir(), 'signing.keychain-db')
14
+
15
+ type Run = (cmd: string[], o?: { stdin?: string }) => { code: number; out: string; err: string }
16
+ const run: Run = (cmd, o = {}) => {
17
+ const p = Bun.spawnSync(cmd, { stdout: 'pipe', stderr: 'pipe', ...(o.stdin !== undefined ? { stdin: Buffer.from(o.stdin) } : {}) })
18
+ return { code: p.exitCode ?? 1, out: p.stdout.toString(), err: p.stderr.toString().trim() }
19
+ }
20
+
21
+ const password = (r: Run = run): string | null => {
22
+ const p = r(['security', 'find-generic-password', '-s', PW_SERVICE, '-a', 'shipkit', '-w'])
23
+ return p.code === 0 ? p.out.trim() : null
24
+ }
25
+
26
+ /** the signing keychain in the user's search list: codesign finds an identity only there, `--keychain` or not */
27
+ function listed(kc: string, r: Run): void {
28
+ const now = r(['security', 'list-keychains', '-d', 'user']).out.split('\n').map((l) => l.trim().replace(/^"|"$/g, '')).filter((l) => l !== '')
29
+ if (now.includes(kc)) return
30
+ r(['security', 'list-keychains', '-d', 'user', '-s', ...now, kc])
31
+ }
32
+
33
+ /** the identity's SHA-1 when it is there and trusted for code signing, its keychain unlocked; null otherwise */
34
+ export function signingIdentity(r: Run = run): string | null {
35
+ const kc = signingKeychain()
36
+ if (process.platform !== 'darwin' || !existsSync(kc)) return null
37
+ const pw = password(r)
38
+ if (pw === null) return null
39
+ // a keychain locks at a restart: opened again with its own password
40
+ r(['security', 'unlock-keychain', '-p', pw, kc])
41
+ listed(kc, r)
42
+ const v = r(['security', 'find-identity', '-v', '-p', 'codesigning', kc])
43
+ return new RegExp(`([0-9A-F]{40}) "${SIGN_NAME}"`).exec(v.out)?.[1] ?? null
44
+ }
45
+
46
+ /** the codesign arguments of a bundle: the identity when there is one, else ad hoc */
47
+ export function signArgs(r: Run = run): string[] {
48
+ const id = signingIdentity(r)
49
+ return id ? ['--sign', id, '--keychain', signingKeychain()] : ['--sign', '-']
50
+ }
51
+
52
+ /** the identity made and trusted: the trust step shows the owner macOS's own password prompt. Idempotent */
53
+ export function setupSigning(say: (l: string) => void, r: Run = run): void {
54
+ if (process.platform !== 'darwin') throw new Error('signing is macOS only')
55
+ if (signingIdentity(r)) {
56
+ say(`ok: ${SIGN_NAME} is set up and trusted (${signingKeychain()})`)
57
+ return
58
+ }
59
+ const kc = signingKeychain()
60
+ const tmp = mkdtempSync(join(tmpdir(), 'shipkit-sign-'))
61
+ try {
62
+ let pw = password(r)
63
+ if (!existsSync(kc)) {
64
+ pw = crypto.randomUUID() + crypto.randomUUID()
65
+ const kept = r(['security', 'add-generic-password', '-U', '-s', PW_SERVICE, '-a', 'shipkit', '-w', pw])
66
+ if (kept.code !== 0) throw new Error(`the login keychain did not keep the password: ${kept.err}`)
67
+ const cfg = ['[req]', 'distinguished_name=dn', 'x509_extensions=ext', 'prompt=no', '[dn]', `CN=${SIGN_NAME}`, '[ext]', 'basicConstraints=critical,CA:false', 'keyUsage=critical,digitalSignature', 'extendedKeyUsage=critical,codeSigning'].join('\n')
68
+ writeFileSync(join(tmp, 'cfg'), cfg)
69
+ const steps: string[][] = [
70
+ ['openssl', 'req', '-x509', '-newkey', 'rsa:2048', '-nodes', '-keyout', join(tmp, 'k.pem'), '-out', join(tmp, 'c.pem'), '-days', '3650', '-config', join(tmp, 'cfg')],
71
+ ['openssl', 'pkcs12', '-export', '-legacy', '-inkey', join(tmp, 'k.pem'), '-in', join(tmp, 'c.pem'), '-out', join(tmp, 'id.p12'), '-passout', 'pass:shipkit'],
72
+ ['security', 'create-keychain', '-p', pw, kc],
73
+ // no lock on a timer: codesign runs whenever an app is rebuilt
74
+ ['security', 'set-keychain-settings', kc],
75
+ ['security', 'unlock-keychain', '-p', pw, kc],
76
+ ['security', 'import', join(tmp, 'id.p12'), '-k', kc, '-P', 'shipkit', '-T', '/usr/bin/codesign'],
77
+ ['security', 'set-key-partition-list', '-S', 'apple-tool:,apple:,codesign:', '-s', '-k', pw, kc],
78
+ ]
79
+ for (const s of steps) {
80
+ const res = r(s)
81
+ if (res.code !== 0) throw new Error(`${s.slice(0, 2).join(' ')}: ${res.err.slice(0, 300)}`)
82
+ }
83
+ say(`ok: ${SIGN_NAME} made in ${kc}`)
84
+ } else if (pw === null) throw new Error(`${kc} exists, its password is not in the login keychain: delete ${kc} and run again`)
85
+ // the certificate as the keychain holds it, trusted for code signing in the owner's own trust settings
86
+ const cert = r(['security', 'find-certificate', '-c', SIGN_NAME, '-p', kc])
87
+ if (cert.code !== 0) throw new Error(`no certificate ${SIGN_NAME} in ${kc}: ${cert.err}`)
88
+ writeFileSync(join(tmp, 'trust.pem'), cert.out)
89
+ say('macOS asks for your password once now, to trust it for code signing…')
90
+ const t = r(['security', 'add-trusted-cert', '-r', 'trustRoot', '-p', 'codeSign', join(tmp, 'trust.pem')])
91
+ if (t.code !== 0) throw new Error(`the trust was not given: ${t.err || `exit ${t.code}`}`)
92
+ const id = signingIdentity(r)
93
+ if (!id) throw new Error(`${SIGN_NAME} is still not valid for code signing`)
94
+ say(`ok: ${SIGN_NAME} trusted (${id.slice(0, 12)}): shipkit's apps keep their permissions across rebuilds`)
95
+ } finally {
96
+ rmSync(tmp, { recursive: true, force: true })
97
+ }
98
+ }
@@ -173,6 +173,7 @@ final class Delegate: NSObject, NSApplicationDelegate, WKNavigationDelegate, WKU
173
173
 
174
174
  func applicationDidFinishLaunching(_ note: Notification) {
175
175
  if CommandLine.arguments.contains("--self-test-find") { return selfTestFind() }
176
+ if CommandLine.arguments.contains("--self-test-mic") { return selfTestMic() }
176
177
  if CommandLine.arguments.contains("--self-test-panels") { return selfTestPanels() }
177
178
  if CommandLine.arguments.contains("--self-test-download") { return selfTestDownload() }
178
179
  if CommandLine.arguments.contains("--self-test-badge") { return selfTestBadge() }
@@ -345,6 +346,32 @@ final class Delegate: NSObject, NSApplicationDelegate, WKNavigationDelegate, WKU
345
346
  web.loadHTMLString("<p>one needle, two needle</p>", baseURL: nil)
346
347
  }
347
348
 
349
+ // `--self-test-mic`: a window's own web view on a page of the machine, then on a page of another host, each
350
+ // printing whether the page can reach the microphone api (`getUserMedia`); no capture is asked, so no prompt
351
+ func selfTestMic() {
352
+ let web = WKWebView(frame: NSRect(x: 0, y: 0, width: 400, height: 300), configuration: webConfig())
353
+ web.navigationDelegate = self
354
+ web.uiDelegate = self
355
+ windows.append(NSWindow(contentRect: NSRect(x: -4000, y: -4000, width: 400, height: 300), styleMask: [.titled], backing: .buffered, defer: false))
356
+ windows.last?.contentView = web
357
+ let probe = "typeof (navigator.mediaDevices && navigator.mediaDevices.getUserMedia)"
358
+ onLoad = { _ in
359
+ web.evaluateJavaScript(probe) { local, _ in
360
+ print("local=\(local as? String ?? "error")")
361
+ self.onLoad = { _ in
362
+ web.evaluateJavaScript(probe) { other, _ in
363
+ print("other=\(other as? String ?? "error")")
364
+ exit((local as? String) == "function" ? 0 : 1)
365
+ }
366
+ }
367
+ web.loadHTMLString("<p>other</p>", baseURL: URL(string: "http://example.invalid/"))
368
+ }
369
+ }
370
+ // the page the test serves on the machine, loaded over http as a window loads the home
371
+ let served = CommandLine.arguments.last.flatMap { URL(string: $0) }.flatMap { $0.scheme == "http" ? $0 : nil }
372
+ if let url = served { web.load(URLRequest(url: url)) } else { web.loadHTMLString("<p>local</p>", baseURL: URL(string: "http://127.0.0.1:9/")) }
373
+ }
374
+
348
375
  /** hears every js panel once it shows: the self test answers it */
349
376
  var onPanel: ((NSAlert) -> Void)?
350
377
 
@@ -740,6 +767,14 @@ final class Delegate: NSObject, NSApplicationDelegate, WKNavigationDelegate, WKU
740
767
  // WebKit throws when a handler is dropped or called twice: `panel` calls
741
768
  // `done` exactly once on every path
742
769
 
770
+ // a page of the machine asks for the microphone (the trailer page records a voice line): granted, the system's
771
+ // own prompt (NSMicrophoneUsageDescription) still asks the owner once; any other ask goes to WebKit's prompt
772
+ @available(macOS 12.0, *)
773
+ func webView(_ web: WKWebView, requestMediaCapturePermissionFor origin: WKSecurityOrigin, initiatedByFrame frame: WKFrameInfo, type: WKMediaCaptureType, decisionHandler: @escaping (WKPermissionDecision) -> Void) {
774
+ let local = origin.host == "127.0.0.1" || origin.host == "localhost" || origin.host == startURL.host
775
+ decisionHandler(local && type == .microphone ? .grant : .prompt)
776
+ }
777
+
743
778
  /** one js panel: a sheet on the page's window, a modal where there is
744
779
  * none. Return is OK, esc is Cancel; `done` hears whether OK was pressed */
745
780
  func panel(_ web: WKWebView, _ message: String, cancel: Bool, field: NSTextField? = nil, done: @escaping (Bool) -> Void) {
@@ -9,11 +9,13 @@
9
9
  // The icon is core/app-icon.ts: the repo's mark, its margin cut, on a plate in
10
10
  // the repo's colour. Rebuilt only when the source, the icon, the colours or the
11
11
  // start url changed (a stamp in the bundle). No compiler, or not macOS: the caller falls back.
12
+ // The same build makes the menu bar recorder from its own source (recordings/recorder-app.ts).
12
13
  import { createHash } from 'crypto'
13
14
  import { chmodSync, copyFileSync, existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'fs'
14
15
  import { dirname, join } from 'path'
15
16
  import { appIconOf, appIconPngs, identityOfRoot } from '../core/app-icon.ts'
16
17
  import { identityOfName, type Identity } from '../core/identity-color.ts'
18
+ import { SIGN_NAME, signArgs } from './app-sign.ts'
17
19
  import { homeDir } from './home-paths.ts'
18
20
  import { appNameOf, appsDir, GUI_SOURCE as SOURCE, shipkitBundleOf, wrapperBundleId, wrapperPath, type AppOf } from './process-apps.ts'
19
21
 
@@ -33,6 +35,14 @@ export type AppSpec = {
33
35
  /** where the bundle lands */
34
36
  app: string
35
37
  version: string
38
+ /** the binary's name in the bundle (default `shipkit-gui`): a bundle of another source names its own */
39
+ exe?: string
40
+ /** a menu bar app: no dock icon, no app menu (LSUIElement) */
41
+ agent?: boolean
42
+ /** why it asks for the microphone, the words of the system's prompt */
43
+ micWhy?: string
44
+ /** more plist keys, as `<key>…</key><value>` xml lines */
45
+ plist?: string
36
46
  }
37
47
 
38
48
  const xml = (s: string): string => s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;')
@@ -49,6 +59,7 @@ function atsOf(url: string | null): string {
49
59
  }
50
60
 
51
61
  export function infoPlist(o: Omit<AppSpec, 'app' | 'icon' | 'identity'>): string {
62
+ const exe = o.exe ?? 'shipkit-gui'
52
63
  return `<?xml version="1.0" encoding="UTF-8"?>
53
64
  <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
54
65
  <plist version="1.0">
@@ -56,15 +67,16 @@ export function infoPlist(o: Omit<AppSpec, 'app' | 'icon' | 'identity'>): string
56
67
  \t<key>CFBundleName</key><string>${xml(o.name)}</string>
57
68
  \t<key>CFBundleDisplayName</key><string>${xml(o.name)}</string>
58
69
  \t<key>CFBundleIdentifier</key><string>${xml(o.bundleId)}</string>
59
- \t<key>CFBundleExecutable</key><string>shipkit-gui</string>
70
+ \t<key>CFBundleExecutable</key><string>${xml(exe)}</string>
60
71
  \t<key>CFBundleIconFile</key><string>AppIcon</string>
61
72
  \t<key>CFBundlePackageType</key><string>APPL</string>
62
73
  \t<key>CFBundleShortVersionString</key><string>${xml(o.version)}</string>
63
74
  \t<key>CFBundleVersion</key><string>${xml(o.version)}</string>
64
75
  ${o.url == null ? '' : `\t<key>ShipkitStartURL</key><string>${xml(o.url)}</string>\n`}\t<key>LSMinimumSystemVersion</key><string>12.0</string>
65
76
  \t<key>NSHighResolutionCapable</key><true/>
77
+ \t<key>NSMicrophoneUsageDescription</key><string>${xml(o.micWhy ?? "A page you open here records your voice, a trailer's lines for one.")}</string>
66
78
  \t<key>NSAppTransportSecurity</key>${atsOf(o.url)}
67
- </dict>
79
+ ${o.agent ? '\t<key>LSUIElement</key><true/>\n' : ''}${o.plist ?? ''}</dict>
68
80
  </plist>
69
81
  `
70
82
  }
@@ -88,12 +100,12 @@ export function stampOf(source: string, icon: string | null, identity = ''): str
88
100
 
89
101
  /** the window's binary, compiled once per source text into `bins`: swiftc
90
102
  * takes about a minute, and every bundle runs the same binary */
91
- function compiledGui(source: string, text: string, run: Run, bins: string): string {
92
- const bin = join(bins, `shipkit-gui-${createHash('sha256').update(text).digest('hex').slice(0, 16)}`)
103
+ function compiledGui(source: string | readonly string[], text: string, run: Run, bins: string, exe = 'shipkit-gui'): string {
104
+ const bin = join(bins, `${exe}-${createHash('sha256').update(text).digest('hex').slice(0, 16)}`)
93
105
  if (existsSync(bin)) return bin
94
106
  mkdirSync(bins, { recursive: true })
95
107
  const tmp = `${bin}.building-${process.pid}`
96
- const built = run(['swiftc', '-O', '-o', tmp, source])
108
+ const built = run(['swiftc', '-O', '-o', tmp, ...(typeof source === 'string' ? [source] : source)])
97
109
  if (built.code !== 0 || !existsSync(tmp)) {
98
110
  rmSync(tmp, { force: true })
99
111
  throw new Error(`swiftc could not build the window: ${built.err.slice(0, 400)}`)
@@ -104,15 +116,18 @@ function compiledGui(source: string, text: string, run: Run, bins: string): stri
104
116
 
105
117
  /** one app, built or rebuilt when stale. Throws with the step that failed.
106
118
  * `rebuilt` tells the caller a running copy is now the old one */
107
- export async function ensureApp(spec: AppSpec, o: { run?: Run; source?: string; bins?: string } = {}): Promise<{ app: string; rebuilt: boolean }> {
119
+ export async function ensureApp(spec: AppSpec, o: { run?: Run; source?: string | readonly string[]; bins?: string; sign?: string[] } = {}): Promise<{ app: string; rebuilt: boolean }> {
108
120
  const { app, icon } = spec
109
121
  const run = o.run ?? runSync
110
122
  const source = o.source ?? SOURCE
111
- const text = readFileSync(source, 'utf8')
112
- const stamp = stampOf(text, icon, JSON.stringify([spec.name, spec.bundleId, spec.url, spec.identity, ICON_DRAWING]))
123
+ // several sources: one module, main.swift its entry; the stamp reads them all
124
+ const text = (typeof source === 'string' ? [source] : source).map((f) => readFileSync(f, 'utf8')).join('\n')
125
+ // the machine's signing identity, when it has one, names the app across rebuilds (app-sign.ts): signed anew once it appears
126
+ const sign = o.sign ?? signArgs()
127
+ const stamp = stampOf(text, icon, JSON.stringify([spec.name, spec.bundleId, spec.url, spec.identity, ICON_DRAWING, ...(spec.exe || spec.agent || spec.plist || spec.micWhy ? [spec.exe, spec.agent, spec.plist, spec.micWhy] : []), ...(sign[1] !== '-' ? [sign[1]] : [])]))
113
128
  const stampFile = join(app, 'Contents', 'Resources', 'stamp')
114
129
  if (existsSync(stampFile) && readFileSync(stampFile, 'utf8') === stamp) return { app, rebuilt: false }
115
- const bin = compiledGui(source, text, run, o.bins ?? join(homeDir(), 'gui-bin'))
130
+ const bin = compiledGui(source, text, run, o.bins ?? join(homeDir(), 'gui-bin'), spec.exe)
116
131
  const tmp = `${app}.building-${process.pid}`
117
132
  const fail = (msg: string): never => { rmSync(tmp, { recursive: true, force: true }); throw new Error(msg) }
118
133
  rmSync(tmp, { recursive: true, force: true })
@@ -120,7 +135,7 @@ export async function ensureApp(spec: AppSpec, o: { run?: Run; source?: string;
120
135
  mkdirSync(join(tmp, 'Contents', 'MacOS'), { recursive: true })
121
136
  mkdirSync(res, { recursive: true })
122
137
  writeFileSync(join(tmp, 'Contents', 'Info.plist'), infoPlist(spec))
123
- const exe = join(tmp, 'Contents', 'MacOS', 'shipkit-gui')
138
+ const exe = join(tmp, 'Contents', 'MacOS', spec.exe ?? 'shipkit-gui')
124
139
  copyFileSync(bin, exe)
125
140
  chmodSync(exe, 0o755)
126
141
  if (icon != null) {
@@ -136,7 +151,12 @@ export async function ensureApp(spec: AppSpec, o: { run?: Run; source?: string;
136
151
  }
137
152
  writeFileSync(join(res, 'stamp'), stamp)
138
153
  // signed as the bundle it is, never as the bare binary: macOS refuses notifications to a bundle its signature does not name
139
- const signed = run(['codesign', '--force', '--sign', '-', tmp])
154
+ let signed = run(['codesign', '--force', ...sign, tmp])
155
+ if (signed.code !== 0 && sign[1] !== '-') {
156
+ // the identity refused (a locked or moved keychain): the app still opens, ad hoc, and says so
157
+ console.error(`WARN app: ${spec.name} signed ad hoc, ${SIGN_NAME} refused: ${signed.err.slice(0, 200)}; its macOS permissions will not survive the next rebuild (sk sign-setup)`)
158
+ signed = run(['codesign', '--force', '--sign', '-', tmp])
159
+ }
140
160
  if (signed.code !== 0) fail(`codesign could not sign the bundle: ${signed.err.slice(0, 200)}`)
141
161
  mkdirSync(dirname(app), { recursive: true })
142
162
  // a rename, never `mv`: a build that lands in between would get this one nested inside it
@@ -200,6 +200,12 @@ export function homeRoutes(d: HomeDeps) {
200
200
  const tracked = await postTrackerRoute(req, path)
201
201
  if (tracked != null) return tracked
202
202
  if (!sameOrigin(req)) return new Response('refused: a request that changes something must come from the home page', { status: 403 })
203
+ // the screen recorder's takes of every repo (recordings/routes.ts)
204
+ if (path.startsWith('/api/home/recordings')) {
205
+ const { recordingsRoute } = await import('../recordings/routes.ts')
206
+ const r = await recordingsRoute(req, path)
207
+ if (r != null) return r
208
+ }
203
209
  if (path.startsWith('/api/projects')) return d.gutter.handle(req, path)
204
210
  // who speaks for each repo, and where its data lives (identities/machine-route.ts)
205
211
  if (path.startsWith('/api/home/identities')) return identitiesRoute(req, path, d.root)
@@ -0,0 +1,112 @@
1
+ // a global process, or one of pm's own roles, switched through the running pm
2
+ // and followed until its probe settles it. Lib code, not a command: the daemon
3
+ // reaches it (a take starts the dev server it films), so it never lives in
4
+ // src/cli/, which no role's graph may hold (home/lib-watch.ts).
5
+ import { pmUrl } from './home-paths.ts'
6
+ import { ROLES, type PmAnswer, type Role } from './pm.ts'
7
+ import type { ResourceView } from './resources.ts'
8
+
9
+ /** pm's status answer, or null when it does not answer */
10
+ export async function askPm(url = pmUrl()): Promise<PmAnswer | null> {
11
+ try {
12
+ const r = await fetch(`${url}/api/pm/status.json`, { signal: AbortSignal.timeout(1_500) })
13
+ if (!r.ok) return null
14
+ const j = (await r.json()) as PmAnswer
15
+ return j.pm === 'shipkit-pm' ? j : null
16
+ } catch {
17
+ return null
18
+ }
19
+ }
20
+
21
+ export type SwitchAct = 'start' | 'stop' | 'restart'
22
+
23
+ /** what a switch follows, the same on a global process and on one of pm's own roles (the daemon, the web) */
24
+ export type SwitchView = Pick<ResourceView, 'status' | 'pid' | 'want' | 'note' | 'tail'>
25
+
26
+ export type SwitchDeps = {
27
+ /** pm's answer to the switch: null when it took it, else why not */
28
+ post: (id: string, act: SwitchAct | 'open' | 'chrome' | 'app') => Promise<string | null>
29
+ /** the process as pm sees it now, null when pm does not answer */
30
+ view: (id: string) => Promise<SwitchView | null>
31
+ sleep: (ms: number) => Promise<void>
32
+ now: () => number
33
+ log: (line: string) => void
34
+ }
35
+
36
+ /** the longest a switch is followed: a bring-up polls its health for minutes */
37
+ export const SWITCH_WAIT_MS = 10 * 60_000
38
+ const SWITCH_POLL_MS = 1_000
39
+ /** how long the state the switch left counts as pm not having acted yet */
40
+ export const SWITCH_GRACE_MS = 30_000
41
+
42
+ /** flip a global process, or one of pm's own roles, through pm, then follow
43
+ * pm's state until its probe settles it: 0 once it is up (or down for stop),
44
+ * 1 otherwise. A restart is up only on a new pid: the old one still answers
45
+ * until pm stops it (pm stops the web after its answer is out). The
46
+ * launcher's exit code proves nothing, pm's probe does */
47
+ export async function switchProcess(id: string, act: SwitchAct, d: SwitchDeps, waitMs = SWITCH_WAIT_MS): Promise<number> {
48
+ const before = act === 'restart' ? ((await d.view(id))?.pid ?? null) : null
49
+ const refused = await d.post(id, act)
50
+ if (refused != null) {
51
+ d.log(`FAIL ${act} ${id}: ${refused}`)
52
+ return 1
53
+ }
54
+ const want = act === 'stop' ? 'down' : 'up'
55
+ const start = d.now()
56
+ const end = start + waitMs
57
+ let said = ''
58
+ for (;;) {
59
+ const v = await d.view(id)
60
+ if (v == null) {
61
+ d.log(`FAIL pm stopped answering while ${id} was switched ${want}: shipkit gp`)
62
+ return 1
63
+ }
64
+ if (v.status !== said) {
65
+ said = v.status
66
+ d.log(`${id}: ${v.status}`)
67
+ }
68
+ // the state it is leaving, read just after the switch, is pm not there yet
69
+ const graced = d.now() - start < SWITCH_GRACE_MS
70
+ const leaving = v.status === (want === 'up' ? 'down' : 'up') && graced
71
+ const old = before != null && v.pid === before
72
+ const moving = v.status === 'starting' || v.status === 'stopping' || v.want !== want || leaving || (old && graced)
73
+ if (!moving) {
74
+ if (old && v.status === 'up') {
75
+ d.log(`FAIL ${id} still runs pid ${before} ${Math.round(SWITCH_GRACE_MS / 1000)}s after the restart: pm did not restart it`)
76
+ return 1
77
+ }
78
+ if (v.status === want) return 0
79
+ d.log(`FAIL ${id} is ${v.status}, not ${want}${v.note == null ? '' : `: ${v.note}`}`)
80
+ for (const l of v.tail.slice(-10)) d.log(` log: ${l}`)
81
+ return 1
82
+ }
83
+ if (d.now() >= end) {
84
+ d.log(`FAIL ${id} still ${v.status} after ${Math.round(waitMs / 1000)}s: shipkit gp shows where it stands`)
85
+ return 1
86
+ }
87
+ await d.sleep(SWITCH_POLL_MS)
88
+ }
89
+ }
90
+
91
+ const isRole = (id: string): id is Role => (ROLES as string[]).includes(id)
92
+
93
+ /** the switch against the running pm: pm's own roles (the daemon, the web) through its child api, every other id a
94
+ * global process */
95
+ export const pmSwitchDeps = (log: (line: string) => void, url = pmUrl()): SwitchDeps => ({
96
+ post: async (id, act) => {
97
+ try {
98
+ const r = await fetch(`${url}/api/pm/${isRole(id) ? 'child' : 'resource'}`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ id, act }), signal: AbortSignal.timeout(5_000) })
99
+ return r.ok ? null : await r.text()
100
+ } catch (e) {
101
+ return `pm does not answer on ${url} (${(e as Error).message}): shipkit pm install`
102
+ }
103
+ },
104
+ view: async (id) => {
105
+ const a = await askPm(url)
106
+ if (a == null) return null
107
+ return (isRole(id) ? a.children.find((c) => c.id === id) : a.resources.find((r) => r.id === id)) ?? null
108
+ },
109
+ sleep: (ms) => Bun.sleep(ms),
110
+ now: () => Date.now(),
111
+ log,
112
+ })
@@ -19,7 +19,7 @@ import { HMR_BEAT_MS, HMR_KEEP_SCRIPT, HMR_WORDS } from './hmr-keep.ts'
19
19
  /** the page routes: ONE app for the overview, the plan, and the hub page of
20
20
  * each known repo, which moves between them in place (home-st.ts) */
21
21
  export function pageRoutes<T>(names: string[], page: T): Record<string, T> {
22
- const out: Record<string, T> = { '/': page, '/inbox': page, '/planned': page, '/activity': page, '/archived': page, '/insights': page, '/identities': page }
22
+ const out: Record<string, T> = { '/': page, '/inbox': page, '/planned': page, '/activity': page, '/archived': page, '/insights': page, '/recordings': page, '/identities': page }
23
23
  for (const n of names) out[`${hubBase(n)}/`] = page
24
24
  return out
25
25
  }
@@ -75,6 +75,10 @@ export type Account = {
75
75
  /** the page where its profile is edited (the name, the bio, the avatar) */
76
76
  settings: string
77
77
  max: number | null
78
+ /** the most tags its tag field takes (`max tags`); null, no cap */
79
+ maxTags: number | null
80
+ /** who a post may be shown to (`tiers`, its labels as the platform shows them, the open one first); empty, no tiers */
81
+ tiers: string[]
78
82
  /** the field a message's text goes in: description, comment; empty, the post's own text */
79
83
  text: string
80
84
  /** the word the accounts that take the same messages share, or empty */
@@ -278,8 +282,10 @@ function imageSize(abs: string): { w: number | null; h: number | null } {
278
282
  const SHOWN = ['jpg', 'png', 'webp', 'mp4', 'svg']
279
283
  /** the identity's own folder of pictures, listed first whether `pictures` names it or not */
280
284
  const OWN = 'pictures'
285
+ /** its folders by kind; its other folders (src, art, fonts, candidates) are how they are made, never listed */
286
+ const KINDS = ['avatars', 'banners', 'tiers']
281
287
 
282
- /** the pictures of its own folder then of each `pictures` folder, each folder the largest first, one picture per name
288
+ /** the pictures of its own folder (and its kind folders) then of each `pictures` folder, each folder the largest first, one picture per name
283
289
  * with its other formats: a folder under `files`, or a `~/…` or absolute one elsewhere on the disk (a repo's own files
284
290
  * the identity names), its pictures named by that path */
285
291
  function pictures(files: string | null, dirs: string, file: string, errors: string[]): Picture[] {
@@ -293,11 +299,14 @@ function pictures(files: string | null, dirs: string, file: string, errors: stri
293
299
  continue
294
300
  }
295
301
  const byName = new Map<string, string[]>()
296
- for (const f of readdirSync(abs).sort()) {
297
- const m = /^(.+)\.(\w+)$/.exec(f)
298
- if (m == null || !SHOWN.includes(m[2]!)) continue
299
- byName.set(m[1]!, [...(byName.get(m[1]!) ?? []), m[2]!])
300
- }
302
+ const subs = dir === OWN ? KINDS.filter((k) => existsSync(join(abs, k))) : []
303
+ for (const sub of ['', ...subs])
304
+ for (const f of readdirSync(join(abs, sub)).sort()) {
305
+ const m = /^(.+)\.(\w+)$/.exec(f)
306
+ if (m == null || !SHOWN.includes(m[2]!)) continue
307
+ const name = sub === '' ? m[1]! : `${sub}/${m[1]!}`
308
+ byName.set(name, [...(byName.get(name) ?? []), m[2]!])
309
+ }
301
310
  const here: Picture[] = []
302
311
  for (const [name, exts] of byName) {
303
312
  const [shown, ...rest] = [...exts].sort((x, y) => SHOWN.indexOf(x) - SHOWN.indexOf(y))
@@ -344,6 +353,8 @@ function account(identity: string, id: string, dir: string, shared: ProfileRow[]
344
353
  stats: meta.stats ?? '',
345
354
  settings: meta.settings ?? '',
346
355
  max: meta.max ? Number(meta.max) : null,
356
+ maxTags: meta['max tags'] ? Number(meta['max tags']) : null,
357
+ tiers: (meta.tiers ?? '').split(',').map((t) => t.trim()).filter(Boolean),
347
358
  text: meta.text ?? '',
348
359
  group: meta.group ?? '',
349
360
  place: meta.place ?? '',
@@ -2,14 +2,16 @@
2
2
  // this list. A new caller writes its kind beside its own code and adds its line here
3
3
  import type { MediaKind } from './media-store/kind.ts'
4
4
  import { handKind, labelsInIndex } from './media-store/hand.ts'
5
+ import { recordingKinds, recordingMedia } from './recordings/media-kind.ts'
5
6
  import { reviewMedia } from './review/media-kind.ts'
6
7
  import { trailerMedia } from './review/trailer-media.ts'
7
8
  import { socialMedia } from './social/media-kind.ts'
8
9
 
9
- export const MEDIA_KINDS: readonly MediaKind[] = [reviewMedia, trailerMedia, socialMedia]
10
+ export const MEDIA_KINDS: readonly MediaKind[] = [reviewMedia, trailerMedia, socialMedia, recordingMedia]
10
11
 
11
- /** the kinds of the code, then the generic kind of every other label the index holds (`sk media put`) */
12
+ /** the kinds of the code (a recording kind per root a take went to), then the generic kind of every other label the
13
+ * index holds (`sk media put`) */
12
14
  export function mediaKinds(): MediaKind[] {
13
15
  const code = new Set(MEDIA_KINDS.map((k) => k.kind))
14
- return [...MEDIA_KINDS, ...labelsInIndex().filter((l) => !code.has(l)).map(handKind)]
16
+ return [...MEDIA_KINDS.filter((k) => k !== recordingMedia), ...recordingKinds(), ...labelsInIndex().filter((l) => !code.has(l)).map(handKind)]
15
17
  }
@@ -0,0 +1,54 @@
1
+ // the ONE place an object leaves the Space for good (wiki tools/shipkit/media-store.md, What it guarantees): every version of it
2
+ // deleted, so no link and no undo reaches it, and its index rows dropped. Only an owner's explicit delete of his own
3
+ // file calls it (a recording, tools/shipkit/recordings.md, Delete); a purge, a sync or any command of its own never does.
4
+ // The guard test (tests/media-store/no-remote-delete.test.ts) refuses an S3 delete in any other file
5
+ import { existsSync, realpathSync } from 'node:fs'
6
+ import { join, sep } from 'node:path'
7
+ import { mediaDb } from './db.ts'
8
+ import { houseSpaceConfig, signedCall, signedDelete } from './space.ts'
9
+
10
+ /** every version of the key and every delete marker over it, as S3 lists them (ListObjectVersions) */
11
+ async function versionsOf(key: string): Promise<string[]> {
12
+ const { config, why } = await houseSpaceConfig()
13
+ if (!config) throw new Error(why)
14
+ const xml = await signedCall(config, 'GET', null, { versions: '', prefix: key })
15
+ const ids: string[] = []
16
+ for (const m of xml.matchAll(/<(?:Version|DeleteMarker)>([\s\S]*?)<\/(?:Version|DeleteMarker)>/g)) {
17
+ const k = /<Key>([^<]*)<\/Key>/.exec(m[1]!)?.[1]
18
+ const v = /<VersionId>([^<]*)<\/VersionId>/.exec(m[1]!)?.[1]
19
+ if (k === key && v) ids.push(v)
20
+ }
21
+ return ids
22
+ }
23
+
24
+ /** the keys gone from the Space for good, each version of each, and from the index; a key an index row outside the
25
+ * owner's folder still names (the same content kept elsewhere) is kept and said */
26
+ export async function forgetForGood(keys: readonly string[], o: { owner: string }): Promise<{ gone: string[]; kept: { key: string; why: string }[] }> {
27
+ const { config, why } = await houseSpaceConfig()
28
+ if (!config) throw new Error(`nothing is deleted: ${why}`)
29
+ const db = mediaDb()
30
+ if (!db) throw new Error('the media index does not open: nothing is deleted')
31
+ const gone: string[] = []
32
+ const kept: { key: string; why: string }[] = []
33
+ // a hand put keeps the real path (links resolved), a kind's scan the path it was given: the owner's folder both ways
34
+ const owners = [join(o.owner), ...(existsSync(o.owner) ? [realpathSync(o.owner)] : [])]
35
+ for (const key of keys) {
36
+ // a row is the owner's when its file sits in the owner's folder (a hand put of it lands under any store)
37
+ const inside = (store: string, item: string): boolean => owners.some((ow) => (join(store, item) + sep).startsWith(ow + sep))
38
+ const others = (db.query('select store, item from files where key = ?').all(key) as { store: string; item: string }[]).filter((r) => !inside(r.store, r.item))
39
+ if (others.length > 0) {
40
+ kept.push({ key, why: `${others[0]!.store}/${others[0]!.item} holds the same content` })
41
+ continue
42
+ }
43
+ // a bucket lists every object with its versions (an unversioned one under the version `null`): an empty list
44
+ // is a key already gone, and a plain delete would only leave a marker behind
45
+ for (const v of await versionsOf(key)) await signedDelete(config, key, { versionId: v })
46
+ if ((await versionsOf(key)).length > 0) throw new Error(`${key}: versions remain after the delete`)
47
+ db.transaction(() => {
48
+ db.query('delete from files where key = ?').run(key)
49
+ db.query('delete from objects where key = ?').run(key)
50
+ })()
51
+ gone.push(key)
52
+ }
53
+ return { gone, kept }
54
+ }
@@ -113,14 +113,15 @@ async function keyOf(ref: string): Promise<{ key: string; size: number; name: st
113
113
  return { key: same[0]!.key, size: same[0]!.size, name: at.name }
114
114
  }
115
115
 
116
- /** a fresh signed link to what the Space holds, downloading under the index's name (or `name`) */
117
- export async function linkMedia(ref: string, o: { seconds: number; name?: string; now?: number }): Promise<Link> {
116
+ /** a fresh signed link to what the Space holds, downloading under the index's name (or `name`); `inline` plays it in
117
+ * the browser that opens it */
118
+ export async function linkMedia(ref: string, o: { seconds: number; name?: string; now?: number; inline?: boolean }): Promise<Link> {
118
119
  if (o.seconds > SIGNED_MAX_S) throw new Error(`a signed link lasts at most 7d (the SigV4 limit); the object never expires, sk media link makes a new one`)
119
120
  const k = await keyOf(ref)
120
121
  const { space, why } = await machineSpace()
121
122
  if (!space) throw new Error(why)
122
123
  if (!(await confirmedUp(k.key, k.size))) throw new Error(`${k.key}: not in the Space yet (sk media upload sends what waits)`)
123
124
  const name = o.name ?? k.name ?? basename(k.key)
124
- const url = space.signed(k.key, o.seconds, { name, type: typeOf(name) })
125
+ const url = space.signed(k.key, o.seconds, { name, type: typeOf(name), ...(o.inline ? { inline: true } : {}) })
125
126
  return { key: k.key, sha: shaOfKey(k.key) ?? '', size: k.size, name, url, expires: new Date((o.now ?? Date.now()) + o.seconds * 1000).toISOString() }
126
127
  }