@intellectual-frontiers/formats 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +8 -2
  3. package/dist/archive.d.ts +147 -0
  4. package/dist/archive.js +765 -0
  5. package/dist/base64.d.ts +24 -0
  6. package/dist/base64.js +52 -0
  7. package/dist/cbor.d.ts +39 -0
  8. package/dist/cbor.js +244 -0
  9. package/dist/csv.d.ts +38 -0
  10. package/dist/csv.js +130 -0
  11. package/dist/der.d.ts +67 -0
  12. package/dist/der.js +221 -0
  13. package/dist/glob.d.ts +64 -0
  14. package/dist/glob.js +218 -0
  15. package/dist/hex.d.ts +17 -0
  16. package/dist/hex.js +30 -0
  17. package/dist/http.d.ts +46 -0
  18. package/dist/http.js +102 -0
  19. package/dist/json5.d.ts +46 -0
  20. package/dist/json5.js +291 -0
  21. package/dist/media-types.d.ts +28 -0
  22. package/dist/media-types.js +121 -0
  23. package/dist/mod.d.ts +39 -0
  24. package/dist/mod.js +31 -0
  25. package/dist/png.d.ts +124 -0
  26. package/dist/png.js +607 -0
  27. package/dist/semver.d.ts +94 -0
  28. package/dist/semver.js +331 -0
  29. package/dist/toml.d.ts +51 -0
  30. package/dist/toml.js +583 -0
  31. package/dist/ts-literal.d.ts +62 -0
  32. package/dist/ts-literal.js +173 -0
  33. package/dist/xml.d.ts +73 -0
  34. package/dist/xml.js +282 -0
  35. package/dist/yaml.d.ts +44 -0
  36. package/dist/yaml.js +706 -0
  37. package/package.json +118 -4
  38. package/src/archive.ts +831 -0
  39. package/src/base64.ts +51 -0
  40. package/src/cbor.ts +235 -0
  41. package/src/csv.ts +132 -0
  42. package/src/der.ts +224 -0
  43. package/src/glob.ts +210 -0
  44. package/src/hex.ts +28 -0
  45. package/src/http.ts +104 -0
  46. package/src/json5.ts +267 -0
  47. package/src/media-types.ts +127 -0
  48. package/src/mod.ts +102 -0
  49. package/src/png.ts +625 -0
  50. package/src/semver.ts +373 -0
  51. package/src/toml.ts +525 -0
  52. package/src/ts-literal.ts +183 -0
  53. package/src/xml.ts +291 -0
  54. package/src/yaml.ts +616 -0
package/src/yaml.ts ADDED
@@ -0,0 +1,616 @@
1
+ // Spec: 0001-formats FR-002
2
+ /**
3
+ * YAML 1.2 for data (commons 0001-formats FR-002), read and written with no outside package. The reader takes what data files,
4
+ * front matter and configuration use: block mappings and sequences (a sequence may sit at its key's indentation, and a mapping may begin
5
+ * on a sequence's dash), flow collections over several lines, plain scalars folded over several lines, single- and double-quoted scalars
6
+ * with every escape of YAML 1.2, literal and folded block scalars with their chomping and indentation indicators, comments and one
7
+ * document between `---` and `...`. Plain scalars resolve by the core schema (null, booleans, integers in decimal, octal and hexadecimal,
8
+ * floats with `.inf` and `.nan`) or, with the failsafe schema, stay text. It refuses, with the line and column and the reason, what makes
9
+ * data ambiguous or unsafe to read: anchors and aliases (and so no "billion laughs"), tags, complex keys, directives, more than one
10
+ * document, a key given twice and a tab used for indentation. The writer gives block YAML that the reader reads back as the same value.
11
+ * Replaces `@std/yaml` in erga.
12
+ *
13
+ * @example
14
+ * ```ts
15
+ * import { parseYaml, toYaml } from "./yaml.ts";
16
+ * parseYaml("name: skill\ntags: [a, b]\nsteps:\n - run: build\n times: 2\n");
17
+ * // { kind: "ok", value: { name: "skill", tags: ["a", "b"], steps: [{ run: "build", times: 2 }] } }
18
+ * toYaml({ name: "skill", on: true }); // "name: skill\non: true\n" (YAML 1.2: "on" is only text)
19
+ * ```
20
+ *
21
+ * @module
22
+ */
23
+ import type { Json } from "./json5.ts";
24
+ import { err, ok, type Result } from "@intellectual-frontiers/core";
25
+
26
+ /** Where a text stops being YAML this reader takes, and why. Lines and columns count from 1. */
27
+ export type YamlError = { readonly kind: "yaml"; readonly line: number; readonly column: number; readonly message: string };
28
+
29
+ /** A YAML error as one line: `3:14: anchors and aliases are not read`. */
30
+ export function formatYamlError(e: YamlError): string {
31
+ return `${e.line}:${e.column}: ${e.message}`;
32
+ }
33
+
34
+ /** How plain scalars resolve: by YAML 1.2's core schema (the default), or all as text (failsafe). */
35
+ export type YamlOptions = { readonly schema?: "core" | "failsafe" };
36
+
37
+ class Stop extends Error {
38
+ readonly at: number;
39
+ constructor(at: number, message: string) {
40
+ super(message);
41
+ this.at = at;
42
+ }
43
+ }
44
+
45
+ const NULL = /^(?:~|null|Null|NULL|)$/;
46
+ const BOOL = /^(?:true|True|TRUE|false|False|FALSE)$/;
47
+ const INT = /^[-+]?[0-9]+$/;
48
+ const OCT = /^0o[0-7]+$/;
49
+ const HEX = /^0x[0-9a-fA-F]+$/;
50
+ const FLOAT = /^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)(?:[eE][-+]?[0-9]+)?$/;
51
+ const INF = /^[-+]?(?:\.inf|\.Inf|\.INF)$/;
52
+ const NAN = /^(?:\.nan|\.NaN|\.NAN)$/;
53
+
54
+ /** A plain scalar resolved by YAML 1.2's core schema. */
55
+ export function resolveCore(s: string): Json {
56
+ if (NULL.test(s)) return null;
57
+ if (BOOL.test(s)) return s.toLowerCase() === "true";
58
+ if (INT.test(s)) return Number(s);
59
+ if (OCT.test(s)) return Number.parseInt(s.slice(2), 8);
60
+ if (HEX.test(s)) return Number.parseInt(s.slice(2), 16);
61
+ if (FLOAT.test(s)) return Number(s);
62
+ if (INF.test(s)) return s.startsWith("-") ? Number.NEGATIVE_INFINITY : Number.POSITIVE_INFINITY;
63
+ if (NAN.test(s)) return Number.NaN;
64
+ return s;
65
+ }
66
+
67
+ const DOUBLE_ESCAPES: Readonly<Record<string, string>> = {
68
+ "0": "\0",
69
+ a: "\x07",
70
+ b: "\b",
71
+ t: "\t",
72
+ "\t": "\t",
73
+ n: "\n",
74
+ v: "\v",
75
+ f: "\f",
76
+ r: "\r",
77
+ e: "\x1b",
78
+ " ": " ",
79
+ '"': '"',
80
+ "/": "/",
81
+ "\\": "\\",
82
+ N: "\x85",
83
+ _: "\xa0",
84
+ L: "\u2028",
85
+ P: "\u2029",
86
+ };
87
+
88
+ /** A YAML text read as a JSON value (an empty document is `null`), or where and why it is not YAML this reader takes. */
89
+ export function parseYaml(text: string, options: YamlOptions = {}): Result<Json, YamlError> {
90
+ const failsafe = options.schema === "failsafe";
91
+ const src = text.startsWith("\ufeff") ? text.slice(1) : text;
92
+ let i = 0;
93
+ const fail = (message: string, at = i): never => {
94
+ throw new Stop(at, message);
95
+ };
96
+ const peek = (n = 0): string => src[i + n] ?? "";
97
+ const lineStart = (at: number): number => src.lastIndexOf("\n", at - 1) + 1;
98
+ const column = (at = i): number => at - lineStart(at);
99
+ const atLineEnd = (): boolean => peek() === "" || peek() === "\n" || (peek() === "\r" && peek(1) === "\n");
100
+ const eatLineEnd = (): void => {
101
+ if (peek() === "\r") i++;
102
+ if (peek() === "\n") i++;
103
+ };
104
+ const spaces = (): void => {
105
+ while (peek() === " " || peek() === "\t") i++;
106
+ };
107
+ /** The rest of a line: space, then a comment or nothing. */
108
+ const restOfLine = (): void => {
109
+ spaces();
110
+ if (peek() === "#") while (!atLineEnd()) i++;
111
+ if (!atLineEnd()) fail("the end of the line");
112
+ eatLineEnd();
113
+ };
114
+ const marker = (m: "---" | "..."): boolean => column() === 0 && src.startsWith(m, i) && /^[ \t\r\n]?$/.test(src[i + 3] ?? "");
115
+ /** Past blank lines and comment lines, to the first character of the next content (or the end); refusing a tab in indentation. */
116
+ const toContent = (): void => {
117
+ for (;;) {
118
+ const start = i;
119
+ while (peek() === " ") i++;
120
+ if (peek() === "\t") {
121
+ let j = i;
122
+ while (src[j] === " " || src[j] === "\t") j++;
123
+ if (src[j] === "\n" || src[j] === "\r" || src[j] === "#" || src[j] === undefined) i = j;
124
+ else fail("spaces for indentation, not a tab");
125
+ }
126
+ if (peek() === "#") while (!atLineEnd()) i++;
127
+ if (peek() === "" || !atLineEnd()) {
128
+ if (peek() !== "") i = start + (i - start);
129
+ return;
130
+ }
131
+ eatLineEnd();
132
+ }
133
+ };
134
+ const refuseSpecial = (): void => {
135
+ const c = peek();
136
+ if (c === "&" || c === "*") fail("no anchor or alias (they are not read, so no value is ever repeated or expanded)");
137
+ if (c === "!") fail("no tag (a value's type comes from the schema)");
138
+ if (c === "?" && /[ \t\r\n]/.test(peek(1) || "\n")) fail("a simple key (complex keys are not read)");
139
+ if (c === "%" && column() === 0) fail("no directive");
140
+ if (c === "@" || c === "`") fail(`no ${c} at the start of a plain scalar (it is reserved)`);
141
+ };
142
+ const hex = (n: number): string => {
143
+ const h = src.slice(i, i + n);
144
+ if (h.length !== n || !/^[0-9a-fA-F]+$/.test(h)) fail(`${n} hexadecimal digits`);
145
+ i += n;
146
+ return String.fromCodePoint(Number.parseInt(h, 16));
147
+ };
148
+ /** Line breaks inside a quoted scalar folded: one break is a space, each further empty line a line break. */
149
+ const foldQuoted = (): string => {
150
+ let breaks = 0;
151
+ while (atLineEnd() && peek() !== "") {
152
+ eatLineEnd();
153
+ breaks++;
154
+ spaces();
155
+ }
156
+ return breaks === 1 ? " " : "\n".repeat(breaks - 1);
157
+ };
158
+ const trimEnd = (s: string): string => s.replace(/[ \t]+$/, "");
159
+ const doubleQuoted = (): string => {
160
+ i++;
161
+ let out = "";
162
+ for (;;) {
163
+ const c = peek();
164
+ if (c === "") fail("the closing quote");
165
+ if (c === '"') {
166
+ i++;
167
+ return out;
168
+ }
169
+ if (c === "\\") {
170
+ i++;
171
+ const e = peek();
172
+ if (atLineEnd() && e !== "") {
173
+ eatLineEnd();
174
+ spaces();
175
+ while (atLineEnd() && peek() !== "") {
176
+ eatLineEnd();
177
+ out += "\n";
178
+ spaces();
179
+ }
180
+ continue;
181
+ }
182
+ i++;
183
+ const simple = DOUBLE_ESCAPES[e];
184
+ if (simple !== undefined) out += simple;
185
+ else if (e === "x") out += hex(2);
186
+ else if (e === "u") out += hex(4);
187
+ else if (e === "U") out += hex(8);
188
+ else fail(`a known escape, not \\${e}`, i - 2);
189
+ continue;
190
+ }
191
+ if (atLineEnd()) {
192
+ out = trimEnd(out) + foldQuoted();
193
+ continue;
194
+ }
195
+ out += c;
196
+ i++;
197
+ }
198
+ };
199
+ const singleQuoted = (): string => {
200
+ i++;
201
+ let out = "";
202
+ for (;;) {
203
+ const c = peek();
204
+ if (c === "") fail("the closing quote");
205
+ if (c === "'") {
206
+ if (peek(1) === "'") {
207
+ out += "'";
208
+ i += 2;
209
+ continue;
210
+ }
211
+ i++;
212
+ return out;
213
+ }
214
+ if (atLineEnd()) {
215
+ out = trimEnd(out) + foldQuoted();
216
+ continue;
217
+ }
218
+ out += c;
219
+ i++;
220
+ }
221
+ };
222
+ const scalarOf = (s: string): Json => (failsafe ? s : resolveCore(s));
223
+ /** A plain scalar: in flow, up to `,[]{}`; in block, folded over lines indented more than `parent`. */
224
+ const plain = (parent: number, flow: boolean): string => {
225
+ refuseSpecial();
226
+ const first = peek();
227
+ if (first === "-" && /[ \t\r\n]/.test(peek(1) || "\n")) fail("a value, not a sequence entry here");
228
+ if (/[|>]/.test(first)) fail("a block scalar only after a key or a dash");
229
+ if (/[,\]}]/.test(first) && flow) fail("a value");
230
+ let out = "";
231
+ for (;;) {
232
+ let line = "";
233
+ for (;;) {
234
+ const c = peek();
235
+ if (atLineEnd()) break;
236
+ if (c === ":" && (/[ \t\r\n]/.test(peek(1) || "\n") || (flow && /[,\]}[{]/.test(peek(1))))) break;
237
+ if (c === "#" && /[ \t]$/.test(line)) break;
238
+ if (flow && /[,[\]{}]/.test(c)) break;
239
+ line += c;
240
+ i++;
241
+ }
242
+ out += trimEnd(line);
243
+ if (peek() === "#" || peek() === ":" || (flow && /[,[\]{}]/.test(peek())) || !atLineEnd() || peek() === "") return out;
244
+ const save = i;
245
+ let breaks = 0;
246
+ while (atLineEnd() && peek() !== "") {
247
+ eatLineEnd();
248
+ breaks++;
249
+ while (peek() === " " || peek() === "\t") i++;
250
+ if (peek() === "#") {
251
+ i = save;
252
+ return out;
253
+ }
254
+ }
255
+ if (peek() === "" || (!flow && column() <= parent) || marker("---") || marker("...")) {
256
+ i = save;
257
+ return out;
258
+ }
259
+ if (!flow && peek() === "-" && /[ \t\r\n]/.test(peek(1) || "\n") && column() <= parent + 1) {
260
+ i = save;
261
+ return out;
262
+ }
263
+ out += breaks === 1 ? " " : "\n".repeat(breaks - 1);
264
+ }
265
+ };
266
+ const blockScalar = (parent: number): string => {
267
+ const literal = peek() === "|";
268
+ i++;
269
+ let chomp: "clip" | "strip" | "keep" = "clip";
270
+ let explicit = 0;
271
+ for (let k = 0; k < 2; k++) {
272
+ const c = peek();
273
+ if (c === "-" || c === "+") {
274
+ chomp = c === "-" ? "strip" : "keep";
275
+ i++;
276
+ } else if (/[1-9]/.test(c)) {
277
+ explicit = Number(c);
278
+ i++;
279
+ }
280
+ }
281
+ restOfLine();
282
+ const lines: string[] = [];
283
+ let indent = explicit > 0 ? parent + explicit : -1;
284
+ let trailingBreak = false;
285
+ for (;;) {
286
+ if (peek() === "") break;
287
+ const start = i;
288
+ let n = 0;
289
+ while (peek() === " ") {
290
+ i++;
291
+ n++;
292
+ }
293
+ if (atLineEnd()) {
294
+ if (indent >= 0 && n > indent) lines.push(src.slice(start + indent, i));
295
+ else lines.push("");
296
+ if (peek() === "") {
297
+ i = start + n;
298
+ break;
299
+ }
300
+ eatLineEnd();
301
+ trailingBreak = true;
302
+ continue;
303
+ }
304
+ if (indent < 0) {
305
+ if (n <= parent) {
306
+ i = start;
307
+ break;
308
+ }
309
+ indent = n;
310
+ }
311
+ if (n < indent || ((marker("---") || marker("...")) && n === 0)) {
312
+ i = start;
313
+ break;
314
+ }
315
+ let end = i;
316
+ while (!atLineEnd()) end = ++i;
317
+ lines.push(src.slice(start + indent, end));
318
+ trailingBreak = peek() !== "";
319
+ eatLineEnd();
320
+ }
321
+ let last = lines.length;
322
+ while (last > 0 && lines[last - 1] === "") last--;
323
+ const content = lines.slice(0, last);
324
+ const trailing = lines.length - last;
325
+ let body: string;
326
+ if (literal) body = content.join("\n");
327
+ else {
328
+ body = "";
329
+ let empty = 0;
330
+ let moreIndented = false;
331
+ let started = false;
332
+ for (const line of content) {
333
+ if (line === "") {
334
+ empty++;
335
+ continue;
336
+ }
337
+ const more = line.startsWith(" ") || line.startsWith("\t");
338
+ if (!started) body += "\n".repeat(empty);
339
+ else if (more || moreIndented) body += "\n".repeat(empty + 1);
340
+ else body += empty === 0 ? " " : "\n".repeat(empty);
341
+ body += line;
342
+ moreIndented = more;
343
+ started = true;
344
+ empty = 0;
345
+ }
346
+ }
347
+ if (content.length === 0) return chomp === "keep" ? "\n".repeat(trailing + (trailingBreak && trailing === 0 ? 1 : 0)) : "";
348
+ switch (chomp) {
349
+ case "strip":
350
+ return body;
351
+ case "clip":
352
+ return trailingBreak || trailing > 0 ? `${body}\n` : body;
353
+ case "keep":
354
+ return `${body}${"\n".repeat(trailing + (trailingBreak ? 1 : 0))}`;
355
+ }
356
+ };
357
+ const define = (o: Record<string, Json>, k: string, v: Json, at: number): void => {
358
+ if (Object.hasOwn(o, k)) fail(`the key ${JSON.stringify(k)} only once`, at);
359
+ Object.defineProperty(o, k, { value: v, enumerable: true, writable: true, configurable: true });
360
+ };
361
+ const keyText = (k: Json): string =>
362
+ typeof k === "string" ? k : k === null ? "null" : typeof k === "number" || typeof k === "boolean" ? String(k) : fail("a scalar key");
363
+ /** Space, line breaks and comments inside a flow collection. */
364
+ const flowGap = (): void => {
365
+ for (;;) {
366
+ spaces();
367
+ if (peek() === "#") while (!atLineEnd()) i++;
368
+ if (atLineEnd() && peek() !== "") eatLineEnd();
369
+ else return;
370
+ }
371
+ };
372
+ const flowNode = (depth: number): Json => {
373
+ if (depth > 256) fail("less nesting (more than 256 levels)");
374
+ flowGap();
375
+ const c = peek();
376
+ if (c === "[") {
377
+ i++;
378
+ const out: Json[] = [];
379
+ for (;;) {
380
+ flowGap();
381
+ if (peek() === "]") {
382
+ i++;
383
+ return out;
384
+ }
385
+ out.push(flowNode(depth + 1));
386
+ flowGap();
387
+ if (peek() === ":") fail("no mapping inside a flow sequence");
388
+ if (peek() === ",") i++;
389
+ else if (peek() !== "]") fail("a comma or ]");
390
+ }
391
+ }
392
+ if (c === "{") {
393
+ i++;
394
+ const out: Record<string, Json> = {};
395
+ for (;;) {
396
+ flowGap();
397
+ if (peek() === "}") {
398
+ i++;
399
+ return out;
400
+ }
401
+ const at = i;
402
+ const k = keyText(flowNode(depth + 1));
403
+ flowGap();
404
+ let v: Json = null;
405
+ if (peek() === ":") {
406
+ i++;
407
+ flowGap();
408
+ if (peek() !== "," && peek() !== "}") v = flowNode(depth + 1);
409
+ }
410
+ define(out, k, v, at);
411
+ flowGap();
412
+ if (peek() === ",") i++;
413
+ else if (peek() !== "}") fail("a comma or }");
414
+ }
415
+ }
416
+ if (c === '"') return doubleQuoted();
417
+ if (c === "'") return singleQuoted();
418
+ return scalarOf(plain(-1, true));
419
+ };
420
+ /** Whether a mapping key starts here: a scalar followed, on the same line, by `:` and space or the line's end. */
421
+ const startsKey = (): boolean => {
422
+ const save = i;
423
+ try {
424
+ const c = peek();
425
+ if (c === '"') doubleQuoted();
426
+ else if (c === "'") singleQuoted();
427
+ else if (c === "[" || c === "{") return false;
428
+ else {
429
+ if (c === "-" && /[ \t\r\n]/.test(peek(1) || "\n")) return false;
430
+ if (/[&*!|>%@`]/.test(c) || (c === "?" && /[ \t\r\n]/.test(peek(1) || "\n"))) {
431
+ for (let j = i; j < src.length && src[j] !== "\n"; j++) if (src[j] === ":" && /[ \t\r\n]/.test(src[j + 1] ?? "\n")) return true;
432
+ return false;
433
+ }
434
+ while (!atLineEnd()) {
435
+ if (peek() === ":" && /[ \t\r\n]/.test(peek(1) || "\n")) return true;
436
+ if (peek() === "#" && /[ \t]/.test(src[i - 1] ?? "")) return false;
437
+ i++;
438
+ }
439
+ return false;
440
+ }
441
+ spaces();
442
+ return peek() === ":" && /[ \t\r\n]/.test(peek(1) || "\n");
443
+ } catch {
444
+ return false;
445
+ } finally {
446
+ i = save;
447
+ }
448
+ };
449
+ /** A value on the line of its key or dash, or below it: `parent` is the indentation of that key or dash. */
450
+ const valueAfter = (parent: number, depth: number, seqAtParent: boolean): Json => {
451
+ spaces();
452
+ if (peek() === "#" || atLineEnd()) {
453
+ restOfLine();
454
+ toContent();
455
+ if (peek() === "" || marker("---") || marker("...")) return null;
456
+ const col = column();
457
+ if (col > parent) return blockNode(col, depth + 1);
458
+ if (seqAtParent && col === parent && peek() === "-" && /[ \t\r\n]/.test(peek(1) || "\n")) return sequence(col, depth + 1);
459
+ return null;
460
+ }
461
+ const c = peek();
462
+ let v: Json;
463
+ if (c === "|" || c === ">") return blockScalar(parent);
464
+ if (c === "[" || c === "{") v = flowNode(depth + 1);
465
+ else if (c === '"') v = doubleQuoted();
466
+ else if (c === "'") v = singleQuoted();
467
+ else {
468
+ if (startsKey()) fail("a value, not another key on the same line");
469
+ v = scalarOf(plain(parent, false));
470
+ }
471
+ restOfLine();
472
+ return v;
473
+ };
474
+ const sequence = (col: number, depth: number): Json[] => {
475
+ const out: Json[] = [];
476
+ for (;;) {
477
+ i++;
478
+ if (peek() === " " || peek() === "\t") {
479
+ spaces();
480
+ if (!(peek() === "#" || atLineEnd())) {
481
+ const inner = column();
482
+ if (peek() === "-" && /[ \t\r\n]/.test(peek(1) || "\n")) out.push(sequence(inner, depth + 1));
483
+ else if (startsKey()) out.push(mapping(inner, depth + 1));
484
+ else out.push(valueAfter(col, depth, false));
485
+ } else out.push(valueAfter(col, depth, false));
486
+ } else out.push(valueAfter(col, depth, false));
487
+ toContent();
488
+ if (peek() === "" || marker("---") || marker("...")) return out;
489
+ const next = column();
490
+ if (next > col) fail("the indentation of the sequence");
491
+ if (next < col || !(peek() === "-" && /[ \t\r\n]/.test(peek(1) || "\n"))) return out;
492
+ }
493
+ };
494
+ const mapping = (col: number, depth: number): Record<string, Json> => {
495
+ const out: Record<string, Json> = {};
496
+ for (;;) {
497
+ refuseSpecial();
498
+ const at = i;
499
+ const c = peek();
500
+ const k = c === '"' ? doubleQuoted() : c === "'" ? singleQuoted() : keyText(scalarOf(plain(col, false)));
501
+ spaces();
502
+ if (peek() !== ":") fail("a colon after the key");
503
+ i++;
504
+ define(out, k, valueAfter(col, depth, true), at);
505
+ toContent();
506
+ if (peek() === "" || marker("---") || marker("...")) return out;
507
+ const next = column();
508
+ if (next > col) fail("the indentation of the mapping");
509
+ if (next < col) return out;
510
+ if (peek() === "-" && /[ \t\r\n]/.test(peek(1) || "\n")) return out;
511
+ }
512
+ };
513
+ const blockNode = (col: number, depth: number): Json => {
514
+ if (depth > 256) fail("less nesting (more than 256 levels)");
515
+ refuseSpecial();
516
+ if (peek() === "-" && /[ \t\r\n]/.test(peek(1) || "\n")) return sequence(col, depth);
517
+ if (startsKey()) return mapping(col, depth);
518
+ const c = peek();
519
+ let v: Json;
520
+ if (c === "[" || c === "{") v = flowNode(depth + 1);
521
+ else if (c === '"') v = doubleQuoted();
522
+ else if (c === "'") v = singleQuoted();
523
+ else if (c === "|" || c === ">") return blockScalar(col - 1);
524
+ else v = scalarOf(plain(col - 1, false));
525
+ restOfLine();
526
+ return v;
527
+ };
528
+ try {
529
+ toContent();
530
+ if (peek() === "%") fail("no directive");
531
+ if (marker("---")) {
532
+ i += 3;
533
+ spaces();
534
+ if (atLineEnd() || peek() === "#") {
535
+ restOfLine();
536
+ toContent();
537
+ }
538
+ }
539
+ let value: Json = null;
540
+ if (!(peek() === "" || marker("...") || marker("---"))) value = blockNode(column(), 0);
541
+ toContent();
542
+ if (marker("...")) {
543
+ i += 3;
544
+ restOfLine();
545
+ toContent();
546
+ }
547
+ if (marker("---")) fail("one document (more than one is not read)");
548
+ if (peek() !== "") fail("the end of the document");
549
+ return ok(value);
550
+ } catch (e) {
551
+ if (!(e instanceof Stop)) throw e;
552
+ const before = src.slice(0, e.at).split(/\r?\n/);
553
+ return err({ kind: "yaml", line: before.length, column: (before.at(-1)?.length ?? 0) + 1, message: `expected ${e.message}` });
554
+ }
555
+ }
556
+
557
+ const isObject = (v: Json): v is { readonly [key: string]: Json } => typeof v === "object" && v !== null && !Array.isArray(v);
558
+
559
+ /** Whether text can be written as a plain scalar and read back as the same text by the core schema. */
560
+ export function isPlainSafe(s: string): boolean {
561
+ if (s === "" || s !== s.trim() || /[\n\r\t]/.test(s)) return false;
562
+ if (typeof resolveCore(s) !== "string") return false;
563
+ if (/^[-?:,[\]{}#&*!|>'"%@`]/.test(s)) return false;
564
+ if (/: |:$| #/.test(s)) return false;
565
+ if (s === "---" || s === "...") return false;
566
+ return /^[\x20-\x7e\u00a0-\ud7ff\ue000-\ufffd]*$/.test(s);
567
+ }
568
+
569
+ function scalar(v: Json): string {
570
+ if (v === null) return "null";
571
+ if (typeof v === "boolean") return String(v);
572
+ if (typeof v === "number") {
573
+ if (Number.isNaN(v)) return ".nan";
574
+ if (!Number.isFinite(v)) return v > 0 ? ".inf" : "-.inf";
575
+ if (Object.is(v, -0)) return "-0.0";
576
+ return String(v);
577
+ }
578
+ if (typeof v === "string") return isPlainSafe(v) ? v : JSON.stringify(v);
579
+ return Array.isArray(v) ? "[]" : "{}";
580
+ }
581
+
582
+ const empty = (v: Json): boolean => (Array.isArray(v) ? v.length === 0 : isObject(v) ? Object.keys(v).length === 0 : false);
583
+
584
+ function block(v: Json, indent: number, out: string[]): void {
585
+ const pad = " ".repeat(indent);
586
+ if (Array.isArray(v)) {
587
+ for (const item of v as readonly Json[]) {
588
+ if ((Array.isArray(item) || isObject(item)) && !empty(item)) {
589
+ const inner: string[] = [];
590
+ block(item, 0, inner);
591
+ out.push(`${pad}- ${(inner[0] ?? "").trimStart()}`);
592
+ for (const line of inner.slice(1)) out.push(`${pad} ${line}`);
593
+ } else out.push(`${pad}- ${scalar(item)}`);
594
+ }
595
+ return;
596
+ }
597
+ if (isObject(v)) {
598
+ for (const [k, item] of Object.entries(v)) {
599
+ const key = isPlainSafe(k) ? k : JSON.stringify(k);
600
+ if ((Array.isArray(item) || isObject(item)) && !empty(item)) {
601
+ out.push(`${pad}${key}:`);
602
+ block(item, indent + 1, out);
603
+ } else out.push(`${pad}${key}: ${scalar(item)}`);
604
+ }
605
+ return;
606
+ }
607
+ out.push(`${pad}${scalar(v)}`);
608
+ }
609
+
610
+ /** A value as block YAML, ending in a line break: mappings and sequences by indentation, text plain where it reads back the same, else double-quoted. */
611
+ export function toYaml(value: Json): string {
612
+ if ((Array.isArray(value) || isObject(value)) && empty(value)) return `${scalar(value)}\n`;
613
+ const out: string[] = [];
614
+ block(value, 0, out);
615
+ return `${out.join("\n")}\n`;
616
+ }