-
-
Notifications
You must be signed in to change notification settings - Fork 93
Expand file tree
/
Copy pathserialize.ts
More file actions
67 lines (56 loc) · 1.72 KB
/
serialize.ts
File metadata and controls
67 lines (56 loc) · 1.72 KB
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
// From https://github.com/nodeca/js-yaml/issues/586#issuecomment-814310104
// This file ensures that simple objects and arrays (ie without array or object
// children) will be serialized inline, and also ensures that "fullTargets" will be inlined as well
import * as yaml from "js-yaml";
class CustomDump {
constructor(
private readonly data: unknown,
private readonly opts: yaml.DumpOptions,
) {}
represent(): string {
let result = yaml.dump(
this.data,
Object.assign({ replacer, schema }, this.opts),
);
result = result.trim();
if (result.includes("\n")) {
result = "\n" + result;
}
return result;
}
}
const customDumpType = new yaml.Type("!format", {
kind: "scalar",
resolve: () => false,
instanceOf: CustomDump,
represent: (d: unknown) => (d as CustomDump).represent(),
});
const schema = yaml.DEFAULT_SCHEMA.extend({ implicit: [customDumpType] });
const isObject = (value: unknown): value is object =>
typeof value === "object" && value != null;
function hasSimpleChildren(value: unknown): boolean {
if (isObject(value)) {
return Object.values(value).every(
(value) => !isObject(value) && !Array.isArray(value),
);
}
if (Array.isArray(value)) {
return value.every((value) => !isObject(value) && !Array.isArray(value));
}
return false;
}
function replacer(key: string, value: unknown): unknown {
if (key === "") {
return value;
} // top-level, don't change this
if (hasSimpleChildren(value)) {
return new CustomDump(value, { flowLevel: 0 });
}
return value; // default
}
export function serialize(obj: unknown): string {
return (
new CustomDump(obj, { noRefs: true, quotingType: '"' }).represent().trim() +
"\n"
);
}