@amritk/helpers 0.13.1 → 0.13.3
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/LICENSE +21 -0
- package/dist/build-dynamic-ref-map.js +30 -53
- package/dist/derive-root-type-name.js +19 -49
- package/dist/escape-regex-pattern.js +39 -80
- package/dist/extract-dynamic-anchor-defs.js +5 -22
- package/dist/extract-refs.js +31 -63
- package/dist/generate-index-barrel.js +53 -84
- package/dist/generate-type-definition.js +372 -458
- package/dist/has-ref.js +5 -7
- package/dist/is-object.js +4 -14
- package/dist/mjst-extension.js +25 -44
- package/dist/multiple-of-check.js +12 -26
- package/dist/parse-documentation.js +86 -128
- package/dist/quote-js-string.js +4 -18
- package/dist/ref-to-filename.js +40 -105
- package/dist/ref-to-name.js +17 -53
- package/dist/resolve-dynamic-refs.js +47 -61
- package/dist/resolve-ref.js +37 -73
- package/dist/safe-accessor.js +18 -45
- package/dist/schema-guards.js +158 -175
- package/dist/unknown-key-check.js +19 -37
- package/dist/upgrade-draft07-schema.js +86 -149
- package/dist/validate-array.js +20 -31
- package/dist/validate-record.js +18 -24
- package/dist/walk-ref-graph.js +113 -158
- package/package.json +3 -3
package/dist/has-ref.js
CHANGED
|
@@ -1,8 +1,6 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
'$ref' in value &&
|
|
7
|
-
typeof value.$ref === 'string');
|
|
1
|
+
const hasRef = (value) => {
|
|
2
|
+
return typeof value === "object" && value !== null && !Array.isArray(value) && "$ref" in value && typeof value.$ref === "string";
|
|
3
|
+
};
|
|
4
|
+
export {
|
|
5
|
+
hasRef
|
|
8
6
|
};
|
package/dist/is-object.js
CHANGED
|
@@ -1,14 +1,4 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
*
|
|
6
|
-
* Examples:
|
|
7
|
-
* isObject({}) // true
|
|
8
|
-
* isObject({ a: 1 }) // true
|
|
9
|
-
* isObject([]) // false (Array)
|
|
10
|
-
* isObject(null) // false
|
|
11
|
-
* isObject(123) // false
|
|
12
|
-
* isObject('string') // false
|
|
13
|
-
*/
|
|
14
|
-
export const isObject = (value) => !!value && typeof value === 'object' && !Array.isArray(value);
|
|
1
|
+
const isObject = (value) => !!value && typeof value === "object" && !Array.isArray(value);
|
|
2
|
+
export {
|
|
3
|
+
isObject
|
|
4
|
+
};
|
package/dist/mjst-extension.js
CHANGED
|
@@ -1,51 +1,32 @@
|
|
|
1
|
-
import { isSchemaObject } from
|
|
2
|
-
|
|
3
|
-
* Vendor extension keyword carrying mjst-specific runtime hints that plain JSON
|
|
4
|
-
* Schema cannot express on its own. Adapters (TypeBox, Zod, ...) emit it when a
|
|
5
|
-
* source construct has no native JSON Schema equivalent, and the generators read
|
|
6
|
-
* it to produce the right TypeScript type and runtime checks.
|
|
7
|
-
*/
|
|
8
|
-
export const MJST_EXTENSION_KEY = 'x-mjst';
|
|
9
|
-
// Only identifier-safe class names are honoured, so a malicious or malformed
|
|
10
|
-
// schema cannot inject arbitrary code into the generated output.
|
|
1
|
+
import { isSchemaObject } from "./schema-guards.js";
|
|
2
|
+
const MJST_EXTENSION_KEY = "x-mjst";
|
|
11
3
|
const IDENTIFIER = /^[A-Za-z_$][A-Za-z0-9_$]*$/;
|
|
12
|
-
|
|
13
|
-
// Anything outside this set is ignored so unknown hints degrade gracefully.
|
|
14
|
-
const SUPPORTED_PRIMITIVES = new Set(['bigint']);
|
|
15
|
-
// Brand names are embedded inside a single-quoted string literal in generated
|
|
16
|
-
// output, so we only allow characters that cannot break out of the literal.
|
|
4
|
+
const SUPPORTED_PRIMITIVES = /* @__PURE__ */ new Set(["bigint"]);
|
|
17
5
|
const SAFE_BRAND = /^[\w$ -]+$/;
|
|
18
6
|
const readExtensionString = (schema, field) => {
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
7
|
+
if (!isSchemaObject(schema))
|
|
8
|
+
return void 0;
|
|
9
|
+
const extension = schema[MJST_EXTENSION_KEY];
|
|
10
|
+
if (typeof extension !== "object" || extension === null)
|
|
11
|
+
return void 0;
|
|
12
|
+
const value = extension[field];
|
|
13
|
+
return typeof value === "string" ? value : void 0;
|
|
26
14
|
};
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
* back to ordinary type handling.
|
|
31
|
-
*/
|
|
32
|
-
export const getMjstInstanceOf = (schema) => {
|
|
33
|
-
const instanceOf = readExtensionString(schema, 'instanceOf');
|
|
34
|
-
return instanceOf !== undefined && IDENTIFIER.test(instanceOf) ? instanceOf : undefined;
|
|
15
|
+
const getMjstInstanceOf = (schema) => {
|
|
16
|
+
const instanceOf = readExtensionString(schema, "instanceOf");
|
|
17
|
+
return instanceOf !== void 0 && IDENTIFIER.test(instanceOf) ? instanceOf : void 0;
|
|
35
18
|
};
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
*/
|
|
40
|
-
export const getMjstPrimitive = (schema) => {
|
|
41
|
-
const primitive = readExtensionString(schema, 'primitive');
|
|
42
|
-
return primitive !== undefined && SUPPORTED_PRIMITIVES.has(primitive) ? primitive : undefined;
|
|
19
|
+
const getMjstPrimitive = (schema) => {
|
|
20
|
+
const primitive = readExtensionString(schema, "primitive");
|
|
21
|
+
return primitive !== void 0 && SUPPORTED_PRIMITIVES.has(primitive) ? primitive : void 0;
|
|
43
22
|
};
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
export
|
|
49
|
-
|
|
50
|
-
|
|
23
|
+
const getMjstBrand = (schema) => {
|
|
24
|
+
const brand = readExtensionString(schema, "brand");
|
|
25
|
+
return brand !== void 0 && SAFE_BRAND.test(brand) ? brand : void 0;
|
|
26
|
+
};
|
|
27
|
+
export {
|
|
28
|
+
MJST_EXTENSION_KEY,
|
|
29
|
+
getMjstBrand,
|
|
30
|
+
getMjstInstanceOf,
|
|
31
|
+
getMjstPrimitive
|
|
51
32
|
};
|
|
@@ -1,30 +1,16 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Emits code for a JSON Schema `multipleOf` check that agrees with the runtime
|
|
3
|
-
* interpreter (`packages/runtime-validators/src/interpreter/interpret.ts`).
|
|
4
|
-
*
|
|
5
|
-
* The naive `x % m === 0` is float-wrong: IEEE-754 makes `0.3 % 0.1` evaluate to
|
|
6
|
-
* `0.0999…`, so `0.3` would spuriously fail `multipleOf: 0.1`. The interpreter
|
|
7
|
-
* instead divides and compares the quotient to its nearest integer within a
|
|
8
|
-
* tolerance that *scales with the quotient's magnitude* — a fixed epsilon falsely
|
|
9
|
-
* rejects large values (e.g. `1234567.89` against `multipleOf: 0.01`) whose
|
|
10
|
-
* representation error in the quotient already exceeds it. Keeping the emitted
|
|
11
|
-
* check identical to the interpreter's keeps generated validators/parsers and the
|
|
12
|
-
* interpreter from disagreeing on the same document.
|
|
13
|
-
*
|
|
14
|
-
* `valueExpr` is inlined three times, so it must be a side-effect-free expression
|
|
15
|
-
* (a property read or a cached variable — which is all the generators ever pass).
|
|
16
|
-
*/
|
|
17
1
|
const quotientTolerance = (valueExpr, divisor) => {
|
|
18
|
-
|
|
19
|
-
|
|
2
|
+
const q = `${valueExpr} / ${divisor}`;
|
|
3
|
+
return { q, tol: `1e-8 * Math.max(1, Math.abs(${q}))` };
|
|
20
4
|
};
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
return `Math.abs(${q} - Math.round(${q})) <= ${tol}`;
|
|
5
|
+
const multipleOfPassExpr = (valueExpr, divisor) => {
|
|
6
|
+
const { q, tol } = quotientTolerance(valueExpr, divisor);
|
|
7
|
+
return `Math.abs(${q} - Math.round(${q})) <= ${tol}`;
|
|
25
8
|
};
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
9
|
+
const multipleOfFailExpr = (valueExpr, divisor) => {
|
|
10
|
+
const { q, tol } = quotientTolerance(valueExpr, divisor);
|
|
11
|
+
return `Math.abs(${q} - Math.round(${q})) > ${tol}`;
|
|
12
|
+
};
|
|
13
|
+
export {
|
|
14
|
+
multipleOfFailExpr,
|
|
15
|
+
multipleOfPassExpr
|
|
30
16
|
};
|
|
@@ -1,136 +1,94 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
1
|
+
const parseDocumentation = (markdownDocumentation, commentUrl, fallbackCommentUrl) => {
|
|
2
|
+
try {
|
|
3
|
+
const markdown = markdownDocumentation;
|
|
4
|
+
const fragmentId = commentUrl.split("#")[1];
|
|
5
|
+
if (!fragmentId) {
|
|
6
|
+
return null;
|
|
7
|
+
}
|
|
8
|
+
const baseUrl = commentUrl.split("#")[0];
|
|
9
|
+
const titleWords = fragmentId.split("-");
|
|
10
|
+
let sectionTitle = "";
|
|
11
|
+
for (let i = 0; i < titleWords.length; i++) {
|
|
12
|
+
if (i > 0)
|
|
13
|
+
sectionTitle += " ";
|
|
14
|
+
const word = titleWords[i] ?? "";
|
|
15
|
+
sectionTitle += word.charAt(0).toUpperCase() + word.slice(1);
|
|
16
|
+
}
|
|
17
|
+
const headingLevelMatch = markdown.match(/^(#{2,5})\s+\S.*Object\s*$/m);
|
|
18
|
+
const headingHashes = headingLevelMatch?.[1] ?? "####";
|
|
19
|
+
const subHeadingHashes = headingHashes + "#";
|
|
20
|
+
const escapedHashes = headingHashes.replace(/#/g, "\\#");
|
|
21
|
+
const escapedTitle = sectionTitle.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
22
|
+
const sectionRegex = new RegExp(`${escapedHashes}\\s+${escapedTitle}\\s*\\n([\\s\\S]*?)(?=\\n${escapedHashes}\\s|$)`, "i");
|
|
23
|
+
const sectionMatch = markdown.match(sectionRegex);
|
|
24
|
+
if (!sectionMatch) {
|
|
25
|
+
return null;
|
|
26
|
+
}
|
|
27
|
+
const sectionContent = sectionMatch?.[1];
|
|
28
|
+
if (!sectionContent) {
|
|
29
|
+
return null;
|
|
30
|
+
}
|
|
31
|
+
const escapedSubHashes = subHeadingHashes.replace(/#/g, "\\#");
|
|
32
|
+
const descriptionMatch = sectionContent.match(new RegExp(`^([\\s\\S]*?)(?=\\n?${escapedSubHashes}|$)`));
|
|
33
|
+
const description = descriptionMatch?.[1]?.trim().replace(/\n/g, " ") || "";
|
|
34
|
+
const fixedFieldsRegex = new RegExp(`${escapedSubHashes} Fixed Fields\\s*\\n([\\s\\S]*)`);
|
|
35
|
+
const fixedFieldsMatch = sectionContent.match(fixedFieldsRegex);
|
|
36
|
+
const properties = {};
|
|
37
|
+
if (fixedFieldsMatch?.[1]) {
|
|
38
|
+
const fixedFieldsContent = fixedFieldsMatch[1];
|
|
39
|
+
const lines = fixedFieldsContent.split("\n");
|
|
40
|
+
let inTable = false;
|
|
41
|
+
for (const line of lines) {
|
|
42
|
+
if (line.includes("Field Name") || line.includes("---|")) {
|
|
43
|
+
inTable = true;
|
|
44
|
+
continue;
|
|
42
45
|
}
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
+
if (line.startsWith("#")) {
|
|
47
|
+
inTable = false;
|
|
48
|
+
continue;
|
|
46
49
|
}
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
// which happens when the section heading is followed by a blank line consumed by \s* in sectionRegex.
|
|
50
|
-
const escapedSubHashes = subHeadingHashes.replace(/#/g, '\\#');
|
|
51
|
-
const descriptionMatch = sectionContent.match(new RegExp(`^([\\s\\S]*?)(?=\\n?${escapedSubHashes}|$)`));
|
|
52
|
-
const description = descriptionMatch?.[1]?.trim().replace(/\n/g, ' ') || '';
|
|
53
|
-
// Extract all Fixed Fields tables within the section (some objects like Encoding Object
|
|
54
|
-
// split their fields across multiple sub-tables under different sub-sub-headings).
|
|
55
|
-
// Capture everything from the first "Fixed Fields" sub-heading to the end of the section —
|
|
56
|
-
// the section content is already bounded by the outer section regex so we don't need
|
|
57
|
-
// a stop condition here.
|
|
58
|
-
const fixedFieldsRegex = new RegExp(`${escapedSubHashes} Fixed Fields\\s*\\n([\\s\\S]*)`);
|
|
59
|
-
const fixedFieldsMatch = sectionContent.match(fixedFieldsRegex);
|
|
60
|
-
const properties = {};
|
|
61
|
-
if (fixedFieldsMatch?.[1]) {
|
|
62
|
-
const fixedFieldsContent = fixedFieldsMatch[1];
|
|
63
|
-
// Parse all markdown table rows across all sub-tables within the Fixed Fields section
|
|
64
|
-
const lines = fixedFieldsContent.split('\n');
|
|
65
|
-
let inTable = false;
|
|
66
|
-
for (const line of lines) {
|
|
67
|
-
// Skip the header row and separator row
|
|
68
|
-
if (line.includes('Field Name') || line.includes('---|')) {
|
|
69
|
-
inTable = true;
|
|
70
|
-
continue;
|
|
71
|
-
}
|
|
72
|
-
// A ###### sub-heading resets inTable so we re-enter on the next header row
|
|
73
|
-
if (line.startsWith('#')) {
|
|
74
|
-
inTable = false;
|
|
75
|
-
continue;
|
|
76
|
-
}
|
|
77
|
-
if (!inTable || !line.trim() || !line.includes('|')) {
|
|
78
|
-
continue;
|
|
79
|
-
}
|
|
80
|
-
// Parse table row: | fieldName | type | description |
|
|
81
|
-
// First, replace escaped pipes (\|) with a placeholder to avoid splitting on them
|
|
82
|
-
const lineWithPlaceholder = line.replace(/\\\|/g, '___PIPE___');
|
|
83
|
-
const cells = lineWithPlaceholder
|
|
84
|
-
.split('|')
|
|
85
|
-
.map((cell) => cell.replace(/___PIPE___/g, '|').trim())
|
|
86
|
-
.filter((cell) => cell);
|
|
87
|
-
if (cells.length >= 3) {
|
|
88
|
-
const fieldName = cells[0]?.replace(/<[^>]*>/g, '').trim(); // Remove HTML tags
|
|
89
|
-
// Some OpenAPI tables include an "Applies To" column before Description.
|
|
90
|
-
// We always want the right-most column as the property description.
|
|
91
|
-
const descriptionCellIndex = cells.length >= 4 ? 3 : 2;
|
|
92
|
-
let fieldDescription = cells[descriptionCellIndex]?.trim() || '';
|
|
93
|
-
const isRequired = fieldDescription.includes('REQUIRED');
|
|
94
|
-
// Replace relative anchor links with full URLs using the base URL
|
|
95
|
-
fieldDescription = fieldDescription.replace(/\(#([^)]+)\)/g, `(${baseUrl}#$1)`);
|
|
96
|
-
// Only accept field names that look like valid identifiers (camelCase or plain words).
|
|
97
|
-
// This filters out rows from non-field tables (e.g. type/contentType default tables)
|
|
98
|
-
// where the "field name" column contains type annotations like `string` or [_absent_].
|
|
99
|
-
const isValidFieldName = fieldName &&
|
|
100
|
-
!fieldName.includes('Field Name') &&
|
|
101
|
-
!fieldName.startsWith('`') &&
|
|
102
|
-
!fieldName.startsWith('[') &&
|
|
103
|
-
/^[a-zA-Z]/.test(fieldName);
|
|
104
|
-
if (isValidFieldName) {
|
|
105
|
-
properties[fieldName] = {
|
|
106
|
-
description: fieldDescription,
|
|
107
|
-
isRequired,
|
|
108
|
-
};
|
|
109
|
-
}
|
|
110
|
-
}
|
|
111
|
-
}
|
|
50
|
+
if (!inTable || !line.trim() || !line.includes("|")) {
|
|
51
|
+
continue;
|
|
112
52
|
}
|
|
113
|
-
|
|
114
|
-
const
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
53
|
+
const lineWithPlaceholder = line.replace(/\\\|/g, "___PIPE___");
|
|
54
|
+
const cells = lineWithPlaceholder.split("|").map((cell) => cell.replace(/___PIPE___/g, "|").trim()).filter((cell) => cell);
|
|
55
|
+
if (cells.length >= 3) {
|
|
56
|
+
const fieldName = cells[0]?.replace(/<[^>]*>/g, "").trim();
|
|
57
|
+
const descriptionCellIndex = cells.length >= 4 ? 3 : 2;
|
|
58
|
+
let fieldDescription = cells[descriptionCellIndex]?.trim() || "";
|
|
59
|
+
const isRequired = fieldDescription.includes("REQUIRED");
|
|
60
|
+
fieldDescription = fieldDescription.replace(/\(#([^)]+)\)/g, `(${baseUrl}#$1)`);
|
|
61
|
+
const isValidFieldName = fieldName && !fieldName.includes("Field Name") && !fieldName.startsWith("`") && !fieldName.startsWith("[") && /^[a-zA-Z]/.test(fieldName);
|
|
62
|
+
if (isValidFieldName) {
|
|
63
|
+
properties[fieldName] = {
|
|
64
|
+
description: fieldDescription,
|
|
65
|
+
isRequired
|
|
66
|
+
};
|
|
67
|
+
}
|
|
125
68
|
}
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
const title = sectionTitle.replace(/\sObject$/, " object");
|
|
72
|
+
if (Object.keys(properties).length === 0 && fallbackCommentUrl) {
|
|
73
|
+
const fallback = parseDocumentation(markdownDocumentation, fallbackCommentUrl);
|
|
74
|
+
if (fallback && Object.keys(fallback.properties).length > 0) {
|
|
126
75
|
return {
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
76
|
+
title,
|
|
77
|
+
description,
|
|
78
|
+
properties: fallback.properties
|
|
130
79
|
};
|
|
80
|
+
}
|
|
131
81
|
}
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
82
|
+
return {
|
|
83
|
+
title,
|
|
84
|
+
description,
|
|
85
|
+
properties
|
|
86
|
+
};
|
|
87
|
+
} catch (error) {
|
|
88
|
+
console.error("Failed to fetch OpenAPI documentation:", error);
|
|
89
|
+
return null;
|
|
90
|
+
}
|
|
91
|
+
};
|
|
92
|
+
export {
|
|
93
|
+
parseDocumentation
|
|
136
94
|
};
|
package/dist/quote-js-string.js
CHANGED
|
@@ -1,19 +1,5 @@
|
|
|
1
|
-
// Characters that force the JSON.stringify escaping path below: quote,
|
|
2
|
-
// backslash, C0 controls, and the JS line separators. Anything else sits
|
|
3
|
-
// verbatim inside a double-quoted literal.
|
|
4
|
-
// biome-ignore lint/suspicious/noControlCharactersInRegex: the C0 range is exactly the set that must never appear raw in a generated string literal
|
|
5
1
|
const NEEDS_ESCAPING = /["\\\u0000-\u001f\u2028\u2029]/;
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
* (property names, patterns, enum values) embedded in generated source — a key
|
|
11
|
-
* like `it's` or a pattern with a quote or newline must never break out of the
|
|
12
|
-
* literal or inject code, so anything carrying such a character goes through
|
|
13
|
-
* `JSON.stringify`. The common all-plain string skips the full escaper: code
|
|
14
|
-
* generators emit one literal per assertion/message, and the stringify calls
|
|
15
|
-
* were a measurable slice of generation time. Centralized so the next
|
|
16
|
-
* generator wanting the fast path cannot get the security-sensitive regex
|
|
17
|
-
* subtly wrong.
|
|
18
|
-
*/
|
|
19
|
-
export const quoteJsString = (text) => (NEEDS_ESCAPING.test(text) ? JSON.stringify(text) : `"${text}"`);
|
|
2
|
+
const quoteJsString = (text) => NEEDS_ESCAPING.test(text) ? JSON.stringify(text) : `"${text}"`;
|
|
3
|
+
export {
|
|
4
|
+
quoteJsString
|
|
5
|
+
};
|
package/dist/ref-to-filename.js
CHANGED
|
@@ -1,108 +1,43 @@
|
|
|
1
|
-
|
|
2
|
-
* Converts a PascalCase or camelCase string to kebab-case.
|
|
3
|
-
* Handles consecutive uppercase sequences (e.g. "APIKey" → "api-key") and
|
|
4
|
-
* known mixed-case acronyms like "OAuth" that would otherwise split incorrectly.
|
|
5
|
-
*
|
|
6
|
-
* @example
|
|
7
|
-
* ```ts
|
|
8
|
-
* toKebabCase('ServerVariable') // 'server-variable'
|
|
9
|
-
* toKebabCase('APIKeySecurityScheme') // 'api-key-security-scheme'
|
|
10
|
-
* toKebabCase('OAuthFlows') // 'oauth-flows'
|
|
11
|
-
* toKebabCase('already-kebab') // 'already-kebab'
|
|
12
|
-
* ```
|
|
13
|
-
*/
|
|
14
|
-
export const toKebabCase = (value) => value
|
|
15
|
-
// Collapse known mixed-case acronyms before splitting so they stay together
|
|
16
|
-
.replace(/OAuth/g, 'Oauth')
|
|
17
|
-
.replace(/([A-Z]+)([A-Z][a-z])/g, '$1-$2')
|
|
18
|
-
.replace(/([a-z\d])([A-Z])/g, '$1-$2')
|
|
19
|
-
.toLowerCase();
|
|
20
|
-
/**
|
|
21
|
-
* Derives a unique kebab-case filename from a URI ref.
|
|
22
|
-
*
|
|
23
|
-
* For a plain URI (no fragment), uses the path segments after the host,
|
|
24
|
-
* stripping version numbers, `.json` extension, and joining with `-`.
|
|
25
|
-
* For a URI with a fragment, appends the fragment's last path segment.
|
|
26
|
-
*
|
|
27
|
-
* @example
|
|
28
|
-
* ```ts
|
|
29
|
-
* uriRefToFilename('http://asyncapi.com/definitions/3.1.0/channel.json')
|
|
30
|
-
* // 'channel'
|
|
31
|
-
* uriRefToFilename('http://asyncapi.com/bindings/kafka/0.5.0/channel.json')
|
|
32
|
-
* // 'kafka-channel-binding'
|
|
33
|
-
* uriRefToFilename('http://asyncapi.com/bindings/sns/0.1.0/channel.json#/definitions/queue')
|
|
34
|
-
* // 'sns-channel-queue'
|
|
35
|
-
* ```
|
|
36
|
-
*/
|
|
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();
|
|
37
2
|
const uriRefToFilename = (uri) => {
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
const
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
const baseName = segments.map((s) => toKebabCase(s).replace(/\./g, '-')).join('-');
|
|
64
|
-
if (!fragment)
|
|
65
|
-
return baseName;
|
|
66
|
-
// Append the last meaningful segment of the fragment, skipping structural keys
|
|
67
|
-
const fragSegments = fragment.split('/').filter((s) => s && !SKIP_KEYS.has(s) && s !== 'properties');
|
|
68
|
-
const fragLast = fragSegments[fragSegments.length - 1];
|
|
69
|
-
if (!fragLast)
|
|
70
|
-
return baseName;
|
|
71
|
-
return `${baseName}-${toKebabCase(fragLast)}`;
|
|
3
|
+
const hashIndex = uri.indexOf("#");
|
|
4
|
+
const baseUri = hashIndex === -1 ? uri : uri.slice(0, hashIndex);
|
|
5
|
+
const fragment = hashIndex === -1 ? "" : uri.slice(hashIndex + 1);
|
|
6
|
+
const withoutProtocol = baseUri.replace(/^https?:\/\/[^/]+\//, "");
|
|
7
|
+
const withoutExt = withoutProtocol.replace(/\.json$/, "");
|
|
8
|
+
const rawSegments = withoutExt.split("/");
|
|
9
|
+
const SKIP_KEYS = /* @__PURE__ */ new Set(["definitions", "$defs"]);
|
|
10
|
+
const segments = [];
|
|
11
|
+
for (let i = 0; i < rawSegments.length; i++) {
|
|
12
|
+
const s = rawSegments[i];
|
|
13
|
+
if (SKIP_KEYS.has(s))
|
|
14
|
+
continue;
|
|
15
|
+
const prevRaw = rawSegments[i - 1];
|
|
16
|
+
if (/^\d+\.\d+/.test(s) && prevRaw !== void 0 && SKIP_KEYS.has(prevRaw))
|
|
17
|
+
continue;
|
|
18
|
+
segments.push(s);
|
|
19
|
+
}
|
|
20
|
+
const baseName = segments.map((s) => toKebabCase(s).replace(/\./g, "-")).join("-");
|
|
21
|
+
if (!fragment)
|
|
22
|
+
return baseName;
|
|
23
|
+
const fragSegments = fragment.split("/").filter((s) => s && !SKIP_KEYS.has(s) && s !== "properties");
|
|
24
|
+
const fragLast = fragSegments[fragSegments.length - 1];
|
|
25
|
+
if (!fragLast)
|
|
26
|
+
return baseName;
|
|
27
|
+
return `${baseName}-${toKebabCase(fragLast)}`;
|
|
72
28
|
};
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
* refToFilename('#/$defs/contact') // 'contact'
|
|
88
|
-
* refToFilename('#/$defs/server-variable') // 'server-variable'
|
|
89
|
-
* refToFilename('#/definitions/ServerVariable') // 'server-variable'
|
|
90
|
-
* refToFilename('#/definitions/APIKeySecurityScheme') // 'api-key-security-scheme'
|
|
91
|
-
* refToFilename('http://asyncapi.com/definitions/3.1.0/channel.json') // 'channel'
|
|
92
|
-
* ```
|
|
93
|
-
*/
|
|
94
|
-
export const refToFilename = (ref) => {
|
|
95
|
-
// URI ref — derive name from URI path
|
|
96
|
-
if (ref.startsWith('http://') || ref.startsWith('https://')) {
|
|
97
|
-
return uriRefToFilename(ref);
|
|
98
|
-
}
|
|
99
|
-
// Internal ref — extract the last segment after the last /
|
|
100
|
-
const segments = ref.split('/');
|
|
101
|
-
// Non-null assertion is safe here: split always returns at least one element
|
|
102
|
-
let filename = segments[segments.length - 1];
|
|
103
|
-
// Normalise PascalCase/camelCase keys (e.g. from draft-07 "definitions") to kebab-case
|
|
104
|
-
if (/[A-Z]/.test(filename)) {
|
|
105
|
-
filename = toKebabCase(filename);
|
|
106
|
-
}
|
|
107
|
-
return filename;
|
|
29
|
+
const refToFilename = (ref) => {
|
|
30
|
+
if (ref.startsWith("http://") || ref.startsWith("https://")) {
|
|
31
|
+
return uriRefToFilename(ref);
|
|
32
|
+
}
|
|
33
|
+
const segments = ref.split("/");
|
|
34
|
+
let filename = segments[segments.length - 1];
|
|
35
|
+
if (/[A-Z]/.test(filename)) {
|
|
36
|
+
filename = toKebabCase(filename);
|
|
37
|
+
}
|
|
38
|
+
return filename;
|
|
39
|
+
};
|
|
40
|
+
export {
|
|
41
|
+
refToFilename,
|
|
42
|
+
toKebabCase
|
|
108
43
|
};
|
package/dist/ref-to-name.js
CHANGED
|
@@ -1,55 +1,19 @@
|
|
|
1
|
-
import { refToFilename } from
|
|
2
|
-
/**
|
|
3
|
-
* Converts a filename-like string to a PascalCase TypeScript identifier,
|
|
4
|
-
* appending an optional suffix.
|
|
5
|
-
*
|
|
6
|
-
* Word boundaries are *any* run of characters that cannot appear in a JS
|
|
7
|
-
* identifier — not just `-` — so a dotted key like `io.k8s.api.core.v1.Pod`
|
|
8
|
-
* becomes `IoK8sApiCoreV1Pod` instead of the invalid `Io.k8s.api.core.v1.pod`.
|
|
9
|
-
* A leading digit is prefixed with `_`, and an otherwise-empty result falls back
|
|
10
|
-
* to `_`, so the output is always a usable identifier.
|
|
11
|
-
*
|
|
12
|
-
* @example
|
|
13
|
-
* ```ts
|
|
14
|
-
* kebabToPascal('server-variable') // 'ServerVariable'
|
|
15
|
-
* kebabToPascal('channel') // 'Channel'
|
|
16
|
-
* kebabToPascal('channel', 'Object') // 'ChannelObject'
|
|
17
|
-
* kebabToPascal('io.k8s.api.core.v1.pod') // 'IoK8sApiCoreV1Pod'
|
|
18
|
-
* kebabToPascal('123abc') // '_123abc'
|
|
19
|
-
* ```
|
|
20
|
-
*/
|
|
1
|
+
import { refToFilename } from "./ref-to-filename.js";
|
|
21
2
|
const kebabToPascal = (kebab, suffix) => {
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
3
|
+
const words = kebab.split(/[^A-Za-z0-9]+/);
|
|
4
|
+
let pascalCase = "";
|
|
5
|
+
for (const word of words) {
|
|
6
|
+
if (word === "")
|
|
7
|
+
continue;
|
|
8
|
+
pascalCase += word.charAt(0).toUpperCase() + word.slice(1);
|
|
9
|
+
}
|
|
10
|
+
if (pascalCase === "")
|
|
11
|
+
pascalCase = "_";
|
|
12
|
+
else if (/^[0-9]/.test(pascalCase))
|
|
13
|
+
pascalCase = `_${pascalCase}`;
|
|
14
|
+
return pascalCase + suffix;
|
|
15
|
+
};
|
|
16
|
+
const refToName = (ref, suffix = "") => kebabToPascal(refToFilename(ref), suffix);
|
|
17
|
+
export {
|
|
18
|
+
refToName
|
|
34
19
|
};
|
|
35
|
-
/**
|
|
36
|
-
* Converts a JSON Schema $ref to a type name.
|
|
37
|
-
* Derives the filename via `refToFilename` then converts to PascalCase,
|
|
38
|
-
* appending an optional suffix.
|
|
39
|
-
*
|
|
40
|
-
* Handles all ref forms: internal `#/$defs/...`, `#/definitions/...`, and URI refs.
|
|
41
|
-
*
|
|
42
|
-
* @param ref - The $ref string
|
|
43
|
-
* @param suffix - Optional suffix appended to the PascalCase name. Defaults to
|
|
44
|
-
* `''` (no suffix). Pass e.g. `'Object'` to get `ContactObject`.
|
|
45
|
-
* @returns The type name in PascalCase with the suffix applied
|
|
46
|
-
*
|
|
47
|
-
* @example
|
|
48
|
-
* ```ts
|
|
49
|
-
* refToName('#/$defs/contact') // 'Contact'
|
|
50
|
-
* refToName('#/$defs/server-variable') // 'ServerVariable'
|
|
51
|
-
* refToName('#/$defs/contact', 'Object') // 'ContactObject'
|
|
52
|
-
* refToName('http://asyncapi.com/definitions/3.1.0/channel.json') // 'Channel'
|
|
53
|
-
* ```
|
|
54
|
-
*/
|
|
55
|
-
export const refToName = (ref, suffix = '') => kebabToPascal(refToFilename(ref), suffix);
|