@intellectual-frontiers/formats 0.0.0-stage → 0.1.0

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/glob.ts ADDED
@@ -0,0 +1,210 @@
1
+ // Spec: 0001-formats FR-017
2
+ /**
3
+ * Path globs as regular expressions, on `/` paths, with the meaning `@std/path`'s `globToRegExp` gives them (commons
4
+ * 0001-formats FR-017); `fs.expandGlob` walks a folder with what this gives.
5
+ *
6
+ * The API, which `fs.expandGlob` builds on and which stays as it is:
7
+ * - `globToRegExp(glob, { extended?, globstar?, caseInsensitive? })`: the glob as a `RegExp` anchored at both ends, or why it is refused.
8
+ * - `matchGlob(glob, path, options?)`: whether the path matches, or why the glob is refused.
9
+ * - `isGlob(text)`: whether the text holds anything a glob gives a meaning to (else it names one path).
10
+ * - `globRoot(glob)`: the leading folders (every segment but the last) with no glob character, where a walk starts (`.` if none).
11
+ *
12
+ * The syntax, one segment (between `/`) at a time:
13
+ * - `*` any characters but `/`; `?` one character but `/` (where `@std/path` lets `?` and `[!a]` match a `/`, these do not);
14
+ * - `**` alone in its segment (with `globstar`, the default): any number of segments, none included, so `src/**\/*.ts` matches
15
+ * `src/a.ts` and `src/a/b/c.ts`; elsewhere it is `*`;
16
+ * - `[abc]`, `[a-z]`, `[!abc]` (not one of, nor `/`), `[[:alpha:]]` and the other POSIX classes; `[^a]` is `^` or `a`, as in `@std/path`;
17
+ * - `{a,b}` either alternative (always on);
18
+ * - with `extended` (the default): `?(a|b)` at most one, `*(a|b)` any number, `+(a|b)` at least one, `@(a|b)` exactly one, `!(a|b)` none;
19
+ * - `\` takes the next character as it is.
20
+ *
21
+ * A segment with an unclosed `[`, `{` or `(`, or ending in `\`, is taken as it is written. Separators run together (`a//b` is `a/b`), a
22
+ * trailing one is optional, and the empty glob matches nothing. A glob that begins with `!` not followed by `(` is refused: it reads as
23
+ * the negation of a gitignore or a shell, which a regular expression of the path cannot mean.
24
+ *
25
+ * @example
26
+ * ```ts
27
+ * import { globToRegExp, matchGlob } from "./glob.ts";
28
+ * matchGlob("src/**\/*.ts", "src/a/b/c.ts"); // { kind: "ok", value: true }
29
+ * matchGlob("src/**\/*.ts", "srcx/a.ts"); // { kind: "ok", value: false }
30
+ * globToRegExp("!x"); // { kind: "err", error: { kind: "negated", glob: "!x" } }
31
+ * ```
32
+ *
33
+ * @module
34
+ */
35
+ import { err, ok, type Result } from "@intellectual-frontiers/core";
36
+
37
+ /** How a glob is read: `extended` (extglob groups, default true), `globstar` (`**` across segments, default true), `caseInsensitive`. */
38
+ export type GlobOptions = {
39
+ readonly extended?: boolean;
40
+ readonly globstar?: boolean;
41
+ readonly caseInsensitive?: boolean;
42
+ };
43
+
44
+ /** Why a glob is refused: it begins with a `!` that negates nothing a path expression can say. */
45
+ export type GlobError = { readonly kind: "negated"; readonly glob: string };
46
+
47
+ /** A refused glob as one sentence. */
48
+ export function formatGlobError(e: GlobError): string {
49
+ return `the glob ${JSON.stringify(e.glob)} begins with "!", a negation a path glob cannot mean; escape it as "\\!" to match a "!"`;
50
+ }
51
+
52
+ const SEP = "/+";
53
+ const SEP_MAYBE = "/*";
54
+ const WILDCARD = "[^/]*";
55
+ const GLOBSTAR = "(?:[^/]*(?:/|$)+)*";
56
+ const ESCAPE_OUTSIDE = new Set(["!", "$", "(", ")", "*", "+", ".", "=", "?", "[", "\\", "^", "{", "|"]);
57
+ const ESCAPE_INSIDE = new Set(["-", "\\", "]"]);
58
+ const CLASSES: ReadonlyMap<string, string> = new Map([
59
+ ["alnum", "\\dA-Za-z"],
60
+ ["alpha", "A-Za-z"],
61
+ ["ascii", "\\x00-\\x7F"],
62
+ ["blank", "\\t "],
63
+ ["cntrl", "\\x00-\\x1F\\x7F"],
64
+ ["digit", "\\d"],
65
+ ["graph", "\\x21-\\x7E"],
66
+ ["lower", "a-z"],
67
+ ["print", "\\x20-\\x7E"],
68
+ ["punct", "!-\\/:-@\\[-`{-~"],
69
+ ["space", "\\s\\v"],
70
+ ["upper", "A-Z"],
71
+ ["word", "\\w"],
72
+ ["xdigit", "\\dA-Fa-f"],
73
+ ]);
74
+
75
+ const literal = (c: string): string => (ESCAPE_OUTSIDE.has(c) ? `\\${c}` : c);
76
+
77
+ type Group = "brace" | "?" | "*" | "+" | "@" | "!";
78
+
79
+ /** One segment of a glob (no `/` in it) as a regular expression, and whether it is a globstar; undefined where it does not close. */
80
+ function segment(text: string, extended: boolean, globstar: boolean): { readonly source: string; readonly star: boolean } | undefined {
81
+ let out = "";
82
+ const groups: Group[] = [];
83
+ let inClass = false;
84
+ for (let i = 0; i < text.length; i++) {
85
+ const c = text[i] ?? "";
86
+ const next = text[i + 1];
87
+ if (c === "\\") {
88
+ const e = text[i + 1];
89
+ if (e === undefined) return undefined;
90
+ i++;
91
+ out += inClass ? (ESCAPE_INSIDE.has(e) ? `\\${e}` : e) : literal(e);
92
+ continue;
93
+ }
94
+ if (inClass) {
95
+ if (c === "]") {
96
+ inClass = false;
97
+ out += "]";
98
+ } else if (c === "[" && next === ":") {
99
+ const end = text.indexOf(":]", i + 2);
100
+ const cls = end < 0 ? undefined : CLASSES.get(text.slice(i + 2, end));
101
+ if (end >= 0 && cls !== undefined) {
102
+ out += cls;
103
+ i = end + 1;
104
+ } else out += "\\[";
105
+ } else out += c === "\\" || c === "^" ? `\\${c}` : c;
106
+ continue;
107
+ }
108
+ const top = groups[groups.length - 1];
109
+ if (c === "[") {
110
+ inClass = true;
111
+ out += "[";
112
+ if (next === "!") {
113
+ out += "^/";
114
+ i++;
115
+ } else if (next === "^") {
116
+ out += "\\^";
117
+ i++;
118
+ }
119
+ } else if (extended && next === "(" && (c === "?" || c === "*" || c === "+" || c === "@" || c === "!")) {
120
+ groups.push(c);
121
+ out += c === "!" ? "(?!" : "(?:";
122
+ i++;
123
+ } else if (c === ")" && top !== undefined && top !== "brace") {
124
+ groups.pop();
125
+ out += top === "!" ? `)${WILDCARD}` : top === "@" ? ")" : `)${top}`;
126
+ } else if (c === "|" && top !== undefined && top !== "brace") out += "|";
127
+ else if (c === "{") {
128
+ groups.push("brace");
129
+ out += "(?:";
130
+ } else if (c === "}" && top === "brace") {
131
+ groups.pop();
132
+ out += ")";
133
+ } else if (c === "," && top === "brace") out += "|";
134
+ else if (c === "?") out += "[^/]";
135
+ else if (c === "*") {
136
+ let stars = 1;
137
+ while (text[i + 1] === "*") {
138
+ i++;
139
+ stars++;
140
+ }
141
+ if (globstar && stars === 2 && text.length === 2) return { source: GLOBSTAR, star: true };
142
+ out += WILDCARD;
143
+ } else out += literal(c);
144
+ }
145
+ return groups.length > 0 || inClass ? undefined : { source: out, star: false };
146
+ }
147
+
148
+ /**
149
+ * The glob as a regular expression of a whole `/` path, as `@std/path`'s `globToRegExp` makes it (see the module's documentation for the
150
+ * syntax); refused where it begins with a `!` that is not an extglob `!(...)`.
151
+ */
152
+ export function globToRegExp(glob: string, options: GlobOptions = {}): Result<RegExp, GlobError> {
153
+ const extended = options.extended ?? true;
154
+ const globstar = options.globstar ?? true;
155
+ if (glob.startsWith("!") && !(extended && glob[1] === "(")) return err({ kind: "negated", glob });
156
+ if (glob === "") return ok(/(?!)/);
157
+ const leading = glob.startsWith("/");
158
+ const body = glob.replace(/^\/+/, "").replace(/\/+$/, "");
159
+ let source = leading ? SEP : "";
160
+ const parts = body === "" ? [] : body.split(/\/+/);
161
+ parts.forEach((part, n) => {
162
+ const s = segment(part, extended, globstar);
163
+ if (s?.star === true) {
164
+ source += s.source;
165
+ return;
166
+ }
167
+ source += s === undefined ? [...part].map(literal).join("") : s.source;
168
+ source += n < parts.length - 1 ? SEP : SEP_MAYBE;
169
+ });
170
+ return ok(new RegExp(`^${source}$`, options.caseInsensitive === true ? "i" : ""));
171
+ }
172
+
173
+ /** Whether the `/` path matches the glob (see `globToRegExp`), or why the glob is refused. */
174
+ export function matchGlob(glob: string, path: string, options: GlobOptions = {}): Result<boolean, GlobError> {
175
+ const re = globToRegExp(glob, options);
176
+ return re.kind === "err" ? re : ok(re.value.test(path));
177
+ }
178
+
179
+ /**
180
+ * Whether the text holds anything a glob gives a meaning to, not escaped: `*`, `?`, a closed `[...]` or `{...}`, an extglob group, or a
181
+ * leading `!`. Text that is not a glob names one path, which a caller can take as it is.
182
+ */
183
+ export function isGlob(text: string): boolean {
184
+ if (text.startsWith("!")) return true;
185
+ for (let i = 0; i < text.length; i++) {
186
+ const c = text[i];
187
+ if (c === "\\") i++;
188
+ else if (c === "*" || c === "?") return true;
189
+ else if (c === "[" && text.indexOf("]", i + 2) > 0) return true;
190
+ else if (c === "{" && text.indexOf("}", i + 1) > 0) return true;
191
+ else if ((c === "+" || c === "@" || c === "!") && text[i + 1] === "(" && text.indexOf(")", i + 2) > 0) return true;
192
+ }
193
+ return false;
194
+ }
195
+
196
+ /**
197
+ * The leading segments of a glob, its last one never among them, in which nothing is a glob, joined by `/`: the folder a walk for its
198
+ * matches starts from. `.` where there are none; `/` for an absolute glob with none. Escapes in these segments are taken off.
199
+ */
200
+ export function globRoot(glob: string): string {
201
+ const absolute = glob.startsWith("/");
202
+ const parts = glob.split(/\/+/).filter((p) => p !== "");
203
+ const plain: string[] = [];
204
+ for (const p of parts.slice(0, -1)) {
205
+ if (isGlob(p)) break;
206
+ plain.push(p.replace(/\\(.)/g, "$1"));
207
+ }
208
+ if (plain.length === 0) return absolute ? "/" : ".";
209
+ return `${absolute ? "/" : ""}${plain.join("/")}`;
210
+ }
package/src/hex.ts ADDED
@@ -0,0 +1,28 @@
1
+ // Spec: 0001-formats FR-013
2
+ /**
3
+ * Hexadecimal text: bytes as lower-case hexadecimal, two digits each, and hexadecimal text as bytes (commons 0005-typescript-runtime FR-008). Taken from `sha256.ts`, which every digest
4
+ * is written through, so that a format of bytes is in the library of formats and the digests depend on it.
5
+ *
6
+ * @example
7
+ * ```ts
8
+ * import { fromHex, toHex } from "./hex.ts";
9
+ * toHex(new Uint8Array([1, 255])); // "01ff"
10
+ * fromHex("01ff"); // Uint8Array [1, 255]
11
+ * ```
12
+ *
13
+ * @module
14
+ */
15
+ /** Bytes as lower-case hexadecimal, two digits each. */
16
+ export function toHex(bytes: Uint8Array): string {
17
+ let out = "";
18
+ for (const b of bytes) out += b.toString(16).padStart(2, "0");
19
+ return out;
20
+ }
21
+
22
+ /** Hexadecimal text as bytes, or undefined where it is not an even number of hexadecimal digits. */
23
+ export function fromHex(text: string): Uint8Array | undefined {
24
+ if (text.length % 2 !== 0 || !/^[0-9a-fA-F]*$/.test(text)) return undefined;
25
+ const out = new Uint8Array(text.length / 2);
26
+ for (let i = 0; i < out.length; i++) out[i] = Number.parseInt(text.slice(i * 2, i * 2 + 2), 16);
27
+ return out;
28
+ }
package/src/http.ts ADDED
@@ -0,0 +1,104 @@
1
+ // Spec: 0001-formats FR-019
2
+ /**
3
+ * Pure HTTP helpers that API clients and servers keep rewriting (commons 0001-formats FR-019): the `Link` header (RFC 8288) read into its
4
+ * links so a client follows `rel="next"` pages, `Retry-After` (RFC 9110 §10.2.3) read as a wait whether it is seconds or a date, and which
5
+ * methods are safe (RFC 9110 §9.2.1) so a read-only client can refuse the rest, and the entity-tag conditions of `If-Match` and
6
+ * `If-None-Match` (RFC 9110 §13.1) a server answers with 412 or 304. Taken from Stolos's connector SDK (`src/archon/connect/sdk.ts`,
7
+ * `connector.ts`), which matched `rel="next"` with a regular expression in two places, and erga's `lib/ts/http` (on `@std/http/etag`).
8
+ *
9
+ * @example
10
+ * ```ts
11
+ * import { nextLink, retryAfterMs } from "./http.ts";
12
+ * nextLink('<https://api.example.com/items?page=2>; rel="next", <https://api.example.com/items?page=9>; rel="last"');
13
+ * // "https://api.example.com/items?page=2"
14
+ * retryAfterMs("120", Date.now()); // 120000
15
+ * ```
16
+ *
17
+ * @module
18
+ */
19
+
20
+ /** One link of a `Link` header: its target and its parameters (`rel`, `type`, ...), names in lower case. */
21
+ export type WebLink = { readonly target: string; readonly params: Readonly<Record<string, string>> };
22
+
23
+ /** The links of a `Link` header, in order; a part that is not `<target>; params` is skipped. Relative targets are resolved against `base`. */
24
+ export function parseLinkHeader(header: string, base?: string): readonly WebLink[] {
25
+ const out: WebLink[] = [];
26
+ const re = /<([^>]*)>((?:\s*;\s*[^;,=\s]+(?:\s*=\s*(?:"(?:[^"\\]|\\.)*"|[^;,\s]*))?)*)\s*(?:,|$)/g;
27
+ for (const m of header.matchAll(re)) {
28
+ const raw = m[1] ?? "";
29
+ let target = raw;
30
+ if (base !== undefined) {
31
+ try {
32
+ target = new URL(raw, base).href;
33
+ } catch {
34
+ continue;
35
+ }
36
+ }
37
+ const params: Record<string, string> = {};
38
+ for (const p of (m[2] ?? "").matchAll(/;\s*([^;,=\s]+)(?:\s*=\s*(?:"((?:[^"\\]|\\.)*)"|([^;,\s]*)))?/g)) {
39
+ const name = (p[1] ?? "").toLowerCase();
40
+ if (!(name in params)) params[name] = (p[2] ?? p[3] ?? "").replace(/\\(.)/g, "$1");
41
+ }
42
+ out.push({ target, params });
43
+ }
44
+ return out;
45
+ }
46
+
47
+ /** The target of the first link whose `rel` names `rel` (`next` by default); a `rel` may name several, separated by spaces. */
48
+ export function nextLink(header: string | null | undefined, rel = "next", base?: string): string | undefined {
49
+ if (header === null || header === undefined) return undefined;
50
+ return parseLinkHeader(header, base).find((l) => (l.params["rel"] ?? "").toLowerCase().split(/\s+/).includes(rel))?.target;
51
+ }
52
+
53
+ /** How long a `Retry-After` value asks to wait, in milliseconds from `now`: whole seconds, or an HTTP date (never negative); undefined where it is neither. */
54
+ export function retryAfterMs(value: string | null | undefined, now: number): number | undefined {
55
+ if (value === null || value === undefined) return undefined;
56
+ const v = value.trim();
57
+ if (/^\d+$/.test(v)) return Number(v) * 1000;
58
+ if (!/[A-Za-z]/.test(v)) return undefined;
59
+ const at = Date.parse(v);
60
+ return Number.isNaN(at) ? undefined : Math.max(0, at - now);
61
+ }
62
+
63
+ /** The methods that only read (RFC 9110 §9.2.1). */
64
+ export const SAFE_METHODS: ReadonlySet<string> = new Set(["GET", "HEAD", "OPTIONS", "TRACE"]);
65
+
66
+ /** Whether a method only reads; case does not matter. */
67
+ export function isSafeMethod(method: string): boolean {
68
+ return SAFE_METHODS.has(method.toUpperCase());
69
+ }
70
+
71
+ /** The entity tags of an `If-Match` or `If-None-Match` header, as written (`"abc"`, `W/"abc"`), or `*`. */
72
+ export function entityTags(header: string): readonly string[] | "*" {
73
+ if (header.trim() === "*") return "*";
74
+ return [...header.matchAll(/(?:W\/)?"[^"]*"/g)].map((m) => m[0]);
75
+ }
76
+
77
+ const opaque = (tag: string): string => tag.replace(/^W\//, "");
78
+
79
+ /** An entity tag for content by its checksum or another stable token: strong (`"token"`), or weak (`W/"token"`). */
80
+ export function entityTag(token: string, weak = false): string {
81
+ return `${weak ? "W/" : ""}"${token.replaceAll('"', "")}"`;
82
+ }
83
+
84
+ /**
85
+ * Whether a request with this `If-Match` header may go on for content with this entity tag (RFC 9110 §13.1.1): yes where the header is
86
+ * absent, is `*`, or names the tag by strong comparison (a weak tag never matches).
87
+ */
88
+ export function ifMatch(header: string | null | undefined, etag: string): boolean {
89
+ if (header === null || header === undefined) return true;
90
+ const tags = entityTags(header);
91
+ if (tags === "*") return true;
92
+ return !etag.startsWith("W/") && tags.some((t) => !t.startsWith("W/") && t === etag);
93
+ }
94
+
95
+ /**
96
+ * Whether a request with this `If-None-Match` header should get the content again (RFC 9110 §13.1.2), rather than 304 or 412: yes where
97
+ * the header is absent or names no tag equal to this one by weak comparison; no where it is `*`.
98
+ */
99
+ export function ifNoneMatch(header: string | null | undefined, etag: string): boolean {
100
+ if (header === null || header === undefined) return true;
101
+ const tags = entityTags(header);
102
+ if (tags === "*") return false;
103
+ return !tags.some((t) => opaque(t) === opaque(etag));
104
+ }
package/src/json5.ts ADDED
@@ -0,0 +1,267 @@
1
+ // Spec: 0001-formats FR-001
2
+ /**
3
+ * JSON5 (https://spec.json5.org/, 1.0.0), read and written with no outside package (commons 0001-formats FR-001): the reader
4
+ * takes the whole grammar (comments, trailing commas, unquoted ECMAScript keys, single-quoted and continued strings, hexadecimal,
5
+ * `Infinity`, `NaN`, a leading `+`, a leading or trailing decimal point) and gives a typed `Json` value or the line and column where the
6
+ * text stops being JSON5; the writer gives the form a person edits: a `//` comment at the head, keys bare where they can be, two spaces of
7
+ * indent, a comma after every member, and a short list of plain values on one line. Taken from erga's `lib/ts/json5`, whose reader was
8
+ * the `json5` package.
9
+ *
10
+ * @example
11
+ * ```ts
12
+ * import { parseJson5, toJson5 } from "./json5.ts";
13
+ * parseJson5("{ unquoted: 'and you can quote me on that', trailing: [1, 2,], }");
14
+ * // { kind: "ok", value: { unquoted: "and you can quote me on that", trailing: [1, 2] } }
15
+ * toJson5({ name: "a", tags: ["x", "y"] }, "What this file is");
16
+ * // "// What this file is\n{\n name: \"a\",\n tags: [\"x\", \"y\"],\n}\n"
17
+ * ```
18
+ *
19
+ * @module
20
+ */
21
+ import { err, ok, type Result } from "@intellectual-frontiers/core";
22
+
23
+ /** A JSON value: what a JSON5 file holds once read. An object keeps its members in the order they were written; a number may be `NaN` or infinite. */
24
+ export type Json = null | boolean | number | string | readonly Json[] | JsonObject;
25
+
26
+ /** A JSON object. */
27
+ export type JsonObject = { readonly [key: string]: Json };
28
+
29
+ /** Where a text stops being JSON5, and why. Lines and columns count from 1. */
30
+ export type Json5Error = { readonly kind: "json5"; readonly line: number; readonly column: number; readonly message: string };
31
+
32
+ /** A JSON5 error as one line: `3:14: expected a value`. */
33
+ export function formatJson5Error(e: Json5Error): string {
34
+ return `${e.line}:${e.column}: ${e.message}`;
35
+ }
36
+
37
+ /** Whether a value is a JSON object. */
38
+ export function isJsonObject(v: Json): v is JsonObject {
39
+ return typeof v === "object" && v !== null && !Array.isArray(v);
40
+ }
41
+
42
+ class Stop extends Error {
43
+ readonly at: number;
44
+ constructor(at: number, message: string) {
45
+ super(message);
46
+ this.at = at;
47
+ }
48
+ }
49
+
50
+ const LINE = /[\n\r\u2028\u2029]/;
51
+ const SPACE = /[\t\v\f \u00a0\ufeff\p{Zs}]/u;
52
+ const ID_START = /[\p{ID_Start}$_]/u;
53
+ const ID_PART = /[\p{ID_Continue}$\u200c\u200d]/u;
54
+ const ESCAPES: Readonly<Record<string, string>> = { "'": "'", '"': '"', "\\": "\\", b: "\b", f: "\f", n: "\n", r: "\r", t: "\t", v: "\v" };
55
+
56
+ /** JSON5 (or JSON) text read as a JSON value, or where and why it is not JSON5. */
57
+ export function parseJson5(text: string): Result<Json, Json5Error> {
58
+ let i = 0;
59
+ const fail = (message: string, at = i): never => {
60
+ throw new Stop(at, message);
61
+ };
62
+ const peek = (): string => text[i] ?? "";
63
+ const skip = (): void => {
64
+ for (;;) {
65
+ const c = peek();
66
+ if (c !== "" && (SPACE.test(c) || LINE.test(c))) i++;
67
+ else if (text.startsWith("//", i)) {
68
+ while (i < text.length && !LINE.test(peek())) i++;
69
+ } else if (text.startsWith("/*", i)) {
70
+ const end = text.indexOf("*/", i + 2);
71
+ if (end < 0) fail("a comment that is not closed");
72
+ i = end + 2;
73
+ } else return;
74
+ }
75
+ };
76
+ const hex = (n: number): number => {
77
+ const h = text.slice(i, i + n);
78
+ if (h.length !== n || !/^[0-9a-fA-F]+$/.test(h)) fail(`${n} hexadecimal digits`);
79
+ i += n;
80
+ return Number.parseInt(h, 16);
81
+ };
82
+ const escape = (): string => {
83
+ const c = peek();
84
+ i++;
85
+ if (c === "") return fail("the rest of an escape");
86
+ const simple = ESCAPES[c];
87
+ if (simple !== undefined) return simple;
88
+ if (c === "0") {
89
+ if (/[0-9]/.test(peek())) fail("no digit after \\0");
90
+ return "\0";
91
+ }
92
+ if (/[1-9]/.test(c)) fail("no escaped digit", i - 1);
93
+ if (c === "x") return String.fromCharCode(hex(2));
94
+ if (c === "u") return String.fromCharCode(hex(4));
95
+ if (c === "\r") {
96
+ if (peek() === "\n") i++;
97
+ return "";
98
+ }
99
+ if (LINE.test(c)) return "";
100
+ return c;
101
+ };
102
+ const string = (): string => {
103
+ const quote = peek();
104
+ i++;
105
+ let out = "";
106
+ for (;;) {
107
+ const c = peek();
108
+ if (c === "") fail("a closing quote");
109
+ i++;
110
+ if (c === quote) return out;
111
+ if (c === "\\") out += escape();
112
+ else if (c === "\n" || c === "\r") fail("no line break inside a string", i - 1);
113
+ else out += c;
114
+ }
115
+ };
116
+ const identifier = (): string => {
117
+ let out = "";
118
+ for (let first = true; ; first = false) {
119
+ let c = peek();
120
+ if (c === "\\") {
121
+ if (text[i + 1] !== "u") fail("\\u in a key");
122
+ i += 2;
123
+ c = String.fromCharCode(hex(4));
124
+ } else {
125
+ const cp = text.codePointAt(i);
126
+ c = cp === undefined ? "" : String.fromCodePoint(cp);
127
+ if (c === "" || !(first ? ID_START : ID_PART).test(c)) {
128
+ if (first) fail("a key");
129
+ return out;
130
+ }
131
+ i += c.length;
132
+ }
133
+ if (!(first ? ID_START : ID_PART).test(c)) fail("a key");
134
+ out += c;
135
+ }
136
+ };
137
+ const number = (): number => {
138
+ const m =
139
+ /^([+-]?)(Infinity|NaN|0[xX][0-9a-fA-F]+|(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][+-]?[0-9]+)?|\.[0-9]+(?:[eE][+-]?[0-9]+)?)/.exec(
140
+ text.slice(i),
141
+ );
142
+ if (m === null) return fail("a value");
143
+ const [whole = "", sign = "", body = ""] = m;
144
+ i += whole.length;
145
+ if (ID_PART.test(peek())) fail("a number that ends where it should");
146
+ const magnitude =
147
+ body === "Infinity"
148
+ ? Number.POSITIVE_INFINITY
149
+ : body === "NaN"
150
+ ? Number.NaN
151
+ : /^0[xX]/.test(body)
152
+ ? Number.parseInt(body.slice(2), 16)
153
+ : Number(body);
154
+ return sign === "-" ? -magnitude : magnitude;
155
+ };
156
+ const word = (w: string): boolean => {
157
+ if (!text.startsWith(w, i) || ID_PART.test(text[i + w.length] ?? "")) return false;
158
+ i += w.length;
159
+ return true;
160
+ };
161
+ const value = (depth: number): Json => {
162
+ if (depth > 512) fail("less nesting (more than 512 levels)");
163
+ skip();
164
+ const c = peek();
165
+ if (c === "{") {
166
+ i++;
167
+ const o: Record<string, Json> = {};
168
+ for (;;) {
169
+ skip();
170
+ if (peek() === "}") {
171
+ i++;
172
+ return o;
173
+ }
174
+ const key = peek() === '"' || peek() === "'" ? string() : identifier();
175
+ skip();
176
+ if (peek() !== ":") fail("a colon");
177
+ i++;
178
+ Object.defineProperty(o, key, { value: value(depth + 1), enumerable: true, writable: true, configurable: true });
179
+ skip();
180
+ if (peek() === ",") i++;
181
+ else if (peek() !== "}") fail("a comma or }");
182
+ }
183
+ }
184
+ if (c === "[") {
185
+ i++;
186
+ const a: Json[] = [];
187
+ for (;;) {
188
+ skip();
189
+ if (peek() === "]") {
190
+ i++;
191
+ return a;
192
+ }
193
+ a.push(value(depth + 1));
194
+ skip();
195
+ if (peek() === ",") i++;
196
+ else if (peek() !== "]") fail("a comma or ]");
197
+ }
198
+ }
199
+ if (c === '"' || c === "'") return string();
200
+ if (word("null")) return null;
201
+ if (word("true")) return true;
202
+ if (word("false")) return false;
203
+ return number();
204
+ };
205
+ try {
206
+ const v = value(0);
207
+ skip();
208
+ if (i < text.length) fail("the end of the text");
209
+ return ok(v);
210
+ } catch (e) {
211
+ if (!(e instanceof Stop)) throw e;
212
+ const before = text.slice(0, e.at).split(/\r\n|[\n\r\u2028\u2029]/);
213
+ return err({ kind: "json5", line: before.length, column: (before.at(-1)?.length ?? 0) + 1, message: `expected ${e.message}` });
214
+ }
215
+ }
216
+
217
+ /** Whether a key may stand without quotes: an ECMAScript identifier of ASCII letters, digits, `_` and `$`, not starting with a digit. */
218
+ export function isBareKey(key: string): boolean {
219
+ return /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(key);
220
+ }
221
+
222
+ const plainValue = (v: Json): boolean => !(Array.isArray(v) || isJsonObject(v));
223
+
224
+ function scalar(v: Json): string {
225
+ if (typeof v === "number") {
226
+ if (Number.isNaN(v)) return "NaN";
227
+ if (!Number.isFinite(v)) return v > 0 ? "Infinity" : "-Infinity";
228
+ if (Object.is(v, -0)) return "-0";
229
+ }
230
+ return JSON.stringify(v);
231
+ }
232
+
233
+ function write(v: Json, depth: number, width: number): string {
234
+ const pad = (n: number): string => " ".repeat(n);
235
+ if (Array.isArray(v)) {
236
+ const items: readonly Json[] = v;
237
+ if (items.length === 0) return "[]";
238
+ const line = items.map(scalar).join(", ");
239
+ if (items.every(plainValue) && new TextEncoder().encode(line).length + depth * 2 <= width) return `[${line}]`;
240
+ return `[\n${items.map((item) => `${pad(depth + 1)}${write(item, depth + 1, width)},\n`).join("")}${pad(depth)}]`;
241
+ }
242
+ if (isJsonObject(v)) {
243
+ const entries = Object.entries(v);
244
+ if (entries.length === 0) return "{}";
245
+ return `{\n${entries.map(([k, item]) => `${pad(depth + 1)}${isBareKey(k) ? k : JSON.stringify(k)}: ${write(item, depth + 1, width)},\n`).join("")}${pad(depth)}}`;
246
+ }
247
+ return scalar(v);
248
+ }
249
+
250
+ /** The lines of a comment: none for empty text, and no last empty line for a final line break. */
251
+ function linesOf(text: string): string[] {
252
+ if (text === "") return [];
253
+ const lines = text.split("\n").map((l) => (l.endsWith("\r") ? l.slice(0, -1) : l));
254
+ if (text.endsWith("\n")) lines.pop();
255
+ return lines;
256
+ }
257
+
258
+ /**
259
+ * A value as JSON5 text: `comment` first, one `//` line for each of its lines (none where it is empty), then the value, ending in a line
260
+ * break. A list of plain values stays on one line while it fits in `width` bytes (100 by default).
261
+ */
262
+ export function toJson5(value: Json, comment = "", width = 100): string {
263
+ const head = linesOf(comment)
264
+ .map((l) => (l === "" ? "//\n" : `// ${l}\n`))
265
+ .join("");
266
+ return `${head}${write(value, 0, width)}\n`;
267
+ }