-
Notifications
You must be signed in to change notification settings - Fork 0
/
mod.ts
111 lines (95 loc) · 2.34 KB
/
mod.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
const KEY_ORDER = [
"name",
"private",
"version",
"description",
"keywords",
"engines",
"os",
"type",
"browser",
"main",
"module",
"svelte",
"types",
"bin",
"files",
"homepage",
"bugs",
"repository",
"author",
"contributors",
"funding",
"license",
"scripts",
"dependencies",
"devDependencies",
"bundledDependencies",
"optionalDependencies",
"peerDependencies",
"publishConfig",
"config",
"workspaces",
];
const SORTABLE_STR_KEY = ["files", "keywords"];
const SORTABLE_OBJ_KEY = [
"engines",
"publishConfig",
"repository",
"scripts",
"dependencies",
"devDependencies",
"peerDependencies",
"bundledDependencies",
"optionalDependencies",
];
type ObjectValue = {
// deno-lint-ignore no-explicit-any
[key: string]: any;
};
export default function nicePackageJson(originalPackage: ObjectValue) {
const pkg = { ...originalPackage };
const formatted: ObjectValue = {};
for (const key of KEY_ORDER) {
const pkgValue = pkg[key];
if (pkgValue === undefined) continue;
delete pkg[key];
if (SORTABLE_STR_KEY.includes(key) && Array.isArray(pkgValue)) {
formatted[key] = pkgValue.sort();
} else if (SORTABLE_OBJ_KEY.includes(key)) {
if (typeof pkgValue === "string") {
formatted[key] = pkgValue;
continue;
} else if (isObject(pkgValue)) {
const sortedObj: ObjectValue = {};
assignAlphabetically(pkgValue, sortedObj);
formatted[key] = sortedObj;
}
} else if (key === "contributors" && Array.isArray(pkgValue)) {
formatted[key] = pkgValue.sort(byContributorName);
} else {
formatted[key] = pkgValue;
}
}
assignAlphabetically(pkg, formatted);
return createJsonString(formatted);
}
function assignAlphabetically(source: ObjectValue, target: ObjectValue): void {
Object.keys(source)
.sort()
.forEach((k) => {
target[k] = source[k];
});
}
// deno-lint-ignore no-explicit-any
function byContributorName(a: any, b: any): number {
const valueA = isObject(a) ? a.name : a;
const valueB = isObject(b) ? b.name : b;
return valueA > valueB ? 1 : -1;
}
function createJsonString(obj: ObjectValue): string {
return `${JSON.stringify(obj, null, " ")}\n`;
}
function isObject(val: unknown): val is ObjectValue {
return Object.prototype.toString.call(val) === "[object Object]";
}