Open History to see the last commit
1export function isRecord(value: unknown): value is Record<string, unknown> {
2 return typeof value === 'object' && value !== null
3}
4
5/** Base64url (RFC 4648 section 5) without padding. */
6export function base64url(bytes: Uint8Array): string {
7 let binary = ''
8 for (const byte of bytes) binary += String.fromCharCode(byte)
9 return btoa(binary).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '')
10}
11
12/**
13 * A JSON copy of `value`, as a store gives it back. `undefined` when `value`
14 * is not JSON: a cycle or a `BigInt` throws in `JSON.stringify`.
15 */
16export function jsonCopy(value: unknown) {
17 try {
18 const text: string | undefined = JSON.stringify(value)
19 if (text === undefined) return undefined
20 const copy: unknown = JSON.parse(text)
21 return copy
22 } catch {
23 return undefined
24 }
25}
26
27/**
28 * The longest delay of one `setTimeout` (about 24.8 days). A longer wait
29 * waits in parts.
30 */
31export const MAX_TIMER_MS = 2_147_483_647
32
33/**
34 * Resolve at the epoch time `until`, or reject with the reason of `signal`
35 * when it aborts first.
36 */
37export async function waitUntil(until: number, signal?: AbortSignal) {
38 for (;;) {
39 signal?.throwIfAborted()
40 const left = until - Date.now()
41 if (left <= 0) return
42 await new Promise<void>((resolve, reject) => {
43 const onAbort = () => {
44 clearTimeout(timer)
45 reject(signal?.reason)
46 }
47 const timer = setTimeout(
48 () => {
49 signal?.removeEventListener('abort', onAbort)
50 resolve()
51 },
52 Math.min(left, MAX_TIMER_MS),
53 )
54 signal?.addEventListener('abort', onAbort, { once: true })
55 })
56 }
57}
58
59/** A unified patch, and the number of lines that it adds and deletes. */
60export interface UnifiedDiff {
61 /** The patch in git's form, or `''` when nothing changed. */
62 patch: string
63 /** The number of `+` lines. */
64 additions: number
65 /** The number of `-` lines. */
66 deletions: number
67}
68
69// The equal lines around each change, as in git.
70const CONTEXT = 3
71// ponytail: the search for the fewest edits stops after this many edits. Then
72// the changed middle is one deleted block and one inserted block: a valid
73// patch, but not the smallest. The search keeps about MAX_EDITS * MAX_EDITS / 2
74// numbers (8 MB at the cap). A linear-space Myers can raise the cap.
75const MAX_EDITS = 2000
76const NO_NEWLINE = '\n\\ No newline at end of file\n'
77
78/**
79 * A hunk range as git writes it: no `,1`, and an empty range names the line
80 * before it.
81 */
82function range(start: number, count: number) {
83 if (count === 1) return `${start + 1}`
84 return `${count === 0 ? start : start + 1},${count}`
85}
86
87/**
88 * Myers' search for the fewest edits that make `a` into `b` ("An O(ND)
89 * Difference Algorithm and Its Variations", 1986). Row d of the trace has the
90 * furthest x that d edits reach on each diagonal k = x - y = 2i - d. Gives the
91 * rows before the one that reaches the end, or `undefined` when more than
92 * MAX_EDITS edits are needed.
93 */
94function search(a: Array<string>, b: Array<string>) {
95 const trace: Array<Int32Array> = []
96 for (let d = 0; d <= MAX_EDITS; d++) {
97 // Before the first step, diagonal 1 is at x = 0.
98 const prev = trace.at(-1) ?? Int32Array.of(0)
99 const row = new Int32Array(d + 1)
100 for (let i = 0; i <= d; i++) {
101 // One edit more: down from diagonal k + 1 (insert a line of `b`) or
102 // right from diagonal k - 1 (delete a line of `a`), whichever gets
103 // further. Then follow the equal lines.
104 let x = Math.max(prev[i] ?? -1, (prev[i - 1] ?? -2) + 1)
105 let y = x - 2 * i + d
106 while (x < a.length && y < b.length && a[x] === b[y]) {
107 x++
108 y++
109 }
110 if (x >= a.length && y >= b.length) return trace
111 row[i] = x
112 }
113 trace.push(row)
114 }
115 return undefined
116}
117
118/** Marks the lines of `a` to delete and the lines of `b` to insert. */
119function edits(a: Array<string>, b: Array<string>) {
120 const deleted = new Uint8Array(a.length)
121 const inserted = new Uint8Array(b.length)
122 // Skip the lines that both texts start with and end with.
123 let start = 0
124 while (start < a.length && start < b.length && a[start] === b[start]) start++
125 let endA = a.length
126 let endB = b.length
127 while (endA > start && endB > start && a[endA - 1] === b[endB - 1]) {
128 endA--
129 endB--
130 }
131 const trace = search(a.slice(start, endA), b.slice(start, endB))
132 if (!trace) {
133 deleted.fill(1, start, endA)
134 inserted.fill(1, start, endB)
135 return { deleted, inserted }
136 }
137 // Walk back from the end. Each row takes back the equal lines and one edit.
138 let x = endA - start
139 let y = endB - start
140 for (let row = trace.pop(); row; row = trace.pop()) {
141 const k = x - y
142 const i = (k + trace.length + 1) / 2
143 const down = row[i] ?? -1
144 const right = (row[i - 1] ?? -2) + 1
145 if (down >= right) {
146 x = down
147 y = down - k - 1
148 inserted[start + y] = 1
149 } else {
150 x = right - 1
151 y = right - k
152 deleted[start + x] = 1
153 }
154 }
155 return { deleted, inserted }
156}
157
158/**
159 * A unified diff of one file in git's form, which `git apply` accepts. Lines
160 * split on `\n`, so a `\r` stays part of its line. Each change has 3 lines of
161 * context, and changes whose context touches share one hunk.
162 *
163 * @example
164 * ```ts
165 * const { patch, additions, deletions } = unifiedDiff({
166 * path: 'src/app.ts',
167 * before: 'one\n',
168 * after: 'two\n',
169 * })
170 * ```
171 */
172export function unifiedDiff(options: {
173 /** The file, `/`-separated and relative to the workspace root. */
174 path: string
175 /** The old path of a file that moved. */
176 from?: string
177 /** The old text, or `undefined` for a new file. */
178 before: string | undefined
179 /** The new text, or `undefined` for a file that is gone. */
180 after: string | undefined
181}) {
182 const { path, from, before, after } = options
183 const oldPath = from ?? path
184 const moved = oldPath !== path
185 if (before === after && !moved) {
186 return { patch: '', additions: 0, deletions: 0 } satisfies UnifiedDiff
187 }
188 // Each line keeps its `\n`, so a last line without one is not equal to the
189 // same line with one.
190 const a = before ? before.split(/(?<=\n)/) : []
191 const b = after ? after.split(/(?<=\n)/) : []
192 const { deleted, inserted } = edits(a, b)
193
194 // The hunks, as line ranges of `a` and `b`.
195 const hunks: Array<{
196 startA: number
197 startB: number
198 endA: number
199 endB: number
200 }> = []
201 // Each step passes one equal line, or one change and the equal line after it.
202 for (let i = 0, j = 0; i < a.length || j < b.length; i++, j++) {
203 let del = 0
204 let ins = 0
205 while (deleted[i + del]) del++
206 while (inserted[j + ins]) ins++
207 if (del + ins > 0) {
208 const lead = Math.min(CONTEXT, i)
209 const tail = Math.min(CONTEXT, a.length - i - del)
210 const last = hunks.at(-1)
211 // A change whose context touches the last hunk joins it.
212 if (last && i - CONTEXT <= last.endA) {
213 last.endA = i + del + tail
214 last.endB = j + ins + tail
215 } else {
216 hunks.push({
217 startA: i - lead,
218 startB: j - lead,
219 endA: i + del + tail,
220 endB: j + ins + tail,
221 })
222 }
223 }
224 i += del
225 j += ins
226 }
227
228 // ponytail: paths go in as they are. Git C-quotes a path with odd
229 // characters (a quote, a tab, a newline); add that if such paths show up.
230 const out = [`diff --git a/${oldPath} b/${path}\n`]
231 if (before === undefined) out.push('new file mode 100644\n')
232 else if (after === undefined) out.push('deleted file mode 100644\n')
233 else if (moved) out.push(`rename from ${oldPath}\n`, `rename to ${path}\n`)
234 if (hunks.length > 0) {
235 out.push(
236 before === undefined ? '--- /dev/null\n' : `--- a/${oldPath}\n`,
237 after === undefined ? '+++ /dev/null\n' : `+++ b/${path}\n`,
238 )
239 }
240 let additions = 0
241 let deletions = 0
242 const add = (sign: string, line: string) => {
243 out.push(sign + line + (line.endsWith('\n') ? '' : NO_NEWLINE))
244 }
245 for (const { startA, startB, endA, endB } of hunks) {
246 out.push(
247 `@@ -${range(startA, endA - startA)} +${range(startB, endB - startB)} @@\n`,
248 )
249 for (let i = startA, j = startB; i < endA || j < endB;) {
250 if (deleted[i] || inserted[j]) {
251 for (; deleted[i]; i++, deletions++) add('-', a[i] ?? '')
252 for (; inserted[j]; j++, additions++) add('+', b[j] ?? '')
253 } else {
254 add(' ', a[i] ?? '')
255 i++
256 j++
257 }
258 }
259 }
260 return { patch: out.join(''), additions, deletions } satisfies UnifiedDiff
261}