@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.
Files changed (83) hide show
  1. package/dist/build-dynamic-ref-map.d.ts +0 -1
  2. package/dist/derive-root-type-name.d.ts +0 -1
  3. package/dist/escape-regex-pattern.d.ts +16 -0
  4. package/dist/escape-regex-pattern.js +20 -0
  5. package/dist/extract-dynamic-anchor-defs.d.ts +0 -1
  6. package/dist/extract-refs.d.ts +0 -1
  7. package/dist/generate-index-barrel.d.ts +0 -1
  8. package/dist/generate-type-definition.d.ts +0 -1
  9. package/dist/has-ref.d.ts +0 -1
  10. package/dist/is-object.d.ts +0 -1
  11. package/dist/mjst-extension.d.ts +0 -1
  12. package/dist/parse-documentation.d.ts +0 -1
  13. package/dist/ref-to-filename.d.ts +0 -1
  14. package/dist/ref-to-name.d.ts +0 -1
  15. package/dist/resolve-dynamic-refs.d.ts +4 -4
  16. package/dist/resolve-dynamic-refs.js +10 -4
  17. package/dist/resolve-ref.d.ts +0 -1
  18. package/dist/safe-accessor.d.ts +0 -1
  19. package/dist/schema-guards.d.ts +16 -1
  20. package/dist/schema-guards.js +29 -0
  21. package/dist/upgrade-draft07-schema.d.ts +0 -1
  22. package/dist/validate-array.d.ts +0 -1
  23. package/dist/validate-record.d.ts +0 -1
  24. package/dist/walk-ref-graph.d.ts +0 -1
  25. package/package.json +2 -4
  26. package/dist/build-dynamic-ref-map.d.ts.map +0 -1
  27. package/dist/derive-root-type-name.d.ts.map +0 -1
  28. package/dist/extract-dynamic-anchor-defs.d.ts.map +0 -1
  29. package/dist/extract-refs.d.ts.map +0 -1
  30. package/dist/generate-index-barrel.d.ts.map +0 -1
  31. package/dist/generate-type-definition.d.ts.map +0 -1
  32. package/dist/has-ref.d.ts.map +0 -1
  33. package/dist/is-object.d.ts.map +0 -1
  34. package/dist/mjst-extension.d.ts.map +0 -1
  35. package/dist/parse-documentation.d.ts.map +0 -1
  36. package/dist/ref-to-filename.d.ts.map +0 -1
  37. package/dist/ref-to-name.d.ts.map +0 -1
  38. package/dist/resolve-dynamic-refs.d.ts.map +0 -1
  39. package/dist/resolve-ref.d.ts.map +0 -1
  40. package/dist/safe-accessor.d.ts.map +0 -1
  41. package/dist/schema-guards.d.ts.map +0 -1
  42. package/dist/upgrade-draft07-schema.d.ts.map +0 -1
  43. package/dist/validate-array.d.ts.map +0 -1
  44. package/dist/validate-record.d.ts.map +0 -1
  45. package/dist/walk-ref-graph.d.ts.map +0 -1
  46. package/src/build-dynamic-ref-map.test.ts +0 -65
  47. package/src/build-dynamic-ref-map.ts +0 -42
  48. package/src/derive-root-type-name.test.ts +0 -42
  49. package/src/derive-root-type-name.ts +0 -42
  50. package/src/extract-dynamic-anchor-defs.test.ts +0 -29
  51. package/src/extract-dynamic-anchor-defs.ts +0 -33
  52. package/src/extract-refs.test.ts +0 -183
  53. package/src/extract-refs.ts +0 -73
  54. package/src/generate-index-barrel.test.ts +0 -41
  55. package/src/generate-index-barrel.ts +0 -62
  56. package/src/generate-type-definition.test.ts +0 -1386
  57. package/src/generate-type-definition.ts +0 -580
  58. package/src/has-ref.ts +0 -10
  59. package/src/is-object.test.ts +0 -65
  60. package/src/is-object.ts +0 -15
  61. package/src/mjst-extension.test.ts +0 -59
  62. package/src/mjst-extension.ts +0 -81
  63. package/src/parse-documentation.test.ts +0 -313
  64. package/src/parse-documentation.ts +0 -173
  65. package/src/ref-to-filename.test.ts +0 -64
  66. package/src/ref-to-filename.ts +0 -116
  67. package/src/ref-to-name.test.ts +0 -57
  68. package/src/ref-to-name.ts +0 -42
  69. package/src/resolve-dynamic-refs.test.ts +0 -94
  70. package/src/resolve-dynamic-refs.ts +0 -48
  71. package/src/resolve-ref.test.ts +0 -186
  72. package/src/resolve-ref.ts +0 -82
  73. package/src/safe-accessor.test.ts +0 -41
  74. package/src/safe-accessor.ts +0 -48
  75. package/src/schema-guards.test.ts +0 -406
  76. package/src/schema-guards.ts +0 -160
  77. package/src/upgrade-draft07-schema.ts +0 -179
  78. package/src/validate-array.test.ts +0 -52
  79. package/src/validate-array.ts +0 -15
  80. package/src/validate-record.test.ts +0 -56
  81. package/src/validate-record.ts +0 -19
  82. package/src/walk-ref-graph.test.ts +0 -118
  83. package/src/walk-ref-graph.ts +0 -184
@@ -1,59 +0,0 @@
1
- import type { JSONSchema } from 'json-schema-typed/draft-2020-12'
2
- import { describe, expect, it } from 'vitest'
3
-
4
- import { getMjstBrand, getMjstInstanceOf, getMjstPrimitive, MJST_EXTENSION_KEY } from './mjst-extension'
5
-
6
- describe('getMjstInstanceOf', () => {
7
- it('reads a valid instanceOf class name', () => {
8
- expect(getMjstInstanceOf({ 'x-mjst': { instanceOf: 'Date' } })).toBe('Date')
9
- })
10
-
11
- it('returns undefined when the extension is absent', () => {
12
- expect(getMjstInstanceOf({ type: 'string' })).toBeUndefined()
13
- })
14
-
15
- it('returns undefined for a boolean schema', () => {
16
- expect(getMjstInstanceOf(true as unknown as JSONSchema)).toBeUndefined()
17
- })
18
-
19
- it('rejects instanceOf values that are not safe identifiers', () => {
20
- expect(getMjstInstanceOf({ 'x-mjst': { instanceOf: 'Date; doEvil()' } })).toBeUndefined()
21
- expect(getMjstInstanceOf({ 'x-mjst': { instanceOf: '' } })).toBeUndefined()
22
- })
23
-
24
- it('exposes the extension key', () => {
25
- expect(MJST_EXTENSION_KEY).toBe('x-mjst')
26
- })
27
- })
28
-
29
- describe('getMjstPrimitive', () => {
30
- it('reads a supported primitive', () => {
31
- expect(getMjstPrimitive({ 'x-mjst': { primitive: 'bigint' } })).toBe('bigint')
32
- })
33
-
34
- it('ignores unsupported primitives', () => {
35
- expect(getMjstPrimitive({ 'x-mjst': { primitive: 'symbol' } })).toBeUndefined()
36
- expect(getMjstPrimitive({ 'x-mjst': { primitive: 'evil()' } })).toBeUndefined()
37
- })
38
-
39
- it('returns undefined when the extension is absent', () => {
40
- expect(getMjstPrimitive({ type: 'string' })).toBeUndefined()
41
- })
42
- })
43
-
44
- describe('getMjstBrand', () => {
45
- it('reads a safe brand name', () => {
46
- expect(getMjstBrand({ 'x-mjst': { brand: 'UserId' } })).toBe('UserId')
47
- expect(getMjstBrand({ 'x-mjst': { brand: 'order-id 2' } })).toBe('order-id 2')
48
- })
49
-
50
- it('rejects brand names that could break out of a string literal', () => {
51
- expect(getMjstBrand({ 'x-mjst': { brand: "x'; doEvil()" } })).toBeUndefined()
52
- expect(getMjstBrand({ 'x-mjst': { brand: 'a\\b' } })).toBeUndefined()
53
- expect(getMjstBrand({ 'x-mjst': { brand: '' } })).toBeUndefined()
54
- })
55
-
56
- it('returns undefined when the extension is absent', () => {
57
- expect(getMjstBrand({ type: 'string' })).toBeUndefined()
58
- })
59
- })
@@ -1,81 +0,0 @@
1
- import type { JSONSchema } from 'json-schema-typed/draft-2020-12'
2
-
3
- import { isSchemaObject } from './schema-guards'
4
-
5
- /**
6
- * Vendor extension keyword carrying mjst-specific runtime hints that plain JSON
7
- * Schema cannot express on its own. Adapters (TypeBox, Zod, ...) emit it when a
8
- * source construct has no native JSON Schema equivalent, and the generators read
9
- * it to produce the right TypeScript type and runtime checks.
10
- */
11
- export const MJST_EXTENSION_KEY = 'x-mjst'
12
-
13
- /**
14
- * The shape of the `x-mjst` extension object.
15
- *
16
- * - `instanceOf` names a JavaScript class the value must be an instance of at
17
- * runtime (e.g. `'Date'`). It round-trips constructs like TypeBox's
18
- * `Type.Date()` that JSON Schema's core vocabulary has no keyword for.
19
- * - `primitive` names a non-JSON primitive type (e.g. `'bigint'`) that has no
20
- * JSON Schema representation. Unlike `instanceOf`, the value is checked with
21
- * `typeof`, not `instanceof`.
22
- * - `brand` carries a nominal-typing brand name. It is purely type-level: the
23
- * runtime value still validates as its underlying JSON Schema type, but the
24
- * generated TypeScript type is intersected with a unique brand so values are
25
- * not interchangeable with the unbranded base type.
26
- */
27
- export type MjstExtension = {
28
- readonly instanceOf?: string
29
- readonly primitive?: string
30
- readonly brand?: string
31
- }
32
-
33
- // Only identifier-safe class names are honoured, so a malicious or malformed
34
- // schema cannot inject arbitrary code into the generated output.
35
- const IDENTIFIER = /^[A-Za-z_$][A-Za-z0-9_$]*$/
36
-
37
- // The non-JSON primitives we know how to generate type/runtime handling for.
38
- // Anything outside this set is ignored so unknown hints degrade gracefully.
39
- const SUPPORTED_PRIMITIVES = new Set(['bigint'])
40
-
41
- // Brand names are embedded inside a single-quoted string literal in generated
42
- // output, so we only allow characters that cannot break out of the literal.
43
- const SAFE_BRAND = /^[\w$ -]+$/
44
-
45
- const readExtensionString = (schema: JSONSchema, field: keyof MjstExtension): string | undefined => {
46
- if (!isSchemaObject(schema)) return undefined
47
-
48
- const extension = (schema as Record<string, unknown>)[MJST_EXTENSION_KEY]
49
- if (typeof extension !== 'object' || extension === null) return undefined
50
-
51
- const value = (extension as Record<string, unknown>)[field]
52
- return typeof value === 'string' ? value : undefined
53
- }
54
-
55
- /**
56
- * Reads the `instanceOf` class name from a schema's `x-mjst` extension, when it
57
- * is present and a safe identifier. Returns undefined otherwise so callers fall
58
- * back to ordinary type handling.
59
- */
60
- export const getMjstInstanceOf = (schema: JSONSchema): string | undefined => {
61
- const instanceOf = readExtensionString(schema, 'instanceOf')
62
- return instanceOf !== undefined && IDENTIFIER.test(instanceOf) ? instanceOf : undefined
63
- }
64
-
65
- /**
66
- * Reads the `primitive` type name from a schema's `x-mjst` extension, when it is
67
- * one we support (e.g. `'bigint'`). Returns undefined otherwise.
68
- */
69
- export const getMjstPrimitive = (schema: JSONSchema): string | undefined => {
70
- const primitive = readExtensionString(schema, 'primitive')
71
- return primitive !== undefined && SUPPORTED_PRIMITIVES.has(primitive) ? primitive : undefined
72
- }
73
-
74
- /**
75
- * Reads the nominal `brand` name from a schema's `x-mjst` extension, when it is
76
- * present and safe to embed in generated output. Returns undefined otherwise.
77
- */
78
- export const getMjstBrand = (schema: JSONSchema): string | undefined => {
79
- const brand = readExtensionString(schema, 'brand')
80
- return brand !== undefined && SAFE_BRAND.test(brand) ? brand : undefined
81
- }
@@ -1,313 +0,0 @@
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
- })
@@ -1,173 +0,0 @@
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
- }
@@ -1,64 +0,0 @@
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
- })