@zyro-sec/util 1.0.2 → 1.0.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/docs/layer-node.md +155 -155
- package/package.json +1 -1
- package/script/build.ts +9 -9
- package/script/pack.ts +5 -5
- package/src/abort.ts +9 -9
- package/src/activity-calendar.ts +50 -50
- package/src/artifact.ts +95 -95
- package/src/base64.ts +29 -29
- package/src/binary.ts +30 -30
- package/src/bom.ts +46 -46
- package/src/cross-spawn-spawner.ts +694 -694
- package/src/duration.ts +22 -22
- package/src/effect/app-node-platform.ts +40 -40
- package/src/effect/app-node.ts +14 -14
- package/src/effect/layer-node.ts +360 -360
- package/src/effect-flock.ts +313 -313
- package/src/encode.ts +39 -39
- package/src/execute-output.ts +23 -23
- package/src/flock.ts +346 -346
- package/src/fs-util.ts +271 -271
- package/src/glob.ts +38 -38
- package/src/global-roots.ts +19 -19
- package/src/global-roots.workerd.ts +16 -16
- package/src/global.ts +88 -88
- package/src/hash.ts +11 -11
- package/src/heap-snapshot.ts +44 -44
- package/src/no-timeout-fetch.ts +5 -5
- package/src/npm-config.ts +41 -41
- package/src/npm.ts +557 -557
- package/src/observability/logging.ts +179 -179
- package/src/observability/otlp.ts +109 -109
- package/src/observability/shared.ts +8 -8
- package/src/observability.ts +60 -60
- package/src/open.ts +12 -12
- package/src/patch.ts +382 -382
- package/src/path.ts +149 -149
- package/src/process-signal.ts +23 -23
- package/src/process.ts +270 -270
- package/src/qr.ts +323 -323
- package/src/record.ts +3 -3
- package/src/retry.ts +51 -51
- package/src/runtime/import.bun.ts +10 -10
- package/src/runtime/import.node.ts +61 -61
- package/src/runtime/import.workerd.ts +9 -9
- package/src/runtime-import.ts +1 -1
- package/src/session-mention.ts +24 -24
- package/src/session-title-fallback.ts +36 -36
- package/src/session-turn.ts +82 -82
- package/src/teardown.ts +19 -19
- package/src/text-boundary.ts +36 -36
- package/src/uuid.ts +15 -15
- package/test/fixtures/qr.json +625 -625
- package/tsconfig.build.json +12 -12
- package/tsconfig.dist.json +10 -10
- package/tsconfig.json +14 -14
- package/src/abort.test.ts +0 -16
- package/src/activity-calendar.test.ts +0 -136
- package/src/artifact.test.ts +0 -29
- package/src/base64.test.ts +0 -12
- package/src/binary.test.ts +0 -19
- package/src/bom.test.ts +0 -21
- package/src/encode.test.ts +0 -32
- package/src/execute-output.test.ts +0 -36
- package/src/no-timeout-fetch.test.ts +0 -33
- package/src/open.test.ts +0 -16
- package/src/path.test.ts +0 -89
- package/src/process-signal.test.ts +0 -38
- package/src/retry.test.ts +0 -87
- package/src/session-mention.test.ts +0 -19
- package/src/session-turn.test.ts +0 -131
- package/src/text-boundary.test.ts +0 -39
- package/src/uuid.test.ts +0 -80
- package/test/glob.test.ts +0 -11
- package/test/global-roots.test.ts +0 -62
- package/test/global.test.ts +0 -99
- package/test/observability-otlp.test.ts +0 -45
- package/test/qr.test.ts +0 -113
- package/test/session-title-fallback.test.ts +0 -49
package/src/patch.ts
CHANGED
|
@@ -1,382 +1,382 @@
|
|
|
1
|
-
export * as Patch from "./patch.js"
|
|
2
|
-
|
|
3
|
-
import { Result, Schema } from "effect"
|
|
4
|
-
import { Bom } from "./bom.js"
|
|
5
|
-
|
|
6
|
-
export class BoundaryError extends Schema.TaggedError<BoundaryError>()("Patch.BoundaryError", {
|
|
7
|
-
boundary: Schema.Literals(["first", "last"]),
|
|
8
|
-
}) {
|
|
9
|
-
override get message() {
|
|
10
|
-
return `The ${this.boundary} line of the patch must be '${this.boundary === "first" ? "*** Begin Patch" : "*** End Patch"}'`
|
|
11
|
-
}
|
|
12
|
-
}
|
|
13
|
-
|
|
14
|
-
export class InvalidHunkError extends Schema.TaggedError<InvalidHunkError>()("Patch.InvalidHunkError", {
|
|
15
|
-
line: Schema.String,
|
|
16
|
-
lineNumber: Schema.Number,
|
|
17
|
-
reason: Schema.optional(Schema.String),
|
|
18
|
-
}) {
|
|
19
|
-
override get message() {
|
|
20
|
-
if (this.reason) return `Invalid hunk at line ${this.lineNumber}: ${this.reason}`
|
|
21
|
-
return `Invalid hunk at line ${this.lineNumber}: '${this.line}' is not a valid hunk header. Valid hunk headers: '*** Add File: {path}', '*** Delete File: {path}', '*** Update File: {path}'`
|
|
22
|
-
}
|
|
23
|
-
}
|
|
24
|
-
|
|
25
|
-
export type ParseError = BoundaryError | InvalidHunkError
|
|
26
|
-
|
|
27
|
-
export type Hunk =
|
|
28
|
-
| { readonly type: "add"; readonly path: string; readonly contents: string }
|
|
29
|
-
| { readonly type: "delete"; readonly path: string }
|
|
30
|
-
| {
|
|
31
|
-
readonly type: "update"
|
|
32
|
-
readonly path: string
|
|
33
|
-
readonly movePath?: string
|
|
34
|
-
readonly chunks: ReadonlyArray<UpdateFileChunk>
|
|
35
|
-
}
|
|
36
|
-
|
|
37
|
-
export interface UpdateFileChunk {
|
|
38
|
-
readonly oldLines: ReadonlyArray<string>
|
|
39
|
-
readonly newLines: ReadonlyArray<string>
|
|
40
|
-
readonly changeContext?: string
|
|
41
|
-
readonly endOfFile?: boolean
|
|
42
|
-
}
|
|
43
|
-
|
|
44
|
-
export interface FileUpdate {
|
|
45
|
-
readonly content: string
|
|
46
|
-
readonly bom: boolean
|
|
47
|
-
}
|
|
48
|
-
|
|
49
|
-
export function parse(patchText: string): Result.Result<ReadonlyArray<Hunk>, ParseError> {
|
|
50
|
-
const lines = stripHeredoc(patchText.trim())
|
|
51
|
-
.split("\n")
|
|
52
|
-
.map((line) => (line.endsWith("\r") ? line.slice(0, -1) : line))
|
|
53
|
-
const begin = lines[0]?.trim() === "*** Begin Patch" ? 0 : -1
|
|
54
|
-
const end = lines.at(-1)?.trim() === "*** End Patch" ? lines.length - 1 : -1
|
|
55
|
-
if (begin === -1) return Result.fail(new BoundaryError({ boundary: "first" }))
|
|
56
|
-
if (end === -1 || begin >= end) return Result.fail(new BoundaryError({ boundary: "last" }))
|
|
57
|
-
|
|
58
|
-
const hunks: Hunk[] = []
|
|
59
|
-
let index = begin + 1
|
|
60
|
-
while (index < end) {
|
|
61
|
-
const line = lines[index]!
|
|
62
|
-
const header = line.trim()
|
|
63
|
-
if (
|
|
64
|
-
index === begin + 1 &&
|
|
65
|
-
header.startsWith("*** Environment ID:") &&
|
|
66
|
-
header.slice("*** Environment ID:".length).trim()
|
|
67
|
-
) {
|
|
68
|
-
index++
|
|
69
|
-
continue
|
|
70
|
-
}
|
|
71
|
-
if (header.startsWith("*** Add File: ")) {
|
|
72
|
-
const path = header.slice("*** Add File: ".length).trim()
|
|
73
|
-
const parsed = parseAdd(lines, index + 1, end, path)
|
|
74
|
-
if ("error" in parsed) return Result.fail(parsed.error)
|
|
75
|
-
hunks.push({ type: "add", path, contents: parsed.content })
|
|
76
|
-
index = parsed.next
|
|
77
|
-
continue
|
|
78
|
-
}
|
|
79
|
-
if (header.startsWith("*** Delete File: ")) {
|
|
80
|
-
const path = header.slice("*** Delete File: ".length).trim()
|
|
81
|
-
const next = lines[index + 1]?.trim()
|
|
82
|
-
if (index + 1 < end && next !== undefined && !isBoundary(next)) {
|
|
83
|
-
if (next.startsWith("*** ")) {
|
|
84
|
-
return Result.fail(new InvalidHunkError({ line: next, lineNumber: index + 2 }))
|
|
85
|
-
}
|
|
86
|
-
return Result.fail(
|
|
87
|
-
new InvalidHunkError({
|
|
88
|
-
line: next,
|
|
89
|
-
lineNumber: index + 2,
|
|
90
|
-
reason: `Unexpected line after Delete File '${path}': '${next}'. Delete hunks do not contain body lines`,
|
|
91
|
-
}),
|
|
92
|
-
)
|
|
93
|
-
}
|
|
94
|
-
hunks.push({ type: "delete", path })
|
|
95
|
-
index++
|
|
96
|
-
continue
|
|
97
|
-
}
|
|
98
|
-
if (header.startsWith("*** Update File: ")) {
|
|
99
|
-
const path = header.slice("*** Update File: ".length).trim()
|
|
100
|
-
let next = index + 1
|
|
101
|
-
let movePath: string | undefined
|
|
102
|
-
while (lines[next]?.trimEnd() === "*** End of File") next++
|
|
103
|
-
const move = lines[next]?.trimEnd()
|
|
104
|
-
if (move === "*** Move to:" || move?.startsWith("*** Move to: ")) {
|
|
105
|
-
movePath = move.slice("*** Move to: ".length).trim()
|
|
106
|
-
if (!movePath) {
|
|
107
|
-
return Result.fail(
|
|
108
|
-
new InvalidHunkError({
|
|
109
|
-
line: lines[next]!.trim(),
|
|
110
|
-
lineNumber: next + 1,
|
|
111
|
-
reason: `Move destination for '${path}' must not be empty`,
|
|
112
|
-
}),
|
|
113
|
-
)
|
|
114
|
-
}
|
|
115
|
-
next++
|
|
116
|
-
}
|
|
117
|
-
const parsed = parseUpdate(lines, next, end, path, index)
|
|
118
|
-
if ("error" in parsed) return Result.fail(parsed.error)
|
|
119
|
-
hunks.push({ type: "update", path, movePath, chunks: parsed.chunks })
|
|
120
|
-
index = parsed.next
|
|
121
|
-
continue
|
|
122
|
-
}
|
|
123
|
-
return Result.fail(new InvalidHunkError({ line: header, lineNumber: index + 1 }))
|
|
124
|
-
}
|
|
125
|
-
return Result.succeed(hunks)
|
|
126
|
-
}
|
|
127
|
-
|
|
128
|
-
export function derive(path: string, chunks: ReadonlyArray<UpdateFileChunk>, original: string): FileUpdate {
|
|
129
|
-
const source = Bom.split(original)
|
|
130
|
-
const lines = source.text.split("\n")
|
|
131
|
-
if (lines.at(-1) === "") lines.pop()
|
|
132
|
-
const replacements = computeReplacements(lines, path, chunks)
|
|
133
|
-
for (const [start, remove, insert] of replacements.reverse()) lines.splice(start, remove, ...insert)
|
|
134
|
-
if (lines.at(-1) !== "") lines.push("")
|
|
135
|
-
const next = Bom.split(lines.join("\n"))
|
|
136
|
-
return { content: next.text, bom: source.bom || next.bom }
|
|
137
|
-
}
|
|
138
|
-
|
|
139
|
-
export function joinBom(text: string, bom: boolean) {
|
|
140
|
-
return Bom.join(text, bom)
|
|
141
|
-
}
|
|
142
|
-
|
|
143
|
-
function parseAdd(
|
|
144
|
-
lines: ReadonlyArray<string>,
|
|
145
|
-
start: number,
|
|
146
|
-
end: number,
|
|
147
|
-
path: string,
|
|
148
|
-
): { content: string; next: number } | { error: InvalidHunkError } {
|
|
149
|
-
const content: string[] = []
|
|
150
|
-
let index = start
|
|
151
|
-
while (index < end && !isBoundary(lines[index]!.trim())) {
|
|
152
|
-
if (!lines[index]!.startsWith("+")) {
|
|
153
|
-
const line = lines[index]!.trim()
|
|
154
|
-
return {
|
|
155
|
-
error: new InvalidHunkError({
|
|
156
|
-
line,
|
|
157
|
-
lineNumber: index + 1,
|
|
158
|
-
reason: `Invalid Add File line for '${path}': expected a line starting with '+', got '${line}'`,
|
|
159
|
-
}),
|
|
160
|
-
}
|
|
161
|
-
}
|
|
162
|
-
// Every + line is a whole line of the file, as in Codex, so a final empty + line is a blank last line.
|
|
163
|
-
content.push(`${lines[index]!.slice(1)}\n`)
|
|
164
|
-
index++
|
|
165
|
-
}
|
|
166
|
-
return { content: content.join(""), next: index }
|
|
167
|
-
}
|
|
168
|
-
|
|
169
|
-
function parseUpdate(
|
|
170
|
-
lines: ReadonlyArray<string>,
|
|
171
|
-
start: number,
|
|
172
|
-
end: number,
|
|
173
|
-
path: string,
|
|
174
|
-
hunk: number,
|
|
175
|
-
): { chunks: ReadonlyArray<UpdateFileChunk>; next: number } | { error: InvalidHunkError } {
|
|
176
|
-
const chunks: Array<{
|
|
177
|
-
oldLines: string[]
|
|
178
|
-
newLines: string[]
|
|
179
|
-
changeContext?: string
|
|
180
|
-
endOfFile?: boolean
|
|
181
|
-
}> = []
|
|
182
|
-
let index = start
|
|
183
|
-
let afterEndOfFile = false
|
|
184
|
-
while (index < end) {
|
|
185
|
-
const line = lines[index]!
|
|
186
|
-
const updateLine = line.trimEnd()
|
|
187
|
-
if (afterEndOfFile) {
|
|
188
|
-
if (updateLine === "") {
|
|
189
|
-
index++
|
|
190
|
-
continue
|
|
191
|
-
}
|
|
192
|
-
if (updateLine === "@@" || updateLine.startsWith("@@ ")) afterEndOfFile = false
|
|
193
|
-
else if (isBoundary(updateLine)) break
|
|
194
|
-
else {
|
|
195
|
-
return {
|
|
196
|
-
error: new InvalidHunkError({
|
|
197
|
-
line,
|
|
198
|
-
lineNumber: index + 1,
|
|
199
|
-
reason: `Expected update hunk to start with a @@ context marker, got: '${line}'`,
|
|
200
|
-
}),
|
|
201
|
-
}
|
|
202
|
-
}
|
|
203
|
-
}
|
|
204
|
-
if (updateLine === "*** End of File") {
|
|
205
|
-
const chunk = chunks.at(-1)
|
|
206
|
-
if (chunk && chunk.oldLines.length === 0 && chunk.newLines.length === 0) {
|
|
207
|
-
return {
|
|
208
|
-
error: new InvalidHunkError({
|
|
209
|
-
line: updateLine,
|
|
210
|
-
lineNumber: index + 1,
|
|
211
|
-
reason: "Update hunk does not contain any lines",
|
|
212
|
-
}),
|
|
213
|
-
}
|
|
214
|
-
}
|
|
215
|
-
if (chunk) {
|
|
216
|
-
chunk.endOfFile = true
|
|
217
|
-
afterEndOfFile = true
|
|
218
|
-
}
|
|
219
|
-
index++
|
|
220
|
-
continue
|
|
221
|
-
}
|
|
222
|
-
if (isBoundary(updateLine)) break
|
|
223
|
-
if (updateLine === "@@" || updateLine.startsWith("@@ ")) {
|
|
224
|
-
const previous = chunks.at(-1)
|
|
225
|
-
if (previous && previous.oldLines.length === 0 && previous.newLines.length === 0) {
|
|
226
|
-
return {
|
|
227
|
-
error: new InvalidHunkError({
|
|
228
|
-
line,
|
|
229
|
-
lineNumber: index + 1,
|
|
230
|
-
reason: `Unexpected line found in update hunk: '${line}'. Every line should start with ' ' (context line), '+' (added line), or '-' (removed line)`,
|
|
231
|
-
}),
|
|
232
|
-
}
|
|
233
|
-
}
|
|
234
|
-
chunks.push({
|
|
235
|
-
oldLines: [],
|
|
236
|
-
newLines: [],
|
|
237
|
-
changeContext: updateLine === "@@" ? undefined : updateLine.slice("@@ ".length),
|
|
238
|
-
})
|
|
239
|
-
index++
|
|
240
|
-
continue
|
|
241
|
-
}
|
|
242
|
-
if (chunks.length === 0) chunks.push({ oldLines: [], newLines: [] })
|
|
243
|
-
const chunk = chunks.at(-1)!
|
|
244
|
-
if (line === "") {
|
|
245
|
-
chunk.oldLines.push("")
|
|
246
|
-
chunk.newLines.push("")
|
|
247
|
-
index++
|
|
248
|
-
continue
|
|
249
|
-
}
|
|
250
|
-
if (line.startsWith(" ")) {
|
|
251
|
-
chunk.oldLines.push(line.slice(1))
|
|
252
|
-
chunk.newLines.push(line.slice(1))
|
|
253
|
-
index++
|
|
254
|
-
continue
|
|
255
|
-
}
|
|
256
|
-
if (line.startsWith("-")) {
|
|
257
|
-
chunk.oldLines.push(line.slice(1))
|
|
258
|
-
index++
|
|
259
|
-
continue
|
|
260
|
-
}
|
|
261
|
-
if (line.startsWith("+")) {
|
|
262
|
-
chunk.newLines.push(line.slice(1))
|
|
263
|
-
index++
|
|
264
|
-
continue
|
|
265
|
-
}
|
|
266
|
-
const populated = chunk.oldLines.length > 0 || chunk.newLines.length > 0
|
|
267
|
-
return {
|
|
268
|
-
error: new InvalidHunkError({
|
|
269
|
-
line,
|
|
270
|
-
lineNumber: index + 1,
|
|
271
|
-
reason: populated
|
|
272
|
-
? `Expected update hunk to start with a @@ context marker, got: '${line}'`
|
|
273
|
-
: `Unexpected line found in update hunk: '${line}'. Every line should start with ' ' (context line), '+' (added line), or '-' (removed line)`,
|
|
274
|
-
}),
|
|
275
|
-
}
|
|
276
|
-
}
|
|
277
|
-
if (chunks.length === 0) {
|
|
278
|
-
return {
|
|
279
|
-
error: new InvalidHunkError({
|
|
280
|
-
line: lines[hunk]!.trim(),
|
|
281
|
-
lineNumber: hunk + 1,
|
|
282
|
-
reason: `Update file hunk for path '${path}' is empty`,
|
|
283
|
-
}),
|
|
284
|
-
}
|
|
285
|
-
}
|
|
286
|
-
const last = chunks.at(-1)!
|
|
287
|
-
if (last.oldLines.length === 0 && last.newLines.length === 0) {
|
|
288
|
-
const line = lines[index]!.trim()
|
|
289
|
-
return {
|
|
290
|
-
error: new InvalidHunkError({
|
|
291
|
-
line,
|
|
292
|
-
lineNumber: index + 1,
|
|
293
|
-
reason:
|
|
294
|
-
line === "*** End Patch"
|
|
295
|
-
? "Update hunk does not contain any lines"
|
|
296
|
-
: `Unexpected line found in update hunk: '${line}'. Every line should start with ' ' (context line), '+' (added line), or '-' (removed line)`,
|
|
297
|
-
}),
|
|
298
|
-
}
|
|
299
|
-
}
|
|
300
|
-
return { chunks, next: index }
|
|
301
|
-
}
|
|
302
|
-
|
|
303
|
-
function isBoundary(line: string) {
|
|
304
|
-
return (
|
|
305
|
-
line === "*** End Patch" ||
|
|
306
|
-
line.startsWith("*** Add File: ") ||
|
|
307
|
-
line.startsWith("*** Delete File: ") ||
|
|
308
|
-
line.startsWith("*** Update File: ")
|
|
309
|
-
)
|
|
310
|
-
}
|
|
311
|
-
|
|
312
|
-
function computeReplacements(lines: ReadonlyArray<string>, path: string, chunks: ReadonlyArray<UpdateFileChunk>) {
|
|
313
|
-
const replacements: Array<readonly [start: number, remove: number, insert: ReadonlyArray<string>]> = []
|
|
314
|
-
let lineIndex = 0
|
|
315
|
-
for (const chunk of chunks) {
|
|
316
|
-
if (chunk.changeContext) {
|
|
317
|
-
const context = seek(lines, [chunk.changeContext], lineIndex)
|
|
318
|
-
if (context === -1) throw new Error(`Failed to find context '${chunk.changeContext}' in ${path}`)
|
|
319
|
-
lineIndex = context + 1
|
|
320
|
-
}
|
|
321
|
-
if (chunk.oldLines.length === 0) {
|
|
322
|
-
replacements.push([lines.length, 0, chunk.newLines])
|
|
323
|
-
continue
|
|
324
|
-
}
|
|
325
|
-
let oldLines = chunk.oldLines
|
|
326
|
-
let newLines = chunk.newLines
|
|
327
|
-
let found = seek(lines, oldLines, lineIndex, chunk.endOfFile)
|
|
328
|
-
if (found === -1 && oldLines.at(-1) === "") {
|
|
329
|
-
oldLines = oldLines.slice(0, -1)
|
|
330
|
-
if (newLines.at(-1) === "") newLines = newLines.slice(0, -1)
|
|
331
|
-
found = seek(lines, oldLines, lineIndex, chunk.endOfFile)
|
|
332
|
-
}
|
|
333
|
-
if (found === -1 && chunk.oldLines.every((line) => line === "")) {
|
|
334
|
-
const expected =
|
|
335
|
-
chunk.oldLines.length === 1 ? "an expected blank line" : `${chunk.oldLines.length} consecutive blank lines`
|
|
336
|
-
throw new Error(`Failed to find ${expected} in ${path}`)
|
|
337
|
-
}
|
|
338
|
-
if (found === -1) throw new Error(`Failed to find expected lines in ${path}:\n${chunk.oldLines.join("\n")}`)
|
|
339
|
-
replacements.push([found, oldLines.length, newLines])
|
|
340
|
-
lineIndex = found + oldLines.length
|
|
341
|
-
}
|
|
342
|
-
return replacements.sort((left, right) => left[0] - right[0])
|
|
343
|
-
}
|
|
344
|
-
|
|
345
|
-
function seek(lines: ReadonlyArray<string>, pattern: ReadonlyArray<string>, start: number, eof = false) {
|
|
346
|
-
if (pattern.length === 0) return -1
|
|
347
|
-
if (eof) {
|
|
348
|
-
const offset = lines.length - pattern.length
|
|
349
|
-
if (offset < start) return -1
|
|
350
|
-
for (const compare of [exact, rstrip, trim, normalized]) {
|
|
351
|
-
if (matches(lines, pattern, offset, compare)) return offset
|
|
352
|
-
}
|
|
353
|
-
return -1
|
|
354
|
-
}
|
|
355
|
-
for (const compare of [exact, rstrip, trim, normalized]) {
|
|
356
|
-
for (let offset = start; offset <= lines.length - pattern.length; offset++) {
|
|
357
|
-
if (matches(lines, pattern, offset, compare)) return offset
|
|
358
|
-
}
|
|
359
|
-
}
|
|
360
|
-
return -1
|
|
361
|
-
}
|
|
362
|
-
|
|
363
|
-
function matches(
|
|
364
|
-
lines: ReadonlyArray<string>,
|
|
365
|
-
pattern: ReadonlyArray<string>,
|
|
366
|
-
offset: number,
|
|
367
|
-
compare: (left: string, right: string) => boolean,
|
|
368
|
-
) {
|
|
369
|
-
return pattern.every((line, index) => compare(lines[offset + index]!, line))
|
|
370
|
-
}
|
|
371
|
-
|
|
372
|
-
const exact = (left: string, right: string) => left === right
|
|
373
|
-
const rstrip = (left: string, right: string) => left.trimEnd() === right.trimEnd()
|
|
374
|
-
const trim = (left: string, right: string) => left.trim() === right.trim()
|
|
375
|
-
const normalized = (left: string, right: string) => normalize(left.trim()) === normalize(right.trim())
|
|
376
|
-
const normalize = (value: string) =>
|
|
377
|
-
value
|
|
378
|
-
.replace(/[‘’‚‛]/g, "'")
|
|
379
|
-
.replace(/[“”„‟]/g, '"')
|
|
380
|
-
.replace(/[‐‑‒–—―−]/g, "-")
|
|
381
|
-
.replace(/[\u00A0\u2002-\u200A\u202F\u205F\u3000]/g, " ")
|
|
382
|
-
const stripHeredoc = (input: string) => input.match(/^(?:cat\s+)?<<(['"]?)(\w+)\1\s*\n([\s\S]*?)\n\2\s*$/)?.[3] ?? input
|
|
1
|
+
export * as Patch from "./patch.js"
|
|
2
|
+
|
|
3
|
+
import { Result, Schema } from "effect"
|
|
4
|
+
import { Bom } from "./bom.js"
|
|
5
|
+
|
|
6
|
+
export class BoundaryError extends Schema.TaggedError<BoundaryError>()("Patch.BoundaryError", {
|
|
7
|
+
boundary: Schema.Literals(["first", "last"]),
|
|
8
|
+
}) {
|
|
9
|
+
override get message() {
|
|
10
|
+
return `The ${this.boundary} line of the patch must be '${this.boundary === "first" ? "*** Begin Patch" : "*** End Patch"}'`
|
|
11
|
+
}
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export class InvalidHunkError extends Schema.TaggedError<InvalidHunkError>()("Patch.InvalidHunkError", {
|
|
15
|
+
line: Schema.String,
|
|
16
|
+
lineNumber: Schema.Number,
|
|
17
|
+
reason: Schema.optional(Schema.String),
|
|
18
|
+
}) {
|
|
19
|
+
override get message() {
|
|
20
|
+
if (this.reason) return `Invalid hunk at line ${this.lineNumber}: ${this.reason}`
|
|
21
|
+
return `Invalid hunk at line ${this.lineNumber}: '${this.line}' is not a valid hunk header. Valid hunk headers: '*** Add File: {path}', '*** Delete File: {path}', '*** Update File: {path}'`
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export type ParseError = BoundaryError | InvalidHunkError
|
|
26
|
+
|
|
27
|
+
export type Hunk =
|
|
28
|
+
| { readonly type: "add"; readonly path: string; readonly contents: string }
|
|
29
|
+
| { readonly type: "delete"; readonly path: string }
|
|
30
|
+
| {
|
|
31
|
+
readonly type: "update"
|
|
32
|
+
readonly path: string
|
|
33
|
+
readonly movePath?: string
|
|
34
|
+
readonly chunks: ReadonlyArray<UpdateFileChunk>
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export interface UpdateFileChunk {
|
|
38
|
+
readonly oldLines: ReadonlyArray<string>
|
|
39
|
+
readonly newLines: ReadonlyArray<string>
|
|
40
|
+
readonly changeContext?: string
|
|
41
|
+
readonly endOfFile?: boolean
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export interface FileUpdate {
|
|
45
|
+
readonly content: string
|
|
46
|
+
readonly bom: boolean
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export function parse(patchText: string): Result.Result<ReadonlyArray<Hunk>, ParseError> {
|
|
50
|
+
const lines = stripHeredoc(patchText.trim())
|
|
51
|
+
.split("\n")
|
|
52
|
+
.map((line) => (line.endsWith("\r") ? line.slice(0, -1) : line))
|
|
53
|
+
const begin = lines[0]?.trim() === "*** Begin Patch" ? 0 : -1
|
|
54
|
+
const end = lines.at(-1)?.trim() === "*** End Patch" ? lines.length - 1 : -1
|
|
55
|
+
if (begin === -1) return Result.fail(new BoundaryError({ boundary: "first" }))
|
|
56
|
+
if (end === -1 || begin >= end) return Result.fail(new BoundaryError({ boundary: "last" }))
|
|
57
|
+
|
|
58
|
+
const hunks: Hunk[] = []
|
|
59
|
+
let index = begin + 1
|
|
60
|
+
while (index < end) {
|
|
61
|
+
const line = lines[index]!
|
|
62
|
+
const header = line.trim()
|
|
63
|
+
if (
|
|
64
|
+
index === begin + 1 &&
|
|
65
|
+
header.startsWith("*** Environment ID:") &&
|
|
66
|
+
header.slice("*** Environment ID:".length).trim()
|
|
67
|
+
) {
|
|
68
|
+
index++
|
|
69
|
+
continue
|
|
70
|
+
}
|
|
71
|
+
if (header.startsWith("*** Add File: ")) {
|
|
72
|
+
const path = header.slice("*** Add File: ".length).trim()
|
|
73
|
+
const parsed = parseAdd(lines, index + 1, end, path)
|
|
74
|
+
if ("error" in parsed) return Result.fail(parsed.error)
|
|
75
|
+
hunks.push({ type: "add", path, contents: parsed.content })
|
|
76
|
+
index = parsed.next
|
|
77
|
+
continue
|
|
78
|
+
}
|
|
79
|
+
if (header.startsWith("*** Delete File: ")) {
|
|
80
|
+
const path = header.slice("*** Delete File: ".length).trim()
|
|
81
|
+
const next = lines[index + 1]?.trim()
|
|
82
|
+
if (index + 1 < end && next !== undefined && !isBoundary(next)) {
|
|
83
|
+
if (next.startsWith("*** ")) {
|
|
84
|
+
return Result.fail(new InvalidHunkError({ line: next, lineNumber: index + 2 }))
|
|
85
|
+
}
|
|
86
|
+
return Result.fail(
|
|
87
|
+
new InvalidHunkError({
|
|
88
|
+
line: next,
|
|
89
|
+
lineNumber: index + 2,
|
|
90
|
+
reason: `Unexpected line after Delete File '${path}': '${next}'. Delete hunks do not contain body lines`,
|
|
91
|
+
}),
|
|
92
|
+
)
|
|
93
|
+
}
|
|
94
|
+
hunks.push({ type: "delete", path })
|
|
95
|
+
index++
|
|
96
|
+
continue
|
|
97
|
+
}
|
|
98
|
+
if (header.startsWith("*** Update File: ")) {
|
|
99
|
+
const path = header.slice("*** Update File: ".length).trim()
|
|
100
|
+
let next = index + 1
|
|
101
|
+
let movePath: string | undefined
|
|
102
|
+
while (lines[next]?.trimEnd() === "*** End of File") next++
|
|
103
|
+
const move = lines[next]?.trimEnd()
|
|
104
|
+
if (move === "*** Move to:" || move?.startsWith("*** Move to: ")) {
|
|
105
|
+
movePath = move.slice("*** Move to: ".length).trim()
|
|
106
|
+
if (!movePath) {
|
|
107
|
+
return Result.fail(
|
|
108
|
+
new InvalidHunkError({
|
|
109
|
+
line: lines[next]!.trim(),
|
|
110
|
+
lineNumber: next + 1,
|
|
111
|
+
reason: `Move destination for '${path}' must not be empty`,
|
|
112
|
+
}),
|
|
113
|
+
)
|
|
114
|
+
}
|
|
115
|
+
next++
|
|
116
|
+
}
|
|
117
|
+
const parsed = parseUpdate(lines, next, end, path, index)
|
|
118
|
+
if ("error" in parsed) return Result.fail(parsed.error)
|
|
119
|
+
hunks.push({ type: "update", path, movePath, chunks: parsed.chunks })
|
|
120
|
+
index = parsed.next
|
|
121
|
+
continue
|
|
122
|
+
}
|
|
123
|
+
return Result.fail(new InvalidHunkError({ line: header, lineNumber: index + 1 }))
|
|
124
|
+
}
|
|
125
|
+
return Result.succeed(hunks)
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
export function derive(path: string, chunks: ReadonlyArray<UpdateFileChunk>, original: string): FileUpdate {
|
|
129
|
+
const source = Bom.split(original)
|
|
130
|
+
const lines = source.text.split("\n")
|
|
131
|
+
if (lines.at(-1) === "") lines.pop()
|
|
132
|
+
const replacements = computeReplacements(lines, path, chunks)
|
|
133
|
+
for (const [start, remove, insert] of replacements.reverse()) lines.splice(start, remove, ...insert)
|
|
134
|
+
if (lines.at(-1) !== "") lines.push("")
|
|
135
|
+
const next = Bom.split(lines.join("\n"))
|
|
136
|
+
return { content: next.text, bom: source.bom || next.bom }
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
export function joinBom(text: string, bom: boolean) {
|
|
140
|
+
return Bom.join(text, bom)
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
function parseAdd(
|
|
144
|
+
lines: ReadonlyArray<string>,
|
|
145
|
+
start: number,
|
|
146
|
+
end: number,
|
|
147
|
+
path: string,
|
|
148
|
+
): { content: string; next: number } | { error: InvalidHunkError } {
|
|
149
|
+
const content: string[] = []
|
|
150
|
+
let index = start
|
|
151
|
+
while (index < end && !isBoundary(lines[index]!.trim())) {
|
|
152
|
+
if (!lines[index]!.startsWith("+")) {
|
|
153
|
+
const line = lines[index]!.trim()
|
|
154
|
+
return {
|
|
155
|
+
error: new InvalidHunkError({
|
|
156
|
+
line,
|
|
157
|
+
lineNumber: index + 1,
|
|
158
|
+
reason: `Invalid Add File line for '${path}': expected a line starting with '+', got '${line}'`,
|
|
159
|
+
}),
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
// Every + line is a whole line of the file, as in Codex, so a final empty + line is a blank last line.
|
|
163
|
+
content.push(`${lines[index]!.slice(1)}\n`)
|
|
164
|
+
index++
|
|
165
|
+
}
|
|
166
|
+
return { content: content.join(""), next: index }
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
function parseUpdate(
|
|
170
|
+
lines: ReadonlyArray<string>,
|
|
171
|
+
start: number,
|
|
172
|
+
end: number,
|
|
173
|
+
path: string,
|
|
174
|
+
hunk: number,
|
|
175
|
+
): { chunks: ReadonlyArray<UpdateFileChunk>; next: number } | { error: InvalidHunkError } {
|
|
176
|
+
const chunks: Array<{
|
|
177
|
+
oldLines: string[]
|
|
178
|
+
newLines: string[]
|
|
179
|
+
changeContext?: string
|
|
180
|
+
endOfFile?: boolean
|
|
181
|
+
}> = []
|
|
182
|
+
let index = start
|
|
183
|
+
let afterEndOfFile = false
|
|
184
|
+
while (index < end) {
|
|
185
|
+
const line = lines[index]!
|
|
186
|
+
const updateLine = line.trimEnd()
|
|
187
|
+
if (afterEndOfFile) {
|
|
188
|
+
if (updateLine === "") {
|
|
189
|
+
index++
|
|
190
|
+
continue
|
|
191
|
+
}
|
|
192
|
+
if (updateLine === "@@" || updateLine.startsWith("@@ ")) afterEndOfFile = false
|
|
193
|
+
else if (isBoundary(updateLine)) break
|
|
194
|
+
else {
|
|
195
|
+
return {
|
|
196
|
+
error: new InvalidHunkError({
|
|
197
|
+
line,
|
|
198
|
+
lineNumber: index + 1,
|
|
199
|
+
reason: `Expected update hunk to start with a @@ context marker, got: '${line}'`,
|
|
200
|
+
}),
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
if (updateLine === "*** End of File") {
|
|
205
|
+
const chunk = chunks.at(-1)
|
|
206
|
+
if (chunk && chunk.oldLines.length === 0 && chunk.newLines.length === 0) {
|
|
207
|
+
return {
|
|
208
|
+
error: new InvalidHunkError({
|
|
209
|
+
line: updateLine,
|
|
210
|
+
lineNumber: index + 1,
|
|
211
|
+
reason: "Update hunk does not contain any lines",
|
|
212
|
+
}),
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
if (chunk) {
|
|
216
|
+
chunk.endOfFile = true
|
|
217
|
+
afterEndOfFile = true
|
|
218
|
+
}
|
|
219
|
+
index++
|
|
220
|
+
continue
|
|
221
|
+
}
|
|
222
|
+
if (isBoundary(updateLine)) break
|
|
223
|
+
if (updateLine === "@@" || updateLine.startsWith("@@ ")) {
|
|
224
|
+
const previous = chunks.at(-1)
|
|
225
|
+
if (previous && previous.oldLines.length === 0 && previous.newLines.length === 0) {
|
|
226
|
+
return {
|
|
227
|
+
error: new InvalidHunkError({
|
|
228
|
+
line,
|
|
229
|
+
lineNumber: index + 1,
|
|
230
|
+
reason: `Unexpected line found in update hunk: '${line}'. Every line should start with ' ' (context line), '+' (added line), or '-' (removed line)`,
|
|
231
|
+
}),
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
chunks.push({
|
|
235
|
+
oldLines: [],
|
|
236
|
+
newLines: [],
|
|
237
|
+
changeContext: updateLine === "@@" ? undefined : updateLine.slice("@@ ".length),
|
|
238
|
+
})
|
|
239
|
+
index++
|
|
240
|
+
continue
|
|
241
|
+
}
|
|
242
|
+
if (chunks.length === 0) chunks.push({ oldLines: [], newLines: [] })
|
|
243
|
+
const chunk = chunks.at(-1)!
|
|
244
|
+
if (line === "") {
|
|
245
|
+
chunk.oldLines.push("")
|
|
246
|
+
chunk.newLines.push("")
|
|
247
|
+
index++
|
|
248
|
+
continue
|
|
249
|
+
}
|
|
250
|
+
if (line.startsWith(" ")) {
|
|
251
|
+
chunk.oldLines.push(line.slice(1))
|
|
252
|
+
chunk.newLines.push(line.slice(1))
|
|
253
|
+
index++
|
|
254
|
+
continue
|
|
255
|
+
}
|
|
256
|
+
if (line.startsWith("-")) {
|
|
257
|
+
chunk.oldLines.push(line.slice(1))
|
|
258
|
+
index++
|
|
259
|
+
continue
|
|
260
|
+
}
|
|
261
|
+
if (line.startsWith("+")) {
|
|
262
|
+
chunk.newLines.push(line.slice(1))
|
|
263
|
+
index++
|
|
264
|
+
continue
|
|
265
|
+
}
|
|
266
|
+
const populated = chunk.oldLines.length > 0 || chunk.newLines.length > 0
|
|
267
|
+
return {
|
|
268
|
+
error: new InvalidHunkError({
|
|
269
|
+
line,
|
|
270
|
+
lineNumber: index + 1,
|
|
271
|
+
reason: populated
|
|
272
|
+
? `Expected update hunk to start with a @@ context marker, got: '${line}'`
|
|
273
|
+
: `Unexpected line found in update hunk: '${line}'. Every line should start with ' ' (context line), '+' (added line), or '-' (removed line)`,
|
|
274
|
+
}),
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
if (chunks.length === 0) {
|
|
278
|
+
return {
|
|
279
|
+
error: new InvalidHunkError({
|
|
280
|
+
line: lines[hunk]!.trim(),
|
|
281
|
+
lineNumber: hunk + 1,
|
|
282
|
+
reason: `Update file hunk for path '${path}' is empty`,
|
|
283
|
+
}),
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
const last = chunks.at(-1)!
|
|
287
|
+
if (last.oldLines.length === 0 && last.newLines.length === 0) {
|
|
288
|
+
const line = lines[index]!.trim()
|
|
289
|
+
return {
|
|
290
|
+
error: new InvalidHunkError({
|
|
291
|
+
line,
|
|
292
|
+
lineNumber: index + 1,
|
|
293
|
+
reason:
|
|
294
|
+
line === "*** End Patch"
|
|
295
|
+
? "Update hunk does not contain any lines"
|
|
296
|
+
: `Unexpected line found in update hunk: '${line}'. Every line should start with ' ' (context line), '+' (added line), or '-' (removed line)`,
|
|
297
|
+
}),
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
return { chunks, next: index }
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
function isBoundary(line: string) {
|
|
304
|
+
return (
|
|
305
|
+
line === "*** End Patch" ||
|
|
306
|
+
line.startsWith("*** Add File: ") ||
|
|
307
|
+
line.startsWith("*** Delete File: ") ||
|
|
308
|
+
line.startsWith("*** Update File: ")
|
|
309
|
+
)
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
function computeReplacements(lines: ReadonlyArray<string>, path: string, chunks: ReadonlyArray<UpdateFileChunk>) {
|
|
313
|
+
const replacements: Array<readonly [start: number, remove: number, insert: ReadonlyArray<string>]> = []
|
|
314
|
+
let lineIndex = 0
|
|
315
|
+
for (const chunk of chunks) {
|
|
316
|
+
if (chunk.changeContext) {
|
|
317
|
+
const context = seek(lines, [chunk.changeContext], lineIndex)
|
|
318
|
+
if (context === -1) throw new Error(`Failed to find context '${chunk.changeContext}' in ${path}`)
|
|
319
|
+
lineIndex = context + 1
|
|
320
|
+
}
|
|
321
|
+
if (chunk.oldLines.length === 0) {
|
|
322
|
+
replacements.push([lines.length, 0, chunk.newLines])
|
|
323
|
+
continue
|
|
324
|
+
}
|
|
325
|
+
let oldLines = chunk.oldLines
|
|
326
|
+
let newLines = chunk.newLines
|
|
327
|
+
let found = seek(lines, oldLines, lineIndex, chunk.endOfFile)
|
|
328
|
+
if (found === -1 && oldLines.at(-1) === "") {
|
|
329
|
+
oldLines = oldLines.slice(0, -1)
|
|
330
|
+
if (newLines.at(-1) === "") newLines = newLines.slice(0, -1)
|
|
331
|
+
found = seek(lines, oldLines, lineIndex, chunk.endOfFile)
|
|
332
|
+
}
|
|
333
|
+
if (found === -1 && chunk.oldLines.every((line) => line === "")) {
|
|
334
|
+
const expected =
|
|
335
|
+
chunk.oldLines.length === 1 ? "an expected blank line" : `${chunk.oldLines.length} consecutive blank lines`
|
|
336
|
+
throw new Error(`Failed to find ${expected} in ${path}`)
|
|
337
|
+
}
|
|
338
|
+
if (found === -1) throw new Error(`Failed to find expected lines in ${path}:\n${chunk.oldLines.join("\n")}`)
|
|
339
|
+
replacements.push([found, oldLines.length, newLines])
|
|
340
|
+
lineIndex = found + oldLines.length
|
|
341
|
+
}
|
|
342
|
+
return replacements.sort((left, right) => left[0] - right[0])
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
function seek(lines: ReadonlyArray<string>, pattern: ReadonlyArray<string>, start: number, eof = false) {
|
|
346
|
+
if (pattern.length === 0) return -1
|
|
347
|
+
if (eof) {
|
|
348
|
+
const offset = lines.length - pattern.length
|
|
349
|
+
if (offset < start) return -1
|
|
350
|
+
for (const compare of [exact, rstrip, trim, normalized]) {
|
|
351
|
+
if (matches(lines, pattern, offset, compare)) return offset
|
|
352
|
+
}
|
|
353
|
+
return -1
|
|
354
|
+
}
|
|
355
|
+
for (const compare of [exact, rstrip, trim, normalized]) {
|
|
356
|
+
for (let offset = start; offset <= lines.length - pattern.length; offset++) {
|
|
357
|
+
if (matches(lines, pattern, offset, compare)) return offset
|
|
358
|
+
}
|
|
359
|
+
}
|
|
360
|
+
return -1
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
function matches(
|
|
364
|
+
lines: ReadonlyArray<string>,
|
|
365
|
+
pattern: ReadonlyArray<string>,
|
|
366
|
+
offset: number,
|
|
367
|
+
compare: (left: string, right: string) => boolean,
|
|
368
|
+
) {
|
|
369
|
+
return pattern.every((line, index) => compare(lines[offset + index]!, line))
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
const exact = (left: string, right: string) => left === right
|
|
373
|
+
const rstrip = (left: string, right: string) => left.trimEnd() === right.trimEnd()
|
|
374
|
+
const trim = (left: string, right: string) => left.trim() === right.trim()
|
|
375
|
+
const normalized = (left: string, right: string) => normalize(left.trim()) === normalize(right.trim())
|
|
376
|
+
const normalize = (value: string) =>
|
|
377
|
+
value
|
|
378
|
+
.replace(/[‘’‚‛]/g, "'")
|
|
379
|
+
.replace(/[“”„‟]/g, '"')
|
|
380
|
+
.replace(/[‐‑‒–—―−]/g, "-")
|
|
381
|
+
.replace(/[\u00A0\u2002-\u200A\u202F\u205F\u3000]/g, " ")
|
|
382
|
+
const stripHeredoc = (input: string) => input.match(/^(?:cat\s+)?<<(['"]?)(\w+)\1\s*\n([\s\S]*?)\n\2\s*$/)?.[3] ?? input
|