@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.
- package/LICENSE +21 -0
- package/README.md +8 -2
- package/dist/archive.d.ts +147 -0
- package/dist/archive.js +765 -0
- package/dist/base64.d.ts +24 -0
- package/dist/base64.js +52 -0
- package/dist/cbor.d.ts +39 -0
- package/dist/cbor.js +244 -0
- package/dist/csv.d.ts +38 -0
- package/dist/csv.js +130 -0
- package/dist/der.d.ts +67 -0
- package/dist/der.js +221 -0
- package/dist/glob.d.ts +64 -0
- package/dist/glob.js +218 -0
- package/dist/hex.d.ts +17 -0
- package/dist/hex.js +30 -0
- package/dist/http.d.ts +46 -0
- package/dist/http.js +102 -0
- package/dist/json5.d.ts +46 -0
- package/dist/json5.js +291 -0
- package/dist/media-types.d.ts +28 -0
- package/dist/media-types.js +121 -0
- package/dist/mod.d.ts +39 -0
- package/dist/mod.js +31 -0
- package/dist/png.d.ts +124 -0
- package/dist/png.js +607 -0
- package/dist/semver.d.ts +94 -0
- package/dist/semver.js +331 -0
- package/dist/toml.d.ts +51 -0
- package/dist/toml.js +583 -0
- package/dist/ts-literal.d.ts +62 -0
- package/dist/ts-literal.js +173 -0
- package/dist/xml.d.ts +73 -0
- package/dist/xml.js +282 -0
- package/dist/yaml.d.ts +44 -0
- package/dist/yaml.js +706 -0
- package/package.json +118 -4
- package/src/archive.ts +831 -0
- package/src/base64.ts +51 -0
- package/src/cbor.ts +235 -0
- package/src/csv.ts +132 -0
- package/src/der.ts +224 -0
- package/src/glob.ts +210 -0
- package/src/hex.ts +28 -0
- package/src/http.ts +104 -0
- package/src/json5.ts +267 -0
- package/src/media-types.ts +127 -0
- package/src/mod.ts +102 -0
- package/src/png.ts +625 -0
- package/src/semver.ts +373 -0
- package/src/toml.ts +525 -0
- package/src/ts-literal.ts +183 -0
- package/src/xml.ts +291 -0
- package/src/yaml.ts +616 -0
package/dist/toml.js
ADDED
|
@@ -0,0 +1,583 @@
|
|
|
1
|
+
// Spec: 0001-formats FR-003
|
|
2
|
+
/**
|
|
3
|
+
* TOML 1.0.0 (https://toml.io/en/v1.0.0), read and written with no outside package (commons 0001-formats FR-003). The reader
|
|
4
|
+
* takes the whole language (bare, quoted and dotted keys; tables, arrays of tables and inline tables; the four kinds of string; decimal,
|
|
5
|
+
* hexadecimal, octal and binary integers; floats with `inf` and `nan`; the four kinds of date and time) and holds to its rules: no key or
|
|
6
|
+
* table defined twice, an inline table or a static array never extended, a table made by dotted keys never reopened by a header. It
|
|
7
|
+
* gives a typed `TomlTable`, or the line and column where the text stops being TOML. An integer outside JavaScript's safe range is refused
|
|
8
|
+
* rather than rounded. A date or time stays as its text, with its kind. The writer gives TOML the reader reads back as the same table.
|
|
9
|
+
* Replaces `@std/toml` in erga.
|
|
10
|
+
*
|
|
11
|
+
* @example
|
|
12
|
+
* ```ts
|
|
13
|
+
* import { parseToml } from "./toml.ts";
|
|
14
|
+
* parseToml('[server]\nhost = "127.0.0.1"\nports = [8000, 8001]\n');
|
|
15
|
+
* // { kind: "ok", value: { server: { host: "127.0.0.1", ports: [8000, 8001] } } }
|
|
16
|
+
* ```
|
|
17
|
+
*
|
|
18
|
+
* @module
|
|
19
|
+
*/
|
|
20
|
+
import { err, ok } from "@intellectual-frontiers/core";
|
|
21
|
+
/** A TOML error as one line: `3:14: expected a value`. */
|
|
22
|
+
export function formatTomlError(e) {
|
|
23
|
+
return `${e.line}:${e.column}: ${e.message}`;
|
|
24
|
+
}
|
|
25
|
+
/** Whether a TOML value is a date or time. */
|
|
26
|
+
export function isTomlDateTime(v) {
|
|
27
|
+
return (typeof v === "object" &&
|
|
28
|
+
!Array.isArray(v) &&
|
|
29
|
+
Object.keys(v).length === 2 &&
|
|
30
|
+
"kind" in v &&
|
|
31
|
+
"text" in v &&
|
|
32
|
+
typeof v["text"] === "string" &&
|
|
33
|
+
typeof v["kind"] === "string" &&
|
|
34
|
+
/^(offset-date-time|local-date-time|local-date|local-time)$/.test(v["kind"]));
|
|
35
|
+
}
|
|
36
|
+
/** Whether a TOML value is a table (not an array, not a date or time). */
|
|
37
|
+
export function isTomlTable(v) {
|
|
38
|
+
return typeof v === "object" && !Array.isArray(v) && !isTomlDateTime(v);
|
|
39
|
+
}
|
|
40
|
+
class Stop extends Error {
|
|
41
|
+
at;
|
|
42
|
+
constructor(at, message) {
|
|
43
|
+
super(message);
|
|
44
|
+
this.at = at;
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
const BARE = /^[A-Za-z0-9_-]+/;
|
|
48
|
+
const ESCAPES = { b: "\b", t: "\t", n: "\n", f: "\f", r: "\r", '"': '"', "\\": "\\" };
|
|
49
|
+
const CONTROL = new RegExp(`[${String.fromCharCode(0)}-${String.fromCharCode(8, 10)}-${String.fromCharCode(31, 127)}]`);
|
|
50
|
+
const DATE = /^(\d{4})-(\d{2})-(\d{2})/;
|
|
51
|
+
const TIME = /^(\d{2}):(\d{2}):(\d{2})(\.\d+)?/;
|
|
52
|
+
const OFFSET = /^(?:[Zz]|[+-](\d{2}):(\d{2}))/;
|
|
53
|
+
function validDate(y, m, d) {
|
|
54
|
+
if (m < 1 || m > 12 || d < 1)
|
|
55
|
+
return false;
|
|
56
|
+
const days = [31, (y % 4 === 0 && y % 100 !== 0) || y % 400 === 0 ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][m - 1] ?? 0;
|
|
57
|
+
return d <= days;
|
|
58
|
+
}
|
|
59
|
+
/** TOML text read as a table, or where and why it is not TOML. */
|
|
60
|
+
export function parseToml(text) {
|
|
61
|
+
let i = 0;
|
|
62
|
+
const root = {};
|
|
63
|
+
/** Tables a header defined; tables a header made on its way; tables dotted keys made; inline tables and static arrays; arrays of tables. */
|
|
64
|
+
const defined = new Set();
|
|
65
|
+
const byHeader = new Set();
|
|
66
|
+
const byDots = new Set();
|
|
67
|
+
const frozen = new Set();
|
|
68
|
+
const tableArrays = new Set();
|
|
69
|
+
const fail = (message, at = i) => {
|
|
70
|
+
throw new Stop(at, message);
|
|
71
|
+
};
|
|
72
|
+
const peek = (n = 0) => text[i + n] ?? "";
|
|
73
|
+
const blank = () => {
|
|
74
|
+
while (peek() === " " || peek() === "\t")
|
|
75
|
+
i++;
|
|
76
|
+
};
|
|
77
|
+
const comment = () => {
|
|
78
|
+
if (peek() !== "#")
|
|
79
|
+
return;
|
|
80
|
+
while (i < text.length && peek() !== "\n" && !(peek() === "\r" && peek(1) === "\n")) {
|
|
81
|
+
if (CONTROL.test(peek()) && peek() !== "\t")
|
|
82
|
+
fail("no control character in a comment");
|
|
83
|
+
i++;
|
|
84
|
+
}
|
|
85
|
+
};
|
|
86
|
+
const newline = () => {
|
|
87
|
+
if (peek() === "\n") {
|
|
88
|
+
i++;
|
|
89
|
+
return true;
|
|
90
|
+
}
|
|
91
|
+
if (peek() === "\r" && peek(1) === "\n") {
|
|
92
|
+
i += 2;
|
|
93
|
+
return true;
|
|
94
|
+
}
|
|
95
|
+
return false;
|
|
96
|
+
};
|
|
97
|
+
const endOfLine = () => {
|
|
98
|
+
blank();
|
|
99
|
+
comment();
|
|
100
|
+
if (i < text.length && !newline())
|
|
101
|
+
fail("the end of the line");
|
|
102
|
+
};
|
|
103
|
+
/** Space, comments and line breaks, as an array allows between its values. */
|
|
104
|
+
const gap = () => {
|
|
105
|
+
for (;;) {
|
|
106
|
+
blank();
|
|
107
|
+
comment();
|
|
108
|
+
if (!newline())
|
|
109
|
+
return;
|
|
110
|
+
}
|
|
111
|
+
};
|
|
112
|
+
const hexChar = (n) => {
|
|
113
|
+
const h = text.slice(i, i + n);
|
|
114
|
+
if (h.length !== n || !/^[0-9a-fA-F]+$/.test(h))
|
|
115
|
+
fail(`${n} hexadecimal digits`);
|
|
116
|
+
const cp = Number.parseInt(h, 16);
|
|
117
|
+
if (cp > 0x10ffff || (cp >= 0xd800 && cp <= 0xdfff))
|
|
118
|
+
fail("a Unicode scalar value", i - 2);
|
|
119
|
+
i += n;
|
|
120
|
+
return String.fromCodePoint(cp);
|
|
121
|
+
};
|
|
122
|
+
const escape = () => {
|
|
123
|
+
const c = peek();
|
|
124
|
+
i++;
|
|
125
|
+
const simple = ESCAPES[c];
|
|
126
|
+
if (simple !== undefined)
|
|
127
|
+
return simple;
|
|
128
|
+
if (c === "u")
|
|
129
|
+
return hexChar(4);
|
|
130
|
+
if (c === "U")
|
|
131
|
+
return hexChar(8);
|
|
132
|
+
return fail(`a known escape, not \\${c}`, i - 2);
|
|
133
|
+
};
|
|
134
|
+
const basic = () => {
|
|
135
|
+
i++;
|
|
136
|
+
let out = "";
|
|
137
|
+
for (;;) {
|
|
138
|
+
const c = peek();
|
|
139
|
+
if (c === "" || c === "\n" || c === "\r")
|
|
140
|
+
fail("the closing quote of a string");
|
|
141
|
+
i++;
|
|
142
|
+
if (c === '"')
|
|
143
|
+
return out;
|
|
144
|
+
if (c === "\\")
|
|
145
|
+
out += escape();
|
|
146
|
+
else if (CONTROL.test(c))
|
|
147
|
+
fail("no control character in a string", i - 1);
|
|
148
|
+
else
|
|
149
|
+
out += c;
|
|
150
|
+
}
|
|
151
|
+
};
|
|
152
|
+
const literal = () => {
|
|
153
|
+
i++;
|
|
154
|
+
const start = i;
|
|
155
|
+
for (;;) {
|
|
156
|
+
const c = peek();
|
|
157
|
+
if (c === "" || c === "\n" || c === "\r")
|
|
158
|
+
fail("the closing quote of a string");
|
|
159
|
+
if (c === "'")
|
|
160
|
+
break;
|
|
161
|
+
if (CONTROL.test(c))
|
|
162
|
+
fail("no control character in a string");
|
|
163
|
+
i++;
|
|
164
|
+
}
|
|
165
|
+
const s = text.slice(start, i);
|
|
166
|
+
i++;
|
|
167
|
+
return s;
|
|
168
|
+
};
|
|
169
|
+
const multiline = (quote) => {
|
|
170
|
+
i += 3;
|
|
171
|
+
newline();
|
|
172
|
+
let out = "";
|
|
173
|
+
for (;;) {
|
|
174
|
+
if (i >= text.length)
|
|
175
|
+
fail("the closing quotes of a multi-line string");
|
|
176
|
+
if (text.startsWith(quote.repeat(3), i)) {
|
|
177
|
+
let n = 3;
|
|
178
|
+
while (peek(n) === quote && n < 5)
|
|
179
|
+
n++;
|
|
180
|
+
out += quote.repeat(n - 3);
|
|
181
|
+
i += n;
|
|
182
|
+
return out;
|
|
183
|
+
}
|
|
184
|
+
const c = peek();
|
|
185
|
+
if (newline()) {
|
|
186
|
+
out += "\n";
|
|
187
|
+
continue;
|
|
188
|
+
}
|
|
189
|
+
if (quote === '"' && c === "\\") {
|
|
190
|
+
let j = i + 1;
|
|
191
|
+
while (text[j] === " " || text[j] === "\t")
|
|
192
|
+
j++;
|
|
193
|
+
if (text[j] === "\n" || (text[j] === "\r" && text[j + 1] === "\n")) {
|
|
194
|
+
i = j;
|
|
195
|
+
while (newline() || peek() === " " || peek() === "\t")
|
|
196
|
+
if (peek() === " " || peek() === "\t")
|
|
197
|
+
i++;
|
|
198
|
+
continue;
|
|
199
|
+
}
|
|
200
|
+
i++;
|
|
201
|
+
out += escape();
|
|
202
|
+
continue;
|
|
203
|
+
}
|
|
204
|
+
if (CONTROL.test(c) && c !== "\t")
|
|
205
|
+
fail("no control character in a string");
|
|
206
|
+
out += c;
|
|
207
|
+
i++;
|
|
208
|
+
}
|
|
209
|
+
};
|
|
210
|
+
const key = () => {
|
|
211
|
+
const c = peek();
|
|
212
|
+
if (c === '"')
|
|
213
|
+
return text.startsWith('"""', i) ? fail("a key on one line") : basic();
|
|
214
|
+
if (c === "'")
|
|
215
|
+
return text.startsWith("'''", i) ? fail("a key on one line") : literal();
|
|
216
|
+
const m = BARE.exec(text.slice(i));
|
|
217
|
+
if (m === null)
|
|
218
|
+
return fail("a key");
|
|
219
|
+
i += m[0].length;
|
|
220
|
+
return m[0];
|
|
221
|
+
};
|
|
222
|
+
const dottedKey = () => {
|
|
223
|
+
const parts = [key()];
|
|
224
|
+
for (;;) {
|
|
225
|
+
blank();
|
|
226
|
+
if (peek() !== ".")
|
|
227
|
+
return parts;
|
|
228
|
+
i++;
|
|
229
|
+
blank();
|
|
230
|
+
parts.push(key());
|
|
231
|
+
}
|
|
232
|
+
};
|
|
233
|
+
const dateTime = () => {
|
|
234
|
+
const start = i;
|
|
235
|
+
const rest = text.slice(i);
|
|
236
|
+
const d = DATE.exec(rest);
|
|
237
|
+
if (d !== null) {
|
|
238
|
+
if (!validDate(Number(d[1]), Number(d[2]), Number(d[3])))
|
|
239
|
+
fail("a real date", start);
|
|
240
|
+
i += d[0].length;
|
|
241
|
+
const sep = peek();
|
|
242
|
+
const t = sep === "T" || sep === "t" || sep === " " ? TIME.exec(text.slice(i + 1)) : null;
|
|
243
|
+
if (t === null)
|
|
244
|
+
return { kind: "local-date", text: d[0] };
|
|
245
|
+
i += 1;
|
|
246
|
+
time(t, start);
|
|
247
|
+
const o = OFFSET.exec(text.slice(i));
|
|
248
|
+
if (o !== null) {
|
|
249
|
+
if (o[1] !== undefined && (Number(o[1]) > 23 || Number(o[2]) > 59))
|
|
250
|
+
fail("a real offset");
|
|
251
|
+
i += o[0].length;
|
|
252
|
+
return { kind: "offset-date-time", text: `${d[0]}T${text.slice(start + 11, i)}` };
|
|
253
|
+
}
|
|
254
|
+
return { kind: "local-date-time", text: `${d[0]}T${text.slice(start + 11, i)}` };
|
|
255
|
+
}
|
|
256
|
+
const t = TIME.exec(rest);
|
|
257
|
+
if (t === null)
|
|
258
|
+
return undefined;
|
|
259
|
+
time(t, start);
|
|
260
|
+
return { kind: "local-time", text: t[0] };
|
|
261
|
+
};
|
|
262
|
+
const time = (t, start) => {
|
|
263
|
+
if (Number(t[1]) > 23 || Number(t[2]) > 59 || Number(t[3]) > 60)
|
|
264
|
+
fail("a real time", start);
|
|
265
|
+
i += t[0].length;
|
|
266
|
+
};
|
|
267
|
+
const number = () => {
|
|
268
|
+
const start = i;
|
|
269
|
+
const rest = text.slice(i);
|
|
270
|
+
const special = /^([+-]?)(inf|nan)/.exec(rest);
|
|
271
|
+
if (special !== null) {
|
|
272
|
+
i += special[0].length;
|
|
273
|
+
return special[2] === "nan" ? Number.NaN : special[1] === "-" ? Number.NEGATIVE_INFINITY : Number.POSITIVE_INFINITY;
|
|
274
|
+
}
|
|
275
|
+
const radix = /^0(?:x([0-9A-Fa-f](?:_?[0-9A-Fa-f])*)|o([0-7](?:_?[0-7])*)|b([01](?:_?[01])*))/.exec(rest);
|
|
276
|
+
if (radix !== null) {
|
|
277
|
+
i += radix[0].length;
|
|
278
|
+
const [digits, base] = radix[1] !== undefined ? [radix[1], 16] : radix[2] !== undefined ? [radix[2], 8] : [radix[3] ?? "", 2];
|
|
279
|
+
const n = Number.parseInt(digits.replaceAll("_", ""), base);
|
|
280
|
+
if (!Number.isSafeInteger(n))
|
|
281
|
+
fail("an integer JavaScript holds exactly (at most 2^53 - 1)", start);
|
|
282
|
+
return n;
|
|
283
|
+
}
|
|
284
|
+
const dec = /^[+-]?(?:0|[1-9](?:_?\d)*)(\.\d(?:_?\d)*)?([eE][+-]?\d(?:_?\d)*)?/.exec(rest);
|
|
285
|
+
if (dec === null)
|
|
286
|
+
return fail("a value");
|
|
287
|
+
i += dec[0].length;
|
|
288
|
+
const n = Number(dec[0].replaceAll("_", ""));
|
|
289
|
+
if (dec[1] === undefined && dec[2] === undefined && !Number.isSafeInteger(n))
|
|
290
|
+
fail("an integer JavaScript holds exactly (at most 2^53 - 1)", start);
|
|
291
|
+
return n;
|
|
292
|
+
};
|
|
293
|
+
const value = (depth) => {
|
|
294
|
+
if (depth > 256)
|
|
295
|
+
fail("less nesting (more than 256 levels)");
|
|
296
|
+
const c = peek();
|
|
297
|
+
let v;
|
|
298
|
+
if (text.startsWith('"""', i))
|
|
299
|
+
v = multiline('"');
|
|
300
|
+
else if (text.startsWith("'''", i))
|
|
301
|
+
v = multiline("'");
|
|
302
|
+
else if (c === '"')
|
|
303
|
+
v = basic();
|
|
304
|
+
else if (c === "'")
|
|
305
|
+
v = literal();
|
|
306
|
+
else if (text.startsWith("true", i)) {
|
|
307
|
+
i += 4;
|
|
308
|
+
v = true;
|
|
309
|
+
}
|
|
310
|
+
else if (text.startsWith("false", i)) {
|
|
311
|
+
i += 5;
|
|
312
|
+
v = false;
|
|
313
|
+
}
|
|
314
|
+
else if (c === "[")
|
|
315
|
+
v = array(depth);
|
|
316
|
+
else if (c === "{")
|
|
317
|
+
v = inline(depth);
|
|
318
|
+
else
|
|
319
|
+
v = dateTime() ?? number();
|
|
320
|
+
const after = peek();
|
|
321
|
+
if (!(after === "" || /[ \t\r\n#,\]}]/.test(after)))
|
|
322
|
+
fail("the end of the value");
|
|
323
|
+
return v;
|
|
324
|
+
};
|
|
325
|
+
const array = (depth) => {
|
|
326
|
+
i++;
|
|
327
|
+
const out = [];
|
|
328
|
+
for (;;) {
|
|
329
|
+
gap();
|
|
330
|
+
if (peek() === "]") {
|
|
331
|
+
i++;
|
|
332
|
+
frozen.add(out);
|
|
333
|
+
return out;
|
|
334
|
+
}
|
|
335
|
+
out.push(value(depth + 1));
|
|
336
|
+
gap();
|
|
337
|
+
if (peek() === ",")
|
|
338
|
+
i++;
|
|
339
|
+
else if (peek() !== "]")
|
|
340
|
+
fail("a comma or ]");
|
|
341
|
+
}
|
|
342
|
+
};
|
|
343
|
+
const inline = (depth) => {
|
|
344
|
+
i++;
|
|
345
|
+
const table = {};
|
|
346
|
+
blank();
|
|
347
|
+
if (peek() === "}") {
|
|
348
|
+
i++;
|
|
349
|
+
frozen.add(table);
|
|
350
|
+
return table;
|
|
351
|
+
}
|
|
352
|
+
for (;;) {
|
|
353
|
+
blank();
|
|
354
|
+
const keyAt = i;
|
|
355
|
+
const path = dottedKey();
|
|
356
|
+
blank();
|
|
357
|
+
if (peek() !== "=")
|
|
358
|
+
fail("=");
|
|
359
|
+
i++;
|
|
360
|
+
blank();
|
|
361
|
+
assign(table, path, value(depth + 1), keyAt, true);
|
|
362
|
+
blank();
|
|
363
|
+
if (peek() === ",") {
|
|
364
|
+
i++;
|
|
365
|
+
blank();
|
|
366
|
+
if (peek() === "}")
|
|
367
|
+
fail("a key after the comma (no trailing comma in an inline table)");
|
|
368
|
+
continue;
|
|
369
|
+
}
|
|
370
|
+
if (peek() === "}") {
|
|
371
|
+
i++;
|
|
372
|
+
frozen.add(table);
|
|
373
|
+
return table;
|
|
374
|
+
}
|
|
375
|
+
fail("a comma or }");
|
|
376
|
+
}
|
|
377
|
+
};
|
|
378
|
+
const isTable = (v) => v !== undefined && typeof v === "object" && !Array.isArray(v) && !isTomlDateTime(v);
|
|
379
|
+
const define = (t, k, v) => {
|
|
380
|
+
Object.defineProperty(t, k, { value: v, enumerable: true, writable: true, configurable: true });
|
|
381
|
+
};
|
|
382
|
+
const assign = (table, path, v, at, inInline) => {
|
|
383
|
+
let t = table;
|
|
384
|
+
for (const k of path.slice(0, -1)) {
|
|
385
|
+
const next = Object.hasOwn(t, k) ? t[k] : undefined;
|
|
386
|
+
if (next === undefined) {
|
|
387
|
+
const made = {};
|
|
388
|
+
define(t, k, made);
|
|
389
|
+
byDots.add(made);
|
|
390
|
+
if (inInline)
|
|
391
|
+
frozen.add(made);
|
|
392
|
+
t = made;
|
|
393
|
+
}
|
|
394
|
+
else if (isTable(next) && byDots.has(next) && !frozen.has(next))
|
|
395
|
+
t = next;
|
|
396
|
+
else if (isTable(next) && byDots.has(next) && inInline)
|
|
397
|
+
t = next;
|
|
398
|
+
else
|
|
399
|
+
fail(`a key not already defined: ${path.join(".")}`, at);
|
|
400
|
+
}
|
|
401
|
+
const last = path.at(-1) ?? "";
|
|
402
|
+
if (Object.hasOwn(t, last))
|
|
403
|
+
fail(`a key not already defined: ${path.join(".")}`, at);
|
|
404
|
+
define(t, last, v);
|
|
405
|
+
};
|
|
406
|
+
const header = (path, array, at) => {
|
|
407
|
+
let t = root;
|
|
408
|
+
for (const k of path.slice(0, -1)) {
|
|
409
|
+
const next = Object.hasOwn(t, k) ? t[k] : undefined;
|
|
410
|
+
if (next === undefined) {
|
|
411
|
+
const made = {};
|
|
412
|
+
define(t, k, made);
|
|
413
|
+
byHeader.add(made);
|
|
414
|
+
t = made;
|
|
415
|
+
}
|
|
416
|
+
else if (Array.isArray(next) && tableArrays.has(next)) {
|
|
417
|
+
const list = next;
|
|
418
|
+
const lastTable = list.at(-1);
|
|
419
|
+
if (!isTable(lastTable))
|
|
420
|
+
return fail("a table", at);
|
|
421
|
+
t = lastTable;
|
|
422
|
+
}
|
|
423
|
+
else if (isTable(next) && !frozen.has(next))
|
|
424
|
+
t = next;
|
|
425
|
+
else
|
|
426
|
+
return fail(`a header that does not extend a value: ${path.join(".")}`, at);
|
|
427
|
+
}
|
|
428
|
+
const last = path.at(-1) ?? "";
|
|
429
|
+
const existing = Object.hasOwn(t, last) ? t[last] : undefined;
|
|
430
|
+
if (array) {
|
|
431
|
+
const made = {};
|
|
432
|
+
byHeader.add(made);
|
|
433
|
+
defined.add(made);
|
|
434
|
+
if (existing === undefined) {
|
|
435
|
+
const list = [made];
|
|
436
|
+
tableArrays.add(list);
|
|
437
|
+
define(t, last, list);
|
|
438
|
+
}
|
|
439
|
+
else if (Array.isArray(existing) && tableArrays.has(existing))
|
|
440
|
+
existing.push(made);
|
|
441
|
+
else
|
|
442
|
+
fail(`[[${path.join(".")}]] where a value or table already is`, at);
|
|
443
|
+
return made;
|
|
444
|
+
}
|
|
445
|
+
if (existing === undefined) {
|
|
446
|
+
const made = {};
|
|
447
|
+
byHeader.add(made);
|
|
448
|
+
defined.add(made);
|
|
449
|
+
define(t, last, made);
|
|
450
|
+
return made;
|
|
451
|
+
}
|
|
452
|
+
if (isTable(existing) && byHeader.has(existing) && !defined.has(existing)) {
|
|
453
|
+
defined.add(existing);
|
|
454
|
+
return existing;
|
|
455
|
+
}
|
|
456
|
+
return fail(`[${path.join(".")}] defined only once`, at);
|
|
457
|
+
};
|
|
458
|
+
try {
|
|
459
|
+
if (text.startsWith("\ufeff"))
|
|
460
|
+
i = 1;
|
|
461
|
+
let current = root;
|
|
462
|
+
for (;;) {
|
|
463
|
+
gap();
|
|
464
|
+
if (i >= text.length)
|
|
465
|
+
return ok(root);
|
|
466
|
+
const at = i;
|
|
467
|
+
if (text.startsWith("[[", i)) {
|
|
468
|
+
i += 2;
|
|
469
|
+
blank();
|
|
470
|
+
const path = dottedKey();
|
|
471
|
+
blank();
|
|
472
|
+
if (!text.startsWith("]]", i))
|
|
473
|
+
fail("]]");
|
|
474
|
+
i += 2;
|
|
475
|
+
current = header(path, true, at);
|
|
476
|
+
}
|
|
477
|
+
else if (peek() === "[") {
|
|
478
|
+
i++;
|
|
479
|
+
blank();
|
|
480
|
+
const path = dottedKey();
|
|
481
|
+
blank();
|
|
482
|
+
if (peek() !== "]")
|
|
483
|
+
fail("]");
|
|
484
|
+
i++;
|
|
485
|
+
current = header(path, false, at);
|
|
486
|
+
}
|
|
487
|
+
else {
|
|
488
|
+
const path = dottedKey();
|
|
489
|
+
blank();
|
|
490
|
+
if (peek() !== "=")
|
|
491
|
+
fail("=");
|
|
492
|
+
i++;
|
|
493
|
+
blank();
|
|
494
|
+
assign(current, path, value(0), at, false);
|
|
495
|
+
}
|
|
496
|
+
endOfLine();
|
|
497
|
+
}
|
|
498
|
+
}
|
|
499
|
+
catch (e) {
|
|
500
|
+
if (!(e instanceof Stop))
|
|
501
|
+
throw e;
|
|
502
|
+
const before = text.slice(0, e.at).split(/\r?\n/);
|
|
503
|
+
return err({ kind: "toml", line: before.length, column: (before.at(-1)?.length ?? 0) + 1, message: `expected ${e.message}` });
|
|
504
|
+
}
|
|
505
|
+
}
|
|
506
|
+
const BARE_KEY = /^[A-Za-z0-9_-]+$/;
|
|
507
|
+
/** A key as TOML writes it: bare where it can be, else a basic string. */
|
|
508
|
+
export function tomlKey(k) {
|
|
509
|
+
return BARE_KEY.test(k) ? k : tomlString(k);
|
|
510
|
+
}
|
|
511
|
+
/** A string as a TOML basic string: `"`, `\` and every control character escaped. */
|
|
512
|
+
export function tomlString(s) {
|
|
513
|
+
let out = '"';
|
|
514
|
+
for (const ch of s) {
|
|
515
|
+
const code = ch.codePointAt(0) ?? 0;
|
|
516
|
+
if (ch === '"')
|
|
517
|
+
out += '\\"';
|
|
518
|
+
else if (ch === "\\")
|
|
519
|
+
out += "\\\\";
|
|
520
|
+
else if (ch === "\n")
|
|
521
|
+
out += "\\n";
|
|
522
|
+
else if (ch === "\t")
|
|
523
|
+
out += "\\t";
|
|
524
|
+
else if (ch === "\r")
|
|
525
|
+
out += "\\r";
|
|
526
|
+
else if (code < 0x20 || code === 0x7f)
|
|
527
|
+
out += `\\u${code.toString(16).padStart(4, "0")}`;
|
|
528
|
+
else
|
|
529
|
+
out += ch;
|
|
530
|
+
}
|
|
531
|
+
return `${out}"`;
|
|
532
|
+
}
|
|
533
|
+
function scalar(v) {
|
|
534
|
+
if (typeof v === "string")
|
|
535
|
+
return tomlString(v);
|
|
536
|
+
if (typeof v === "boolean")
|
|
537
|
+
return String(v);
|
|
538
|
+
if (typeof v === "number") {
|
|
539
|
+
if (Number.isNaN(v))
|
|
540
|
+
return "nan";
|
|
541
|
+
if (!Number.isFinite(v))
|
|
542
|
+
return v > 0 ? "inf" : "-inf";
|
|
543
|
+
if (Object.is(v, -0))
|
|
544
|
+
return "-0.0";
|
|
545
|
+
if (Number.isInteger(v) && !Number.isSafeInteger(v))
|
|
546
|
+
return v.toExponential();
|
|
547
|
+
return String(v);
|
|
548
|
+
}
|
|
549
|
+
if (Array.isArray(v))
|
|
550
|
+
return `[${v.map(scalar).join(", ")}]`;
|
|
551
|
+
if (isTomlDateTime(v))
|
|
552
|
+
return v.text;
|
|
553
|
+
const entries = Object.entries(v);
|
|
554
|
+
return entries.length === 0 ? "{}" : `{ ${entries.map(([k, x]) => `${tomlKey(k)} = ${scalar(x)}`).join(", ")} }`;
|
|
555
|
+
}
|
|
556
|
+
const isTableArray = (v) => Array.isArray(v) && v.length > 0 && v.every((x) => isTomlTable(x));
|
|
557
|
+
function section(table, path, out) {
|
|
558
|
+
const entries = Object.entries(table);
|
|
559
|
+
for (const [k, v] of entries)
|
|
560
|
+
if (!isTomlTable(v) && !isTableArray(v))
|
|
561
|
+
out.push(`${tomlKey(k)} = ${scalar(v)}`);
|
|
562
|
+
for (const [k, v] of entries) {
|
|
563
|
+
const name = [...path, k].map(tomlKey).join(".");
|
|
564
|
+
if (isTomlTable(v)) {
|
|
565
|
+
out.push("", `[${name}]`);
|
|
566
|
+
section(v, [...path, k], out);
|
|
567
|
+
}
|
|
568
|
+
else if (isTableArray(v)) {
|
|
569
|
+
for (const t of v) {
|
|
570
|
+
out.push("", `[[${name}]]`);
|
|
571
|
+
section(t, [...path, k], out);
|
|
572
|
+
}
|
|
573
|
+
}
|
|
574
|
+
}
|
|
575
|
+
}
|
|
576
|
+
/** A table as TOML text: plain values first, then each table under its header and each array of tables under `[[...]]`, ending in a line break. */
|
|
577
|
+
export function toToml(table) {
|
|
578
|
+
const out = [];
|
|
579
|
+
section(table, [], out);
|
|
580
|
+
while (out[0] === "")
|
|
581
|
+
out.shift();
|
|
582
|
+
return out.length === 0 ? "" : `${out.join("\n")}\n`;
|
|
583
|
+
}
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Data as TypeScript object literals, for files a program writes for people to read and edit (keys bare where they are identifiers, strings
|
|
3
|
+
* in double quotes, two-space indentation and trailing commas), and the reader of exactly that subset, which never runs the file, so a past
|
|
4
|
+
* version from `git show` can be read safely (commons 0001-formats FR-006); the writer takes any type shaped as JSON (FR-063).
|
|
5
|
+
* Taken from Stolos's `src/archon/core/ts-literal.ts`; the reader returns a `Result` instead of throwing.
|
|
6
|
+
*
|
|
7
|
+
* @example
|
|
8
|
+
* ```ts
|
|
9
|
+
* import { parseTsLiteral, tsLiteral } from "./ts-literal.js";
|
|
10
|
+
* const text = tsLiteral({ timezone: "America/New_York", "otel-ui": true });
|
|
11
|
+
* parseTsLiteral(text); // { kind: "ok", value: { value: { timezone: "America/New_York", "otel-ui": true }, end: text.length } }
|
|
12
|
+
* ```
|
|
13
|
+
*
|
|
14
|
+
* @module
|
|
15
|
+
*/
|
|
16
|
+
import { type Result } from "@intellectual-frontiers/core";
|
|
17
|
+
/** A key that needs no quotes: an identifier (letters, digits, `_`, `$`; not starting with a digit). */
|
|
18
|
+
export declare const BARE_KEY: RegExp;
|
|
19
|
+
/** A key as TypeScript writes it: bare where it can be, else a double-quoted string. */
|
|
20
|
+
export declare function tsKey(key: string): string;
|
|
21
|
+
/** A value that {@link parseTsLiteral} reads back, and so {@link tsLiteral} writes: what JSON holds. */
|
|
22
|
+
export type Literal = null | boolean | number | string | readonly Literal[] | {
|
|
23
|
+
readonly [key: string]: Literal | undefined;
|
|
24
|
+
};
|
|
25
|
+
/**
|
|
26
|
+
* `T` itself where `T` is shaped as JSON at every depth, else a type `T` is not assignable to, so that a parameter `T & LiteralShape<T>`
|
|
27
|
+
* takes any JSON-shaped type (FR-063), an interface with no index signature included: strings, numbers, booleans and `null`; arrays and
|
|
28
|
+
* tuples of such values; objects whose string keys hold such values, `undefined` allowed only as an optional property's. A function, a
|
|
29
|
+
* `Date`, a `Map`, a `bigint`, a symbol or `unknown` anywhere makes it `never` there.
|
|
30
|
+
*/
|
|
31
|
+
export type LiteralShape<T> = T extends Literal ? T : T extends readonly unknown[] ? {
|
|
32
|
+
readonly [I in keyof T]: LiteralShape<T[I]>;
|
|
33
|
+
} : T extends (...args: never) => unknown ? never : T extends object ? {
|
|
34
|
+
readonly [K in keyof T]: K extends string ? PropertyShape<T[K]> : never;
|
|
35
|
+
} : never;
|
|
36
|
+
/** A property's value shaped as JSON: `undefined` allowed, as an absent optional property, beside a JSON-shaped value. */
|
|
37
|
+
type PropertyShape<V> = undefined extends V ? LiteralShape<Exclude<V, undefined>> | undefined : LiteralShape<V>;
|
|
38
|
+
/**
|
|
39
|
+
* A value as a TypeScript literal, indented for `depth` (two spaces each). It takes any value whose type is shaped as JSON (FR-063), an
|
|
40
|
+
* interface with no index signature included, and refuses at compile time a value holding a function, a `Date`, a `bigint` or another
|
|
41
|
+
* type JSON has not. Objects and arrays span lines (empty ones stay `{}` and `[]`); properties that are `undefined` are left out, as
|
|
42
|
+
* `JSON.stringify` leaves them out. A number that is not finite is written `null`, as JSON writes it. (The check is on the parameter,
|
|
43
|
+
* `T & LiteralShape<T>`, because TypeScript refuses `T extends LiteralShape<T>` as a circular constraint.)
|
|
44
|
+
*/
|
|
45
|
+
export declare function tsLiteral<T>(value: T & LiteralShape<T>, depth?: number): string;
|
|
46
|
+
/** Where a text stopped being a literal, and what was expected there. */
|
|
47
|
+
export type LiteralError = {
|
|
48
|
+
readonly kind: "literal";
|
|
49
|
+
readonly at: number;
|
|
50
|
+
readonly expected: string;
|
|
51
|
+
};
|
|
52
|
+
/**
|
|
53
|
+
* The value of a literal {@link tsLiteral} wrote, starting at `start`, and where it ended: objects with bare or quoted keys, arrays,
|
|
54
|
+
* double-quoted strings, numbers, `true`, `false` and `null`, with trailing commas and `//` comments. Anything else is an error.
|
|
55
|
+
*/
|
|
56
|
+
export declare function parseTsLiteral(text: string, start?: number): Result<{
|
|
57
|
+
readonly value: Literal;
|
|
58
|
+
readonly end: number;
|
|
59
|
+
}, LiteralError>;
|
|
60
|
+
/** The value of `export const <name>[: Type] = <literal>;` in a file {@link tsLiteral} wrote, or why it cannot be read. */
|
|
61
|
+
export declare function exportedLiteral(source: string, name: string): Result<Literal, LiteralError>;
|
|
62
|
+
export {};
|