@amritk/helpers 0.2.1 → 0.3.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.
Files changed (39) hide show
  1. package/dist/build-dynamic-ref-map.js +5 -3
  2. package/dist/derive-root-type-name.d.ts +20 -0
  3. package/dist/derive-root-type-name.js +19 -0
  4. package/dist/generate-type-definition.js +5 -3
  5. package/dist/has-ref.d.ts +4 -0
  6. package/dist/has-ref.js +7 -0
  7. package/dist/schema-guards.d.ts +1 -5
  8. package/dist/schema-guards.js +5 -3
  9. package/package.json +15 -3
  10. package/src/build-dynamic-ref-map.test.ts +65 -0
  11. package/src/build-dynamic-ref-map.ts +42 -0
  12. package/src/derive-root-type-name.test.ts +42 -0
  13. package/src/derive-root-type-name.ts +42 -0
  14. package/src/extract-refs.test.ts +183 -0
  15. package/src/extract-refs.ts +73 -0
  16. package/src/generate-type-definition.test.ts +1210 -0
  17. package/src/generate-type-definition.ts +487 -0
  18. package/src/has-ref.ts +10 -0
  19. package/src/is-object.test.ts +65 -0
  20. package/src/is-object.ts +15 -0
  21. package/src/parse-documentation.test.ts +313 -0
  22. package/src/parse-documentation.ts +173 -0
  23. package/src/ref-to-filename.test.ts +64 -0
  24. package/src/ref-to-filename.ts +116 -0
  25. package/src/ref-to-name.test.ts +48 -0
  26. package/src/ref-to-name.ts +38 -0
  27. package/src/resolve-dynamic-refs.test.ts +94 -0
  28. package/src/resolve-dynamic-refs.ts +48 -0
  29. package/src/resolve-ref.test.ts +186 -0
  30. package/src/resolve-ref.ts +82 -0
  31. package/src/safe-accessor.test.ts +41 -0
  32. package/src/safe-accessor.ts +48 -0
  33. package/src/schema-guards.test.ts +406 -0
  34. package/src/schema-guards.ts +160 -0
  35. package/src/upgrade-draft07-schema.ts +179 -0
  36. package/src/validate-array.test.ts +52 -0
  37. package/src/validate-array.ts +15 -0
  38. package/src/validate-record.test.ts +56 -0
  39. package/src/validate-record.ts +19 -0
@@ -0,0 +1,179 @@
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
+ }
@@ -0,0 +1,52 @@
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
+ })
@@ -0,0 +1,15 @@
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
+ }
@@ -0,0 +1,56 @@
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
+ })
@@ -0,0 +1,19 @@
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
+ }