|
| 1 | +import fs from "fs"; |
| 2 | +import { PackageJson, TsConfigJson } from "type-fest"; |
| 3 | +import detectIndent from "detect-indent" |
| 4 | +import loadJsonFile from "load-json-file" |
| 5 | + |
| 6 | +interface Options { |
| 7 | + /** @default utf-8 */ |
| 8 | + encoding: BufferEncoding |
| 9 | + /** |
| 10 | + * Will throw in case of FS error or invalid JSON |
| 11 | + * @default true |
| 12 | + * */ |
| 13 | + throws: boolean |
| 14 | + // ideally this lib should integrate with json validator |
| 15 | + /** @default "throw" (even if throws is false) */ |
| 16 | + ifFieldIsMissing: "throw" | "skip" | "add" |
| 17 | + /** |
| 18 | + * - throw - throws (even if throws param is false) |
| 19 | + *- skip - won't call the function |
| 20 | + * - pass - pass the `undefined` value |
| 21 | + * @default "throw" |
| 22 | + * */ |
| 23 | + ifFieldIsMissingForSetter: "throw" | "skip" | "pass" |
| 24 | + /** |
| 25 | + * - null - disable formatting |
| 26 | + * - hard - one hard tab \t |
| 27 | + * - number - number of spaces |
| 28 | + * @default "preserve" |
| 29 | + * */ |
| 30 | + tabSize: null | number | "preserve" | "hard" |
| 31 | +} |
| 32 | + |
| 33 | +type GettersDeep<T extends object> = { |
| 34 | + [K in keyof T]: (oldValue: T[K], json: T) => unknown |
| 35 | + //T[K] extends object ? ((oldValue: T[K]) => unknown)/* | GettersDeep<T[K]> */ : (oldValue: T[K]) => unknown |
| 36 | +} |
| 37 | + |
| 38 | +export type ModifyJsonFileFunction<T extends object> = ( |
| 39 | + path: string, |
| 40 | + fields: Partial<T | GettersDeep<T>>, |
| 41 | + options?: Options |
| 42 | +) => Promise<void>; |
| 43 | + |
| 44 | +type ModifyJsonFileGenericFunction = <T extends object>( |
| 45 | + path: string, |
| 46 | + fields: Partial<T | GettersDeep<T>>, |
| 47 | + options?: Partial<Options> |
| 48 | +) => Promise<void>; |
| 49 | + |
| 50 | +/** It's just Error */ |
| 51 | +class InnerError extends Error { |
| 52 | + innerError = true; |
| 53 | +} |
| 54 | + |
| 55 | +/** |
| 56 | + * modifies **original** JSON file |
| 57 | + * You can pass generic, that reflects the structure of original JSON file |
| 58 | + * |
| 59 | + * Fields, that are functions will be skipped if they're not preset in original JSON file |
| 60 | + */ |
| 61 | +export const modifyJsonFile: ModifyJsonFileGenericFunction = async ( |
| 62 | + path, |
| 63 | + fields, |
| 64 | + options |
| 65 | +) => { |
| 66 | + const { |
| 67 | + encoding = "utf-8", |
| 68 | + throws = true , |
| 69 | + ifFieldIsMissing = "throw", |
| 70 | + ifFieldIsMissingForSetter = "throw", |
| 71 | + tabSize: tabSizeOption = "preserve" |
| 72 | + } = options || {}; |
| 73 | + try { |
| 74 | + const json = await loadJsonFile(path); |
| 75 | + // todo remove restriction or not? |
| 76 | + if (!json || typeof json !== "object" || Array.isArray(json)) throw new TypeError(`${path}: JSON root type must be object`); |
| 77 | + // todo we don't need to read the file twice |
| 78 | + const rawText = await fs.promises.readFile(path, encoding); |
| 79 | + const indent = tabSizeOption === "preserve" ? detectIndent(rawText).indent : tabSizeOption === "hard" ? "\t" : tabSizeOption === null ? undefined : " ".repeat(tabSizeOption); |
| 80 | + |
| 81 | + for (const [name, value] of Object.entries(fields)) { |
| 82 | + if (!(name in json)) { |
| 83 | + const isSetter = typeof value === "function"; |
| 84 | + const generalAction = isSetter ? ifFieldIsMissingForSetter : ifFieldIsMissing; |
| 85 | + if (generalAction === "throw") throw new InnerError(`Property to modify "${name}" is missing in ${path}`); |
| 86 | + if (generalAction === "skip") continue; |
| 87 | + } |
| 88 | + json[name as string] = typeof value === "function" ? value(json[name as string], json) : value; |
| 89 | + } |
| 90 | + |
| 91 | + await fs.promises.writeFile( |
| 92 | + path, |
| 93 | + JSON.stringify(json, undefined, indent) |
| 94 | + ); |
| 95 | + } catch(err) { |
| 96 | + if (err.innerError) throw new Error(err.message); |
| 97 | + if (throws) throw err; |
| 98 | + } |
| 99 | +} |
| 100 | + |
| 101 | +// todo: use read-pkg / write-pkg for normalization |
| 102 | + |
| 103 | +/** |
| 104 | + * Almost the same is sindresorhus/write-pkg, but with proper typing support and setters for fields |
| 105 | + */ |
| 106 | +export const modifyPackageJson: ModifyJsonFileFunction<PackageJson> = modifyJsonFile; |
| 107 | + |
| 108 | +export const modifyTsConfigJson: ModifyJsonFileFunction<TsConfigJson> = modifyJsonFile; |
| 109 | + |
0 commit comments