const MAX_TEXT_BYTES = 16 * 1024; const MAX_CONTENT_BYTES = 32 * 1024; const MAX_BODY_BYTES = 256 * 1024; type AppendEdit = { op: "append"; content: string }; type InsertAfterEdit = { op: "insert_after"; target: string; content: string }; type ReplaceEdit = { op: "replace"; target: string; content: string }; type DeleteEdit = { op: "delete"; target: string }; export type PatchEdit = AppendEdit | InsertAfterEdit | ReplaceEdit | DeleteEdit; export type Patch = { edits: PatchEdit[] }; export type EditReport = { index: number; status: "applied" | "rejected"; reason?: string; }; function byteLength(value: string): number { return Buffer.byteLength(value, "utf8"); } function assertObject( value: unknown, label: string, ): asserts value is Record { if (typeof value !== "object" || value === null || Array.isArray(value)) throw new Error(`${label} must be an object`); } function assertExactKeys( value: Record, keys: readonly string[], ): void { for (const key of Object.keys(value)) if (!keys.includes(key)) throw new Error(`patch edit has unknown field: ${key}`); } function requiredText(value: unknown, field: "target" | "content"): string { if (typeof value !== "string" || value.length === 0) throw new Error(`patch ${field} must be nonempty`); if (byteLength(value) > MAX_TEXT_BYTES) throw new Error(`patch ${field} exceeds 16 KiB`); return value; } export function parsePatch(value: unknown): Patch { assertObject(value, "patch"); if (Object.keys(value).length !== 1 || !Array.isArray(value.edits)) throw new Error("patch must contain only edits"); if (value.edits.length < 1 || value.edits.length > 4) throw new Error("patch must contain one to four edits"); let appendCount = 0; let contentBytes = 0; const edits = value.edits.map((entry): PatchEdit => { assertObject(entry, "patch edit"); if (typeof entry.op !== "string") throw new Error("patch edit operation is required"); switch (entry.op) { case "append": { assertExactKeys(entry, ["op", "content"]); appendCount += 1; const content = requiredText(entry.content, "content"); contentBytes += byteLength(content); return { op: "append", content }; } case "insert_after": { assertExactKeys(entry, ["op", "target", "content"]); const target = requiredText(entry.target, "target"); const content = requiredText(entry.content, "content"); contentBytes += byteLength(content); return { op: "insert_after", target, content }; } case "replace": { assertExactKeys(entry, ["op", "target", "content"]); const target = requiredText(entry.target, "target"); const content = requiredText(entry.content, "content"); contentBytes += byteLength(content); return { op: "replace", target, content }; } case "delete": { assertExactKeys(entry, ["op", "target"]); return { op: "delete", target: requiredText(entry.target, "target") }; } default: throw new Error(`unknown patch operation: ${entry.op}`); } }); if (appendCount > 1) throw new Error("patch allows at most one append"); if (contentBytes > MAX_CONTENT_BYTES) throw new Error("patch content exceeds 32 KiB"); return { edits }; } type ResolvedEdit = { index: number; edit: Exclude; start: number; end: number; byteStart: number; }; function allOccurrences(body: string, target: string): number[] { const occurrences: number[] = []; let offset = 0; while (offset <= body.length - target.length) { const found = body.indexOf(target, offset); if (found < 0) break; occurrences.push(found); offset = found + 1; } return occurrences; } function validUtf8(value: string): boolean { for (let index = 0; index < value.length; index += 1) { const code = value.charCodeAt(index); if (code < 0xd800 || code > 0xdfff) continue; if ( code >= 0xdc00 || index + 1 >= value.length || value.charCodeAt(index + 1) < 0xdc00 || value.charCodeAt(index + 1) > 0xdfff ) return false; index += 1; } return true; } function rejected(edits: readonly PatchEdit[], reason: string): EditReport[] { return edits.map((_, index) => ({ index, status: "rejected", reason })); } export function applyPatch( body: string, patch: Patch, ): { body: string; changed: boolean; reports: EditReport[] } { const ranges: ResolvedEdit[] = []; for (const [index, edit] of patch.edits.entries()) { if (edit.op === "append") continue; const occurrences = allOccurrences(body, edit.target); if (occurrences.length !== 1) return { body, changed: false, reports: rejected(patch.edits, "target must occur exactly once"), }; const start = occurrences[0]; if (start === undefined) throw new Error("unreachable missing target"); const end = start + edit.target.length; ranges.push({ index, edit, start, end, byteStart: byteLength(body.slice(0, start)), }); } const orderedRanges = [...ranges].sort( (left, right) => left.start - right.start, ); for (let index = 1; index < orderedRanges.length; index += 1) { const previous = orderedRanges[index - 1]; const current = orderedRanges[index]; if (!previous || !current) continue; if (current.start < previous.end) return { body, changed: false, reports: rejected(patch.edits, "target ranges overlap"), }; } let candidate = body; for (const range of [...ranges].sort( (left, right) => right.byteStart - left.byteStart, )) { const { edit } = range; const content = edit.op === "delete" ? "" : edit.content; const insertion = edit.op === "insert_after" ? range.end : range.start; const removalEnd = edit.op === "insert_after" ? range.end : range.end; candidate = `${candidate.slice(0, insertion)}${content}${candidate.slice(removalEnd)}`; } const append = patch.edits.find( (edit): edit is AppendEdit => edit.op === "append", ); if (append) candidate = `${candidate}${candidate.endsWith("\n") ? "" : "\n"}${append.content}`; if (candidate.length === 0) return { body, changed: false, reports: rejected(patch.edits, "candidate body must be nonempty"), }; if (!validUtf8(candidate)) return { body, changed: false, reports: rejected(patch.edits, "candidate body must be valid UTF-8"), }; if (byteLength(candidate) > MAX_BODY_BYTES) return { body, changed: false, reports: rejected(patch.edits, "candidate body exceeds 256 KiB"), }; if (candidate === body) return { body, changed: false, reports: rejected(patch.edits, "patch does not change the body"), }; return { body: candidate, changed: true, reports: patch.edits.map((_, index) => ({ index, status: "applied" })), }; }