0
# AST Nodes
1
2
Direct manipulation of YAML Abstract Syntax Tree nodes including scalars, collections, aliases, and pairs. This provides fine-grained control over YAML document structure and enables programmatic document generation and modification.
3
4
## Capabilities
5
6
### Scalar Nodes
7
8
Scalar nodes represent individual values (strings, numbers, booleans, null, etc.) with complete control over formatting and type representation.
9
10
```typescript { .api }
11
class Scalar<T = unknown> {
12
/** Scalar value */
13
value: T;
14
15
/** Node type identifier */
16
type?: 'BLOCK_FOLDED' | 'BLOCK_LITERAL' | 'PLAIN' | 'QUOTE_DOUBLE' | 'QUOTE_SINGLE';
17
18
/** Comment after the scalar */
19
comment?: string | null;
20
21
/** Comment before the scalar */
22
commentBefore?: string | null;
23
24
/** Spacing before the node */
25
spaceBefore?: boolean;
26
27
/** Source range information */
28
range?: Range;
29
30
/** Anchor name if present */
31
anchor?: string | null;
32
33
/** Tag information */
34
tag?: string | null;
35
36
/** Format settings */
37
format?: 'BIN' | 'HEX' | 'OCT' | 'TIME' | string;
38
39
/** Minimum number of fractional digits for numbers */
40
minFractionDigits?: number;
41
42
/**
43
* Create scalar node
44
* @param value - Scalar value
45
*/
46
constructor(value: T);
47
48
/** Convert to JSON representation */
49
toJSON(): any;
50
51
/** Convert to YAML string */
52
toString(): string;
53
54
// Static formatting constants
55
static readonly BLOCK_FOLDED: 'BLOCK_FOLDED';
56
static readonly BLOCK_LITERAL: 'BLOCK_LITERAL';
57
static readonly PLAIN: 'PLAIN';
58
static readonly QUOTE_DOUBLE: 'QUOTE_DOUBLE';
59
static readonly QUOTE_SINGLE: 'QUOTE_SINGLE';
60
}
61
```
62
63
**Usage Examples:**
64
65
```typescript
66
import { Scalar } from "yaml";
67
68
// Basic scalar creation
69
const stringScalar = new Scalar("Hello World");
70
const numberScalar = new Scalar(42);
71
const booleanScalar = new Scalar(true);
72
73
// Formatted scalars
74
const multilineScalar = new Scalar("Line 1\nLine 2\nLine 3");
75
multilineScalar.type = Scalar.BLOCK_LITERAL;
76
77
const quotedScalar = new Scalar("Text with spaces");
78
quotedScalar.type = Scalar.QUOTE_DOUBLE;
79
80
// With comments
81
const commentedScalar = new Scalar(100);
82
commentedScalar.comment = " Maximum value";
83
commentedScalar.commentBefore = " Configuration setting";
84
85
// With anchors and tags
86
const anchoredScalar = new Scalar("shared-value");
87
anchoredScalar.anchor = "shared";
88
anchoredScalar.tag = "!!str";
89
90
console.log(commentedScalar.toString());
91
// # Configuration setting
92
// 100 # Maximum value
93
```
94
95
### Map Collections
96
97
YAMLMap represents mapping collections (objects) with key-value pairs and comprehensive manipulation methods.
98
99
```typescript { .api }
100
class YAMLMap<K = unknown, V = unknown> extends Collection {
101
/** Map items as array of pairs */
102
items: Pair<K, V>[];
103
104
/** Collection flow style */
105
flow?: boolean;
106
107
/** Comment after the collection */
108
comment?: string | null;
109
110
/** Comment before the collection */
111
commentBefore?: string | null;
112
113
/** Spacing before the node */
114
spaceBefore?: boolean;
115
116
/** Tag name for this collection type */
117
static readonly tagName: '!!map';
118
119
/**
120
* Create YAMLMap from object
121
* @param schema - Schema to use
122
* @param obj - Object to convert
123
* @param ctx - Creation context
124
* @returns YAMLMap instance
125
*/
126
static from(schema: Schema, obj: unknown, ctx: CreateNodeContext): YAMLMap;
127
128
/**
129
* Create empty map
130
* @param schema - Schema to use
131
*/
132
constructor(schema?: Schema);
133
134
/**
135
* Add key-value pair to map
136
* @param pair - Pair to add or plain object
137
* @param overwrite - Whether to overwrite existing keys
138
*/
139
add(pair: Pair | { key: any; value: any }, overwrite?: boolean): void;
140
141
/**
142
* Delete key from map
143
* @param key - Key to delete
144
* @returns True if key was deleted
145
*/
146
delete(key: unknown): boolean;
147
148
/**
149
* Get value for key
150
* @param key - Key to retrieve
151
* @param keepScalar - Keep scalar nodes instead of values
152
* @returns Value for key
153
*/
154
get(key: unknown, keepScalar?: boolean): unknown;
155
156
/**
157
* Check if map has key
158
* @param key - Key to check
159
* @returns True if key exists
160
*/
161
has(key: unknown): boolean;
162
163
/**
164
* Set value for key
165
* @param key - Key to set
166
* @param value - Value to set
167
*/
168
set(key: any, value: any): void;
169
170
/** Convert to JSON object */
171
toJSON(): any;
172
173
/** Convert to YAML string */
174
toString(): string;
175
}
176
```
177
178
**Usage Examples:**
179
180
```typescript
181
import { YAMLMap, Scalar, Pair } from "yaml";
182
183
// Create empty map
184
const map = new YAMLMap();
185
186
// Add key-value pairs
187
map.add({ key: 'name', value: 'John Doe' });
188
map.add({ key: 'age', value: 30 });
189
map.add({ key: 'active', value: true });
190
191
// Using Pair objects
192
const emailPair = new Pair('email', 'john@example.com');
193
emailPair.comment = ' Contact information';
194
map.add(emailPair);
195
196
// Set values directly
197
map.set('location', 'New York');
198
map.set('skills', ['JavaScript', 'TypeScript', 'Node.js']);
199
200
// Access values
201
console.log(map.get('name')); // 'John Doe'
202
console.log(map.has('email')); // true
203
204
// Flow style
205
map.flow = true; // Use flow notation: {key: value, ...}
206
207
console.log(map.toString());
208
```
209
210
### Sequence Collections
211
212
YAMLSeq represents sequence collections (arrays) with indexed access and manipulation methods.
213
214
```typescript { .api }
215
class YAMLSeq<T = unknown> extends Collection {
216
/** Sequence items */
217
items: T[];
218
219
/** Collection flow style */
220
flow?: boolean;
221
222
/** Comment after the collection */
223
comment?: string | null;
224
225
/** Comment before the collection */
226
commentBefore?: string | null;
227
228
/** Spacing before the node */
229
spaceBefore?: boolean;
230
231
/** Tag name for this collection type */
232
static readonly tagName: '!!seq';
233
234
/**
235
* Create YAMLSeq from array
236
* @param schema - Schema to use
237
* @param obj - Array to convert
238
* @param ctx - Creation context
239
* @returns YAMLSeq instance
240
*/
241
static from(schema: Schema, obj: unknown, ctx: CreateNodeContext): YAMLSeq;
242
243
/**
244
* Create empty sequence
245
* @param schema - Schema to use
246
*/
247
constructor(schema?: Schema);
248
249
/**
250
* Add value to sequence
251
* @param value - Value to add
252
* @returns Index of added item
253
*/
254
add(value: T): number;
255
256
/**
257
* Delete item at index
258
* @param index - Index to delete
259
* @returns True if item was deleted
260
*/
261
delete(index: number): boolean;
262
263
/**
264
* Get item at index
265
* @param index - Index to retrieve
266
* @param keepScalar - Keep scalar nodes instead of values
267
* @returns Item at index
268
*/
269
get(index: number, keepScalar?: boolean): unknown;
270
271
/**
272
* Check if sequence has item at index
273
* @param index - Index to check
274
* @returns True if index exists
275
*/
276
has(index: number): boolean;
277
278
/**
279
* Set item at index
280
* @param index - Index to set
281
* @param value - Value to set
282
*/
283
set(index: number, value: T): void;
284
285
/** Convert to JSON array */
286
toJSON(): any;
287
288
/** Convert to YAML string */
289
toString(): string;
290
}
291
```
292
293
**Usage Examples:**
294
295
```typescript
296
import { YAMLSeq, Scalar } from "yaml";
297
298
// Create sequence
299
const seq = new YAMLSeq();
300
301
// Add items
302
seq.add('item1');
303
seq.add('item2');
304
seq.add(42);
305
seq.add(true);
306
307
// Add complex items
308
const nestedMap = new YAMLMap();
309
nestedMap.set('nested', 'value');
310
seq.add(nestedMap);
311
312
// Access items
313
console.log(seq.get(0)); // 'item1'
314
console.log(seq.has(2)); // true
315
316
// Modify items
317
seq.set(1, 'modified-item2');
318
seq.delete(3); // Remove boolean
319
320
// Flow style
321
seq.flow = true; // Use flow notation: [item1, item2, ...]
322
323
console.log(seq.toString());
324
```
325
326
### Pair Nodes
327
328
Pair nodes represent key-value relationships within maps and provide metadata for comments and spacing.
329
330
```typescript { .api }
331
class Pair<K = unknown, V = unknown> {
332
/** Pair key */
333
key: K;
334
335
/** Pair value */
336
value: V;
337
338
/** Comment after the pair */
339
comment?: string | null;
340
341
/** Comment before the pair */
342
commentBefore?: string | null;
343
344
/** Spacing before the pair */
345
spaceBefore?: boolean;
346
347
/** Source range information */
348
range?: Range;
349
350
/**
351
* Create key-value pair
352
* @param key - Key for the pair
353
* @param value - Value for the pair
354
*/
355
constructor(key: K, value?: V);
356
357
/** Create deep clone of pair */
358
clone(): Pair<K, V>;
359
360
/** Convert to JSON representation */
361
toJSON(): { key: any; value: any };
362
363
/** Convert to YAML string */
364
toString(): string;
365
}
366
```
367
368
### Alias Nodes
369
370
Alias nodes represent references to other nodes using YAML anchors and aliases.
371
372
```typescript { .api }
373
class Alias {
374
/** Source node being referenced */
375
source: Node;
376
377
/** Comment after the alias */
378
comment?: string | null;
379
380
/** Comment before the alias */
381
commentBefore?: string | null;
382
383
/** Spacing before the alias */
384
spaceBefore?: boolean;
385
386
/** Source range information */
387
range?: Range;
388
389
/**
390
* Create alias node
391
* @param source - Node to reference
392
*/
393
constructor(source: Node);
394
395
/**
396
* Resolve alias to its target value
397
* @param doc - Document context
398
* @returns Resolved value
399
*/
400
resolve(doc: Document): unknown;
401
402
/** Convert to JSON (resolves to source value) */
403
toJSON(_arg?: unknown, ctx?: ToJSContext): unknown;
404
405
/** Convert to YAML string */
406
toString(): string;
407
}
408
```
409
410
**Usage Examples:**
411
412
```typescript
413
import { parseDocument, Alias } from "yaml";
414
415
// Create document with anchored node
416
const doc = parseDocument(`
417
defaults: &defaults
418
timeout: 30
419
retries: 3
420
421
production:
422
<<: *defaults
423
host: prod.example.com
424
425
staging:
426
<<: *defaults
427
host: staging.example.com
428
`);
429
430
// Create new alias programmatically
431
const defaultsNode = doc.get(['defaults'], true);
432
if (defaultsNode) {
433
const alias = new Alias(defaultsNode);
434
doc.set(['development'], alias);
435
}
436
437
console.log(doc.toString());
438
```
439
440
## Collection Base Class
441
442
```typescript { .api }
443
abstract class Collection {
444
/** Collection items */
445
items: unknown[];
446
447
/** Collection schema */
448
schema?: Schema;
449
450
/** Collection flow style */
451
flow?: boolean;
452
453
/** Comment after the collection */
454
comment?: string | null;
455
456
/** Comment before the collection */
457
commentBefore?: string | null;
458
459
/** Spacing before the collection */
460
spaceBefore?: boolean;
461
462
/** Source range information */
463
range?: Range;
464
465
/** Anchor name if present */
466
anchor?: string | null;
467
468
/** Tag information */
469
tag?: string | null;
470
471
/** Convert to JSON representation */
472
abstract toJSON(): any;
473
474
/** Convert to YAML string */
475
abstract toString(): string;
476
}
477
```
478
479
## Common Node Types
480
481
```typescript { .api }
482
type Node = Alias | Scalar | YAMLMap | YAMLSeq;
483
type ParsedNode = Alias | Scalar<any> | YAMLMap<any, any> | YAMLSeq<any>;
484
type Collection = YAMLMap | YAMLSeq;
485
486
type Range = [start: number, valueEnd: number, nodeEnd: number];
487
488
interface CreateNodeContext {
489
/** Node creation options */
490
options: CreateNodeOptions;
491
/** Document schema */
492
schema: Schema;
493
}
494
```