@amritk/helpers 0.7.1 → 0.9.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/dist/build-dynamic-ref-map.d.ts +0 -1
- package/dist/derive-root-type-name.d.ts +0 -1
- package/dist/escape-regex-pattern.d.ts +16 -0
- package/dist/escape-regex-pattern.js +20 -0
- package/dist/extract-dynamic-anchor-defs.d.ts +0 -1
- package/dist/extract-refs.d.ts +0 -1
- package/dist/generate-index-barrel.d.ts +0 -1
- package/dist/generate-type-definition.d.ts +0 -1
- package/dist/has-ref.d.ts +0 -1
- package/dist/is-object.d.ts +0 -1
- package/dist/mjst-extension.d.ts +0 -1
- package/dist/parse-documentation.d.ts +0 -1
- package/dist/ref-to-filename.d.ts +0 -1
- package/dist/ref-to-name.d.ts +0 -1
- package/dist/resolve-dynamic-refs.d.ts +4 -4
- package/dist/resolve-dynamic-refs.js +10 -4
- package/dist/resolve-ref.d.ts +0 -1
- package/dist/safe-accessor.d.ts +0 -1
- package/dist/schema-guards.d.ts +16 -1
- package/dist/schema-guards.js +29 -0
- package/dist/upgrade-draft07-schema.d.ts +0 -1
- package/dist/validate-array.d.ts +0 -1
- package/dist/validate-record.d.ts +0 -1
- package/dist/walk-ref-graph.d.ts +0 -1
- package/package.json +2 -4
- package/dist/build-dynamic-ref-map.d.ts.map +0 -1
- package/dist/derive-root-type-name.d.ts.map +0 -1
- package/dist/extract-dynamic-anchor-defs.d.ts.map +0 -1
- package/dist/extract-refs.d.ts.map +0 -1
- package/dist/generate-index-barrel.d.ts.map +0 -1
- package/dist/generate-type-definition.d.ts.map +0 -1
- package/dist/has-ref.d.ts.map +0 -1
- package/dist/is-object.d.ts.map +0 -1
- package/dist/mjst-extension.d.ts.map +0 -1
- package/dist/parse-documentation.d.ts.map +0 -1
- package/dist/ref-to-filename.d.ts.map +0 -1
- package/dist/ref-to-name.d.ts.map +0 -1
- package/dist/resolve-dynamic-refs.d.ts.map +0 -1
- package/dist/resolve-ref.d.ts.map +0 -1
- package/dist/safe-accessor.d.ts.map +0 -1
- package/dist/schema-guards.d.ts.map +0 -1
- package/dist/upgrade-draft07-schema.d.ts.map +0 -1
- package/dist/validate-array.d.ts.map +0 -1
- package/dist/validate-record.d.ts.map +0 -1
- package/dist/walk-ref-graph.d.ts.map +0 -1
- package/src/build-dynamic-ref-map.test.ts +0 -65
- package/src/build-dynamic-ref-map.ts +0 -42
- package/src/derive-root-type-name.test.ts +0 -42
- package/src/derive-root-type-name.ts +0 -42
- package/src/extract-dynamic-anchor-defs.test.ts +0 -29
- package/src/extract-dynamic-anchor-defs.ts +0 -33
- package/src/extract-refs.test.ts +0 -183
- package/src/extract-refs.ts +0 -73
- package/src/generate-index-barrel.test.ts +0 -41
- package/src/generate-index-barrel.ts +0 -62
- package/src/generate-type-definition.test.ts +0 -1386
- package/src/generate-type-definition.ts +0 -580
- package/src/has-ref.ts +0 -10
- package/src/is-object.test.ts +0 -65
- package/src/is-object.ts +0 -15
- package/src/mjst-extension.test.ts +0 -59
- package/src/mjst-extension.ts +0 -81
- package/src/parse-documentation.test.ts +0 -313
- package/src/parse-documentation.ts +0 -173
- package/src/ref-to-filename.test.ts +0 -64
- package/src/ref-to-filename.ts +0 -116
- package/src/ref-to-name.test.ts +0 -57
- package/src/ref-to-name.ts +0 -42
- package/src/resolve-dynamic-refs.test.ts +0 -94
- package/src/resolve-dynamic-refs.ts +0 -48
- package/src/resolve-ref.test.ts +0 -186
- package/src/resolve-ref.ts +0 -82
- package/src/safe-accessor.test.ts +0 -41
- package/src/safe-accessor.ts +0 -48
- package/src/schema-guards.test.ts +0 -406
- package/src/schema-guards.ts +0 -160
- package/src/upgrade-draft07-schema.ts +0 -179
- package/src/validate-array.test.ts +0 -52
- package/src/validate-array.ts +0 -15
- package/src/validate-record.test.ts +0 -56
- package/src/validate-record.ts +0 -19
- package/src/walk-ref-graph.test.ts +0 -118
- package/src/walk-ref-graph.ts +0 -184
|
@@ -1,179 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Upgrades a JSON Schema draft-07 document to be compatible with the
|
|
3
|
-
* draft 2020-12 conventions used by the build pipeline.
|
|
4
|
-
*
|
|
5
|
-
* Draft-07 schemas differ from 2020-12 in two ways that affect our pipeline:
|
|
6
|
-
* - They use `definitions` instead of `$defs`
|
|
7
|
-
* - Their `definitions` keys (and `$ref` values) may be full URIs
|
|
8
|
-
* (e.g. `http://asyncapi.com/definitions/3.1.0/channel.json`) rather than
|
|
9
|
-
* short names (e.g. `channel`)
|
|
10
|
-
*
|
|
11
|
-
* This function:
|
|
12
|
-
* 1. Renames `definitions` → `$defs` at the root level only
|
|
13
|
-
* 2. Hoists any nested `$defs` (originally `definitions` inside sub-schemas)
|
|
14
|
-
* up to the root `$defs` with a prefixed name, rewriting internal refs
|
|
15
|
-
* so they resolve correctly from the root
|
|
16
|
-
* 3. Rewrites bare `$ref: "#"` self-references within each definition to
|
|
17
|
-
* point back to that definition's root-level `$defs` entry
|
|
18
|
-
*
|
|
19
|
-
* Only applied when the schema declares `$schema: http://json-schema.org/draft-07/schema`.
|
|
20
|
-
*/
|
|
21
|
-
|
|
22
|
-
import { refToFilename, toKebabCase } from './ref-to-filename'
|
|
23
|
-
|
|
24
|
-
/**
|
|
25
|
-
* Returns true if the schema is a draft-07 document that needs upgrading.
|
|
26
|
-
*/
|
|
27
|
-
export const isDraft07Schema = (schema: Record<string, unknown>): boolean =>
|
|
28
|
-
typeof schema['$schema'] === 'string' && schema['$schema'].includes('draft-07')
|
|
29
|
-
|
|
30
|
-
/**
|
|
31
|
-
* Rewrites `$ref` values in a schema tree using an explicit string→string map.
|
|
32
|
-
* Also rewrites bare `$ref: "#"` to the given `selfRef` path when provided.
|
|
33
|
-
*/
|
|
34
|
-
const rewriteRefs = (obj: unknown, refMap: ReadonlyMap<string, string>, selfRef?: string): unknown => {
|
|
35
|
-
if (typeof obj !== 'object' || obj === null) return obj
|
|
36
|
-
if (Array.isArray(obj)) return obj.map((item) => rewriteRefs(item, refMap, selfRef))
|
|
37
|
-
|
|
38
|
-
const record = obj as Record<string, unknown>
|
|
39
|
-
const result: Record<string, unknown> = {}
|
|
40
|
-
|
|
41
|
-
for (const [key, value] of Object.entries(record)) {
|
|
42
|
-
if (key === '$ref' && typeof value === 'string') {
|
|
43
|
-
if (refMap.has(value)) {
|
|
44
|
-
result[key] = refMap.get(value)
|
|
45
|
-
} else if (value === '#' && selfRef) {
|
|
46
|
-
result[key] = selfRef
|
|
47
|
-
} else {
|
|
48
|
-
result[key] = value
|
|
49
|
-
}
|
|
50
|
-
} else {
|
|
51
|
-
result[key] = rewriteRefs(value, refMap, selfRef)
|
|
52
|
-
}
|
|
53
|
-
}
|
|
54
|
-
|
|
55
|
-
return result
|
|
56
|
-
}
|
|
57
|
-
|
|
58
|
-
/**
|
|
59
|
-
* Hoists nested `$defs` from each root-level definition up to the root `$defs`.
|
|
60
|
-
*
|
|
61
|
-
* When a definition contains its own `$defs` (originally `definitions` in draft-07,
|
|
62
|
-
* e.g. the json-schema meta-schema or avro schema), those nested defs are moved to
|
|
63
|
-
* the root with a `parentName-childName` prefix. All internal `#/$defs/X` refs
|
|
64
|
-
* within the parent and its nested defs are rewritten to `#/$defs/parentName-X`.
|
|
65
|
-
* Bare `$ref: "#"` within nested defs is rewritten to `#/$defs/parentName`.
|
|
66
|
-
*/
|
|
67
|
-
const hoistNestedDefs = (defs: Record<string, unknown>): Record<string, unknown> => {
|
|
68
|
-
const hoisted: Record<string, unknown> = {}
|
|
69
|
-
|
|
70
|
-
for (const [parentName, parentSchema] of Object.entries(defs)) {
|
|
71
|
-
if (typeof parentSchema !== 'object' || parentSchema === null) {
|
|
72
|
-
hoisted[parentName] = parentSchema
|
|
73
|
-
continue
|
|
74
|
-
}
|
|
75
|
-
|
|
76
|
-
const parentObj = parentSchema as Record<string, unknown>
|
|
77
|
-
const nestedDefs = parentObj['$defs'] as Record<string, unknown> | undefined
|
|
78
|
-
|
|
79
|
-
if (!nestedDefs || typeof nestedDefs !== 'object') {
|
|
80
|
-
hoisted[parentName] = parentSchema
|
|
81
|
-
continue
|
|
82
|
-
}
|
|
83
|
-
|
|
84
|
-
// Derive a short kebab-case prefix from the parent name (which may be a URI)
|
|
85
|
-
const parentPrefix =
|
|
86
|
-
parentName.startsWith('http://') || parentName.startsWith('https://') ? refToFilename(parentName) : parentName
|
|
87
|
-
|
|
88
|
-
// Build a map from local ref → hoisted ref for every nested def
|
|
89
|
-
const localToHoisted = new Map<string, string>()
|
|
90
|
-
for (const localName of Object.keys(nestedDefs)) {
|
|
91
|
-
const hoistedName = `${parentPrefix}-${toKebabCase(localName)}`
|
|
92
|
-
localToHoisted.set(`#/$defs/${localName}`, `#/$defs/${hoistedName}`)
|
|
93
|
-
}
|
|
94
|
-
|
|
95
|
-
const selfRef = `#/$defs/${parentPrefix}`
|
|
96
|
-
|
|
97
|
-
// Rewrite refs in the parent. Keep the nested $defs in place so that
|
|
98
|
-
// URI-with-fragment refs (e.g. "http://foo.json#/$defs/queue") can still
|
|
99
|
-
// navigate into the parent's nested defs after resolution.
|
|
100
|
-
const rewrittenParent = rewriteRefs(parentObj, localToHoisted, selfRef) as Record<string, unknown>
|
|
101
|
-
hoisted[parentName] = rewrittenParent
|
|
102
|
-
|
|
103
|
-
// Hoist each nested def, rewriting its internal refs too
|
|
104
|
-
for (const [localName, localSchema] of Object.entries(nestedDefs)) {
|
|
105
|
-
const hoistedName = `${parentPrefix}-${toKebabCase(localName)}`
|
|
106
|
-
hoisted[hoistedName] = rewriteRefs(localSchema, localToHoisted, selfRef)
|
|
107
|
-
}
|
|
108
|
-
}
|
|
109
|
-
|
|
110
|
-
return hoisted
|
|
111
|
-
}
|
|
112
|
-
|
|
113
|
-
/**
|
|
114
|
-
* Upgrades a draft-07 schema so it is compatible with the build pipeline.
|
|
115
|
-
* If the schema is not draft-07, it is returned unchanged.
|
|
116
|
-
*
|
|
117
|
-
* @param schema - The raw JSON Schema (any draft)
|
|
118
|
-
* @returns The schema with `definitions` renamed to `$defs` at the root,
|
|
119
|
-
* nested defs hoisted to the root, and internal refs rewritten
|
|
120
|
-
*/
|
|
121
|
-
export const upgradeDraft07Schema = (schema: Record<string, unknown>): Record<string, unknown> => {
|
|
122
|
-
if (!isDraft07Schema(schema)) return schema
|
|
123
|
-
|
|
124
|
-
// Rename root-level `definitions` to `$defs` (keep all other keys as-is)
|
|
125
|
-
const { definitions, $schema: _, ...rest } = schema
|
|
126
|
-
const rawDefs = (definitions ?? {}) as Record<string, unknown>
|
|
127
|
-
|
|
128
|
-
// Recursively rename `definitions` → `$defs` inside each definition's body
|
|
129
|
-
// so nested defs are accessible before hoisting
|
|
130
|
-
const renamedDefs: Record<string, unknown> = {}
|
|
131
|
-
for (const [key, value] of Object.entries(rawDefs)) {
|
|
132
|
-
renamedDefs[key] = renameNestedDefs(value)
|
|
133
|
-
}
|
|
134
|
-
|
|
135
|
-
// Hoist nested $defs up to root so the pipeline can resolve all refs flatly
|
|
136
|
-
const hoistedDefs = hoistNestedDefs(renamedDefs)
|
|
137
|
-
|
|
138
|
-
// Add short-name aliases for URI-keyed definitions so that internal refs
|
|
139
|
-
// like `#/$defs/draft-07-schema` (produced by self-ref rewriting in hoistNestedDefs)
|
|
140
|
-
// resolve correctly alongside the original URI key lookups.
|
|
141
|
-
for (const key of Object.keys(hoistedDefs)) {
|
|
142
|
-
if (key.startsWith('http://') || key.startsWith('https://')) {
|
|
143
|
-
const shortName = refToFilename(key)
|
|
144
|
-
if (shortName && !(shortName in hoistedDefs)) {
|
|
145
|
-
hoistedDefs[shortName] = hoistedDefs[key]
|
|
146
|
-
}
|
|
147
|
-
}
|
|
148
|
-
}
|
|
149
|
-
|
|
150
|
-
return {
|
|
151
|
-
...rest,
|
|
152
|
-
$defs: hoistedDefs,
|
|
153
|
-
}
|
|
154
|
-
}
|
|
155
|
-
|
|
156
|
-
/**
|
|
157
|
-
* Recursively renames `definitions` → `$defs` within a schema value and
|
|
158
|
-
* rewrites `$ref: "#/definitions/X"` to `$ref: "#/$defs/X"` so that
|
|
159
|
-
* `hoistNestedDefs` can map them to their hoisted root-level equivalents.
|
|
160
|
-
* Does NOT hoist — hoisting is done separately at the root level.
|
|
161
|
-
*/
|
|
162
|
-
const renameNestedDefs = (obj: unknown): unknown => {
|
|
163
|
-
if (typeof obj !== 'object' || obj === null) return obj
|
|
164
|
-
if (Array.isArray(obj)) return obj.map(renameNestedDefs)
|
|
165
|
-
|
|
166
|
-
const record = obj as Record<string, unknown>
|
|
167
|
-
const result: Record<string, unknown> = {}
|
|
168
|
-
|
|
169
|
-
for (const [key, value] of Object.entries(record)) {
|
|
170
|
-
if (key === '$ref' && typeof value === 'string' && value.startsWith('#/definitions/')) {
|
|
171
|
-
result[key] = value.replace('#/definitions/', '#/$defs/')
|
|
172
|
-
} else {
|
|
173
|
-
const outKey = key === 'definitions' ? '$defs' : key
|
|
174
|
-
result[outKey] = renameNestedDefs(value)
|
|
175
|
-
}
|
|
176
|
-
}
|
|
177
|
-
|
|
178
|
-
return result
|
|
179
|
-
}
|
|
@@ -1,52 +0,0 @@
|
|
|
1
|
-
import { describe, expect, it } from 'vitest'
|
|
2
|
-
|
|
3
|
-
import { validateArray } from './validate-array'
|
|
4
|
-
|
|
5
|
-
describe('validate-array', () => {
|
|
6
|
-
it('validates and transforms array items with parser function', () => {
|
|
7
|
-
const parser = (item: unknown) => (typeof item === 'number' ? item * 2 : 0)
|
|
8
|
-
const result = validateArray([1, 2, 3], parser)
|
|
9
|
-
expect(result).toEqual([2, 4, 6])
|
|
10
|
-
})
|
|
11
|
-
|
|
12
|
-
it('returns empty array when input is not an array', () => {
|
|
13
|
-
const parser = (item: unknown) => item
|
|
14
|
-
expect(validateArray(null, parser)).toEqual([])
|
|
15
|
-
expect(validateArray(undefined, parser)).toEqual([])
|
|
16
|
-
expect(validateArray('string', parser)).toEqual([])
|
|
17
|
-
expect(validateArray(123, parser)).toEqual([])
|
|
18
|
-
expect(validateArray({}, parser)).toEqual([])
|
|
19
|
-
})
|
|
20
|
-
|
|
21
|
-
it('handles empty array input', () => {
|
|
22
|
-
const parser = (item: unknown) => item
|
|
23
|
-
const result = validateArray([], parser)
|
|
24
|
-
expect(result).toEqual([])
|
|
25
|
-
})
|
|
26
|
-
|
|
27
|
-
it('applies parser to each item independently', () => {
|
|
28
|
-
const parser = (item: unknown) => {
|
|
29
|
-
if (typeof item === 'string') return item.toUpperCase()
|
|
30
|
-
if (typeof item === 'number') return item.toString()
|
|
31
|
-
return 'unknown'
|
|
32
|
-
}
|
|
33
|
-
const result = validateArray(['hello', 42, true, null], parser)
|
|
34
|
-
expect(result).toEqual(['HELLO', '42', 'unknown', 'unknown'])
|
|
35
|
-
})
|
|
36
|
-
|
|
37
|
-
it('propagates parser errors for invalid items', () => {
|
|
38
|
-
// Parser that throws on invalid input
|
|
39
|
-
const strictParser = (item: unknown) => {
|
|
40
|
-
if (typeof item !== 'number') {
|
|
41
|
-
throw new Error(`Expected number, got ${typeof item}`)
|
|
42
|
-
}
|
|
43
|
-
return item * 2
|
|
44
|
-
}
|
|
45
|
-
|
|
46
|
-
// Valid array passes through
|
|
47
|
-
expect(validateArray([1, 2, 3], strictParser)).toEqual([2, 4, 6])
|
|
48
|
-
|
|
49
|
-
// Invalid item causes parser to throw
|
|
50
|
-
expect(() => validateArray([1, 'invalid', 3], strictParser)).toThrow('Expected number, got string')
|
|
51
|
-
})
|
|
52
|
-
})
|
package/src/validate-array.ts
DELETED
|
@@ -1,15 +0,0 @@
|
|
|
1
|
-
/** Parses the items of an array with a parser function */
|
|
2
|
-
export const validateArray = (input: unknown, parser: (input: unknown) => unknown) => {
|
|
3
|
-
if (!Array.isArray(input)) {
|
|
4
|
-
return []
|
|
5
|
-
}
|
|
6
|
-
|
|
7
|
-
// Pre-allocate the result array for better performance than push()
|
|
8
|
-
const len = input.length
|
|
9
|
-
const result = new Array(len)
|
|
10
|
-
for (let i = 0; i < len; i++) {
|
|
11
|
-
result[i] = parser(input[i])
|
|
12
|
-
}
|
|
13
|
-
|
|
14
|
-
return result
|
|
15
|
-
}
|
|
@@ -1,56 +0,0 @@
|
|
|
1
|
-
import { describe, expect, it } from 'vitest'
|
|
2
|
-
|
|
3
|
-
import { validateRecord } from './validate-record'
|
|
4
|
-
|
|
5
|
-
describe('validate-record', () => {
|
|
6
|
-
it('validates all values in a record using the parser function', () => {
|
|
7
|
-
const input = { a: '1', b: '2', c: '3' }
|
|
8
|
-
const parser = (value: unknown) => Number(value)
|
|
9
|
-
const result = validateRecord(input, parser)
|
|
10
|
-
|
|
11
|
-
expect(result).toEqual({ a: 1, b: 2, c: 3 })
|
|
12
|
-
})
|
|
13
|
-
|
|
14
|
-
it('returns empty object when input is not a plain object', () => {
|
|
15
|
-
const parser = (value: unknown) => value
|
|
16
|
-
|
|
17
|
-
expect(validateRecord(null, parser)).toEqual({})
|
|
18
|
-
expect(validateRecord(undefined, parser)).toEqual({})
|
|
19
|
-
expect(validateRecord(123, parser)).toEqual({})
|
|
20
|
-
expect(validateRecord('string', parser)).toEqual({})
|
|
21
|
-
expect(validateRecord([], parser)).toEqual({})
|
|
22
|
-
expect(validateRecord(new Date(), parser)).toEqual({})
|
|
23
|
-
})
|
|
24
|
-
|
|
25
|
-
it('handles empty objects correctly', () => {
|
|
26
|
-
const parser = (value: unknown) => value
|
|
27
|
-
const result = validateRecord({}, parser)
|
|
28
|
-
|
|
29
|
-
expect(result).toEqual({})
|
|
30
|
-
})
|
|
31
|
-
|
|
32
|
-
it('preserves keys and applies parser to nested objects as values', () => {
|
|
33
|
-
const input = { user: { name: 'John' }, count: { value: 42 } }
|
|
34
|
-
const parser = (value: unknown) => JSON.stringify(value)
|
|
35
|
-
const result = validateRecord(input, parser)
|
|
36
|
-
|
|
37
|
-
expect(result).toEqual({
|
|
38
|
-
user: '{"name":"John"}',
|
|
39
|
-
count: '{"value":42}',
|
|
40
|
-
})
|
|
41
|
-
})
|
|
42
|
-
|
|
43
|
-
it('applies parser to all values including null and undefined', () => {
|
|
44
|
-
const input = { a: null, b: undefined, c: 0, d: false, e: '' }
|
|
45
|
-
const parser = (value: unknown) => (value === null || value === undefined ? 'missing' : value)
|
|
46
|
-
const result = validateRecord(input, parser)
|
|
47
|
-
|
|
48
|
-
expect(result).toEqual({
|
|
49
|
-
a: 'missing',
|
|
50
|
-
b: 'missing',
|
|
51
|
-
c: 0,
|
|
52
|
-
d: false,
|
|
53
|
-
e: '',
|
|
54
|
-
})
|
|
55
|
-
})
|
|
56
|
-
})
|
package/src/validate-record.ts
DELETED
|
@@ -1,19 +0,0 @@
|
|
|
1
|
-
import { isObject } from './is-object'
|
|
2
|
-
|
|
3
|
-
/**
|
|
4
|
-
* Parses the values of a record with a parser function.
|
|
5
|
-
* Uses for...in instead of Object.entries() to avoid allocating an intermediate array.
|
|
6
|
-
*/
|
|
7
|
-
export const validateRecord = (input: unknown, parser: (input: unknown) => unknown) => {
|
|
8
|
-
if (!isObject(input)) {
|
|
9
|
-
return {}
|
|
10
|
-
}
|
|
11
|
-
|
|
12
|
-
const record = input as Record<string, unknown>
|
|
13
|
-
const result: Record<string, unknown> = {}
|
|
14
|
-
for (const key in record) {
|
|
15
|
-
result[key] = parser(record[key])
|
|
16
|
-
}
|
|
17
|
-
|
|
18
|
-
return result
|
|
19
|
-
}
|
|
@@ -1,118 +0,0 @@
|
|
|
1
|
-
import { describe, expect, it, vi } from 'vitest'
|
|
2
|
-
|
|
3
|
-
import { type RefNode, walkRefGraph } from './walk-ref-graph'
|
|
4
|
-
|
|
5
|
-
/** Collects every visited node so a test can assert what the walker produced. */
|
|
6
|
-
const collect = (rootSchema: Parameters<typeof walkRefGraph>[0], rootTypeName: string, typeSuffix = ''): RefNode[] => {
|
|
7
|
-
const nodes: RefNode[] = []
|
|
8
|
-
walkRefGraph(rootSchema, rootTypeName, { typeSuffix }, (node) => nodes.push(node))
|
|
9
|
-
return nodes
|
|
10
|
-
}
|
|
11
|
-
|
|
12
|
-
describe('walk-ref-graph', () => {
|
|
13
|
-
it('visits the root first, then each referenced definition', () => {
|
|
14
|
-
const schema = {
|
|
15
|
-
type: 'object',
|
|
16
|
-
properties: { contact: { $ref: '#/$defs/contact' } },
|
|
17
|
-
$defs: { contact: { type: 'object', properties: { email: { type: 'string' } } } },
|
|
18
|
-
}
|
|
19
|
-
|
|
20
|
-
const nodes = collect(schema, 'Document')
|
|
21
|
-
|
|
22
|
-
expect(nodes.map((n) => ({ ref: n.ref, typeName: n.typeName, filename: n.filename, isRoot: n.isRoot }))).toEqual([
|
|
23
|
-
{ ref: undefined, typeName: 'Document', filename: 'document', isRoot: true },
|
|
24
|
-
{ ref: '#/$defs/contact', typeName: 'Contact', filename: 'contact', isRoot: false },
|
|
25
|
-
])
|
|
26
|
-
})
|
|
27
|
-
|
|
28
|
-
it('follows nested refs breadth-first and resolves each schema', () => {
|
|
29
|
-
const schema = {
|
|
30
|
-
properties: { user: { $ref: '#/$defs/user' } },
|
|
31
|
-
$defs: {
|
|
32
|
-
user: { type: 'object', properties: { address: { $ref: '#/$defs/address' } } },
|
|
33
|
-
address: { type: 'object', properties: { city: { type: 'string' } } },
|
|
34
|
-
},
|
|
35
|
-
}
|
|
36
|
-
|
|
37
|
-
const nodes = collect(schema, 'Document')
|
|
38
|
-
|
|
39
|
-
expect(nodes.map((n) => n.filename)).toEqual(['document', 'user', 'address'])
|
|
40
|
-
expect(nodes[2]?.schema).toEqual({ type: 'object', properties: { city: { type: 'string' } } })
|
|
41
|
-
})
|
|
42
|
-
|
|
43
|
-
it('applies the type suffix to ref-derived names but not the root', () => {
|
|
44
|
-
const schema = { properties: { contact: { $ref: '#/$defs/contact' } }, $defs: { contact: { type: 'object' } } }
|
|
45
|
-
|
|
46
|
-
const nodes = collect(schema, 'Document', 'Object')
|
|
47
|
-
|
|
48
|
-
expect(nodes.map((n) => n.typeName)).toEqual(['Document', 'ContactObject'])
|
|
49
|
-
})
|
|
50
|
-
|
|
51
|
-
it('does not visit two refs that map to the same filename twice', () => {
|
|
52
|
-
// A URI key and its short-name alias both resolve to the same definition and
|
|
53
|
-
// share a filename, so only one file should be emitted.
|
|
54
|
-
const schema = {
|
|
55
|
-
allOf: [{ $ref: 'http://example.com/channel.json' }, { $ref: '#/$defs/channel' }],
|
|
56
|
-
$defs: {
|
|
57
|
-
'http://example.com/channel.json': { type: 'object' },
|
|
58
|
-
channel: { type: 'object' },
|
|
59
|
-
},
|
|
60
|
-
}
|
|
61
|
-
|
|
62
|
-
const filenames = collect(schema, 'Document').map((n) => n.filename)
|
|
63
|
-
expect(filenames.filter((f) => f === 'channel')).toHaveLength(1)
|
|
64
|
-
})
|
|
65
|
-
|
|
66
|
-
it('seeds $dynamicAnchor definitions and rewrites $dynamicRef to $ref', () => {
|
|
67
|
-
const schema = {
|
|
68
|
-
type: 'object',
|
|
69
|
-
properties: { payload: { $dynamicRef: '#meta' } },
|
|
70
|
-
$defs: { schema: { $dynamicAnchor: 'meta', type: 'object' } },
|
|
71
|
-
}
|
|
72
|
-
|
|
73
|
-
const nodes = collect(schema, 'Document')
|
|
74
|
-
|
|
75
|
-
// The dynamic-anchor target gets its own file even though no plain $ref points at it...
|
|
76
|
-
expect(nodes.map((n) => n.filename)).toContain('schema')
|
|
77
|
-
// ...and the $dynamicRef on the root is rewritten to a concrete $ref.
|
|
78
|
-
const root = nodes.find((n) => n.isRoot)
|
|
79
|
-
expect(root?.schema).toMatchObject({ properties: { payload: { $ref: '#/$defs/schema' } } })
|
|
80
|
-
})
|
|
81
|
-
|
|
82
|
-
it('warns and skips a ref that cannot be resolved', () => {
|
|
83
|
-
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
|
|
84
|
-
const schema = { properties: { missing: { $ref: '#/$defs/nope' } }, $defs: {} }
|
|
85
|
-
|
|
86
|
-
const nodes = collect(schema, 'Document')
|
|
87
|
-
|
|
88
|
-
expect(nodes.map((n) => n.filename)).toEqual(['document'])
|
|
89
|
-
expect(warn).toHaveBeenCalledWith('Warning: Could not resolve ref: #/$defs/nope')
|
|
90
|
-
warn.mockRestore()
|
|
91
|
-
})
|
|
92
|
-
|
|
93
|
-
it('handles circular refs (A → B → A) without infinite looping', () => {
|
|
94
|
-
const schema = {
|
|
95
|
-
properties: { root: { $ref: '#/$defs/a' } },
|
|
96
|
-
$defs: {
|
|
97
|
-
a: { type: 'object', properties: { b: { $ref: '#/$defs/b' } } },
|
|
98
|
-
b: { type: 'object', properties: { a: { $ref: '#/$defs/a' } } },
|
|
99
|
-
},
|
|
100
|
-
}
|
|
101
|
-
|
|
102
|
-
const nodes = collect(schema, 'Document')
|
|
103
|
-
|
|
104
|
-
// Both defs are visited exactly once each despite the cycle.
|
|
105
|
-
expect(nodes.map((n) => n.filename)).toEqual(['document', 'a', 'b'])
|
|
106
|
-
})
|
|
107
|
-
|
|
108
|
-
it('reuses cached resolution across repeated walks of the same schema object', () => {
|
|
109
|
-
// The second walk should produce the same nodes from the per-root cache,
|
|
110
|
-
// proving the cache does not corrupt or drop results on reuse.
|
|
111
|
-
const schema = { properties: { contact: { $ref: '#/$defs/contact' } }, $defs: { contact: { type: 'object' } } }
|
|
112
|
-
|
|
113
|
-
const first = collect(schema, 'Document').map((n) => n.filename)
|
|
114
|
-
const second = collect(schema, 'Document').map((n) => n.filename)
|
|
115
|
-
|
|
116
|
-
expect(second).toEqual(first)
|
|
117
|
-
})
|
|
118
|
-
})
|
package/src/walk-ref-graph.ts
DELETED
|
@@ -1,184 +0,0 @@
|
|
|
1
|
-
import type { JSONSchema } from 'json-schema-typed/draft-2020-12'
|
|
2
|
-
|
|
3
|
-
import { buildDynamicRefMap } from './build-dynamic-ref-map'
|
|
4
|
-
import { extractDynamicAnchorDefs } from './extract-dynamic-anchor-defs'
|
|
5
|
-
import { extractRefs } from './extract-refs'
|
|
6
|
-
import { refToFilename } from './ref-to-filename'
|
|
7
|
-
import { refToName } from './ref-to-name'
|
|
8
|
-
import { resolveDynamicRefs } from './resolve-dynamic-refs'
|
|
9
|
-
import { resolveRef } from './resolve-ref'
|
|
10
|
-
import { upgradeDraft07Schema } from './upgrade-draft07-schema'
|
|
11
|
-
|
|
12
|
-
/**
|
|
13
|
-
* One node of the `$ref` graph, handed to the `visit` callback. Everything a
|
|
14
|
-
* generator needs to emit a single output file is pre-computed here so the
|
|
15
|
-
* traversal, naming, and `$dynamicRef` rewriting live in one place instead of
|
|
16
|
-
* being copy-pasted into every generator.
|
|
17
|
-
*/
|
|
18
|
-
export type RefNode = {
|
|
19
|
-
/** The `$ref` string this node was reached through, or `undefined` for the root schema. */
|
|
20
|
-
ref: string | undefined
|
|
21
|
-
/** PascalCase type name — the root type name verbatim, or `refToName(ref, typeSuffix)`. */
|
|
22
|
-
typeName: string
|
|
23
|
-
/** kebab-case filename without extension — the lowercased root type name, or `refToFilename(ref)`. */
|
|
24
|
-
filename: string
|
|
25
|
-
/** The subschema to generate, with any `$dynamicRef` already rewritten to `$ref`. */
|
|
26
|
-
schema: JSONSchema
|
|
27
|
-
/** The upgraded root document, for callers that resolve imports against it. */
|
|
28
|
-
rootSchema: Record<string, unknown>
|
|
29
|
-
/** True for the root schema node, which is always visited first. */
|
|
30
|
-
isRoot: boolean
|
|
31
|
-
}
|
|
32
|
-
|
|
33
|
-
/** Options controlling how `$ref`-derived names are produced. */
|
|
34
|
-
export type WalkRefGraphOptions = {
|
|
35
|
-
/**
|
|
36
|
-
* Suffix appended to every `$ref`-derived type name (e.g. `'Object'` →
|
|
37
|
-
* `ContactObject`). The root type name is used verbatim and is not affected.
|
|
38
|
-
* Defaults to `''`.
|
|
39
|
-
*/
|
|
40
|
-
readonly typeSuffix?: string
|
|
41
|
-
}
|
|
42
|
-
|
|
43
|
-
/**
|
|
44
|
-
* The reusable, schema-scoped work the walker memoizes. Keyed by the *original*
|
|
45
|
-
* root schema object so repeated walks of the same document — the parsers,
|
|
46
|
-
* validators, and examples generators all running over one loaded schema —
|
|
47
|
-
* pay for the draft-07 upgrade, the dynamic-ref map, and each `resolveRef` /
|
|
48
|
-
* `extractRefs` exactly once. JSON Schema inputs are treated as immutable here;
|
|
49
|
-
* the `WeakMap` drops the entry once the caller releases the schema.
|
|
50
|
-
*/
|
|
51
|
-
type RootCache = {
|
|
52
|
-
upgraded: Record<string, unknown>
|
|
53
|
-
dynamicRefMap: Record<string, string>
|
|
54
|
-
resolveRefCache: Map<string, Record<string, unknown> | undefined>
|
|
55
|
-
extractRefsCache: WeakMap<object, Set<string>>
|
|
56
|
-
}
|
|
57
|
-
|
|
58
|
-
const rootCaches = new WeakMap<object, RootCache>()
|
|
59
|
-
|
|
60
|
-
const getRootCache = (rootSchema: JSONSchema): RootCache => {
|
|
61
|
-
// Only object roots can key a WeakMap. A boolean root has no refs to walk and
|
|
62
|
-
// the draft-07 upgrade is a no-op for it, so a throwaway cache is fine.
|
|
63
|
-
if (typeof rootSchema !== 'object' || rootSchema === null) {
|
|
64
|
-
const upgraded = rootSchema as unknown as Record<string, unknown>
|
|
65
|
-
return { upgraded, dynamicRefMap: {}, resolveRefCache: new Map(), extractRefsCache: new WeakMap() }
|
|
66
|
-
}
|
|
67
|
-
|
|
68
|
-
const existing = rootCaches.get(rootSchema)
|
|
69
|
-
if (existing) return existing
|
|
70
|
-
|
|
71
|
-
const upgraded = upgradeDraft07Schema(rootSchema as Record<string, unknown>)
|
|
72
|
-
const cache: RootCache = {
|
|
73
|
-
upgraded,
|
|
74
|
-
dynamicRefMap: buildDynamicRefMap(upgraded as JSONSchema),
|
|
75
|
-
resolveRefCache: new Map(),
|
|
76
|
-
extractRefsCache: new WeakMap(),
|
|
77
|
-
}
|
|
78
|
-
rootCaches.set(rootSchema, cache)
|
|
79
|
-
return cache
|
|
80
|
-
}
|
|
81
|
-
|
|
82
|
-
/** Memoized `resolveRef` keyed by ref string within a single root document. */
|
|
83
|
-
const cachedResolveRef = (cache: RootCache, ref: string): Record<string, unknown> | undefined => {
|
|
84
|
-
if (cache.resolveRefCache.has(ref)) return cache.resolveRefCache.get(ref)
|
|
85
|
-
const resolved = resolveRef(ref, cache.upgraded)
|
|
86
|
-
cache.resolveRefCache.set(ref, resolved)
|
|
87
|
-
return resolved
|
|
88
|
-
}
|
|
89
|
-
|
|
90
|
-
/** Memoized `extractRefs` keyed by the (stable) resolved subschema identity. */
|
|
91
|
-
const cachedExtractRefs = (cache: RootCache, schema: JSONSchema): Set<string> => {
|
|
92
|
-
if (typeof schema !== 'object' || schema === null) return extractRefs(schema)
|
|
93
|
-
const existing = cache.extractRefsCache.get(schema)
|
|
94
|
-
if (existing) return existing
|
|
95
|
-
const refs = extractRefs(schema)
|
|
96
|
-
cache.extractRefsCache.set(schema, refs)
|
|
97
|
-
return refs
|
|
98
|
-
}
|
|
99
|
-
|
|
100
|
-
/**
|
|
101
|
-
* Walks a JSON Schema and its entire `$ref` / `$dynamicRef` graph, invoking
|
|
102
|
-
* `visit` once per distinct output file: first the root, then every reachable
|
|
103
|
-
* definition (breadth-first). This is the single, shared traversal the parser,
|
|
104
|
-
* validator, and example generators were each re-implementing.
|
|
105
|
-
*
|
|
106
|
-
* For every node the walker has already upgraded draft-07 inputs, resolved the
|
|
107
|
-
* ref, rewritten `$dynamicRef` to `$ref`, and derived the type/file names — so
|
|
108
|
-
* callers only have to turn `node.schema` into file content. Definitions
|
|
109
|
-
* reachable only via `$dynamicAnchor` are seeded too, so nothing the generated
|
|
110
|
-
* code imports goes ungenerated. A ref that fails to resolve is reported via
|
|
111
|
-
* `console.warn` and skipped, matching the generators' prior behavior.
|
|
112
|
-
*
|
|
113
|
-
* Resolution work is memoized per root document (see {@link RootCache}), so
|
|
114
|
-
* running several generators over the same loaded schema does the expensive
|
|
115
|
-
* walking once.
|
|
116
|
-
*
|
|
117
|
-
* @param rootSchema - The root JSON Schema to walk.
|
|
118
|
-
* @param rootTypeName - The name for the root type (e.g. `'Document'`).
|
|
119
|
-
* @param options - Naming options ({@link WalkRefGraphOptions}).
|
|
120
|
-
* @param visit - Called once per output file with a fully prepared {@link RefNode}.
|
|
121
|
-
*/
|
|
122
|
-
export const walkRefGraph = (
|
|
123
|
-
rootSchema: JSONSchema,
|
|
124
|
-
rootTypeName: string,
|
|
125
|
-
options: WalkRefGraphOptions,
|
|
126
|
-
visit: (node: RefNode) => void,
|
|
127
|
-
): void => {
|
|
128
|
-
const typeSuffix = options.typeSuffix ?? ''
|
|
129
|
-
const cache = getRootCache(rootSchema)
|
|
130
|
-
const { upgraded, dynamicRefMap } = cache
|
|
131
|
-
|
|
132
|
-
const processedRefs = new Set<string>()
|
|
133
|
-
const processedFilenames = new Set<string>()
|
|
134
|
-
|
|
135
|
-
// Root node first — its filename reserves a slot so a later ref that maps to
|
|
136
|
-
// the same name does not emit a duplicate file.
|
|
137
|
-
const rootFilename = rootTypeName.toLowerCase()
|
|
138
|
-
processedFilenames.add(rootFilename)
|
|
139
|
-
visit({
|
|
140
|
-
ref: undefined,
|
|
141
|
-
typeName: rootTypeName,
|
|
142
|
-
filename: rootFilename,
|
|
143
|
-
schema: resolveDynamicRefs(upgraded as JSONSchema, dynamicRefMap),
|
|
144
|
-
rootSchema: upgraded,
|
|
145
|
-
isRoot: true,
|
|
146
|
-
})
|
|
147
|
-
|
|
148
|
-
const queue: string[] = [
|
|
149
|
-
...cachedExtractRefs(cache, upgraded as JSONSchema),
|
|
150
|
-
...extractDynamicAnchorDefs(upgraded as JSONSchema),
|
|
151
|
-
]
|
|
152
|
-
|
|
153
|
-
while (queue.length > 0) {
|
|
154
|
-
const ref = queue.shift()
|
|
155
|
-
if (!ref || processedRefs.has(ref)) continue
|
|
156
|
-
processedRefs.add(ref)
|
|
157
|
-
|
|
158
|
-
const resolved = cachedResolveRef(cache, ref)
|
|
159
|
-
if (!resolved) {
|
|
160
|
-
console.warn(`Warning: Could not resolve ref: ${ref}`)
|
|
161
|
-
continue
|
|
162
|
-
}
|
|
163
|
-
|
|
164
|
-
const filename = refToFilename(ref)
|
|
165
|
-
if (!processedFilenames.has(filename)) {
|
|
166
|
-
processedFilenames.add(filename)
|
|
167
|
-
visit({
|
|
168
|
-
ref,
|
|
169
|
-
typeName: refToName(ref, typeSuffix),
|
|
170
|
-
filename,
|
|
171
|
-
schema: resolveDynamicRefs(resolved as JSONSchema, dynamicRefMap),
|
|
172
|
-
rootSchema: upgraded,
|
|
173
|
-
isRoot: false,
|
|
174
|
-
})
|
|
175
|
-
}
|
|
176
|
-
|
|
177
|
-
// Always queue nested refs from the resolved schema, even when its file was
|
|
178
|
-
// a duplicate: two ref strings can share a filename yet reach different
|
|
179
|
-
// sub-definitions (e.g. a URI key and its short-name alias).
|
|
180
|
-
for (const nested of cachedExtractRefs(cache, resolved as JSONSchema)) {
|
|
181
|
-
if (!processedRefs.has(nested)) queue.push(nested)
|
|
182
|
-
}
|
|
183
|
-
}
|
|
184
|
-
}
|