@amritk/helpers 0.18.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/
|
|
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/
|
|
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
|
-
|
|
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
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
const
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
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 (
|
|
61
|
-
|
|
62
|
-
|
|
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
|
-
|
|
66
|
-
|
|
67
|
-
|
|
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
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
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(
|
|
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(
|
|
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(
|
|
423
|
-
const additionalProperties = keywordOf(
|
|
424
|
-
const patternProperties = keywordMap(
|
|
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(
|
|
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(
|
|
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 (
|
|
483
|
-
typeBody
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
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 + ";";
|
package/dist/ref-to-filename.js
CHANGED
|
@@ -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}
|
|
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(/^[
|
|
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
|
-
...
|
|
84
|
-
$defs:
|
|
94
|
+
...rewrittenRest,
|
|
95
|
+
$defs: mergedDefs
|
|
85
96
|
};
|
|
86
97
|
};
|
|
87
98
|
const rewriteDefinitionsRefs = (obj, depth = 0, inSchemaMap = false) => {
|