@amritk/helpers 0.17.0 → 0.19.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
@@ -51,6 +51,17 @@ bun add @amritk/helpers
51
51
  | `@amritk/helpers/upgrade-draft07-schema` | `upgradeDraft07Schema`, `isDraft07Schema` | Upgrade a Draft-07 schema to 2020-12. |
52
52
  | `@amritk/helpers/ref-to-filename` | `refToFilename`, `toKebabCase` | Convert a `$ref` to a stable filename. |
53
53
  | `@amritk/helpers/ref-to-name` | `refToName` | Convert a `$ref` to a TypeScript identifier (PascalCase). |
54
+ | `@amritk/helpers/walk-ref-graph` | `walkRefGraph`, `RefNode` | The shared `$ref`-graph traversal every generator runs: upgrades draft-07, resolves each ref, rewrites `$dynamicRef`, derives type/file names, and hands one pre-computed node per output file to a `visit` callback. |
55
+ | `@amritk/helpers/build-resource-registry` | `buildResourceRegistry`, `ResourceRegistry` | Read a document's `$id` base-URI scopes once, expressed as JSON Pointers. |
56
+ | `@amritk/helpers/normalize-ref-scopes` | `normalizeRefScopes` | Rewrite every `$ref` / `$dynamicRef` to a plain root-relative JSON Pointer, applying the `$id` bases in scope. |
57
+ | `@amritk/helpers/resolve-scoped-ref` | `resolveScopedRef`, `ScopedRefTarget` | Where a `$ref` lands once the `$id` bases in scope are applied. |
58
+ | `@amritk/helpers/graft-external-schemas` | `graftExternalSchemas`, `GraftedSchema` | Fold already-loaded external documents into the document being generated so cross-document refs resolve like local ones. |
59
+ | `@amritk/helpers/prune-external-schemas` | `pruneExternalSchemas` | Drop the grafted documents nothing references. |
60
+ | `@amritk/helpers/extract-dynamic-anchor-defs` | `extractDynamicAnchorDefs` | Collect a `#/...` ref for every subschema carrying a `$dynamicAnchor`. |
61
+ | `@amritk/helpers/fold-nullable` | `foldNullable` | Rewrite OpenAPI 3.0 `nullable: true` into a `null` member of `type`. |
62
+ | `@amritk/helpers/derive-root-type-name` | `deriveRootTypeName` | Turn a schema `title` into a PascalCase root type name. |
63
+ | `@amritk/helpers/read-key` | `readKey`, `declaresKey` | Read an author-chosen name (`$defs` entry, config key) off a map, treating inherited names such as `__proto__` as absent. |
64
+ | `@amritk/helpers/assign-key` | `assignKey` | Assign a key on a rebuilt object without letting `__proto__` reach the prototype setter. |
54
65
  | `@amritk/helpers/schema-guards` | `isSchemaObject`, `hasType`, `hasProperties`, `hasOneOf`, `hasAnyOf`, `hasAllOf`, `hasEnum`, `hasConst`, `hasPattern`, `hasFormat`, `hasDefault`, `hasExamples`, `hasRequired`, `hasItems`, `hasAdditionalProperties`, `hasMinLength`, `hasMaxLength`, `hasMinimum`, `hasMaximum`, `hasExclusiveMinimum`, `hasExclusiveMaximum`, `hasMultipleOf`, `hasMinItems`, `hasMaxItems`, `hasUniqueItems`, `hasMinProperties`, `hasMaxProperties`, … | Type-narrowing predicates for JSON Schema keywords. |
55
66
 
56
67
  ### Codegen utilities
@@ -59,14 +70,22 @@ bun add @amritk/helpers
59
70
  |:---|:---|:---|
60
71
  | `@amritk/helpers/generate-type-definition` | `generateTypeDefinition` | Render a TypeScript type from a schema node. |
61
72
  | `@amritk/helpers/mjst-extension` | `MJST_EXTENSION_KEY`, `getMjstInstanceOf`, `getMjstPrimitive`, `getMjstBrand` | Read the `x-mjst` vendor hints (`instanceOf`, `primitive`, `brand`) a schema carries. |
62
- | `@amritk/helpers/parse-documentation` | `parseDocumentation`, `ObjectDocumentation` | Parse a markdown doc file into per-property descriptions. |
73
+ | `@amritk/helpers/generate-index-barrel` | `generateIndexBarrel` | Render the `index.ts` barrel that re-exports every generated file. |
74
+ | `@amritk/helpers/escape-regex-pattern` | `escapeRegexPattern`, `regexFlagsFor`, `regexLiteral` | Embed a JSON Schema `pattern` in a generated regex literal, validating it at generation time. |
75
+ | `@amritk/helpers/quote-js-string` | `quoteJsString` | Quote a string as a JS literal, escaping only when needed. |
76
+ | `@amritk/helpers/multiple-of-check` | `multipleOfPassExpr`, `multipleOfFailExpr` | Emit a `multipleOf` check that agrees with the runtime interpreter. |
77
+ | `@amritk/helpers/numeric-bound-check` | `boundPassExpr`, `boundFailExpr`, `boundOperator` | Emit `minimum` / `maximum` / `exclusive*` checks that agree with the runtime interpreter. |
78
+ | `@amritk/helpers/string-length-check` | `minLengthPassExpr`, `maxLengthPassExpr`, … | Emit `minLength` / `maxLength` checks that count code points, not UTF-16 units. |
79
+ | `@amritk/helpers/unknown-key-check` | `unknownKeyCheck`, `INLINE_KEY_LIMIT` | Emit an unknown-key sweep — inline comparisons for small key sets, a hoisted `Set` past the limit. |
80
+ | `@amritk/helpers/parse-documentation` | `parseDocumentation`, `ObjectDocumentation` | Parse one section of the OpenAPI specification markdown (selected by a `commentUrl` fragment such as `#info-object`) into a title, description, and per-property descriptions. |
81
+ | `@amritk/helpers/safe-accessor` | `safeAccessor`, `hasOwnCheck`, `missingCheck`, `safeKey` | Emit a safe JS property-access expression (dot vs bracket notation, own-property guard for `Object.prototype` names). |
63
82
 
64
83
  ### Runtime helpers (also copied into generated output)
65
84
 
66
85
  | Subpath | Exports | Purpose |
67
86
  |:---|:---|:---|
68
87
  | `@amritk/helpers/is-object` | `isObject` | Narrow `unknown` → `Record<string, unknown>`. |
69
- | `@amritk/helpers/safe-accessor` | `safeAccessor` | Read a key from an unknown value without throwing. |
88
+ | `@amritk/helpers/has-ref` | `hasRef` | Narrow a value to an object carrying a string `$ref`. |
70
89
  | `@amritk/helpers/validate-array` | `validateArray` | Validate array shape and items. |
71
90
  | `@amritk/helpers/validate-record` | `validateRecord` | Validate record shape and additional properties. |
72
91
 
@@ -87,7 +106,7 @@ if (isObjectSchema(node) && hasProperties(node)) {
87
106
  }
88
107
  ```
89
108
 
90
- Each helper has its own colocated test file (`*.test.ts`) — read those for canonical examples.
109
+ Most helpers have a colocated test file (`*.test.ts`) — read those for canonical examples.
91
110
 
92
111
  ---
93
112
 
@@ -1,3 +1,4 @@
1
+ import { assignKey } from "./assign-key.js";
1
2
  import { assertSchemaDepth, MAX_SCHEMA_DEPTH } from "./max-schema-depth.js";
2
3
  import { getMjstBrand, getMjstInstanceOf, getMjstPrimitive } from "./mjst-extension.js";
3
4
  import { readKey } from "./read-key.js";
@@ -23,60 +24,184 @@ const refTypeName = (ref, options) => {
23
24
  return refToName(ref, options.typeSuffix);
24
25
  return "unknown";
25
26
  };
26
- const getConditionalObjectSchema = (schema) => {
27
- if (!isSchemaObject(schema)) {
28
- return null;
29
- }
30
- if (!declares(schema, "if") || !declares(schema, "then")) {
31
- return null;
32
- }
33
- const ifSchema = keywordOf(schema, "if");
34
- const thenSchema = keywordOf(schema, "then");
35
- if (!isSchemaObject(ifSchema) || !isSchemaObject(thenSchema)) {
36
- return null;
37
- }
38
- const ownProperties = keywordOf(schema, "properties");
39
- const ifProperties = keywordOf(ifSchema, "properties");
40
- const thenProperties = keywordOf(thenSchema, "properties");
41
- const hasOwnProperties = ownProperties && typeof ownProperties === "object";
42
- const hasIfProperties = ifProperties && typeof ifProperties === "object";
43
- const hasThenProperties = thenProperties && typeof thenProperties === "object";
44
- if (!hasIfProperties && !hasThenProperties) {
45
- return null;
46
- }
47
- const properties = {
48
- ...hasOwnProperties ? ownProperties : {},
49
- ...hasIfProperties ? ifProperties : {},
50
- ...hasThenProperties ? thenProperties : {}
51
- };
52
- const required = /* @__PURE__ */ new Set();
53
- for (const node of [schema, ifSchema, thenSchema]) {
54
- const declared = keywordOf(node, "required");
55
- if (Array.isArray(declared)) {
56
- for (const key of declared)
57
- required.add(key);
58
- }
27
+ const NON_PLAIN_KEYWORDS = /* @__PURE__ */ new Set([
28
+ "$ref",
29
+ "$dynamicRef",
30
+ "allOf",
31
+ "anyOf",
32
+ "oneOf",
33
+ "not",
34
+ "if",
35
+ "then",
36
+ "else",
37
+ "additionalProperties",
38
+ "patternProperties",
39
+ "items",
40
+ "prefixItems",
41
+ "const",
42
+ "enum",
43
+ "nullable",
44
+ "x-mjst"
45
+ ]);
46
+ const isPlainFragment = (schema) => {
47
+ if (!isSchemaObject(schema))
48
+ return false;
49
+ const type = keywordOf(schema, "type");
50
+ if (type !== void 0 && type !== "object")
51
+ return false;
52
+ return !Object.keys(schema).some((key) => NON_PLAIN_KEYWORDS.has(key));
53
+ };
54
+ const requiredOf = (schema) => {
55
+ const declared = keywordOf(schema, "required");
56
+ return Array.isArray(declared) ? declared.filter((key) => typeof key === "string") : [];
57
+ };
58
+ const literalDomain = (schema) => {
59
+ if (schema === void 0 || !isSchemaObject(schema))
60
+ return void 0;
61
+ if (declares(schema, "const"))
62
+ return [keywordOf(schema, "const")];
63
+ const enumValues = keywordOf(schema, "enum");
64
+ if (Array.isArray(enumValues))
65
+ return enumValues;
66
+ const type = keywordOf(schema, "type");
67
+ const members = Array.isArray(type) ? type : [type];
68
+ const values = [];
69
+ for (const member of members) {
70
+ if (member === "boolean")
71
+ values.push(true, false);
72
+ else if (member === "null")
73
+ values.push(null);
74
+ else
75
+ return void 0;
59
76
  }
60
- if (hasIfProperties) {
61
- for (const key of Object.keys(ifProperties)) {
62
- required.add(key);
77
+ if (isNullableSchema(schema))
78
+ values.push(null);
79
+ return values;
80
+ };
81
+ const sameLiteral = (a, b) => JSON.stringify(a) === JSON.stringify(b);
82
+ const negateCondition = (condition, domain, options) => {
83
+ if (!isPlainFragment(condition))
84
+ return void 0;
85
+ const tested = keywordMap(condition, "properties") ?? {};
86
+ const required = new Set(requiredOf(condition));
87
+ const readonlyPrefix = options.readonly ? "readonly " : "";
88
+ const absent = (key) => `{ ${readonlyPrefix}${safeKey(key)}?: never }`;
89
+ const failures = [];
90
+ for (const key of Object.keys(tested)) {
91
+ const test = readKey(tested, key);
92
+ const accepted = literalDomain(test);
93
+ if (accepted === void 0) {
94
+ const vacuous = test === true || isSchemaObject(test) && Object.keys(test).length === 0;
95
+ if (!vacuous)
96
+ return void 0;
97
+ if (required.has(key))
98
+ failures.push(absent(key));
99
+ continue;
63
100
  }
101
+ const possible = domain === void 0 ? void 0 : literalDomain(readKey(domain, key));
102
+ if (possible === void 0)
103
+ return void 0;
104
+ const rejected = possible.filter((value) => !accepted.some((match) => sameLiteral(value, match)));
105
+ if (rejected.length === 0) {
106
+ if (required.has(key))
107
+ failures.push(absent(key));
108
+ continue;
109
+ }
110
+ const literal = unionOf(rejected.map((value) => JSON.stringify(value)));
111
+ failures.push(`{ ${readonlyPrefix}${safeKey(key)}${required.has(key) ? "?" : ""}: ${literal} }`);
64
112
  }
65
- if (hasThenProperties) {
66
- for (const key of Object.keys(thenProperties)) {
67
- required.add(key);
113
+ for (const key of required) {
114
+ if (!Object.hasOwn(tested, key))
115
+ failures.push(absent(key));
116
+ }
117
+ return failures;
118
+ };
119
+ const branchOf = (fragments, options, depth) => {
120
+ const members = [];
121
+ const properties = {};
122
+ const required = /* @__PURE__ */ new Set();
123
+ for (const fragment of fragments) {
124
+ if (!isPlainFragment(fragment)) {
125
+ members.push(wrapUnion(getTypeScriptType(fragment, options, depth + 1)));
126
+ continue;
127
+ }
128
+ const declared = keywordMap(fragment, "properties") ?? {};
129
+ for (const key of Object.keys(declared)) {
130
+ const sub = readKey(declared, key);
131
+ const existing = readKey(properties, key);
132
+ assignKey(properties, key, existing === void 0 ? sub : { allOf: [existing, sub] });
68
133
  }
134
+ for (const key of requiredOf(fragment))
135
+ required.add(key);
136
+ }
137
+ for (const key of required) {
138
+ if (!Object.hasOwn(properties, key))
139
+ assignKey(properties, key, true);
140
+ }
141
+ if (Object.keys(properties).length > 0) {
142
+ const merged = { type: "object", properties, required: [...required] };
143
+ members.unshift(objectTypeToTs(merged, options, depth));
69
144
  }
70
- const thenRefValue = keywordOf(thenSchema, "$ref");
71
- const thenRef = typeof thenRefValue === "string" ? thenRefValue : null;
72
- return {
73
- schema: {
74
- type: "object",
75
- properties,
76
- ...required.size > 0 ? { required: Array.from(required) } : {}
77
- },
78
- thenRef
79
- };
145
+ return wrapIntersection(intersectionOf(members));
146
+ };
147
+ const conditionalMember = (schema, domain, options, depth) => {
148
+ if (!declares(schema, "if"))
149
+ return void 0;
150
+ const condition = keywordOf(schema, "if");
151
+ const thenSchema = declares(schema, "then") ? keywordOf(schema, "then") : void 0;
152
+ const elseSchema = declares(schema, "else") ? keywordOf(schema, "else") : void 0;
153
+ if (thenSchema === void 0 && elseSchema === void 0)
154
+ return void 0;
155
+ const branch = (sub) => sub === void 0 ? "unknown" : branchOf([sub], options, depth);
156
+ if (condition === true)
157
+ return thenSchema === void 0 ? void 0 : branch(thenSchema);
158
+ if (condition === false)
159
+ return elseSchema === void 0 ? void 0 : branch(elseSchema);
160
+ if (!isSchemaObject(condition))
161
+ return void 0;
162
+ const matched = branchOf(thenSchema === void 0 ? [condition] : [condition, thenSchema], options, depth);
163
+ const failures = negateCondition(condition, domain, options);
164
+ if (failures !== void 0 && failures.length === 0)
165
+ return matched === "unknown" ? void 0 : matched;
166
+ const elseType = branch(elseSchema);
167
+ const negated = failures === void 0 ? void 0 : unionOf(failures);
168
+ const bracketed = failures !== void 0 && failures.length > 1 ? `(${negated})` : negated;
169
+ const unmatched = elseType === "unknown" ? negated ?? "unknown" : bracketed === void 0 ? elseType : `(${bracketed} & ${elseType})`;
170
+ if (unmatched === "unknown" || matched === "unknown")
171
+ return void 0;
172
+ return unionOf([matched, unmatched]);
173
+ };
174
+ const withoutConditional = (schema) => {
175
+ const rest = {};
176
+ for (const key of Object.keys(schema)) {
177
+ if (key !== "if" && key !== "then" && key !== "else")
178
+ assignKey(rest, key, readKey(schema, key));
179
+ }
180
+ return rest;
181
+ };
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
+ };
189
+ const allOfMember = (entry, domain, options, depth) => {
190
+ const source = isSchemaObject(entry) ? declares(entry, "if") ? entry : referencedConditional(entry, options) : void 0;
191
+ if (source === void 0)
192
+ return wrapUnion(getTypeScriptType(entry, options, depth + 1));
193
+ const own = keywordMap(source, "properties");
194
+ const merged = {};
195
+ for (const block of [domain, own]) {
196
+ if (block === void 0)
197
+ continue;
198
+ for (const key of Object.keys(block))
199
+ assignKey(merged, key, readKey(block, key));
200
+ }
201
+ const conditional = conditionalMember(source, merged, options, depth + 1);
202
+ const rest = source === entry ? withoutConditional(entry) : entry;
203
+ const remainder = wrapUnion(getTypeScriptType(rest, options, depth + 1));
204
+ return intersectionOf([remainder, ...conditional === void 0 ? [] : [wrapUnion(conditional)]]);
80
205
  };
81
206
  const isObjectLikeSchema = (schema) => {
82
207
  if (!isSchemaObject(schema)) {
@@ -117,6 +242,7 @@ const getTypeScriptType = (schema, options, depth) => {
117
242
  };
118
243
  const isNullableSchema = (schema) => isSchemaObject(schema) && keywordOf(schema, "nullable") === true;
119
244
  const wrapUnion = (type) => type.includes(" | ") ? `(${type})` : type;
245
+ const wrapIntersection = (type) => type.includes(" & ") ? `(${type})` : type;
120
246
  const withNull = (type) => type.split(" | ").includes("null") ? type : `${type} | null`;
121
247
  const unionOf = (members) => [...new Set(members)].join(" | ");
122
248
  const intersectionOf = (members) => {
@@ -265,11 +391,6 @@ const objectTypeToTs = (schema, options, depth) => {
265
391
  return "object";
266
392
  };
267
393
  const getLocalShapeType = (schema, options, depth) => {
268
- const conditionalResult = getConditionalObjectSchema(schema);
269
- if (conditionalResult) {
270
- const baseType = objectTypeToTs(conditionalResult.schema, options, depth);
271
- return conditionalResult.thenRef ? `(${baseType}) & ${refToName(conditionalResult.thenRef, options.typeSuffix)}` : baseType;
272
- }
273
394
  const type = keywordOf(schema, "type");
274
395
  if (!type) {
275
396
  const index = getIndexSignature(schema, options, depth);
@@ -352,10 +473,14 @@ const getUnbrandedType = (schema, options, depth) => {
352
473
  const localType = getLocalShapeType(schema, options, depth);
353
474
  if (localType !== void 0)
354
475
  members.push(localType);
476
+ const domain = keywordMap(schema, "properties");
477
+ const conditional = conditionalMember(schema, domain, options, depth);
478
+ if (conditional !== void 0)
479
+ members.push(wrapUnion(conditional));
355
480
  const allOf = keywordOf(schema, "allOf");
356
481
  if (Array.isArray(allOf)) {
357
482
  for (const entry of allOf)
358
- members.push(wrapUnion(getTypeScriptType(entry, options, depth + 1)));
483
+ members.push(allOfMember(entry, domain, options, depth));
359
484
  }
360
485
  const unionBranches = unionBranchesOf(schema);
361
486
  if (unionBranches) {
@@ -383,8 +508,9 @@ const getCompositionMembers = (schema, options, depth) => {
383
508
  const members = [];
384
509
  const allOf = keywordOf(schema, "allOf");
385
510
  if (Array.isArray(allOf)) {
511
+ const domain = keywordMap(schema, "properties");
386
512
  for (const entry of allOf)
387
- members.push(wrapUnion(getTypeScriptType(entry, options, depth + 1)));
513
+ members.push(allOfMember(entry, domain, options, depth));
388
514
  }
389
515
  const ref = keywordOf(schema, "$ref");
390
516
  if (typeof ref === "string") {
@@ -409,9 +535,6 @@ const generateTypeDefinition = (schema, typeName, options = {}) => {
409
535
  return result;
410
536
  }
411
537
  if (isObjectLikeSchema(schema)) {
412
- const conditionalResult = getConditionalObjectSchema(schema);
413
- const normalizedSchema = conditionalResult?.schema ?? schema;
414
- const conditionalThenRef = conditionalResult?.thenRef ?? null;
415
538
  let jsDocTitle;
416
539
  let jsDocDescription;
417
540
  const topLevelComment = isSchemaObject(schema) ? propertyDescription(schema) : void 0;
@@ -419,9 +542,9 @@ const generateTypeDefinition = (schema, typeName, options = {}) => {
419
542
  jsDocTitle = typeName;
420
543
  jsDocDescription = topLevelComment;
421
544
  }
422
- const declaredProperties = keywordMap(normalizedSchema, "properties");
423
- const additionalProperties = keywordOf(normalizedSchema, "additionalProperties");
424
- const patternProperties = keywordMap(normalizedSchema, "patternProperties");
545
+ const declaredProperties = keywordMap(schema, "properties");
546
+ const additionalProperties = keywordOf(schema, "additionalProperties");
547
+ const patternProperties = keywordMap(schema, "patternProperties");
425
548
  const hasProperties = declaredProperties !== void 0 && Object.keys(declaredProperties).length > 0;
426
549
  const hasAdditionalProperties = typeof additionalProperties === "object" && additionalProperties !== null;
427
550
  const hasPatternProperties = patternProperties !== void 0 && Object.keys(patternProperties).length > 0;
@@ -446,7 +569,7 @@ const generateTypeDefinition = (schema, typeName, options = {}) => {
446
569
  return result2;
447
570
  }
448
571
  const schemaProps = declaredProperties ?? {};
449
- const declaredRequired = keywordOf(normalizedSchema, "required");
572
+ const declaredRequired = keywordOf(schema, "required");
450
573
  const requiredSet = new Set(Array.isArray(declaredRequired) ? declaredRequired : []);
451
574
  const declaredTypes = [];
452
575
  let hasOptionalProperty = false;
@@ -470,7 +593,7 @@ const generateTypeDefinition = (schema, typeName, options = {}) => {
470
593
  const inlineDescription = propertyDescription(propSchema);
471
594
  appendLine(inlineDescription ? buildInlinePropertyComment(inlineDescription) + " " + quotedKey + optional + ": " + propType + ";" : " " + quotedKey + optional + ": " + propType + ";");
472
595
  }
473
- const index = getIndexSignature(normalizedSchema, options, 0);
596
+ const index = getIndexSignature(schema, options, 0);
474
597
  if (index) {
475
598
  appendLine(" " + buildIndexSignatureLine(index, declaredTypes, hasOptionalProperty, options) + ";");
476
599
  }
@@ -478,13 +601,17 @@ const generateTypeDefinition = (schema, typeName, options = {}) => {
478
601
  if (jsDocTitle && jsDocDescription) {
479
602
  result += buildJsDocBlock(jsDocTitle, jsDocDescription);
480
603
  }
604
+ const conditional = conditionalMember(schema, declaredProperties, options, 0);
605
+ const intersected = [
606
+ ...conditional === void 0 ? [] : [wrapUnion(conditional)],
607
+ ...getCompositionMembers(schema, options, 0)
608
+ ];
481
609
  let typeBody = properties === "" ? "{}" : "{\n" + properties + "\n}";
482
- if (conditionalThenRef) {
483
- typeBody += " & " + refToName(conditionalThenRef, options.typeSuffix);
484
- }
485
- for (const intersectionType of getCompositionMembers(schema, options, 0)) {
486
- typeBody += " & " + intersectionType;
487
- }
610
+ if (properties === "" && intersected.length > 0)
611
+ typeBody = intersected.join(" & ");
612
+ else
613
+ for (const intersectionType of intersected)
614
+ typeBody += " & " + intersectionType;
488
615
  if (isNullableSchema(schema))
489
616
  typeBody = withNull(typeBody);
490
617
  result += "export type " + typeName + " = " + typeBody + ";";
@@ -0,0 +1,59 @@
1
+ /**
2
+ * Emits code for the JSON Schema numeric *bound* keywords — `minimum`,
3
+ * `maximum`, `exclusiveMinimum`, `exclusiveMaximum` — that agrees with the
4
+ * runtime interpreter (`packages/runtime-validators/src/interpreter/interpret.ts`).
5
+ *
6
+ * There is one rule here and it is easy to get wrong: **a bound is written as a
7
+ * pass condition and negated, never as a failure condition directly.** For every
8
+ * ordinary value the two spellings are identical:
9
+ *
10
+ * ```
11
+ * !(x >= min) // pass condition, negated
12
+ * x < min // failure condition, written directly
13
+ * ```
14
+ *
15
+ * For `NaN` they are opposite. `NaN` compares `false` against every relational
16
+ * operator, so `!(NaN >= 5)` is `true` — the value fails the bound, which is
17
+ * Ajv's verdict and the interpreter's — while `NaN < 5` is `false`, which
18
+ * silently *accepts* it. A generated validator spelled the second way was more
19
+ * permissive than the interpreter for the same schema, and nothing caught it:
20
+ * a conformance corpus is JSON, and JSON cannot express `NaN`.
21
+ *
22
+ * The keyword-level semantics this encodes, all matching Ajv:
23
+ *
24
+ * - `NaN` fails any bound it is checked against.
25
+ * - `±Infinity` follows the ordinary comparison, so `Infinity` passes
26
+ * `minimum: 0` and fails `maximum: 10`.
27
+ * - A bare `type: 'number'` with no bound still accepts non-finite numbers.
28
+ * Only a bound (or `multipleOf`) rejects them.
29
+ * - Draft-04's boolean `exclusiveMinimum: true` / `exclusiveMaximum: true`
30
+ * makes a sibling `minimum` / `maximum` strict; draft-06+ replaced it with
31
+ * the standalone numeric keywords. Both forms are spelled through `strict`.
32
+ *
33
+ * `valueExpr` is inlined once per expression, so it must be a side-effect-free
34
+ * expression (a property read or a cached variable — which is all the generators
35
+ * ever pass). Every expression is self-parenthesized, so a caller can drop one
36
+ * into a `&&` / `||` chain or negate it without re-bracketing.
37
+ *
38
+ * Companion to `multiple-of-check`, which does the same for `multipleOf`.
39
+ */
40
+ /** Which bound a check is for, in the direction it compares. */
41
+ export type BoundKind = 'minimum' | 'maximum';
42
+ /**
43
+ * Boolean expression that is TRUE when `valueExpr` satisfies the bound.
44
+ *
45
+ * @param strict `>` / `<` rather than `>=` / `<=` — draft-06+'s
46
+ * `exclusiveMinimum` / `exclusiveMaximum`, or draft-04's boolean form.
47
+ */
48
+ export declare const boundPassExpr: (valueExpr: string, kind: BoundKind, bound: number, strict?: boolean) => string;
49
+ /**
50
+ * Boolean expression that is TRUE when `valueExpr` VIOLATES the bound (the error
51
+ * condition) — the negated pass condition, which is the whole point of this
52
+ * module. See the file comment for why the direct spelling is wrong.
53
+ */
54
+ export declare const boundFailExpr: (valueExpr: string, kind: BoundKind, bound: number, strict?: boolean) => string;
55
+ /**
56
+ * The relational operator a bound's *message* names (`must be >= 5`), kept here
57
+ * so the message and the check it describes cannot drift apart.
58
+ */
59
+ export declare const boundOperator: (kind: BoundKind, strict?: boolean) => string;
@@ -0,0 +1,11 @@
1
+ const boundPassExpr = (valueExpr, kind, bound, strict = false) => {
2
+ const operator = kind === "minimum" ? strict ? ">" : ">=" : strict ? "<" : "<=";
3
+ return `(${valueExpr} ${operator} ${bound})`;
4
+ };
5
+ const boundFailExpr = (valueExpr, kind, bound, strict = false) => `!${boundPassExpr(valueExpr, kind, bound, strict)}`;
6
+ const boundOperator = (kind, strict = false) => kind === "minimum" ? strict ? ">" : ">=" : strict ? "<" : "<=";
7
+ export {
8
+ boundFailExpr,
9
+ boundOperator,
10
+ boundPassExpr
11
+ };
@@ -1,5 +1,5 @@
1
1
  const toKebabCase = (value) => value.replace(/OAuth/g, "Oauth").replace(/([A-Z]+)([A-Z][a-z])/g, "$1-$2").replace(/([a-z\d])([A-Z])/g, "$1-$2").toLowerCase();
2
- const UNSAFE_FILENAME_CHARS = /[^\p{ID_Continue}.\-]+/gu;
2
+ const UNSAFE_FILENAME_CHARS = /[^\p{ID_Continue}.-]+/gu;
3
3
  const stableSuffix = (ref) => {
4
4
  let hash = 2166136261;
5
5
  for (const char of ref) {
@@ -9,7 +9,7 @@ const stableSuffix = (ref) => {
9
9
  return hash.toString(36);
10
10
  };
11
11
  const normalizeFilename = (raw, ref) => {
12
- const cleaned = raw.replace(UNSAFE_FILENAME_CHARS, "-").replace(/-{2,}/g, "-").replace(/^[.\-]+/, "").replace(/[.\-]+$/, "");
12
+ const cleaned = raw.replace(UNSAFE_FILENAME_CHARS, "-").replace(/-{2,}/g, "-").replace(/^[.-]+/, "").replace(/[.-]+$/, "");
13
13
  return cleaned === "" ? `ref-${stableSuffix(ref)}` : cleaned;
14
14
  };
15
15
  const uriRefToFilename = (uri) => {
@@ -0,0 +1,34 @@
1
+ /**
2
+ * How a generated fast path proves that a closed object — `additionalProperties:
3
+ * false` with every declared property required — carries no undeclared key.
4
+ *
5
+ * The typed checks ahead of the test have already proven every declared key
6
+ * present, so "exactly N keys" is "no extra key", and the two strategies differ
7
+ * only in how they count:
8
+ *
9
+ * - `'count-keys'` — `Object.keys(obj).length === N`. Builds a keys array per
10
+ * call. The array is scalar-replaced on V8 when only its length is read, and
11
+ * on JavaScriptCore it is the fast form by a wide margin: a `for…in` there
12
+ * takes a generic slow path over a non-extensible (frozen, sealed) object.
13
+ * - `'count-enumerable'` — `let c = 0; for (const k in obj) c++`. Allocates
14
+ * nothing and is answered from V8's enum cache, so it is markedly faster on
15
+ * Node; on JavaScriptCore it is slower, and much slower on frozen input.
16
+ *
17
+ * The two also differ in *which* keys they see — `Object.keys` reads own keys,
18
+ * `for…in` enumerable ones, inherited included — which only matters for a value
19
+ * that could not have come from JSON. Each generator documents what its fast
20
+ * path does with such a value under either strategy.
21
+ *
22
+ * mjst benches on Bun, so `'count-keys'` is the default: it is never worse
23
+ * than about 0.9× there and up to 2× better on the strict parse case. A
24
+ * consumer running on Node alone gains from flipping to `'count-enumerable'`.
25
+ * The choice is made at generation time on purpose — generated code never
26
+ * detects its runtime.
27
+ */
28
+ export type UnknownKeysStrategy = 'count-enumerable' | 'count-keys';
29
+ /** Every strategy, in the order the CLI lists them. */
30
+ export declare const UNKNOWN_KEYS_STRATEGIES: readonly UnknownKeysStrategy[];
31
+ /** The strategy used when a caller does not choose one — see {@link UnknownKeysStrategy}. */
32
+ export declare const DEFAULT_UNKNOWN_KEYS: UnknownKeysStrategy;
33
+ /** True when `value` names a strategy — the check a CLI flag or a config key goes through. */
34
+ export declare const isUnknownKeysStrategy: (value: unknown) => value is UnknownKeysStrategy;
@@ -0,0 +1,8 @@
1
+ const UNKNOWN_KEYS_STRATEGIES = ["count-enumerable", "count-keys"];
2
+ const DEFAULT_UNKNOWN_KEYS = "count-keys";
3
+ const isUnknownKeysStrategy = (value) => typeof value === "string" && UNKNOWN_KEYS_STRATEGIES.includes(value);
4
+ export {
5
+ DEFAULT_UNKNOWN_KEYS,
6
+ UNKNOWN_KEYS_STRATEGIES,
7
+ isUnknownKeysStrategy
8
+ };
@@ -79,9 +79,20 @@ const upgradeDraft07Schema = (schema) => {
79
79
  }
80
80
  }
81
81
  }
82
+ const rewrittenRest = rewriteDefinitionsRefs(rest);
83
+ const authoredDefs = readKey(rewrittenRest, "$defs");
84
+ const mergedDefs = {};
85
+ if (typeof authoredDefs === "object" && authoredDefs !== null && !Array.isArray(authoredDefs)) {
86
+ for (const [key, value] of Object.entries(authoredDefs)) {
87
+ assignKey(mergedDefs, key, value);
88
+ }
89
+ }
90
+ for (const [key, value] of Object.entries(hoistedDefs)) {
91
+ assignKey(mergedDefs, key, value);
92
+ }
82
93
  return {
83
- ...rewriteDefinitionsRefs(rest),
84
- $defs: hoistedDefs
94
+ ...rewrittenRest,
95
+ $defs: mergedDefs
85
96
  };
86
97
  };
87
98
  const rewriteDefinitionsRefs = (obj, depth = 0, inSchemaMap = false) => {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@amritk/helpers",
3
- "version": "0.17.0",
3
+ "version": "0.19.0",
4
4
  "description": "Shared utilities for the mjst code generation ecosystem.",
5
5
  "type": "module",
6
6
  "sideEffects": false,