@amritk/helpers 0.22.0 → 0.23.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.
package/README.md CHANGED
@@ -112,8 +112,7 @@ Most helpers have a colocated test file (`*.test.ts`) — read those for canonic
112
112
 
113
113
  ## Related packages
114
114
 
115
- - [`@amritk/generate-parsers`](../generate-parsers) — primary consumer
116
- - [`@amritk/generate-validators`](../generate-validators) — primary consumer
115
+ - [`@amritk/parsers`](../parsers) — primary consumer
117
116
  - [`@amritk/mjst`](../cli) — the CLI surface
118
117
 
119
118
  ---
@@ -0,0 +1,26 @@
1
+ /**
2
+ * Builds a default string for a `pattern`-constrained schema — a value a
3
+ * coercing parser can fall back to when the input cannot be repaired.
4
+ *
5
+ * The one invariant: **a returned default always matches the pattern it was
6
+ * built from** (and any length bounds handed in alongside it). Every candidate,
7
+ * synthesized or recognized, is tested against the real `RegExp` before it is
8
+ * returned, and anything that fails is discarded. That check is the whole point.
9
+ * Without it this returned a value the schema rejects — `'^\\+?\\d{3}\\d{4}$'`
10
+ * was answered with `"+1234567890"`, which has three digits too many — so a
11
+ * coercing parser "repaired" input into a document still invalid against its own
12
+ * schema, and the array or object built around it was invalid for the same
13
+ * reason.
14
+ *
15
+ * Two sources of candidates, in order:
16
+ *
17
+ * 1. {@link synthesize}, which reads the pattern and constructs a matching
18
+ * string from it. This covers the ordinary shapes real schemas use — slugs,
19
+ * identifiers, fixed-width codes — that no fixed list can anticipate.
20
+ * 2. A short list of well-known shapes (email, UUID, URL, semver, ISO date),
21
+ * which read better than a synthesized `"aaa"` when they happen to fit.
22
+ *
23
+ * Returns `null` when nothing verifies, which callers already treat as "no
24
+ * usable default" — the safe answer, and far better than a confident wrong one.
25
+ */
26
+ export declare const generateDefaultFromPattern: (pattern: string, minLength?: number, maxLength?: number) => string | null;
@@ -0,0 +1,223 @@
1
+ const RECOGNIZED_DEFAULTS = [
2
+ "user@example.com",
3
+ "00000000-0000-0000-0000-000000000000",
4
+ "https://example.com",
5
+ "1.0.0",
6
+ "2000-01-01",
7
+ "+1234567890"
8
+ ];
9
+ const UNSUPPORTED = /\(\?[=!<]|\\[1-9]|\\b|\\B/;
10
+ const PREFERRED = "abcdefghijklmnopqrstuvwxyz0123456789";
11
+ const escapedChar = (sequence) => {
12
+ switch (sequence) {
13
+ case "d":
14
+ return "0";
15
+ case "w":
16
+ return "a";
17
+ case "s":
18
+ return " ";
19
+ case "D":
20
+ case "S":
21
+ return "a";
22
+ case "W":
23
+ return "-";
24
+ case "n":
25
+ return "\n";
26
+ case "t":
27
+ return " ";
28
+ case "r":
29
+ return "\r";
30
+ default:
31
+ return null;
32
+ }
33
+ };
34
+ const ONCE = { min: 1, max: 1 };
35
+ const pickFromClass = (body) => {
36
+ const negated = body.startsWith("^");
37
+ const source = negated ? body.slice(1) : body;
38
+ const members = [];
39
+ for (let i = 0; i < source.length; i++) {
40
+ const char = source[i];
41
+ if (char === "\\") {
42
+ const next = source[++i];
43
+ if (next === void 0)
44
+ return null;
45
+ members.push(escapedChar(next) ?? next);
46
+ continue;
47
+ }
48
+ if (source[i + 1] === "-" && i + 2 < source.length && source[i + 2] !== "]") {
49
+ const low = char;
50
+ const high = source[i + 2];
51
+ const preferred = [...PREFERRED].find((candidate) => candidate >= low && candidate <= high);
52
+ members.push(preferred ?? low);
53
+ i += 2;
54
+ continue;
55
+ }
56
+ members.push(char);
57
+ }
58
+ if (!negated) {
59
+ return [...PREFERRED].find((candidate) => members.includes(candidate)) ?? members[0] ?? null;
60
+ }
61
+ return [...PREFERRED].find((candidate) => !members.includes(candidate)) ?? null;
62
+ };
63
+ const readQuantifier = (pattern, start) => {
64
+ const char = pattern[start];
65
+ let quantifier = ONCE;
66
+ let next = start;
67
+ if (char === "*") {
68
+ quantifier = { min: 0, max: Number.POSITIVE_INFINITY };
69
+ next = start + 1;
70
+ } else if (char === "+") {
71
+ quantifier = { min: 1, max: Number.POSITIVE_INFINITY };
72
+ next = start + 1;
73
+ } else if (char === "?") {
74
+ quantifier = { min: 0, max: 1 };
75
+ next = start + 1;
76
+ } else if (char === "{") {
77
+ const close = pattern.indexOf("}", start);
78
+ const body = close === -1 ? null : pattern.slice(start + 1, close);
79
+ const match = body === null ? null : /^(\d+)(,(\d*)?)?$/.exec(body);
80
+ if (match && close !== -1) {
81
+ const min = Number(match[1]);
82
+ const max = match[2] === void 0 ? min : match[3] ? Number(match[3]) : Number.POSITIVE_INFINITY;
83
+ quantifier = { min, max };
84
+ next = close + 1;
85
+ }
86
+ }
87
+ if (quantifier !== ONCE && (pattern[next] === "?" || pattern[next] === "+"))
88
+ next += 1;
89
+ return { quantifier, next };
90
+ };
91
+ const parseAlternatives = (pattern, start, stop) => {
92
+ const alternatives = [];
93
+ let current = [];
94
+ let i = start;
95
+ while (i < stop) {
96
+ const char = pattern[i];
97
+ if (char === ")")
98
+ break;
99
+ if (char === "|") {
100
+ alternatives.push(current);
101
+ current = [];
102
+ i += 1;
103
+ continue;
104
+ }
105
+ let node = null;
106
+ if (char === "(") {
107
+ let bodyStart = i + 1;
108
+ if (pattern.startsWith("(?:", i))
109
+ bodyStart = i + 3;
110
+ else if (pattern.startsWith("(?<", i)) {
111
+ const close = pattern.indexOf(">", i);
112
+ if (close === -1)
113
+ return { alternatives: [], next: stop };
114
+ bodyStart = close + 1;
115
+ }
116
+ const inner = parseAlternatives(pattern, bodyStart, stop);
117
+ if (pattern[inner.next] !== ")")
118
+ return { alternatives: [], next: stop };
119
+ const { quantifier, next } = readQuantifier(pattern, inner.next + 1);
120
+ node = { kind: "group", alternatives: inner.alternatives, quantifier };
121
+ i = next;
122
+ } else if (char === "[") {
123
+ let end = i + 1;
124
+ if (pattern[end] === "^")
125
+ end += 1;
126
+ if (pattern[end] === "]")
127
+ end += 1;
128
+ while (end < stop && pattern[end] !== "]")
129
+ end += pattern[end] === "\\" ? 2 : 1;
130
+ if (end >= stop)
131
+ return { alternatives: [], next: stop };
132
+ const picked = pickFromClass(pattern.slice(i + 1, end));
133
+ if (picked === null)
134
+ return { alternatives: [], next: stop };
135
+ const { quantifier, next } = readQuantifier(pattern, end + 1);
136
+ node = { kind: "class", value: picked, quantifier };
137
+ i = next;
138
+ } else if (char === "\\") {
139
+ const sequence = pattern[i + 1];
140
+ if (sequence === void 0)
141
+ return { alternatives: [], next: stop };
142
+ const { quantifier, next } = readQuantifier(pattern, i + 2);
143
+ node = { kind: "literal", value: escapedChar(sequence) ?? sequence, quantifier };
144
+ i = next;
145
+ } else if (char === ".") {
146
+ const { quantifier, next } = readQuantifier(pattern, i + 1);
147
+ node = { kind: "class", value: "a", quantifier };
148
+ i = next;
149
+ } else if (char === "^" || char === "$") {
150
+ i += 1;
151
+ continue;
152
+ } else {
153
+ const { quantifier, next } = readQuantifier(pattern, i + 1);
154
+ node = { kind: "literal", value: char, quantifier };
155
+ i = next;
156
+ }
157
+ current.push(node);
158
+ }
159
+ alternatives.push(current);
160
+ return { alternatives, next: i };
161
+ };
162
+ const render = (nodes, budget) => {
163
+ let out = "";
164
+ for (const node of nodes) {
165
+ const { min, max } = node.quantifier;
166
+ const count = Math.min(min + (max > min ? budget : 0), max);
167
+ const unit = node.kind === "group" ? render(node.alternatives[0] ?? [], budget) : node.value;
168
+ out += unit.repeat(count);
169
+ }
170
+ return out;
171
+ };
172
+ const synthesize = (pattern) => {
173
+ if (UNSUPPORTED.test(pattern))
174
+ return [];
175
+ const { alternatives } = parseAlternatives(pattern, 0, pattern.length);
176
+ const candidates = [];
177
+ for (const alternative of alternatives) {
178
+ for (let budget = 0; budget <= 64; budget++) {
179
+ const rendered = render(alternative, budget);
180
+ candidates.push(rendered);
181
+ if (rendered.length > 512)
182
+ break;
183
+ }
184
+ }
185
+ return candidates;
186
+ };
187
+ const compile = (pattern) => {
188
+ try {
189
+ return new RegExp(pattern, "u");
190
+ } catch {
191
+ try {
192
+ return new RegExp(pattern);
193
+ } catch {
194
+ return null;
195
+ }
196
+ }
197
+ };
198
+ const generateDefaultFromPattern = (pattern, minLength, maxLength) => {
199
+ if (pattern === "")
200
+ return null;
201
+ const regex = compile(pattern);
202
+ if (regex === null)
203
+ return null;
204
+ const low = typeof minLength === "number" && minLength > 0 ? minLength : 0;
205
+ const high = typeof maxLength === "number" && maxLength >= 0 ? maxLength : Number.POSITIVE_INFINITY;
206
+ const fits = (candidate) => {
207
+ if (candidate.length < low || candidate.length > high)
208
+ return false;
209
+ return regex.test(candidate);
210
+ };
211
+ for (const candidate of RECOGNIZED_DEFAULTS) {
212
+ if (fits(candidate))
213
+ return JSON.stringify(candidate);
214
+ }
215
+ for (const candidate of synthesize(pattern)) {
216
+ if (fits(candidate))
217
+ return JSON.stringify(candidate);
218
+ }
219
+ return null;
220
+ };
221
+ export {
222
+ generateDefaultFromPattern
223
+ };
@@ -58,6 +58,25 @@ const requiredOf = (schema) => {
58
58
  const declared = keywordOf(schema, "required");
59
59
  return Array.isArray(declared) ? declared.filter((key) => typeof key === "string") : [];
60
60
  };
61
+ const propertyDescription = (propSchema) => {
62
+ if (!isSchemaObject(propSchema))
63
+ return void 0;
64
+ const description = keywordOf(propSchema, "description");
65
+ if (typeof description === "string")
66
+ return description;
67
+ const comment = keywordOf(propSchema, "$comment");
68
+ if (typeof comment === "string")
69
+ return comment;
70
+ return void 0;
71
+ };
72
+ const intersectProperties = (existing, sub) => {
73
+ if (existing === void 0 || existing === true)
74
+ return sub;
75
+ if (sub === true)
76
+ return existing;
77
+ const description = propertyDescription(sub) ?? propertyDescription(existing);
78
+ return description === void 0 ? { allOf: [existing, sub] } : { allOf: [existing, sub], description };
79
+ };
61
80
  const literalDomain = (schema) => {
62
81
  if (schema === void 0 || !isSchemaObject(schema))
63
82
  return void 0;
@@ -132,7 +151,7 @@ const branchOf = (fragments, options, depth) => {
132
151
  for (const key of Object.keys(declared)) {
133
152
  const sub = readKey(declared, key);
134
153
  const existing = readKey(properties, key);
135
- assignKey(properties, key, existing === void 0 ? sub : { allOf: [existing, sub] });
154
+ assignKey(properties, key, intersectProperties(existing, sub));
136
155
  }
137
156
  for (const key of requiredOf(fragment))
138
157
  required.add(key);
@@ -527,17 +546,6 @@ const overlappingKeys = (keys) => {
527
546
  }
528
547
  return false;
529
548
  };
530
- const propertyDescription = (propSchema) => {
531
- if (!isSchemaObject(propSchema))
532
- return void 0;
533
- const description = keywordOf(propSchema, "description");
534
- if (typeof description === "string")
535
- return description;
536
- const comment = keywordOf(propSchema, "$comment");
537
- if (typeof comment === "string")
538
- return comment;
539
- return void 0;
540
- };
541
549
  const objectTypeToTs = (schema, options, depth) => {
542
550
  const indexes = getIndexSignatures(schema, options, depth);
543
551
  const properties = keywordOf(schema, "properties");
@@ -695,18 +703,18 @@ const unionBranchType = (branch, domain, options, depth) => {
695
703
  const own = keywordMap(branch, "properties");
696
704
  if (required.length === 0)
697
705
  return standalone();
706
+ const declaredBy = (key) => domain === void 0 ? void 0 : readKey(domain, key);
698
707
  const properties = {};
699
- for (const key of required) {
700
- const declared = domain === void 0 ? void 0 : readKey(domain, key);
701
- assignKey(properties, key, declared === void 0 ? true : declared);
702
- }
703
708
  if (own !== void 0) {
704
709
  for (const key of Object.keys(own)) {
705
- const sub = readKey(own, key);
706
- const existing = readKey(properties, key);
707
- assignKey(properties, key, existing === void 0 ? sub : { allOf: [existing, sub] });
710
+ assignKey(properties, key, intersectProperties(declaredBy(key), readKey(own, key)));
708
711
  }
709
712
  }
713
+ for (const key of required) {
714
+ if (Object.hasOwn(properties, key))
715
+ continue;
716
+ assignKey(properties, key, declaredBy(key) ?? true);
717
+ }
710
718
  return objectTypeToTs({ type: "object", properties, required: [...required] }, options, depth);
711
719
  };
712
720
  const unionBranchesOf = (schema) => {
@@ -0,0 +1,7 @@
1
+ import type { JSONSchema } from 'json-schema-typed/draft-2020-12';
2
+ /**
3
+ * Returns the default value for a JSON Schema property.
4
+ * Priority order: explicit default > first enum value > first example > union first schema > pattern-based > type-based.
5
+ * These defaults ensure that parsing never fails, even with missing data.
6
+ */
7
+ export declare const getDefaultValue: (schema: JSONSchema) => string;
@@ -0,0 +1,155 @@
1
+ import { generateDefaultFromPattern } from "./generate-default-from-pattern.js";
2
+ import { getMjstPrimitive } from "./mjst-extension.js";
3
+ import { hasAllOf, hasAnyOf, hasConst, hasDefault, hasEnum, hasExamples, hasOneOf, hasPattern, hasProperties, hasRequired, hasType, isSchemaObject } from "./schema-guards.js";
4
+ const defaultMatchesType = (value, schema) => {
5
+ if (!hasType(schema))
6
+ return true;
7
+ switch (schema.type) {
8
+ case "string":
9
+ return typeof value === "string";
10
+ case "number":
11
+ return typeof value === "number";
12
+ case "integer":
13
+ return typeof value === "number" && Number.isInteger(value);
14
+ case "boolean":
15
+ return typeof value === "boolean";
16
+ case "null":
17
+ return value === null;
18
+ case "array":
19
+ return Array.isArray(value);
20
+ case "object":
21
+ return typeof value === "object" && value !== null && !Array.isArray(value);
22
+ default:
23
+ return true;
24
+ }
25
+ };
26
+ const MAX_FALLBACK_ITEMS = 32;
27
+ const arrayFallback = (schema) => {
28
+ const record = schema;
29
+ const positions = Array.isArray(Object.hasOwn(record, "prefixItems") ? record["prefixItems"] : void 0) ? Object.hasOwn(record, "prefixItems") ? record["prefixItems"] : void 0 : Array.isArray(Object.hasOwn(record, "items") ? record["items"] : void 0) ? Object.hasOwn(record, "items") ? record["items"] : void 0 : [];
30
+ const tail = Array.isArray(Object.hasOwn(record, "items") ? record["items"] : void 0) ? Object.hasOwn(record, "additionalItems") ? record["additionalItems"] : void 0 : Object.hasOwn(record, "items") ? record["items"] : void 0;
31
+ const minItems = typeof record["minItems"] === "number" ? record["minItems"] : 0;
32
+ const wanted = minItems > MAX_FALLBACK_ITEMS ? Math.min(minItems, positions.length) : minItems;
33
+ if (wanted === 0)
34
+ return "[]";
35
+ const elements = [];
36
+ for (let i = 0; i < wanted; i++) {
37
+ const elementSchema = i < positions.length ? positions[i] : tail;
38
+ if (elementSchema === void 0 || typeof elementSchema === "boolean")
39
+ return "[]";
40
+ const element = getDefaultValue(elementSchema);
41
+ if (element === "undefined")
42
+ return "[]";
43
+ elements.push(element);
44
+ }
45
+ return `[${elements.join(", ")}]`;
46
+ };
47
+ const MAX_FALLBACK_LENGTH = 256;
48
+ const stringFallback = (schema) => {
49
+ const bounds = schema;
50
+ if (hasPattern(schema)) {
51
+ const patternDefault = generateDefaultFromPattern(schema.pattern, typeof bounds["minLength"] === "number" ? bounds["minLength"] : void 0, typeof bounds["maxLength"] === "number" ? bounds["maxLength"] : void 0);
52
+ if (patternDefault)
53
+ return patternDefault;
54
+ return '""';
55
+ }
56
+ const minLength = schema["minLength"];
57
+ if (typeof minLength !== "number" || !(minLength > 0))
58
+ return '""';
59
+ return JSON.stringify("x".repeat(Math.min(minLength, MAX_FALLBACK_LENGTH)));
60
+ };
61
+ const finiteKeyword = (schema, keyword) => {
62
+ const value = schema[keyword];
63
+ return typeof value === "number" && Number.isFinite(value) ? value : void 0;
64
+ };
65
+ const numberFallback = (schema, integer) => {
66
+ const minimum = finiteKeyword(schema, "minimum");
67
+ const maximum = finiteKeyword(schema, "maximum");
68
+ const exclusiveMinimum = finiteKeyword(schema, "exclusiveMinimum");
69
+ const exclusiveMaximum = finiteKeyword(schema, "exclusiveMaximum");
70
+ const multipleOf = finiteKeyword(schema, "multipleOf");
71
+ const low = Math.max(minimum ?? -Infinity, exclusiveMinimum !== void 0 ? exclusiveMinimum + 1 : -Infinity);
72
+ const high = Math.min(maximum ?? Infinity, exclusiveMaximum !== void 0 ? exclusiveMaximum - 1 : Infinity);
73
+ let candidate = Math.min(Math.max(0, low), high);
74
+ if (integer)
75
+ candidate = Math.ceil(candidate);
76
+ if (multipleOf !== void 0 && multipleOf > 0 && candidate !== 0) {
77
+ candidate = Math.ceil(candidate / multipleOf) * multipleOf;
78
+ }
79
+ const satisfies = Number.isFinite(candidate) && (minimum === void 0 || candidate >= minimum) && (maximum === void 0 || candidate <= maximum) && (exclusiveMinimum === void 0 || candidate > exclusiveMinimum) && (exclusiveMaximum === void 0 || candidate < exclusiveMaximum) && (!integer || Number.isInteger(candidate)) && (multipleOf === void 0 || multipleOf <= 0 || Number.isInteger(candidate / multipleOf));
80
+ return satisfies ? String(candidate) : "0";
81
+ };
82
+ const getDefaultValue = (schema) => {
83
+ if (!isSchemaObject(schema)) {
84
+ return "undefined";
85
+ }
86
+ if (hasDefault(schema) && defaultMatchesType(schema.default, schema)) {
87
+ return JSON.stringify(schema.default);
88
+ }
89
+ if (hasConst(schema)) {
90
+ return JSON.stringify(schema.const);
91
+ }
92
+ if (hasEnum(schema) && schema.enum.length > 0) {
93
+ return JSON.stringify(schema.enum[0]);
94
+ }
95
+ if (hasExamples(schema) && schema.examples.length > 0) {
96
+ return JSON.stringify(schema.examples[0]);
97
+ }
98
+ if (hasOneOf(schema) && schema.oneOf.length > 0) {
99
+ const firstSchema = schema.oneOf[0];
100
+ if (firstSchema !== void 0) {
101
+ return getDefaultValue(firstSchema);
102
+ }
103
+ }
104
+ if (hasAnyOf(schema) && schema.anyOf.length > 0) {
105
+ const firstSchema = schema.anyOf[0];
106
+ if (firstSchema !== void 0) {
107
+ return getDefaultValue(firstSchema);
108
+ }
109
+ }
110
+ if (hasAllOf(schema) && schema.allOf.length > 0) {
111
+ const firstSchema = schema.allOf[0];
112
+ if (firstSchema !== void 0) {
113
+ return getDefaultValue(firstSchema);
114
+ }
115
+ }
116
+ if (getMjstPrimitive(schema) === "bigint") {
117
+ return "0n";
118
+ }
119
+ const rawType = schema["type"];
120
+ if (Array.isArray(rawType) && rawType.length > 0 && typeof rawType[0] === "string") {
121
+ return getDefaultValue({ ...schema, type: rawType[0] });
122
+ }
123
+ if (!hasType(schema)) {
124
+ return "undefined";
125
+ }
126
+ switch (schema.type) {
127
+ case "string":
128
+ return stringFallback(schema);
129
+ case "number":
130
+ case "integer":
131
+ return numberFallback(schema, schema.type === "integer");
132
+ case "boolean":
133
+ return "false";
134
+ case "null":
135
+ return "null";
136
+ case "array":
137
+ return arrayFallback(schema);
138
+ case "object": {
139
+ if (hasProperties(schema) && hasRequired(schema)) {
140
+ const props = schema.properties;
141
+ const required = schema.required.filter((key) => Object.hasOwn(props, key));
142
+ const defaults = required.map((key) => getDefaultValue(props[key]));
143
+ if (defaults.length > 0 && !defaults.includes("undefined")) {
144
+ return `{ ${required.map((key, i) => `${JSON.stringify(key)}: ${defaults[i]}`).join(", ")} }`;
145
+ }
146
+ }
147
+ return "{}";
148
+ }
149
+ default:
150
+ return "undefined";
151
+ }
152
+ };
153
+ export {
154
+ getDefaultValue
155
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@amritk/helpers",
3
- "version": "0.22.0",
3
+ "version": "0.23.0",
4
4
  "description": "Shared utilities for the mjst code generation ecosystem.",
5
5
  "type": "module",
6
6
  "sideEffects": false,