kanagata 0.3.2 → 0.5.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.
@@ -0,0 +1,12 @@
1
+ import { type Ty } from "./ty.ts";
2
+ /**
3
+ * The most strings TypeScript builds into one union from a template: it rejects 100,000
4
+ * ("Expression produces a union type that is too complex to represent", TS2590).
5
+ */
6
+ export declare const MAX_UNION = 99999;
7
+ /**
8
+ * The strings an ECMA-262 pattern matches (anywhere in the string, as JSON Schema reads
9
+ * it), as template literal types; undefined where no type says exactly those, where
10
+ * TypeScript would not build their union, or where JavaScript cannot read the pattern.
11
+ */
12
+ export declare function patternType(pattern: string): Ty | undefined;
@@ -0,0 +1,349 @@
1
+ // An ECMA-262 `pattern` → the strings it matches, as template literal types.
2
+ //
3
+ // A pattern says which strings match; a template literal type (`` `https://${string}` ``)
4
+ // says which strings it admits. Where a pattern's strings are exactly a template's (fixed
5
+ // text, finite sets of characters, any text), the pattern is that type; anything else
6
+ // (`.`, `+`, a negated class, lookarounds, …) is no type.
7
+ import { lit, union } from "./ty.js";
8
+ /**
9
+ * The most strings TypeScript builds into one union from a template: it rejects 100,000
10
+ * ("Expression produces a union type that is too complex to represent", TS2590).
11
+ */
12
+ export const MAX_UNION = 99_999;
13
+ const ANY = { any: true };
14
+ /** No type says the strings: a reason not to read further. */
15
+ class NoType extends Error {
16
+ }
17
+ /** How many strings of fixed length a template's sets make. */
18
+ function count(seq) {
19
+ let n = 1;
20
+ for (const s of seq)
21
+ if ("set" in s)
22
+ n *= s.set.length;
23
+ return n;
24
+ }
25
+ function size(lang) {
26
+ let n = 0;
27
+ for (const seq of lang)
28
+ n += count(seq);
29
+ return n;
30
+ }
31
+ /** Strings no more than TypeScript builds into a union. */
32
+ function bounded(lang) {
33
+ if (size(lang) > MAX_UNION)
34
+ throw new NoType();
35
+ return lang;
36
+ }
37
+ /** Every string of `a` followed by every string of `b`. */
38
+ function concat(a, b) {
39
+ const out = [];
40
+ for (const x of a)
41
+ for (const y of b)
42
+ out.push([...x, ...y]);
43
+ return bounded(out);
44
+ }
45
+ const EMPTY = [[]];
46
+ /** Characters that stand for themselves when escaped. */
47
+ const SYNTAX = new Set("^$\\.*+?()[]{}|/");
48
+ const range = (from, to) => Array.from({ length: to - from + 1 }, (_, i) => String.fromCodePoint(from + i));
49
+ const chars = (codes) => codes.map((c) => String.fromCodePoint(c));
50
+ /** The characters `\s` matches: WhiteSpace and LineTerminator (ECMA-262). */
51
+ const SPACE = [
52
+ ...range(0x09, 0x0d),
53
+ ...chars([0x20, 0xa0, 0x1680]),
54
+ ...range(0x2000, 0x200a),
55
+ ...chars([0x2028, 0x2029, 0x202f, 0x205f, 0x3000, 0xfeff]),
56
+ ];
57
+ const DIGIT = range(0x30, 0x39);
58
+ const WORD = [...range(0x41, 0x5a), ...range(0x61, 0x7a), ...DIGIT, "_"];
59
+ /** What a class escape matches; for `\D`, `\S`, `\W`, the escape it negates. */
60
+ const CLASS_ESCAPES = { d: DIGIT, s: SPACE, w: WORD };
61
+ /** A parser over a pattern's code points (the `u` flag: JSON Schema patterns are Unicode). */
62
+ class Parser {
63
+ cs;
64
+ i = 0;
65
+ constructor(pattern) {
66
+ this.cs = [...pattern];
67
+ }
68
+ get done() {
69
+ return this.i >= this.cs.length;
70
+ }
71
+ peek() {
72
+ return this.cs[this.i];
73
+ }
74
+ /** The next code point; the pattern is one RegExp reads, so it does not end where one is due. */
75
+ next() {
76
+ return this.cs[this.i++];
77
+ }
78
+ /** alternation := sequence ('|' sequence)* */
79
+ alternation(top) {
80
+ const alts = [this.sequence(top)];
81
+ while (this.peek() === "|") {
82
+ this.i++;
83
+ alts.push(this.sequence(top));
84
+ }
85
+ return bounded(alts.flat());
86
+ }
87
+ /** A sequence of terms; at the top, `^` and `$` anchor it, and it is unanchored without them. */
88
+ sequence(top) {
89
+ let lang = EMPTY;
90
+ const start = top && this.peek() === "^";
91
+ if (start)
92
+ this.i++;
93
+ else if (top)
94
+ lang = [[ANY]];
95
+ let end = false;
96
+ while (!this.done && this.peek() !== "|" && this.peek() !== ")") {
97
+ if (top && this.peek() === "$") {
98
+ this.i++;
99
+ end = true;
100
+ break;
101
+ }
102
+ lang = concat(lang, this.term());
103
+ }
104
+ if (top && !end)
105
+ lang = concat(lang, [[ANY]]);
106
+ // A `$` before the sequence ends anchors nothing a template says.
107
+ if (end && !this.done && this.peek() !== "|")
108
+ throw new NoType();
109
+ return lang;
110
+ }
111
+ /** term := atom quantifier? */
112
+ term() {
113
+ const atom = this.atom();
114
+ const c = this.peek();
115
+ if (c === "?") {
116
+ this.i++;
117
+ this.lazy();
118
+ if (atom.anyChar)
119
+ throw new NoType();
120
+ return [...EMPTY, ...atom.lang];
121
+ }
122
+ if (c === "*" || c === "+") {
123
+ this.i++;
124
+ this.lazy();
125
+ // Any number of any character is any text; anything else repeated is no template.
126
+ if (c === "*" && atom.anyChar)
127
+ return [[ANY]];
128
+ throw new NoType();
129
+ }
130
+ if (c === "{") {
131
+ // With the `u` flag a `{` here begins a quantifier.
132
+ const m = /^\{(\d+)(,(\d*))?\}/.exec(this.cs.slice(this.i).join(""));
133
+ this.i += m[0].length;
134
+ this.lazy();
135
+ const min = Number(m[1]);
136
+ const max = m[2] === undefined ? min : m[3] === "" ? Infinity : Number(m[3]);
137
+ if (max === Infinity || atom.anyChar)
138
+ throw new NoType();
139
+ let out = [];
140
+ let power = EMPTY;
141
+ for (let k = 0; k <= max; k++) {
142
+ if (k >= min)
143
+ out = bounded([...out, ...power]);
144
+ if (k < max)
145
+ power = concat(power, atom.lang);
146
+ }
147
+ return out;
148
+ }
149
+ if (atom.anyChar)
150
+ throw new NoType();
151
+ return atom.lang;
152
+ }
153
+ /** A `?` after a quantifier makes it lazy, which changes nothing a type says. */
154
+ lazy() {
155
+ if (this.peek() === "?")
156
+ this.i++;
157
+ }
158
+ atom() {
159
+ const c = this.next();
160
+ if (c === "(") {
161
+ if (this.peek() === "?") {
162
+ this.i++;
163
+ const kind = this.next();
164
+ // (?:…) and (?<name>…) group; lookarounds say what no type does.
165
+ if (kind === "<" && this.peek() !== "=" && this.peek() !== "!") {
166
+ while (this.next() !== ">")
167
+ ;
168
+ }
169
+ else if (kind !== ":")
170
+ throw new NoType();
171
+ }
172
+ const lang = this.alternation(false);
173
+ this.next(); // ")"
174
+ return { lang, anyChar: false };
175
+ }
176
+ if (c === "[")
177
+ return this.cls();
178
+ if (c === "\\") {
179
+ const e = this.escape(false);
180
+ if (typeof e === "string")
181
+ return { lang: [[{ set: [e] }]], anyChar: false };
182
+ // \d, \s and \w are sets; \D, \S and \W, everything but one.
183
+ const set = CLASS_ESCAPES[e.cls];
184
+ if (set === undefined)
185
+ throw new NoType();
186
+ return { lang: [[{ set }]], anyChar: false };
187
+ }
188
+ // `.` leaves out line breaks; `^` and `$` here anchor what no template says.
189
+ if (c === "." || c === "^" || c === "$")
190
+ throw new NoType();
191
+ return { lang: [[{ set: [c] }]], anyChar: false };
192
+ }
193
+ /**
194
+ * The character an escape stands for, or the class escape it is (`d`, `D`, …). In a class
195
+ * `\b` is a backspace and `\-` a hyphen; outside it `\b` and `\B` are word boundaries.
196
+ */
197
+ escape(inClass) {
198
+ const c = this.next();
199
+ if (SYNTAX.has(c) || (inClass && c === "-"))
200
+ return c;
201
+ const controls = {
202
+ t: "\t",
203
+ n: "\n",
204
+ v: "\v",
205
+ f: "\f",
206
+ r: "\r",
207
+ };
208
+ if (c in controls)
209
+ return controls[c];
210
+ if (inClass && c === "b")
211
+ return "\b";
212
+ // With the `u` flag `\0` is not followed by a digit.
213
+ if (c === "0")
214
+ return "\0";
215
+ if (c === "c")
216
+ return String.fromCodePoint(this.next().codePointAt(0) % 32);
217
+ if (c === "x")
218
+ return this.hex(2);
219
+ if (c === "u") {
220
+ if (this.peek() !== "{")
221
+ return this.hex(4);
222
+ this.i++;
223
+ let digits = "";
224
+ for (let d = this.next(); d !== "}"; d = this.next())
225
+ digits += d;
226
+ return String.fromCodePoint(Number.parseInt(digits, 16));
227
+ }
228
+ if (c.toLowerCase() in CLASS_ESCAPES)
229
+ return { cls: c };
230
+ // Word boundaries, back references, \k<name>, \p{…}.
231
+ throw new NoType();
232
+ }
233
+ hex(n) {
234
+ let digits = "";
235
+ for (let k = 0; k < n; k++)
236
+ digits += this.next();
237
+ return String.fromCodePoint(Number.parseInt(digits, 16));
238
+ }
239
+ /** `[…]`: a finite set of characters, or any character (`[\s\S]`, `[^]`). */
240
+ cls() {
241
+ const negated = this.peek() === "^";
242
+ if (negated)
243
+ this.i++;
244
+ const set = new Set();
245
+ const escapes = new Set();
246
+ const one = () => {
247
+ const c = this.next();
248
+ return c === "\\" ? this.escape(true) : c;
249
+ };
250
+ while (this.peek() !== "]") {
251
+ const a = one();
252
+ if (typeof a !== "string") {
253
+ escapes.add(a.cls);
254
+ continue;
255
+ }
256
+ if (this.peek() === "-" && this.cs[this.i + 1] !== "]") {
257
+ this.i++;
258
+ // With the `u` flag a range ends at a character, not a class escape.
259
+ const b = one();
260
+ const from = a.codePointAt(0);
261
+ const to = b.codePointAt(0);
262
+ if (to - from >= MAX_UNION)
263
+ throw new NoType();
264
+ for (const x of range(from, to))
265
+ set.add(x);
266
+ }
267
+ else
268
+ set.add(a);
269
+ }
270
+ this.i++;
271
+ let any = false;
272
+ for (const e of escapes) {
273
+ const lower = e.toLowerCase();
274
+ if (e === lower)
275
+ for (const x of CLASS_ESCAPES[lower])
276
+ set.add(x);
277
+ else if (escapes.has(lower))
278
+ any = true;
279
+ else
280
+ throw new NoType();
281
+ }
282
+ if (negated) {
283
+ // [^] is any character; any other negated class is no finite set.
284
+ if (set.size > 0 || escapes.size > 0)
285
+ throw new NoType();
286
+ any = true;
287
+ }
288
+ if (any)
289
+ return { lang: [], anyChar: true };
290
+ if (set.size > MAX_UNION)
291
+ throw new NoType();
292
+ return { lang: [[{ set: [...set] }]], anyChar: false };
293
+ }
294
+ }
295
+ /** Characters a template literal would read as more than themselves. */
296
+ const SPECIAL = /[`\\$\p{Cc}\p{Zl}\p{Zp}]+/gu;
297
+ /** A template written out: fixed text as it is (or as a string where it would be read), sets as unions of strings. */
298
+ function render(seq) {
299
+ // Adjacent single characters are one piece of text, and adjacent any text is one.
300
+ const parts = [];
301
+ for (const s of seq) {
302
+ const last = parts[parts.length - 1];
303
+ if ("set" in s && s.set.length === 1) {
304
+ const c = s.set[0];
305
+ if (typeof last === "string")
306
+ parts[parts.length - 1] = last + c;
307
+ else
308
+ parts.push(c);
309
+ }
310
+ else if (!("any" in s && typeof last === "object" && "any" in last))
311
+ parts.push(s);
312
+ }
313
+ if (parts.every((p) => typeof p === "string"))
314
+ return lit(JSON.stringify(parts.join("")));
315
+ const strings = (values) => `\${${values.map((c) => JSON.stringify(c)).join(" | ")}}`;
316
+ const text = parts
317
+ .map((p) => typeof p === "string"
318
+ ? p.replace(SPECIAL, (run) => strings([run]))
319
+ : "set" in p
320
+ ? strings(p.set)
321
+ : `\${${"string"}}`)
322
+ .join("");
323
+ return { kind: "template", text: `\`${text}\`` };
324
+ }
325
+ /**
326
+ * The strings an ECMA-262 pattern matches (anywhere in the string, as JSON Schema reads
327
+ * it), as template literal types; undefined where no type says exactly those, where
328
+ * TypeScript would not build their union, or where JavaScript cannot read the pattern.
329
+ */
330
+ export function patternType(pattern) {
331
+ try {
332
+ new RegExp(pattern, "u");
333
+ }
334
+ catch {
335
+ return undefined;
336
+ }
337
+ let lang;
338
+ try {
339
+ lang = new Parser(pattern).alternation(true);
340
+ }
341
+ catch {
342
+ // NoType: the parser throws nothing else on a pattern RegExp reads.
343
+ return undefined;
344
+ }
345
+ // A template keeps the pattern, so that the values next to it can be read against it.
346
+ return union(lang
347
+ .map(render)
348
+ .map((t) => (t.kind === "template" ? { ...t, pattern } : t)));
349
+ }
package/dist/ty.d.ts CHANGED
@@ -6,6 +6,11 @@ export interface Prop {
6
6
  /** A key a JSON object must have: its value is a JSON value, never `undefined` (see `presentKeys`). */
7
7
  present?: true;
8
8
  }
9
+ /** An index signature by a template literal type: `[key: `x-${string}`]: ty`. */
10
+ export interface Keyed {
11
+ key: Ty;
12
+ ty: Ty;
13
+ }
9
14
  /** Which view of a component schema a reference means: as returned, or as sent. */
10
15
  export type View = "read" | "write";
11
16
  export type Ty = {
@@ -42,6 +47,15 @@ export type Ty = {
42
47
  kind: "lit";
43
48
  text: string;
44
49
  }
50
+ /**
51
+ * A template literal type, as printed: `` `https://${"us" | "eu"}.example.com` ``; the
52
+ * `pattern` it is from, if it is, tells which strings it admits.
53
+ */
54
+ | {
55
+ kind: "template";
56
+ text: string;
57
+ pattern?: string;
58
+ }
45
59
  /** A component schema, by its key in `components.schemas`; named when emitted. */
46
60
  | {
47
61
  kind: "ref";
@@ -71,11 +85,15 @@ export type Ty = {
71
85
  kind: "object";
72
86
  props: Prop[];
73
87
  }
74
- /** Object literal with an index signature: `{ a: A; [key: string]: T }`. */
88
+ /**
89
+ * Object literal with index signatures: `{ a: A; [key: `x-${string}`]: K; [key: string]: T }`,
90
+ * `keyed` by template literal types, `index` by any string.
91
+ */
75
92
  | {
76
93
  kind: "map";
77
94
  props: Prop[];
78
- index: Ty;
95
+ index?: Ty;
96
+ keyed?: Keyed[];
79
97
  } | {
80
98
  kind: "union";
81
99
  items: Ty[];
@@ -105,8 +123,11 @@ export declare const object: (props: Prop[]) => Ty;
105
123
  export declare const tuple: (items: Ty[]) => Ty;
106
124
  /** A required property without documentation. */
107
125
  export declare const prop: (key: string, ty: Ty) => Prop;
108
- /** Structural equality; with `views: false`, references to either view of a schema are equal. */
109
- export declare function equal(a: Ty, b: Ty, views?: boolean): boolean;
126
+ /**
127
+ * Structural equality. References to two views of a schema differ only where `views` says
128
+ * the schema's views differ: always (`true`), never (`false`), or for the schemas in it.
129
+ */
130
+ export declare function equal(a: Ty, b: Ty, views?: boolean | ReadonlySet<string>): boolean;
110
131
  /** Every component schema a type refers to. */
111
132
  export declare function refs(t: Ty, out?: Set<string>): Set<string>;
112
133
  /**
@@ -127,6 +148,7 @@ export declare function admitsAny(t: Ty, resolve: (r: {
127
148
  * admits any value (`any`): such a type admits `undefined` in TypeScript, which would
128
149
  * stay in the type another member gives (`{ a?: string } & { a: unknown }` reads `a`
129
150
  * as `string | undefined`), while JSON has no `undefined`. `unknown` becomes `{} | null`.
151
+ * A type with no such key is kept as it is.
130
152
  */
131
153
  export declare function presentKeys(t: Ty, any: (t: Ty) => boolean): Ty;
132
154
  /**
@@ -141,3 +163,5 @@ export declare function union(items: Ty[]): Ty;
141
163
  * collapses to `never` if any member is `never`, and unwraps a single member.
142
164
  */
143
165
  export declare function inter(items: Ty[]): Ty;
166
+ /** Whether two types of JSON values are the same value: literals by value (`1` and `1.0`), others by structure. */
167
+ export declare function equalValues(a: Ty, b: Ty): boolean;