-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathhttp-dispatcher.ts
More file actions
1487 lines (1331 loc) · 67.8 KB
/
http-dispatcher.ts
File metadata and controls
1487 lines (1331 loc) · 67.8 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
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.
import { ObjectKernel, getEnv, resolveLocale } from '@objectstack/core';
import { CoreServiceName } from '@objectstack/spec/system';
/** Browser-safe UUID generator — prefers Web Crypto, falls back to RFC 4122 v4 */
function randomUUID(): string {
if (globalThis.crypto && typeof globalThis.crypto.randomUUID === 'function') {
return globalThis.crypto.randomUUID();
}
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => {
const r = (Math.random() * 16) | 0;
const v = c === 'x' ? r : (r & 0x3) | 0x8;
return v.toString(16);
});
}
export interface HttpProtocolContext {
request: any;
response?: any;
}
export interface HttpDispatcherResult {
handled: boolean;
response?: {
status: number;
body?: any;
headers?: Record<string, string>;
};
result?: any; // For flexible return types or direct response objects (Response/NextResponse)
}
/**
* @deprecated Use `createDispatcherPlugin()` from `@objectstack/runtime` instead.
* This class will be removed in v2. Prefer the plugin-based approach:
* ```ts
* import { createDispatcherPlugin } from '@objectstack/runtime';
* kernel.use(createDispatcherPlugin({ prefix: '/api/v1' }));
* ```
*/
export class HttpDispatcher {
private kernel: any; // Casting to any to access dynamic props like broker, services, graphql
constructor(kernel: ObjectKernel) {
this.kernel = kernel;
}
private success(data: any, meta?: any) {
return {
status: 200,
body: { success: true, data, meta }
};
}
private error(message: string, code: number = 500, details?: any) {
return {
status: code,
body: { success: false, error: { message, code, details } }
};
}
/**
* 404 Route Not Found — no route is registered for this path.
*/
private routeNotFound(route: string) {
return {
status: 404,
body: {
success: false,
error: {
code: 404,
message: `Route Not Found: ${route}`,
type: 'ROUTE_NOT_FOUND' as const,
route,
hint: 'No route is registered for this path. Check the API discovery endpoint for available routes.',
},
},
};
}
private ensureBroker() {
if (!this.kernel.broker) {
throw { statusCode: 500, message: 'Kernel Broker not available' };
}
return this.kernel.broker;
}
/**
* Generates the discovery JSON response for the API root.
*
* Uses the same async `resolveService()` fallback chain that request
* handlers use, so the reported service status is always consistent
* with the actual runtime availability.
*/
async getDiscoveryInfo(prefix: string) {
// Resolve all services through the same async fallback chain
// that request handlers (handleI18n, handleAuth, …) use.
const [
authSvc, graphqlSvc, searchSvc, realtimeSvc, filesSvc,
analyticsSvc, workflowSvc, aiSvc, notificationSvc, i18nSvc,
uiSvc, automationSvc, cacheSvc, queueSvc, jobSvc,
] = await Promise.all([
this.resolveService(CoreServiceName.enum.auth),
this.resolveService(CoreServiceName.enum.graphql),
this.resolveService(CoreServiceName.enum.search),
this.resolveService(CoreServiceName.enum.realtime),
this.resolveService(CoreServiceName.enum['file-storage']),
this.resolveService(CoreServiceName.enum.analytics),
this.resolveService(CoreServiceName.enum.workflow),
this.resolveService(CoreServiceName.enum.ai),
this.resolveService(CoreServiceName.enum.notification),
this.resolveService(CoreServiceName.enum.i18n),
this.resolveService(CoreServiceName.enum.ui),
this.resolveService(CoreServiceName.enum.automation),
this.resolveService(CoreServiceName.enum.cache),
this.resolveService(CoreServiceName.enum.queue),
this.resolveService(CoreServiceName.enum.job),
]);
const hasAuth = !!authSvc;
const hasGraphQL = !!(graphqlSvc || this.kernel.graphql);
const hasSearch = !!searchSvc;
const hasWebSockets = !!realtimeSvc;
const hasFiles = !!filesSvc;
const hasAnalytics = !!analyticsSvc;
const hasWorkflow = !!workflowSvc;
const hasAi = !!aiSvc;
const hasNotification = !!notificationSvc;
const hasI18n = !!i18nSvc;
const hasUi = !!uiSvc;
const hasAutomation = !!automationSvc;
const hasCache = !!cacheSvc;
const hasQueue = !!queueSvc;
const hasJob = !!jobSvc;
// Routes are only exposed when a plugin provides the service
const routes = {
data: `${prefix}/data`,
metadata: `${prefix}/meta`,
packages: `${prefix}/packages`,
auth: hasAuth ? `${prefix}/auth` : undefined,
ui: hasUi ? `${prefix}/ui` : undefined,
graphql: hasGraphQL ? `${prefix}/graphql` : undefined,
storage: hasFiles ? `${prefix}/storage` : undefined,
analytics: hasAnalytics ? `${prefix}/analytics` : undefined,
automation: hasAutomation ? `${prefix}/automation` : undefined,
workflow: hasWorkflow ? `${prefix}/workflow` : undefined,
realtime: hasWebSockets ? `${prefix}/realtime` : undefined,
notifications: hasNotification ? `${prefix}/notifications` : undefined,
ai: hasAi ? `${prefix}/ai` : undefined,
i18n: hasI18n ? `${prefix}/i18n` : undefined,
};
// Build per-service status map
// handlerReady: true means the dispatcher has a real, bound handler for this route.
// handlerReady: false means the route is present in the discovery table but may not
// yet have a concrete implementation or may be served by a stub.
const svcAvailable = (route?: string, provider?: string) => ({
enabled: true, status: 'available' as const, handlerReady: true, route, provider,
});
const svcUnavailable = (name: string) => ({
enabled: false, status: 'unavailable' as const, handlerReady: false,
message: `Install a ${name} plugin to enable`,
});
// Derive locale info from actual i18n service when available
let locale = { default: 'en', supported: ['en'], timezone: 'UTC' };
if (hasI18n && i18nSvc) {
const defaultLocale = typeof i18nSvc.getDefaultLocale === 'function'
? i18nSvc.getDefaultLocale() : 'en';
const locales = typeof i18nSvc.getLocales === 'function'
? i18nSvc.getLocales() : [];
locale = {
default: defaultLocale,
supported: locales.length > 0 ? locales : [defaultLocale],
timezone: 'UTC',
};
}
return {
name: 'ObjectOS',
version: '1.0.0',
environment: getEnv('NODE_ENV', 'development'),
routes,
endpoints: routes, // Alias for backward compatibility with some clients
features: {
graphql: hasGraphQL,
search: hasSearch,
websockets: hasWebSockets,
files: hasFiles,
analytics: hasAnalytics,
ai: hasAi,
workflow: hasWorkflow,
notifications: hasNotification,
i18n: hasI18n,
},
services: {
// Kernel-provided (always available via protocol implementation)
metadata: { enabled: true, status: 'degraded' as const, handlerReady: true, route: routes.metadata, provider: 'kernel', message: 'In-memory registry; DB persistence pending' },
data: svcAvailable(routes.data, 'kernel'),
// Plugin-provided — only available when a plugin registers the service
auth: hasAuth ? svcAvailable(routes.auth) : svcUnavailable('auth'),
automation: hasAutomation ? svcAvailable(routes.automation) : svcUnavailable('automation'),
analytics: hasAnalytics ? svcAvailable(routes.analytics) : svcUnavailable('analytics'),
cache: hasCache ? svcAvailable() : svcUnavailable('cache'),
queue: hasQueue ? svcAvailable() : svcUnavailable('queue'),
job: hasJob ? svcAvailable() : svcUnavailable('job'),
ui: hasUi ? svcAvailable(routes.ui) : svcUnavailable('ui'),
workflow: hasWorkflow ? svcAvailable(routes.workflow) : svcUnavailable('workflow'),
realtime: hasWebSockets ? svcAvailable(routes.realtime) : svcUnavailable('realtime'),
notification: hasNotification ? svcAvailable(routes.notifications) : svcUnavailable('notification'),
ai: hasAi ? svcAvailable(routes.ai) : svcUnavailable('ai'),
i18n: hasI18n ? svcAvailable(routes.i18n) : svcUnavailable('i18n'),
graphql: hasGraphQL ? svcAvailable(routes.graphql) : svcUnavailable('graphql'),
'file-storage': hasFiles ? svcAvailable(routes.storage) : svcUnavailable('file-storage'),
search: hasSearch ? svcAvailable() : svcUnavailable('search'),
},
locale,
};
}
/**
* Handles GraphQL requests
*/
async handleGraphQL(body: { query: string; variables?: any }, context: HttpProtocolContext) {
if (!body || !body.query) {
throw { statusCode: 400, message: 'Missing query in request body' };
}
if (typeof this.kernel.graphql !== 'function') {
throw { statusCode: 501, message: 'GraphQL service not available' };
}
return this.kernel.graphql(body.query, body.variables, {
request: context.request
});
}
/**
* Handles Auth requests
* path: sub-path after /auth/
*/
async handleAuth(path: string, method: string, body: any, context: HttpProtocolContext): Promise<HttpDispatcherResult> {
// 1. Try generic Auth Service
const authService = await this.getService(CoreServiceName.enum.auth);
if (authService && typeof authService.handler === 'function') {
const response = await authService.handler(context.request, context.response);
return { handled: true, result: response };
}
// 2. Legacy Login via broker
const normalizedPath = path.replace(/^\/+/, '');
if (normalizedPath === 'login' && method.toUpperCase() === 'POST') {
try {
const broker = this.ensureBroker();
const data = await broker.call('auth.login', body, { request: context.request });
return { handled: true, response: { status: 200, body: data } };
} catch (error: any) {
// Only fall through to mock when the broker is truly unavailable
// (ensureBroker throws statusCode 500 when kernel.broker is null)
const statusCode = error?.statusCode ?? error?.status;
if (statusCode !== 500 || !error?.message?.includes('Broker not available')) {
throw error;
}
}
}
// 3. Mock fallback for MSW/test environments when no auth service is registered
return this.mockAuthFallback(normalizedPath, method, body);
}
/**
* Provides mock auth responses for core better-auth endpoints when
* AuthPlugin is not loaded (e.g. MSW/browser-only environments).
* This ensures registration/sign-in flows do not 404 in mock mode.
*/
private mockAuthFallback(path: string, method: string, body: any): HttpDispatcherResult {
const m = method.toUpperCase();
const MOCK_SESSION_EXPIRY_MS = 86_400_000; // 24 hours
// POST sign-up/email
if ((path === 'sign-up/email' || path === 'register') && m === 'POST') {
const id = `mock_${randomUUID()}`;
return {
handled: true,
response: {
status: 200,
body: {
user: { id, name: body?.name || 'Mock User', email: body?.email || 'mock@test.local', emailVerified: false, createdAt: new Date().toISOString(), updatedAt: new Date().toISOString() },
session: { id: `session_${id}`, userId: id, token: `mock_token_${id}`, expiresAt: new Date(Date.now() + MOCK_SESSION_EXPIRY_MS).toISOString() },
},
},
};
}
// POST sign-in/email or login
if ((path === 'sign-in/email' || path === 'login') && m === 'POST') {
const id = `mock_${randomUUID()}`;
return {
handled: true,
response: {
status: 200,
body: {
user: { id, name: 'Mock User', email: body?.email || 'mock@test.local', emailVerified: true, createdAt: new Date().toISOString(), updatedAt: new Date().toISOString() },
session: { id: `session_${id}`, userId: id, token: `mock_token_${id}`, expiresAt: new Date(Date.now() + MOCK_SESSION_EXPIRY_MS).toISOString() },
},
},
};
}
// GET get-session
if (path === 'get-session' && m === 'GET') {
return {
handled: true,
response: { status: 200, body: { session: null, user: null } },
};
}
// POST sign-out
if (path === 'sign-out' && m === 'POST') {
return {
handled: true,
response: { status: 200, body: { success: true } },
};
}
return { handled: false };
}
/**
* Handles Metadata requests
* Standard: /metadata/:type/:name
* Fallback for backward compat: /metadata (all objects), /metadata/:objectName (get object)
*/
async handleMetadata(path: string, context: HttpProtocolContext, method?: string, body?: any, query?: any): Promise<HttpDispatcherResult> {
// Broker is used as a fallback — not required upfront.
// This allows metadata to be served when only the protocol service
// or ObjectQL service is available (e.g. lightweight / serverless setups).
const broker = this.kernel.broker ?? null;
const parts = path.replace(/^\/+/, '').split('/').filter(Boolean);
// GET /metadata/types
if (parts[0] === 'types') {
// Try protocol service for dynamic types
const protocol = await this.resolveService('protocol');
if (protocol && typeof protocol.getMetaTypes === 'function') {
const result = await protocol.getMetaTypes({});
return { handled: true, response: this.success(result) };
}
// Fallback: ask broker for registered types
if (broker) {
try {
const data = await broker.call('metadata.types', {}, { request: context.request });
return { handled: true, response: this.success(data) };
} catch {
// fall through to hardcoded defaults
}
}
// Last resort: hardcoded defaults
return { handled: true, response: this.success({ types: ['object', 'app', 'plugin'] }) };
}
// GET /metadata/:type/:name/published → get published version
if (parts.length === 3 && parts[2] === 'published' && (!method || method === 'GET')) {
const [type, name] = parts;
const metadataService = await this.getService(CoreServiceName.enum.metadata);
if (metadataService && typeof (metadataService as any).getPublished === 'function') {
const data = await (metadataService as any).getPublished(type, name);
if (data === undefined) return { handled: true, response: this.error('Not found', 404) };
return { handled: true, response: this.success(data) };
}
// Broker fallback
if (broker) {
try {
const data = await broker.call('metadata.getPublished', { type, name }, { request: context.request });
return { handled: true, response: this.success(data) };
} catch (e: any) {
return { handled: true, response: this.error(e.message, 404) };
}
}
return { handled: true, response: this.error('Not found', 404) };
}
// /metadata/:type/:name
if (parts.length === 2) {
const [type, name] = parts;
// Extract optional package filter from query string
const packageId = query?.package || undefined;
// PUT /metadata/:type/:name (Save)
if (method === 'PUT' && body) {
// Try to get the protocol service directly
const protocol = await this.resolveService('protocol');
if (protocol && typeof protocol.saveMetaItem === 'function') {
try {
const result = await protocol.saveMetaItem({ type, name, item: body });
return { handled: true, response: this.success(result) };
} catch (e: any) {
return { handled: true, response: this.error(e.message, 400) };
}
}
// Fallback to broker if protocol not available (legacy)
if (broker) {
try {
const data = await broker.call('metadata.saveItem', { type, name, item: body }, { request: context.request });
return { handled: true, response: this.success(data) };
} catch (e: any) {
return { handled: true, response: this.error(e.message || 'Save not supported', 501) };
}
}
return { handled: true, response: this.error('Save not supported', 501) };
}
try {
// Try specific calls based on type
if (type === 'objects' || type === 'object') {
if (broker) {
const data = await broker.call('metadata.getObject', { objectName: name }, { request: context.request });
return { handled: true, response: this.success(data) };
}
// Try ObjectQL service directly when broker is unavailable
const qlService = await this.getObjectQLService();
if (qlService?.registry) {
const data = qlService.registry.getObject(name);
if (data) return { handled: true, response: this.success(data) };
}
return { handled: true, response: this.error('Not found', 404) };
}
// If type is singular (e.g. 'app'), use it directly
// If plural (e.g. 'apps'), slice it
const singularType = type.endsWith('s') ? type.slice(0, -1) : type;
// Try Protocol Service First (Preferred)
const protocol = await this.resolveService('protocol');
if (protocol && typeof protocol.getMetaItem === 'function') {
try {
const data = await protocol.getMetaItem({ type: singularType, name, packageId });
return { handled: true, response: this.success(data) };
} catch (e: any) {
// Protocol might throw if not found or not supported
// Fallback to broker?
}
}
// Generic call for other types if supported via Broker (Legacy)
if (broker) {
const method = `metadata.get${this.capitalize(singularType)}`;
const data = await broker.call(method, { name }, { request: context.request });
return { handled: true, response: this.success(data) };
}
return { handled: true, response: this.error('Not found', 404) };
} catch (e: any) {
// Fallback: treat first part as object name if only 1 part (handled below)
// But here we are deep in 2 parts. Must be an error.
return { handled: true, response: this.error(e.message, 404) };
}
}
// GET /metadata/:type (List items of type) OR /metadata/:objectName (Legacy)
if (parts.length === 1) {
const typeOrName = parts[0];
// Extract optional package filter from query string
const packageId = query?.package || undefined;
// Try protocol service first for any type
const protocol = await this.resolveService('protocol');
if (protocol && typeof protocol.getMetaItems === 'function') {
try {
const data = await protocol.getMetaItems({ type: typeOrName, packageId });
// Return any valid response from protocol (including empty items arrays)
if (data && (data.items !== undefined || Array.isArray(data))) {
return { handled: true, response: this.success(data) };
}
} catch {
// Protocol doesn't know this type, fall through
}
}
// Try broker for the type
if (broker) {
try {
if (typeOrName === 'objects') {
const data = await broker.call('metadata.objects', { packageId }, { request: context.request });
return { handled: true, response: this.success(data) };
}
const data = await broker.call(`metadata.${typeOrName}`, { packageId }, { request: context.request });
if (data !== null && data !== undefined) {
return { handled: true, response: this.success(data) };
}
} catch {
// Broker doesn't support this action, fall through
}
// Legacy: /metadata/:objectName (treat as single object lookup)
try {
const data = await broker.call('metadata.getObject', { objectName: typeOrName }, { request: context.request });
return { handled: true, response: this.success(data) };
} catch (e: any) {
return { handled: true, response: this.error(e.message, 404) };
}
}
// No broker — try ObjectQL registry directly for object lookups
const qlService = await this.getObjectQLService();
if (qlService?.registry) {
if (typeOrName === 'objects') {
const objs = qlService.registry.getAllObjects(packageId);
return { handled: true, response: this.success({ type: 'object', items: objs }) };
}
// Try listing items of the given type
const items = qlService.registry.listItems?.(typeOrName, packageId);
if (items && items.length > 0) {
return { handled: true, response: this.success({ type: typeOrName, items }) };
}
// Legacy: treat as object name
const obj = qlService.registry.getObject(typeOrName);
if (obj) return { handled: true, response: this.success(obj) };
}
return { handled: true, response: this.error('Not found', 404) };
}
// GET /metadata — return available metadata types
if (parts.length === 0) {
// Try protocol service for dynamic types
const protocol = await this.resolveService('protocol');
if (protocol && typeof protocol.getMetaTypes === 'function') {
const result = await protocol.getMetaTypes({});
return { handled: true, response: this.success(result) };
}
// Fallback: ask broker for registered types
if (broker) {
try {
const data = await broker.call('metadata.types', {}, { request: context.request });
return { handled: true, response: this.success(data) };
} catch {
// fall through to hardcoded defaults
}
}
return { handled: true, response: this.success({ types: ['object', 'app', 'plugin'] }) };
}
return { handled: false };
}
/**
* Handles Data requests
* path: sub-path after /data/ (e.g. "contacts", "contacts/123", "contacts/query")
*/
async handleData(path: string, method: string, body: any, query: any, context: HttpProtocolContext): Promise<HttpDispatcherResult> {
const broker = this.ensureBroker();
const parts = path.replace(/^\/+/, '').split('/');
const objectName = parts[0];
if (!objectName) {
return { handled: true, response: this.error('Object name required', 400) };
}
const m = method.toUpperCase();
// 1. Custom Actions (query, batch)
if (parts.length > 1) {
const action = parts[1];
// POST /data/:object/query
if (action === 'query' && m === 'POST') {
// Spec: broker returns FindDataResponse = { object, records, total?, hasMore? }
const result = await broker.call('data.query', { object: objectName, ...body }, { request: context.request });
return { handled: true, response: this.success(result) };
}
// POST /data/:object/batch
if (action === 'batch' && m === 'POST') {
const result = await broker.call('data.batch', { object: objectName, ...body }, { request: context.request });
return { handled: true, response: this.success(result) };
}
// GET /data/:object/:id
if (parts.length === 2 && m === 'GET') {
const id = parts[1];
// Spec: Only select/expand are allowlisted query params for GET by ID.
// All other query parameters are discarded to prevent parameter pollution.
const { select, expand } = query || {};
const allowedParams: Record<string, unknown> = {};
if (select != null) allowedParams.select = select;
if (expand != null) allowedParams.expand = expand;
// Spec: broker returns GetDataResponse = { object, id, record }
const result = await broker.call('data.get', { object: objectName, id, ...allowedParams }, { request: context.request });
return { handled: true, response: this.success(result) };
}
// PATCH /data/:object/:id
if (parts.length === 2 && m === 'PATCH') {
const id = parts[1];
// Spec: broker returns UpdateDataResponse = { object, id, record }
const result = await broker.call('data.update', { object: objectName, id, data: body }, { request: context.request });
return { handled: true, response: this.success(result) };
}
// DELETE /data/:object/:id
if (parts.length === 2 && m === 'DELETE') {
const id = parts[1];
// Spec: broker returns DeleteDataResponse = { object, id, deleted }
const result = await broker.call('data.delete', { object: objectName, id }, { request: context.request });
return { handled: true, response: this.success(result) };
}
} else {
// GET /data/:object (List)
if (m === 'GET') {
// ── Normalize HTTP transport params → Spec canonical (QueryAST) ──
// HTTP GET query params use transport-level names (filter, sort, top,
// skip, select, expand) which are normalized here to canonical
// QueryAST field names (where, orderBy, limit, offset, fields,
// expand) before forwarding to the broker layer.
// The protocol.ts findData() method performs a deeper normalization
// pass, but pre-normalizing here ensures the broker always receives
// Spec-canonical keys.
const normalized: Record<string, unknown> = { ...query };
// filter/filters → where
// Note: `filter` is the canonical HTTP *transport* parameter name
// (see HttpFindQueryParamsSchema). It is normalized here to the
// canonical *QueryAST* field name `where` before broker dispatch.
// `filters` (plural) is a deprecated alias for `filter`.
if (normalized.filter != null || normalized.filters != null) {
normalized.where = normalized.where ?? normalized.filter ?? normalized.filters;
delete normalized.filter;
delete normalized.filters;
}
// select → fields
if (normalized.select != null && normalized.fields == null) {
normalized.fields = normalized.select;
delete normalized.select;
}
// sort → orderBy
if (normalized.sort != null && normalized.orderBy == null) {
normalized.orderBy = normalized.sort;
delete normalized.sort;
}
// top → limit
if (normalized.top != null && normalized.limit == null) {
normalized.limit = normalized.top;
delete normalized.top;
}
// skip → offset
if (normalized.skip != null && normalized.offset == null) {
normalized.offset = normalized.skip;
delete normalized.skip;
}
// Spec: broker returns FindDataResponse = { object, records, total?, hasMore? }
const result = await broker.call('data.query', { object: objectName, query: normalized }, { request: context.request });
return { handled: true, response: this.success(result) };
}
// POST /data/:object (Create)
if (m === 'POST') {
// Spec: broker returns CreateDataResponse = { object, id, record }
const result = await broker.call('data.create', { object: objectName, data: body }, { request: context.request });
const res = this.success(result);
res.status = 201;
return { handled: true, response: res };
}
}
return { handled: false };
}
/**
* Handles Analytics requests
* path: sub-path after /analytics/
*/
async handleAnalytics(path: string, method: string, body: any, _context: HttpProtocolContext): Promise<HttpDispatcherResult> {
const analyticsService = await this.getService(CoreServiceName.enum.analytics);
if (!analyticsService) return { handled: false }; // 404 handled by caller if unhandled
const m = method.toUpperCase();
const subPath = path.replace(/^\/+/, '');
// POST /analytics/query
if (subPath === 'query' && m === 'POST') {
const result = await analyticsService.query(body);
return { handled: true, response: this.success(result) };
}
// GET /analytics/meta
if (subPath === 'meta' && m === 'GET') {
const result = await analyticsService.getMeta();
return { handled: true, response: this.success(result) };
}
// POST /analytics/sql (Dry-run or debug)
if (subPath === 'sql' && m === 'POST') {
// Assuming service has generateSql method
const result = await analyticsService.generateSql(body);
return { handled: true, response: this.success(result) };
}
return { handled: false };
}
/**
* Handles i18n requests
* path: sub-path after /i18n/
*
* Routes:
* GET /locales → getLocales
* GET /translations/:locale → getTranslations (locale from path)
* GET /translations?locale=xx → getTranslations (locale from query)
* GET /labels/:object/:locale → getFieldLabels (both from path)
* GET /labels/:object?locale=xx → getFieldLabels (locale from query)
*/
async handleI18n(path: string, method: string, query: any, _context: HttpProtocolContext): Promise<HttpDispatcherResult> {
const i18nService = await this.getService(CoreServiceName.enum.i18n);
if (!i18nService) return { handled: true, response: this.error('i18n service not available', 501) };
const m = method.toUpperCase();
const parts = path.replace(/^\/+/, '').split('/').filter(Boolean);
if (m !== 'GET') return { handled: false };
// GET /i18n/locales
if (parts[0] === 'locales' && parts.length === 1) {
const locales = i18nService.getLocales();
return { handled: true, response: this.success({ locales }) };
}
// GET /i18n/translations/:locale OR /i18n/translations?locale=xx
if (parts[0] === 'translations') {
const locale = parts[1] ? decodeURIComponent(parts[1]) : query?.locale;
if (!locale) return { handled: true, response: this.error('Missing locale parameter', 400) };
let translations = i18nService.getTranslations(locale);
// Locale fallback: try resolving to an available locale when
// the exact code yields empty translations (e.g. zh → zh-CN).
if (Object.keys(translations).length === 0) {
const availableLocales = typeof i18nService.getLocales === 'function'
? i18nService.getLocales() : [];
const resolved = resolveLocale(locale, availableLocales);
if (resolved && resolved !== locale) {
translations = i18nService.getTranslations(resolved);
return { handled: true, response: this.success({ locale: resolved, requestedLocale: locale, translations }) };
}
}
return { handled: true, response: this.success({ locale, translations }) };
}
// GET /i18n/labels/:object/:locale OR /i18n/labels/:object?locale=xx
if (parts[0] === 'labels' && parts.length >= 2) {
const objectName = decodeURIComponent(parts[1]);
let locale = parts[2] ? decodeURIComponent(parts[2]) : query?.locale;
if (!locale) return { handled: true, response: this.error('Missing locale parameter', 400) };
// Locale fallback for labels endpoint
const availableLocales = typeof i18nService.getLocales === 'function'
? i18nService.getLocales() : [];
const resolved = resolveLocale(locale, availableLocales);
if (resolved) locale = resolved;
if (typeof i18nService.getFieldLabels === 'function') {
const labels = i18nService.getFieldLabels(objectName, locale);
return { handled: true, response: this.success({ object: objectName, locale, labels }) };
}
// Fallback: derive field labels from full translation bundle
const translations = i18nService.getTranslations(locale);
const prefix = `o.${objectName}.fields.`;
const labels: Record<string, string> = {};
for (const [key, value] of Object.entries(translations)) {
if (key.startsWith(prefix)) {
labels[key.substring(prefix.length)] = value as string;
}
}
return { handled: true, response: this.success({ object: objectName, locale, labels }) };
}
return { handled: false };
}
/**
* Handles Package Management requests
*
* REST Endpoints:
* - GET /packages → list all installed packages
* - GET /packages/:id → get a specific package
* - POST /packages → install a new package
* - DELETE /packages/:id → uninstall a package
* - PATCH /packages/:id/enable → enable a package
* - PATCH /packages/:id/disable → disable a package
* - POST /packages/:id/publish → publish a package (metadata snapshot)
* - POST /packages/:id/revert → revert a package to last published state
*
* Uses ObjectQL SchemaRegistry directly (via the 'objectql' service)
* with broker fallback for backward compatibility.
*/
async handlePackages(path: string, method: string, body: any, query: any, context: HttpProtocolContext): Promise<HttpDispatcherResult> {
const m = method.toUpperCase();
const parts = path.replace(/^\/+/, '').split('/').filter(Boolean);
// Try to get SchemaRegistry from the ObjectQL service
const qlService = await this.getObjectQLService();
const registry = qlService?.registry;
// If no registry available, try broker as fallback
if (!registry) {
if (this.kernel.broker) {
return this.handlePackagesViaBroker(parts, m, body, query, context);
}
return { handled: true, response: this.error('Package service not available', 503) };
}
try {
// GET /packages → list packages
if (parts.length === 0 && m === 'GET') {
let packages = registry.getAllPackages();
// Apply optional filters
if (query?.status) {
packages = packages.filter((p: any) => p.status === query.status);
}
if (query?.type) {
packages = packages.filter((p: any) => p.manifest?.type === query.type);
}
return { handled: true, response: this.success({ packages, total: packages.length }) };
}
// POST /packages → install package
if (parts.length === 0 && m === 'POST') {
const pkg = registry.installPackage(body.manifest || body, body.settings);
const res = this.success(pkg);
res.status = 201;
return { handled: true, response: res };
}
// PATCH /packages/:id/enable
if (parts.length === 2 && parts[1] === 'enable' && m === 'PATCH') {
const id = decodeURIComponent(parts[0]);
const pkg = registry.enablePackage(id);
if (!pkg) return { handled: true, response: this.error(`Package '${id}' not found`, 404) };
return { handled: true, response: this.success(pkg) };
}
// PATCH /packages/:id/disable
if (parts.length === 2 && parts[1] === 'disable' && m === 'PATCH') {
const id = decodeURIComponent(parts[0]);
const pkg = registry.disablePackage(id);
if (!pkg) return { handled: true, response: this.error(`Package '${id}' not found`, 404) };
return { handled: true, response: this.success(pkg) };
}
// POST /packages/:id/publish → publish package metadata
if (parts.length === 2 && parts[1] === 'publish' && m === 'POST') {
const id = decodeURIComponent(parts[0]);
const metadataService = await this.getService(CoreServiceName.enum.metadata);
if (metadataService && typeof (metadataService as any).publishPackage === 'function') {
const result = await (metadataService as any).publishPackage(id, body || {});
return { handled: true, response: this.success(result) };
}
// Broker fallback
if (this.kernel.broker) {
const result = await this.kernel.broker.call('metadata.publishPackage', { packageId: id, ...body }, { request: context.request });
return { handled: true, response: this.success(result) };
}
return { handled: true, response: this.error('Metadata service not available', 503) };
}
// POST /packages/:id/revert → revert package to last published state
if (parts.length === 2 && parts[1] === 'revert' && m === 'POST') {
const id = decodeURIComponent(parts[0]);
const metadataService = await this.getService(CoreServiceName.enum.metadata);
if (metadataService && typeof (metadataService as any).revertPackage === 'function') {
await (metadataService as any).revertPackage(id);
return { handled: true, response: this.success({ success: true }) };
}
// Broker fallback
if (this.kernel.broker) {
await this.kernel.broker.call('metadata.revertPackage', { packageId: id }, { request: context.request });
return { handled: true, response: this.success({ success: true }) };
}
return { handled: true, response: this.error('Metadata service not available', 503) };
}
// GET /packages/:id → get package
if (parts.length === 1 && m === 'GET') {
const id = decodeURIComponent(parts[0]);
const pkg = registry.getPackage(id);
if (!pkg) return { handled: true, response: this.error(`Package '${id}' not found`, 404) };
return { handled: true, response: this.success(pkg) };
}
// DELETE /packages/:id → uninstall package
if (parts.length === 1 && m === 'DELETE') {
const id = decodeURIComponent(parts[0]);
const success = registry.uninstallPackage(id);
if (!success) return { handled: true, response: this.error(`Package '${id}' not found`, 404) };
return { handled: true, response: this.success({ success: true }) };
}
} catch (e: any) {
return { handled: true, response: this.error(e.message, e.statusCode || 500) };
}
return { handled: false };
}
/**
* Fallback: handle packages via broker (for backward compatibility)
*/
private async handlePackagesViaBroker(parts: string[], m: string, body: any, query: any, context: HttpProtocolContext): Promise<HttpDispatcherResult> {
const broker = this.kernel.broker;
try {
if (parts.length === 0 && m === 'GET') {
const result = await broker.call('package.list', query || {}, { request: context.request });
return { handled: true, response: this.success(result) };
}
if (parts.length === 0 && m === 'POST') {
const result = await broker.call('package.install', body, { request: context.request });
const res = this.success(result);
res.status = 201;
return { handled: true, response: res };
}
if (parts.length === 2 && parts[1] === 'enable' && m === 'PATCH') {
const id = decodeURIComponent(parts[0]);
const result = await broker.call('package.enable', { id }, { request: context.request });
return { handled: true, response: this.success(result) };
}
if (parts.length === 2 && parts[1] === 'disable' && m === 'PATCH') {
const id = decodeURIComponent(parts[0]);
const result = await broker.call('package.disable', { id }, { request: context.request });
return { handled: true, response: this.success(result) };
}
if (parts.length === 1 && m === 'GET') {
const id = decodeURIComponent(parts[0]);
const result = await broker.call('package.get', { id }, { request: context.request });
return { handled: true, response: this.success(result) };
}
if (parts.length === 1 && m === 'DELETE') {
const id = decodeURIComponent(parts[0]);
const result = await broker.call('package.uninstall', { id }, { request: context.request });
return { handled: true, response: this.success(result) };
}
} catch (e: any) {
return { handled: true, response: this.error(e.message, e.statusCode || 500) };
}
return { handled: false };
}
/**
* Handles Storage requests
* path: sub-path after /storage/
*/
async handleStorage(path: string, method: string, file: any, context: HttpProtocolContext): Promise<HttpDispatcherResult> {
const storageService = await this.getService(CoreServiceName.enum['file-storage']) || this.kernel.services?.['file-storage'];
if (!storageService) {
return { handled: true, response: this.error('File storage not configured', 501) };
}
const m = method.toUpperCase();
const parts = path.replace(/^\/+/, '').split('/');
// POST /storage/upload
if (parts[0] === 'upload' && m === 'POST') {
if (!file) {
return { handled: true, response: this.error('No file provided', 400) };
}
const result = await storageService.upload(file, { request: context.request });
return { handled: true, response: this.success(result) };
}
// GET /storage/file/:id
if (parts[0] === 'file' && parts[1] && m === 'GET') {
const id = parts[1];
const result = await storageService.download(id, { request: context.request });
// Result can be URL (redirect), Stream/Blob, or metadata
if (result.url && result.redirect) {
// Must be handled by adapter to do actual redirect
return { handled: true, result: { type: 'redirect', url: result.url } };
}
if (result.stream) {
// Must be handled by adapter to pipe stream
return {
handled: true,
result: {
type: 'stream',
stream: result.stream,
headers: {
'Content-Type': result.mimeType || 'application/octet-stream',
'Content-Length': result.size
}
}
};
}
return { handled: true, response: this.success(result) };
}
return { handled: false };