Skip to content
Source
Sign inSign up
Open History to see the last commit

OpenApiPatch.ts

580 lines16.6 KB

1/**
2 * OpenAPI spec patching utilities.
3 *
4 * Handles parsing and applying JSON Patch documents (RFC 6902) to OpenAPI
5 * specs. Supports patches from:
6 * - JSON files (.json)
7 * - YAML files (.yaml, .yml)
8 * - Inline JSON strings
9 *
10 * @since 4.0.0
11 */
12​
13import * as Effect from "effect/Effect"
14import * as Yaml from "effect/encoding/Yaml"
15import * as FileSystem from "effect/FileSystem"
16import { constFalse, constUndefined } from "effect/Function"
17import * as JsonPatch from "effect/JsonPatch"
18import * as JsonPointer from "effect/JsonPointer"
19import * as Path from "effect/Path"
20import * as Predicate from "effect/Predicate"
21import * as Schema from "effect/Schema"
22​
23// =============================================================================
24// Error Types
25// =============================================================================
26​
27/**
28 * Error thrown when parsing a JSON Patch input fails.
29 *
30 * **Details**
31 *
32 * This error occurs when:
33 * - A patch file cannot be read
34 * - JSON or YAML syntax is invalid
35 * - The file format is unsupported
36 *
37 * **Example** (Creating a parse error)
38 *
39 * ```ts import.meta.vitest
40 * import { JsonPatchParseError } from "@effect/openapi-generator/OpenApiPatch"
41 *
42 * const error = new JsonPatchParseError({
43 * source: "./patches/fix.json",
44 * reason: "Unexpected token at position 42"
45 * })
46 *
47 * error.message // => "Failed to parse patch from ./patches/fix.json: Unexpected token at position 42"
48 * ```
49 *
50 * @category errors
51 * @since 4.0.0
52 */
53export class JsonPatchParseError extends Schema.Error<JsonPatchParseError>("JsonPatchParseError")({
54 _tag: Schema.tag("JsonPatchParseError"),
55 source: Schema.String,
56 reason: Schema.String
57}) {
58 override get message() {
59 return `Failed to parse patch from ${this.source}: ${this.reason}`
60 }
62​
63/**
64 * Error thrown when a parsed value does not conform to the JSON Patch schema.
65 *
66 * **Details**
67 *
68 * This error occurs when:
69 * - The patch is not an array
70 * - An operation is missing required fields (op, path)
71 * - An operation has an unsupported op value
72 * - An add/replace operation is missing the value field
73 *
74 * **Example** (Creating a validation error)
75 *
76 * ```ts import.meta.vitest
77 * import { JsonPatchValidationError } from "@effect/openapi-generator/OpenApiPatch"
78 *
79 * const error = new JsonPatchValidationError({
80 * source: "inline",
81 * reason: "Expected 'add' | 'remove' | 'replace' at [0].op, got 'copy'"
82 * })
83 *
84 * error.message // => "Invalid JSON Patch from inline: Expected 'add' | 'remove' | 'replace' at [0].op, got 'copy'"
85 * ```
86 *
87 * @category errors
88 * @since 4.0.0
89 */
90export class JsonPatchValidationError extends Schema.Error<JsonPatchValidationError>("JsonPatchValidationError")({
91 _tag: Schema.tag("JsonPatchValidationError"),
92 source: Schema.String,
93 reason: Schema.String
94}) {
95 override get message() {
96 return `Invalid JSON Patch from ${this.source}: ${this.reason}`
97 }
99​
100/**
101 * Error thrown when applying a JSON Patch operation fails.
102 *
103 * **Details**
104 *
105 * This error occurs when:
106 * - A path does not exist for remove/replace operations
107 * - An array index is out of bounds
108 * - The target location is not a valid container
109 *
110 * **Example** (Creating an application error)
111 *
112 * ```ts import.meta.vitest
113 * import { JsonPatchApplicationError } from "@effect/openapi-generator/OpenApiPatch"
114 *
115 * const error = new JsonPatchApplicationError({
116 * source: "./patches/fix.json",
117 * operationIndex: 2,
118 * operation: "remove",
119 * path: "/paths/~1users",
120 * reason: "Property \"users\" does not exist"
121 * })
122 *
123 * error.message // => 'Failed to apply patch from ./patches/fix.json: operation 2 (remove at /paths/~1users): Property "users" does not exist'
124 * ```
125 *
126 * @category errors
127 * @since 4.0.0
128 */
129export class JsonPatchApplicationError extends Schema.Error<JsonPatchApplicationError>("JsonPatchApplicationError")({
130 _tag: Schema.tag("JsonPatchApplicationError"),
131 source: Schema.String,
132 operationIndex: Schema.Natural,
133 operation: Schema.String,
134 path: Schema.String,
135 reason: Schema.String
136}) {
137 override get message() {
138 return `Failed to apply patch from ${this.source}: operation ${this.operationIndex} ` +
139 `(${this.operation} at ${this.path}): ${this.reason}`
140 }
142​
143/**
144 * Error thrown when multiple JSON Patch operations fail.
145 *
146 * **Details**
147 *
148 * This error aggregates all application errors so users can see every
149 * failing operation at once instead of fixing them one at a time.
150 *
151 * **Example** (Creating an aggregate error)
152 *
153 * ```ts import.meta.vitest
154 * import { JsonPatchAggregateError, JsonPatchApplicationError } from "@effect/openapi-generator/OpenApiPatch"
155 *
156 * const error = new JsonPatchAggregateError({
157 * errors: [
158 * new JsonPatchApplicationError({
159 * source: "./fix.json",
160 * operationIndex: 0,
161 * operation: "replace",
162 * path: "/info/x",
163 * reason: "Property does not exist"
164 * }),
165 * new JsonPatchApplicationError({
166 * source: "./fix.json",
167 * operationIndex: 2,
168 * operation: "remove",
169 * path: "/paths/~1users",
170 * reason: "Property does not exist"
171 * })
172 * ]
173 * })
174 *
175 * error.message.split("\n")[0] // => "2 patch operations failed:"
176 * ```
177 *
178 * @category errors
179 * @since 4.0.0
180 */
181export class JsonPatchAggregateError extends Schema.Error<JsonPatchAggregateError>("JsonPatchAggregateError")({
182 _tag: Schema.tag("JsonPatchAggregateError"),
183 errors: Schema.Array(Schema.Unknown)
184}) {
185 override get message() {
186 const errors = this.errors as ReadonlyArray<JsonPatchApplicationError>
187 const count = errors.length
188 const plural = count === 1 ? "operation" : "operations"
189 const details = errors
190 .map((e, i) => ` ${i + 1}. [${e.source}] op ${e.operationIndex} (${e.operation} at ${e.path}): ${e.reason}`)
191 .join("\n")
192 return `${count} patch ${plural} failed:\n${details}`
193 }
195​
196// =============================================================================
197// Schema
198// =============================================================================
199​
200/**
201 * Schema for a JSON Patch "add" operation.
202 *
203 * @category schemas
204 * @since 4.0.0
205 */
206export const JsonPatchAdd: Schema.Codec<
207 Extract<
208 JsonPatch.JsonPatchOperation,
209 { op: "add" }
210 >
211> = Schema.Struct({
212 op: Schema.Literal("add"),
213 path: Schema.String,
214 value: Schema.Json,
215 description: Schema.optionalKey(Schema.String)
216})
217​
218/**
219 * Schema for a JSON Patch "remove" operation.
220 *
221 * @category schemas
222 * @since 4.0.0
223 */
224export const JsonPatchRemove: Schema.Codec<
225 Extract<
226 JsonPatch.JsonPatchOperation,
227 { op: "remove" }
228 >
229> = Schema.Struct({
230 op: Schema.Literal("remove"),
231 path: Schema.String,
232 description: Schema.optionalKey(Schema.String)
233})
234​
235/**
236 * Schema for a JSON Patch "replace" operation.
237 *
238 * @category schemas
239 * @since 4.0.0
240 */
241export const JsonPatchReplace: Schema.Codec<
242 Extract<
243 JsonPatch.JsonPatchOperation,
244 { op: "replace" }
245 >
246> = Schema.Struct({
247 op: Schema.Literal("replace"),
248 path: Schema.String,
249 value: Schema.Json,
250 description: Schema.optionalKey(Schema.String)
251})
252​
253/**
254 * A JSON Patch "move" operation, which removes the value at `from` and adds it at `path`.
255 *
256 * @category models
257 * @since 4.0.0
258 */
259export interface JsonPatchMoveOperation {
260 readonly op: "move"
261 readonly from: string
262 readonly path: string
263 readonly description?: string
265​
266/**
267 * Schema for a JSON Patch "move" operation.
268 *
269 * @category schemas
270 * @since 4.0.0
271 */
272export const JsonPatchMove: Schema.Codec<JsonPatchMoveOperation> = Schema.Struct({
273 op: Schema.Literal("move"),
274 from: Schema.String,
275 path: Schema.String,
276 description: Schema.optionalKey(Schema.String)
277})
278​
279/**
280 * Schema for a single JSON Patch operation.
281 *
282 * **Details**
283 *
284 * Supports the RFC 6902 operations `add`, `remove`, `replace`, and `move`.
285 * `move` is applied as a `remove` followed by an `add` of the moved value.
286 *
287 * @category schemas
288 * @since 4.0.0
289 */
290export const JsonPatchOperation: Schema.Codec<JsonPatch.JsonPatchOperation | JsonPatchMoveOperation> = Schema
291 .Union([
292 JsonPatchAdd,
293 JsonPatchRemove,
294 JsonPatchReplace,
295 JsonPatchMove
296 ])
297​
298/**
299 * Schema for a JSON Patch document (array of operations).
300 *
301 * **Details**
302 *
303 * A JSON Patch document is an ordered list of operations to apply to a JSON
304 * document. Operations are applied in sequence, with each operation seeing
305 * the result of previous operations.
306 *
307 * **Example** (Decoding a patch document)
308 *
309 * ```ts import.meta.vitest
310 * import { Schema } from "effect"
311 * import { JsonPatchDocument } from "@effect/openapi-generator/OpenApiPatch"
312 *
313 * const patch = Schema.decodeUnknownSync(JsonPatchDocument)([
314 * { op: "add", path: "/foo", value: "bar" },
315 * { op: "remove", path: "/baz" },
316 * { op: "replace", path: "/qux", value: 42 }
317 * ])
318 *
319 * patch.map((operation) => operation.op) // => ["add", "remove", "replace"]
320 * ```
321 *
322 * @category schemas
323 * @since 4.0.0
324 */
325export const JsonPatchDocument = Schema.Array(JsonPatchOperation)
326​
327// RFC 6902 defines `move` as removing the value at `from` and adding it at `path`
328const expandMove = (op: JsonPatchMoveOperation, document: Schema.Json): JsonPatch.JsonPatch => {
329 if (op.path.startsWith(`${op.from}/`)) {
330 throw new Error(`Cannot move ${op.from} into its own child ${op.path}`)
331 }
332 let value: unknown = document
333 for (const token of op.from.split("/").slice(1).map(JsonPointer.unescapeToken)) {
334 if (!Predicate.isObjectOrArray(value) || !Object.hasOwn(value, token)) {
335 throw new Error(`Path ${op.from} does not exist`)
336 }
337 value = (value as Record<string, unknown>)[token]
338 }
339 // Moving a location onto itself leaves the document unchanged, once the source is known to exist
340 if (op.from === op.path) return []
341 return [{ op: "remove", path: op.from }, { op: "add", path: op.path, value: value as Schema.Json }]
343​
344/**
345 * Type for a JSON Patch document.
346 *
347 * @category models
348 * @since 4.0.0
349 */
350export type JsonPatchDocument = typeof JsonPatchDocument.Type
351​
352// =============================================================================
353// Parsing Functions
354// =============================================================================
355​
356const decodeJsonPatchDocument = Schema.decodeUnknownEffect(JsonPatchDocument)
357​
358/**
359 * Check if a string looks like it could be a file path.
360 *
361 * Heuristic: contains path separators or ends with a known extension.
362 */
363const looksLikeFilePath = (input: string): boolean => {
364 const trimmed = input.trim()
365 if (trimmed.startsWith("[")) return false
366 if (trimmed.includes("/") || trimmed.includes("\\")) return true
367 if (/\.(json|yaml|yml)$/i.test(trimmed)) return true
368 return false
370​
371/**
372 * Determine file format from extension.
373 */
374const getFileFormat = Effect.fn(function*(filePath: string) {
375 const path = yield* Path.Path
376 const { ext } = path.parse(filePath)
377 if (ext === ".json") return "json"
378 if (ext === ".yaml" || ext === ".yml") return "yaml"
379 return undefined
380})
381​
382/**
383 * Check if a file path exists and is a file.
384 */
385const checkFileExists = Effect.fn("checkFileExists")(function*(filePath: string) {
386 const fs = yield* FileSystem.FileSystem
387 const path = yield* Path.Path
388 const absolutePath = path.isAbsolute(filePath) ? filePath : path.resolve(filePath)
389 const exists = yield* Effect.orElseSucceed(fs.exists(absolutePath), constFalse)
390 if (!exists) return false
391 const stat = yield* Effect.orElseSucceed(fs.stat(absolutePath), constUndefined)
392 return Predicate.isNotUndefined(stat) && stat.type === "File"
393})
394​
395/**
396 * Parse content as JSON.
397 */
398const parseJsonContent = Effect.fnUntraced(function*(content: string, source: string) {
399 return yield* Effect.try({
400 try: () => JSON.parse(content) as unknown,
401 catch: (error) =>
402 new JsonPatchParseError({
403 source,
404 reason: error instanceof Error ? error.message : String(error)
405 })
406 })
407})
408​
409/**
410 * Parse content as YAML.
411 */
412const parseYamlContent = Effect.fnUntraced(function*(content: string, source: string) {
413 return yield* Effect.try({
414 try: () => Yaml.parse(content) as unknown,
415 catch: (error) =>
416 new JsonPatchParseError({
417 source,
418 reason: error instanceof Error ? error.message : String(error)
419 })
420 })
421})
422​
423/**
424 * Read and parse a patch file.
425 */
426const parsePatchFile = Effect.fn("parsePatchFile")(function*(filePath: string) {
427 const fs = yield* FileSystem.FileSystem
428 const path = yield* Path.Path
429 const absolutePath = path.isAbsolute(filePath) ? filePath : path.resolve(filePath)
430​
431 const fileFormat = yield* getFileFormat(filePath)
432 if (Predicate.isUndefined(fileFormat)) {
433 return yield* new JsonPatchParseError({
434 source: filePath,
435 reason: `Unsupported file format. Expected .json, .yaml, or .yml`
436 })
437 }
438​
439 const content = yield* Effect.mapError(fs.readFileString(absolutePath), (error) =>
440 new JsonPatchParseError({
441 source: filePath,
442 reason: `Failed to read file: ${error.message}`
443 }))
444​
445 const parsed = fileFormat === "json"
446 ? yield* parseJsonContent(content, filePath)
447 : yield* parseYamlContent(content, filePath)
448​
449 return yield* Effect.mapError(decodeJsonPatchDocument(parsed), (error) =>
450 new JsonPatchValidationError({
451 source: filePath,
452 reason: error.message
453 }))
454})
455​
456/**
457 * Parse inline JSON string as a patch document.
458 */
459const parseInlinePatch = Effect.fn("parseInlinePatch")(function*(input: string) {
460 const parsed = yield* parseJsonContent(input, "inline")
461 return yield* Effect.mapError(decodeJsonPatchDocument(parsed), (error) =>
462 new JsonPatchValidationError({
463 source: "inline",
464 reason: error.message
465 }))
466})
467​
468/**
469 * Parse a JSON Patch from either a file path or inline JSON string.
470 *
471 * **Details**
472 *
473 * The input is first checked as a file path. If the file exists, it is read
474 * and parsed based on its extension (.json, .yaml, .yml). Otherwise, the
475 * input is parsed as inline JSON.
476 *
477 * **Example** (Parsing patch input)
478 *
479 * ```ts import.meta.vitest
480 * import { Effect } from "effect"
481 * import { parsePatchInput } from "@effect/openapi-generator/OpenApiPatch"
482 *
483 * // From inline JSON
484 * const fromInline = parsePatchInput(
485 * '[{"op":"replace","path":"/info/title","value":"My API"}]'
486 * )
487 *
488 * const program = Effect.gen(function*() {
489 * const patch = yield* fromInline
490 * return [patch[0].op, patch[0].path]
491 * })
492 *
493 * Effect.runSync(program) // => ["replace", "/info/title"]
494 * ```
495 *
496 * @category parsing
497 * @since 4.0.0
498 */
499export const parsePatchInput = Effect.fn("parsePatchInput")(function*(input: string) {
500 if (looksLikeFilePath(input)) {
501 const exists = yield* checkFileExists(input)
502 if (exists) {
503 return yield* parsePatchFile(input)
504 }
505 }
506 return yield* parseInlinePatch(input)
507})
508​
509// =============================================================================
510// Application Functions
511// =============================================================================
512​
513/**
514 * Apply a sequence of JSON patches to a document.
515 *
516 * **Details**
517 *
518 * Patches are applied in order, with each patch operating on the result of
519 * the previous one. All operations are attempted, and if any fail, the errors
520 * are accumulated and reported together so users can fix all issues at once.
521 *
522 * **Example** (Applying patches)
523 *
524 * ```ts import.meta.vitest
525 * import { Effect } from "effect"
526 * import { applyPatches } from "@effect/openapi-generator/OpenApiPatch"
527 *
528 * const document = { info: { title: "Old Title" }, paths: {} }
529 * const patches = [
530 * {
531 * source: "inline",
532 * patch: [{ op: "replace" as const, path: "/info/title", value: "New Title" }]
533 * }
534 * ]
535 *
536 * const program = Effect.gen(function*() {
537 * const result = yield* applyPatches(patches, document)
538 * return (result as typeof document).info.title
539 * })
540 *
541 * Effect.runSync(program) // => "New Title"
542 * ```
543 *
544 * @category transforming
545 * @since 4.0.0
546 */
547export const applyPatches = Effect.fn("applyPatches")(function*(
548 patches: ReadonlyArray<{ readonly source: string; readonly patch: JsonPatchDocument }>,
549 document: Schema.Json
550) {
551 let result: Schema.Json = document
552 const errors: Array<JsonPatchApplicationError> = []
553​
554 for (const { source, patch } of patches) {
555 for (let i = 0; i < patch.length; i++) {
556 const op = patch[i]
557 yield* Effect.ignore(Effect.try({
558 try: () => {
559 result = JsonPatch.apply(op.op === "move" ? expandMove(op, result) : [op], result)
560 },
561 catch: (error) =>
562 errors.push(
563 new JsonPatchApplicationError({
564 source,
565 operationIndex: i,
566 operation: op.op,
567 path: op.path,
568 reason: error instanceof Error ? error.message : String(error)
569 })
570 )
571 }))
572 }
573 }
574​
575 if (errors.length > 0) {
576 return yield* new JsonPatchAggregateError({ errors })
577 }
578​
579 return result
580})