rvlib-shipkit 2.22.1 → 2.24.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 (139) hide show
  1. package/CHANGELOG.md +44 -0
  2. package/package.json +1 -1
  3. package/src/agent-time/render.ts +28 -14
  4. package/src/agent-time/report.ts +46 -25
  5. package/src/agent-time/store.ts +30 -10
  6. package/src/agent-time/timeline.ts +43 -15
  7. package/src/annex/annex.ts +3 -0
  8. package/src/annex/born.ts +464 -0
  9. package/src/annex/flush.ts +46 -0
  10. package/src/annex/offload.ts +171 -38
  11. package/src/annex/snapshots.ts +53 -0
  12. package/src/annex/tidy.ts +368 -0
  13. package/src/asks/asks-queue.ts +32 -11
  14. package/src/checks/SK041-annex-links.check.ts +4 -2
  15. package/src/checks/SK043-scratch-on-the-mac.check.ts +45 -0
  16. package/src/checks/SK044-behind-upstream.check.ts +38 -0
  17. package/src/cli/cmd_Annex.ts +60 -9
  18. package/src/cli/cmd_Asks.ts +2 -0
  19. package/src/cli/cmd_Backup.ts +7 -5
  20. package/src/cli/cmd_Bump.ts +1 -0
  21. package/src/cli/cmd_Capacity.ts +26 -0
  22. package/src/cli/cmd_Check.ts +1 -0
  23. package/src/cli/cmd_Checks.ts +1 -0
  24. package/src/cli/cmd_Ci.ts +1 -0
  25. package/src/cli/cmd_Commands.ts +50 -14
  26. package/src/cli/cmd_Home.ts +0 -1
  27. package/src/cli/cmd_Hooks.ts +1 -0
  28. package/src/cli/cmd_Mv.ts +1 -0
  29. package/src/cli/cmd_Rec.ts +17 -7
  30. package/src/cli/cmd_Reflect.ts +1 -0
  31. package/src/cli/cmd_Releases.ts +1 -0
  32. package/src/cli/cmd_Review.ts +124 -17
  33. package/src/cli/cmd_Secret.ts +41 -2
  34. package/src/cli/cmd_Shot.ts +1 -0
  35. package/src/cli/cmd_Status.ts +1 -0
  36. package/src/cli/cmd_Time.ts +3 -1
  37. package/src/cli/cmd_Tmp.ts +82 -0
  38. package/src/cli/cmd_Wiki.ts +1 -0
  39. package/src/cli/registry.ts +13 -1
  40. package/src/collections/pings.ts +1 -1
  41. package/src/core/capacity.ts +71 -0
  42. package/src/core/check-runner.ts +86 -15
  43. package/src/core/machine-db.ts +8 -0
  44. package/src/core/motherhome.ts +67 -9
  45. package/src/core/slots.ts +49 -12
  46. package/src/core/trace-audit.ts +4 -1
  47. package/src/drill/run.ts +5 -2
  48. package/src/home/daemon-jobs.ts +10 -3
  49. package/src/home/global-units.ts +3 -0
  50. package/src/home/gui-app/ShipkitGui.swift +1 -0
  51. package/src/home/home-launchd.ts +11 -3
  52. package/src/home/home-routes.ts +11 -4
  53. package/src/home/machine-host.ts +65 -0
  54. package/src/home/machine-stores.ts +30 -4
  55. package/src/home/machine-temp.ts +493 -0
  56. package/src/home/other-macs.ts +74 -0
  57. package/src/home/pm.ts +4 -1
  58. package/src/home/run-daemon.ts +10 -2
  59. package/src/home/run-pm.ts +1 -0
  60. package/src/home/serve-web.ts +2 -2
  61. package/src/home/via-hub.ts +6 -1
  62. package/src/identities/identities.ts +92 -24
  63. package/src/init-repo.ts +7 -3
  64. package/src/ledger/ledger.ts +6 -0
  65. package/src/ledger/store.ts +6 -0
  66. package/src/media-store/backup/keys.ts +21 -6
  67. package/src/media-store/backup/manifest.ts +52 -11
  68. package/src/media-store/backup/restore.ts +17 -10
  69. package/src/media-store/backup/run.ts +5 -2
  70. package/src/media-store/backup/sources.ts +2 -1
  71. package/src/media-store/daemon.ts +2 -2
  72. package/src/media-store/purge.ts +4 -0
  73. package/src/mv/mv-md.ts +121 -42
  74. package/src/recordings/load.ts +3 -3
  75. package/src/recordings/model.ts +7 -0
  76. package/src/recordings/open.ts +12 -0
  77. package/src/recordings/presets.ts +12 -5
  78. package/src/recordings/recorder-app/Capture.swift +34 -5
  79. package/src/recordings/recorder-app/Clip.swift +126 -17
  80. package/src/recordings/recorder-app/Editor.swift +177 -7
  81. package/src/recordings/recorder-app/Hud.swift +189 -0
  82. package/src/recordings/recorder-app/Tray.swift +179 -36
  83. package/src/recordings/recorder-app/icon.svg +16 -0
  84. package/src/recordings/recorder-app/main.swift +349 -18
  85. package/src/recordings/recorder-app.ts +8 -4
  86. package/src/recordings/recorder.shipkit.ts +2 -1
  87. package/src/recordings/routes.ts +52 -6
  88. package/src/recordings/run-recorder.ts +2 -1
  89. package/src/recordings/share.ts +27 -0
  90. package/src/recordings/take.ts +36 -4
  91. package/src/recordings/view.ts +11 -0
  92. package/src/reflect/transcript.ts +56 -11
  93. package/src/releases/from-card.ts +45 -3
  94. package/src/releases/model.ts +6 -0
  95. package/src/releases/store.ts +8 -1
  96. package/src/repo-config.ts +14 -4
  97. package/src/review/cells.ts +24 -3
  98. package/src/review/format.ts +33 -9
  99. package/src/review/media-kind.ts +14 -11
  100. package/src/review/media-read.ts +6 -5
  101. package/src/review/model.ts +104 -7
  102. package/src/review/paste.ts +2 -1
  103. package/src/review/previews.ts +123 -36
  104. package/src/review/routes.ts +29 -18
  105. package/src/review/store.ts +74 -12
  106. package/src/review/threads.ts +7 -5
  107. package/src/secrets/copy.ts +110 -0
  108. package/src/secrets/list.ts +17 -7
  109. package/src/serve/hub-app/home-strip.css +5 -0
  110. package/src/serve/hub-app/home-strip.tsx +18 -0
  111. package/src/serve/hub-app/hub-app.tsx +2 -1
  112. package/src/serve/hub-app/hub.css +18 -0
  113. package/src/serve/hub-app/inbox.css +1 -0
  114. package/src/serve/hub-app/pull-refresh.tsx +88 -0
  115. package/src/serve/hub-app/recordings-st.ts +135 -24
  116. package/src/serve/hub-app/recordings-view.tsx +293 -54
  117. package/src/serve/hub-app/recordings.css +77 -24
  118. package/src/serve/hub-app/review/review-cells.tsx +52 -13
  119. package/src/serve/hub-app/review/review-list.tsx +6 -1
  120. package/src/serve/hub-app/review/review-st.ts +6 -5
  121. package/src/serve/hub-app/review/review-thread.tsx +3 -1
  122. package/src/serve/hub-app/review/review-views.tsx +18 -11
  123. package/src/serve/hub-app/review/thread-st.ts +82 -14
  124. package/src/serve/hub-app/review.css +15 -2
  125. package/src/serve/hub-runtime.ts +2 -1
  126. package/src/serve/run-serve.ts +4 -2
  127. package/src/serve/serve-hub.ts +9 -2
  128. package/src/shipkit-files.ts +5 -0
  129. package/src/social/drafts.ts +4 -3
  130. package/src/social/load.ts +7 -2
  131. package/src/social/publish/discord.ts +10 -3
  132. package/src/suite/child-tools.ts +45 -0
  133. package/src/suite/judge-suites.ts +10 -22
  134. package/src/suite/select.ts +83 -8
  135. package/src/suite/suite-cli.ts +38 -14
  136. package/src/suite/suite-cores.ts +68 -0
  137. package/src/suite/suite-reads-preload.ts +8 -6
  138. package/src/ts/config.ts +44 -0
  139. package/src/ts/rename.ts +11 -1
package/src/mv/mv-md.ts CHANGED
@@ -55,7 +55,14 @@ const REF_FORMS: { re: RegExp; group: number }[] = [
55
55
  /** rewrite every relative reference in one file so it still points at the same
56
56
  * thing after the move. `moves` is every path this operation relocates; a ref
57
57
  * that names none of them still moves when the FILE moved under it. */
58
- export function retargetRelativeRefs(root: string, text: string, fromDir: string, toDir: string, moves: Map<string, string>): string {
58
+ export function retargetRelativeRefs(
59
+ root: string,
60
+ text: string,
61
+ fromDir: string,
62
+ toDir: string,
63
+ moves: Map<string, string>,
64
+ isFileAt: (rel: string) => boolean = (rel) => isFile(join(root, rel)),
65
+ ): string {
59
66
  const fix = (target: string): string | null => {
60
67
  // a url, an absolute path and a bare anchor are not ours to resolve
61
68
  if (target === '' || /^[a-z][a-z0-9+.-]*:/i.test(target) || target.startsWith('/') || target.startsWith('#')) return null
@@ -71,7 +78,7 @@ export function retargetRelativeRefs(root: string, text: string, fromDir: string
71
78
  // nothing moved for this reference: neither its target nor its carrier
72
79
  if (to == null && fromDir === toDir) return null
73
80
  // a target that is not a real FILE is prose, not a link
74
- if (to == null && !isFile(join(root, from))) return null
81
+ if (to == null && !isFileAt(from)) return null
75
82
  const next = posix(relative(toDir, to ?? from))
76
83
  if (next === '') return null
77
84
  return `${path.startsWith('./') && !next.startsWith('.') ? `./${next}` : next}${anchor}`
@@ -91,11 +98,79 @@ export function retargetRelativeRefs(root: string, text: string, fromDir: string
91
98
  return out
92
99
  }
93
100
 
94
- export function movePage(root: string, oldRel: string, newRel: string, io: MvIo, o: MvOpts = {}): number {
101
+ /** where a move reads and writes. Applied, it is the disk and git; a dry run is
102
+ * an overlay on them, so the dry run walks the very same steps, and a map's
103
+ * next line sees what the line before it moved */
104
+ class MvTree {
105
+ private readonly text = new Map<string, string>()
106
+ private readonly gone = new Set<string>()
107
+ private list: string[] | null = null
108
+ constructor(readonly root: string, readonly live: boolean) {}
109
+
110
+ private real = (rel: string): string => join(this.root, rel)
111
+ private isGone = (rel: string): boolean => [...this.gone].some((g) => rel === g || rel.startsWith(`${g}/`))
112
+ /** the files the sweep reads: tracked, never a binary, and third party
113
+ * code keeps its own references byte for byte */
114
+ files(): string[] {
115
+ if (this.live || this.list == null) {
116
+ const repo = vendoredAround(this.root)
117
+ const vendored = (repo?.dirs ?? []).map((d) => posix(relative(this.root, join(repo!.root, d))))
118
+ this.list = sh('git ls-files', this.root).split('\n').filter(Boolean)
119
+ .filter((f) => !/\.(png|jpe?g|gif|webp|ico|woff2?|ttf|zip|gz|lockb|lock)$/i.test(f) && !isVendored(f, vendored))
120
+ }
121
+ return this.list
122
+ }
123
+ isFile = (rel: string): boolean => this.text.has(rel) || (!this.isGone(rel) && isFile(this.real(rel)))
124
+ exists = (rel: string): boolean =>
125
+ this.isFile(rel) || (!this.live && this.files().some((f) => f.startsWith(`${rel}/`))) || (!this.isGone(rel) && existsSync(this.real(rel)))
126
+ read = (rel: string): string => this.text.get(rel) ?? readFileSync(this.real(rel), 'utf8')
127
+ write(rel: string, text: string): void {
128
+ if (this.live) writeFileSync(this.real(rel), text)
129
+ else this.text.set(rel, text)
130
+ }
131
+ /** git mv, a file or a folder; the destination's folder is made first */
132
+ mv(from: string, to: string): void {
133
+ if (this.live) {
134
+ mkdirSync(this.real(dirOf(to)), { recursive: true })
135
+ sh(`git mv ${JSON.stringify(from)} ${JSON.stringify(to)}`, this.root)
136
+ return
137
+ }
138
+ const files = this.files()
139
+ files.forEach((f, i) => {
140
+ if (f !== from && !f.startsWith(`${from}/`)) return
141
+ const next = `${to}${f.slice(from.length)}`
142
+ this.text.set(next, this.read(f))
143
+ this.text.delete(f)
144
+ files[i] = next
145
+ })
146
+ this.gone.add(from)
147
+ }
148
+ /** a leftover folder with nothing but Finder's litter */
149
+ dropEmptyDir(rel: string): void {
150
+ if (this.live) rmSync(this.real(rel), { recursive: true })
151
+ else this.gone.add(rel)
152
+ }
153
+ }
154
+
155
+ /** the first line a rewrite changed, as it reads after it, cut around the change */
156
+ const firstChanged = (before: string, after: string): string => {
157
+ const a = before.split('\n')
158
+ const b = after.split('\n')
159
+ const i = b.findIndex((l, k) => l !== a[k])
160
+ const line = b[i] ?? ''
161
+ const old = a[i] ?? ''
162
+ let at = 0
163
+ while (at < line.length && line[at] === old[at]) at++
164
+ const from = Math.max(0, at - 50)
165
+ const cut = line.slice(from, from + 160).trim()
166
+ return `${from > 0 ? '...' : ''}${cut}${from + 160 < line.length ? '...' : ''}`
167
+ }
168
+
169
+ export function movePage(root: string, oldRel: string, newRel: string, io: MvIo, o: MvOpts = {}, tree = new MvTree(root, o.write === true || o.commit === true)): number {
95
170
  const die = (m: string): number => { io.printErr(`FAIL: ${m}`); return 1 }
96
171
  if (!oldRel.endsWith('.md') || !newRel.endsWith('.md')) return die('both paths must be .md (TS moves are not this tool\'s job)')
97
- if (!existsSync(join(root, oldRel))) return die(`${oldRel} does not exist`)
98
- if (existsSync(join(root, newRel))) return die(`${newRel} already exists`)
172
+ if (!tree.exists(oldRel)) return die(`${oldRel} does not exist`)
173
+ if (tree.exists(newRel)) return die(`${newRel} already exists`)
99
174
  // git mv puts a source directory INSIDE an existing destination instead of
100
175
  // refusing, so the probe lands one level too deep and the run still says
101
176
  // ok. Unreachable while every move was a same-dir rename, likely the
@@ -107,21 +182,20 @@ export function movePage(root: string, oldRel: string, newRel: string, io: MvIo,
107
182
  const newBase = indexForm ? dirOf(newRel) : newRel.slice(0, -3)
108
183
  // in place: the page moves into its own asset dir, which already is the topic folder
109
184
  const inPlace = indexForm && newBase === oldBase
110
- if (indexForm && !inPlace && existsSync(join(root, newBase))) return die(`${newBase}/ already exists: a topic folder is created by its move, never merged into`)
111
- if (!indexForm && existsSync(join(root, oldBase)) && existsSync(join(root, newBase)))
185
+ if (indexForm && !inPlace && tree.exists(newBase)) return die(`${newBase}/ already exists: a topic folder is created by its move, never merged into`)
186
+ if (!indexForm && tree.exists(oldBase) && tree.exists(newBase))
112
187
  return die(`${newBase}/ already exists, and ${oldBase}/ would be nested inside it rather than become it: move or merge it by hand first`)
113
188
 
114
- const write = o.write === true || o.commit === true
189
+ const write = tree.live
115
190
  const oldName = basename(oldRel, '.md')
116
191
  const newName = basename(newBase)
117
192
  // docs-root-relative id: refs inside a wiki usually omit the top dir
118
- // (`build/state`, not `wiki/build/state`) — sweep both forms
193
+ // (`build/state`, not `wiki/build/state`), so the sweep takes both forms
119
194
  const tail = (p: string): string | null => { const seg = p.split('/'); return seg.length >= 3 ? seg.slice(1).join('/') : null }
120
195
  const oldId = tail(oldBase)
121
196
  const newId = tail(newBase)
122
197
  const newPageId = tail(newRel.slice(0, -3))
123
198
 
124
- // longest-first so `wiki/x/state.md` beats `x/state` beats bare tokens
125
199
  const pairs: [string, string][] = [
126
200
  [`${oldBase}.md`, newRel],
127
201
  ...(oldId != null ? [[`${oldId}.md`, `${newPageId}.md`] as [string, string]] : []),
@@ -136,14 +210,21 @@ export function movePage(root: string, oldRel: string, newRel: string, io: MvIo,
136
210
  [oldBase, newBase],
137
211
  ...(oldId != null ? [[oldId, newId!] as [string, string]] : []),
138
212
  ]
139
- const bound = (t: string): RegExp =>
140
- new RegExp('(?<![\\w-])' + t.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + (/[/.]$/.test(t) || t.endsWith('.ts') ? '' : '(?![\\w-])'), 'g')
213
+ // ONE pass over the text, longest token first at each place: a path one
214
+ // pair writes is never read by the next (`a.md` into `a/a.md` wrote
215
+ // `a/a/a/a.md` when the pairs ran one after the other)
216
+ const to = new Map<string, string>()
217
+ for (const [oldTok, newTok] of pairs) if (!to.has(oldTok)) to.set(oldTok, newTok)
218
+ const sweep = new RegExp(
219
+ '(?<![\\w-])(?:' +
220
+ [...to.keys()].sort((a, b) => b.length - a.length)
221
+ .map((t) => t.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + (/[/.]$/.test(t) || t.endsWith('.ts') ? '' : '(?![\\w-])'))
222
+ .join('|') +
223
+ ')',
224
+ 'g',
225
+ )
141
226
 
142
- // third party code keeps its own references, byte for byte
143
- const repo = vendoredAround(root)
144
- const vendored = (repo?.dirs ?? []).map((d) => posix(relative(root, join(repo!.root, d))))
145
- const tracked = sh('git ls-files', root).split('\n').filter(Boolean)
146
- .filter((f) => !/\.(png|jpe?g|gif|webp|ico|woff2?|ttf|zip|gz|lockb|lock)$/i.test(f) && !isVendored(f, vendored))
227
+ const tracked = tree.files()
147
228
 
148
229
  // every path this move relocates, old → new. The sibling dir carries its
149
230
  // whole subtree, and the probe is renamed after the page, so its own entry
@@ -156,47 +237,45 @@ export function movePage(root: string, oldRel: string, newRel: string, io: MvIo,
156
237
  for (const f of tracked) if (f.startsWith(`${oldBase}/`)) moves.set(f, `${newBase}${f.slice(oldBase.length)}`)
157
238
  for (const sfx of SIBLING_SUFFIXES) {
158
239
  const probe = `${oldBase}/${oldName}${sfx}`
159
- if (existsSync(join(root, probe))) moves.set(probe, `${newBase}/${newName}${sfx}`)
240
+ if (tree.exists(probe)) moves.set(probe, `${newBase}/${newName}${sfx}`)
160
241
  }
161
242
  }
162
243
 
163
244
  let touched = 0
164
- for (const f of tracked) {
165
- const p = join(root, f)
245
+ for (const f of [...tracked]) {
166
246
  // a submodule is one ls-files entry and a directory: nothing to read
167
- if (!isFile(p)) continue
168
- const before = readFileSync(p, 'utf8')
169
- let after = retargetRelativeRefs(root, before, dirOf(f), dirOf(moves.get(f) ?? f), moves)
170
- for (const [oldTok, newTok] of pairs) after = after.replace(bound(oldTok), newTok)
247
+ if (!tree.isFile(f)) continue
248
+ const before = tree.read(f)
249
+ let refs = 0
250
+ const linked = retargetRelativeRefs(root, before, dirOf(f), dirOf(moves.get(f) ?? f), moves, tree.isFile)
251
+ if (linked !== before) { const lines = before.split('\n'); refs += linked.split('\n').filter((l, i) => l !== lines[i]).length }
252
+ const after = linked.replace(sweep, (m) => { const next = to.get(m)!; if (next !== m) refs++; return next })
171
253
  if (after !== before) {
172
- io.print(` ${f}`)
173
- if (write) writeFileSync(p, after)
254
+ io.print(` ${f}: ${refs} ref(s)`)
255
+ io.print(` ${firstChanged(before, after)}`)
256
+ tree.write(f, after)
174
257
  touched++
175
258
  }
176
259
  }
177
- io.print(`${write ? 'renamed' : 'DRY RUN'}: ${oldBase} → ${newBase}, refs in ${touched} file(s)`)
178
- if (!write) { io.print('re-run with --write (or --commit) to apply'); return 0 }
179
260
 
180
261
  // moves AFTER the sweep (the sweep rewrote files at their old paths).
181
- // git mv refuses into a directory that is not there yet, and a move
182
- // between directories is the case where it usually is not
183
262
  // the index form moves the asset dir FIRST, so it becomes the topic
184
263
  // folder; created first, git mv would nest it one level down
185
- if (!hasDir && existsSync(join(root, oldBase)) && readdirSync(join(root, oldBase)).every((e) => e === '.DS_Store')) rmSync(join(root, oldBase), { recursive: true })
186
- mkdirSync(join(root, dirOf(hasDir ? newBase : newRel)), { recursive: true })
187
- if (indexForm && hasDir && !inPlace) sh(`git mv ${JSON.stringify(oldBase)} ${JSON.stringify(newBase)}`, root)
188
- mkdirSync(join(root, dirOf(newRel)), { recursive: true })
189
- sh(`git mv ${JSON.stringify(oldRel)} ${JSON.stringify(newRel)}`, root)
264
+ if (!hasDir && tree.exists(oldBase) && !tree.isFile(oldBase) && readdirSync(join(root, oldBase)).every((e) => e === '.DS_Store')) tree.dropEmptyDir(oldBase)
265
+ if (indexForm && hasDir && !inPlace) tree.mv(oldBase, newBase)
266
+ tree.mv(oldRel, newRel)
190
267
  if (hasDir) {
191
- if (!indexForm) sh(`git mv ${JSON.stringify(oldBase)} ${JSON.stringify(newBase)}`, root)
268
+ if (!indexForm) tree.mv(oldBase, newBase)
192
269
  // the probe is named after its page, so it only moves when the NAME
193
270
  // changed. A move that keeps the name and changes the directory takes
194
271
  // the probe along inside the dir, and `git mv X X` is a fatal
195
272
  for (const sfx of SIBLING_SUFFIXES) {
196
- const oldProbe = join(newBase, `${oldName}${sfx}`)
197
- if (oldName !== newName && existsSync(join(root, oldProbe))) sh(`git mv ${JSON.stringify(oldProbe)} ${JSON.stringify(join(newBase, `${newName}${sfx}`))}`, root)
273
+ const oldProbe = `${newBase}/${oldName}${sfx}`
274
+ if (oldName !== newName && tree.exists(oldProbe)) tree.mv(oldProbe, `${newBase}/${newName}${sfx}`)
198
275
  }
199
276
  }
277
+ io.print(`${write ? 'renamed' : 'DRY RUN'}: ${oldBase} → ${newBase}, refs in ${touched} file(s)`)
278
+ if (!write) { io.print('re-run with --write (or --commit) to apply'); return 0 }
200
279
 
201
280
  if (o.after !== false && !runAfter(root)) return die('mv:after failed, fix before committing')
202
281
  if (o.commit === true) {
@@ -226,13 +305,13 @@ export function parseMoveMap(text: string): [string, string][] {
226
305
  }
227
306
 
228
307
  /** many pages in one run, in map order: each move sweeps the tree the previous
229
- * one left, and `mv:after` runs once at the end. A dry run shows each move
230
- * against the CURRENT tree, so a later pair that depends on an earlier one
231
- * only reports true once applied. Stops at the first failure. */
308
+ * one left, a dry run too (its overlay holds what the lines before moved),
309
+ * and `mv:after` runs once at the end. Stops at the first failure. */
232
310
  export function movePages(root: string, pairs: [string, string][], io: MvIo, o: MvOpts = {}): number {
233
311
  if (o.commit === true) { io.printErr('FAIL: a move map applies with --write, then you commit what you own'); return 1 }
312
+ const tree = new MvTree(root, o.write === true)
234
313
  for (const [from, to] of pairs) {
235
- const code = movePage(root, from, to, io, { ...o, after: false })
314
+ const code = movePage(root, from, to, io, { ...o, after: false }, tree)
236
315
  if (code !== 0) return code
237
316
  }
238
317
  if (o.write === true && !runAfter(root)) { io.printErr('FAIL: mv:after failed, fix before committing'); return 1 }
@@ -6,7 +6,7 @@ import { basename } from 'node:path'
6
6
  import { UNASSIGNED } from './place.ts'
7
7
  import { mergePresets, type NamedPreset } from './presets.ts'
8
8
 
9
- export type RecorderState = { presets: NamedPreset[]; problems: string[]; repos: string[]; repo: string; home: string | null }
9
+ export type RecorderState = { presets: NamedPreset[]; trayKeys: string[]; problems: string[]; repos: string[]; repo: string; home: string | null }
10
10
 
11
11
 
12
12
  /** the house repos and every preset, read from their configs side by side */
@@ -30,8 +30,8 @@ export async function recorderState(cwd = process.cwd()): Promise<RecorderState>
30
30
  const others = repos.filter((r) => r !== house)
31
31
  const each = await Promise.all(others.map(read))
32
32
  const merged = mergePresets(own, others.map((root, i) => ({ root, recorder: each[i] })))
33
- const { presets } = merged
33
+ const { presets, trayKeys } = merged
34
34
  const problems = [...broken, ...merged.problems]
35
35
  const names = [UNASSIGNED, ...repos.map((r) => basename(r)).sort()]
36
- return { presets, problems, repos: names, repo: UNASSIGNED, home: house ? homeUrl() : null }
36
+ return { presets, trayKeys, problems, repos: names, repo: UNASSIGNED, home: house ? homeUrl() : null }
37
37
  }
@@ -32,8 +32,15 @@ export type RecMeta = {
32
32
  /** every Space key it had that its files no longer name (an export, a poster or a public copy replaced): a delete
33
33
  * takes them too, so a link copied before an export dies with the rest */
34
34
  former?: string[]
35
+ /** every save of its edit that changed something, oldest first (take.ts, versionsOf) */
36
+ versions?: RecVersion[]
35
37
  }
36
38
 
39
+ /** one save of an edit: its number, when, the text that made it, and what it rendered (none for the take whole) */
40
+ export type RecVersion = { n: number; at: string; text: string; sha?: string; size?: number }
41
+ /** the saves kept: the oldest go first */
42
+ export const VERSIONS_KEPT = 50
43
+
37
44
  export type Recording = RecMeta & { dir: string; root: string }
38
45
 
39
46
  export const META = 'meta.json'
@@ -26,6 +26,18 @@ export function recorderUrl(o: { preset?: string; spec?: RecPreset; repo?: strin
26
26
  return `${RECORDER_SCHEME}://record?${q.toString()}`
27
27
  }
28
28
 
29
+ /** the url that asks the app to copy a capture's file natively, confirmed and shown by its clipboard indicator:
30
+ * `png` and `webp-hq` a still as that image, `file` the file alone (a video). `keep`: where the still's WebP stays
31
+ * once made, so the next copy reads it instead of encoding again */
32
+ export function recorderCopyUrl(file: string, format: 'png' | 'webp-hq' | 'file', keep?: string): string {
33
+ return `${RECORDER_SCHEME}://copy?${new URLSearchParams({ file, format, ...(keep ? { keep } : {}) }).toString()}`
34
+ }
35
+
36
+ /** the same for a text (a link): `label` and `detail` are what the indicator says */
37
+ export function recorderCopyTextUrl(text: string, label: string, detail: string): string {
38
+ return `${RECORDER_SCHEME}://copy?${new URLSearchParams({ text, label, detail }).toString()}`
39
+ }
40
+
29
41
  /** a folder to the Trash through the Finder: it works across drives, and it can be put back */
30
42
  export async function trash(dir: string): Promise<void> {
31
43
  const p = Bun.spawn(['osascript', '-e', 'on run argv', '-e', 'tell application "Finder" to delete (POSIX file (item 1 of argv) as alias)', '-e', 'end run', dir], { stdout: 'ignore', stderr: 'pipe' })
@@ -44,12 +44,18 @@ export type RecorderConfig = {
44
44
  * used while the drive is mounted, else the Mac's disk takes the take, said loud */
45
45
  dir?: string
46
46
  presets?: Record<string, RecPreset>
47
+ /** the global hotkey (or several) that shows or hides the recent captures tray (house config only). Absent: shipkit's
48
+ * own when the house names no presets either, else none */
49
+ trayKey?: string | string[]
47
50
  }
48
51
 
52
+ /** the tray's hotkey when the house names neither presets nor a tray key */
53
+ export const BUILTIN_TRAY_KEY = 'alt+shift+t'
54
+
49
55
  /** what ships when the house names none: a video and a screenshot, each a window or an area, and a screenshot taken
50
56
  * on the screen as it was the instant its hotkey was pressed */
51
57
  export const BUILTIN_PRESETS: Record<string, RecPreset> = {
52
- video: { key: 'alt+shift+r', label: 'Video', shoot: 'select', mic: true, clicks: true, after: ['upload', 'copy-link'] },
58
+ video: { key: 'alt+shift+r', label: 'Video', shoot: 'select', mic: true, clicks: true, after: ['upload', 'copy-link', 'open-editor'] },
53
59
  still: { key: 'alt+shift+s', label: 'Screenshot', shoot: 'select', still: true, after: ['copy-file', 'upload', 'open-editor'] },
54
60
  instant: { key: 'alt+shift+i', label: 'Screenshot, frozen', shoot: 'freeze', still: true, after: ['copy-file', 'upload', 'open-editor'] },
55
61
  }
@@ -82,18 +88,19 @@ export function presetProblems(id: string, p: RecPreset): string[] {
82
88
 
83
89
  /** the presets of the menu: the house's (or the built-in ones), then each repo's own as `<repo>/<name>`; a hotkey
84
90
  * two presets claim is a problem */
85
- export function mergePresets(house: RecorderConfig | undefined, repos: { root: string; recorder: RecorderConfig | undefined }[]): { presets: NamedPreset[]; problems: string[] } {
91
+ export function mergePresets(house: RecorderConfig | undefined, repos: { root: string; recorder: RecorderConfig | undefined }[]): { presets: NamedPreset[]; trayKeys: string[]; problems: string[] } {
86
92
  const presets: NamedPreset[] = []
87
93
  const base = house?.presets ?? BUILTIN_PRESETS
88
94
  for (const [id, p] of Object.entries(base)) presets.push({ ...p, id, from: house?.presets ? 'house' : 'shipkit', keys: keysOf(p) })
89
95
  for (const r of repos) for (const [n, p] of Object.entries(r.recorder?.presets ?? {})) presets.push({ ...p, id: `${basename(r.root)}/${n}`, from: basename(r.root), keys: keysOf(p) })
90
- const problems = presets.flatMap((p) => presetProblems(p.id, p))
91
- const keys = new Map<string, string>()
96
+ const trayKeys = keysOf({ key: house?.trayKey ?? (house?.presets ? undefined : BUILTIN_TRAY_KEY) })
97
+ const problems = [...trayKeys.filter((k) => !KEY.test(k)).map((k) => `tray: key ${k}: modifiers (cmd, ctrl, alt, shift) then one key, like alt+shift+t`), ...presets.flatMap((p) => presetProblems(p.id, p))]
98
+ const keys = new Map<string, string>(trayKeys.map((k) => [k, 'the tray']))
92
99
  for (const p of presets)
93
100
  for (const k of p.keys) {
94
101
  const had = keys.get(k)
95
102
  if (had) problems.push(`${p.id}: key ${k} is already ${had}'s`)
96
103
  else keys.set(k, p.id)
97
104
  }
98
- return { presets, problems }
105
+ return { presets, trayKeys, problems }
99
106
  }
@@ -75,9 +75,31 @@ func axSetFrame(_ w: AXUIElement, _ frame: NSRect) {
75
75
 
76
76
  enum Grip { case move, n, s, e, w, ne, nw, se, sw }
77
77
 
78
+ /** the bar's mic and system sound as they were left for a preset: its next video starts with them again. The preset's
79
+ * own values hold only until the bar is touched once */
80
+ enum SoundChoice {
81
+ private static func key(_ what: String, _ preset: String) -> String { "barChoice.\(what).\(preset)" }
82
+
83
+ static func get(_ what: String, _ preset: String?, else preset0: Bool) -> Bool {
84
+ guard let preset, !preset.isEmpty, let v = UserDefaults.standard.object(forKey: key(what, preset)) as? Bool else { return preset0 }
85
+ return v
86
+ }
87
+
88
+ static func set(_ what: String, _ preset: String?, _ on: Bool) {
89
+ guard let preset, !preset.isEmpty else { return }
90
+ UserDefaults.standard.set(on, forKey: key(what, preset))
91
+ }
92
+
93
+ static func forget(_ preset: String) {
94
+ for w in ["mic", "sound"] { UserDefaults.standard.removeObject(forKey: key(w, preset)) }
95
+ }
96
+ }
97
+
78
98
  @MainActor
79
99
  final class Chooser {
80
100
  let video: Bool
101
+ /** the preset whose bar this is: a switch flipped is kept for its next video */
102
+ let remember: String?
81
103
  let windowsToo: Bool
82
104
  var mic: Bool
83
105
  var sound: Bool
@@ -97,8 +119,9 @@ final class Chooser {
97
119
  /** a frozen screenshot's screen and its image of that instant: the overlay covers that screen alone, over it */
98
120
  let frozen: (screen: NSScreen, image: CGImage)?
99
121
 
100
- init(video: Bool, windowsToo: Bool, mic: Bool, sound: Bool, frozen: (screen: NSScreen, image: CGImage)? = nil) {
122
+ init(video: Bool, windowsToo: Bool, mic: Bool, sound: Bool, frozen: (screen: NSScreen, image: CGImage)? = nil, remember: String? = nil) {
101
123
  self.video = video
124
+ self.remember = remember
102
125
  self.windowsToo = windowsToo
103
126
  self.mic = mic
104
127
  self.sound = sound
@@ -322,8 +345,14 @@ final class Chooser {
322
345
 
323
346
  @objc func recordClicked() { go() }
324
347
  @objc func cancelClicked() { cancel() }
325
- @objc func micClicked(_ b: NSButton) { mic = b.state == .on }
326
- @objc func soundClicked(_ b: NSButton) { sound = b.state == .on }
348
+ @objc func micClicked(_ b: NSButton) {
349
+ mic = b.state == .on
350
+ SoundChoice.set("mic", remember, mic)
351
+ }
352
+ @objc func soundClicked(_ b: NSButton) {
353
+ sound = b.state == .on
354
+ SoundChoice.set("sound", remember, sound)
355
+ }
327
356
  }
328
357
 
329
358
  /** a borderless window that still takes the keyboard */
@@ -409,9 +438,9 @@ final class ChooseView: NSView {
409
438
  }
410
439
 
411
440
  /** the person's choice: a window or an area, then (a video) adjusted and confirmed; nil when cancelled */
412
- @MainActor func choose(video: Bool, windowsToo: Bool, mic: Bool, sound: Bool, frozen: (screen: NSScreen, image: CGImage)? = nil) async -> Picked? {
441
+ @MainActor func choose(video: Bool, windowsToo: Bool, mic: Bool, sound: Bool, frozen: (screen: NSScreen, image: CGImage)? = nil, remember: String? = nil) async -> Picked? {
413
442
  await withCheckedContinuation { k in
414
- let c = Chooser(video: video, windowsToo: windowsToo, mic: mic, sound: sound, frozen: frozen)
443
+ let c = Chooser(video: video, windowsToo: windowsToo, mic: mic, sound: sound, frozen: frozen, remember: remember)
415
444
  c.done = { p in
416
445
  k.resume(returning: p)
417
446
  _ = c
@@ -3,9 +3,31 @@
3
3
  // terminal pastes the image). The item is written at once with its data PROMISED: the PNG, the file and the WebP are
4
4
  // made behind it, and a paste that comes first waits for them, so a ⌘V right after the shot never pastes the clipboard
5
5
  // before it. Its format is the menu's choice; WebP is encoded by cwebp (Homebrew's webp), since ImageIO writes no
6
- // WebP. The file a paste reads lives in the app's own cache folder, the newest few kept
6
+ // WebP. The file a paste reads lives in the app's own cache folder, the newest few kept. What the indicator says is
7
+ // read back from the clipboard, never assumed: the change count the write got, then the bytes the clipboard serves
7
8
  import AppKit
8
9
 
10
+ /** what the clipboard holds once a job's data is made, read back from it */
11
+ enum ClipCheck: Equatable {
12
+ /** served byte for byte in the chosen format */
13
+ case ready(format: String, size: String)
14
+ /** served, but as the PNG: the chosen format could not be made */
15
+ case fallback(why: String, size: String)
16
+ /** another copy (a newer still, another app) took the clipboard before the data was made */
17
+ case replaced
18
+ /** the clipboard still holds the item, yet serves other bytes than the still's */
19
+ case unreadable(String)
20
+
21
+ var line: String {
22
+ switch self {
23
+ case let .ready(f, n): "ok: confirmed on the clipboard as \(f) (\(n))"
24
+ case let .fallback(why, n): "WARN: \(why): the clipboard has the PNG (\(n))"
25
+ case .replaced: "note: another copy took the clipboard before this still's data was made"
26
+ case let .unreadable(why): "FAIL: \(why)"
27
+ }
28
+ }
29
+ }
30
+
9
31
  enum ClipFormat: String, CaseIterable {
10
32
  case png
11
33
  case webpLossless = "webp-lossless"
@@ -41,12 +63,19 @@ final class ClipJob: NSObject, NSPasteboardItemDataProvider, @unchecked Sendable
41
63
  private(set) var png = Data()
42
64
  private(set) var file: URL?
43
65
  private(set) var webp: Data?
44
- /** why the chosen format could not be made; the PNG stands in */
66
+ /** why the chosen format could not be made; the PNG stands in, and ClipCheck says so */
45
67
  private(set) var failure: String?
68
+ /** the clipboard it was written to and the change count that write got: the clipboard is still ours while it holds */
69
+ fileprivate(set) var board: NSPasteboard?
70
+ fileprivate(set) var count = -1
71
+
72
+ /** where this still's WebP is kept once made: read there when it is, so a second copy encodes nothing */
73
+ private let keep: URL?
46
74
 
47
75
  /** from the image itself (a capture), or from a PNG on the disk (a tray copy) */
48
- init(image: CGImage? = nil, pngFile: URL? = nil, format: ClipFormat) {
76
+ init(image: CGImage? = nil, pngFile: URL? = nil, format: ClipFormat, keep: URL? = nil) {
49
77
  self.format = format
78
+ self.keep = format == .webpHigh ? keep : nil
50
79
  super.init()
51
80
  ready.enter()
52
81
  DispatchQueue.global(qos: .userInitiated).async {
@@ -78,30 +107,39 @@ final class ClipJob: NSObject, NSPasteboardItemDataProvider, @unchecked Sendable
78
107
  return
79
108
  }
80
109
  guard format != .png else { return }
110
+ let out = base.appendingPathExtension("webp")
111
+ if let keep, let d = try? Data(contentsOf: keep), !d.isEmpty, (try? d.write(to: out)) != nil {
112
+ webp = d
113
+ file = out
114
+ return
115
+ }
81
116
  guard let bin = ["/opt/homebrew/bin/cwebp", "/usr/local/bin/cwebp"].first(where: { FileManager.default.isExecutableFile(atPath: $0) }) else {
82
- failure = "\(format.label) needs cwebp (brew install webp): the clipboard has the PNG"
117
+ failure = "\(format.label) needs cwebp (brew install webp)"
83
118
  return
84
119
  }
85
- let out = base.appendingPathExtension("webp")
86
120
  let r = Clip.runNow(bin, ["-quiet", "-mt"] + format.cwebp + [at.path, "-o", out.path])
87
121
  guard r.code == 0, let d = try? Data(contentsOf: out) else {
88
- failure = "cwebp: \(r.err.isEmpty ? "exit \(r.code)" : r.err); the clipboard has the PNG"
122
+ failure = "cwebp: \(r.err.isEmpty ? "exit \(r.code)" : r.err)"
89
123
  return
90
124
  }
91
125
  webp = d
92
126
  file = out
127
+ if let keep { try? d.write(to: keep, options: .atomic) }
93
128
  }
94
129
 
95
- /** waits for the data, then runs `done` on the main thread with what it says */
96
- func whenReady(_ done: @escaping @MainActor (String, String?) -> Void) {
97
- ready.notify(queue: .main) {
98
- MainActor.assumeIsolated {
99
- let size = ByteCountFormatter.string(fromByteCount: Int64(self.webp?.count ?? self.png.count), countStyle: .file)
100
- done("on the clipboard as \(self.webp != nil ? self.format.label : "PNG") (\(size))", self.failure)
101
- }
130
+ /** the WebP HQ this job made, written to `at` once it is made: a capture's own, kept beside it */
131
+ func keepWebp(at: URL) {
132
+ guard format == .webpHigh else { return }
133
+ ready.notify(queue: .global(qos: .utility)) {
134
+ if let d = self.webp { try? d.write(to: at, options: .atomic) }
102
135
  }
103
136
  }
104
137
 
138
+ /** waits for the data, then runs `done` on the main thread with what the clipboard serves now */
139
+ func whenReady(_ done: @escaping @MainActor (ClipCheck) -> Void) {
140
+ ready.notify(queue: .main) { MainActor.assumeIsolated { done(Clip.check(self)) } }
141
+ }
142
+
105
143
  func pasteboard(_ pasteboard: NSPasteboard?, item: NSPasteboardItem, provideDataForType type: NSPasteboard.PasteboardType) {
106
144
  // a paste that comes before the data waits for it: never the clipboard's older content
107
145
  ready.wait()
@@ -125,17 +163,88 @@ enum Clip {
125
163
  return d
126
164
  }
127
165
 
128
- /** the job's item on the clipboard now, every type promised: the file, the PNG and, for a WebP format, the WebP */
129
- @MainActor static func put(_ job: ClipJob) throws {
166
+ /** the job's item on the clipboard now, every type promised: the file, the PNG and, for a WebP format, the WebP.
167
+ * Throws unless the clipboard reads back as this write: its change count, and every type promised */
168
+ @MainActor static func put(_ job: ClipJob, on pb: NSPasteboard = .general) throws {
130
169
  let it = NSPasteboardItem()
131
170
  let types: [NSPasteboard.PasteboardType] = job.format == .png ? [.fileURL, .png] : [.fileURL, WEBP_TYPE, .png]
132
171
  guard it.setDataProvider(job, forTypes: types) else { throw Err("the clipboard took no promise") }
133
- let pb = NSPasteboard.general
134
- pb.clearContents()
172
+ let n = pb.clearContents()
135
173
  if !pb.writeObjects([it]) { throw Err("the clipboard refused the still") }
174
+ guard pb.changeCount == n, let has = pb.types, types.allSatisfy(has.contains) else { throw Err("the clipboard does not read back as the still just written") }
175
+ job.board = pb
176
+ job.count = n
136
177
  ClipJob.live.append(job)
137
178
  }
138
179
 
180
+ /** the clipboard read back once the job's data is made: still this write (its change count), then the bytes and
181
+ * the file it serves compared with the job's own */
182
+ @MainActor static func check(_ job: ClipJob) -> ClipCheck {
183
+ guard let pb = job.board, pb.changeCount == job.count else { return .replaced }
184
+ let want = job.webp ?? job.png
185
+ let type = job.webp != nil ? WEBP_TYPE : .png
186
+ guard !want.isEmpty else { return .unreadable(job.failure ?? "the still did not encode") }
187
+ guard pb.data(forType: type) == want else { return .unreadable("the clipboard serves other bytes than the still's \(job.webp != nil ? job.format.label : "PNG")") }
188
+ guard let f = job.file, pb.string(forType: .fileURL) == f.absoluteString else { return .unreadable(job.failure ?? "the clipboard's file is not the still's") }
189
+ let size = ByteCountFormatter.string(fromByteCount: Int64(want.count), countStyle: .file)
190
+ if let why = job.failure { return .fallback(why: why, size: size) }
191
+ return .ready(format: job.webp != nil ? job.format.label : "PNG", size: size)
192
+ }
193
+
194
+ /** the one way a still reaches the clipboard: written, confirmed, the indicator showing each step it read back.
195
+ * `onFail` hears a write or a read back that failed. False when the write did not land */
196
+ @MainActor @discardableResult static func copy(_ job: ClipJob, onFail: @escaping @MainActor (String) -> Void) -> Bool {
197
+ ClipHud.shared.begin(job)
198
+ do { try put(job) } catch {
199
+ ClipHud.shared.show(job, .failed(error.localizedDescription))
200
+ onFail("the clipboard: \(error.localizedDescription)")
201
+ return false
202
+ }
203
+ ClipHud.shared.show(job, .copied(job.format))
204
+ job.whenReady { r in
205
+ say(r.line)
206
+ ClipHud.shared.show(job, .checked(r))
207
+ if case let .unreadable(why) = r { onFail(why) }
208
+ }
209
+ return true
210
+ }
211
+
212
+ /** a file alone on the clipboard (a video), as Finder's Copy puts it: written, read back (this write's change count,
213
+ * this file's url), the indicator showing what it read. `onFail` hears a write or a read back that failed */
214
+ @MainActor static func copyFile(_ file: URL, on pb: NSPasteboard = .general, onFail: @escaping @MainActor (String) -> Void) {
215
+ let owner = NSObject()
216
+ ClipHud.shared.begin(owner)
217
+ let n = pb.clearContents()
218
+ let wrote = pb.writeObjects([file as NSURL])
219
+ let read = pb.string(forType: .fileURL).flatMap { URL(string: $0) }?.standardizedFileURL.path
220
+ guard wrote, pb.changeCount == n, read == file.standardizedFileURL.path else {
221
+ let why = "the clipboard does not read back as \(file.lastPathComponent)"
222
+ ClipHud.shared.show(owner, .failed(why))
223
+ onFail(why)
224
+ return
225
+ }
226
+ let bytes = (try? FileManager.default.attributesOfItem(atPath: file.path)[.size] as? Int) ?? 0
227
+ let r = ClipCheck.ready(format: "\(file.pathExtension.uppercased()) file", size: ByteCountFormatter.string(fromByteCount: Int64(bytes), countStyle: .file))
228
+ say(r.line)
229
+ ClipHud.shared.show(owner, .checked(r))
230
+ }
231
+
232
+ /** a text on the clipboard (a link), written and read back, the indicator saying `label` and `detail` */
233
+ @MainActor static func copyText(_ text: String, label: String, detail: String, on pb: NSPasteboard = .general, onFail: @escaping @MainActor (String) -> Void) {
234
+ let owner = NSObject()
235
+ ClipHud.shared.begin(owner)
236
+ let n = pb.clearContents()
237
+ guard pb.setString(text, forType: .string), pb.changeCount == n, pb.string(forType: .string) == text else {
238
+ let why = "the clipboard does not read back as the \(label.lowercased())"
239
+ ClipHud.shared.show(owner, .failed(why))
240
+ onFail(why)
241
+ return
242
+ }
243
+ let r = ClipCheck.ready(format: label, size: detail)
244
+ say(r.line)
245
+ ClipHud.shared.show(owner, .checked(r))
246
+ }
247
+
139
248
  /** the newest KEEP stills and their WebP stay: a paste of an older clipboard still finds its file */
140
249
  static func prune() {
141
250
  let fm = FileManager.default