@libo11y/spec 0.0.0-stage → 0.1.2

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/dist/yamlv3.js ADDED
@@ -0,0 +1,335 @@
1
+ /**
2
+ * Ports of the gopkg.in/yaml.v3 behaviours parseAppRegistry must reproduce where the `yaml` library,
3
+ * which follows YAML 1.2, differs: the characters the reader accepts, the double-quoted escapes the
4
+ * scanner accepts, and how an explicitly tagged scalar resolves. Internal to @libo11y/spec.
5
+ */
6
+ /** A problem yaml.v3 reports as a fatal error, which Go's conformance cases name `syntax`. */
7
+ export class YamlSyntaxError extends Error {
8
+ constructor(message) {
9
+ super(message);
10
+ this.name = "YamlSyntaxError";
11
+ }
12
+ }
13
+ // yaml.v3's reader accepts tab, line feed, carriage return, printable ASCII, NEL, and the BMP and
14
+ // astral ranges except surrogates, U+FFFE and U+FFFF. Anything else is "control characters are not
15
+ // allowed". With the u flag, a lone surrogate in the string matches too.
16
+ const INVALID_CHARACTER = /[^\t\n\r\u{20}-\u{7e}\u{85}\u{a0}-\u{d7ff}\u{e000}-\u{fffd}\u{10000}-\u{10ffff}]/u;
17
+ /** Throws YamlSyntaxError when text holds a character yaml.v3's reader rejects. */
18
+ export function checkCharacters(text) {
19
+ const bad = INVALID_CHARACTER.exec(text);
20
+ if (bad !== null) {
21
+ const cp = bad[0].codePointAt(0) ?? 0;
22
+ throw new YamlSyntaxError(`control characters are not allowed: U+${cp.toString(16).toUpperCase().padStart(4, "0")}`);
23
+ }
24
+ }
25
+ const SIMPLE_ESCAPES = new Set([
26
+ "0",
27
+ "a",
28
+ "b",
29
+ "t",
30
+ "\t",
31
+ "n",
32
+ "v",
33
+ "f",
34
+ "r",
35
+ "e",
36
+ " ",
37
+ '"',
38
+ "'",
39
+ "\\",
40
+ "N",
41
+ "_",
42
+ "L",
43
+ "P",
44
+ ]);
45
+ const LINE_BREAKS = new Set(["\n", "\r", "\u0085", "
", "
"]);
46
+ const HEX_LENGTH = { x: 2, u: 4, U: 8 };
47
+ const HEX = /^[0-9a-fA-F]+$/;
48
+ /**
49
+ * Checks the escapes in a double-quoted scalar's source, quotes included, against yaml.v3's scanner, and
50
+ * returns the offsets within raw of every `\'`. yaml.v3 accepts `\'` and the `yaml` library, following
51
+ * YAML 1.2, rejects it. YAML 1.2's `\/` is the reverse. Throws YamlSyntaxError on an escape yaml.v3
52
+ * rejects.
53
+ */
54
+ export function scanEscapes(raw) {
55
+ const quotes = [];
56
+ for (let i = 1; i < raw.length - 1; i++) {
57
+ if (raw[i] !== "\\")
58
+ continue;
59
+ const c = raw[i + 1] ?? "";
60
+ if (LINE_BREAKS.has(c) || SIMPLE_ESCAPES.has(c)) {
61
+ if (c === "'")
62
+ quotes.push(i);
63
+ i++;
64
+ continue;
65
+ }
66
+ const length = HEX_LENGTH[c];
67
+ if (length === undefined)
68
+ throw new YamlSyntaxError(`found unknown escape character ${JSON.stringify(c)}`);
69
+ const hex = raw.slice(i + 2, i + 2 + length);
70
+ if (hex.length !== length || !HEX.test(hex)) {
71
+ throw new YamlSyntaxError("did not find expected hexdecimal number");
72
+ }
73
+ const value = Number.parseInt(hex, 16);
74
+ if ((value >= 0xd800 && value <= 0xdfff) || value > 0x10ffff) {
75
+ throw new YamlSyntaxError("found invalid Unicode character escape code");
76
+ }
77
+ i += 1 + length;
78
+ }
79
+ return quotes;
80
+ }
81
+ const LONG_TAG_PREFIX = "tag:yaml.org,2002:";
82
+ /** yaml.v3's shortTag: `tag:yaml.org,2002:int` becomes `!!int`. An absent tag is "". */
83
+ export function shortTag(tag) {
84
+ if (tag === undefined)
85
+ return "";
86
+ return tag.startsWith(LONG_TAG_PREFIX) ? `!!${tag.slice(LONG_TAG_PREFIX.length)}` : tag;
87
+ }
88
+ const NULL = "!!null";
89
+ const BOOL = "!!bool";
90
+ const STR = "!!str";
91
+ const INT = "!!int";
92
+ const FLOAT = "!!float";
93
+ const TIMESTAMP = "!!timestamp";
94
+ const BINARY = "!!binary";
95
+ const MERGE = "!!merge";
96
+ const RESOLVABLE = new Set(["", STR, BOOL, INT, FLOAT, NULL, TIMESTAMP]);
97
+ const RESOLVE_MAP = new Map([
98
+ ...["true", "True", "TRUE", "false", "False", "FALSE"].map((s) => [s, BOOL]),
99
+ ...["", "~", "null", "Null", "NULL"].map((s) => [s, NULL]),
100
+ ...[
101
+ ".nan",
102
+ ".NaN",
103
+ ".NAN",
104
+ ".inf",
105
+ ".Inf",
106
+ ".INF",
107
+ "+.inf",
108
+ "+.Inf",
109
+ "+.INF",
110
+ "-.inf",
111
+ "-.Inf",
112
+ "-.INF",
113
+ ].map((s) => [s, FLOAT]),
114
+ ["<<", MERGE],
115
+ ]);
116
+ // hint is yaml.v3's resolveTable: what the first byte says a plain scalar might be.
117
+ function hint(s) {
118
+ if (s === "")
119
+ return "N";
120
+ const c = s[0] ?? "";
121
+ if (c === "+" || c === "-")
122
+ return "S";
123
+ if (c >= "0" && c <= "9")
124
+ return "D";
125
+ if ("yYnNtTfFoO~".includes(c))
126
+ return "M";
127
+ return c === "." ? "." : "";
128
+ }
129
+ const INT64_MAX = 2n ** 63n - 1n;
130
+ const UINT64_MAX = 2n ** 64n - 1n;
131
+ // parseUnsigned is Go's strconv.ParseUint digits loop for one base, as a bigint, or undefined.
132
+ function parseDigits(s, base) {
133
+ if (s === "")
134
+ return undefined;
135
+ let n = 0n;
136
+ for (const ch of s) {
137
+ const d = Number.parseInt(ch, 36);
138
+ if (Number.isNaN(d) || d >= base)
139
+ return undefined;
140
+ n = n * BigInt(base) + BigInt(d);
141
+ }
142
+ return n;
143
+ }
144
+ // goParseUint is strconv.ParseUint(s, base, 64). Base 0 reads a 0b, 0o, 0x or leading-0 prefix.
145
+ function goParseUint(s, base) {
146
+ if (s === "")
147
+ return undefined;
148
+ let b = base;
149
+ let digits = s;
150
+ if (base === 0) {
151
+ b = 10;
152
+ if (s[0] === "0") {
153
+ const p = (s[1] ?? "").toLowerCase();
154
+ if (s.length >= 3 && p === "b")
155
+ [b, digits] = [2, s.slice(2)];
156
+ else if (s.length >= 3 && p === "o")
157
+ [b, digits] = [8, s.slice(2)];
158
+ else if (s.length >= 3 && p === "x")
159
+ [b, digits] = [16, s.slice(2)];
160
+ else
161
+ [b, digits] = [8, s.slice(1)];
162
+ if (b === 8 && digits === "" && s === "0")
163
+ return 0n;
164
+ }
165
+ }
166
+ const n = parseDigits(digits, b);
167
+ return n === undefined || n > UINT64_MAX ? undefined : n;
168
+ }
169
+ // goParseInt is strconv.ParseInt(s, base, 64).
170
+ function goParseInt(s, base) {
171
+ if (s === "")
172
+ return undefined;
173
+ const negative = s[0] === "-";
174
+ const body = s[0] === "+" || s[0] === "-" ? s.slice(1) : s;
175
+ const n = goParseUint(body, base);
176
+ if (n === undefined)
177
+ return undefined;
178
+ if (negative ? n > INT64_MAX + 1n : n > INT64_MAX)
179
+ return undefined;
180
+ return negative ? -n : n;
181
+ }
182
+ // A float strconv.ParseFloat accepts that is not out of range. The syntax is checked by the caller.
183
+ function finiteFloat(s) {
184
+ return Number.isFinite(Number(s));
185
+ }
186
+ const YAML_STYLE_FLOAT = /^[-+]?(\.[0-9]+|[0-9]+(\.[0-9]*)?)([eE][-+]?[0-9]+)?$/;
187
+ const DOT_FLOAT = /^\.[0-9]+([eE][-+]?[0-9]+)?$/;
188
+ const TIMESTAMP_FORMATS = [
189
+ /^(\d{4})-(\d\d?)-(\d\d?)T(\d\d?):(\d\d?):(\d\d?)(?:[.,]\d+)?(Z|[+-](\d\d):(\d\d))$/,
190
+ /^(\d{4})-(\d\d?)-(\d\d?)t(\d\d?):(\d\d?):(\d\d?)(?:[.,]\d+)?(Z|[+-](\d\d):(\d\d))$/,
191
+ /^(\d{4})-(\d\d?)-(\d\d?) (\d\d?):(\d\d?):(\d\d?)(?:[.,]\d+)?$/,
192
+ /^(\d{4})-(\d\d?)-(\d\d?)$/,
193
+ ];
194
+ function daysIn(month, year) {
195
+ if (month === 2)
196
+ return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0) ? 29 : 28;
197
+ return [4, 6, 9, 11].includes(month) ? 30 : 31;
198
+ }
199
+ // parseTimestamp is yaml.v3's parseTimestamp: Go's time.Parse with its four layouts, whose fields take
200
+ // one or two digits and are range-checked.
201
+ function parseTimestamp(s) {
202
+ if (!/^\d{4}-/.test(s))
203
+ return false;
204
+ for (const format of TIMESTAMP_FORMATS) {
205
+ const m = format.exec(s);
206
+ if (m === null)
207
+ continue;
208
+ const [year, month, day, hour = 0, minute = 0, second = 0] = m.slice(1, 7).map((v) => Number(v ?? 0));
209
+ if (month === undefined || day === undefined || year === undefined)
210
+ continue;
211
+ if (month < 1 || month > 12 || day < 1 || day > daysIn(month, year))
212
+ continue;
213
+ if (hour > 23 || minute > 59 || second > 59)
214
+ continue;
215
+ if (m[8] !== undefined && (Number(m[8]) > 24 || Number(m[9]) > 60))
216
+ continue;
217
+ return true;
218
+ }
219
+ return false;
220
+ }
221
+ // classify is the body of yaml.v3's resolve: the tag a plain value resolves to under the given tag.
222
+ function classify(tag, s) {
223
+ const h = hint(s);
224
+ if (h === "" || tag === STR)
225
+ return { tag: STR };
226
+ const fromMap = RESOLVE_MAP.get(s);
227
+ if (fromMap !== undefined)
228
+ return { tag: fromMap };
229
+ if (h === "." && DOT_FLOAT.test(s) && finiteFloat(s))
230
+ return { tag: FLOAT };
231
+ if (h === "D" || h === "S") {
232
+ if ((tag === "" || tag === TIMESTAMP) && parseTimestamp(s))
233
+ return { tag: TIMESTAMP };
234
+ const plain = s.replaceAll("_", "");
235
+ if (goParseInt(plain, 0) !== undefined)
236
+ return { tag: INT };
237
+ if (goParseUint(plain, 0) !== undefined)
238
+ return { tag: INT, unsigned: true };
239
+ if (YAML_STYLE_FLOAT.test(plain) && finiteFloat(plain))
240
+ return { tag: FLOAT };
241
+ if (plain.startsWith("0b")) {
242
+ if (goParseInt(plain.slice(2), 2) !== undefined)
243
+ return { tag: INT };
244
+ if (goParseUint(plain.slice(2), 2) !== undefined)
245
+ return { tag: INT, unsigned: true };
246
+ }
247
+ else if (plain.startsWith("-0b")) {
248
+ if (goParseInt(`-${plain.slice(3)}`, 2) !== undefined)
249
+ return { tag: INT };
250
+ }
251
+ if (plain.startsWith("0o")) {
252
+ if (goParseInt(plain.slice(2), 8) !== undefined)
253
+ return { tag: INT };
254
+ if (goParseUint(plain.slice(2), 8) !== undefined)
255
+ return { tag: INT, unsigned: true };
256
+ }
257
+ else if (plain.startsWith("-0o")) {
258
+ if (goParseInt(`-${plain.slice(3)}`, 8) !== undefined)
259
+ return { tag: INT };
260
+ }
261
+ }
262
+ return { tag: STR };
263
+ }
264
+ const BASE64 = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/;
265
+ const BASE64_ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
266
+ /** Decodes bytes as UTF-8, or as UTF-16 after a UTF-16 byte order mark, as yaml.v3's reader does. */
267
+ export function decodeInput(bytes) {
268
+ let label = "utf-8";
269
+ let input = bytes;
270
+ if (bytes[0] === 0xff && bytes[1] === 0xfe) {
271
+ label = "utf-16le";
272
+ }
273
+ else if (bytes[0] === 0xfe && bytes[1] === 0xff) {
274
+ // Swap to little-endian, which every runtime's TextDecoder supports.
275
+ label = "utf-16le";
276
+ input = new Uint8Array(bytes.length);
277
+ for (let i = 0; i + 1 < bytes.length; i += 2) {
278
+ input[i] = bytes[i + 1];
279
+ input[i + 1] = bytes[i];
280
+ }
281
+ if (bytes.length % 2 === 1)
282
+ input[bytes.length - 1] = bytes[bytes.length - 1];
283
+ }
284
+ try {
285
+ return new TextDecoder(label, { fatal: true }).decode(input);
286
+ }
287
+ catch {
288
+ throw new YamlSyntaxError(`invalid ${label === "utf-8" ? "UTF-8" : "UTF-16"} input`);
289
+ }
290
+ }
291
+ // decodeBase64 is Go's base64.StdEncoding.DecodeString, which skips line breaks, as UTF-8 text.
292
+ function decodeBase64(s) {
293
+ const compact = s.replace(/[\r\n]/g, "");
294
+ if (!BASE64.test(compact))
295
+ throw new YamlSyntaxError("!!binary value contains invalid base64 data");
296
+ const bytes = [];
297
+ let bits = 0;
298
+ let buffer = 0;
299
+ for (const ch of compact) {
300
+ if (ch === "=")
301
+ break;
302
+ buffer = (buffer << 6) | BASE64_ALPHABET.indexOf(ch);
303
+ bits += 6;
304
+ if (bits >= 8) {
305
+ bits -= 8;
306
+ bytes.push((buffer >> bits) & 0xff);
307
+ }
308
+ }
309
+ return new TextDecoder("utf-8").decode(new Uint8Array(bytes));
310
+ }
311
+ /**
312
+ * Resolves a scalar the way yaml.v3's decoder does before storing it in a Go string. value is yaml.v3's
313
+ * Node.Value, the folded text before tag resolution. quotedOrBlock is true for any non-plain style.
314
+ * Throws YamlSyntaxError when an explicit tag does not fit the value, as yaml.v3 does.
315
+ */
316
+ export function resolveScalar(tag, value, quotedOrBlock) {
317
+ const short = shortTag(tag);
318
+ if (short === STR || ((short === "" || short === "!") && quotedOrBlock)) {
319
+ return { isNull: false, text: value, isString: true };
320
+ }
321
+ if (!RESOLVABLE.has(short)) {
322
+ return short === BINARY
323
+ ? { isNull: false, text: decodeBase64(value), isString: true }
324
+ : { isNull: false, text: value, isString: true };
325
+ }
326
+ let resolved = classify(short, value);
327
+ if (short === FLOAT && resolved.tag === INT && resolved.unsigned !== true)
328
+ resolved = { tag: FLOAT };
329
+ if (short !== "" && short !== resolved.tag) {
330
+ throw new YamlSyntaxError(`cannot decode ${resolved.tag} \`${value}\` as a ${short}`);
331
+ }
332
+ if (resolved.tag === NULL)
333
+ return { isNull: true };
334
+ return { isNull: false, text: value, isString: resolved.tag === STR || resolved.tag === MERGE };
335
+ }
package/package.json CHANGED
@@ -1,6 +1,38 @@
1
1
  {
2
2
  "name": "@libo11y/spec",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.2",
4
+ "description": "The libo11y telemetry specification for TypeScript: attribute keys, enums, event and metric names, and the sensitivity tables, generated from spec/registry.",
5
+ "license": "Apache-2.0",
6
+ "type": "module",
7
+ "sideEffects": false,
8
+ "exports": {
9
+ ".": {
10
+ "types": "./dist/index.d.ts",
11
+ "default": "./dist/index.js"
12
+ },
13
+ "./yaml": {
14
+ "types": "./dist/yaml.d.ts",
15
+ "default": "./dist/yaml.js"
16
+ }
17
+ },
18
+ "bin": {
19
+ "libo11y": "./dist/cli.js"
20
+ },
21
+ "repository": {
22
+ "type": "git",
23
+ "url": "git+https://github.com/jamesainslie/libo11y.git",
24
+ "directory": "ts/packages/spec"
25
+ },
26
+ "dependencies": {
27
+ "yaml": "2.9.1"
28
+ },
29
+ "files": [
30
+ "dist",
31
+ "README.md",
32
+ "LICENSE"
33
+ ],
34
+ "publishConfig": {
35
+ "access": "public",
36
+ "provenance": true
37
+ }
38
+ }