/
Document.ts
458 lines (420 loc) · 14 KB
/
Document.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
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
import type { YAMLError, YAMLWarning } from '../errors.js'
import { Alias } from '../nodes/Alias.js'
import { collectionFromPath, isEmptyPath } from '../nodes/Collection.js'
import {
DOC,
isCollection,
isNode,
isScalar,
Node,
NODE_TYPE,
ParsedNode,
Range
} from '../nodes/Node.js'
import { Pair } from '../nodes/Pair.js'
import type { Scalar } from '../nodes/Scalar.js'
import { toJS, ToJSContext } from '../nodes/toJS.js'
import type { YAMLMap } from '../nodes/YAMLMap.js'
import type { YAMLSeq } from '../nodes/YAMLSeq.js'
import type {
CreateNodeOptions,
DocumentOptions,
ParseOptions,
SchemaOptions,
ToJSOptions,
ToStringOptions
} from '../options.js'
import { Schema } from '../schema/Schema.js'
import { stringify } from '../stringify/stringify.js'
import { stringifyDocument } from '../stringify/stringifyDocument.js'
import { anchorNames, createNodeAnchors, findNewAnchor } from './anchors.js'
import { applyReviver } from './applyReviver.js'
import { createNode, CreateNodeContext } from './createNode.js'
import { Directives } from './directives.js'
export type Replacer = any[] | ((key: any, value: any) => unknown)
export declare namespace Document {
interface Parsed<T extends ParsedNode = ParsedNode> extends Document<T> {
directives: Directives
range: Range
}
}
export class Document<T = unknown> {
readonly [NODE_TYPE]: symbol
/** A comment before this Document */
commentBefore: string | null = null
/** A comment immediately after this Document */
comment: string | null = null
/** The document contents. */
contents: T | null
directives?: Directives
/** Errors encountered during parsing. */
errors: YAMLError[] = []
options: Required<
Omit<
ParseOptions & DocumentOptions,
'lineCounter' | 'directives' | 'version'
>
>
/**
* The `[start, value-end, node-end]` character offsets for the part of the
* source parsed into this document (undefined if not parsed). The `value-end`
* and `node-end` positions are themselves not included in their respective
* ranges.
*/
declare range?: Range
// TS can't figure out that setSchema() will set this, or throw
/** The schema used with the document. Use `setSchema()` to change. */
declare schema: Schema
/** Warnings encountered during parsing. */
warnings: YAMLWarning[] = []
/**
* @param value - The initial value for the document, which will be wrapped
* in a Node container.
*/
constructor(
value?: any,
options?: DocumentOptions & SchemaOptions & ParseOptions & CreateNodeOptions
)
constructor(
value: any,
replacer: null | Replacer,
options?: DocumentOptions & SchemaOptions & ParseOptions & CreateNodeOptions
)
constructor(
value?: unknown,
replacer?:
| Replacer
| (DocumentOptions & SchemaOptions & ParseOptions & CreateNodeOptions)
| null,
options?: DocumentOptions & SchemaOptions & ParseOptions & CreateNodeOptions
) {
Object.defineProperty(this, NODE_TYPE, { value: DOC })
let _replacer: Replacer | null = null
if (typeof replacer === 'function' || Array.isArray(replacer)) {
_replacer = replacer
} else if (options === undefined && replacer) {
options = replacer
replacer = undefined
}
const opt = Object.assign(
{
intAsBigInt: false,
keepSourceTokens: false,
logLevel: 'warn',
prettyErrors: true,
strict: true,
uniqueKeys: true,
version: '1.2'
},
options
)
this.options = opt
let { version } = opt
if (options?.directives) {
this.directives = options.directives.atDocument()
if (this.directives.yaml.explicit) version = this.directives.yaml.version
} else this.directives = new Directives({ version })
this.setSchema(version, options)
if (value === undefined) this.contents = null
else {
this.contents = this.createNode(value, _replacer, options) as unknown as T
}
}
/**
* Create a deep copy of this Document and its contents.
*
* Custom Node values that inherit from `Object` still refer to their original instances.
*/
clone(): Document<T> {
const copy: Document<T> = Object.create(Document.prototype, {
[NODE_TYPE]: { value: DOC }
})
copy.commentBefore = this.commentBefore
copy.comment = this.comment
copy.errors = this.errors.slice()
copy.warnings = this.warnings.slice()
copy.options = Object.assign({}, this.options)
if (this.directives) copy.directives = this.directives.clone()
copy.schema = this.schema.clone()
copy.contents = isNode(this.contents)
? (this.contents.clone(copy.schema) as unknown as T)
: this.contents
if (this.range) copy.range = this.range.slice() as Document['range']
return copy
}
/** Adds a value to the document. */
add(value: any) {
if (assertCollection(this.contents)) this.contents.add(value)
}
/** Adds a value to the document. */
addIn(path: Iterable<unknown>, value: unknown) {
if (assertCollection(this.contents)) this.contents.addIn(path, value)
}
/**
* Create a new `Alias` node, ensuring that the target `node` has the required anchor.
*
* If `node` already has an anchor, `name` is ignored.
* Otherwise, the `node.anchor` value will be set to `name`,
* or if an anchor with that name is already present in the document,
* `name` will be used as a prefix for a new unique anchor.
* If `name` is undefined, the generated anchor will use 'a' as a prefix.
*/
createAlias(node: Scalar | YAMLMap | YAMLSeq, name?: string): Alias {
if (!node.anchor) {
const prev = anchorNames(this)
node.anchor =
!name || prev.has(name) ? findNewAnchor(name || 'a', prev) : name
}
return new Alias(node.anchor)
}
/**
* Convert any value into a `Node` using the current schema, recursively
* turning objects into collections.
*/
createNode(value: unknown, options?: CreateNodeOptions): Node
createNode(
value: unknown,
replacer: Replacer | CreateNodeOptions | null,
options?: CreateNodeOptions
): Node
createNode(
value: unknown,
replacer?: Replacer | CreateNodeOptions | null,
options?: CreateNodeOptions
): Node {
let _replacer: Replacer | undefined = undefined
if (typeof replacer === 'function') {
value = replacer.call({ '': value }, '', value)
_replacer = replacer
} else if (Array.isArray(replacer)) {
const keyToStr = (v: unknown) =>
typeof v === 'number' || v instanceof String || v instanceof Number
const asStr = replacer.filter(keyToStr).map(String)
if (asStr.length > 0) replacer = replacer.concat(asStr)
_replacer = replacer
} else if (options === undefined && replacer) {
options = replacer
replacer = undefined
}
const {
aliasDuplicateObjects,
anchorPrefix,
flow,
keepUndefined,
onTagObj,
tag
} = options || {}
const { onAnchor, setAnchors, sourceObjects } = createNodeAnchors(
this,
anchorPrefix || 'a'
)
const ctx: CreateNodeContext = {
aliasDuplicateObjects: aliasDuplicateObjects ?? true,
keepUndefined: keepUndefined ?? false,
onAnchor,
onTagObj,
replacer: _replacer,
schema: this.schema,
sourceObjects
}
const node = createNode(value, tag, ctx)
if (flow && isCollection(node)) node.flow = true
setAnchors()
return node
}
/**
* Convert a key and a value into a `Pair` using the current schema,
* recursively wrapping all values as `Scalar` or `Collection` nodes.
*/
createPair<K extends Node = Node, V extends Node = Node>(
key: unknown,
value: unknown,
options: CreateNodeOptions = {}
) {
const k = this.createNode(key, null, options) as K
const v = this.createNode(value, null, options) as V
return new Pair(k, v)
}
/**
* Removes a value from the document.
* @returns `true` if the item was found and removed.
*/
delete(key: any) {
return assertCollection(this.contents) ? this.contents.delete(key) : false
}
/**
* Removes a value from the document.
* @returns `true` if the item was found and removed.
*/
deleteIn(path: Iterable<unknown>) {
if (isEmptyPath(path)) {
if (this.contents == null) return false
this.contents = null
return true
}
return assertCollection(this.contents)
? this.contents.deleteIn(path)
: false
}
/**
* Returns item at `key`, or `undefined` if not found. By default unwraps
* scalar values from their surrounding node; to disable set `keepScalar` to
* `true` (collections are always returned intact).
*/
get(key: unknown, keepScalar?: boolean) {
return isCollection(this.contents)
? this.contents.get(key, keepScalar)
: undefined
}
/**
* Returns item at `path`, or `undefined` if not found. By default unwraps
* scalar values from their surrounding node; to disable set `keepScalar` to
* `true` (collections are always returned intact).
*/
getIn(path: Iterable<unknown>, keepScalar?: boolean) {
if (isEmptyPath(path))
return !keepScalar && isScalar(this.contents)
? this.contents.value
: this.contents
return isCollection(this.contents)
? this.contents.getIn(path, keepScalar)
: undefined
}
/**
* Checks if the document includes a value with the key `key`.
*/
has(key: unknown) {
return isCollection(this.contents) ? this.contents.has(key) : false
}
/**
* Checks if the document includes a value at `path`.
*/
hasIn(path: Iterable<unknown>) {
if (isEmptyPath(path)) return this.contents !== undefined
return isCollection(this.contents) ? this.contents.hasIn(path) : false
}
/**
* Sets a value in this document. For `!!set`, `value` needs to be a
* boolean to add/remove the item from the set.
*/
set(key: any, value: unknown) {
if (this.contents == null) {
this.contents = collectionFromPath(
this.schema,
[key],
value
) as unknown as T
} else if (assertCollection(this.contents)) {
this.contents.set(key, value)
}
}
/**
* Sets a value in this document. For `!!set`, `value` needs to be a
* boolean to add/remove the item from the set.
*/
setIn(path: Iterable<unknown>, value: unknown) {
if (isEmptyPath(path)) this.contents = value as unknown as T
else if (this.contents == null) {
this.contents = collectionFromPath(
this.schema,
Array.from(path),
value
) as unknown as T
} else if (assertCollection(this.contents)) {
this.contents.setIn(path, value)
}
}
/**
* Change the YAML version and schema used by the document.
* A `null` version disables support for directives, explicit tags, anchors, and aliases.
* It also requires the `schema` option to be given as a `Schema` instance value.
*
* Overrides all previously set schema options.
*/
setSchema(version: '1.1' | '1.2' | null, options: SchemaOptions = {}) {
if (typeof version === 'number') version = String(version) as '1.1' | '1.2'
let opt: (SchemaOptions & { schema: string }) | null
switch (version) {
case '1.1':
if (this.directives) this.directives.yaml.version = '1.1'
else this.directives = new Directives({ version: '1.1' })
opt = { merge: true, resolveKnownTags: false, schema: 'yaml-1.1' }
break
case '1.2':
if (this.directives) this.directives.yaml.version = '1.2'
else this.directives = new Directives({ version: '1.2' })
opt = { merge: false, resolveKnownTags: true, schema: 'core' }
break
case null:
if (this.directives) delete this.directives
opt = null
break
default: {
const sv = JSON.stringify(version)
throw new Error(
`Expected '1.1', '1.2' or null as first argument, but found: ${sv}`
)
}
}
// Not using `instanceof Schema` to allow for duck typing
if (options.schema instanceof Object) this.schema = options.schema
else if (opt) this.schema = new Schema(Object.assign(opt, options))
else
throw new Error(
`With a null YAML version, the { schema: Schema } option is required`
)
}
/** A plain JavaScript representation of the document `contents`. */
toJS(opt?: ToJSOptions & { [ignored: string]: unknown }): any
// json & jsonArg are only used from toJSON()
toJS({
json,
jsonArg,
mapAsMap,
maxAliasCount,
onAnchor,
reviver
}: ToJSOptions & { json?: boolean; jsonArg?: string | null } = {}) {
const ctx: ToJSContext = {
anchors: new Map(),
doc: this,
keep: !json,
mapAsMap: mapAsMap === true,
mapKeyWarned: false,
maxAliasCount: typeof maxAliasCount === 'number' ? maxAliasCount : 100,
stringify
}
const res = toJS(this.contents, jsonArg || '', ctx)
if (typeof onAnchor === 'function')
for (const { count, res } of ctx.anchors.values()) onAnchor(res, count)
return typeof reviver === 'function'
? applyReviver(reviver, { '': res }, '', res)
: res
}
/**
* A JSON representation of the document `contents`.
*
* @param jsonArg Used by `JSON.stringify` to indicate the array index or
* property name.
*/
toJSON(jsonArg?: string | null, onAnchor?: ToJSOptions['onAnchor']) {
return this.toJS({ json: true, jsonArg, mapAsMap: false, onAnchor })
}
/** A YAML representation of the document. */
toString(options: ToStringOptions = {}): string {
if (this.errors.length > 0)
throw new Error('Document with errors cannot be stringified')
if (
'indent' in options &&
(!Number.isInteger(options.indent) || Number(options.indent) <= 0)
) {
const s = JSON.stringify(options.indent)
throw new Error(`"indent" option must be a positive integer, not ${s}`)
}
return stringifyDocument(this, options)
}
}
function assertCollection(contents: unknown): contents is YAMLMap | YAMLSeq {
if (isCollection(contents)) return true
throw new Error('Expected a YAML collection as document contents')
}