@amritk/helpers 0.2.1 → 0.2.2

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.
@@ -0,0 +1,313 @@
1
+ import { describe, expect, it } from 'vitest'
2
+
3
+ import { parseDocumentation } from './parse-documentation'
4
+
5
+ describe('parse-documentation', () => {
6
+ const markdown = `
7
+ #### Info Object
8
+
9
+ This is the info description that spans
10
+ across multiple lines.
11
+
12
+ ##### Fixed Fields
13
+
14
+ Field Name | Type | Description
15
+ ---|---|---
16
+ title | string | **REQUIRED**. The title of the API.
17
+ description | string | A description of the API. [CommonMark syntax](http://commonmark.org/) MAY be used for rich text representation.
18
+ version | string | **REQUIRED**. The version of the OpenAPI Document.
19
+
20
+ This object MAY be extended with Specification Extensions.
21
+
22
+ #### Contact Object
23
+
24
+ Contact information for the exposed API.
25
+
26
+ ##### Fixed Fields
27
+
28
+ Field Name | Type | Description
29
+ ---|---|---
30
+ name | string | The identifying name of the contact person/organization.
31
+ url | string | The URL for the contact information. This MUST be in the form of a URL.
32
+ email | string | The email address of the contact person/organization.
33
+ `
34
+
35
+ it('parses title from fragment ID', () => {
36
+ const result = parseDocumentation(markdown, 'https://spec.openapis.org/oas/v3.1.1#info-object')
37
+ expect(result?.title).toBe('Info object')
38
+ })
39
+
40
+ it('parses description from section content', () => {
41
+ const result = parseDocumentation(markdown, 'https://spec.openapis.org/oas/v3.1.1#info-object')
42
+ expect(result?.description).toContain('info description')
43
+ })
44
+
45
+ it('parses properties from Fixed Fields table', () => {
46
+ const result = parseDocumentation(markdown, 'https://spec.openapis.org/oas/v3.1.1#info-object')
47
+ expect(result?.properties).toHaveProperty('title')
48
+ expect(result?.properties).toHaveProperty('description')
49
+ expect(result?.properties).toHaveProperty('version')
50
+ })
51
+
52
+ it('detects REQUIRED fields', () => {
53
+ const result = parseDocumentation(markdown, 'https://spec.openapis.org/oas/v3.1.1#info-object')
54
+ expect(result?.properties['title']?.isRequired).toBe(true)
55
+ expect(result?.properties['description']?.isRequired).toBe(false)
56
+ expect(result?.properties['version']?.isRequired).toBe(true)
57
+ })
58
+
59
+ it('returns null when fragment ID is missing', () => {
60
+ const result = parseDocumentation(markdown, 'https://spec.openapis.org/oas/v3.1.1')
61
+ expect(result).toBeNull()
62
+ })
63
+
64
+ it('returns null when section is not found', () => {
65
+ const result = parseDocumentation(markdown, 'https://spec.openapis.org/oas/v3.1.1#nonexistent-object')
66
+ expect(result).toBeNull()
67
+ })
68
+
69
+ it('parses contact object correctly', () => {
70
+ const result = parseDocumentation(markdown, 'https://spec.openapis.org/oas/v3.1.1#contact-object')
71
+ expect(result?.title).toBe('Contact object')
72
+ expect(result?.properties).toHaveProperty('name')
73
+ expect(result?.properties).toHaveProperty('url')
74
+ expect(result?.properties).toHaveProperty('email')
75
+ })
76
+
77
+ it('replaces relative anchor links with full URLs', () => {
78
+ const mdWithAnchors = `
79
+ #### Test Object
80
+
81
+ Test description.
82
+
83
+ ##### Fixed Fields
84
+
85
+ Field Name | Type | Description
86
+ ---|---|---
87
+ ref | string | See (#other-object) for details.
88
+ `
89
+ const result = parseDocumentation(mdWithAnchors, 'https://spec.openapis.org/oas/v3.1.1#test-object')
90
+ expect(result?.properties['ref']?.description).toContain('https://spec.openapis.org/oas/v3.1.1#other-object')
91
+ })
92
+
93
+ it('handles escaped pipes in table cells', () => {
94
+ const mdWithPipes = `
95
+ #### Pipe Object
96
+
97
+ Description.
98
+
99
+ ##### Fixed Fields
100
+
101
+ Field Name | Type | Description
102
+ ---|---|---
103
+ pattern | string | Uses \\| as separator.
104
+ `
105
+ const result = parseDocumentation(mdWithPipes, 'https://example.com#pipe-object')
106
+ expect(result?.properties['pattern']?.description).toContain('|')
107
+ })
108
+
109
+ it('handles table with Applies To column', () => {
110
+ const mdWithAppliesTo = `
111
+ #### Extended Object
112
+
113
+ Description.
114
+
115
+ ##### Fixed Fields
116
+
117
+ Field Name | Applies To | Type | Description
118
+ ---|---|---|---
119
+ name | All | string | The field name description.
120
+ `
121
+ const result = parseDocumentation(mdWithAppliesTo, 'https://example.com#extended-object')
122
+ expect(result?.properties['name']?.description).toContain('field name description')
123
+ })
124
+
125
+ it('returns null for empty markdown', () => {
126
+ const result = parseDocumentation('', 'https://example.com#some-object')
127
+ expect(result).toBeNull()
128
+ })
129
+
130
+ it('returns empty description when section has no description before Fixed Fields', () => {
131
+ const mdNoDesc = `
132
+ #### No Desc Object
133
+
134
+ ##### Fixed Fields
135
+
136
+ Field Name | Type | Description
137
+ ---|---|---
138
+ name | string | A name field.
139
+ `
140
+ const result = parseDocumentation(mdNoDesc, 'https://example.com#no-desc-object')
141
+ expect(result?.description).toBe('')
142
+ expect(result?.properties).toHaveProperty('name')
143
+ })
144
+
145
+ it('handles HTML tags in field names', () => {
146
+ const mdWithHtml = `
147
+ #### Html Object
148
+
149
+ Description.
150
+
151
+ ##### Fixed Fields
152
+
153
+ Field Name | Type | Description
154
+ ---|---|---
155
+ <span>name</span> | string | A name field.
156
+ `
157
+ const result = parseDocumentation(mdWithHtml, 'https://example.com#html-object')
158
+ expect(result?.properties).toHaveProperty('name')
159
+ })
160
+
161
+ it('inherits properties from fallback section when primary has no Fixed Fields table', () => {
162
+ const mdWithFallback = `
163
+ #### Header Object
164
+
165
+ The Header Object follows the structure of the Parameter Object.
166
+
167
+ #### Parameter Object
168
+
169
+ Parameter description.
170
+
171
+ ##### Fixed Fields
172
+
173
+ Field Name | Type | Description
174
+ ---|---|---
175
+ description | string | A brief description.
176
+ required | boolean | Whether the parameter is mandatory.
177
+ `
178
+ const result = parseDocumentation(
179
+ mdWithFallback,
180
+ 'https://example.com#header-object',
181
+ 'https://example.com#parameter-object',
182
+ )
183
+ expect(result?.title).toBe('Header object')
184
+ expect(result?.description).toContain('follows the structure')
185
+ expect(result?.properties).toHaveProperty('description')
186
+ expect(result?.properties).toHaveProperty('required')
187
+ })
188
+
189
+ it('does not use fallback when primary section has its own Fixed Fields table', () => {
190
+ const mdWithBoth = `
191
+ #### Header Object
192
+
193
+ Header description.
194
+
195
+ ##### Fixed Fields
196
+
197
+ Field Name | Type | Description
198
+ ---|---|---
199
+ ownField | string | A field unique to header.
200
+
201
+ #### Parameter Object
202
+
203
+ Parameter description.
204
+
205
+ ##### Fixed Fields
206
+
207
+ Field Name | Type | Description
208
+ ---|---|---
209
+ description | string | A brief description.
210
+ `
211
+ const result = parseDocumentation(
212
+ mdWithBoth,
213
+ 'https://example.com#header-object',
214
+ 'https://example.com#parameter-object',
215
+ )
216
+ expect(result?.properties).toHaveProperty('ownField')
217
+ expect(result?.properties).not.toHaveProperty('description')
218
+ })
219
+
220
+ it('excludes non-field rows from adjacent tables within the Fixed Fields section', () => {
221
+ // The Encoding Object has a "default contentType" table between its two Fixed Fields
222
+ // sub-tables. Rows like `\`string\`` and `[_absent_]` must not be treated as field names.
223
+ const mdWithAdjacentTable = `
224
+ #### Encoding Object
225
+
226
+ Encoding description.
227
+
228
+ ##### Fixed Fields
229
+
230
+ ###### Common Fixed Fields
231
+
232
+ | Field Name | Type | Description |
233
+ | ---- | :----: | ---- |
234
+ | contentType | \`string\` | The content type. |
235
+
236
+ This object MAY be extended with Specification Extensions.
237
+
238
+ | \`type\` | \`contentEncoding\` | Default |
239
+ | ---- | ---- | ---- |
240
+ | \`string\` | present | \`application/octet-stream\` |
241
+ | [_absent_](#foo) | n/a | \`application/octet-stream\` |
242
+
243
+ ###### RFC6570 Fields
244
+
245
+ | Field Name | Type | Description |
246
+ | ---- | :----: | ---- |
247
+ | style | \`string\` | The style. |
248
+ `
249
+ const result = parseDocumentation(mdWithAdjacentTable, 'https://example.com#encoding-object')
250
+ expect(result?.properties).toHaveProperty('contentType')
251
+ expect(result?.properties).toHaveProperty('style')
252
+ // Rows from the non-field table should be excluded
253
+ expect(result?.properties).not.toHaveProperty('`string`')
254
+ expect(result?.properties).not.toHaveProperty('`type`')
255
+ expect(Object.keys(result?.properties ?? {}).some((k) => k.startsWith('['))).toBe(false)
256
+ })
257
+
258
+ it('collects properties from multiple sub-tables within a single Fixed Fields section', () => {
259
+ const mdMultiTable = `
260
+ #### Encoding Object
261
+
262
+ Encoding description.
263
+
264
+ ##### Fixed Fields
265
+
266
+ ###### Common Fixed Fields
267
+
268
+ | Field Name | Type | Description |
269
+ | ---- | :----: | ---- |
270
+ | contentType | \`string\` | The content type. |
271
+ | headers | Map | A map of headers. |
272
+
273
+ This object MAY be extended with Specification Extensions.
274
+
275
+ ###### Fixed Fields for RFC6570-style Serialization
276
+
277
+ | Field Name | Type | Description |
278
+ | ---- | :----: | ---- |
279
+ | style | \`string\` | The style. |
280
+ | explode | \`boolean\` | Whether to explode. |
281
+ | allowReserved | \`boolean\` | Whether to allow reserved. |
282
+
283
+ #### Next Object
284
+
285
+ Next description.
286
+ `
287
+ const result = parseDocumentation(mdMultiTable, 'https://example.com#encoding-object')
288
+ expect(result?.properties).toHaveProperty('contentType')
289
+ expect(result?.properties).toHaveProperty('headers')
290
+ expect(result?.properties).toHaveProperty('style')
291
+ expect(result?.properties).toHaveProperty('explode')
292
+ expect(result?.properties).toHaveProperty('allowReserved')
293
+ expect(result?.properties['style']?.description).toBe('The style.')
294
+ })
295
+
296
+ it('ignores fallback when fallback section also has no properties', () => {
297
+ const mdNoProperties = `
298
+ #### Header Object
299
+
300
+ Header description.
301
+
302
+ #### Parameter Object
303
+
304
+ Parameter description with no table.
305
+ `
306
+ const result = parseDocumentation(
307
+ mdNoProperties,
308
+ 'https://example.com#header-object',
309
+ 'https://example.com#parameter-object',
310
+ )
311
+ expect(result?.properties).toEqual({})
312
+ })
313
+ })
@@ -0,0 +1,173 @@
1
+ type PropertyDocumentation = {
2
+ description: string
3
+ isRequired: boolean
4
+ }
5
+
6
+ export type ObjectDocumentation = {
7
+ title: string
8
+ description: string
9
+ properties: Record<string, PropertyDocumentation>
10
+ }
11
+
12
+ /**
13
+ * Fetches and parses OpenAPI specification documentation from the markdown source.
14
+ *
15
+ * When a section has no Fixed Fields table (e.g. Header Object delegates to Parameter Object),
16
+ * pass `fallbackCommentUrl` to inherit property documentation from another section.
17
+ */
18
+ export const parseDocumentation = (
19
+ markdownDocumentation: string,
20
+ commentUrl: string,
21
+ fallbackCommentUrl?: string,
22
+ ): ObjectDocumentation | null => {
23
+ try {
24
+ const markdown = markdownDocumentation
25
+
26
+ // Extract the fragment ID from the URL (e.g., #info-object)
27
+ const fragmentId = commentUrl.split('#')[1]
28
+ if (!fragmentId) {
29
+ return null
30
+ }
31
+
32
+ // Extract the base URL (everything before the #)
33
+ const baseUrl = commentUrl.split('#')[0]
34
+
35
+ // Convert fragment ID to title case (e.g., "info-object" -> "Info Object")
36
+ const titleWords = fragmentId.split('-')
37
+ let sectionTitle = ''
38
+ for (let i = 0; i < titleWords.length; i++) {
39
+ if (i > 0) sectionTitle += ' '
40
+ const word = titleWords[i] ?? ''
41
+ sectionTitle += word.charAt(0).toUpperCase() + word.slice(1)
42
+ }
43
+
44
+ // Detect the heading level used for object sections in this markdown file.
45
+ // OAS 3.1 uses #### while OAS 3.2 uses ###, so we probe for both.
46
+ const headingLevelMatch = markdown.match(/^(#{2,5})\s+\S.*Object\s*$/m)
47
+ const headingHashes = headingLevelMatch?.[1] ?? '####'
48
+ const subHeadingHashes = headingHashes + '#'
49
+
50
+ // Find the section in the markdown
51
+ // Match the section heading and capture everything until the next same-level heading or end of file
52
+ const escapedHashes = headingHashes.replace(/#/g, '\\#')
53
+ const sectionRegex = new RegExp(
54
+ `${escapedHashes}\\s+${sectionTitle}\\s*\\n([\\s\\S]*?)(?=\\n${escapedHashes}\\s|$)`,
55
+ 'i',
56
+ )
57
+ const sectionMatch = markdown.match(sectionRegex)
58
+
59
+ if (!sectionMatch) {
60
+ return null
61
+ }
62
+
63
+ const sectionContent = sectionMatch?.[1]
64
+
65
+ if (!sectionContent) {
66
+ return null
67
+ }
68
+
69
+ // Extract the description (paragraphs before the "Fixed Fields" sub-heading)
70
+ // \n? handles the case where sectionContent starts directly with the sub-heading (no leading newline),
71
+ // which happens when the section heading is followed by a blank line consumed by \s* in sectionRegex.
72
+ const escapedSubHashes = subHeadingHashes.replace(/#/g, '\\#')
73
+ const descriptionMatch = sectionContent.match(new RegExp(`^([\\s\\S]*?)(?=\\n?${escapedSubHashes}|$)`))
74
+ const description = descriptionMatch?.[1]?.trim().replace(/\n/g, ' ') || ''
75
+
76
+ // Extract all Fixed Fields tables within the section (some objects like Encoding Object
77
+ // split their fields across multiple sub-tables under different sub-sub-headings).
78
+ // Capture everything from the first "Fixed Fields" sub-heading to the end of the section —
79
+ // the section content is already bounded by the outer section regex so we don't need
80
+ // a stop condition here.
81
+ const fixedFieldsRegex = new RegExp(`${escapedSubHashes} Fixed Fields\\s*\\n([\\s\\S]*)`)
82
+ const fixedFieldsMatch = sectionContent.match(fixedFieldsRegex)
83
+
84
+ const properties: Record<string, PropertyDocumentation> = {}
85
+
86
+ if (fixedFieldsMatch?.[1]) {
87
+ const fixedFieldsContent = fixedFieldsMatch[1]
88
+
89
+ // Parse all markdown table rows across all sub-tables within the Fixed Fields section
90
+ const lines = fixedFieldsContent.split('\n')
91
+ let inTable = false
92
+
93
+ for (const line of lines) {
94
+ // Skip the header row and separator row
95
+ if (line.includes('Field Name') || line.includes('---|')) {
96
+ inTable = true
97
+ continue
98
+ }
99
+
100
+ // A ###### sub-heading resets inTable so we re-enter on the next header row
101
+ if (line.startsWith('#')) {
102
+ inTable = false
103
+ continue
104
+ }
105
+
106
+ if (!inTable || !line.trim() || !line.includes('|')) {
107
+ continue
108
+ }
109
+
110
+ // Parse table row: | fieldName | type | description |
111
+ // First, replace escaped pipes (\|) with a placeholder to avoid splitting on them
112
+ const lineWithPlaceholder = line.replace(/\\\|/g, '___PIPE___')
113
+ const cells = lineWithPlaceholder
114
+ .split('|')
115
+ .map((cell) => cell.replace(/___PIPE___/g, '|').trim())
116
+ .filter((cell) => cell)
117
+
118
+ if (cells.length >= 3) {
119
+ const fieldName = cells[0]?.replace(/<[^>]*>/g, '').trim() // Remove HTML tags
120
+ // Some OpenAPI tables include an "Applies To" column before Description.
121
+ // We always want the right-most column as the property description.
122
+ const descriptionCellIndex = cells.length >= 4 ? 3 : 2
123
+ let fieldDescription = cells[descriptionCellIndex]?.trim() || ''
124
+ const isRequired = fieldDescription.includes('REQUIRED')
125
+
126
+ // Replace relative anchor links with full URLs using the base URL
127
+ fieldDescription = fieldDescription.replace(/\(#([^)]+)\)/g, `(${baseUrl}#$1)`)
128
+
129
+ // Only accept field names that look like valid identifiers (camelCase or plain words).
130
+ // This filters out rows from non-field tables (e.g. type/contentType default tables)
131
+ // where the "field name" column contains type annotations like `string` or [_absent_].
132
+ const isValidFieldName =
133
+ fieldName &&
134
+ !fieldName.includes('Field Name') &&
135
+ !fieldName.startsWith('`') &&
136
+ !fieldName.startsWith('[') &&
137
+ /^[a-zA-Z]/.test(fieldName)
138
+
139
+ if (isValidFieldName) {
140
+ properties[fieldName] = {
141
+ description: fieldDescription,
142
+ isRequired,
143
+ }
144
+ }
145
+ }
146
+ }
147
+ }
148
+
149
+ // Format title as "Info object" instead of "Info Object"
150
+ const title = sectionTitle.replace(/\sObject$/, ' object')
151
+
152
+ // If no properties were found and a fallback URL is provided, inherit properties from it
153
+ if (Object.keys(properties).length === 0 && fallbackCommentUrl) {
154
+ const fallback = parseDocumentation(markdownDocumentation, fallbackCommentUrl)
155
+ if (fallback && Object.keys(fallback.properties).length > 0) {
156
+ return {
157
+ title,
158
+ description,
159
+ properties: fallback.properties,
160
+ }
161
+ }
162
+ }
163
+
164
+ return {
165
+ title,
166
+ description,
167
+ properties,
168
+ }
169
+ } catch (error) {
170
+ console.error('Failed to fetch OpenAPI documentation:', error)
171
+ return null
172
+ }
173
+ }
@@ -0,0 +1,64 @@
1
+ import { describe, expect, it } from 'vitest'
2
+
3
+ import { refToFilename } from './ref-to-filename'
4
+
5
+ describe('ref-to-filename', () => {
6
+ it('extracts filename from simple ref', () => {
7
+ expect(refToFilename('#/$defs/contact')).toBe('contact')
8
+ })
9
+
10
+ it('extracts filename from kebab-case ref', () => {
11
+ expect(refToFilename('#/$defs/server-variable')).toBe('server-variable')
12
+ })
13
+
14
+ it('extracts filename from multi-word ref', () => {
15
+ expect(refToFilename('#/$defs/external-documentation')).toBe('external-documentation')
16
+ })
17
+
18
+ it('extracts filename from refs with multiple path segments', () => {
19
+ expect(refToFilename('#/components/schemas/user-profile')).toBe('user-profile')
20
+ })
21
+
22
+ it('extracts filename from single word ref', () => {
23
+ expect(refToFilename('#/$defs/info')).toBe('info')
24
+ })
25
+
26
+ it('handles refs with numbers', () => {
27
+ expect(refToFilename('#/$defs/oauth2-flow')).toBe('oauth2-flow')
28
+ })
29
+
30
+ it('converts PascalCase definitions keys to kebab-case', () => {
31
+ expect(refToFilename('#/definitions/ServerVariable')).toBe('server-variable')
32
+ expect(refToFilename('#/definitions/Contact')).toBe('contact')
33
+ expect(refToFilename('#/definitions/ExternalDocumentation')).toBe('external-documentation')
34
+ })
35
+
36
+ it('converts consecutive uppercase acronyms correctly', () => {
37
+ expect(refToFilename('#/definitions/APIKeySecurityScheme')).toBe('api-key-security-scheme')
38
+ })
39
+
40
+ it('handles OAuth mixed-case acronym correctly', () => {
41
+ expect(refToFilename('#/definitions/OAuthFlows')).toBe('oauth-flows')
42
+ expect(refToFilename('#/definitions/ImplicitOAuthFlow')).toBe('implicit-oauth-flow')
43
+ expect(refToFilename('#/definitions/OAuth2SecurityScheme')).toBe('oauth2-security-scheme')
44
+ })
45
+
46
+ it('derives filename from a plain URI ref', () => {
47
+ expect(refToFilename('http://asyncapi.com/definitions/3.1.0/channel.json')).toBe('channel')
48
+ expect(refToFilename('http://asyncapi.com/definitions/3.1.0/info.json')).toBe('info')
49
+ })
50
+
51
+ it('derives filename from a URI binding ref including version for disambiguation', () => {
52
+ expect(refToFilename('http://asyncapi.com/bindings/kafka/0.5.0/channel.json')).toBe('bindings-kafka-0-5-0-channel')
53
+ })
54
+
55
+ it('derives filename from a URI ref with a fragment', () => {
56
+ expect(refToFilename('http://asyncapi.com/bindings/sns/0.1.0/channel.json#/definitions/queue')).toBe(
57
+ 'bindings-sns-0-1-0-channel-queue',
58
+ )
59
+ })
60
+
61
+ it('handles URI ref with empty fragment (trailing #)', () => {
62
+ expect(refToFilename('http://json-schema.org/draft-07/schema#')).toBe('draft-07-schema')
63
+ })
64
+ })
@@ -0,0 +1,116 @@
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: string): string =>
15
+ value
16
+ // Collapse known mixed-case acronyms before splitting so they stay together
17
+ .replace(/OAuth/g, 'Oauth')
18
+ .replace(/([A-Z]+)([A-Z][a-z])/g, '$1-$2')
19
+ .replace(/([a-z\d])([A-Z])/g, '$1-$2')
20
+ .toLowerCase()
21
+
22
+ /**
23
+ * Derives a unique kebab-case filename from a URI ref.
24
+ *
25
+ * For a plain URI (no fragment), uses the path segments after the host,
26
+ * stripping version numbers, `.json` extension, and joining with `-`.
27
+ * For a URI with a fragment, appends the fragment's last path segment.
28
+ *
29
+ * @example
30
+ * ```ts
31
+ * uriRefToFilename('http://asyncapi.com/definitions/3.1.0/channel.json')
32
+ * // 'channel'
33
+ * uriRefToFilename('http://asyncapi.com/bindings/kafka/0.5.0/channel.json')
34
+ * // 'kafka-channel-binding'
35
+ * uriRefToFilename('http://asyncapi.com/bindings/sns/0.1.0/channel.json#/definitions/queue')
36
+ * // 'sns-channel-queue'
37
+ * ```
38
+ */
39
+ const uriRefToFilename = (uri: string): string => {
40
+ const hashIndex = uri.indexOf('#')
41
+ const baseUri = hashIndex === -1 ? uri : uri.slice(0, hashIndex)
42
+ const fragment = hashIndex === -1 ? '' : uri.slice(hashIndex + 1)
43
+
44
+ // Strip protocol + host, remove .json extension
45
+ const withoutProtocol = baseUri.replace(/^https?:\/\/[^/]+\//, '')
46
+ const withoutExt = withoutProtocol.replace(/\.json$/, '')
47
+
48
+ // Drop structural/noise segments:
49
+ // - "definitions" and "$defs" container keys
50
+ // - Version numbers that immediately follow "definitions" (e.g. "3.1.0" in "definitions/3.1.0/channel")
51
+ // but NOT version numbers in other positions (e.g. "0.5.0" in "bindings/kafka/0.5.0/channel")
52
+ // since those are needed to disambiguate multiple versions of the same binding
53
+ const rawSegments = withoutExt.split('/')
54
+ const SKIP_KEYS = new Set(['definitions', '$defs'])
55
+ const segments: string[] = []
56
+ for (let i = 0; i < rawSegments.length; i++) {
57
+ const s = rawSegments[i] as string
58
+ if (SKIP_KEYS.has(s)) continue
59
+ // Skip a version segment only if the previous (non-skipped) segment was "definitions"
60
+ const prevRaw = rawSegments[i - 1]
61
+ if (/^\d+\.\d+/.test(s) && prevRaw !== undefined && SKIP_KEYS.has(prevRaw)) continue
62
+ segments.push(s)
63
+ }
64
+
65
+ // Join remaining segments, converting to kebab-case and replacing dots with dashes
66
+ const baseName = segments.map((s) => toKebabCase(s).replace(/\./g, '-')).join('-')
67
+
68
+ if (!fragment) return baseName
69
+
70
+ // Append the last meaningful segment of the fragment, skipping structural keys
71
+ const fragSegments = fragment.split('/').filter((s) => s && !SKIP_KEYS.has(s) && s !== 'properties')
72
+ const fragLast = fragSegments[fragSegments.length - 1]
73
+ if (!fragLast) return baseName
74
+
75
+ return `${baseName}-${toKebabCase(fragLast)}`
76
+ }
77
+
78
+ /**
79
+ * Converts a JSON Schema $ref to a filename.
80
+ *
81
+ * Handles three ref forms:
82
+ * - Internal `#/$defs/contact` → `contact`
83
+ * - Internal `#/definitions/ServerVariable` → `server-variable`
84
+ * - URI `http://example.com/definitions/3.1.0/channel.json` → `channel`
85
+ * - URI with fragment `http://example.com/channel.json#/definitions/queue` → `channel-queue`
86
+ *
87
+ * @param ref - The $ref string
88
+ * @returns The filename without extension
89
+ *
90
+ * @example
91
+ * ```ts
92
+ * refToFilename('#/$defs/contact') // 'contact'
93
+ * refToFilename('#/$defs/server-variable') // 'server-variable'
94
+ * refToFilename('#/definitions/ServerVariable') // 'server-variable'
95
+ * refToFilename('#/definitions/APIKeySecurityScheme') // 'api-key-security-scheme'
96
+ * refToFilename('http://asyncapi.com/definitions/3.1.0/channel.json') // 'channel'
97
+ * ```
98
+ */
99
+ export const refToFilename = (ref: string): string => {
100
+ // URI ref — derive name from URI path
101
+ if (ref.startsWith('http://') || ref.startsWith('https://')) {
102
+ return uriRefToFilename(ref)
103
+ }
104
+
105
+ // Internal ref — extract the last segment after the last /
106
+ const segments = ref.split('/')
107
+ // Non-null assertion is safe here: split always returns at least one element
108
+ let filename = segments[segments.length - 1] as string
109
+
110
+ // Normalise PascalCase/camelCase keys (e.g. from draft-07 "definitions") to kebab-case
111
+ if (/[A-Z]/.test(filename)) {
112
+ filename = toKebabCase(filename)
113
+ }
114
+
115
+ return filename
116
+ }