@amritk/helpers 0.21.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
+ };
@@ -16,6 +16,12 @@ export type TypeOptions = {
16
16
  * type and the import agree.
17
17
  */
18
18
  readonly rootSchema?: Record<string, unknown>;
19
+ /**
20
+ * Conditional definitions this render is already inlining, so a cycle through
21
+ * one terminates. Internal: callers never set it, `allOfMember` grows it as it
22
+ * descends.
23
+ */
24
+ readonly inliningRefs?: ReadonlySet<string>;
19
25
  };
20
26
  /**
21
27
  * Generates a TypeScript type definition from a JSON Schema.
@@ -3,6 +3,7 @@ import { assertSchemaDepth, MAX_SCHEMA_DEPTH } from "./max-schema-depth.js";
3
3
  import { getMjstBrand, getMjstInstanceOf, getMjstPrimitive } from "./mjst-extension.js";
4
4
  import { readKey } from "./read-key.js";
5
5
  import { refToName } from "./ref-to-name.js";
6
+ import { referencedConditional } from "./referenced-conditional.js";
6
7
  import { resolveRef } from "./resolve-ref.js";
7
8
  import { safeKey } from "./safe-accessor.js";
8
9
  import { isObjectSchema, isSchemaObject } from "./schema-guards.js";
@@ -15,6 +16,8 @@ const keywordMap = (schema, name) => {
15
16
  };
16
17
  const MAX_TYPE_DEPTH = Math.floor(MAX_SCHEMA_DEPTH / 5);
17
18
  const declares = (schema, name) => Object.hasOwn(schema, name);
19
+ const COMPOSITION_KEYWORDS = ["$ref", "$dynamicRef", "allOf", "anyOf", "oneOf", "if", "not"];
20
+ const composes = (schema) => COMPOSITION_KEYWORDS.some((keyword) => declares(schema, keyword));
18
21
  const refTypeName = (ref, options) => {
19
22
  if (ref.startsWith("#"))
20
23
  return refToName(ref, options.typeSuffix);
@@ -55,6 +58,25 @@ const requiredOf = (schema) => {
55
58
  const declared = keywordOf(schema, "required");
56
59
  return Array.isArray(declared) ? declared.filter((key) => typeof key === "string") : [];
57
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
+ };
58
80
  const literalDomain = (schema) => {
59
81
  if (schema === void 0 || !isSchemaObject(schema))
60
82
  return void 0;
@@ -129,7 +151,7 @@ const branchOf = (fragments, options, depth) => {
129
151
  for (const key of Object.keys(declared)) {
130
152
  const sub = readKey(declared, key);
131
153
  const existing = readKey(properties, key);
132
- assignKey(properties, key, existing === void 0 ? sub : { allOf: [existing, sub] });
154
+ assignKey(properties, key, intersectProperties(existing, sub));
133
155
  }
134
156
  for (const key of requiredOf(fragment))
135
157
  required.add(key);
@@ -179,17 +201,14 @@ const withoutConditional = (schema) => {
179
201
  }
180
202
  return rest;
181
203
  };
182
- const referencedConditional = (entry, options) => {
183
- const ref = keywordOf(entry, "$ref");
184
- if (typeof ref !== "string" || !ref.startsWith("#") || options.rootSchema === void 0)
185
- return void 0;
186
- const resolved = resolveRef(ref, options.rootSchema);
187
- return resolved !== void 0 && isSchemaObject(resolved) && declares(resolved, "if") ? resolved : void 0;
188
- };
204
+ const referencedConditionalOf = (entry, options) => referencedConditional(entry, options.rootSchema);
189
205
  const allOfMember = (entry, domain, options, depth) => {
190
- const source = isSchemaObject(entry) ? declares(entry, "if") ? entry : referencedConditional(entry, options) : void 0;
206
+ const ref = isSchemaObject(entry) ? keywordOf(entry, "$ref") : void 0;
207
+ const inlining = typeof ref === "string" && options.inliningRefs?.has(ref) === true;
208
+ const source = isSchemaObject(entry) && !inlining ? declares(entry, "if") ? entry : referencedConditionalOf(entry, options) : void 0;
191
209
  if (source === void 0)
192
210
  return wrapUnion(getTypeScriptType(entry, options, depth + 1));
211
+ const inner = typeof ref === "string" ? { ...options, inliningRefs: /* @__PURE__ */ new Set([...options.inliningRefs ?? [], ref]) } : options;
193
212
  const own = keywordMap(source, "properties");
194
213
  const merged = {};
195
214
  for (const block of [domain, own]) {
@@ -198,9 +217,9 @@ const allOfMember = (entry, domain, options, depth) => {
198
217
  for (const key of Object.keys(block))
199
218
  assignKey(merged, key, readKey(block, key));
200
219
  }
201
- const conditional = conditionalMember(source, merged, options, depth + 1);
220
+ const conditional = conditionalMember(source, merged, inner, depth + 1);
202
221
  const rest = source === entry ? withoutConditional(entry) : entry;
203
- const remainder = wrapUnion(getTypeScriptType(rest, options, depth + 1));
222
+ const remainder = wrapUnion(getTypeScriptType(rest, inner, depth + 1));
204
223
  return intersectionOf([remainder, ...conditional === void 0 ? [] : [wrapUnion(conditional)]]);
205
224
  };
206
225
  const isObjectLikeSchema = (schema) => {
@@ -241,10 +260,43 @@ const getTypeScriptType = (schema, options, depth) => {
241
260
  return isNullableSchema(schema) ? withNull(branded) : branded;
242
261
  };
243
262
  const isNullableSchema = (schema) => isSchemaObject(schema) && keywordOf(schema, "nullable") === true;
263
+ const isTopLevelUnion = (type) => {
264
+ let depth = 0;
265
+ let quote;
266
+ for (let i = 0; i < type.length; i++) {
267
+ const char = type[i];
268
+ if (quote !== void 0) {
269
+ if (char === "\\")
270
+ i++;
271
+ else if (char === quote)
272
+ quote = void 0;
273
+ continue;
274
+ }
275
+ if (char === "/" && type[i + 1] === "*") {
276
+ const end = type.indexOf("*/", i + 2);
277
+ if (end === -1)
278
+ return false;
279
+ i = end + 1;
280
+ continue;
281
+ }
282
+ if (char === '"' || char === "'" || char === "`")
283
+ quote = char;
284
+ else if (char === "(" || char === "<" || char === "[" || char === "{")
285
+ depth++;
286
+ else if (char === ")" || char === ">" || char === "]" || char === "}")
287
+ depth--;
288
+ else if (char === "|" && depth === 0)
289
+ return true;
290
+ }
291
+ return false;
292
+ };
244
293
  const wrapUnion = (type) => type.includes(" | ") ? `(${type})` : type;
245
294
  const wrapIntersection = (type) => type.includes(" & ") ? `(${type})` : type;
246
295
  const withNull = (type) => type.split(" | ").includes("null") ? type : `${type} | null`;
247
- const unionOf = (members) => [...new Set(members)].join(" | ");
296
+ const unionOf = (members) => {
297
+ const unique = [...new Set(members)];
298
+ return unique.includes("unknown") ? "unknown" : unique.join(" | ");
299
+ };
248
300
  const intersectionOf = (members) => {
249
301
  const kept = [...new Set(members)].filter((member) => member !== "unknown");
250
302
  if (kept.length === 0)
@@ -252,27 +304,130 @@ const intersectionOf = (members) => {
252
304
  const meaningful = kept.length > 1 ? kept.filter((member) => member !== "object") : kept;
253
305
  if (meaningful.length === 0)
254
306
  return "object";
255
- return meaningful.join(" & ");
307
+ if (meaningful.length === 1)
308
+ return meaningful[0];
309
+ return meaningful.map((member) => isTopLevelUnion(member) ? `(${member})` : member).join(" & ");
256
310
  };
257
311
  const recordType = (keyType, valueType, options) => options.readonly ? `Readonly<Record<${keyType}, ${valueType}>>` : `Record<${keyType}, ${valueType}>`;
258
- const patternPropertiesRecordType = (patternProperties, options, depth) => {
259
- const entries = Object.entries(patternProperties);
260
- if (entries.length === 0)
312
+ const REGEX_SYNTAX = /* @__PURE__ */ new Set([
313
+ "\\",
314
+ "^",
315
+ "$",
316
+ ".",
317
+ "|",
318
+ "?",
319
+ "*",
320
+ "+",
321
+ "(",
322
+ ")",
323
+ "[",
324
+ "]",
325
+ "{",
326
+ "}"
327
+ ]);
328
+ const startsOptional = (rest) => /^[*?{]/.test(rest);
329
+ const characterClassMembers = (body) => {
330
+ if (body === "" || body.startsWith("^") || body.includes("\\"))
261
331
  return void 0;
262
- const seen = /* @__PURE__ */ new Set();
263
- const valueTypes = [];
264
- for (const [, value] of entries) {
265
- const valueType2 = typeof value === "boolean" ? getBooleanSubSchemaType(value) : getTypeScriptType(value, options, depth + 1);
266
- if (!seen.has(valueType2)) {
267
- seen.add(valueType2);
268
- valueTypes.push(valueType2);
332
+ const members = [];
333
+ for (let i = 0; i < body.length; i++) {
334
+ const char = body[i];
335
+ if (body[i + 1] === "-" && i + 2 < body.length) {
336
+ const from = char.codePointAt(0);
337
+ const to = body[i + 2].codePointAt(0);
338
+ if (to < from || to - from > 64)
339
+ return void 0;
340
+ for (let code = from; code <= to; code++)
341
+ members.push(String.fromCodePoint(code));
342
+ i += 2;
343
+ continue;
269
344
  }
345
+ members.push(char);
270
346
  }
271
- if (valueTypes.length === 0)
347
+ return members.length > 0 && members.length <= 64 ? members : void 0;
348
+ };
349
+ const hasTopLevelAlternation = (pattern) => {
350
+ let depth = 0;
351
+ for (let i = 0; i < pattern.length; i++) {
352
+ const char = pattern[i];
353
+ if (char === "\\")
354
+ i++;
355
+ else if (char === "(" || char === "[")
356
+ depth++;
357
+ else if (char === ")" || char === "]")
358
+ depth--;
359
+ else if (char === "|" && depth <= 0)
360
+ return true;
361
+ }
362
+ return false;
363
+ };
364
+ const leadingPrefixes = (pattern) => {
365
+ if (!pattern.startsWith("^"))
366
+ return void 0;
367
+ const rest = pattern.slice(1);
368
+ if (hasTopLevelAlternation(rest))
369
+ return void 0;
370
+ let run = "";
371
+ let cursor = 0;
372
+ while (cursor < rest.length) {
373
+ const char = rest[cursor];
374
+ if (char === "\\") {
375
+ const escaped = rest[cursor + 1];
376
+ if (escaped === void 0 || /[A-Za-z0-9]/.test(escaped))
377
+ break;
378
+ run += escaped;
379
+ cursor += 2;
380
+ continue;
381
+ }
382
+ if (REGEX_SYNTAX.has(char))
383
+ break;
384
+ run += char;
385
+ cursor += 1;
386
+ }
387
+ if (run !== "" && startsOptional(rest.slice(cursor)))
388
+ run = run.slice(0, -1);
389
+ if (run !== "")
390
+ return [run];
391
+ if (!rest.startsWith("["))
272
392
  return void 0;
273
- const valueType = valueTypes.join(" | ");
274
- const keyType = entries.length === 1 && entries[0]?.[0] === "^x-" ? "`x-${string}`" : "string";
275
- return recordType(keyType, valueType, options);
393
+ const close = rest.indexOf("]");
394
+ if (close === -1 || startsOptional(rest.slice(close + 1)))
395
+ return void 0;
396
+ return characterClassMembers(rest.slice(1, close));
397
+ };
398
+ const patternKeyType = (pattern) => {
399
+ const prefixes = leadingPrefixes(pattern);
400
+ if (prefixes === void 0 || prefixes.some((prefix) => /[`\\$]/.test(prefix)))
401
+ return "string";
402
+ return prefixes.map((prefix) => `\`${prefix}\${string}\``).join(" | ");
403
+ };
404
+ const patternIndexSignatures = (patternProperties, options, depth) => {
405
+ const entries = Object.entries(patternProperties);
406
+ if (entries.length === 0)
407
+ return [];
408
+ const signatures = entries.map(([pattern, value]) => ({
409
+ key: patternKeyType(pattern),
410
+ value: typeof value === "boolean" ? getBooleanSubSchemaType(value) : getTypeScriptType(value, options, depth + 1)
411
+ }));
412
+ const widened = [{ key: "string", value: unionOf(signatures.map((signature) => signature.value)) }];
413
+ if (signatures.length === 1)
414
+ return signatures;
415
+ if (signatures.some((signature) => signature.key === "string"))
416
+ return widened;
417
+ const byKey = /* @__PURE__ */ new Map();
418
+ for (const { key, value } of signatures)
419
+ byKey.set(key, [...byKey.get(key) ?? [], value]);
420
+ const grouped = [...byKey].map(([key, values]) => ({ key, value: unionOf(values) }));
421
+ return overlappingKeys(grouped.map((signature) => signature.key)) ? widened : grouped;
422
+ };
423
+ const indexSignaturesType = (indexes, options, asBlock) => {
424
+ const only = indexes[0];
425
+ if (!asBlock && indexes.length === 1)
426
+ return recordType(only.key, only.value, options);
427
+ const readonlyPrefix = options.readonly ? "readonly " : "";
428
+ return `{
429
+ ${indexes.map(({ key, value }) => ` ${readonlyPrefix}[key: ${key}]: ${value};`).join("\n")}
430
+ }`;
276
431
  };
277
432
  const getTuplePositions = (schema) => {
278
433
  const prefixItems = keywordOf(schema, "prefixItems");
@@ -312,53 +467,94 @@ const arrayTypeToTs = (schema, options, depth) => {
312
467
  }
313
468
  return options.readonly ? "readonly unknown[]" : "unknown[]";
314
469
  };
315
- const getIndexSignature = (schema, options, depth) => {
470
+ const literalPatternKeys = (pattern) => {
471
+ const anchored = /^\^\((?:\?:)?([^()[\]{}.*+?^$\\|]+(?:\|[^()[\]{}.*+?^$\\|]+)*)\)\$$/.exec(pattern);
472
+ const bare = /^\^([^()[\]{}.*+?^$\\|]+)\$$/.exec(pattern);
473
+ const body = anchored?.[1] ?? bare?.[1];
474
+ return body === void 0 ? void 0 : body.split("|");
475
+ };
476
+ const openPatternProperties = (schema, patternProperties) => {
477
+ const declared = keywordMap(schema, "properties");
478
+ if (declared === void 0)
479
+ return patternProperties;
480
+ const kept = {};
481
+ for (const [pattern, value] of Object.entries(patternProperties)) {
482
+ const keys = literalPatternKeys(pattern);
483
+ if (keys?.every((key) => Object.hasOwn(declared, key)))
484
+ continue;
485
+ assignKey(kept, pattern, value);
486
+ }
487
+ return kept;
488
+ };
489
+ const declaresOpenKeys = (schema) => {
490
+ const additionalProperties = keywordOf(schema, "additionalProperties");
491
+ if (additionalProperties !== void 0 && typeof additionalProperties !== "boolean")
492
+ return true;
493
+ const declaredPatterns = keywordMap(schema, "patternProperties");
494
+ return declaredPatterns !== void 0 && Object.keys(openPatternProperties(schema, declaredPatterns)).length > 0;
495
+ };
496
+ const getIndexSignatures = (schema, options, depth) => {
316
497
  const additionalProperties = keywordOf(schema, "additionalProperties");
317
498
  if (additionalProperties !== void 0 && typeof additionalProperties !== "boolean") {
318
- return { key: "string", value: getTypeScriptType(additionalProperties, options, depth + 1) };
499
+ return [{ key: "string", value: getTypeScriptType(additionalProperties, options, depth + 1) }];
319
500
  }
320
- const patternProperties = keywordOf(schema, "patternProperties");
321
- if (patternProperties && typeof patternProperties === "object") {
322
- const entries = Object.entries(patternProperties);
323
- if (entries.length === 0)
324
- return void 0;
325
- const valueTypes = entries.map(([, value]) => typeof value === "boolean" ? getBooleanSubSchemaType(value) : getTypeScriptType(value, options, depth + 1));
326
- const key = entries.length === 1 && entries[0]?.[0] === "^x-" ? "`x-${string}`" : "string";
327
- return { key, value: unionOf(valueTypes) };
501
+ const declaredPatterns = keywordMap(schema, "patternProperties");
502
+ if (declaredPatterns !== void 0) {
503
+ return patternIndexSignatures(openPatternProperties(schema, declaredPatterns), options, depth);
328
504
  }
329
- return void 0;
505
+ return [];
330
506
  };
331
- const buildIndexSignatureLine = (index, declaredTypes, hasOptionalProperty, options) => {
507
+ const buildIndexSignatureLine = (index, declared, hasOptionalProperty, options) => {
332
508
  const readonlyPrefix = options.readonly ? "readonly " : "";
333
- if (index.key !== "string")
509
+ const covered = index.key === "string" ? declared : declared.filter((property) => matchesKeyType(index.key, property.name));
510
+ if (covered.length === 0)
334
511
  return `${readonlyPrefix}[key: ${index.key}]: ${index.value}`;
335
512
  const widened = unionOf([
336
513
  ...index.value.split(" | "),
337
- ...declaredTypes,
514
+ ...covered.map((property) => property.type),
338
515
  ...hasOptionalProperty ? ["undefined"] : []
339
516
  ]);
340
- return `${readonlyPrefix}[key: string]: ${widened}`;
517
+ return `${readonlyPrefix}[key: ${index.key}]: ${widened}`;
341
518
  };
342
- const propertyDescription = (propSchema) => {
343
- if (!isSchemaObject(propSchema))
519
+ const matchesKeyType = (key, name) => {
520
+ const prefixes = keyTypePrefixes(key);
521
+ return prefixes === void 0 || prefixes.some((prefix) => name.startsWith(prefix));
522
+ };
523
+ const keyTypePrefixes = (key) => {
524
+ if (key === "string")
344
525
  return void 0;
345
- const description = keywordOf(propSchema, "description");
346
- if (typeof description === "string")
347
- return description;
348
- const comment = keywordOf(propSchema, "$comment");
349
- if (typeof comment === "string")
350
- return comment;
351
- return void 0;
526
+ const prefixes = [];
527
+ for (const member of key.split(" | ")) {
528
+ const prefix = /^`(.*)\$\{string\}`$/.exec(member)?.[1];
529
+ if (prefix === void 0)
530
+ return void 0;
531
+ prefixes.push(prefix);
532
+ }
533
+ return prefixes;
534
+ };
535
+ const overlappingKeys = (keys) => {
536
+ const prefixLists = keys.map((key) => keyTypePrefixes(key));
537
+ if (prefixLists.some((prefixes) => prefixes === void 0))
538
+ return true;
539
+ for (let i = 0; i < prefixLists.length; i++) {
540
+ for (let j = i + 1; j < prefixLists.length; j++) {
541
+ const left = prefixLists[i];
542
+ const right = prefixLists[j];
543
+ if (left.some((a) => right.some((b) => a.startsWith(b) || b.startsWith(a))))
544
+ return true;
545
+ }
546
+ }
547
+ return false;
352
548
  };
353
549
  const objectTypeToTs = (schema, options, depth) => {
354
- const index = getIndexSignature(schema, options, depth);
550
+ const indexes = getIndexSignatures(schema, options, depth);
355
551
  const properties = keywordOf(schema, "properties");
356
552
  if (properties && Object.keys(properties).length > 0) {
357
553
  const readonlyPrefix = options.readonly ? "readonly " : "";
358
554
  const declaredRequired = keywordOf(schema, "required");
359
555
  const requiredSet = new Set(Array.isArray(declaredRequired) ? declaredRequired : []);
360
556
  const hasDescriptions = Object.values(properties).some((p) => propertyDescription(p) !== void 0);
361
- const declaredTypes = [];
557
+ const declared = [];
362
558
  let hasOptionalProperty = false;
363
559
  const entries = [];
364
560
  for (const key of Object.keys(properties)) {
@@ -368,7 +564,7 @@ const objectTypeToTs = (schema, options, depth) => {
368
564
  if (!isRequired)
369
565
  hasOptionalProperty = true;
370
566
  const propType = getTypeScriptType(propSchema, options, depth + 1);
371
- declaredTypes.push(propType);
567
+ declared.push({ name: key, type: propType });
372
568
  const declaration = readonlyPrefix + safeKey(key) + optional + ": " + propType;
373
569
  if (!hasDescriptions) {
374
570
  entries.push(declaration);
@@ -377,40 +573,46 @@ const objectTypeToTs = (schema, options, depth) => {
377
573
  const inlineDescription = propertyDescription(propSchema);
378
574
  entries.push((inlineDescription ? buildInlinePropertyComment(inlineDescription) : "") + " " + declaration + ";");
379
575
  }
380
- if (index) {
381
- const line = buildIndexSignatureLine(index, declaredTypes, hasOptionalProperty, options);
576
+ for (const index of indexes) {
577
+ const line = buildIndexSignatureLine(index, declared, hasOptionalProperty, options);
382
578
  entries.push(hasDescriptions ? " " + line + ";" : line);
383
579
  }
384
580
  if (hasDescriptions)
385
581
  return "{\n" + entries.join("\n") + "\n}";
386
582
  return "{ " + entries.join("; ") + " }";
387
583
  }
388
- if (index) {
389
- return index.key === "string" && !options.readonly ? recordType("string", index.value, options) : recordType(index.key, index.value, options);
584
+ const only = indexes[0];
585
+ if (only !== void 0 && indexes.length === 1) {
586
+ return only.key === "string" && !options.readonly ? recordType("string", only.value, options) : recordType(only.key, only.value, options);
587
+ }
588
+ if (indexes.length > 1) {
589
+ const readonlyPrefix = options.readonly ? "readonly " : "";
590
+ return `{ ${indexes.map(({ key, value }) => `${readonlyPrefix}[key: ${key}]: ${value}`).join("; ")} }`;
390
591
  }
391
592
  return "object";
392
593
  };
393
594
  const getLocalShapeType = (schema, options, depth) => {
394
595
  const type = keywordOf(schema, "type");
395
596
  if (!type) {
396
- const index = getIndexSignature(schema, options, depth);
397
- if (index)
597
+ if (declaresOpenKeys(schema))
598
+ return objectTypeToTs(schema, options, depth);
599
+ const properties = keywordOf(schema, "properties");
600
+ if (properties && Object.keys(properties).length > 0)
398
601
  return objectTypeToTs(schema, options, depth);
399
602
  const additionalProperties = keywordOf(schema, "additionalProperties");
400
603
  if (typeof additionalProperties === "boolean") {
401
604
  return recordType("string", getBooleanSubSchemaType(additionalProperties), options);
402
605
  }
403
- const properties = keywordOf(schema, "properties");
404
- if (properties && Object.keys(properties).length > 0)
405
- return objectTypeToTs(schema, options, depth);
406
- const defaultValue = keywordOf(schema, "default");
407
- if (defaultValue !== void 0) {
408
- if (typeof defaultValue === "string")
409
- return "string";
410
- if (typeof defaultValue === "number")
411
- return "number";
412
- if (typeof defaultValue === "boolean")
413
- return "boolean";
606
+ if (!composes(schema)) {
607
+ const defaultValue = keywordOf(schema, "default");
608
+ if (defaultValue !== void 0) {
609
+ if (typeof defaultValue === "string")
610
+ return "string";
611
+ if (typeof defaultValue === "number")
612
+ return "number";
613
+ if (typeof defaultValue === "boolean")
614
+ return "boolean";
615
+ }
414
616
  }
415
617
  return void 0;
416
618
  }
@@ -484,7 +686,7 @@ const getUnbrandedType = (schema, options, depth) => {
484
686
  }
485
687
  const unionBranches = unionBranchesOf(schema);
486
688
  if (unionBranches) {
487
- const union = unionOf(unionBranches.map((branch) => getTypeScriptType(branch, options, depth + 1)));
689
+ const union = unionOf(unionBranches.map((branch) => unionBranchType(branch, domain, options, depth)));
488
690
  if (members.length === 0 && !Array.isArray(allOf))
489
691
  return union;
490
692
  members.push(wrapUnion(union));
@@ -493,6 +695,28 @@ const getUnbrandedType = (schema, options, depth) => {
493
695
  return "unknown";
494
696
  return intersectionOf(members);
495
697
  };
698
+ const unionBranchType = (branch, domain, options, depth) => {
699
+ const standalone = () => getTypeScriptType(branch, options, depth + 1);
700
+ if (!isPlainFragment(branch))
701
+ return standalone();
702
+ const required = requiredOf(branch);
703
+ const own = keywordMap(branch, "properties");
704
+ if (required.length === 0)
705
+ return standalone();
706
+ const declaredBy = (key) => domain === void 0 ? void 0 : readKey(domain, key);
707
+ const properties = {};
708
+ if (own !== void 0) {
709
+ for (const key of Object.keys(own)) {
710
+ assignKey(properties, key, intersectProperties(declaredBy(key), readKey(own, key)));
711
+ }
712
+ }
713
+ for (const key of required) {
714
+ if (Object.hasOwn(properties, key))
715
+ continue;
716
+ assignKey(properties, key, declaredBy(key) ?? true);
717
+ }
718
+ return objectTypeToTs({ type: "object", properties, required: [...required] }, options, depth);
719
+ };
496
720
  const unionBranchesOf = (schema) => {
497
721
  const oneOf = keywordOf(schema, "oneOf");
498
722
  if (Array.isArray(oneOf) && oneOf.length > 0)
@@ -506,9 +730,9 @@ const getCompositionMembers = (schema, options, depth) => {
506
730
  if (!isSchemaObject(schema))
507
731
  return [];
508
732
  const members = [];
733
+ const domain = keywordMap(schema, "properties");
509
734
  const allOf = keywordOf(schema, "allOf");
510
735
  if (Array.isArray(allOf)) {
511
- const domain = keywordMap(schema, "properties");
512
736
  for (const entry of allOf)
513
737
  members.push(allOfMember(entry, domain, options, depth));
514
738
  }
@@ -518,7 +742,7 @@ const getCompositionMembers = (schema, options, depth) => {
518
742
  }
519
743
  const unionBranches = unionBranchesOf(schema);
520
744
  if (unionBranches) {
521
- members.push(wrapUnion(unionOf(unionBranches.map((branch) => getTypeScriptType(branch, options, depth + 1)))));
745
+ members.push(wrapUnion(unionOf(unionBranches.map((branch) => unionBranchType(branch, domain, options, depth)))));
522
746
  }
523
747
  return [...new Set(members)].filter((member) => member !== "unknown");
524
748
  };
@@ -548,30 +772,23 @@ const generateTypeDefinition = (schema, typeName, options = {}) => {
548
772
  const hasProperties = declaredProperties !== void 0 && Object.keys(declaredProperties).length > 0;
549
773
  const hasAdditionalProperties = typeof additionalProperties === "object" && additionalProperties !== null;
550
774
  const hasPatternProperties = patternProperties !== void 0 && Object.keys(patternProperties).length > 0;
551
- if (!hasProperties && hasPatternProperties) {
552
- const record = patternPropertiesRecordType(patternProperties, options, 0) ?? "Record<string, unknown>";
553
- let result2 = "";
554
- if (jsDocTitle && jsDocDescription) {
555
- result2 += buildJsDocBlock(jsDocTitle, jsDocDescription);
556
- }
557
- result2 += `export type ${typeName} = ${record};`;
558
- return result2;
559
- }
560
- if (!hasProperties && hasAdditionalProperties) {
561
- const additionalPropType = getTypeScriptType(additionalProperties, options, 0);
562
- let result2 = "";
563
- if (jsDocTitle && jsDocDescription) {
564
- result2 += buildJsDocBlock(jsDocTitle, jsDocDescription);
775
+ const composed = (body) => [body, ...getCompositionMembers(schema, options, 0)].filter((member) => member !== "unknown").join(" & ");
776
+ if (!hasProperties && (hasPatternProperties || hasAdditionalProperties)) {
777
+ const indexes = getIndexSignatures(schema, options, 0);
778
+ if (indexes.length > 0) {
779
+ const body = indexSignaturesType(indexes, options, hasAdditionalProperties);
780
+ let result2 = "";
781
+ if (jsDocTitle && jsDocDescription) {
782
+ result2 += buildJsDocBlock(jsDocTitle, jsDocDescription);
783
+ }
784
+ result2 += `export type ${typeName} = ${composed(body)};`;
785
+ return result2;
565
786
  }
566
- result2 += `export type ${typeName} = {
567
- ${readonlyPrefix}[key: string]: ${additionalPropType};
568
- };`;
569
- return result2;
570
787
  }
571
788
  const schemaProps = declaredProperties ?? {};
572
789
  const declaredRequired = keywordOf(schema, "required");
573
790
  const requiredSet = new Set(Array.isArray(declaredRequired) ? declaredRequired : []);
574
- const declaredTypes = [];
791
+ const declared = [];
575
792
  let hasOptionalProperty = false;
576
793
  let properties = "";
577
794
  let isFirstProp = true;
@@ -588,14 +805,13 @@ const generateTypeDefinition = (schema, typeName, options = {}) => {
588
805
  if (!isRequired)
589
806
  hasOptionalProperty = true;
590
807
  const propType = getTypeScriptType(propSchema, options, 0);
591
- declaredTypes.push(propType);
808
+ declared.push({ name: key, type: propType });
592
809
  const quotedKey = readonlyPrefix + safeKey(key);
593
810
  const inlineDescription = propertyDescription(propSchema);
594
811
  appendLine(inlineDescription ? buildInlinePropertyComment(inlineDescription) + " " + quotedKey + optional + ": " + propType + ";" : " " + quotedKey + optional + ": " + propType + ";");
595
812
  }
596
- const index = getIndexSignature(schema, options, 0);
597
- if (index) {
598
- appendLine(" " + buildIndexSignatureLine(index, declaredTypes, hasOptionalProperty, options) + ";");
813
+ for (const index of getIndexSignatures(schema, options, 0)) {
814
+ appendLine(" " + buildIndexSignatureLine(index, declared, hasOptionalProperty, options) + ";");
599
815
  }
600
816
  let result = "";
601
817
  if (jsDocTitle && jsDocDescription) {
@@ -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
+ };
@@ -0,0 +1,14 @@
1
+ /**
2
+ * Asks whether emitted source names an identifier — the question that decides
3
+ * which `$ref` imports a generated file actually needs.
4
+ *
5
+ * Deciding it from the text rather than from a second walk over the schema is
6
+ * what keeps the import list in step with whatever the type and function
7
+ * emitters chose to write: a `$ref` in a position the type emitter does not read
8
+ * is called and never named, one it inlines through is named in a file that
9
+ * never walked into it, and a ref inside a folded-away branch is neither.
10
+ *
11
+ * The remaining inexactness is the harmless direction — a name spelled in code
12
+ * that is not a reference to the import keeps a binding that could have gone.
13
+ */
14
+ export declare const identifierMentions: (source: string) => ((name: string) => boolean);
@@ -0,0 +1,88 @@
1
+ const escapeForWordMatch = (name) => name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
2
+ const BEFORE_REGEX = /* @__PURE__ */ new Set(["(", ",", "=", ":", "[", "!", "&", "|", "?", "{", "}", ";", "\n"]);
3
+ const stripDataText = (source) => {
4
+ const out = source.split("");
5
+ let previous = "\n";
6
+ let i = 0;
7
+ const blank = (from, to) => {
8
+ for (let n = from; n < to; n++)
9
+ if (out[n] !== "\n")
10
+ out[n] = " ";
11
+ };
12
+ while (i < source.length) {
13
+ const char = source[i];
14
+ const next = source[i + 1];
15
+ if (char === "/" && next === "/") {
16
+ const end = source.indexOf("\n", i);
17
+ blank(i, end === -1 ? source.length : end);
18
+ i = end === -1 ? source.length : end;
19
+ continue;
20
+ }
21
+ if (char === "/" && next === "*") {
22
+ const end = source.indexOf("*/", i + 2);
23
+ if (end === -1)
24
+ return source;
25
+ blank(i, end + 2);
26
+ i = end + 2;
27
+ previous = " ";
28
+ continue;
29
+ }
30
+ if (char === '"' || char === "'" || char === "`") {
31
+ let n = i + 1;
32
+ while (n < source.length && source[n] !== char) {
33
+ if (source[n] === "\\")
34
+ n++;
35
+ if (char !== "`" && source[n] === "\n")
36
+ return source;
37
+ n++;
38
+ }
39
+ if (n >= source.length)
40
+ return source;
41
+ blank(i, n + 1);
42
+ i = n + 1;
43
+ previous = char;
44
+ continue;
45
+ }
46
+ if (char === "/" && BEFORE_REGEX.has(previous)) {
47
+ let n = i + 1;
48
+ let inClass = false;
49
+ while (n < source.length) {
50
+ const c = source[n];
51
+ if (c === "\\")
52
+ n += 2;
53
+ else if (c === "\n")
54
+ return source;
55
+ else if (c === "[")
56
+ inClass = true, n++;
57
+ else if (c === "]")
58
+ inClass = false, n++;
59
+ else if (c === "/" && !inClass)
60
+ break;
61
+ else
62
+ n++;
63
+ }
64
+ if (n >= source.length)
65
+ return source;
66
+ let end = n + 1;
67
+ while (end < source.length && /[a-z]/.test(source[end]))
68
+ end++;
69
+ blank(i, end);
70
+ i = end;
71
+ previous = "/";
72
+ continue;
73
+ }
74
+ if (!/\s/.test(char))
75
+ previous = char;
76
+ else if (char === "\n")
77
+ previous = "\n";
78
+ i++;
79
+ }
80
+ return out.join("");
81
+ };
82
+ const identifierMentions = (source) => {
83
+ const code = stripDataText(source);
84
+ return (name) => new RegExp(`\\b${escapeForWordMatch(name)}\\b`).test(code);
85
+ };
86
+ export {
87
+ identifierMentions
88
+ };
@@ -0,0 +1,19 @@
1
+ import type { JSONSchema } from 'json-schema-typed/draft-2020-12';
2
+ /**
3
+ * The conditional definition an `allOf` member's local `$ref` points at, when it
4
+ * points at one.
5
+ *
6
+ * OpenAPI's security scheme composes its per-type rules as `allOf: [{ $ref:
7
+ * '#/$defs/type-http' }, …]`, each definition an `if`/`then` on the `type` the
8
+ * composing schema enumerates. The definition's own file cannot see that
9
+ * enumeration, so its conditional drops there; the type emitter reads the
10
+ * definition *here* instead and renders its arms into the composing type.
11
+ *
12
+ * That makes this the one place where a type name reaches a file through a
13
+ * `$ref` the file never walks into, which is why the import collectors ask the
14
+ * same question rather than each deciding for themselves: `security-scheme.ts`
15
+ * named `OauthFlows` in an arm it had inlined while `security-scheme-type-oauth2.ts`
16
+ * imported it and rendered nothing — a `TS2304` in one file and a `TS6133` in
17
+ * the other, from a single disagreement about what gets inlined.
18
+ */
19
+ export declare const referencedConditional: (entry: JSONSchema, rootSchema: Record<string, unknown> | undefined) => Record<string, unknown> | undefined;
@@ -0,0 +1,17 @@
1
+ import { readKey } from "./read-key.js";
2
+ import { resolveRef } from "./resolve-ref.js";
3
+ import { isSchemaObject } from "./schema-guards.js";
4
+ const referencedConditional = (entry, rootSchema) => {
5
+ if (!isSchemaObject(entry) || rootSchema === void 0)
6
+ return void 0;
7
+ const ref = readKey(entry, "$ref");
8
+ if (typeof ref !== "string" || !ref.startsWith("#"))
9
+ return void 0;
10
+ const resolved = resolveRef(ref, rootSchema);
11
+ if (resolved === void 0 || !isSchemaObject(resolved))
12
+ return void 0;
13
+ return Object.hasOwn(resolved, "if") ? resolved : void 0;
14
+ };
15
+ export {
16
+ referencedConditional
17
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@amritk/helpers",
3
- "version": "0.21.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,