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