@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
@@ -0,0 +1,183 @@
1
+ // Spec: 0001-formats FR-006
2
+ /**
3
+ * Data as TypeScript object literals, for files a program writes for people to read and edit (keys bare where they are identifiers, strings
4
+ * in double quotes, two-space indentation and trailing commas), and the reader of exactly that subset, which never runs the file, so a past
5
+ * version from `git show` can be read safely (commons 0001-formats FR-006); the writer takes any type shaped as JSON (FR-063).
6
+ * Taken from Stolos's `src/archon/core/ts-literal.ts`; the reader returns a `Result` instead of throwing.
7
+ *
8
+ * @example
9
+ * ```ts
10
+ * import { parseTsLiteral, tsLiteral } from "./ts-literal.ts";
11
+ * const text = tsLiteral({ timezone: "America/New_York", "otel-ui": true });
12
+ * parseTsLiteral(text); // { kind: "ok", value: { value: { timezone: "America/New_York", "otel-ui": true }, end: text.length } }
13
+ * ```
14
+ *
15
+ * @module
16
+ */
17
+ import { err, ok, type Result } from "@intellectual-frontiers/core";
18
+
19
+ /** A key that needs no quotes: an identifier (letters, digits, `_`, `$`; not starting with a digit). */
20
+ export const BARE_KEY: RegExp = /^[A-Za-z_$][A-Za-z0-9_$]*$/;
21
+
22
+ /** A key as TypeScript writes it: bare where it can be, else a double-quoted string. */
23
+ export function tsKey(key: string): string {
24
+ return BARE_KEY.test(key) ? key : JSON.stringify(key);
25
+ }
26
+
27
+ /** A value that {@link parseTsLiteral} reads back, and so {@link tsLiteral} writes: what JSON holds. */
28
+ export type Literal = null | boolean | number | string | readonly Literal[] | { readonly [key: string]: Literal | undefined };
29
+
30
+ /**
31
+ * `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>`
32
+ * takes any JSON-shaped type (FR-063), an interface with no index signature included: strings, numbers, booleans and `null`; arrays and
33
+ * tuples of such values; objects whose string keys hold such values, `undefined` allowed only as an optional property's. A function, a
34
+ * `Date`, a `Map`, a `bigint`, a symbol or `unknown` anywhere makes it `never` there.
35
+ */
36
+ export type LiteralShape<T> = T extends Literal
37
+ ? T
38
+ : T extends readonly unknown[]
39
+ ? { readonly [I in keyof T]: LiteralShape<T[I]> }
40
+ : T extends (...args: never) => unknown
41
+ ? never
42
+ : T extends object
43
+ ? { readonly [K in keyof T]: K extends string ? PropertyShape<T[K]> : never }
44
+ : never;
45
+
46
+ /** A property's value shaped as JSON: `undefined` allowed, as an absent optional property, beside a JSON-shaped value. */
47
+ type PropertyShape<V> = undefined extends V ? LiteralShape<Exclude<V, undefined>> | undefined : LiteralShape<V>;
48
+
49
+ /**
50
+ * 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
51
+ * interface with no index signature included, and refuses at compile time a value holding a function, a `Date`, a `bigint` or another
52
+ * type JSON has not. Objects and arrays span lines (empty ones stay `{}` and `[]`); properties that are `undefined` are left out, as
53
+ * `JSON.stringify` leaves them out. A number that is not finite is written `null`, as JSON writes it. (The check is on the parameter,
54
+ * `T & LiteralShape<T>`, because TypeScript refuses `T extends LiteralShape<T>` as a circular constraint.)
55
+ */
56
+ export function tsLiteral<T>(value: T & LiteralShape<T>, depth = 0): string {
57
+ return write(value, depth);
58
+ }
59
+
60
+ // The type parameter of `tsLiteral` already holds the value to JSON's shape; here it is walked as what it is at run time.
61
+ function write(value: unknown, depth: number): string {
62
+ const pad = " ".repeat(depth + 1);
63
+ const end = " ".repeat(depth);
64
+ if (value === null || value === undefined) return "null";
65
+ if (Array.isArray(value)) {
66
+ const items: readonly unknown[] = value;
67
+ if (items.length === 0) return "[]";
68
+ return `[\n${items.map((v) => `${pad}${write(v, depth + 1)},\n`).join("")}${end}]`;
69
+ }
70
+ if (typeof value === "object") {
71
+ const entries = Object.entries(value).filter((e) => e[1] !== undefined);
72
+ if (entries.length === 0) return "{}";
73
+ return `{\n${entries.map(([k, v]) => `${pad}${tsKey(k)}: ${write(v, depth + 1)},\n`).join("")}${end}}`;
74
+ }
75
+ if (typeof value === "string") return JSON.stringify(value);
76
+ if (typeof value === "number") return Number.isFinite(value) ? JSON.stringify(value) : "null";
77
+ if (typeof value === "boolean") return String(value);
78
+ return "null";
79
+ }
80
+
81
+ /** Where a text stopped being a literal, and what was expected there. */
82
+ export type LiteralError = { readonly kind: "literal"; readonly at: number; readonly expected: string };
83
+
84
+ class Stop extends Error {
85
+ readonly at: number;
86
+ readonly expected: string;
87
+ constructor(at: number, expected: string) {
88
+ super(`not a literal at ${at}: expected ${expected}`);
89
+ this.at = at;
90
+ this.expected = expected;
91
+ }
92
+ }
93
+
94
+ /**
95
+ * The value of a literal {@link tsLiteral} wrote, starting at `start`, and where it ended: objects with bare or quoted keys, arrays,
96
+ * double-quoted strings, numbers, `true`, `false` and `null`, with trailing commas and `//` comments. Anything else is an error.
97
+ */
98
+ export function parseTsLiteral(text: string, start = 0): Result<{ readonly value: Literal; readonly end: number }, LiteralError> {
99
+ let i = start;
100
+ const ws = (): void => {
101
+ for (;;) {
102
+ while (i < text.length && /\s/.test(text[i] ?? "")) i++;
103
+ if (!text.startsWith("//", i)) return;
104
+ while (i < text.length && text[i] !== "\n") i++;
105
+ }
106
+ };
107
+ const fail = (expected: string): never => {
108
+ throw new Stop(i, expected);
109
+ };
110
+ const str = (): string => {
111
+ const m = /^"(?:[^"\\\n]|\\.)*"/.exec(text.slice(i));
112
+ if (m === null) return fail("a complete string");
113
+ i += m[0].length;
114
+ const s: unknown = JSON.parse(m[0]);
115
+ return typeof s === "string" ? s : fail("a string");
116
+ };
117
+ const value = (): Literal => {
118
+ ws();
119
+ const c = text[i];
120
+ if (c === "{") {
121
+ i++;
122
+ const o: { [key: string]: Literal } = {};
123
+ for (;;) {
124
+ ws();
125
+ if (text[i] === "}") {
126
+ i++;
127
+ return o;
128
+ }
129
+ let k: string;
130
+ if (text[i] === '"') k = str();
131
+ else {
132
+ const m = /^[A-Za-z_$][A-Za-z0-9_$]*/.exec(text.slice(i));
133
+ if (m === null) return fail("a key");
134
+ k = m[0];
135
+ i += k.length;
136
+ }
137
+ ws();
138
+ if (text[i] !== ":") fail("a colon");
139
+ i++;
140
+ Object.defineProperty(o, k, { value: value(), enumerable: true, writable: true, configurable: true });
141
+ ws();
142
+ if (text[i] === ",") i++;
143
+ else if (text[i] !== "}") fail("a comma or }");
144
+ }
145
+ }
146
+ if (c === "[") {
147
+ i++;
148
+ const a: Literal[] = [];
149
+ for (;;) {
150
+ ws();
151
+ if (text[i] === "]") {
152
+ i++;
153
+ return a;
154
+ }
155
+ a.push(value());
156
+ ws();
157
+ if (text[i] === ",") i++;
158
+ else if (text[i] !== "]") fail("a comma or ]");
159
+ }
160
+ }
161
+ if (c === '"') return str();
162
+ const m = /^(-?\d+(\.\d+)?([eE][+-]?\d+)?|true|false|null)/.exec(text.slice(i));
163
+ if (m === null) return fail("a value");
164
+ i += m[0].length;
165
+ const v: unknown = JSON.parse(m[0]);
166
+ return typeof v === "number" || typeof v === "boolean" || v === null ? v : fail("a value");
167
+ };
168
+ try {
169
+ const v = value();
170
+ return ok({ value: v, end: i });
171
+ } catch (e) {
172
+ if (e instanceof Stop) return err({ kind: "literal", at: e.at, expected: e.expected });
173
+ throw e;
174
+ }
175
+ }
176
+
177
+ /** The value of `export const <name>[: Type] = <literal>;` in a file {@link tsLiteral} wrote, or why it cannot be read. */
178
+ export function exportedLiteral(source: string, name: string): Result<Literal, LiteralError> {
179
+ const m = new RegExp(`export const ${name}(?:\\s*:\\s*[A-Za-z_$][\\w$.<>, \\[\\]]*)?\\s*=\\s*`).exec(source);
180
+ if (m === null) return err({ kind: "literal", at: 0, expected: `export const ${name}` });
181
+ const r = parseTsLiteral(source, m.index + m[0].length);
182
+ return r.kind === "ok" ? ok(r.value.value) : r;
183
+ }
package/src/xml.ts ADDED
@@ -0,0 +1,291 @@
1
+ // Spec: 0001-formats FR-004
2
+ /**
3
+ * XML as a typed tree of elements and text, written with every value escaped (no document is a template of values) and read with no
4
+ * outside package (commons 0001-formats FR-004). The reader takes elements, attributes in either quote, the five named entities
5
+ * and character references, CDATA, comments, processing instructions and the XML declaration, checks that every element is closed by its
6
+ * own name, and refuses a document type with an internal subset, so no entity is ever expanded (no "billion laughs", no external entity).
7
+ * Names are kept as written (`dc:title`); the finders match a name with or without its prefix. Taken from erga's `lib/ts/xml`, whose
8
+ * reader was `@std/xml`.
9
+ *
10
+ * @example
11
+ * ```ts
12
+ * import { el, readXml, textOf, writeXml } from "./xml.ts";
13
+ * const doc = writeXml(el("note", [el("to", ["Ada & Charles"])], [["lang", "en"]]));
14
+ * // '<?xml version="1.0" encoding="UTF-8"?>\n<note lang="en"><to>Ada &amp; Charles</to></note>'
15
+ * const back = readXml(doc);
16
+ * if (back.kind === "ok") textOf(back.value); // "Ada & Charles"
17
+ * ```
18
+ *
19
+ * @module
20
+ */
21
+ import { absurd, err, ok, type Result } from "@intellectual-frontiers/core";
22
+
23
+ /** An element: its name as written, its attributes in order, and its children. */
24
+ export type XmlElement = {
25
+ readonly kind: "element";
26
+ readonly name: string;
27
+ readonly attributes: readonly (readonly [string, string])[];
28
+ readonly children: readonly XmlNode[];
29
+ };
30
+
31
+ /** Text, its entities and references already replaced. */
32
+ export type XmlText = { readonly kind: "text"; readonly text: string };
33
+
34
+ /** A node of an XML document. */
35
+ export type XmlNode = XmlElement | XmlText;
36
+
37
+ /** What an element may be given as a child: a node, or a value written as text; `undefined` gives nothing. */
38
+ export type XmlChild = XmlNode | string | number | boolean | undefined;
39
+
40
+ const asNodes = (c: XmlChild): readonly XmlNode[] =>
41
+ c === undefined ? [] : typeof c === "object" ? [c] : [{ kind: "text", text: String(c) }];
42
+
43
+ /** An element. */
44
+ export function el(name: string, children: readonly XmlChild[] = [], attributes: readonly (readonly [string, string])[] = []): XmlElement {
45
+ return { kind: "element", name, attributes, children: children.flatMap(asNodes) };
46
+ }
47
+
48
+ /** An element holding one value, or nothing where the value is absent. */
49
+ export function leaf(name: string, value: string | number | boolean | undefined): XmlElement | undefined {
50
+ return value === undefined ? undefined : el(name, [value]);
51
+ }
52
+
53
+ const FORBIDDEN = new RegExp(
54
+ `[${String.fromCharCode(0)}-${String.fromCharCode(8)}${String.fromCharCode(11, 12)}${String.fromCharCode(14)}-${String.fromCharCode(31)}\\ufffe\\uffff]`,
55
+ "g",
56
+ );
57
+
58
+ /** A value as XML text or an attribute's value: `&`, `<`, `>`, `"` and `'` escaped, and the characters XML 1.0 forbids removed. */
59
+ export function escapeXml(s: string): string {
60
+ return s
61
+ .replace(FORBIDDEN, "")
62
+ .replaceAll("&", "&amp;")
63
+ .replaceAll("<", "&lt;")
64
+ .replaceAll(">", "&gt;")
65
+ .replaceAll('"', "&quot;")
66
+ .replaceAll("'", "&apos;");
67
+ }
68
+
69
+ /** A node as XML text, with no declaration. */
70
+ export function writeNode(n: XmlNode): string {
71
+ switch (n.kind) {
72
+ case "text":
73
+ return escapeXml(n.text);
74
+ case "element": {
75
+ const attrs = n.attributes.map(([k, v]) => ` ${k}="${escapeXml(v)}"`).join("");
76
+ return n.children.length === 0 ? `<${n.name}${attrs}/>` : `<${n.name}${attrs}>${n.children.map(writeNode).join("")}</${n.name}>`;
77
+ }
78
+ default:
79
+ return absurd(n);
80
+ }
81
+ }
82
+
83
+ /** A whole document: the XML declaration, then its root. */
84
+ export function writeXml(root: XmlElement): string {
85
+ return `<?xml version="1.0" encoding="UTF-8"?>\n${writeNode(root)}`;
86
+ }
87
+
88
+ /** Where a text stops being XML this reader takes, and why. Lines and columns count from 1. */
89
+ export type XmlError = { readonly kind: "xml"; readonly line: number; readonly column: number; readonly message: string };
90
+
91
+ class Stop extends Error {
92
+ readonly at: number;
93
+ constructor(at: number, message: string) {
94
+ super(message);
95
+ this.at = at;
96
+ }
97
+ }
98
+
99
+ const NAME_START = /[:A-Z_a-z\p{L}\p{Nl}]/u;
100
+ const NAME_PART = /[-.0-9:A-Z_a-z\p{L}\p{Nl}\p{Mn}\p{Mc}\p{Nd}\p{Pc}\u00b7]/u;
101
+ const ENTITIES: Readonly<Record<string, string>> = { amp: "&", lt: "<", gt: ">", quot: '"', apos: "'" };
102
+
103
+ /** How to read: whether text that is only white space between elements is kept (it is dropped by default). */
104
+ export type ReadXmlOptions = { readonly keepWhitespace?: boolean };
105
+
106
+ /** A document read: its root element; or where and why it is not XML this reader takes. */
107
+ export function readXml(text: string, options: ReadXmlOptions = {}): Result<XmlElement, XmlError> {
108
+ let i = text.startsWith("\ufeff") ? 1 : 0;
109
+ const fail = (message: string, at = i): never => {
110
+ throw new Stop(at, message);
111
+ };
112
+ const space = (): void => {
113
+ while (/[ \t\r\n]/.test(text[i] ?? "")) i++;
114
+ };
115
+ const expect = (s: string): void => {
116
+ if (!text.startsWith(s, i)) fail(`expected ${JSON.stringify(s)}`);
117
+ i += s.length;
118
+ };
119
+ const charAt = (at: number): string => {
120
+ const cp = text.codePointAt(at);
121
+ return cp === undefined ? "" : String.fromCodePoint(cp);
122
+ };
123
+ const name = (): string => {
124
+ const start = i;
125
+ if (!NAME_START.test(charAt(i))) fail("expected a name");
126
+ while (i < text.length && NAME_PART.test(charAt(i))) i += charAt(i).length;
127
+ return text.slice(start, i);
128
+ };
129
+ const decode = (raw: string, at: number): string =>
130
+ raw.replace(/&([^;&]*);?/g, (whole: string, ref: string, offset: number) => {
131
+ if (!whole.endsWith(";")) fail("an entity reference that ends with ;", at + offset);
132
+ const named = ENTITIES[ref];
133
+ if (named !== undefined) return named;
134
+ const m = /^#(?:x([0-9a-fA-F]+)|([0-9]+))$/.exec(ref);
135
+ const code = m === null ? Number.NaN : m[1] !== undefined ? Number.parseInt(m[1], 16) : Number(m[2]);
136
+ if (!Number.isInteger(code) || code < 1 || code > 0x10ffff)
137
+ fail(`a known entity or a character reference, not &${ref};`, at + offset);
138
+ return String.fromCodePoint(code);
139
+ });
140
+ const misc = (): void => {
141
+ for (;;) {
142
+ space();
143
+ if (text.startsWith("<!--", i)) {
144
+ const end = text.indexOf("-->", i + 4);
145
+ if (end < 0) fail("a comment that is closed");
146
+ i = end + 3;
147
+ } else if (text.startsWith("<?", i)) {
148
+ const end = text.indexOf("?>", i + 2);
149
+ if (end < 0) fail("a processing instruction that is closed");
150
+ i = end + 2;
151
+ } else if (text.startsWith("<!DOCTYPE", i)) {
152
+ const end = text.indexOf(">", i);
153
+ if (end < 0) fail("a document type that is closed");
154
+ if (text.slice(i, end).includes("[")) fail("a document type with no internal subset (no entity is expanded)");
155
+ i = end + 1;
156
+ } else return;
157
+ }
158
+ };
159
+ const element = (depth: number): XmlElement => {
160
+ if (depth > 512) fail("less nesting (more than 512 levels)");
161
+ expect("<");
162
+ const tag = name();
163
+ const attributes: [string, string][] = [];
164
+ for (;;) {
165
+ const before = i;
166
+ space();
167
+ if (text.startsWith("/>", i)) {
168
+ i += 2;
169
+ return { kind: "element", name: tag, attributes, children: [] };
170
+ }
171
+ if (text[i] === ">") {
172
+ i++;
173
+ break;
174
+ }
175
+ if (i === before) fail("white space before an attribute");
176
+ const keyAt = i;
177
+ const key = name();
178
+ if (attributes.some(([k]) => k === key)) fail(`the attribute ${key} only once`, keyAt);
179
+ space();
180
+ expect("=");
181
+ space();
182
+ const quote = text[i];
183
+ if (quote !== '"' && quote !== "'") fail("a quoted attribute value");
184
+ const end = text.indexOf(quote ?? "", i + 1);
185
+ if (end < 0) fail("a closing quote");
186
+ const raw = text.slice(i + 1, end);
187
+ if (raw.includes("<")) fail("no < in an attribute value", i + 1 + raw.indexOf("<"));
188
+ attributes.push([key, decode(raw, i + 1).replace(/[\t\n\r]/g, " ")]);
189
+ i = end + 1;
190
+ }
191
+ const children: XmlNode[] = [];
192
+ let buffer = "";
193
+ let whitespaceOnly = true;
194
+ const flush = (): void => {
195
+ if (buffer !== "" && (options.keepWhitespace === true || !whitespaceOnly)) children.push({ kind: "text", text: buffer });
196
+ buffer = "";
197
+ whitespaceOnly = true;
198
+ };
199
+ for (;;) {
200
+ if (i >= text.length) fail(`the end tag </${tag}>`);
201
+ if (text.startsWith("</", i)) {
202
+ flush();
203
+ i += 2;
204
+ const at = i;
205
+ const closing = name();
206
+ if (closing !== tag) fail(`</${tag}>, not </${closing}>`, at);
207
+ space();
208
+ expect(">");
209
+ return { kind: "element", name: tag, attributes, children };
210
+ }
211
+ if (text.startsWith("<![CDATA[", i)) {
212
+ const end = text.indexOf("]]>", i + 9);
213
+ if (end < 0) fail("a CDATA section that is closed");
214
+ buffer += text.slice(i + 9, end);
215
+ whitespaceOnly = false;
216
+ i = end + 3;
217
+ } else if (text.startsWith("<!--", i)) {
218
+ const end = text.indexOf("-->", i + 4);
219
+ if (end < 0) fail("a comment that is closed");
220
+ i = end + 3;
221
+ } else if (text.startsWith("<?", i)) {
222
+ const end = text.indexOf("?>", i + 2);
223
+ if (end < 0) fail("a processing instruction that is closed");
224
+ i = end + 2;
225
+ } else if (text[i] === "<") {
226
+ flush();
227
+ children.push(element(depth + 1));
228
+ } else {
229
+ const next = text.indexOf("<", i);
230
+ const end = next < 0 ? text.length : next;
231
+ const raw = text.slice(i, end);
232
+ const decoded = decode(raw, i);
233
+ if (!/^[ \t\r\n]*$/.test(decoded)) whitespaceOnly = false;
234
+ buffer += decoded;
235
+ i = end;
236
+ }
237
+ }
238
+ };
239
+ try {
240
+ misc();
241
+ if (text[i] !== "<") fail("a root element");
242
+ const root = element(0);
243
+ misc();
244
+ if (i < text.length) fail("nothing after the root element");
245
+ return ok(root);
246
+ } catch (e) {
247
+ if (!(e instanceof Stop)) throw e;
248
+ const before = text.slice(0, e.at).split(/\r\n|[\n\r]/);
249
+ return err({ kind: "xml", line: before.length, column: (before.at(-1)?.length ?? 0) + 1, message: e.message });
250
+ }
251
+ }
252
+
253
+ /** An XML error as one line: `3:14: expected a name`. */
254
+ export function formatXmlError(e: XmlError): string {
255
+ return `${e.line}:${e.column}: ${e.message}`;
256
+ }
257
+
258
+ /** A name without its prefix: `title` for `dc:title`. */
259
+ export function localName(name: string): string {
260
+ const at = name.indexOf(":");
261
+ return at < 0 ? name : name.slice(at + 1);
262
+ }
263
+
264
+ const named = (n: XmlNode, name: string): n is XmlElement => n.kind === "element" && (n.name === name || localName(n.name) === name);
265
+
266
+ /** The child elements of a node named `name` (with or without a prefix). */
267
+ export function children(n: XmlNode, name: string): readonly XmlElement[] {
268
+ return n.kind === "element" ? n.children.filter((c): c is XmlElement => named(c, name)) : [];
269
+ }
270
+
271
+ /** The first child element named `name`. */
272
+ export function child(n: XmlNode, name: string): XmlElement | undefined {
273
+ return children(n, name)[0];
274
+ }
275
+
276
+ /** Every element below a node named `name`, in document order. */
277
+ export function descendants(n: XmlNode, name: string): readonly XmlElement[] {
278
+ if (n.kind !== "element") return [];
279
+ return n.children.flatMap((c) => [...(named(c, name) ? [c] : []), ...descendants(c, name)]);
280
+ }
281
+
282
+ /** All the text a node holds. */
283
+ export function textOf(n: XmlNode | undefined): string {
284
+ if (n === undefined) return "";
285
+ return n.kind === "text" ? n.text : n.children.map(textOf).join("");
286
+ }
287
+
288
+ /** An attribute's value, by its name with or without a prefix. */
289
+ export function attribute(n: XmlNode | undefined, name: string): string | undefined {
290
+ return n?.kind === "element" ? n.attributes.find(([k]) => k === name || localName(k) === name)?.[1] : undefined;
291
+ }