/
stringify.ts
130 lines (119 loc) · 3.63 KB
/
stringify.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
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
import { Type } from '../constants.js'
import type { Document } from '../doc/Document.js'
import { isAlias, isNode, isPair, isScalar, Node } from '../nodes/Node.js'
import type { Scalar } from '../nodes/Scalar.js'
import type { ToStringOptions } from '../options.js'
import type { TagObj } from '../tags/types.js'
import { stringifyString } from './stringifyString.js'
export type StringifyContext = {
actualString?: boolean
allNullValues?: boolean
anchors: Record<string, Node>
doc: Document
forceBlockIndent?: boolean
implicitKey?: boolean
indent: string
indentStep: string
indentAtStart?: number
inFlow?: boolean
inStringifyKey?: boolean
options: Readonly<Required<Omit<ToStringOptions, 'indent'>>>
}
export const createStringifyContext = (
doc: Document,
options: ToStringOptions
): StringifyContext => ({
anchors: Object.create(null),
doc,
indent: '',
indentStep:
typeof options.indent === 'number' ? ' '.repeat(options.indent) : ' ',
options: Object.assign(
{
defaultKeyType: null,
defaultStringType: Type.PLAIN,
directives: null,
doubleQuotedAsJSON: false,
doubleQuotedMinMultiLineLength: 40,
falseStr: 'false',
indentSeq: true,
lineWidth: 80,
minContentWidth: 20,
nullStr: 'null',
simpleKeys: false,
singleQuote: false,
trueStr: 'true'
},
options
)
})
function getTagObject(tags: TagObj[], item: Node) {
if (item.tag) {
const match = tags.filter(t => t.tag === item.tag)
if (match.length > 0)
return match.find(t => t.format === (item as Scalar).format) || match[0]
}
let tagObj: TagObj | undefined = undefined
let obj: unknown
if (isScalar(item)) {
obj = item.value
const match = tags.filter(t => t.identify && t.identify(obj))
tagObj =
match.find(t => t.format === item.format) || match.find(t => !t.format)
} else {
obj = item
tagObj = tags.find(t => t.nodeClass && obj instanceof t.nodeClass)
}
if (!tagObj) {
// @ts-ignore
const name = obj && obj.constructor ? obj.constructor.name : typeof obj
throw new Error(`Tag not resolved for ${name} value`)
}
return tagObj
}
// needs to be called before value stringifier to allow for circular anchor refs
function stringifyProps(
node: Node,
tagObj: TagObj,
{ anchors, doc }: StringifyContext
) {
const props = []
const anchor = doc.anchors.getName(node)
if (anchor) {
anchors[anchor] = node
props.push(`&${anchor}`)
}
if (node.tag) {
props.push(doc.directives.tagString(node.tag))
} else if (!tagObj.default) {
props.push(doc.directives.tagString(tagObj.tag))
}
return props.join(' ')
}
export function stringify(
item: unknown,
ctx: StringifyContext,
onComment?: () => void,
onChompKeep?: () => void
): string {
if (isPair(item)) return item.toString(ctx, onComment, onChompKeep)
if (isAlias(item)) return item.toString(ctx)
let tagObj: TagObj | undefined = undefined
const node = isNode(item)
? item
: ctx.doc.createNode(item, { onTagObj: o => (tagObj = o) })
if (!tagObj) tagObj = getTagObject(ctx.doc.schema.tags, node)
const props = stringifyProps(node, tagObj, ctx)
if (props.length > 0)
ctx.indentAtStart = (ctx.indentAtStart || 0) + props.length + 1
const str =
typeof tagObj.stringify === 'function'
? tagObj.stringify(node as Scalar, ctx, onComment, onChompKeep)
: isScalar(node)
? stringifyString(node, ctx, onComment, onChompKeep)
: node.toString(ctx, onComment, onChompKeep)
if (!props) return str
return isScalar(node) || str[0] === '{' || str[0] === '['
? `${props} ${str}`
: `${props}\n${ctx.indent}${str}`
}