@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/der.js
ADDED
|
@@ -0,0 +1,221 @@
|
|
|
1
|
+
// Spec: 0001-formats FR-009
|
|
2
|
+
/**
|
|
3
|
+
* ASN.1 DER (ITU-T X.690), encoded and read with no outside package (commons 0001-formats FR-009): every value a tag, a length
|
|
4
|
+
* and its content, as bytes; enough to build CMS structures (RFC 5652) and read the fields of an X.509 certificate (RFC 5280). Encoders
|
|
5
|
+
* give the one DER form (minimal lengths and integers, a SET OF sorted); a malformed input to an encoder (an OID that is not dotted
|
|
6
|
+
* numbers) is a programming error and throws a `RangeError`. Readers return a `Result`: what is not DER this reader knows is an error
|
|
7
|
+
* saying where. Taken from Stolos's `src/archon/export/der.ts` (S/MIME for emailed exports), with negative integers and integers read.
|
|
8
|
+
*
|
|
9
|
+
* @example
|
|
10
|
+
* ```ts
|
|
11
|
+
* import { oid, readOid, readTlv } from "./der.ts";
|
|
12
|
+
* const t = readTlv(oid("1.2.840.113549.1.7.1"));
|
|
13
|
+
* if (t.kind === "ok") readOid(t.value.content); // { kind: "ok", value: "1.2.840.113549.1.7.1" }
|
|
14
|
+
* ```
|
|
15
|
+
*
|
|
16
|
+
* @module
|
|
17
|
+
*/
|
|
18
|
+
import { concat } from "./archive.js";
|
|
19
|
+
import { err, ok } from "@intellectual-frontiers/core";
|
|
20
|
+
/** The universal tags used (class universal, with the constructed bit where it applies). */
|
|
21
|
+
export const TAG = {
|
|
22
|
+
boolean: 0x01,
|
|
23
|
+
integer: 0x02,
|
|
24
|
+
bitString: 0x03,
|
|
25
|
+
octetString: 0x04,
|
|
26
|
+
null: 0x05,
|
|
27
|
+
oid: 0x06,
|
|
28
|
+
utf8String: 0x0c,
|
|
29
|
+
printableString: 0x13,
|
|
30
|
+
ia5String: 0x16,
|
|
31
|
+
utcTime: 0x17,
|
|
32
|
+
generalizedTime: 0x18,
|
|
33
|
+
sequence: 0x30,
|
|
34
|
+
set: 0x31,
|
|
35
|
+
};
|
|
36
|
+
/** A DER length: the short form below 128, else `0x80` with the number of length bytes, then the bytes. */
|
|
37
|
+
export function encodeLength(n) {
|
|
38
|
+
if (!Number.isSafeInteger(n) || n < 0)
|
|
39
|
+
throw new RangeError(`DER: no length ${n}`);
|
|
40
|
+
if (n < 0x80)
|
|
41
|
+
return Uint8Array.of(n);
|
|
42
|
+
const bytes = [];
|
|
43
|
+
for (let x = n; x > 0; x = Math.floor(x / 256))
|
|
44
|
+
bytes.unshift(x & 0xff);
|
|
45
|
+
return Uint8Array.of(0x80 | bytes.length, ...bytes);
|
|
46
|
+
}
|
|
47
|
+
/** One element: the tag byte, the content's length, the content. */
|
|
48
|
+
export function tlv(tag, content) {
|
|
49
|
+
if (!Number.isInteger(tag) || tag < 0 || tag > 0xff || (tag & 0x1f) === 0x1f)
|
|
50
|
+
throw new RangeError(`DER: no tag byte ${tag} (high tag numbers are not written)`);
|
|
51
|
+
return concat([Uint8Array.of(tag), encodeLength(content.length), content]);
|
|
52
|
+
}
|
|
53
|
+
/** A SEQUENCE of these encodings, in order. */
|
|
54
|
+
export function sequence(...items) {
|
|
55
|
+
return tlv(TAG.sequence, concat(items));
|
|
56
|
+
}
|
|
57
|
+
/** Two byte strings compared as DER sorts them: byte by byte, a prefix first. */
|
|
58
|
+
export function compareBytes(a, b) {
|
|
59
|
+
for (let i = 0; i < Math.min(a.length, b.length); i++) {
|
|
60
|
+
const d = (a[i] ?? 0) - (b[i] ?? 0);
|
|
61
|
+
if (d !== 0)
|
|
62
|
+
return d;
|
|
63
|
+
}
|
|
64
|
+
return a.length - b.length;
|
|
65
|
+
}
|
|
66
|
+
/** A SET OF these encodings, sorted as DER requires (X.690 §11.6). */
|
|
67
|
+
export function setOf(...items) {
|
|
68
|
+
return tlv(TAG.set, concat([...items].sort(compareBytes)));
|
|
69
|
+
}
|
|
70
|
+
/** An OCTET STRING. */
|
|
71
|
+
export function octetString(b) {
|
|
72
|
+
return tlv(TAG.octetString, b);
|
|
73
|
+
}
|
|
74
|
+
/** A BIT STRING of whole bytes (no unused bits). */
|
|
75
|
+
export function bitString(b) {
|
|
76
|
+
return tlv(TAG.bitString, concat([Uint8Array.of(0), b]));
|
|
77
|
+
}
|
|
78
|
+
/** A UTF8String. */
|
|
79
|
+
export function utf8String(s) {
|
|
80
|
+
return tlv(TAG.utf8String, new TextEncoder().encode(s));
|
|
81
|
+
}
|
|
82
|
+
/** A BOOLEAN. */
|
|
83
|
+
export function boolean(v) {
|
|
84
|
+
return tlv(TAG.boolean, Uint8Array.of(v ? 0xff : 0));
|
|
85
|
+
}
|
|
86
|
+
/** NULL. */
|
|
87
|
+
export function derNull() {
|
|
88
|
+
return Uint8Array.of(TAG.null, 0);
|
|
89
|
+
}
|
|
90
|
+
/** The minimal two's complement bytes of an integer: no redundant leading `0x00` or `0xff`. */
|
|
91
|
+
function twosComplement(v) {
|
|
92
|
+
const bytes = [];
|
|
93
|
+
let x = v;
|
|
94
|
+
for (;;) {
|
|
95
|
+
bytes.unshift(Number(BigInt.asUintN(8, x)));
|
|
96
|
+
x >>= 8n;
|
|
97
|
+
const top = bytes[0] ?? 0;
|
|
98
|
+
if ((x === 0n && top < 0x80) || (x === -1n && top >= 0x80))
|
|
99
|
+
return bytes;
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
/** An INTEGER: a JavaScript integer or a bigint (negative too), or big-endian unsigned magnitude bytes; always in its minimal form. */
|
|
103
|
+
export function integer(v) {
|
|
104
|
+
if (v instanceof Uint8Array) {
|
|
105
|
+
let n = 0n;
|
|
106
|
+
for (const b of v)
|
|
107
|
+
n = (n << 8n) | BigInt(b);
|
|
108
|
+
return tlv(TAG.integer, Uint8Array.from(twosComplement(n)));
|
|
109
|
+
}
|
|
110
|
+
if (typeof v === "number" && !Number.isSafeInteger(v))
|
|
111
|
+
throw new RangeError(`DER: no integer ${v}`);
|
|
112
|
+
return tlv(TAG.integer, Uint8Array.from(twosComplement(BigInt(v))));
|
|
113
|
+
}
|
|
114
|
+
/** An OBJECT IDENTIFIER from its dotted form (`1.2.840.113549`). */
|
|
115
|
+
export function oid(dotted) {
|
|
116
|
+
if (!/^\d+(\.\d+)+$/.test(dotted))
|
|
117
|
+
throw new RangeError(`DER: no OID ${dotted}`);
|
|
118
|
+
const arcs = dotted.split(".").map((s) => BigInt(s));
|
|
119
|
+
const [a = 0n, b = 0n] = arcs;
|
|
120
|
+
if (a > 2n || (a < 2n && b > 39n))
|
|
121
|
+
throw new RangeError(`DER: no OID ${dotted}`);
|
|
122
|
+
const out = [];
|
|
123
|
+
const base128 = (n) => {
|
|
124
|
+
const g = [Number(n & 0x7fn)];
|
|
125
|
+
for (let x = n >> 7n; x > 0n; x >>= 7n)
|
|
126
|
+
g.unshift(Number(x & 0x7fn) | 0x80);
|
|
127
|
+
out.push(...g);
|
|
128
|
+
};
|
|
129
|
+
base128(a * 40n + b);
|
|
130
|
+
for (const arc of arcs.slice(2))
|
|
131
|
+
base128(arc);
|
|
132
|
+
return tlv(TAG.oid, Uint8Array.from(out));
|
|
133
|
+
}
|
|
134
|
+
/** A context-specific EXPLICIT tag `[n]` around one encoding. */
|
|
135
|
+
export function explicit(n, inner) {
|
|
136
|
+
return tlv(0xa0 | n, inner);
|
|
137
|
+
}
|
|
138
|
+
/** A context-specific IMPLICIT tag `[n]`: this content under the tag, constructed where the underlying type is. */
|
|
139
|
+
export function implicit(n, content, constructed) {
|
|
140
|
+
return tlv((constructed ? 0xa0 : 0x80) | n, content);
|
|
141
|
+
}
|
|
142
|
+
/** An AlgorithmIdentifier: `SEQUENCE { algorithm OID, parameters ANY OPTIONAL }`. */
|
|
143
|
+
export function algorithm(id, params) {
|
|
144
|
+
return params === undefined ? sequence(oid(id)) : sequence(oid(id), params);
|
|
145
|
+
}
|
|
146
|
+
/** The element that starts at `offset`: its tag, its content and its whole encoding; or why it is not DER this reader knows. */
|
|
147
|
+
export function readTlv(bytes, offset = 0) {
|
|
148
|
+
const fail = (at, message) => err({ kind: "der", at, message });
|
|
149
|
+
const tag = bytes[offset];
|
|
150
|
+
if (tag === undefined)
|
|
151
|
+
return fail(offset, "no tag (the bytes end)");
|
|
152
|
+
if ((tag & 0x1f) === 0x1f)
|
|
153
|
+
return fail(offset, "a high tag number (not read)");
|
|
154
|
+
let i = offset + 1;
|
|
155
|
+
const first = bytes[i++];
|
|
156
|
+
if (first === undefined)
|
|
157
|
+
return fail(offset + 1, "no length (the bytes end)");
|
|
158
|
+
let length = first;
|
|
159
|
+
if ((first & 0x80) !== 0) {
|
|
160
|
+
const n = first & 0x7f;
|
|
161
|
+
if (n === 0)
|
|
162
|
+
return fail(offset + 1, "an indefinite length (not DER)");
|
|
163
|
+
if (n > 6)
|
|
164
|
+
return fail(offset + 1, "a length too long to hold");
|
|
165
|
+
length = 0;
|
|
166
|
+
for (let k = 0; k < n; k++) {
|
|
167
|
+
const b = bytes[i++];
|
|
168
|
+
if (b === undefined)
|
|
169
|
+
return fail(i - 1, "the rest of the length (the bytes end)");
|
|
170
|
+
length = length * 256 + b;
|
|
171
|
+
}
|
|
172
|
+
if (length < 0x80 || (n > 1 && bytes[offset + 2] === 0))
|
|
173
|
+
return fail(offset + 1, "the shortest form of the length (DER)");
|
|
174
|
+
}
|
|
175
|
+
if (i + length > bytes.length)
|
|
176
|
+
return fail(i, `${length} bytes of content (only ${bytes.length - i} are left)`);
|
|
177
|
+
return ok({ tag, content: bytes.subarray(i, i + length), raw: bytes.subarray(offset, i + length) });
|
|
178
|
+
}
|
|
179
|
+
/** The elements inside a constructed element's content, in order. */
|
|
180
|
+
export function children(content) {
|
|
181
|
+
const out = [];
|
|
182
|
+
for (let i = 0; i < content.length;) {
|
|
183
|
+
const t = readTlv(content, i);
|
|
184
|
+
if (t.kind === "err")
|
|
185
|
+
return t;
|
|
186
|
+
out.push(t.value);
|
|
187
|
+
i += t.value.raw.length;
|
|
188
|
+
}
|
|
189
|
+
return ok(out);
|
|
190
|
+
}
|
|
191
|
+
/** The dotted form of an OBJECT IDENTIFIER's content. */
|
|
192
|
+
export function readOid(content) {
|
|
193
|
+
const arcs = [];
|
|
194
|
+
let v = 0n;
|
|
195
|
+
for (const [i, b] of content.entries()) {
|
|
196
|
+
if (v === 0n && b === 0x80)
|
|
197
|
+
return err({ kind: "der", at: i, message: "an OID arc with no leading 0x80 (DER)" });
|
|
198
|
+
v = (v << 7n) | BigInt(b & 0x7f);
|
|
199
|
+
if ((b & 0x80) === 0) {
|
|
200
|
+
arcs.push(v);
|
|
201
|
+
v = 0n;
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
if (arcs.length === 0 || (content.at(-1) ?? 0) & 0x80)
|
|
205
|
+
return err({ kind: "der", at: content.length, message: "a complete OID" });
|
|
206
|
+
const head = arcs[0] ?? 0n;
|
|
207
|
+
const first = head < 80n ? head / 40n : 2n;
|
|
208
|
+
return ok([first, head - first * 40n, ...arcs.slice(1)].join("."));
|
|
209
|
+
}
|
|
210
|
+
/** The value of an INTEGER's content, as a bigint (two's complement). */
|
|
211
|
+
export function readInteger(content) {
|
|
212
|
+
if (content.length === 0)
|
|
213
|
+
return err({ kind: "der", at: 0, message: "an integer of at least one byte" });
|
|
214
|
+
if (content.length > 1 && ((content[0] === 0 && (content[1] ?? 0) < 0x80) || (content[0] === 0xff && (content[1] ?? 0) >= 0x80))) {
|
|
215
|
+
return err({ kind: "der", at: 0, message: "the shortest form of the integer (DER)" });
|
|
216
|
+
}
|
|
217
|
+
let n = 0n;
|
|
218
|
+
for (const b of content)
|
|
219
|
+
n = (n << 8n) | BigInt(b);
|
|
220
|
+
return ok(BigInt.asIntN(content.length * 8, n));
|
|
221
|
+
}
|
package/dist/glob.d.ts
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Path globs as regular expressions, on `/` paths, with the meaning `@std/path`'s `globToRegExp` gives them (commons
|
|
3
|
+
* 0001-formats FR-017); `fs.expandGlob` walks a folder with what this gives.
|
|
4
|
+
*
|
|
5
|
+
* The API, which `fs.expandGlob` builds on and which stays as it is:
|
|
6
|
+
* - `globToRegExp(glob, { extended?, globstar?, caseInsensitive? })`: the glob as a `RegExp` anchored at both ends, or why it is refused.
|
|
7
|
+
* - `matchGlob(glob, path, options?)`: whether the path matches, or why the glob is refused.
|
|
8
|
+
* - `isGlob(text)`: whether the text holds anything a glob gives a meaning to (else it names one path).
|
|
9
|
+
* - `globRoot(glob)`: the leading folders (every segment but the last) with no glob character, where a walk starts (`.` if none).
|
|
10
|
+
*
|
|
11
|
+
* The syntax, one segment (between `/`) at a time:
|
|
12
|
+
* - `*` any characters but `/`; `?` one character but `/` (where `@std/path` lets `?` and `[!a]` match a `/`, these do not);
|
|
13
|
+
* - `**` alone in its segment (with `globstar`, the default): any number of segments, none included, so `src/**\/*.ts` matches
|
|
14
|
+
* `src/a.ts` and `src/a/b/c.ts`; elsewhere it is `*`;
|
|
15
|
+
* - `[abc]`, `[a-z]`, `[!abc]` (not one of, nor `/`), `[[:alpha:]]` and the other POSIX classes; `[^a]` is `^` or `a`, as in `@std/path`;
|
|
16
|
+
* - `{a,b}` either alternative (always on);
|
|
17
|
+
* - 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;
|
|
18
|
+
* - `\` takes the next character as it is.
|
|
19
|
+
*
|
|
20
|
+
* A segment with an unclosed `[`, `{` or `(`, or ending in `\`, is taken as it is written. Separators run together (`a//b` is `a/b`), a
|
|
21
|
+
* trailing one is optional, and the empty glob matches nothing. A glob that begins with `!` not followed by `(` is refused: it reads as
|
|
22
|
+
* the negation of a gitignore or a shell, which a regular expression of the path cannot mean.
|
|
23
|
+
*
|
|
24
|
+
* @example
|
|
25
|
+
* ```ts
|
|
26
|
+
* import { globToRegExp, matchGlob } from "./glob.js";
|
|
27
|
+
* matchGlob("src/**\/*.ts", "src/a/b/c.ts"); // { kind: "ok", value: true }
|
|
28
|
+
* matchGlob("src/**\/*.ts", "srcx/a.ts"); // { kind: "ok", value: false }
|
|
29
|
+
* globToRegExp("!x"); // { kind: "err", error: { kind: "negated", glob: "!x" } }
|
|
30
|
+
* ```
|
|
31
|
+
*
|
|
32
|
+
* @module
|
|
33
|
+
*/
|
|
34
|
+
import { type Result } from "@intellectual-frontiers/core";
|
|
35
|
+
/** How a glob is read: `extended` (extglob groups, default true), `globstar` (`**` across segments, default true), `caseInsensitive`. */
|
|
36
|
+
export type GlobOptions = {
|
|
37
|
+
readonly extended?: boolean;
|
|
38
|
+
readonly globstar?: boolean;
|
|
39
|
+
readonly caseInsensitive?: boolean;
|
|
40
|
+
};
|
|
41
|
+
/** Why a glob is refused: it begins with a `!` that negates nothing a path expression can say. */
|
|
42
|
+
export type GlobError = {
|
|
43
|
+
readonly kind: "negated";
|
|
44
|
+
readonly glob: string;
|
|
45
|
+
};
|
|
46
|
+
/** A refused glob as one sentence. */
|
|
47
|
+
export declare function formatGlobError(e: GlobError): string;
|
|
48
|
+
/**
|
|
49
|
+
* The glob as a regular expression of a whole `/` path, as `@std/path`'s `globToRegExp` makes it (see the module's documentation for the
|
|
50
|
+
* syntax); refused where it begins with a `!` that is not an extglob `!(...)`.
|
|
51
|
+
*/
|
|
52
|
+
export declare function globToRegExp(glob: string, options?: GlobOptions): Result<RegExp, GlobError>;
|
|
53
|
+
/** Whether the `/` path matches the glob (see `globToRegExp`), or why the glob is refused. */
|
|
54
|
+
export declare function matchGlob(glob: string, path: string, options?: GlobOptions): Result<boolean, GlobError>;
|
|
55
|
+
/**
|
|
56
|
+
* Whether the text holds anything a glob gives a meaning to, not escaped: `*`, `?`, a closed `[...]` or `{...}`, an extglob group, or a
|
|
57
|
+
* leading `!`. Text that is not a glob names one path, which a caller can take as it is.
|
|
58
|
+
*/
|
|
59
|
+
export declare function isGlob(text: string): boolean;
|
|
60
|
+
/**
|
|
61
|
+
* 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
|
|
62
|
+
* matches starts from. `.` where there are none; `/` for an absolute glob with none. Escapes in these segments are taken off.
|
|
63
|
+
*/
|
|
64
|
+
export declare function globRoot(glob: string): string;
|
package/dist/glob.js
ADDED
|
@@ -0,0 +1,218 @@
|
|
|
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 } from "@intellectual-frontiers/core";
|
|
36
|
+
/** A refused glob as one sentence. */
|
|
37
|
+
export function formatGlobError(e) {
|
|
38
|
+
return `the glob ${JSON.stringify(e.glob)} begins with "!", a negation a path glob cannot mean; escape it as "\\!" to match a "!"`;
|
|
39
|
+
}
|
|
40
|
+
const SEP = "/+";
|
|
41
|
+
const SEP_MAYBE = "/*";
|
|
42
|
+
const WILDCARD = "[^/]*";
|
|
43
|
+
const GLOBSTAR = "(?:[^/]*(?:/|$)+)*";
|
|
44
|
+
const ESCAPE_OUTSIDE = new Set(["!", "$", "(", ")", "*", "+", ".", "=", "?", "[", "\\", "^", "{", "|"]);
|
|
45
|
+
const ESCAPE_INSIDE = new Set(["-", "\\", "]"]);
|
|
46
|
+
const CLASSES = new Map([
|
|
47
|
+
["alnum", "\\dA-Za-z"],
|
|
48
|
+
["alpha", "A-Za-z"],
|
|
49
|
+
["ascii", "\\x00-\\x7F"],
|
|
50
|
+
["blank", "\\t "],
|
|
51
|
+
["cntrl", "\\x00-\\x1F\\x7F"],
|
|
52
|
+
["digit", "\\d"],
|
|
53
|
+
["graph", "\\x21-\\x7E"],
|
|
54
|
+
["lower", "a-z"],
|
|
55
|
+
["print", "\\x20-\\x7E"],
|
|
56
|
+
["punct", "!-\\/:-@\\[-`{-~"],
|
|
57
|
+
["space", "\\s\\v"],
|
|
58
|
+
["upper", "A-Z"],
|
|
59
|
+
["word", "\\w"],
|
|
60
|
+
["xdigit", "\\dA-Fa-f"],
|
|
61
|
+
]);
|
|
62
|
+
const literal = (c) => (ESCAPE_OUTSIDE.has(c) ? `\\${c}` : c);
|
|
63
|
+
/** One segment of a glob (no `/` in it) as a regular expression, and whether it is a globstar; undefined where it does not close. */
|
|
64
|
+
function segment(text, extended, globstar) {
|
|
65
|
+
let out = "";
|
|
66
|
+
const groups = [];
|
|
67
|
+
let inClass = false;
|
|
68
|
+
for (let i = 0; i < text.length; i++) {
|
|
69
|
+
const c = text[i] ?? "";
|
|
70
|
+
const next = text[i + 1];
|
|
71
|
+
if (c === "\\") {
|
|
72
|
+
const e = text[i + 1];
|
|
73
|
+
if (e === undefined)
|
|
74
|
+
return undefined;
|
|
75
|
+
i++;
|
|
76
|
+
out += inClass ? (ESCAPE_INSIDE.has(e) ? `\\${e}` : e) : literal(e);
|
|
77
|
+
continue;
|
|
78
|
+
}
|
|
79
|
+
if (inClass) {
|
|
80
|
+
if (c === "]") {
|
|
81
|
+
inClass = false;
|
|
82
|
+
out += "]";
|
|
83
|
+
}
|
|
84
|
+
else if (c === "[" && next === ":") {
|
|
85
|
+
const end = text.indexOf(":]", i + 2);
|
|
86
|
+
const cls = end < 0 ? undefined : CLASSES.get(text.slice(i + 2, end));
|
|
87
|
+
if (end >= 0 && cls !== undefined) {
|
|
88
|
+
out += cls;
|
|
89
|
+
i = end + 1;
|
|
90
|
+
}
|
|
91
|
+
else
|
|
92
|
+
out += "\\[";
|
|
93
|
+
}
|
|
94
|
+
else
|
|
95
|
+
out += c === "\\" || c === "^" ? `\\${c}` : c;
|
|
96
|
+
continue;
|
|
97
|
+
}
|
|
98
|
+
const top = groups[groups.length - 1];
|
|
99
|
+
if (c === "[") {
|
|
100
|
+
inClass = true;
|
|
101
|
+
out += "[";
|
|
102
|
+
if (next === "!") {
|
|
103
|
+
out += "^/";
|
|
104
|
+
i++;
|
|
105
|
+
}
|
|
106
|
+
else if (next === "^") {
|
|
107
|
+
out += "\\^";
|
|
108
|
+
i++;
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
else if (extended && next === "(" && (c === "?" || c === "*" || c === "+" || c === "@" || c === "!")) {
|
|
112
|
+
groups.push(c);
|
|
113
|
+
out += c === "!" ? "(?!" : "(?:";
|
|
114
|
+
i++;
|
|
115
|
+
}
|
|
116
|
+
else if (c === ")" && top !== undefined && top !== "brace") {
|
|
117
|
+
groups.pop();
|
|
118
|
+
out += top === "!" ? `)${WILDCARD}` : top === "@" ? ")" : `)${top}`;
|
|
119
|
+
}
|
|
120
|
+
else if (c === "|" && top !== undefined && top !== "brace")
|
|
121
|
+
out += "|";
|
|
122
|
+
else if (c === "{") {
|
|
123
|
+
groups.push("brace");
|
|
124
|
+
out += "(?:";
|
|
125
|
+
}
|
|
126
|
+
else if (c === "}" && top === "brace") {
|
|
127
|
+
groups.pop();
|
|
128
|
+
out += ")";
|
|
129
|
+
}
|
|
130
|
+
else if (c === "," && top === "brace")
|
|
131
|
+
out += "|";
|
|
132
|
+
else if (c === "?")
|
|
133
|
+
out += "[^/]";
|
|
134
|
+
else if (c === "*") {
|
|
135
|
+
let stars = 1;
|
|
136
|
+
while (text[i + 1] === "*") {
|
|
137
|
+
i++;
|
|
138
|
+
stars++;
|
|
139
|
+
}
|
|
140
|
+
if (globstar && stars === 2 && text.length === 2)
|
|
141
|
+
return { source: GLOBSTAR, star: true };
|
|
142
|
+
out += WILDCARD;
|
|
143
|
+
}
|
|
144
|
+
else
|
|
145
|
+
out += literal(c);
|
|
146
|
+
}
|
|
147
|
+
return groups.length > 0 || inClass ? undefined : { source: out, star: false };
|
|
148
|
+
}
|
|
149
|
+
/**
|
|
150
|
+
* The glob as a regular expression of a whole `/` path, as `@std/path`'s `globToRegExp` makes it (see the module's documentation for the
|
|
151
|
+
* syntax); refused where it begins with a `!` that is not an extglob `!(...)`.
|
|
152
|
+
*/
|
|
153
|
+
export function globToRegExp(glob, options = {}) {
|
|
154
|
+
const extended = options.extended ?? true;
|
|
155
|
+
const globstar = options.globstar ?? true;
|
|
156
|
+
if (glob.startsWith("!") && !(extended && glob[1] === "("))
|
|
157
|
+
return err({ kind: "negated", glob });
|
|
158
|
+
if (glob === "")
|
|
159
|
+
return ok(/(?!)/);
|
|
160
|
+
const leading = glob.startsWith("/");
|
|
161
|
+
const body = glob.replace(/^\/+/, "").replace(/\/+$/, "");
|
|
162
|
+
let source = leading ? SEP : "";
|
|
163
|
+
const parts = body === "" ? [] : body.split(/\/+/);
|
|
164
|
+
parts.forEach((part, n) => {
|
|
165
|
+
const s = segment(part, extended, globstar);
|
|
166
|
+
if (s?.star === true) {
|
|
167
|
+
source += s.source;
|
|
168
|
+
return;
|
|
169
|
+
}
|
|
170
|
+
source += s === undefined ? [...part].map(literal).join("") : s.source;
|
|
171
|
+
source += n < parts.length - 1 ? SEP : SEP_MAYBE;
|
|
172
|
+
});
|
|
173
|
+
return ok(new RegExp(`^${source}$`, options.caseInsensitive === true ? "i" : ""));
|
|
174
|
+
}
|
|
175
|
+
/** Whether the `/` path matches the glob (see `globToRegExp`), or why the glob is refused. */
|
|
176
|
+
export function matchGlob(glob, path, options = {}) {
|
|
177
|
+
const re = globToRegExp(glob, options);
|
|
178
|
+
return re.kind === "err" ? re : ok(re.value.test(path));
|
|
179
|
+
}
|
|
180
|
+
/**
|
|
181
|
+
* Whether the text holds anything a glob gives a meaning to, not escaped: `*`, `?`, a closed `[...]` or `{...}`, an extglob group, or a
|
|
182
|
+
* leading `!`. Text that is not a glob names one path, which a caller can take as it is.
|
|
183
|
+
*/
|
|
184
|
+
export function isGlob(text) {
|
|
185
|
+
if (text.startsWith("!"))
|
|
186
|
+
return true;
|
|
187
|
+
for (let i = 0; i < text.length; i++) {
|
|
188
|
+
const c = text[i];
|
|
189
|
+
if (c === "\\")
|
|
190
|
+
i++;
|
|
191
|
+
else if (c === "*" || c === "?")
|
|
192
|
+
return true;
|
|
193
|
+
else if (c === "[" && text.indexOf("]", i + 2) > 0)
|
|
194
|
+
return true;
|
|
195
|
+
else if (c === "{" && text.indexOf("}", i + 1) > 0)
|
|
196
|
+
return true;
|
|
197
|
+
else if ((c === "+" || c === "@" || c === "!") && text[i + 1] === "(" && text.indexOf(")", i + 2) > 0)
|
|
198
|
+
return true;
|
|
199
|
+
}
|
|
200
|
+
return false;
|
|
201
|
+
}
|
|
202
|
+
/**
|
|
203
|
+
* 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
|
|
204
|
+
* matches starts from. `.` where there are none; `/` for an absolute glob with none. Escapes in these segments are taken off.
|
|
205
|
+
*/
|
|
206
|
+
export function globRoot(glob) {
|
|
207
|
+
const absolute = glob.startsWith("/");
|
|
208
|
+
const parts = glob.split(/\/+/).filter((p) => p !== "");
|
|
209
|
+
const plain = [];
|
|
210
|
+
for (const p of parts.slice(0, -1)) {
|
|
211
|
+
if (isGlob(p))
|
|
212
|
+
break;
|
|
213
|
+
plain.push(p.replace(/\\(.)/g, "$1"));
|
|
214
|
+
}
|
|
215
|
+
if (plain.length === 0)
|
|
216
|
+
return absolute ? "/" : ".";
|
|
217
|
+
return `${absolute ? "/" : ""}${plain.join("/")}`;
|
|
218
|
+
}
|
package/dist/hex.d.ts
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 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
|
|
3
|
+
* is written through, so that a format of bytes is in the library of formats and the digests depend on it.
|
|
4
|
+
*
|
|
5
|
+
* @example
|
|
6
|
+
* ```ts
|
|
7
|
+
* import { fromHex, toHex } from "./hex.js";
|
|
8
|
+
* toHex(new Uint8Array([1, 255])); // "01ff"
|
|
9
|
+
* fromHex("01ff"); // Uint8Array [1, 255]
|
|
10
|
+
* ```
|
|
11
|
+
*
|
|
12
|
+
* @module
|
|
13
|
+
*/
|
|
14
|
+
/** Bytes as lower-case hexadecimal, two digits each. */
|
|
15
|
+
export declare function toHex(bytes: Uint8Array): string;
|
|
16
|
+
/** Hexadecimal text as bytes, or undefined where it is not an even number of hexadecimal digits. */
|
|
17
|
+
export declare function fromHex(text: string): Uint8Array | undefined;
|
package/dist/hex.js
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
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) {
|
|
17
|
+
let out = "";
|
|
18
|
+
for (const b of bytes)
|
|
19
|
+
out += b.toString(16).padStart(2, "0");
|
|
20
|
+
return out;
|
|
21
|
+
}
|
|
22
|
+
/** Hexadecimal text as bytes, or undefined where it is not an even number of hexadecimal digits. */
|
|
23
|
+
export function fromHex(text) {
|
|
24
|
+
if (text.length % 2 !== 0 || !/^[0-9a-fA-F]*$/.test(text))
|
|
25
|
+
return undefined;
|
|
26
|
+
const out = new Uint8Array(text.length / 2);
|
|
27
|
+
for (let i = 0; i < out.length; i++)
|
|
28
|
+
out[i] = Number.parseInt(text.slice(i * 2, i * 2 + 2), 16);
|
|
29
|
+
return out;
|
|
30
|
+
}
|
package/dist/http.d.ts
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Pure HTTP helpers that API clients and servers keep rewriting (commons 0001-formats FR-019): the `Link` header (RFC 8288) read into its
|
|
3
|
+
* 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
|
|
4
|
+
* 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
|
|
5
|
+
* `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`,
|
|
6
|
+
* `connector.ts`), which matched `rel="next"` with a regular expression in two places, and erga's `lib/ts/http` (on `@std/http/etag`).
|
|
7
|
+
*
|
|
8
|
+
* @example
|
|
9
|
+
* ```ts
|
|
10
|
+
* import { nextLink, retryAfterMs } from "./http.js";
|
|
11
|
+
* nextLink('<https://api.example.com/items?page=2>; rel="next", <https://api.example.com/items?page=9>; rel="last"');
|
|
12
|
+
* // "https://api.example.com/items?page=2"
|
|
13
|
+
* retryAfterMs("120", Date.now()); // 120000
|
|
14
|
+
* ```
|
|
15
|
+
*
|
|
16
|
+
* @module
|
|
17
|
+
*/
|
|
18
|
+
/** One link of a `Link` header: its target and its parameters (`rel`, `type`, ...), names in lower case. */
|
|
19
|
+
export type WebLink = {
|
|
20
|
+
readonly target: string;
|
|
21
|
+
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 declare function parseLinkHeader(header: string, base?: string): readonly WebLink[];
|
|
25
|
+
/** The target of the first link whose `rel` names `rel` (`next` by default); a `rel` may name several, separated by spaces. */
|
|
26
|
+
export declare function nextLink(header: string | null | undefined, rel?: string, base?: string): string | undefined;
|
|
27
|
+
/** 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. */
|
|
28
|
+
export declare function retryAfterMs(value: string | null | undefined, now: number): number | undefined;
|
|
29
|
+
/** The methods that only read (RFC 9110 §9.2.1). */
|
|
30
|
+
export declare const SAFE_METHODS: ReadonlySet<string>;
|
|
31
|
+
/** Whether a method only reads; case does not matter. */
|
|
32
|
+
export declare function isSafeMethod(method: string): boolean;
|
|
33
|
+
/** The entity tags of an `If-Match` or `If-None-Match` header, as written (`"abc"`, `W/"abc"`), or `*`. */
|
|
34
|
+
export declare function entityTags(header: string): readonly string[] | "*";
|
|
35
|
+
/** An entity tag for content by its checksum or another stable token: strong (`"token"`), or weak (`W/"token"`). */
|
|
36
|
+
export declare function entityTag(token: string, weak?: boolean): string;
|
|
37
|
+
/**
|
|
38
|
+
* 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
|
|
39
|
+
* absent, is `*`, or names the tag by strong comparison (a weak tag never matches).
|
|
40
|
+
*/
|
|
41
|
+
export declare function ifMatch(header: string | null | undefined, etag: string): boolean;
|
|
42
|
+
/**
|
|
43
|
+
* 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
|
|
44
|
+
* the header is absent or names no tag equal to this one by weak comparison; no where it is `*`.
|
|
45
|
+
*/
|
|
46
|
+
export declare function ifNoneMatch(header: string | null | undefined, etag: string): boolean;
|