@danylohotvianskyi/bobra-framework 0.1.9 → 0.2.1

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 (102) hide show
  1. package/batteries/auth/hash.ts +102 -36
  2. package/batteries/auth/token-metadata.ts +25 -8
  3. package/batteries/auth/token.ts +5 -5
  4. package/batteries/openapi/index.ts +62 -41
  5. package/batteries/openapi/merge-openapi.ts +125 -33
  6. package/core/config.ts +40 -14
  7. package/core/discovery.ts +16 -10
  8. package/core/env-resolver.ts +25 -11
  9. package/core/factory.ts +150 -77
  10. package/core/spa.ts +14 -8
  11. package/db/client.ts +80 -415
  12. package/db/drizzle-clients.ts +65 -0
  13. package/db/failover.ts +318 -0
  14. package/db/index.ts +1 -0
  15. package/db/migrate.ts +7 -6
  16. package/db/pgedge.ts +307 -0
  17. package/db/test/client.test.ts +346 -0
  18. package/db/token-auth.ts +40 -0
  19. package/db/types.ts +96 -0
  20. package/dist/batteries/auth/hash.d.ts +10 -2
  21. package/dist/batteries/auth/hash.js +78 -43
  22. package/dist/batteries/auth/hash.js.map +1 -1
  23. package/dist/batteries/auth/token-metadata.d.ts +3 -3
  24. package/dist/batteries/auth/token-metadata.js +14 -6
  25. package/dist/batteries/auth/token-metadata.js.map +1 -1
  26. package/dist/batteries/auth/token.d.ts +3 -3
  27. package/dist/batteries/auth/token.js +2 -2
  28. package/dist/batteries/auth/token.js.map +1 -1
  29. package/dist/batteries/openapi/index.d.ts +51 -13
  30. package/dist/batteries/openapi/index.js +25 -15
  31. package/dist/batteries/openapi/index.js.map +1 -1
  32. package/dist/batteries/openapi/merge-openapi.d.ts +26 -2
  33. package/dist/batteries/openapi/merge-openapi.js +83 -26
  34. package/dist/batteries/openapi/merge-openapi.js.map +1 -1
  35. package/dist/core/config.d.ts +26 -9
  36. package/dist/core/config.js +8 -7
  37. package/dist/core/config.js.map +1 -1
  38. package/dist/core/discovery.d.ts +18 -9
  39. package/dist/core/discovery.js +1 -1
  40. package/dist/core/discovery.js.map +1 -1
  41. package/dist/core/env-resolver.d.ts +7 -4
  42. package/dist/core/env-resolver.js +7 -5
  43. package/dist/core/env-resolver.js.map +1 -1
  44. package/dist/core/factory.d.ts +36 -16
  45. package/dist/core/factory.js +70 -38
  46. package/dist/core/factory.js.map +1 -1
  47. package/dist/core/spa.js +9 -4
  48. package/dist/core/spa.js.map +1 -1
  49. package/dist/db/client.d.ts +16 -66
  50. package/dist/db/client.js +40 -311
  51. package/dist/db/client.js.map +1 -1
  52. package/dist/db/drizzle-clients.d.ts +6 -0
  53. package/dist/db/drizzle-clients.js +42 -0
  54. package/dist/db/drizzle-clients.js.map +1 -0
  55. package/dist/db/failover.d.ts +39 -0
  56. package/dist/db/failover.js +267 -0
  57. package/dist/db/failover.js.map +1 -0
  58. package/dist/db/index.d.ts +1 -0
  59. package/dist/db/index.js +1 -0
  60. package/dist/db/index.js.map +1 -1
  61. package/dist/db/migrate.js +4 -4
  62. package/dist/db/migrate.js.map +1 -1
  63. package/dist/db/pgedge.d.ts +14 -0
  64. package/dist/db/pgedge.js +218 -0
  65. package/dist/db/pgedge.js.map +1 -0
  66. package/dist/db/token-auth.d.ts +34 -0
  67. package/dist/db/token-auth.js +15 -0
  68. package/dist/db/token-auth.js.map +1 -0
  69. package/dist/db/types.d.ts +82 -0
  70. package/dist/db/types.js +2 -0
  71. package/dist/db/types.js.map +1 -0
  72. package/dist/logging/logger.d.ts +13 -13
  73. package/dist/logging/logger.js +11 -2
  74. package/dist/logging/logger.js.map +1 -1
  75. package/dist/logging/logging-middleware.d.ts +1 -1
  76. package/dist/logging/logging-middleware.js +6 -6
  77. package/dist/logging/logging-middleware.js.map +1 -1
  78. package/dist/middleware/ensure-api-token.d.ts +33 -4
  79. package/dist/middleware/ensure-api-token.js.map +1 -1
  80. package/dist/middleware/utils.d.ts +5 -1
  81. package/dist/middleware/utils.js +11 -7
  82. package/dist/middleware/utils.js.map +1 -1
  83. package/dist/network/router.d.ts +9 -6
  84. package/dist/network/router.js +3 -1
  85. package/dist/network/router.js.map +1 -1
  86. package/dist/network/service-discovery.d.ts +1 -1
  87. package/dist/network/service-discovery.js.map +1 -1
  88. package/dist/network/service-fetch.d.ts +6 -9
  89. package/dist/network/service-fetch.js +14 -4
  90. package/dist/network/service-fetch.js.map +1 -1
  91. package/dist/node/generate-wrangler-config.d.ts +28 -4
  92. package/dist/node/generate-wrangler-config.js +75 -20
  93. package/dist/node/generate-wrangler-config.js.map +1 -1
  94. package/logging/logger.ts +31 -21
  95. package/logging/logging-middleware.ts +12 -9
  96. package/middleware/ensure-api-token.ts +8 -6
  97. package/middleware/utils.ts +26 -8
  98. package/network/router.ts +17 -13
  99. package/network/service-discovery.ts +1 -1
  100. package/network/service-fetch.ts +26 -17
  101. package/node/generate-wrangler-config.ts +160 -24
  102. package/package.json +10 -7
@@ -1,5 +1,28 @@
1
1
  import { getLogger } from '../../logging/logger';
2
- import { isSQLite, type DatabaseContext } from '../../db/client';
2
+ import {
3
+ isSQLiteContext,
4
+ isPostgresContext,
5
+ type DatabaseContext,
6
+ type DrizzleSchema,
7
+ type TokenSchemaBindings,
8
+ type TokenRecordInput,
9
+ type TokenRecordRaw,
10
+ type DateLike,
11
+ type IpAddressesLike,
12
+ tokenRecordRawSchema,
13
+ ipAddressListSchema,
14
+ } from '../../db';
15
+ import * as v from 'valibot';
16
+
17
+ export function parseTokenRecord(input: TokenRecordInput): TokenRecordRaw | undefined {
18
+ const parsed = v.safeParse(tokenRecordRawSchema, input);
19
+ return parsed.success ? parsed.output : undefined;
20
+ }
21
+
22
+ export function parseIpAddressList(input: string[]): string[] | undefined {
23
+ const parsed = v.safeParse(ipAddressListSchema, input);
24
+ return parsed.success ? parsed.output : undefined;
25
+ }
3
26
 
4
27
  // Token hash algorithm configuration
5
28
  const HASH_CONFIG = {
@@ -16,50 +39,93 @@ export async function hashToken(token: string, salt: string): Promise<string> {
16
39
  return hashArray.map(b => b.toString(16).padStart(2, '0')).join('');
17
40
  }
18
41
 
42
+ export type MatchedTokenRecord = Omit<TokenRecordRaw, 'createdAt' | 'expiresAt' | 'lastUsedAt' | 'ipAddresses'> & {
43
+ createdAt: Date;
44
+ expiresAt: Date;
45
+ lastUsedAt?: Date;
46
+ ipAddresses?: string[];
47
+ };
48
+
49
+ function normalizeDate(value: DateLike | null | undefined): Date | undefined {
50
+ if (!value) return undefined;
51
+ if (value instanceof Date) return value;
52
+ if (typeof value === 'number') return new Date(value);
53
+ if (typeof value === 'string') return new Date(value);
54
+ return undefined;
55
+ }
56
+
57
+ function parseIps(value: IpAddressesLike | undefined): string[] | undefined {
58
+ if (!value) return undefined;
59
+ if (Array.isArray(value)) return value;
60
+
61
+ if (typeof value === 'string') {
62
+ try {
63
+ const parsed = JSON.parse(value);
64
+ return parseIpAddressList(parsed);
65
+ } catch {
66
+ return undefined;
67
+ }
68
+ }
69
+ return undefined;
70
+ }
71
+
19
72
  // Find a token record by computing hash against all stored records
20
73
  export async function findTokenByHash(
21
- ctx: DatabaseContext<any>,
74
+ ctx: DatabaseContext<DrizzleSchema>,
22
75
  token: string,
23
- schema: any,
24
- ) {
76
+ schema: TokenSchemaBindings,
77
+ ): Promise<MatchedTokenRecord | null> {
25
78
  try {
26
- const t = isSQLite(ctx) ? schema.tokensSqlite : schema.tokens;
27
- const tokenRecords = await (ctx.db as any).select({
28
- uid: (t as any).uid,
29
- tokenHash: t.tokenHash,
30
- tokenSalt: t.tokenSalt,
31
- expiresAt: t.expiresAt,
32
- createdAt: t.createdAt,
33
- lastUsedAt: t.lastUsedAt,
34
- ipAddresses: t.ipAddresses,
35
- initToken: t.initToken
36
- }).from(t);
37
-
38
- for (const record of tokenRecords) {
79
+ let tokenRecords: TokenRecordInput[];
80
+
81
+ if (isSQLiteContext(ctx)) {
82
+ tokenRecords = await ctx.db.select({
83
+ uid: schema.tokensSqlite.uid,
84
+ tokenHash: schema.tokensSqlite.tokenHash,
85
+ tokenSalt: schema.tokensSqlite.tokenSalt,
86
+ expiresAt: schema.tokensSqlite.expiresAt,
87
+ createdAt: schema.tokensSqlite.createdAt,
88
+ lastUsedAt: schema.tokensSqlite.lastUsedAt,
89
+ initToken: schema.tokensSqlite.initToken
90
+ }).from(schema.tokensSqlite) as TokenRecordInput[];
91
+ } else if (isPostgresContext(ctx)) {
92
+ tokenRecords = await ctx.db.select({
93
+ uid: schema.tokens.uid,
94
+ tokenHash: schema.tokens.tokenHash,
95
+ tokenSalt: schema.tokens.tokenSalt,
96
+ expiresAt: schema.tokens.expiresAt,
97
+ createdAt: schema.tokens.createdAt,
98
+ lastUsedAt: schema.tokens.lastUsedAt,
99
+ initToken: schema.tokens.initToken
100
+ }).from(schema.tokens) as TokenRecordInput[];
101
+ } else {
102
+ throw new Error('Unsupported database context type');
103
+ }
104
+
105
+ for (const rawRecord of tokenRecords) {
39
106
  try {
107
+ const record = parseTokenRecord(rawRecord);
108
+ if (!record) {
109
+ continue;
110
+ }
111
+
112
+ if (typeof record.tokenSalt !== 'string' || typeof record.tokenHash !== 'string') {
113
+ continue;
114
+ }
115
+
40
116
  const computedHash = await hashToken(token, record.tokenSalt);
41
117
  if (computedHash === record.tokenHash) {
42
- // Normalize date fields across engines
43
- const normalizeDate = (d: any) => {
44
- if (!d) return undefined;
45
- if (d instanceof Date) return d;
46
- if (typeof d === 'number') return new Date(d);
47
- if (typeof d === 'string') return new Date(d);
48
- return undefined;
49
- };
50
- // Parse ipAddresses if stored as text (sqlite)
51
- const parseIps = (ips: any) => {
52
- if (!ips) return undefined;
53
- if (Array.isArray(ips)) return ips;
54
- if (typeof ips === 'string') {
55
- try { return JSON.parse(ips); } catch { return undefined; }
56
- }
57
- return undefined;
58
- };
118
+ const createdAt = normalizeDate(record.createdAt);
119
+ const expiresAt = normalizeDate(record.expiresAt);
120
+
121
+ if (!createdAt || !expiresAt) {
122
+ continue;
123
+ }
124
+
59
125
  return {
60
126
  ...record,
61
- createdAt: normalizeDate(record.createdAt)!,
62
- expiresAt: normalizeDate(record.expiresAt)!,
127
+ createdAt,
128
+ expiresAt,
63
129
  lastUsedAt: normalizeDate(record.lastUsedAt),
64
130
  ipAddresses: parseIps(record.ipAddresses)
65
131
  };
@@ -1,10 +1,17 @@
1
1
  import { eq } from 'drizzle-orm';
2
- import { isSQLite, type DatabaseContext } from '../../db/client';
2
+ import {
3
+ isSQLiteContext,
4
+ isPostgresContext,
5
+ type DatabaseContext,
6
+ type DrizzleSchema,
7
+ type TokenSchemaBindings
8
+ } from '../../db/client';
9
+
3
10
 
4
11
  // Database client interface for token metadata update
5
12
  export interface TokenMetadataUpdateClient {
6
- ctx: DatabaseContext<any>;
7
- schema: any;
13
+ ctx: DatabaseContext<DrizzleSchema>;
14
+ schema: TokenSchemaBindings;
8
15
  }
9
16
 
10
17
  // Update the lastUsedAt timestamp for a token
@@ -12,9 +19,19 @@ export async function updateTokenLastUsed(
12
19
  client: TokenMetadataUpdateClient,
13
20
  tokenUid: string
14
21
  ): Promise<void> {
15
- const useSqlite = isSQLite(client.ctx);
16
- const table = useSqlite ? client.schema.tokensSqlite : client.schema.tokens;
17
- await (client.ctx.db as any).update(table)
18
- .set({ lastUsedAt: useSqlite ? new Date().toISOString() : new Date() })
19
- .where(eq((table as any).uid, tokenUid));
22
+ if (isSQLiteContext(client.ctx)) {
23
+ await client.ctx.db.update(client.schema.tokensSqlite)
24
+ .set({ lastUsedAt: new Date().toISOString() })
25
+ .where(eq(client.schema.tokensSqlite.uid, tokenUid));
26
+ return;
27
+ }
28
+
29
+ if (isPostgresContext(client.ctx)) {
30
+ await client.ctx.db.update(client.schema.tokens)
31
+ .set({ lastUsedAt: new Date() })
32
+ .where(eq(client.schema.tokens.uid, tokenUid));
33
+ return;
34
+ }
35
+
36
+ throw new Error('Unsupported database context type');
20
37
  }
@@ -36,9 +36,9 @@ export async function createPublicApiToken(options: PublicApiTokenOptions): Prom
36
36
  tokenHash: string;
37
37
  tokenSalt: string;
38
38
  ipAddresses?: string[];
39
- createdAt: number;
40
- lastUsedAt: number | null;
41
- expiresAt: number;
39
+ createdAt: string;
40
+ lastUsedAt: string | null;
41
+ expiresAt: string;
42
42
  initToken: boolean;
43
43
  };
44
44
  }> {
@@ -63,9 +63,9 @@ export async function createPublicApiToken(options: PublicApiTokenOptions): Prom
63
63
  tokenHash,
64
64
  tokenSalt,
65
65
  ipAddresses,
66
- createdAt: now,
66
+ createdAt: new Date(now).toISOString(),
67
67
  lastUsedAt: null,
68
- expiresAt: finalExpiresAt,
68
+ expiresAt: new Date(finalExpiresAt).toISOString(),
69
69
  initToken
70
70
  };
71
71
 
@@ -1,6 +1,25 @@
1
1
  import * as v from 'valibot';
2
2
  import { toJsonSchema } from '@valibot/to-json-schema';
3
- export { mergeOpenApiSpecs } from './merge-openapi';
3
+ import type { OpenAPIV3 } from 'openapi-types';
4
+ export * from './merge-openapi';
5
+
6
+ type JsonSchemaObject = {
7
+ [key: string]: unknown;
8
+ type?: string;
9
+ properties?: Record<string, unknown>;
10
+ required?: string[];
11
+ allOf?: unknown[];
12
+ anyOf?: unknown[];
13
+ items?: unknown;
14
+ enum?: unknown[];
15
+ const?: unknown;
16
+ additionalProperties?: boolean;
17
+ example?: unknown;
18
+ };
19
+
20
+ function isRecord(value: unknown): value is Record<string, unknown> {
21
+ return typeof value === 'object' && value !== null;
22
+ }
4
23
 
5
24
  /**
6
25
  * Generate schema reference for OpenAPI
@@ -15,16 +34,16 @@ export function generateSchemaRef(schemaName: string): { $ref: string } {
15
34
  */
16
35
  export function generateListResponseSchema(itemSchemaName: string) {
17
36
  return {
18
- type: 'object',
37
+ type: 'object' as const,
19
38
  properties: {
20
- success: { type: 'boolean' },
39
+ success: { type: 'boolean' as const },
21
40
  data: {
22
- type: 'array',
41
+ type: 'array' as const,
23
42
  items: generateSchemaRef(itemSchemaName)
24
43
  },
25
- count: { type: 'number' }
44
+ count: { type: 'number' as const }
26
45
  }
27
- } as any;
46
+ };
28
47
  }
29
48
 
30
49
  /**
@@ -33,33 +52,33 @@ export function generateListResponseSchema(itemSchemaName: string) {
33
52
  */
34
53
  export function generateResponseSchema(itemSchemaName: string) {
35
54
  return {
36
- type: 'object',
55
+ type: 'object' as const,
37
56
  properties: {
38
- success: { type: 'boolean' },
57
+ success: { type: 'boolean' as const },
39
58
  data: generateSchemaRef(itemSchemaName)
40
59
  }
41
- } as any;
60
+ };
42
61
  }
43
62
 
44
63
  /**
45
64
  * Standard error response JSON Schema (plain JSON Schema, not Valibot).
46
65
  * Useful directly inside describeRoute responses.
47
66
  */
48
- export const errorResponseJsonSchema: any = {
49
- type: 'object',
67
+ export const errorResponseJsonSchema = {
68
+ type: 'object' as const,
50
69
  properties: {
51
- success: { type: 'boolean', example: false },
52
- error: { type: 'string', example: 'Details about the error' },
53
- details: { type: 'object', additionalProperties: true, example: {} },
70
+ success: { type: 'boolean' as const, example: false },
71
+ error: { type: 'string' as const, example: 'Details about the error' },
72
+ details: { type: 'object' as const, additionalProperties: true, example: {} },
54
73
  },
55
- };
74
+ } satisfies OpenAPIV3.SchemaObject;
56
75
 
57
76
  /**
58
77
  * Schema that transforms Date | string | null to string | undefined.
59
78
  * Handles database Date objects and converts them to ISO string format.
60
79
  */
61
80
  export const dateToStringSchema = v.pipe(
62
- v.any(),
81
+ v.unknown(),
63
82
  v.transform((input) => {
64
83
  if (!input) return undefined;
65
84
  if (typeof input === 'string') return input;
@@ -81,7 +100,7 @@ export const simpleSuccessResponseSchema = v.object({
81
100
  export const errorResponseSchema = v.object({
82
101
  success: v.literal(false),
83
102
  error: v.pipe(v.string(), v.description('Error message')),
84
- details: v.optional(v.record(v.string(), v.any())),
103
+ details: v.optional(v.record(v.string(), v.unknown())),
85
104
  });
86
105
 
87
106
  /**
@@ -89,48 +108,50 @@ export const errorResponseSchema = v.object({
89
108
  * Uses @valibot/to-json-schema to automatically extract properties.
90
109
  * Supports both ObjectSchema and IntersectSchema (from v.intersect).
91
110
  */
92
- export function valibotSchemaToOpenAPIParameters(schema: v.GenericSchema<any>): Array<{
93
- name: string;
94
- in: 'query';
95
- schema: any;
96
- required?: boolean;
97
- description?: string;
98
- }> {
99
- const jsonSchema = toJsonSchema(schema);
111
+ export function valibotSchemaToOpenAPIParameters(schema: v.GenericSchema<unknown>): OpenAPIV3.ParameterObject[] {
112
+ const jsonSchema = toJsonSchema(schema) as unknown;
100
113
 
101
114
  // Handle allOf (from v.intersect) — merge properties from all schemas
102
- let properties: Record<string, any> = {};
115
+ let properties: Record<string, unknown> = {};
103
116
  let required: string[] = [];
104
117
 
105
- if (jsonSchema.allOf && Array.isArray(jsonSchema.allOf)) {
118
+ if (isRecord(jsonSchema) && Array.isArray(jsonSchema.allOf)) {
106
119
  for (const subSchema of jsonSchema.allOf) {
107
- if (typeof subSchema === 'object' && subSchema !== null && !('const' in subSchema) && !('enum' in subSchema)) {
108
- if ('properties' in subSchema && typeof subSchema.properties === 'object' && subSchema.properties !== null) {
120
+ if (isRecord(subSchema) && !('const' in subSchema) && !('enum' in subSchema)) {
121
+ if (isRecord(subSchema.properties)) {
109
122
  properties = { ...properties, ...subSchema.properties };
110
123
  }
111
- if ('required' in subSchema && Array.isArray(subSchema.required)) {
112
- required = [...required, ...subSchema.required];
124
+ if (Array.isArray(subSchema.required)) {
125
+ required = [
126
+ ...required,
127
+ ...subSchema.required.filter((entry): entry is string => typeof entry === 'string')
128
+ ];
113
129
  }
114
130
  }
115
131
  }
116
132
  } else {
117
- if (typeof jsonSchema === 'object' && jsonSchema !== null && 'properties' in jsonSchema && typeof jsonSchema.properties === 'object' && jsonSchema.properties !== null) {
118
- properties = jsonSchema.properties || {};
133
+ if (isRecord(jsonSchema) && isRecord(jsonSchema.properties)) {
134
+ properties = jsonSchema.properties;
119
135
  }
120
- if (typeof jsonSchema === 'object' && jsonSchema !== null && 'required' in jsonSchema && Array.isArray(jsonSchema.required)) {
121
- required = jsonSchema.required || [];
136
+ if (isRecord(jsonSchema) && Array.isArray(jsonSchema.required)) {
137
+ required = jsonSchema.required.filter((entry): entry is string => typeof entry === 'string');
122
138
  }
123
139
  }
124
140
 
125
- return Object.entries(properties).map(([name, prop]: [string, any]) => {
141
+ return Object.entries(properties).map(([name, prop]) => {
126
142
  // Convert anyOf with all const values to enum for better OpenAPI compatibility
127
- let paramSchema = prop;
128
- if (prop.anyOf && Array.isArray(prop.anyOf)) {
143
+ let paramSchema = prop as OpenAPIV3.SchemaObject | OpenAPIV3.ReferenceObject;
144
+ if (isRecord(prop) && Array.isArray(prop.anyOf)) {
129
145
  const constValues = prop.anyOf
130
- .filter((item: any) => item.const !== undefined)
131
- .map((item: any) => item.const);
146
+ .filter(isRecord)
147
+ .filter((item) => Object.prototype.hasOwnProperty.call(item, 'const'))
148
+ .map((item) => item.const);
149
+
132
150
  if (constValues.length === prop.anyOf.length && constValues.length > 0) {
133
- paramSchema = { type: 'string', enum: constValues };
151
+ paramSchema = {
152
+ type: 'string',
153
+ enum: constValues as (string | number | boolean | null)[]
154
+ };
134
155
  }
135
156
  }
136
157
 
@@ -1,32 +1,70 @@
1
- export function mergeOpenApiSpecs(specs: any[], baseInfo?: { title?: string; description?: string; version?: string; }): any {
1
+ type OpenApiTag = {
2
+ name: string;
3
+ description?: string;
4
+ [key: string]: unknown;
5
+ };
6
+
7
+ type OpenApiDoc = {
8
+ openapi: string;
9
+ info: {
10
+ title: string;
11
+ version: string;
12
+ description: string;
13
+ };
14
+ servers: unknown[];
15
+ tags: OpenApiTag[];
16
+ paths: Record<string, Record<string, unknown>>;
17
+ components: {
18
+ schemas: Record<string, unknown>;
19
+ securitySchemes: Record<string, unknown>;
20
+ };
21
+ security?: Array<Record<string, unknown[]>>;
22
+ };
23
+
24
+ function isRecord(value: unknown): value is Record<string, unknown> {
25
+ return typeof value === 'object' && value !== null;
26
+ }
27
+
28
+ function toStringArray(value: unknown): string[] {
29
+ return Array.isArray(value) ? value.filter((item): item is string => typeof item === 'string') : [];
30
+ }
31
+
32
+ export function mergeOpenApiSpecs(specs: unknown[], baseInfo?: { title?: string; description?: string; version?: string; }): OpenApiDoc {
2
33
  const baseInfoDefaults = {
3
34
  title: 'API',
4
35
  description: 'API documentation',
5
36
  version: '1.0.0',
6
37
  };
7
- const { title = baseInfoDefaults.title, description = baseInfoDefaults.description, version = baseInfoDefaults.version } = baseInfo || {};
8
- const base = {
38
+ const { title = baseInfoDefaults.title, description = baseInfoDefaults.description, version = baseInfoDefaults.version } = baseInfo || {};
39
+
40
+ const base: OpenApiDoc = {
9
41
  openapi: '3.0.0',
10
42
  info: { title, version, description },
11
43
  servers: [],
12
- tags: [] as any[],
13
- paths: {} as Record<string, any>,
14
- components: { schemas: {}, securitySchemes: {} } as any,
44
+ tags: [],
45
+ paths: {},
46
+ components: { schemas: {}, securitySchemes: {} },
15
47
  };
16
48
 
17
- const tagSet = new Map<string, any>();
49
+ const tagSet = new Map<string, OpenApiTag>();
18
50
  const schemaSet = new Set<string>();
19
51
 
20
52
  for (const spec of specs) {
21
- if (!spec || typeof spec !== 'object') continue;
53
+ if (!isRecord(spec)) continue;
22
54
 
23
- // Merge existing tags (if any)
24
- for (const tag of spec.tags || []) {
25
- if (tag && tag.name && !tagSet.has(tag.name)) tagSet.set(tag.name, tag);
55
+ // Merge existing tags (if present)
56
+ const specTags = Array.isArray(spec.tags) ? spec.tags : [];
57
+ for (const tag of specTags) {
58
+ if (!isRecord(tag) || typeof tag.name !== 'string') continue;
59
+ if (!tagSet.has(tag.name)) {
60
+ tagSet.set(tag.name, tag as OpenApiTag);
61
+ }
26
62
  }
27
63
 
28
64
  // Extract handler name from spec title (format: "1stLine by Burava API - handler-name")
29
- const handlerName = spec.info?.title?.split(' - ')[1] || 'Unknown';
65
+ const info = isRecord(spec.info) ? spec.info : {};
66
+ const specTitle = typeof info.title === 'string' ? info.title : '';
67
+ const handlerName = specTitle.split(' - ')[1] || 'Unknown';
30
68
  const handlerTag = handlerName.charAt(0).toUpperCase() + handlerName.slice(1);
31
69
 
32
70
  // Create handler tag if it doesn't exist
@@ -38,34 +76,42 @@ const base = {
38
76
  }
39
77
 
40
78
  // Merge paths with handler-specific tags
41
- for (const [path, ops] of Object.entries(spec.paths || {})) {
42
- if (!base.paths[path]) base.paths[path] = {};
79
+ const specPaths = isRecord(spec.paths) ? spec.paths : {};
80
+ for (const [path, ops] of Object.entries(specPaths)) {
81
+ const existingOps = base.paths[path] || {};
82
+ const incomingOps = isRecord(ops) ? ops : {};
83
+ const normalizedOps: Record<string, unknown> = {};
43
84
 
44
85
  // Apply handler tag to all operations in this path
45
- for (const [method, operation] of Object.entries(ops as any)) {
46
- if (operation && typeof operation === 'object') {
47
- const op = operation as any;
48
- if (!op.tags) op.tags = [];
49
- if (!op.tags.includes(handlerTag)) {
50
- op.tags.push(handlerTag);
51
- }
86
+ for (const [method, operation] of Object.entries(incomingOps)) {
87
+ if (isRecord(operation)) {
88
+ const tags = toStringArray(operation.tags);
89
+ const nextTags = tags.includes(handlerTag) ? tags : [...tags, handlerTag];
90
+ normalizedOps[method] = {
91
+ ...operation,
92
+ tags: nextTags,
93
+ };
94
+ } else {
95
+ normalizedOps[method] = operation;
52
96
  }
53
97
  }
54
98
 
55
- Object.assign(base.paths[path], ops);
99
+ base.paths[path] = { ...existingOps, ...normalizedOps };
56
100
  }
57
101
 
58
102
  // Merge components with conflict resolution
59
- if (spec.components) {
60
- if (spec.components.schemas) {
61
- for (const [schemaName, schema] of Object.entries(spec.components.schemas)) {
103
+ const components = isRecord(spec.components) ? spec.components : null;
104
+ if (components) {
105
+ const schemas = isRecord(components.schemas) ? components.schemas : null;
106
+ if (schemas) {
107
+ for (const [schemaName, schema] of Object.entries(schemas)) {
62
108
  // If the conflicting schema is SimpleSuccessResponse or ErrorResponse, leave only 1 (do not prefix)
63
109
  if (schemaName === 'SimpleSuccessResponse' || schemaName === 'ErrorResponse' || schemaName === 'IncomingAlertRequest') {
64
110
  if (!schemaSet.has(schemaName)) {
65
111
  base.components.schemas[schemaName] = schema;
66
112
  schemaSet.add(schemaName);
67
113
  }
68
- // Always skip adding any prefixed variant of SimpleSuccessResponse or ErrorResponse
114
+ // Always skip adding prefixed variants of SimpleSuccessResponse or ErrorResponse
69
115
  continue;
70
116
  }
71
117
 
@@ -73,8 +119,8 @@ const base = {
73
119
  let finalSchemaName = schemaName;
74
120
  if (schemaSet.has(schemaName)) {
75
121
  // Try to extract handler name from the spec info title
76
- const handlerName = spec.info?.title?.split(' - ')[1]?.toLowerCase() || 'unknown';
77
- finalSchemaName = `${handlerName}_${schemaName}`;
122
+ const lowerHandlerName = handlerName.toLowerCase() || 'unknown';
123
+ finalSchemaName = `${lowerHandlerName}_${schemaName}`;
78
124
  }
79
125
 
80
126
  if (!schemaSet.has(finalSchemaName)) {
@@ -83,8 +129,10 @@ const base = {
83
129
  }
84
130
  }
85
131
  }
86
- if (spec.components.securitySchemes) {
87
- Object.assign(base.components.securitySchemes, spec.components.securitySchemes);
132
+
133
+ const securitySchemes = isRecord(components.securitySchemes) ? components.securitySchemes : null;
134
+ if (securitySchemes) {
135
+ Object.assign(base.components.securitySchemes, securitySchemes);
88
136
  }
89
137
  }
90
138
 
@@ -97,7 +145,7 @@ const base = {
97
145
  base.tags = Array.from(tagSet.values());
98
146
 
99
147
  // Ensure a default BearerAuth scheme exists to enable Swagger UI "Authorize"
100
- const schemes = (base.components as any).securitySchemes || {};
148
+ const schemes = base.components.securitySchemes;
101
149
  if (!schemes.BearerAuth) {
102
150
  schemes.BearerAuth = {
103
151
  type: 'http',
@@ -105,9 +153,53 @@ const base = {
105
153
  bearerFormat: 'JWT'
106
154
  };
107
155
  }
108
- (base.components as any).securitySchemes = schemes;
156
+ base.components.securitySchemes = schemes;
109
157
 
110
158
  // Apply security globally so operations inherit it by default
111
- (base as any).security = [{ BearerAuth: [] }];
159
+ base.security = [{ BearerAuth: [] }];
112
160
  return base;
113
161
  }
162
+
163
+ export function isObjectRecord(value: unknown): value is Record<string, unknown> {
164
+ return typeof value === 'object' && value !== null;
165
+ }
166
+
167
+ export function collectHandlerNames(discoveryValue: unknown): Set<string> {
168
+ const handlerNames = new Set<string>();
169
+ if (!isObjectRecord(discoveryValue)) {
170
+ return handlerNames;
171
+ }
172
+
173
+ const allWorkersValue = discoveryValue.allWorkers;
174
+ if (isObjectRecord(allWorkersValue)) {
175
+ for (const worker of Object.values(allWorkersValue)) {
176
+ if (!isObjectRecord(worker)) {
177
+ continue;
178
+ }
179
+
180
+ const handlersValue = worker.handlers;
181
+ if (!Array.isArray(handlersValue)) {
182
+ continue;
183
+ }
184
+
185
+ for (const handlerName of handlersValue) {
186
+ if (typeof handlerName === 'string' && handlerName !== 'api-docs') {
187
+ handlerNames.add(handlerName);
188
+ }
189
+ }
190
+ }
191
+ }
192
+
193
+ if (handlerNames.size === 0) {
194
+ const initializedHandlersValue = discoveryValue.initializedHandlers;
195
+ if (Array.isArray(initializedHandlersValue)) {
196
+ for (const name of initializedHandlersValue) {
197
+ if (typeof name === 'string') {
198
+ handlerNames.add(name);
199
+ }
200
+ }
201
+ }
202
+ }
203
+
204
+ return handlerNames;
205
+ }