@objectstack/runtime 0.9.2 → 1.0.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.
@@ -0,0 +1,625 @@
1
+ import { ObjectKernel } from '@objectstack/core';
2
+ import { CoreServiceName } from '@objectstack/spec/system';
3
+
4
+ export interface HttpProtocolContext {
5
+ request: any;
6
+ response?: any;
7
+ }
8
+
9
+ export interface HttpDispatcherResult {
10
+ handled: boolean;
11
+ response?: {
12
+ status: number;
13
+ body?: any;
14
+ headers?: Record<string, string>;
15
+ };
16
+ result?: any; // For flexible return types or direct response objects (Response/NextResponse)
17
+ }
18
+
19
+ export class HttpDispatcher {
20
+ private kernel: any; // Casting to any to access dynamic props like broker, services, graphql
21
+
22
+ constructor(kernel: ObjectKernel) {
23
+ this.kernel = kernel;
24
+ }
25
+
26
+ private success(data: any, meta?: any) {
27
+ return {
28
+ status: 200,
29
+ body: { success: true, data, meta }
30
+ };
31
+ }
32
+
33
+ private error(message: string, code: number = 500, details?: any) {
34
+ return {
35
+ status: code,
36
+ body: { success: false, error: { message, code, details } }
37
+ };
38
+ }
39
+
40
+ private ensureBroker() {
41
+ if (!this.kernel.broker) {
42
+ throw { statusCode: 500, message: 'Kernel Broker not available' };
43
+ }
44
+ return this.kernel.broker;
45
+ }
46
+
47
+ /**
48
+ * Generates the discovery JSON response for the API root
49
+ */
50
+ getDiscoveryInfo(prefix: string) {
51
+ const services = this.getServicesMap();
52
+
53
+ const hasGraphQL = !!(services[CoreServiceName.enum.graphql] || this.kernel.graphql);
54
+ const hasSearch = !!services[CoreServiceName.enum.search];
55
+ const hasWebSockets = !!services[CoreServiceName.enum.realtime];
56
+ const hasFiles = !!(services[CoreServiceName.enum['file-storage']] || services['storage']?.supportsFiles);
57
+ const hasAnalytics = !!services[CoreServiceName.enum.analytics];
58
+ const hasHub = !!services[CoreServiceName.enum.hub];
59
+
60
+ return {
61
+ name: 'ObjectOS',
62
+ version: '1.0.0',
63
+ environment: process.env.NODE_ENV || 'development',
64
+ routes: {
65
+ data: `${prefix}/data`,
66
+ metadata: `${prefix}/metadata`,
67
+ auth: `${prefix}/auth`,
68
+ graphql: hasGraphQL ? `${prefix}/graphql` : undefined,
69
+ storage: hasFiles ? `${prefix}/storage` : undefined,
70
+ analytics: hasAnalytics ? `${prefix}/analytics` : undefined,
71
+ hub: hasHub ? `${prefix}/hub` : undefined,
72
+ },
73
+ features: {
74
+ graphql: hasGraphQL,
75
+ search: hasSearch,
76
+ websockets: hasWebSockets,
77
+ files: hasFiles,
78
+ analytics: hasAnalytics,
79
+ hub: hasHub,
80
+ },
81
+ locale: {
82
+ default: 'en',
83
+ supported: ['en', 'zh-CN'],
84
+ timezone: 'UTC'
85
+ }
86
+ };
87
+ }
88
+
89
+ /**
90
+ * Handles GraphQL requests
91
+ */
92
+ async handleGraphQL(body: { query: string; variables?: any }, context: HttpProtocolContext) {
93
+ if (!body || !body.query) {
94
+ throw { statusCode: 400, message: 'Missing query in request body' };
95
+ }
96
+
97
+ if (typeof this.kernel.graphql !== 'function') {
98
+ throw { statusCode: 501, message: 'GraphQL service not available' };
99
+ }
100
+
101
+ return this.kernel.graphql(body.query, body.variables, {
102
+ request: context.request
103
+ });
104
+ }
105
+
106
+ /**
107
+ * Handles Auth requests
108
+ * path: sub-path after /auth/
109
+ */
110
+ async handleAuth(path: string, method: string, body: any, context: HttpProtocolContext): Promise<HttpDispatcherResult> {
111
+ // 1. Try generic Auth Service
112
+ const authService = this.getService(CoreServiceName.enum.auth);
113
+ if (authService && typeof authService.handler === 'function') {
114
+ const response = await authService.handler(context.request, context.response);
115
+ return { handled: true, result: response };
116
+ }
117
+
118
+ // 2. Legacy Login
119
+ const normalizedPath = path.replace(/^\/+/, '');
120
+ if (normalizedPath === 'login' && method.toUpperCase() === 'POST') {
121
+ const broker = this.ensureBroker();
122
+ const data = await broker.call('auth.login', body, { request: context.request });
123
+ return { handled: true, response: { status: 200, body: data } };
124
+ }
125
+
126
+ return { handled: false };
127
+ }
128
+
129
+ /**
130
+ * Handles Metadata requests
131
+ * Standard: /metadata/:type/:name
132
+ * Fallback for backward compat: /metadata (all objects), /metadata/:objectName (get object)
133
+ */
134
+ async handleMetadata(path: string, context: HttpProtocolContext, method?: string, body?: any): Promise<HttpDispatcherResult> {
135
+ const broker = this.ensureBroker();
136
+ const parts = path.replace(/^\/+/, '').split('/').filter(Boolean);
137
+
138
+ // GET /metadata/types
139
+ if (parts[0] === 'types') {
140
+ // This would normally come from a registry service
141
+ // For now we mock the types supported by core
142
+ return { handled: true, response: this.success({ types: ['objects', 'apps', 'plugins'] }) };
143
+ }
144
+
145
+ // /metadata/:type/:name
146
+ if (parts.length === 2) {
147
+ const [type, name] = parts;
148
+
149
+ // PUT /metadata/:type/:name (Save)
150
+ if (method === 'PUT' && body) {
151
+ // Try to get the protocol service directly
152
+ const protocol = this.kernel?.context?.getService ? this.kernel.context.getService('protocol') : null;
153
+
154
+ if (protocol && typeof protocol.saveMetaItem === 'function') {
155
+ try {
156
+ const result = await protocol.saveMetaItem({ type, name, item: body });
157
+ return { handled: true, response: this.success(result) };
158
+ } catch (e: any) {
159
+ return { handled: true, response: this.error(e.message, 400) };
160
+ }
161
+ }
162
+
163
+ // Fallback to broker if protocol not available (legacy)
164
+ try {
165
+ const data = await broker.call('metadata.saveItem', { type, name, item: body }, { request: context.request });
166
+ return { handled: true, response: this.success(data) };
167
+ } catch (e: any) {
168
+ // If broker doesn't support it either
169
+ return { handled: true, response: this.error(e.message || 'Save not supported', 501) };
170
+ }
171
+ }
172
+
173
+ try {
174
+ // Try specific calls based on type
175
+ if (type === 'objects') {
176
+ const data = await broker.call('metadata.getObject', { objectName: name }, { request: context.request });
177
+ return { handled: true, response: this.success(data) };
178
+ }
179
+ // Generic call for other types if supported
180
+ const data = await broker.call(`metadata.get${this.capitalize(type.slice(0, -1))}`, { name }, { request: context.request });
181
+ return { handled: true, response: this.success(data) };
182
+ } catch (e: any) {
183
+ // Fallback: treat first part as object name if only 1 part (handled below)
184
+ // But here we are deep in 2 parts. Must be an error.
185
+ return { handled: true, response: this.error(e.message, 404) };
186
+ }
187
+ }
188
+
189
+ // GET /metadata/:type (List items of type) OR /metadata/:objectName (Legacy)
190
+ if (parts.length === 1) {
191
+ const typeOrName = parts[0];
192
+
193
+ // Heuristic: if it maps to a known type, list it. Else treat as object name.
194
+ if (['objects', 'apps', 'plugins'].includes(typeOrName)) {
195
+ if (typeOrName === 'objects') {
196
+ const data = await broker.call('metadata.objects', {}, { request: context.request });
197
+ return { handled: true, response: this.success(data) };
198
+ }
199
+ // Try generic list
200
+ const data = await broker.call(`metadata.${typeOrName}`, {}, { request: context.request });
201
+ return { handled: true, response: this.success(data) };
202
+ }
203
+
204
+ // Legacy: /metadata/:objectName
205
+ const data = await broker.call('metadata.getObject', { objectName: typeOrName }, { request: context.request });
206
+ return { handled: true, response: this.success(data) };
207
+ }
208
+
209
+ // GET /metadata (List Objects - Default)
210
+ if (parts.length === 0) {
211
+ const data = await broker.call('metadata.objects', {}, { request: context.request });
212
+ return { handled: true, response: this.success(data) };
213
+ }
214
+
215
+ return { handled: false };
216
+ }
217
+
218
+ /**
219
+ * Handles Data requests
220
+ * path: sub-path after /data/ (e.g. "contacts", "contacts/123", "contacts/query")
221
+ */
222
+ async handleData(path: string, method: string, body: any, query: any, context: HttpProtocolContext): Promise<HttpDispatcherResult> {
223
+ const broker = this.ensureBroker();
224
+ const parts = path.replace(/^\/+/, '').split('/');
225
+ const objectName = parts[0];
226
+
227
+ if (!objectName) {
228
+ return { handled: true, response: this.error('Object name required', 400) };
229
+ }
230
+
231
+ const m = method.toUpperCase();
232
+
233
+ // 1. Custom Actions (query, batch)
234
+ if (parts.length > 1) {
235
+ const action = parts[1];
236
+
237
+ // POST /data/:object/query
238
+ if (action === 'query' && m === 'POST') {
239
+ const result = await broker.call('data.query', { object: objectName, ...body }, { request: context.request });
240
+ return { handled: true, response: this.success(result.data, { count: result.count, limit: body.limit, skip: body.skip }) };
241
+ }
242
+
243
+ // POST /data/:object/batch
244
+ if (action === 'batch' && m === 'POST') {
245
+ // Spec complaint: forward the whole body { operation, records, options }
246
+ // Implementation in Kernel should handle the 'operation' field
247
+ const result = await broker.call('data.batch', { object: objectName, ...body }, { request: context.request });
248
+ return { handled: true, response: this.success(result) };
249
+ }
250
+
251
+ // GET /data/:object/:id
252
+ if (parts.length === 2 && m === 'GET') {
253
+ const id = parts[1];
254
+ const data = await broker.call('data.get', { object: objectName, id, ...query }, { request: context.request });
255
+ return { handled: true, response: this.success(data) };
256
+ }
257
+
258
+ // PATCH /data/:object/:id
259
+ if (parts.length === 2 && m === 'PATCH') {
260
+ const id = parts[1];
261
+ const data = await broker.call('data.update', { object: objectName, id, data: body }, { request: context.request });
262
+ return { handled: true, response: this.success(data) };
263
+ }
264
+
265
+ // DELETE /data/:object/:id
266
+ if (parts.length === 2 && m === 'DELETE') {
267
+ const id = parts[1];
268
+ await broker.call('data.delete', { object: objectName, id }, { request: context.request });
269
+ return { handled: true, response: this.success({ id, deleted: true }) };
270
+ }
271
+ } else {
272
+ // GET /data/:object (List)
273
+ if (m === 'GET') {
274
+ const result = await broker.call('data.query', { object: objectName, filters: query }, { request: context.request });
275
+ return { handled: true, response: this.success(result.data, { count: result.count }) };
276
+ }
277
+
278
+ // POST /data/:object (Create)
279
+ if (m === 'POST') {
280
+ const data = await broker.call('data.create', { object: objectName, data: body }, { request: context.request });
281
+ // Note: ideally 201
282
+ const res = this.success(data);
283
+ res.status = 201;
284
+ return { handled: true, response: res };
285
+ }
286
+ }
287
+
288
+ return { handled: false };
289
+ }
290
+
291
+ /**
292
+ * Handles Analytics requests
293
+ * path: sub-path after /analytics/
294
+ */
295
+ async handleAnalytics(path: string, method: string, body: any, context: HttpProtocolContext): Promise<HttpDispatcherResult> {
296
+ const analyticsService = this.getService(CoreServiceName.enum.analytics);
297
+ if (!analyticsService) return { handled: false }; // 404 handled by caller if unhandled
298
+
299
+ const m = method.toUpperCase();
300
+ const subPath = path.replace(/^\/+/, '');
301
+
302
+ // POST /analytics/query
303
+ if (subPath === 'query' && m === 'POST') {
304
+ const result = await analyticsService.query(body, { request: context.request });
305
+ return { handled: true, response: this.success(result) };
306
+ }
307
+
308
+ // GET /analytics/meta
309
+ if (subPath === 'meta' && m === 'GET') {
310
+ const result = await analyticsService.getMetadata({ request: context.request });
311
+ return { handled: true, response: this.success(result) };
312
+ }
313
+
314
+ // POST /analytics/sql (Dry-run or debug)
315
+ if (subPath === 'sql' && m === 'POST') {
316
+ // Assuming service has generateSql method
317
+ const result = await analyticsService.generateSql(body, { request: context.request });
318
+ return { handled: true, response: this.success(result) };
319
+ }
320
+
321
+ return { handled: false };
322
+ }
323
+
324
+ /**
325
+ * Handles Hub requests
326
+ * path: sub-path after /hub/
327
+ */
328
+ async handleHub(path: string, method: string, body: any, query: any, context: HttpProtocolContext): Promise<HttpDispatcherResult> {
329
+ const hubService = this.getService(CoreServiceName.enum.hub);
330
+ if (!hubService) return { handled: false };
331
+
332
+ const m = method.toUpperCase();
333
+ const parts = path.replace(/^\/+/, '').split('/');
334
+
335
+ // Resource-based routing: /hub/:resource/:id
336
+ if (parts.length > 0) {
337
+ const resource = parts[0]; // spaces, plugins, etc.
338
+
339
+ // Allow mapping "spaces" -> "createSpace", "listSpaces" etc.
340
+ // Convention:
341
+ // GET /spaces -> listSpaces
342
+ // POST /spaces -> createSpace
343
+ // GET /spaces/:id -> getSpace
344
+ // PATCH /spaces/:id -> updateSpace
345
+ // DELETE /spaces/:id -> deleteSpace
346
+
347
+ const actionBase = resource.endsWith('s') ? resource.slice(0, -1) : resource; // space
348
+ const id = parts[1];
349
+
350
+ try {
351
+ if (parts.length === 1) {
352
+ // Collection Operations
353
+ if (m === 'GET') {
354
+ const capitalizedAction = 'list' + this.capitalize(resource); // listSpaces
355
+ if (typeof hubService[capitalizedAction] === 'function') {
356
+ const result = await hubService[capitalizedAction](query, { request: context.request });
357
+ return { handled: true, response: this.success(result) };
358
+ }
359
+ }
360
+ if (m === 'POST') {
361
+ const capitalizedAction = 'create' + this.capitalize(actionBase); // createSpace
362
+ if (typeof hubService[capitalizedAction] === 'function') {
363
+ const result = await hubService[capitalizedAction](body, { request: context.request });
364
+ return { handled: true, response: this.success(result) };
365
+ }
366
+ }
367
+ } else if (parts.length === 2) {
368
+ // Item Operations
369
+ if (m === 'GET') {
370
+ const capitalizedAction = 'get' + this.capitalize(actionBase); // getSpace
371
+ if (typeof hubService[capitalizedAction] === 'function') {
372
+ const result = await hubService[capitalizedAction](id, { request: context.request });
373
+ return { handled: true, response: this.success(result) };
374
+ }
375
+ }
376
+ if (m === 'PATCH' || m === 'PUT') {
377
+ const capitalizedAction = 'update' + this.capitalize(actionBase); // updateSpace
378
+ if (typeof hubService[capitalizedAction] === 'function') {
379
+ const result = await hubService[capitalizedAction](id, body, { request: context.request });
380
+ return { handled: true, response: this.success(result) };
381
+ }
382
+ }
383
+ if (m === 'DELETE') {
384
+ const capitalizedAction = 'delete' + this.capitalize(actionBase); // deleteSpace
385
+ if (typeof hubService[capitalizedAction] === 'function') {
386
+ const result = await hubService[capitalizedAction](id, { request: context.request });
387
+ return { handled: true, response: this.success(result) };
388
+ }
389
+ }
390
+ }
391
+ } catch(e: any) {
392
+ return { handled: true, response: this.error(e.message, 500) };
393
+ }
394
+ }
395
+
396
+ return { handled: false };
397
+ }
398
+
399
+ /**
400
+ * Handles Storage requests
401
+ * path: sub-path after /storage/
402
+ */
403
+ async handleStorage(path: string, method: string, file: any, context: HttpProtocolContext): Promise<HttpDispatcherResult> {
404
+ const storageService = this.getService(CoreServiceName.enum['file-storage']) || this.kernel.services?.['file-storage'];
405
+ if (!storageService) {
406
+ return { handled: true, response: this.error('File storage not configured', 501) };
407
+ }
408
+
409
+ const m = method.toUpperCase();
410
+ const parts = path.replace(/^\/+/, '').split('/');
411
+
412
+ // POST /storage/upload
413
+ if (parts[0] === 'upload' && m === 'POST') {
414
+ if (!file) {
415
+ return { handled: true, response: this.error('No file provided', 400) };
416
+ }
417
+ const result = await storageService.upload(file, { request: context.request });
418
+ return { handled: true, response: this.success(result) };
419
+ }
420
+
421
+ // GET /storage/file/:id
422
+ if (parts[0] === 'file' && parts[1] && m === 'GET') {
423
+ const id = parts[1];
424
+ const result = await storageService.download(id, { request: context.request });
425
+
426
+ // Result can be URL (redirect), Stream/Blob, or metadata
427
+ if (result.url && result.redirect) {
428
+ // Must be handled by adapter to do actual redirect
429
+ return { handled: true, result: { type: 'redirect', url: result.url } };
430
+ }
431
+
432
+ if (result.stream) {
433
+ // Must be handled by adapter to pipe stream
434
+ return {
435
+ handled: true,
436
+ result: {
437
+ type: 'stream',
438
+ stream: result.stream,
439
+ headers: {
440
+ 'Content-Type': result.mimeType || 'application/octet-stream',
441
+ 'Content-Length': result.size
442
+ }
443
+ }
444
+ };
445
+ }
446
+
447
+ return { handled: true, response: this.success(result) };
448
+ }
449
+
450
+ return { handled: false };
451
+ }
452
+
453
+ /**
454
+ * Handles Automation requests
455
+ * path: sub-path after /automation/
456
+ */
457
+ async handleAutomation(path: string, method: string, body: any, context: HttpProtocolContext): Promise<HttpDispatcherResult> {
458
+ const automationService = this.getService(CoreServiceName.enum.automation);
459
+ if (!automationService) return { handled: false };
460
+
461
+ const m = method.toUpperCase();
462
+ const parts = path.replace(/^\/+/, '').split('/');
463
+
464
+ // POST /automation/trigger/:name
465
+ if (parts[0] === 'trigger' && parts[1] && m === 'POST') {
466
+ const triggerName = parts[1];
467
+ if (typeof automationService.trigger === 'function') {
468
+ const result = await automationService.trigger(triggerName, body, { request: context.request });
469
+ return { handled: true, response: this.success(result) };
470
+ }
471
+ }
472
+
473
+ return { handled: false };
474
+ }
475
+
476
+ private getServicesMap(): Record<string, any> {
477
+ if (this.kernel.services instanceof Map) {
478
+ return Object.fromEntries(this.kernel.services);
479
+ }
480
+ return this.kernel.services || {};
481
+ }
482
+
483
+ private getService(name: CoreServiceName) {
484
+ if (typeof this.kernel.getService === 'function') {
485
+ return this.kernel.getService(name);
486
+ }
487
+ const services = this.getServicesMap();
488
+ return services[name];
489
+ }
490
+
491
+ private capitalize(s: string) {
492
+ return s.charAt(0).toUpperCase() + s.slice(1);
493
+ }
494
+
495
+ /**
496
+ * Main Dispatcher Entry Point
497
+ * Routes the request to the appropriate handler based on path and precedence
498
+ */
499
+ async dispatch(method: string, path: string, body: any, query: any, context: HttpProtocolContext): Promise<HttpDispatcherResult> {
500
+ const cleanPath = path.replace(/\/$/, ''); // Remove trailing slash if present, but strict on clean paths
501
+
502
+ // 1. System Protocols (Prefix-based)
503
+ if (cleanPath.startsWith('/auth')) {
504
+ return this.handleAuth(cleanPath.substring(5), method, body, context);
505
+ }
506
+
507
+ if (cleanPath.startsWith('/metadata')) {
508
+ return this.handleMetadata(cleanPath.substring(9), context);
509
+ }
510
+
511
+ if (cleanPath.startsWith('/data')) {
512
+ return this.handleData(cleanPath.substring(5), method, body, query, context);
513
+ }
514
+
515
+ if (cleanPath.startsWith('/graphql')) {
516
+ if (method === 'POST') return this.handleGraphQL(body, context);
517
+ // GraphQL usually GET for Playground is handled by middleware but we can return 405 or handle it
518
+ }
519
+
520
+ if (cleanPath.startsWith('/storage')) {
521
+ return this.handleStorage(cleanPath.substring(8), method, body, context); // body here is file/stream for upload
522
+ }
523
+
524
+ if (cleanPath.startsWith('/automation')) {
525
+ return this.handleAutomation(cleanPath.substring(11), method, body, context);
526
+ }
527
+
528
+ if (cleanPath.startsWith('/analytics')) {
529
+ return this.handleAnalytics(cleanPath.substring(10), method, body, context);
530
+ }
531
+
532
+ if (cleanPath.startsWith('/hub')) {
533
+ return this.handleHub(cleanPath.substring(4), method, body, query, context);
534
+ }
535
+
536
+ // OpenAPI Specification
537
+ if (cleanPath === '/openapi.json' && method === 'GET') {
538
+ const broker = this.ensureBroker();
539
+ try {
540
+ const result = await broker.call('metadata.generateOpenApi', {}, { request: context.request });
541
+ return { handled: true, response: this.success(result) };
542
+ } catch (e) {
543
+ // If not implemented, fall through or return 404
544
+ }
545
+ }
546
+
547
+ // 2. Custom API Endpoints (Registry lookup)
548
+ // Check if there is a custom endpoint defined for this path
549
+ const result = await this.handleApiEndpoint(cleanPath, method, body, query, context);
550
+ if (result.handled) return result;
551
+
552
+ // 3. Fallback (404)
553
+ return { handled: false };
554
+ }
555
+
556
+ /**
557
+ * Handles Custom API Endpoints defined in metadata
558
+ */
559
+ async handleApiEndpoint(path: string, method: string, body: any, query: any, context: HttpProtocolContext): Promise<HttpDispatcherResult> {
560
+ const broker = this.ensureBroker();
561
+ try {
562
+ // Attempt to find a matching endpoint in the registry
563
+ // This assumes a 'metadata.matchEndpoint' action exists in the kernel/registry
564
+ // path should include initial slash e.g. /api/v1/customers
565
+ const endpoint = await broker.call('metadata.matchEndpoint', { path, method });
566
+
567
+ if (endpoint) {
568
+ // Execute the endpoint target logic
569
+ if (endpoint.type === 'flow') {
570
+ const result = await broker.call('automation.runFlow', {
571
+ flowId: endpoint.target,
572
+ inputs: { ...query, ...body, _request: context.request }
573
+ });
574
+ return { handled: true, response: this.success(result) };
575
+ }
576
+
577
+ if (endpoint.type === 'script') {
578
+ const result = await broker.call('automation.runScript', {
579
+ scriptName: endpoint.target,
580
+ context: { ...query, ...body, request: context.request }
581
+ }, { request: context.request });
582
+ return { handled: true, response: this.success(result) };
583
+ }
584
+
585
+ if (endpoint.type === 'object_operation') {
586
+ // e.g. Proxy to an object action
587
+ if (endpoint.objectParams) {
588
+ const { object, operation } = endpoint.objectParams;
589
+ // Map standard CRUD operations
590
+ if (operation === 'find') {
591
+ const result = await broker.call('data.query', { object, filters: query }, { request: context.request });
592
+ return { handled: true, response: this.success(result.data, { count: result.count }) };
593
+ }
594
+ if (operation === 'get' && query.id) {
595
+ const result = await broker.call('data.get', { object, id: query.id }, { request: context.request });
596
+ return { handled: true, response: this.success(result) };
597
+ }
598
+ if (operation === 'create') {
599
+ const result = await broker.call('data.create', { object, data: body }, { request: context.request });
600
+ return { handled: true, response: this.success(result) };
601
+ }
602
+ }
603
+ }
604
+
605
+ if (endpoint.type === 'proxy') {
606
+ // Simple proxy implementation (requires a network call, which usually is done by a service but here we can stub return)
607
+ // In real implementation this might fetch(endpoint.target)
608
+ // For now, return target info
609
+ return {
610
+ handled: true,
611
+ response: {
612
+ status: 200,
613
+ body: { proxy: true, target: endpoint.target, note: 'Proxy execution requires http-client service' }
614
+ }
615
+ };
616
+ }
617
+ }
618
+ } catch (e) {
619
+ // If matchEndpoint fails (e.g. not found), we just return not handled
620
+ // so we can fallback to 404 or other handlers
621
+ }
622
+
623
+ return { handled: false };
624
+ }
625
+ }
package/src/index.ts CHANGED
@@ -1,12 +1,20 @@
1
1
  // Export Kernels
2
2
  export { ObjectKernel } from '@objectstack/core';
3
3
 
4
+ // Export Runtime
5
+ export { Runtime } from './runtime.js';
6
+ export type { RuntimeConfig } from './runtime.js';
7
+
4
8
  // Export Plugins
5
9
  export { DriverPlugin } from './driver-plugin.js';
6
10
  export { AppPlugin } from './app-plugin.js';
11
+ export { createApiRegistryPlugin } from './api-registry-plugin.js';
12
+ export type { ApiRegistryConfig } from './api-registry-plugin.js';
7
13
 
8
14
  // Export HTTP Server Components
9
15
  export { HttpServer } from './http-server.js';
16
+ export { HttpDispatcher } from './http-dispatcher.js';
17
+ export type { HttpProtocolContext, HttpDispatcherResult } from './http-dispatcher.js';
10
18
  export { RestServer } from './rest-server.js';
11
19
  export { RouteManager, RouteGroupBuilder } from './route-manager.js';
12
20
  export type { RouteEntry } from './route-manager.js';
@@ -333,6 +333,35 @@ export class RestServer {
333
333
  },
334
334
  });
335
335
  }
336
+
337
+ // PUT /meta/:type/:name - Save metadata item
338
+ // We always register this route, but return 501 if protocol doesn't support it
339
+ // This makes it discoverable even if not implemented
340
+ this.routeManager.register({
341
+ method: 'PUT',
342
+ path: `${metaPath}/:type/:name`,
343
+ handler: async (req: any, res: any) => {
344
+ try {
345
+ if (!this.protocol.saveMetaItem) {
346
+ res.status(501).json({ error: 'Save operation not supported by protocol implementation' });
347
+ return;
348
+ }
349
+
350
+ const result = await this.protocol.saveMetaItem({
351
+ type: req.params.type,
352
+ name: req.params.name,
353
+ item: req.body
354
+ });
355
+ res.json(result);
356
+ } catch (error: any) {
357
+ res.status(400).json({ error: error.message });
358
+ }
359
+ },
360
+ metadata: {
361
+ summary: 'Save specific metadata item',
362
+ tags: ['metadata'],
363
+ },
364
+ });
336
365
  }
337
366
 
338
367
  /**