@amritk/helpers 0.1.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.
@@ -0,0 +1,528 @@
1
+ // src/schema-guards.ts
2
+ var isSchemaObject = (schema) => {
3
+ return typeof schema === "object" && schema !== null && typeof schema !== "boolean";
4
+ };
5
+ var hasType = (schema) => {
6
+ return isSchemaObject(schema) && "type" in schema && typeof schema.type === "string";
7
+ };
8
+ var isObjectSchema = (schema) => {
9
+ return isSchemaObject(schema) && (("type" in schema) && schema.type === "object" || ("properties" in schema));
10
+ };
11
+ var hasProperties = (schema) => {
12
+ return isSchemaObject(schema) && "properties" in schema && typeof schema.properties === "object" && schema.properties !== null;
13
+ };
14
+ var hasEnum = (schema) => {
15
+ return isSchemaObject(schema) && "enum" in schema && Array.isArray(schema.enum);
16
+ };
17
+ var hasConst = (schema) => {
18
+ return isSchemaObject(schema) && "const" in schema;
19
+ };
20
+ var hasPattern = (schema) => {
21
+ return isSchemaObject(schema) && "pattern" in schema && typeof schema.pattern === "string";
22
+ };
23
+ var hasFormat = (schema) => {
24
+ return isSchemaObject(schema) && "format" in schema && typeof schema.format === "string";
25
+ };
26
+ var hasDefault = (schema) => {
27
+ return isSchemaObject(schema) && "default" in schema;
28
+ };
29
+ var hasExamples = (schema) => {
30
+ return isSchemaObject(schema) && "examples" in schema && Array.isArray(schema.examples);
31
+ };
32
+ var hasOneOf = (schema) => {
33
+ return isSchemaObject(schema) && "oneOf" in schema && Array.isArray(schema.oneOf);
34
+ };
35
+ var hasAnyOf = (schema) => {
36
+ return isSchemaObject(schema) && "anyOf" in schema && Array.isArray(schema.anyOf);
37
+ };
38
+ var hasAllOf = (schema) => {
39
+ return isSchemaObject(schema) && "allOf" in schema && Array.isArray(schema.allOf);
40
+ };
41
+ var hasRequired = (schema) => {
42
+ return isSchemaObject(schema) && "required" in schema && Array.isArray(schema.required);
43
+ };
44
+ var hasItems = (schema) => {
45
+ return isSchemaObject(schema) && "items" in schema && typeof schema.items === "object" && schema.items !== null && typeof schema.items !== "boolean";
46
+ };
47
+ var hasAdditionalProperties = (schema) => {
48
+ return isSchemaObject(schema) && "additionalProperties" in schema;
49
+ };
50
+ var hasMinLength = (schema) => {
51
+ return isSchemaObject(schema) && "minLength" in schema && typeof schema.minLength === "number";
52
+ };
53
+ var hasMaxLength = (schema) => {
54
+ return isSchemaObject(schema) && "maxLength" in schema && typeof schema.maxLength === "number";
55
+ };
56
+ var hasMinimum = (schema) => {
57
+ return isSchemaObject(schema) && "minimum" in schema && typeof schema.minimum === "number";
58
+ };
59
+ var hasMaximum = (schema) => {
60
+ return isSchemaObject(schema) && "maximum" in schema && typeof schema.maximum === "number";
61
+ };
62
+ var hasExclusiveMinimum = (schema) => {
63
+ return isSchemaObject(schema) && "exclusiveMinimum" in schema && typeof schema.exclusiveMinimum === "number";
64
+ };
65
+ var hasExclusiveMaximum = (schema) => {
66
+ return isSchemaObject(schema) && "exclusiveMaximum" in schema && typeof schema.exclusiveMaximum === "number";
67
+ };
68
+ var hasMultipleOf = (schema) => {
69
+ return isSchemaObject(schema) && "multipleOf" in schema && typeof schema.multipleOf === "number";
70
+ };
71
+ var hasMinItems = (schema) => {
72
+ return isSchemaObject(schema) && "minItems" in schema && typeof schema.minItems === "number";
73
+ };
74
+ var hasMaxItems = (schema) => {
75
+ return isSchemaObject(schema) && "maxItems" in schema && typeof schema.maxItems === "number";
76
+ };
77
+ var hasUniqueItems = (schema) => {
78
+ return isSchemaObject(schema) && "uniqueItems" in schema && typeof schema.uniqueItems === "boolean";
79
+ };
80
+ var hasMinProperties = (schema) => {
81
+ return isSchemaObject(schema) && "minProperties" in schema && typeof schema.minProperties === "number";
82
+ };
83
+ var hasMaxProperties = (schema) => {
84
+ return isSchemaObject(schema) && "maxProperties" in schema && typeof schema.maxProperties === "number";
85
+ };
86
+ var hasRef = (schema) => {
87
+ return isSchemaObject(schema) && "$ref" in schema && typeof schema.$ref === "string";
88
+ };
89
+
90
+ // src/ref-to-filename.ts
91
+ var toKebabCase = (value) => value.replace(/OAuth/g, "Oauth").replace(/([A-Z]+)([A-Z][a-z])/g, "$1-$2").replace(/([a-z\d])([A-Z])/g, "$1-$2").toLowerCase();
92
+ var uriRefToFilename = (uri) => {
93
+ const hashIndex = uri.indexOf("#");
94
+ const baseUri = hashIndex === -1 ? uri : uri.slice(0, hashIndex);
95
+ const fragment = hashIndex === -1 ? "" : uri.slice(hashIndex + 1);
96
+ const withoutProtocol = baseUri.replace(/^https?:\/\/[^/]+\//, "");
97
+ const withoutExt = withoutProtocol.replace(/\.json$/, "");
98
+ const rawSegments = withoutExt.split("/");
99
+ const SKIP_KEYS = new Set(["definitions", "$defs"]);
100
+ const segments = [];
101
+ for (let i = 0;i < rawSegments.length; i++) {
102
+ const s = rawSegments[i];
103
+ if (SKIP_KEYS.has(s))
104
+ continue;
105
+ const prevRaw = rawSegments[i - 1];
106
+ if (/^\d+\.\d+/.test(s) && prevRaw !== undefined && SKIP_KEYS.has(prevRaw))
107
+ continue;
108
+ segments.push(s);
109
+ }
110
+ const baseName = segments.map((s) => toKebabCase(s).replace(/\./g, "-")).join("-");
111
+ if (!fragment)
112
+ return baseName;
113
+ const fragSegments = fragment.split("/").filter((s) => s && !SKIP_KEYS.has(s) && s !== "properties");
114
+ const fragLast = fragSegments[fragSegments.length - 1];
115
+ if (!fragLast)
116
+ return baseName;
117
+ return `${baseName}-${toKebabCase(fragLast)}`;
118
+ };
119
+ var refToFilename = (ref) => {
120
+ if (ref.startsWith("http://") || ref.startsWith("https://")) {
121
+ return uriRefToFilename(ref);
122
+ }
123
+ const segments = ref.split("/");
124
+ let filename = segments[segments.length - 1];
125
+ if (/[A-Z]/.test(filename)) {
126
+ filename = toKebabCase(filename);
127
+ }
128
+ return filename;
129
+ };
130
+
131
+ // src/ref-to-name.ts
132
+ var kebabToPascal = (kebab) => {
133
+ const words = kebab.split("-");
134
+ let pascalCase = "";
135
+ for (const word of words) {
136
+ pascalCase += word.charAt(0).toUpperCase() + word.slice(1);
137
+ }
138
+ return pascalCase + "Object";
139
+ };
140
+ var refToName = (ref) => kebabToPascal(refToFilename(ref));
141
+
142
+ // src/safe-accessor.ts
143
+ var JS_IDENTIFIER = /^[a-zA-Z_$][a-zA-Z0-9_$]*$/;
144
+ var safeAccessor = (variable, key) => {
145
+ if (JS_IDENTIFIER.test(key)) {
146
+ return `${variable}.${key}`;
147
+ }
148
+ if (variable.endsWith("?")) {
149
+ return `${variable}.['${key}']`;
150
+ }
151
+ return `${variable}['${key}']`;
152
+ };
153
+ var safeKey = (key) => {
154
+ if (JS_IDENTIFIER.test(key)) {
155
+ return key;
156
+ }
157
+ return `'${key}'`;
158
+ };
159
+
160
+ // src/generate-type-definition.ts
161
+ var getConditionalObjectSchema = (schema) => {
162
+ if (!isSchemaObject(schema)) {
163
+ return null;
164
+ }
165
+ if (!("if" in schema) || !("then" in schema)) {
166
+ return null;
167
+ }
168
+ const ifSchema = schema.if;
169
+ const thenSchema = schema.then;
170
+ if (!isSchemaObject(ifSchema) || !isSchemaObject(thenSchema)) {
171
+ return null;
172
+ }
173
+ const ifProperties = ifSchema.properties;
174
+ const thenProperties = thenSchema.properties;
175
+ const hasIfProperties = ifProperties && typeof ifProperties === "object";
176
+ const hasThenProperties = thenProperties && typeof thenProperties === "object";
177
+ if (!hasIfProperties && !hasThenProperties) {
178
+ return null;
179
+ }
180
+ const properties = {
181
+ ...hasIfProperties ? ifProperties : {},
182
+ ...hasThenProperties ? thenProperties : {}
183
+ };
184
+ const required = new Set;
185
+ if (Array.isArray(ifSchema.required)) {
186
+ for (const key of ifSchema.required) {
187
+ required.add(key);
188
+ }
189
+ }
190
+ if (hasIfProperties) {
191
+ for (const key in ifProperties) {
192
+ required.add(key);
193
+ }
194
+ }
195
+ if (Array.isArray(thenSchema.required)) {
196
+ for (const key of thenSchema.required) {
197
+ required.add(key);
198
+ }
199
+ }
200
+ if (hasThenProperties) {
201
+ for (const key in thenProperties) {
202
+ required.add(key);
203
+ }
204
+ }
205
+ const thenRef = typeof thenSchema.$ref === "string" ? thenSchema.$ref : null;
206
+ return {
207
+ schema: {
208
+ type: "object",
209
+ properties,
210
+ ...required.size > 0 ? { required: Array.from(required) } : {}
211
+ },
212
+ thenRef
213
+ };
214
+ };
215
+ var isObjectLikeSchema = (schema) => {
216
+ if (!isSchemaObject(schema)) {
217
+ return false;
218
+ }
219
+ if (isObjectSchema(schema)) {
220
+ return true;
221
+ }
222
+ return "patternProperties" in schema || "additionalProperties" in schema || "if" in schema && "then" in schema;
223
+ };
224
+ var getBooleanSubSchemaType = (schema) => {
225
+ return schema ? "unknown" : "never";
226
+ };
227
+ var buildJsDocBlock = (title, description, commentUrl) => {
228
+ let block = `/**
229
+ `;
230
+ block += `* ${title}
231
+ `;
232
+ block += `*
233
+ `;
234
+ block += `* ${description}
235
+ `;
236
+ if (commentUrl?.startsWith("http")) {
237
+ block += `*
238
+ `;
239
+ block += `* @see {@link ${commentUrl}}
240
+ `;
241
+ }
242
+ block += `*/
243
+ `;
244
+ return block;
245
+ };
246
+ var getTypeScriptType = (schema) => {
247
+ if (typeof schema === "boolean") {
248
+ return getBooleanSubSchemaType(schema);
249
+ }
250
+ if (typeof schema !== "object" || schema === null) {
251
+ return "unknown";
252
+ }
253
+ if (schema.$ref) {
254
+ if (!schema.$ref.startsWith("#")) {
255
+ return "unknown";
256
+ }
257
+ return refToName(schema.$ref);
258
+ }
259
+ if (schema.$dynamicRef) {
260
+ if (schema.$dynamicRef === "#meta") {
261
+ return "Schema";
262
+ }
263
+ return refToName(schema.$dynamicRef);
264
+ }
265
+ if (schema.const !== undefined) {
266
+ return JSON.stringify(schema.const);
267
+ }
268
+ if (schema.enum && schema.enum.length > 0) {
269
+ if (schema.enum.length === 1) {
270
+ return JSON.stringify(schema.enum[0]);
271
+ }
272
+ let enumUnion = JSON.stringify(schema.enum[0]);
273
+ for (let i = 1;i < schema.enum.length; i++) {
274
+ enumUnion += " | " + JSON.stringify(schema.enum[i]);
275
+ }
276
+ return enumUnion;
277
+ }
278
+ if (schema.enum && schema.enum.length > 1) {
279
+ let multiEnumUnion = JSON.stringify(schema.enum[0]);
280
+ for (let i = 1;i < schema.enum.length; i++) {
281
+ multiEnumUnion += " | " + JSON.stringify(schema.enum[i]);
282
+ }
283
+ return multiEnumUnion;
284
+ }
285
+ if (schema.oneOf && Array.isArray(schema.oneOf) && schema.oneOf.length > 0) {
286
+ let oneOfUnion = getTypeScriptType(schema.oneOf[0]);
287
+ for (let i = 1;i < schema.oneOf.length; i++) {
288
+ oneOfUnion += " | " + getTypeScriptType(schema.oneOf[i]);
289
+ }
290
+ return oneOfUnion;
291
+ }
292
+ if (schema.anyOf && Array.isArray(schema.anyOf) && schema.anyOf.length > 0) {
293
+ let anyOfUnion = getTypeScriptType(schema.anyOf[0]);
294
+ for (let i = 1;i < schema.anyOf.length; i++) {
295
+ anyOfUnion += " | " + getTypeScriptType(schema.anyOf[i]);
296
+ }
297
+ return anyOfUnion;
298
+ }
299
+ if (schema.allOf && Array.isArray(schema.allOf) && schema.allOf.length > 0) {
300
+ let intersectionTypes = getTypeScriptType(schema.allOf[0]);
301
+ for (let i = 1;i < schema.allOf.length; i++) {
302
+ intersectionTypes += " & " + getTypeScriptType(schema.allOf[i]);
303
+ }
304
+ return intersectionTypes;
305
+ }
306
+ const conditionalResult = getConditionalObjectSchema(schema);
307
+ if (conditionalResult) {
308
+ const baseType = getTypeScriptType(conditionalResult.schema);
309
+ if (conditionalResult.thenRef) {
310
+ return `(${baseType}) & ${refToName(conditionalResult.thenRef)}`;
311
+ }
312
+ return baseType;
313
+ }
314
+ if (!schema.type) {
315
+ if (schema.additionalProperties !== undefined) {
316
+ if (typeof schema.additionalProperties === "boolean") {
317
+ return `Record<string, ${getBooleanSubSchemaType(schema.additionalProperties)}>`;
318
+ }
319
+ return `Record<string, ${getTypeScriptType(schema.additionalProperties)}>`;
320
+ }
321
+ if (schema.patternProperties && typeof schema.patternProperties === "object") {
322
+ const firstEntry = Object.entries(schema.patternProperties)[0];
323
+ if (firstEntry) {
324
+ const [pattern, value] = firstEntry;
325
+ if (value !== undefined) {
326
+ const valueType = typeof value === "boolean" ? getBooleanSubSchemaType(value) : getTypeScriptType(value);
327
+ if (pattern === "^x-") {
328
+ return `Record<\`x-\${string}\`, ${valueType}>`;
329
+ }
330
+ return `Record<string, ${valueType}>`;
331
+ }
332
+ }
333
+ }
334
+ if (schema.default !== undefined) {
335
+ if (typeof schema.default === "string") {
336
+ return "string";
337
+ }
338
+ if (typeof schema.default === "number") {
339
+ return "number";
340
+ }
341
+ if (typeof schema.default === "boolean") {
342
+ return "boolean";
343
+ }
344
+ }
345
+ return "unknown";
346
+ }
347
+ if (Array.isArray(schema.type)) {
348
+ const mapType = (t) => {
349
+ switch (t) {
350
+ case "string":
351
+ return "string";
352
+ case "number":
353
+ case "integer":
354
+ return "number";
355
+ case "boolean":
356
+ return "boolean";
357
+ case "null":
358
+ return "null";
359
+ case "array":
360
+ return "unknown[]";
361
+ case "object":
362
+ return "Record<string, unknown>";
363
+ default:
364
+ return "unknown";
365
+ }
366
+ };
367
+ let typeUnion = mapType(schema.type[0]);
368
+ for (let i = 1;i < schema.type.length; i++) {
369
+ typeUnion += " | " + mapType(schema.type[i]);
370
+ }
371
+ return typeUnion;
372
+ }
373
+ switch (schema.type) {
374
+ case "string":
375
+ return "string";
376
+ case "number":
377
+ case "integer":
378
+ return "number";
379
+ case "boolean":
380
+ return "boolean";
381
+ case "array":
382
+ if (schema.items) {
383
+ const itemType = getTypeScriptType(schema.items);
384
+ const wrappedItemType = itemType.includes(" | ") ? `(${itemType})` : itemType;
385
+ return `${wrappedItemType}[]`;
386
+ }
387
+ return "unknown[]";
388
+ case "object":
389
+ if (schema.properties) {
390
+ let properties = "";
391
+ let first = true;
392
+ for (const key in schema.properties) {
393
+ const propSchema = schema.properties[key];
394
+ const isRequired = schema.required?.includes(key) ?? false;
395
+ const optional = isRequired ? "" : "?";
396
+ const propType = getTypeScriptType(propSchema);
397
+ if (!first)
398
+ properties += "; ";
399
+ properties += safeKey(key) + optional + ": " + propType;
400
+ first = false;
401
+ }
402
+ return "{ " + properties + " }";
403
+ }
404
+ if (schema.additionalProperties && typeof schema.additionalProperties === "object") {
405
+ const additionalPropType = getTypeScriptType(schema.additionalProperties);
406
+ return `Record<string, ${additionalPropType}>`;
407
+ }
408
+ if (schema.patternProperties && typeof schema.patternProperties === "object") {
409
+ const firstEntry = Object.entries(schema.patternProperties)[0];
410
+ if (firstEntry) {
411
+ const [pattern, patternVal] = firstEntry;
412
+ if (patternVal) {
413
+ const valueType = getTypeScriptType(patternVal);
414
+ if (pattern === "^x-") {
415
+ return `Record<\`x-\${string}\`, ${valueType}>`;
416
+ }
417
+ return `Record<string, ${valueType}>`;
418
+ }
419
+ }
420
+ }
421
+ return "object";
422
+ default:
423
+ return "unknown";
424
+ }
425
+ };
426
+ var generateTypeDefinition = (schema, typeName) => {
427
+ if (!isObjectLikeSchema(schema)) {
428
+ const tsType = getTypeScriptType(schema);
429
+ let result = "";
430
+ if (isSchemaObject(schema) && schema.$comment && typeof schema.$comment === "string") {
431
+ result += buildJsDocBlock(typeName, schema.$comment);
432
+ }
433
+ result += `export type ${typeName} = ${tsType};`;
434
+ return result;
435
+ }
436
+ if (isObjectLikeSchema(schema)) {
437
+ const conditionalResult = getConditionalObjectSchema(schema);
438
+ const normalizedSchema = conditionalResult?.schema ?? schema;
439
+ const conditionalThenRef = conditionalResult?.thenRef ?? null;
440
+ let jsDocTitle;
441
+ let jsDocDescription;
442
+ if (isSchemaObject(schema) && schema.$comment && typeof schema.$comment === "string") {
443
+ jsDocTitle = typeName;
444
+ jsDocDescription = schema.$comment;
445
+ }
446
+ const hasProperties2 = normalizedSchema.properties && Object.keys(normalizedSchema.properties).length > 0;
447
+ const hasAdditionalProperties2 = normalizedSchema.additionalProperties && typeof normalizedSchema.additionalProperties === "object";
448
+ const hasPatternProperties = normalizedSchema.patternProperties && typeof normalizedSchema.patternProperties === "object" && Object.keys(normalizedSchema.patternProperties).length > 0;
449
+ if (!hasProperties2 && hasPatternProperties && normalizedSchema.patternProperties) {
450
+ const firstEntry = Object.entries(normalizedSchema.patternProperties)[0];
451
+ const firstPattern = firstEntry?.[0];
452
+ const firstPatternProperty = firstEntry?.[1];
453
+ if (firstPatternProperty === undefined) {
454
+ return `export type ${typeName} = Record<string, unknown>;`;
455
+ }
456
+ const patternPropType = typeof firstPatternProperty === "boolean" ? getBooleanSubSchemaType(firstPatternProperty) : getTypeScriptType(firstPatternProperty);
457
+ const keyType = firstPattern === "^x-" ? "`x-${string}`" : "string";
458
+ let result2 = "";
459
+ if (jsDocTitle && jsDocDescription) {
460
+ result2 += buildJsDocBlock(jsDocTitle, jsDocDescription);
461
+ }
462
+ result2 += `export type ${typeName} = Record<${keyType}, ${patternPropType}>;`;
463
+ return result2;
464
+ }
465
+ if (!hasProperties2 && hasAdditionalProperties2 && normalizedSchema.additionalProperties) {
466
+ const additionalPropType = getTypeScriptType(normalizedSchema.additionalProperties);
467
+ let result2 = "";
468
+ if (jsDocTitle && jsDocDescription) {
469
+ result2 += buildJsDocBlock(jsDocTitle, jsDocDescription);
470
+ }
471
+ result2 += `export type ${typeName} = {
472
+ [key: string]: ${additionalPropType};
473
+ };`;
474
+ return result2;
475
+ }
476
+ const schemaProps = normalizedSchema.properties ?? {};
477
+ let properties = "";
478
+ let isFirstProp = true;
479
+ for (const key in schemaProps) {
480
+ const propSchema = schemaProps[key];
481
+ const isRequired = normalizedSchema.required?.includes(key) ?? false;
482
+ const optional = isRequired ? "" : "?";
483
+ const propType = getTypeScriptType(propSchema);
484
+ const quotedKey = safeKey(key);
485
+ if (!isFirstProp)
486
+ properties += `
487
+ `;
488
+ isFirstProp = false;
489
+ const inlineDescription = isSchemaObject(propSchema) && typeof propSchema.description === "string" ? propSchema.description : isSchemaObject(propSchema) && typeof propSchema.$comment === "string" ? propSchema.$comment : undefined;
490
+ if (inlineDescription) {
491
+ properties += " /** " + inlineDescription + ` */
492
+ ` + quotedKey + optional + ": " + propType + ";";
493
+ } else {
494
+ properties += " " + quotedKey + optional + ": " + propType + ";";
495
+ }
496
+ }
497
+ const allOfIntersections = [];
498
+ if (isSchemaObject(schema) && Array.isArray(schema.allOf)) {
499
+ for (const entry of schema.allOf) {
500
+ if (isSchemaObject(entry) && entry.$ref) {
501
+ allOfIntersections.push(refToName(entry.$ref));
502
+ }
503
+ }
504
+ }
505
+ if (isSchemaObject(schema) && typeof schema.$ref === "string" && schema.$ref.startsWith("#")) {
506
+ allOfIntersections.push(refToName(schema.$ref));
507
+ }
508
+ let result = "";
509
+ if (jsDocTitle && jsDocDescription) {
510
+ result += buildJsDocBlock(jsDocTitle, jsDocDescription);
511
+ }
512
+ let typeBody = `{
513
+ ` + properties + `
514
+ }`;
515
+ if (conditionalThenRef) {
516
+ typeBody += " & " + refToName(conditionalThenRef);
517
+ }
518
+ for (const intersectionType of allOfIntersections) {
519
+ typeBody += " & " + intersectionType;
520
+ }
521
+ result += "export type " + typeName + " = " + typeBody + ";";
522
+ return result;
523
+ }
524
+ return "export type " + typeName + " = unknown;";
525
+ };
526
+ export {
527
+ generateTypeDefinition
528
+ };
@@ -0,0 +1,14 @@
1
+ /**
2
+ * Returns true if the provided value is a plain object.
3
+ * Optimized for JSON data validation: checks that value is truthy, typeof object,
4
+ * and not an array. This correctly handles all JSON value types.
5
+ *
6
+ * Examples:
7
+ * isObject({}) // true
8
+ * isObject({ a: 1 }) // true
9
+ * isObject([]) // false (Array)
10
+ * isObject(null) // false
11
+ * isObject(123) // false
12
+ * isObject('string') // false
13
+ */
14
+ export declare const isObject: (value: unknown) => value is Record<string, unknown>;
@@ -0,0 +1,5 @@
1
+ // src/is-object.ts
2
+ var isObject = (value) => !!value && typeof value === "object" && !Array.isArray(value);
3
+ export {
4
+ isObject
5
+ };
@@ -0,0 +1,17 @@
1
+ type PropertyDocumentation = {
2
+ description: string;
3
+ isRequired: boolean;
4
+ };
5
+ export type ObjectDocumentation = {
6
+ title: string;
7
+ description: string;
8
+ properties: Record<string, PropertyDocumentation>;
9
+ };
10
+ /**
11
+ * Fetches and parses OpenAPI specification documentation from the markdown source.
12
+ *
13
+ * When a section has no Fixed Fields table (e.g. Header Object delegates to Parameter Object),
14
+ * pass `fallbackCommentUrl` to inherit property documentation from another section.
15
+ */
16
+ export declare const parseDocumentation: (markdownDocumentation: string, commentUrl: string, fallbackCommentUrl?: string) => ObjectDocumentation | null;
17
+ export {};
@@ -0,0 +1,95 @@
1
+ // src/parse-documentation.ts
2
+ var parseDocumentation = (markdownDocumentation, commentUrl, fallbackCommentUrl) => {
3
+ try {
4
+ const markdown = markdownDocumentation;
5
+ const fragmentId = commentUrl.split("#")[1];
6
+ if (!fragmentId) {
7
+ return null;
8
+ }
9
+ const baseUrl = commentUrl.split("#")[0];
10
+ const titleWords = fragmentId.split("-");
11
+ let sectionTitle = "";
12
+ for (let i = 0;i < titleWords.length; i++) {
13
+ if (i > 0)
14
+ sectionTitle += " ";
15
+ const word = titleWords[i] ?? "";
16
+ sectionTitle += word.charAt(0).toUpperCase() + word.slice(1);
17
+ }
18
+ const headingLevelMatch = markdown.match(/^(#{2,5})\s+\S.*Object\s*$/m);
19
+ const headingHashes = headingLevelMatch?.[1] ?? "####";
20
+ const subHeadingHashes = headingHashes + "#";
21
+ const escapedHashes = headingHashes.replace(/#/g, "\\#");
22
+ const sectionRegex = new RegExp(`${escapedHashes}\\s+${sectionTitle}\\s*\\n([\\s\\S]*?)(?=\\n${escapedHashes}\\s|$)`, "i");
23
+ const sectionMatch = markdown.match(sectionRegex);
24
+ if (!sectionMatch) {
25
+ return null;
26
+ }
27
+ const sectionContent = sectionMatch?.[1];
28
+ if (!sectionContent) {
29
+ return null;
30
+ }
31
+ const escapedSubHashes = subHeadingHashes.replace(/#/g, "\\#");
32
+ const descriptionMatch = sectionContent.match(new RegExp(`^([\\s\\S]*?)(?=\\n?${escapedSubHashes}|$)`));
33
+ const description = descriptionMatch?.[1]?.trim().replace(/\n/g, " ") || "";
34
+ const fixedFieldsRegex = new RegExp(`${escapedSubHashes} Fixed Fields\\s*\\n([\\s\\S]*)`);
35
+ const fixedFieldsMatch = sectionContent.match(fixedFieldsRegex);
36
+ const properties = {};
37
+ if (fixedFieldsMatch?.[1]) {
38
+ const fixedFieldsContent = fixedFieldsMatch[1];
39
+ const lines = fixedFieldsContent.split(`
40
+ `);
41
+ let inTable = false;
42
+ for (const line of lines) {
43
+ if (line.includes("Field Name") || line.includes("---|")) {
44
+ inTable = true;
45
+ continue;
46
+ }
47
+ if (line.startsWith("#")) {
48
+ inTable = false;
49
+ continue;
50
+ }
51
+ if (!inTable || !line.trim() || !line.includes("|")) {
52
+ continue;
53
+ }
54
+ const lineWithPlaceholder = line.replace(/\\\|/g, "___PIPE___");
55
+ const cells = lineWithPlaceholder.split("|").map((cell) => cell.replace(/___PIPE___/g, "|").trim()).filter((cell) => cell);
56
+ if (cells.length >= 3) {
57
+ const fieldName = cells[0]?.replace(/<[^>]*>/g, "").trim();
58
+ const descriptionCellIndex = cells.length >= 4 ? 3 : 2;
59
+ let fieldDescription = cells[descriptionCellIndex]?.trim() || "";
60
+ const isRequired = fieldDescription.includes("REQUIRED");
61
+ fieldDescription = fieldDescription.replace(/\(#([^)]+)\)/g, `(${baseUrl}#$1)`);
62
+ const isValidFieldName = fieldName && !fieldName.includes("Field Name") && !fieldName.startsWith("`") && !fieldName.startsWith("[") && /^[a-zA-Z]/.test(fieldName);
63
+ if (isValidFieldName) {
64
+ properties[fieldName] = {
65
+ description: fieldDescription,
66
+ isRequired
67
+ };
68
+ }
69
+ }
70
+ }
71
+ }
72
+ const title = sectionTitle.replace(/\sObject$/, " object");
73
+ if (Object.keys(properties).length === 0 && fallbackCommentUrl) {
74
+ const fallback = parseDocumentation(markdownDocumentation, fallbackCommentUrl);
75
+ if (fallback && Object.keys(fallback.properties).length > 0) {
76
+ return {
77
+ title,
78
+ description,
79
+ properties: fallback.properties
80
+ };
81
+ }
82
+ }
83
+ return {
84
+ title,
85
+ description,
86
+ properties
87
+ };
88
+ } catch (error) {
89
+ console.error("Failed to fetch OpenAPI documentation:", error);
90
+ return null;
91
+ }
92
+ };
93
+ export {
94
+ parseDocumentation
95
+ };