|
| 1 | +// Keep only APIs available for a given deployment type: endpoints with no |
| 2 | +// x-availability property, or whose x-availability matches the requested value. |
| 3 | + |
| 4 | +const fs = require("fs"); |
| 5 | +const path = require("path"); |
| 6 | +const yaml = require("js-yaml"); |
| 7 | + |
| 8 | +const HTTP_METHODS = ["get", "post", "put", "patch", "delete"]; |
| 9 | + |
| 10 | +function isHTTPMethod(metadata) { |
| 11 | + return HTTP_METHODS.includes(metadata[0]); |
| 12 | +} |
| 13 | + |
| 14 | +function isAvailableInEnvironment(metadata, environment) { |
| 15 | + const available = |
| 16 | + !Object.hasOwn(metadata, "x-availability") || |
| 17 | + metadata["x-availability"].toLowerCase() === environment.toLowerCase(); |
| 18 | + return available; |
| 19 | +} |
| 20 | + |
| 21 | +function hasOperationOrRef(pathData) { |
| 22 | + return Object.keys(pathData).some( |
| 23 | + (key) => HTTP_METHODS.includes(key) || key === "$ref" |
| 24 | + ); |
| 25 | +} |
| 26 | + |
| 27 | +function filterMethodsForEnvironment(pathData, environment) { |
| 28 | + return Object.fromEntries( |
| 29 | + Object.entries(pathData) |
| 30 | + .filter(isHTTPMethod) |
| 31 | + .filter(([_, metadata]) => |
| 32 | + isAvailableInEnvironment(metadata, environment) |
| 33 | + ) |
| 34 | + ); |
| 35 | +} |
| 36 | + |
| 37 | +function otherMetadata(pathData) { |
| 38 | + return Object.fromEntries( |
| 39 | + Object.entries(pathData).filter((d) => !isHTTPMethod(d)) |
| 40 | + ); |
| 41 | +} |
| 42 | + |
| 43 | +function refsOnly(metadata) { |
| 44 | + return Object.fromEntries( |
| 45 | + Object.entries(metadata).filter(([key]) => key === "$ref") |
| 46 | + ); |
| 47 | +} |
| 48 | + |
| 49 | +function filterPathDataForEnvironment(pathData, environment) { |
| 50 | + const methodsForEnvironment = filterMethodsForEnvironment( |
| 51 | + pathData, |
| 52 | + environment |
| 53 | + ); |
| 54 | + |
| 55 | + if (Object.keys(methodsForEnvironment).length === 0) { |
| 56 | + // when there are no available methods, drop all other metadata except |
| 57 | + // $ref, which will be cleaned up later |
| 58 | + return refsOnly(otherMetadata(pathData)); |
| 59 | + } |
| 60 | + |
| 61 | + // when there are available methods, return all other metadata too |
| 62 | + return { ...methodsForEnvironment, ...otherMetadata(pathData) }; |
| 63 | +} |
| 64 | + |
| 65 | +// we need to escape routes to match spec refs |
| 66 | +// https://swagger.io/docs/specification/v3_0/using-ref/#escape-characters |
| 67 | +function escapeRoute(route) { |
| 68 | + return route.replace(/\~/g, "~0").replace(/\//g, "~1"); |
| 69 | +} |
| 70 | + |
| 71 | +function filterPaths(paths, environment) { |
| 72 | + const filtered = {}; |
| 73 | + const removedRoutes = []; |
| 74 | + |
| 75 | + if (paths) { |
| 76 | + for (const [route, pathData] of Object.entries(paths)) { |
| 77 | + const filteredPathData = filterPathDataForEnvironment( |
| 78 | + pathData, |
| 79 | + environment |
| 80 | + ); |
| 81 | + |
| 82 | + // a path is worth keeping only if it still has an operation or a $ref to one. |
| 83 | + // other metadata (summary/description/parameters) shouldn't keep an |
| 84 | + // operation-less path alive |
| 85 | + if (hasOperationOrRef(filteredPathData)) { |
| 86 | + filtered[route] = filteredPathData; |
| 87 | + } else { |
| 88 | + removedRoutes.push(escapeRoute(route)); |
| 89 | + } |
| 90 | + } |
| 91 | + } |
| 92 | + |
| 93 | + return [filtered, removedRoutes]; |
| 94 | +} |
| 95 | + |
| 96 | +function isDanglingRef(pathData, allRemovedRoutes) { |
| 97 | + return ( |
| 98 | + Object.hasOwn(pathData, "$ref") && allRemovedRoutes.has(pathData["$ref"]) |
| 99 | + ); |
| 100 | +} |
| 101 | + |
| 102 | +function pruneRefs(paths, allRemovedRoutes) { |
| 103 | + return Object.fromEntries( |
| 104 | + Object.entries(paths).filter( |
| 105 | + ([, pathData]) => !isDanglingRef(pathData, allRemovedRoutes) |
| 106 | + ) |
| 107 | + ); |
| 108 | +} |
| 109 | + |
| 110 | +// js-yaml drops comments on load/dump, so we should capture the leading |
| 111 | +// comment block separately and re-prepend. |
| 112 | +function extractHeaderComments(content) { |
| 113 | + const lines = content.split("\n"); |
| 114 | + let end = 0; |
| 115 | + while ( |
| 116 | + end < lines.length && |
| 117 | + (lines[end] === "" || lines[end].trimStart().startsWith("#")) |
| 118 | + ) { |
| 119 | + end++; |
| 120 | + } |
| 121 | + return end === 0 ? "" : lines.slice(0, end).join("\n") + "\n"; |
| 122 | +} |
| 123 | + |
| 124 | +function loadSpecFile(filePath) { |
| 125 | + const content = fs.readFileSync(filePath, "utf8"); |
| 126 | + |
| 127 | + return { |
| 128 | + path: filePath, |
| 129 | + header: extractHeaderComments(content), |
| 130 | + spec: yaml.load(content), |
| 131 | + }; |
| 132 | +} |
| 133 | + |
| 134 | +function getYamlFiles(specDir) { |
| 135 | + return fs |
| 136 | + .readdirSync(specDir) |
| 137 | + .filter((file) => file.endsWith(".yaml") || file.endsWith(".yml")) |
| 138 | + .map((file) => path.join(specDir, file)); |
| 139 | +} |
| 140 | + |
| 141 | +function writeFile(filePath, fileData) { |
| 142 | + fs.writeFileSync(filePath, fileData.header + yaml.dump(fileData.spec)); |
| 143 | +} |
| 144 | + |
| 145 | +// compare against the original paths to know whether a file needs rewriting, |
| 146 | +// instead of threading a "changed" flag through every filtering step |
| 147 | +function pathsChanged(before, after) { |
| 148 | + return JSON.stringify(before ?? {}) !== JSON.stringify(after); |
| 149 | +} |
| 150 | + |
| 151 | +function filterByAvailability(specDir, environment) { |
| 152 | + const files = getYamlFiles(specDir).map((filePath) => loadSpecFile(filePath)); |
| 153 | + |
| 154 | + const mapping = {}; |
| 155 | + const allRemovedRoutes = new Set(); |
| 156 | + for (const file of files) { |
| 157 | + const originalPaths = file.spec.paths; |
| 158 | + |
| 159 | + // filter methods by x-availability |
| 160 | + const [filteredPaths, removedRoutes] = filterPaths( |
| 161 | + originalPaths, |
| 162 | + environment |
| 163 | + ); |
| 164 | + file.spec.paths = filteredPaths; |
| 165 | + |
| 166 | + // store removed routes for pruning refs later |
| 167 | + const fileName = file.path.split("/").at(-1); |
| 168 | + removedRoutes.forEach((e) => |
| 169 | + allRemovedRoutes.add(`${fileName}#/paths/${e}`) |
| 170 | + ); |
| 171 | + |
| 172 | + // store file, data mapping for tracking/writing file changes later |
| 173 | + mapping[file.path] = { |
| 174 | + spec: file.spec, |
| 175 | + header: file.header, |
| 176 | + originalPaths, |
| 177 | + }; |
| 178 | + } |
| 179 | + |
| 180 | + // prune dangling refs |
| 181 | + for (const fileData of Object.values(mapping)) { |
| 182 | + fileData.spec.paths = pruneRefs(fileData.spec.paths, allRemovedRoutes); |
| 183 | + } |
| 184 | + |
| 185 | + // write files whose paths actually changed |
| 186 | + Object.entries(mapping).forEach(([filePath, fileData]) => { |
| 187 | + if (pathsChanged(fileData.originalPaths, fileData.spec.paths)) { |
| 188 | + writeFile(filePath, fileData); |
| 189 | + } |
| 190 | + }); |
| 191 | +} |
| 192 | + |
| 193 | +module.exports = { |
| 194 | + isAvailableInEnvironment, |
| 195 | + filterByAvailability, |
| 196 | + filterPaths, |
| 197 | + filterPathDataForEnvironment, |
| 198 | + extractHeaderComments, |
| 199 | + escapeRoute, |
| 200 | + pruneRefs, |
| 201 | + pathsChanged, |
| 202 | +}; |
0 commit comments