-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathrest-server.zod.ts
More file actions
585 lines (506 loc) · 18 KB
/
rest-server.zod.ts
File metadata and controls
585 lines (506 loc) · 18 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.
import { z } from 'zod';
import { HttpMethod } from '../shared/http.zod';
/**
* REST API Server Protocol
*
* Defines the REST API server configuration for automatically generating
* RESTful CRUD endpoints, metadata endpoints, and batch operations.
*
* Features:
* - Automatic CRUD endpoint generation from Object definitions
* - Standard REST conventions (GET, POST, PUT, PATCH, DELETE)
* - Metadata API endpoints
* - Batch operation endpoints
* - OpenAPI/Swagger documentation generation
*
* Architecture alignment:
* - Salesforce: REST API with Object CRUD
* - Microsoft Dynamics: Web API with entity operations
* - Strapi: Auto-generated REST endpoints
*/
// ==========================================
// REST API Configuration
// ==========================================
/**
* REST API Configuration Schema
* Core configuration for REST API server
*
* @example
* {
* "version": "v1",
* "basePath": "/api",
* "enableCrud": true,
* "enableMetadata": true,
* "enableBatch": true,
* "documentation": {
* "enabled": true,
* "title": "ObjectStack API"
* }
* }
*/
export const RestApiConfigSchema = z.object({
/**
* API version identifier
*/
version: z.string().regex(/^[a-zA-Z0-9_\-\.]+$/).default('v1').describe('API version (e.g., v1, v2, 2024-01)'),
/**
* Base path for all API routes
*/
basePath: z.string().default('/api').describe('Base URL path for API'),
/**
* Full API path (combines basePath and version)
*/
apiPath: z.string().optional().describe('Full API path (defaults to {basePath}/{version})'),
/**
* Enable automatic CRUD endpoints
*/
enableCrud: z.boolean().default(true).describe('Enable automatic CRUD endpoint generation'),
/**
* Enable metadata endpoints
*/
enableMetadata: z.boolean().default(true).describe('Enable metadata API endpoints'),
/**
* Enable UI API endpoints
*/
enableUi: z.boolean().default(true).describe('Enable UI API endpoints (Views, Menus, Layouts)'),
/**
* Enable batch operation endpoints
*/
enableBatch: z.boolean().default(true).describe('Enable batch operation endpoints'),
/**
* Enable discovery endpoint
*/
enableDiscovery: z.boolean().default(true).describe('Enable API discovery endpoint'),
/**
* API documentation configuration
*/
documentation: z.object({
enabled: z.boolean().default(true).describe('Enable API documentation'),
title: z.string().default('ObjectStack API').describe('API documentation title'),
description: z.string().optional().describe('API description'),
version: z.string().optional().describe('Documentation version'),
termsOfService: z.string().optional().describe('Terms of service URL'),
contact: z.object({
name: z.string().optional(),
url: z.string().optional(),
email: z.string().optional(),
}).optional(),
license: z.object({
name: z.string(),
url: z.string().optional(),
}).optional(),
}).optional().describe('OpenAPI/Swagger documentation config'),
/**
* Response format configuration
*/
responseFormat: z.object({
envelope: z.boolean().default(true).describe('Wrap responses in standard envelope'),
includeMetadata: z.boolean().default(true).describe('Include response metadata (timestamp, requestId)'),
includePagination: z.boolean().default(true).describe('Include pagination info in list responses'),
}).optional().describe('Response format options'),
});
export type RestApiConfig = z.infer<typeof RestApiConfigSchema>;
export type RestApiConfigInput = z.input<typeof RestApiConfigSchema>;
// ==========================================
// CRUD Endpoint Configuration
// ==========================================
/**
* CRUD Operation Type Enum
*/
export const CrudOperation = z.enum([
'create', // POST /api/v1/data/{object}
'read', // GET /api/v1/data/{object}/:id
'update', // PATCH /api/v1/data/{object}/:id
'delete', // DELETE /api/v1/data/{object}/:id
'list', // GET /api/v1/data/{object}
]);
export type CrudOperation = z.infer<typeof CrudOperation>;
/**
* CRUD Endpoint Pattern Schema
* Defines the URL pattern for CRUD operations
*
* @example
* {
* "create": { "method": "POST", "path": "/data/{object}" },
* "read": { "method": "GET", "path": "/data/{object}/:id" },
* "update": { "method": "PATCH", "path": "/data/{object}/:id" },
* "delete": { "method": "DELETE", "path": "/data/{object}/:id" },
* "list": { "method": "GET", "path": "/data/{object}" }
* }
*/
export const CrudEndpointPatternSchema = z.object({
/**
* HTTP method
*/
method: HttpMethod.describe('HTTP method'),
/**
* URL path pattern (relative to API base)
*/
path: z.string().describe('URL path pattern'),
/**
* Operation summary for documentation
*/
summary: z.string().optional().describe('Operation summary'),
/**
* Operation description
*/
description: z.string().optional().describe('Operation description'),
});
export type CrudEndpointPattern = z.infer<typeof CrudEndpointPatternSchema>;
/**
* CRUD Endpoints Configuration Schema
* Configuration for automatic CRUD endpoint generation
*/
export const CrudEndpointsConfigSchema = z.object({
/**
* Enable/disable specific CRUD operations
*/
operations: z.object({
create: z.boolean().default(true).describe('Enable create operation'),
read: z.boolean().default(true).describe('Enable read operation'),
update: z.boolean().default(true).describe('Enable update operation'),
delete: z.boolean().default(true).describe('Enable delete operation'),
list: z.boolean().default(true).describe('Enable list operation'),
}).optional().describe('Enable/disable operations'),
/**
* Custom endpoint patterns (override defaults)
*/
patterns: z.record(CrudOperation, CrudEndpointPatternSchema.optional()).optional()
.describe('Custom URL patterns for operations'),
/**
* Path prefix for data operations
*/
dataPrefix: z.string().default('/data').describe('URL prefix for data endpoints'),
/**
* Object name parameter style
*/
objectParamStyle: z.enum(['path', 'query']).default('path')
.describe('How object name is passed (path param or query param)'),
});
export type CrudEndpointsConfig = z.infer<typeof CrudEndpointsConfigSchema>;
export type CrudEndpointsConfigInput = z.input<typeof CrudEndpointsConfigSchema>;
// ==========================================
// Metadata Endpoint Configuration
// ==========================================
/**
* Metadata Endpoint Configuration Schema
* Configuration for metadata API endpoints
*
* @example
* {
* "prefix": "/meta",
* "enableCache": true,
* "endpoints": {
* "types": true,
* "objects": true,
* "fields": true
* }
* }
*/
export const MetadataEndpointsConfigSchema = z.object({
/**
* Path prefix for metadata operations
*/
prefix: z.string().default('/meta').describe('URL prefix for metadata endpoints'),
/**
* Enable HTTP caching for metadata
*/
enableCache: z.boolean().default(true).describe('Enable HTTP cache headers (ETag, Last-Modified)'),
/**
* Cache TTL in seconds
*/
cacheTtl: z.number().int().default(3600).describe('Cache TTL in seconds'),
/**
* Enable specific metadata endpoints
*/
endpoints: z.object({
types: z.boolean().default(true).describe('GET /meta - List all metadata types'),
items: z.boolean().default(true).describe('GET /meta/:type - List items of type'),
item: z.boolean().default(true).describe('GET /meta/:type/:name - Get specific item'),
schema: z.boolean().default(true).describe('GET /meta/:type/:name/schema - Get JSON schema'),
}).optional().describe('Enable/disable specific endpoints'),
});
export type MetadataEndpointsConfig = z.infer<typeof MetadataEndpointsConfigSchema>;
export type MetadataEndpointsConfigInput = z.input<typeof MetadataEndpointsConfigSchema>;
// ==========================================
// Batch Operation Endpoint Configuration
// ==========================================
/**
* Batch Operation Endpoint Configuration Schema
* Configuration for batch/bulk operation endpoints
*
* @example
* {
* "maxBatchSize": 200,
* "enableBatchEndpoint": true,
* "enableCreateMany": true,
* "enableUpdateMany": true,
* "enableDeleteMany": true
* }
*/
export const BatchEndpointsConfigSchema = z.object({
/**
* Maximum batch size
*/
maxBatchSize: z.number().int().min(1).max(1000).default(200)
.describe('Maximum records per batch operation'),
/**
* Enable generic batch endpoint
*/
enableBatchEndpoint: z.boolean().default(true)
.describe('Enable POST /data/:object/batch endpoint'),
/**
* Enable specific batch operations
*/
operations: z.object({
createMany: z.boolean().default(true).describe('Enable POST /data/:object/createMany'),
updateMany: z.boolean().default(true).describe('Enable POST /data/:object/updateMany'),
deleteMany: z.boolean().default(true).describe('Enable POST /data/:object/deleteMany'),
upsertMany: z.boolean().default(true).describe('Enable POST /data/:object/upsertMany'),
}).optional().describe('Enable/disable specific batch operations'),
/**
* Transaction mode default
*/
defaultAtomic: z.boolean().default(true)
.describe('Default atomic/transaction mode for batch operations'),
});
export type BatchEndpointsConfig = z.infer<typeof BatchEndpointsConfigSchema>;
export type BatchEndpointsConfigInput = z.input<typeof BatchEndpointsConfigSchema>;
// ==========================================
// Route Generation Configuration
// ==========================================
/**
* Route Generation Configuration Schema
* Controls automatic route generation for objects
*/
export const RouteGenerationConfigSchema = z.object({
/**
* Objects to include (if empty, include all)
*/
includeObjects: z.array(z.string()).optional()
.describe('Specific objects to generate routes for (empty = all)'),
/**
* Objects to exclude
*/
excludeObjects: z.array(z.string()).optional()
.describe('Objects to exclude from route generation'),
/**
* Object name transformations
*/
nameTransform: z.enum(['none', 'plural', 'kebab-case', 'camelCase']).default('none')
.describe('Transform object names in URLs'),
/**
* Custom route overrides per object
*/
overrides: z.record(z.string(), z.object({
enabled: z.boolean().optional().describe('Enable/disable routes for this object'),
basePath: z.string().optional().describe('Custom base path'),
operations: z.record(CrudOperation, z.boolean()).optional()
.describe('Enable/disable specific operations'),
})).optional().describe('Per-object route customization'),
});
export type RouteGenerationConfig = z.infer<typeof RouteGenerationConfigSchema>;
export type RouteGenerationConfigInput = z.input<typeof RouteGenerationConfigSchema>;
// ==========================================
// OpenAPI 3.1 Webhooks & Callbacks
// ==========================================
/**
* Webhook Event Schema
* Defines an event that can trigger a webhook delivery
*/
export const WebhookEventSchema = z.object({
name: z.string().regex(/^[a-z_][a-z0-9_]*$/).describe('Webhook event identifier (snake_case)'),
description: z.string().describe('Human-readable event description'),
method: HttpMethod.default('POST').describe('HTTP method for webhook delivery'),
payloadSchema: z.string().describe('JSON Schema $ref for the webhook payload'),
headers: z.record(z.string(), z.string()).optional().describe('Custom headers to include in webhook delivery'),
security: z.array(
z.enum(['hmac_sha256', 'basic', 'bearer', 'api_key'])
).describe('Supported authentication methods for webhook verification'),
});
export type WebhookEvent = z.infer<typeof WebhookEventSchema>;
/**
* Webhook Configuration Schema
* Top-level webhook configuration for the REST API
*/
export const WebhookConfigSchema = z.object({
enabled: z.boolean().default(false).describe('Enable webhook support'),
events: z.array(WebhookEventSchema).describe('Registered webhook events'),
deliveryConfig: z.object({
maxRetries: z.number().int().default(3).describe('Maximum delivery retry attempts'),
retryIntervalMs: z.number().int().default(5000).describe('Milliseconds between retry attempts'),
timeoutMs: z.number().int().default(30000).describe('Delivery request timeout in milliseconds'),
signatureHeader: z.string().default('X-Signature-256').describe('Header name for webhook signature'),
}).describe('Webhook delivery configuration'),
registrationEndpoint: z.string().default('/webhooks').describe('URL path for webhook registration'),
});
export type WebhookConfig = z.infer<typeof WebhookConfigSchema>;
/**
* Callback Schema
* OpenAPI 3.1 callback definition for asynchronous API responses
*/
export const CallbackSchema = z.object({
name: z.string().regex(/^[a-z_][a-z0-9_]*$/).describe('Callback identifier (snake_case)'),
expression: z.string().describe('Runtime expression (e.g., {$request.body#/callbackUrl})'),
method: HttpMethod.describe('HTTP method for callback request'),
url: z.string().describe('Callback URL template with runtime expressions'),
});
export type Callback = z.infer<typeof CallbackSchema>;
/**
* OpenAPI 3.1 Extensions Schema
* Extensions specific to OpenAPI 3.1 specification
*/
export const OpenApi31ExtensionsSchema = z.object({
webhooks: z.record(z.string(), WebhookEventSchema).optional()
.describe('OpenAPI 3.1 webhooks (top-level webhook definitions)'),
callbacks: z.record(z.string(), z.array(CallbackSchema)).optional()
.describe('OpenAPI 3.1 callbacks (async response definitions)'),
jsonSchemaDialect: z.string().default('https://json-schema.org/draft/2020-12/schema')
.describe('JSON Schema dialect for schema definitions'),
pathItemReferences: z.boolean().default(false)
.describe('Allow $ref in path items (OpenAPI 3.1 feature)'),
});
export type OpenApi31Extensions = z.infer<typeof OpenApi31ExtensionsSchema>;
// ==========================================
// Complete REST Server Configuration
// ==========================================
/**
* REST Server Configuration Schema
* Complete configuration for REST API server with auto-generated endpoints
*
* @example
* {
* "api": {
* "version": "v1",
* "basePath": "/api",
* "enableCrud": true,
* "enableMetadata": true,
* "enableBatch": true
* },
* "crud": {
* "dataPrefix": "/data"
* },
* "metadata": {
* "prefix": "/meta",
* "enableCache": true
* },
* "batch": {
* "maxBatchSize": 200
* },
* "routes": {
* "excludeObjects": ["system_log"]
* }
* }
*/
export const RestServerConfigSchema = z.object({
/**
* API configuration
*/
api: RestApiConfigSchema.optional().describe('REST API configuration'),
/**
* CRUD endpoints configuration
*/
crud: CrudEndpointsConfigSchema.optional().describe('CRUD endpoints configuration'),
/**
* Metadata endpoints configuration
*/
metadata: MetadataEndpointsConfigSchema.optional().describe('Metadata endpoints configuration'),
/**
* Batch endpoints configuration
*/
batch: BatchEndpointsConfigSchema.optional().describe('Batch endpoints configuration'),
/**
* Route generation configuration
*/
routes: RouteGenerationConfigSchema.optional().describe('Route generation configuration'),
/**
* OpenAPI 3.1 extensions (webhooks, callbacks)
*/
openApi31: OpenApi31ExtensionsSchema.optional().describe('OpenAPI 3.1 extensions configuration'),
});
export type RestServerConfig = z.infer<typeof RestServerConfigSchema>;
export type RestServerConfigInput = z.input<typeof RestServerConfigSchema>;
// ==========================================
// Endpoint Registry
// ==========================================
/**
* Generated Endpoint Schema
* Represents a generated REST endpoint
*/
export const GeneratedEndpointSchema = z.object({
/**
* Endpoint identifier
*/
id: z.string().describe('Unique endpoint identifier'),
/**
* HTTP method
*/
method: HttpMethod.describe('HTTP method'),
/**
* Full URL path
*/
path: z.string().describe('Full URL path'),
/**
* Object this endpoint operates on
*/
object: z.string().describe('Object name (snake_case)'),
/**
* Operation type
*/
operation: z.union([CrudOperation, z.string()]).describe('Operation type'),
/**
* Handler reference
*/
handler: z.string().describe('Handler function identifier'),
/**
* Endpoint metadata
*/
metadata: z.object({
summary: z.string().optional(),
description: z.string().optional(),
tags: z.array(z.string()).optional(),
deprecated: z.boolean().optional(),
}).optional(),
});
export type GeneratedEndpoint = z.infer<typeof GeneratedEndpointSchema>;
/**
* Endpoint Registry Schema
* Registry of all generated endpoints
*/
export const EndpointRegistrySchema = z.object({
/**
* Generated endpoints
*/
endpoints: z.array(GeneratedEndpointSchema).describe('All generated endpoints'),
/**
* Total endpoint count
*/
total: z.number().int().describe('Total number of endpoints'),
/**
* Endpoints by object
*/
byObject: z.record(z.string(), z.array(GeneratedEndpointSchema)).optional()
.describe('Endpoints grouped by object'),
/**
* Endpoints by operation
*/
byOperation: z.record(z.string(), z.array(GeneratedEndpointSchema)).optional()
.describe('Endpoints grouped by operation'),
});
export type EndpointRegistry = z.infer<typeof EndpointRegistrySchema>;
// ==========================================
// Helper Functions
// ==========================================
/**
* Helper to create REST API configuration
*/
export const RestApiConfig = Object.assign(RestApiConfigSchema, {
create: <T extends z.input<typeof RestApiConfigSchema>>(config: T) => config,
});
/**
* Helper to create REST server configuration
*/
export const RestServerConfig = Object.assign(RestServerConfigSchema, {
create: <T extends z.input<typeof RestServerConfigSchema>>(config: T) => config,
});