-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathprotocol.ts
More file actions
2010 lines (1864 loc) · 88.6 KB
/
protocol.ts
File metadata and controls
2010 lines (1864 loc) · 88.6 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 { ObjectStackProtocol } from '@objectstack/spec/api';
import { IDataEngine } from '@objectstack/core';
import type { ObjectQL } from './engine.js';
import type {
BatchUpdateRequest,
BatchUpdateResponse,
UpdateManyDataRequest,
DeleteManyDataRequest
} from '@objectstack/spec/api';
import type { MetadataCacheRequest, MetadataCacheResponse, ServiceInfo, ApiRoutes, WellKnownCapabilities } from '@objectstack/spec/api';
import type { IFeedService } from '@objectstack/spec/contracts';
import { parseFilterAST, isFilterAST } from '@objectstack/spec/data';
import { PLURAL_TO_SINGULAR, SINGULAR_TO_PLURAL } from '@objectstack/spec/shared';
import { ListViewSchema, FormViewSchema, DashboardSchema } from '@objectstack/spec/ui';
import { DEFAULT_METADATA_TYPE_REGISTRY } from '@objectstack/spec/kernel';
import { z } from 'zod';
/**
* Zod schemas used to validate overlay items before they are persisted into
* `sys_metadata` by {@link ObjectStackProtocolImplementation.saveMetaItem}.
*
* Some types (notably `view`) are *not* a single schema but a discriminated
* family — a grid/kanban/calendar list view vs. a simple/tabbed/wizard form
* view. We dispatch to the right schema based on the `type` discriminant
* rather than using `z.union([...])`, which would collapse all branch errors
* into an opaque "Invalid input" union error.
*
* Validation policy:
* - `safeParse` is used so we can craft a 422 with structured `issues`.
* - We do NOT replace the persisted document with `parsed.data`; the
* original payload is stored verbatim so Studio-only auxiliary fields
* (e.g. `isPinned`, `isDefault`, `sortOrder`) survive the round-trip.
* - Schemas are referenced lazily through the Spec's `lazySchema` Proxy,
* so importing this module does not trigger eager Zod construction.
* - Types without a registered schema (e.g. `app`, `package`) fall through
* unvalidated for backwards compatibility — they were never enforced
* historically and existing control-plane writes rely on the lenient
* behaviour.
*/
const FORM_VIEW_TYPES = new Set(['simple', 'tabbed', 'wizard', 'split', 'drawer', 'modal']);
function resolveOverlaySchema(type: string, item: unknown): z.ZodTypeAny | null {
const singular = PLURAL_TO_SINGULAR[type] ?? type;
switch (singular) {
case 'view': {
// Form views and list views share the `view` overlay type. Pick
// the right Zod schema by inspecting the discriminant. Defaults
// to ListViewSchema (matches the ListViewSchema `type.default('grid')`).
const t = (item && typeof item === 'object' && 'type' in item)
? String((item as any).type)
: undefined;
return t && FORM_VIEW_TYPES.has(t) ? FormViewSchema : ListViewSchema;
}
case 'dashboard':
return DashboardSchema;
default:
return null;
}
}
/**
* Simple hash function for ETag generation (browser-compatible)
* Uses a basic hash algorithm instead of crypto.createHash
*/
function simpleHash(str: string): string {
let hash = 0;
for (let i = 0; i < str.length; i++) {
const char = str.charCodeAt(i);
hash = ((hash << 5) - hash) + char;
hash = hash & hash; // Convert to 32bit integer
}
return Math.abs(hash).toString(16);
}
/**
* Service Configuration for Discovery
* Maps service names to their routes and plugin providers
*/
const SERVICE_CONFIG: Record<string, { route: string; plugin: string }> = {
auth: { route: '/api/v1/auth', plugin: 'plugin-auth' },
automation: { route: '/api/v1/automation', plugin: 'plugin-automation' },
cache: { route: '/api/v1/cache', plugin: 'plugin-redis' },
queue: { route: '/api/v1/queue', plugin: 'plugin-bullmq' },
job: { route: '/api/v1/jobs', plugin: 'job-scheduler' },
ui: { route: '/api/v1/ui', plugin: 'ui-plugin' },
workflow: { route: '/api/v1/workflow', plugin: 'plugin-workflow' },
realtime: { route: '/api/v1/realtime', plugin: 'plugin-realtime' },
notification: { route: '/api/v1/notifications', plugin: 'plugin-notifications' },
ai: { route: '/api/v1/ai', plugin: 'plugin-ai' },
i18n: { route: '/api/v1/i18n', plugin: 'service-i18n' },
graphql: { route: '/graphql', plugin: 'plugin-graphql' }, // GraphQL uses /graphql by convention (not versioned REST)
'file-storage': { route: '/api/v1/storage', plugin: 'plugin-storage' },
search: { route: '/api/v1/search', plugin: 'plugin-search' },
};
export class ObjectStackProtocolImplementation implements ObjectStackProtocol {
private engine: ObjectQL;
private getServicesRegistry?: () => Map<string, any>;
private getFeedService?: () => IFeedService | undefined;
/**
* Project scope applied to sys_metadata reads/writes. When undefined
* (single-kernel deployments), rows land in / come from the
* platform-global bucket (`project_id IS NULL`). When set, every
* saveMetaItem insert/update and loadMetaFromDb query is filtered by
* `project_id = projectId`, so per-project kernels see only their own
* metadata even if several projects share the same physical database.
*/
private projectId?: string;
constructor(
engine: IDataEngine,
getServicesRegistry?: () => Map<string, any>,
getFeedService?: () => IFeedService | undefined,
projectId?: string,
) {
this.engine = engine as ObjectQL;
this.getServicesRegistry = getServicesRegistry;
this.getFeedService = getFeedService;
this.projectId = projectId;
}
/**
* One-time guard for ensuring the overlay-uniqueness UNIQUE INDEX exists
* on `sys_metadata`. ADR-0005: scopes overlays by
* `(type, name, organization_id, project_id, scope)` for active rows only.
* Idempotent SQL — safe to attempt on every protocol instance.
*
* Inlined here (rather than importing from @objectstack/metadata/migrations)
* to avoid a circular dependency: metadata already depends on objectql.
*/
private overlayIndexEnsured = false;
private async ensureOverlayIndex(): Promise<void> {
if (this.overlayIndexEnsured) return;
this.overlayIndexEnsured = true;
try {
const engineAny = this.engine as any;
let driver: any = engineAny?.driver ?? engineAny?.getDriver?.();
if (!driver && engineAny?.drivers instanceof Map) {
for (const candidate of engineAny.drivers.values()) {
if (
candidate &&
(typeof (candidate as any).raw === 'function' ||
typeof (candidate as any).execute === 'function')
) {
driver = candidate;
break;
}
}
}
if (!driver) return;
const exec = async (sql: string): Promise<void> => {
if (typeof (driver as any).raw === 'function') {
await (driver as any).raw(sql);
} else if (typeof (driver as any).execute === 'function') {
await (driver as any).execute(sql);
} else {
throw new Error('driver has neither raw nor execute');
}
};
const partialSql =
"CREATE UNIQUE INDEX IF NOT EXISTS idx_sys_metadata_overlay_active " +
"ON sys_metadata (type, name, organization_id, project_id, scope) " +
"WHERE state = 'active'";
const fallbackSql =
"CREATE INDEX IF NOT EXISTS idx_sys_metadata_overlay_active " +
"ON sys_metadata (type, name, organization_id, project_id, scope)";
try {
await exec(partialSql);
} catch (err: any) {
const msg = err instanceof Error ? err.message : String(err);
if (/partial|where clause|syntax/i.test(msg)) {
try {
await exec(fallbackSql);
} catch {
// ignore — non-essential optimization
}
}
// "already exists" or anything else: best-effort
}
} catch {
// ignore — index is an optimization, not a correctness invariant
}
}
/**
* Exposes the project scope the protocol is bound to. Consumers like
* the HTTP dispatcher use this to decide whether to trust the process-
* wide SchemaRegistry or whether they must route a read through the
* protocol's project_id-filtered lookup.
*/
getProjectId(): string | undefined {
return this.projectId;
}
private requireFeedService(): IFeedService {
const svc = this.getFeedService?.();
if (!svc) {
throw new Error('Feed service not available. Install and register service-feed to enable feed operations.');
}
return svc;
}
async getDiscovery() {
// Get registered services from kernel if available
const registeredServices = this.getServicesRegistry ? this.getServicesRegistry() : new Map();
// Build dynamic service info with proper typing
const services: Record<string, ServiceInfo> = {
// --- Kernel-provided (objectql is an example kernel implementation) ---
metadata: { enabled: true, status: 'available' as const, route: '/api/v1/meta', provider: 'objectql' },
data: { enabled: true, status: 'available' as const, route: '/api/v1/data', provider: 'objectql' },
analytics: { enabled: true, status: 'available' as const, route: '/api/v1/analytics', provider: 'objectql' },
};
// Check which services are actually registered
for (const [serviceName, config] of Object.entries(SERVICE_CONFIG)) {
if (registeredServices.has(serviceName)) {
// Service is registered and available
services[serviceName] = {
enabled: true,
status: 'available' as const,
route: config.route,
provider: config.plugin,
};
} else {
// Service is not registered
services[serviceName] = {
enabled: false,
status: 'unavailable' as const,
message: `Install ${config.plugin} to enable`,
};
}
}
// Build routes from services — a flat convenience map for client routing
const serviceToRouteKey: Record<string, keyof ApiRoutes> = {
auth: 'auth',
automation: 'automation',
ui: 'ui',
workflow: 'workflow',
realtime: 'realtime',
notification: 'notifications',
ai: 'ai',
i18n: 'i18n',
graphql: 'graphql',
'file-storage': 'storage',
};
const optionalRoutes: Partial<ApiRoutes> = {
analytics: '/api/v1/analytics',
};
// Add routes for available plugin services
for (const [serviceName, config] of Object.entries(SERVICE_CONFIG)) {
if (registeredServices.has(serviceName)) {
const routeKey = serviceToRouteKey[serviceName];
if (routeKey) {
optionalRoutes[routeKey] = config.route;
}
}
}
// Add feed service status
if (registeredServices.has('feed')) {
services['feed'] = {
enabled: true,
status: 'available' as const,
route: '/api/v1/data',
provider: 'service-feed',
};
} else {
services['feed'] = {
enabled: false,
status: 'unavailable' as const,
message: 'Install service-feed to enable',
};
}
const routes: ApiRoutes = {
data: '/api/v1/data',
metadata: '/api/v1/meta',
...optionalRoutes,
};
// Build well-known capabilities from registered services.
// DiscoverySchema defines capabilities as Record<string, { enabled, features?, description? }>
// (hierarchical format). We also keep a flat WellKnownCapabilities for backward compat.
const wellKnown: WellKnownCapabilities = {
feed: registeredServices.has('feed'),
comments: registeredServices.has('feed'),
automation: registeredServices.has('automation'),
cron: registeredServices.has('job'),
search: registeredServices.has('search'),
export: registeredServices.has('automation') || registeredServices.has('queue'),
chunkedUpload: registeredServices.has('file-storage'),
};
// Convert flat booleans → hierarchical capability objects
const capabilities: Record<string, { enabled: boolean; description?: string }> = {};
for (const [key, enabled] of Object.entries(wellKnown)) {
capabilities[key] = { enabled };
}
return {
version: '1.0',
apiName: 'ObjectStack API',
routes,
services,
capabilities,
};
}
async getMetaTypes() {
const schemaTypes = this.engine.registry.getRegisteredTypes();
// Also include types from MetadataService (runtime-registered: agent, tool, etc.)
let runtimeTypes: string[] = [];
try {
const services = this.getServicesRegistry?.();
const metadataService = services?.get('metadata');
if (metadataService && typeof metadataService.getRegisteredTypes === 'function') {
runtimeTypes = await metadataService.getRegisteredTypes();
}
} catch {
// MetadataService not available
}
const allTypes = Array.from(new Set([...schemaTypes, ...runtimeTypes]));
return { types: allTypes };
}
async getMetaItems(request: { type: string; packageId?: string }) {
const { packageId } = request;
let items: unknown[] = [];
// Unscoped kernels (control plane): read everything from SchemaRegistry.
// Scoped (project) kernels: skip user-project entries in SchemaRegistry to
// prevent cross-project leakage, but DO include scope:'system' packages
// (plugin-auth, plugin-security, plugin-audit, …) — those are globally
// shared and must be visible at every project's meta endpoint.
if (this.projectId === undefined) {
items = [...this.engine.registry.listItems(request.type, packageId)];
// Normalize singular/plural using explicit mapping
if (items.length === 0) {
const alt = PLURAL_TO_SINGULAR[request.type] ?? SINGULAR_TO_PLURAL[request.type];
if (alt) items = [...this.engine.registry.listItems(alt, packageId)];
}
} else {
// For project kernels: the SchemaRegistry is owned by THIS
// kernel's ObjectQL instance (not shared across projects in the
// process), so we can safely include every package — system
// plugins (auth/security/audit) and the project's own app
// package alike. The `_packageId` tag added by `listItems`
// (registry.ts) is preserved for the sidebar to compute the
// correct navigation URL.
items = [...this.engine.registry.listItems(request.type, packageId)];
if (items.length === 0) {
const alt = PLURAL_TO_SINGULAR[request.type] ?? SINGULAR_TO_PLURAL[request.type];
if (alt) items = [...this.engine.registry.listItems(alt, packageId)];
}
}
// Always consult the DB so metadata persisted by the seeder /
// bulkRegister shows up even when the registry already has unrelated
// entries (the previous fallback-only logic meant project metadata
// was never surfaced whenever system-bridged items populated the
// registry). Deduplicate against whatever the registry returned.
//
// ADR-0005 Phase 4: project kernels also consult sys_metadata so that
// customer-saved view/dashboard overlays show up in list endpoints
// alongside the artifact-loaded items.
try {
const whereClause: Record<string, unknown> = {
type: request.type,
state: 'active',
// Always filter by project_id: project kernels use their projectId,
// control-plane kernels use NULL (global scope only).
project_id: this.projectId ?? null,
};
if (packageId) whereClause._packageId = packageId;
let records = await this.engine.find('sys_metadata', { where: whereClause });
if ((!records || records.length === 0)) {
// Try alternate type name in DB using explicit mapping
const alt = PLURAL_TO_SINGULAR[request.type] ?? SINGULAR_TO_PLURAL[request.type];
if (alt) {
const altWhere: Record<string, unknown> = { type: alt, state: 'active', project_id: this.projectId ?? null };
if (packageId) altWhere._packageId = packageId;
records = await this.engine.find('sys_metadata', { where: altWhere });
}
}
if (records && records.length > 0) {
const byName = new Map<string, any>();
for (const existing of items) {
const entry = existing as any;
if (entry && typeof entry === 'object' && 'name' in entry) {
byName.set(entry.name, entry);
}
}
for (const record of records) {
const data = typeof record.metadata === 'string'
? JSON.parse(record.metadata)
: record.metadata;
if (data && typeof data === 'object' && 'name' in data) {
byName.set(data.name, data);
}
// Only hydrate the global registry for unscoped calls —
// scoped project entries must not leak process-wide.
if (this.projectId === undefined) {
this.engine.registry.registerItem(request.type, data, 'name' as any);
}
}
items = Array.from(byName.values());
}
} catch {
// DB not available — fall through with whatever we already have.
}
// Merge with MetadataService (runtime-registered items: agents, tools, etc.)
try {
const services = this.getServicesRegistry?.();
const metadataService = services?.get('metadata');
if (metadataService && typeof metadataService.list === 'function') {
let runtimeItems = await metadataService.list(request.type);
// When filtering by packageId, only include runtime items that
// belong to the requested package. MetadataService.list() returns
// items from ALL packages, so we must filter here to respect the
// package scope requested by the caller (e.g., Studio sidebar).
if (packageId && runtimeItems && runtimeItems.length > 0) {
runtimeItems = runtimeItems.filter((item: any) => item?._packageId === packageId);
}
if (runtimeItems && runtimeItems.length > 0) {
// Merge, avoiding duplicates by name
const itemMap = new Map<string, any>();
for (const item of items) {
const entry = item as any;
if (entry && typeof entry === 'object' && 'name' in entry) {
itemMap.set(entry.name, entry);
}
}
for (const item of runtimeItems) {
const entry = item as any;
if (entry && typeof entry === 'object' && 'name' in entry) {
// Do not overwrite entries already present in the
// map: those came from sys_metadata (customization
// overlays) or the SchemaRegistry and must win
// over the MetadataService's artifact baseline.
// Without this guard, saved per-org dashboard /
// view overlays disappear from list endpoints on
// refresh (detail endpoint kept showing the
// overlay because it uses a different code path).
if (!itemMap.has(entry.name)) {
itemMap.set(entry.name, entry);
}
}
}
items = Array.from(itemMap.values());
}
}
} catch {
// MetadataService not available or doesn't support this type
}
return {
type: request.type,
items
};
}
async getMetaItem(request: { type: string, name: string, packageId?: string }) {
let item: unknown;
// 1. Customization overlay lookup (sys_metadata).
// Per ADR-0005, overlay rows are the customer-managed delta and win
// over the artifact-loaded registry. Both project-kernel and
// control-plane modes participate (control-plane scope = NULL).
try {
const scopedWhere: Record<string, unknown> = {
type: request.type,
name: request.name,
state: 'active',
project_id: this.projectId ?? null,
};
const record = await this.engine.findOne('sys_metadata', { where: scopedWhere });
if (record) {
item = typeof record.metadata === 'string'
? JSON.parse(record.metadata)
: record.metadata;
} else {
// Try alternate type name using explicit singular/plural mapping
const alt = PLURAL_TO_SINGULAR[request.type] ?? SINGULAR_TO_PLURAL[request.type];
if (alt) {
const altWhere: Record<string, unknown> = {
type: alt,
name: request.name,
state: 'active',
project_id: this.projectId ?? null,
};
const altRecord = await this.engine.findOne('sys_metadata', { where: altWhere });
if (altRecord) {
item = typeof altRecord.metadata === 'string'
? JSON.parse(altRecord.metadata)
: altRecord.metadata;
}
}
}
} catch {
// DB not available — fall through to registry / MetadataService
}
// 2. In-memory SchemaRegistry (artifact-loaded out-of-box values).
// Both control-plane (unscoped) and project kernels consult the
// registry. The previous guard that skipped the registry for
// project kernels was meant to prevent cross-project leakage at
// the LIST level — but for a single-item lookup the kernel's own
// `engine.registry` is project-local (each ObjectQL instance has
// its own SchemaRegistry), so reading from it is safe and
// necessary. Without this, project-kernel callers of
// `GET /api/v1/meta/object/<name>` 404 even though the object is
// registered and visible via the list endpoint.
if (item === undefined) {
item = this.engine.registry.getItem(request.type, request.name);
if (item === undefined) {
const alt = PLURAL_TO_SINGULAR[request.type] ?? SINGULAR_TO_PLURAL[request.type];
if (alt) item = this.engine.registry.getItem(alt, request.name);
}
}
// 3. Fallback to MetadataService for runtime-registered items (agents, tools, etc.)
if (item === undefined) {
try {
const services = this.getServicesRegistry?.();
const metadataService = services?.get('metadata');
if (metadataService && typeof metadataService.get === 'function') {
item = await metadataService.get(request.type, request.name);
}
} catch {
// MetadataService not available
}
}
return {
type: request.type,
name: request.name,
item
};
}
async getUiView(request: { object: string, type: 'list' | 'form' }) {
const schema = this.engine.registry.getObject(request.object);
if (!schema) throw new Error(`Object ${request.object} not found`);
const fields = schema.fields || {};
const fieldKeys = Object.keys(fields);
if (request.type === 'list') {
// Intelligent Column Selection
// 1. Always include 'name' or name-like fields
// 2. Limit to 6 columns by default
const priorityFields = ['name', 'title', 'label', 'subject', 'email', 'status', 'type', 'category', 'created_at'];
let columns = fieldKeys.filter(k => priorityFields.includes(k));
// If few priority fields, add others until 5
if (columns.length < 5) {
const remaining = fieldKeys.filter(k => !columns.includes(k) && k !== 'id' && !fields[k].hidden);
columns = [...columns, ...remaining.slice(0, 5 - columns.length)];
}
// Sort columns by priority then alphabet or schema order
// For now, just keep them roughly in order they appear in schema or priority list
return {
list: {
type: 'grid' as const,
object: request.object,
label: schema.label || schema.name,
columns: columns.map(f => ({
field: f,
label: fields[f]?.label || f,
sortable: true
})),
sort: fields['created_at'] ? ([{ field: 'created_at', order: 'desc' }] as any) : undefined,
searchableFields: columns.slice(0, 3) // Make first few textual columns searchable
}
};
} else {
// Form View Generation
// Simple single-section layout for now
const formFields = fieldKeys
.filter(k => k !== 'id' && k !== 'created_at' && k !== 'updated_at' && !fields[k].hidden)
.map(f => ({
field: f,
label: fields[f]?.label,
required: fields[f]?.required,
readonly: fields[f]?.readonly,
type: fields[f]?.type,
// Default to 2 columns for most, 1 for textareas
colSpan: (fields[f]?.type === 'textarea' || fields[f]?.type === 'html') ? 2 : 1
}));
return {
form: {
type: 'simple' as const,
object: request.object,
label: `Edit ${schema.label || schema.name}`,
sections: [
{
label: 'General Information',
columns: 2 as const,
collapsible: false,
collapsed: false,
fields: formFields
}
]
}
};
}
}
async findData(request: { object: string, query?: any, context?: any }) {
const options: any = { ...request.query };
// Forward the dispatcher's ExecutionContext so RBAC/RLS middleware
// can apply per-request enforcement. The protocol layer is purely
// a normalizer — it must never strip security context.
if (request.context !== undefined) {
options.context = request.context;
}
// ====================================================================
// Normalize legacy params → QueryAST standard (where/fields/orderBy/offset/expand)
// ====================================================================
// Numeric fields — normalize top → limit, skip → offset
if (options.top != null) {
options.limit = Number(options.top);
delete options.top;
}
if (options.skip != null) {
options.offset = Number(options.skip);
delete options.skip;
}
if (options.limit != null) options.limit = Number(options.limit);
if (options.offset != null) options.offset = Number(options.offset);
// Select → fields: comma-separated string → array
if (typeof options.select === 'string') {
options.fields = options.select.split(',').map((s: string) => s.trim()).filter(Boolean);
} else if (Array.isArray(options.select)) {
options.fields = options.select;
}
if (options.select !== undefined) delete options.select;
// Sort/orderBy → orderBy: string → SortNode[] array
const sortValue = options.orderBy ?? options.sort;
if (typeof sortValue === 'string') {
const parsed = sortValue.split(',').map((part: string) => {
const trimmed = part.trim();
if (trimmed.startsWith('-')) {
return { field: trimmed.slice(1), order: 'desc' as const };
}
const [field, order] = trimmed.split(/\s+/);
return { field, order: (order?.toLowerCase() === 'desc' ? 'desc' : 'asc') as 'asc' | 'desc' };
}).filter((s: any) => s.field);
options.orderBy = parsed;
} else if (Array.isArray(sortValue)) {
options.orderBy = sortValue;
}
delete options.sort;
// Filter/filters/$filter → where: normalize all filter aliases
const filterValue = options.filter ?? options.filters ?? options.$filter ?? options.where;
delete options.filter;
delete options.filters;
delete options.$filter;
if (filterValue !== undefined) {
let parsedFilter = filterValue;
// JSON string → object
if (typeof parsedFilter === 'string') {
try { parsedFilter = JSON.parse(parsedFilter); } catch { /* keep as-is */ }
}
// Filter AST array → FilterCondition object
if (isFilterAST(parsedFilter)) {
parsedFilter = parseFilterAST(parsedFilter);
}
options.where = parsedFilter;
}
// Populate/expand/$expand → expand (Record<string, QueryAST>)
const populateValue = options.populate;
const expandValue = options.$expand ?? options.expand;
const expandNames: string[] = [];
if (typeof populateValue === 'string') {
expandNames.push(...populateValue.split(',').map((s: string) => s.trim()).filter(Boolean));
} else if (Array.isArray(populateValue)) {
expandNames.push(...populateValue);
}
if (!expandNames.length && expandValue) {
if (typeof expandValue === 'string') {
expandNames.push(...expandValue.split(',').map((s: string) => s.trim()).filter(Boolean));
} else if (Array.isArray(expandValue)) {
expandNames.push(...expandValue);
}
}
delete options.populate;
delete options.$expand;
// Clean up non-object expand (e.g. string) BEFORE the Record conversion
// below, so that populate-derived names can create the expand Record even
// when a legacy string expand was also present.
if (typeof options.expand !== 'object' || options.expand === null) {
delete options.expand;
}
// Only set expand if not already an object (advanced usage)
if (expandNames.length > 0 && !options.expand) {
options.expand = {} as Record<string, any>;
for (const rel of expandNames) {
options.expand[rel] = { object: rel };
}
}
// Boolean fields
for (const key of ['distinct', 'count']) {
if (options[key] === 'true') options[key] = true;
else if (options[key] === 'false') options[key] = false;
}
// Flat field filters: REST-style query params like ?id=abc&status=open
// After extracting all known query parameters, any remaining keys are
// treated as implicit field-level equality filters merged into `where`.
const knownParams = new Set([
'top', 'limit', 'offset',
'orderBy',
'fields',
'where',
'expand',
'distinct', 'count',
'aggregations', 'groupBy',
'search', 'context', 'cursor',
]);
if (!options.where) {
const implicitFilters: Record<string, unknown> = {};
for (const key of Object.keys(options)) {
if (!knownParams.has(key)) {
implicitFilters[key] = options[key];
delete options[key];
}
}
if (Object.keys(implicitFilters).length > 0) {
options.where = implicitFilters;
}
}
const records = await this.engine.find(request.object, options);
// Spec: FindDataResponseSchema — only `records` is returned.
// OData `value` adaptation (if needed) is handled in the HTTP dispatch layer.
return {
object: request.object,
records,
total: records.length,
hasMore: false
};
}
async getData(request: { object: string, id: string, expand?: string | string[], select?: string | string[], context?: any }) {
const queryOptions: any = {
where: { id: request.id }
};
if (request.context !== undefined) {
queryOptions.context = request.context;
}
// Support fields for single-record retrieval
if (request.select) {
queryOptions.fields = typeof request.select === 'string'
? request.select.split(',').map((s: string) => s.trim()).filter(Boolean)
: request.select;
}
// Support expand for single-record retrieval
if (request.expand) {
const expandNames = typeof request.expand === 'string'
? request.expand.split(',').map((s: string) => s.trim()).filter(Boolean)
: request.expand;
queryOptions.expand = {} as Record<string, any>;
for (const rel of expandNames) {
queryOptions.expand[rel] = { object: rel };
}
}
const result = await this.engine.findOne(request.object, queryOptions);
if (result) {
return {
object: request.object,
id: request.id,
record: result
};
}
throw new Error(`Record ${request.id} not found in ${request.object}`);
}
async createData(request: { object: string, data: any, context?: any }) {
const result = await this.engine.insert(
request.object,
request.data,
request.context !== undefined ? { context: request.context } as any : undefined,
);
return {
object: request.object,
id: result.id,
record: result
};
}
async updateData(request: { object: string, id: string, data: any, context?: any }) {
const opts: any = { where: { id: request.id } };
if (request.context !== undefined) opts.context = request.context;
const result = await this.engine.update(request.object, request.data, opts);
return {
object: request.object,
id: request.id,
record: result
};
}
async deleteData(request: { object: string, id: string, context?: any }) {
const opts: any = { where: { id: request.id } };
if (request.context !== undefined) opts.context = request.context;
await this.engine.delete(request.object, opts);
return {
object: request.object,
id: request.id,
success: true
};
}
// ==========================================
// Global Search (M10.5)
// ==========================================
/**
* Cross-object substring search across all registered objects that opt in
* via `enable.searchable !== false` and `enable.apiEnabled !== false`.
* Searches text-like fields (text/textarea/email/url/phone/markdown/html/string)
* whose `searchable: true` flag is set, falling back to the object's
* `displayNameField` (or `name`) when no fields are explicitly searchable.
*
* The query is split into whitespace-separated terms; each term must match
* (case-insensitive LIKE) at least one searchable field. RBAC/RLS is
* enforced by forwarding the caller's `context` to `engine.find` so users
* only see records they are entitled to read.
*/
async searchAll(request: {
q: string;
objects?: string[];
limit?: number;
perObject?: number;
context?: any;
}): Promise<{
query: string;
hits: Array<{
object: string;
id: string;
title: string;
snippet?: string;
record: any;
}>;
totalObjects: number;
totalHits: number;
truncated: boolean;
}> {
const q = (request.q ?? '').trim();
if (!q) {
return { query: '', hits: [], totalObjects: 0, totalHits: 0, truncated: false };
}
const overallLimit = Math.max(1, Math.min(100, Number(request.limit ?? 20)));
const perObject = Math.max(1, Math.min(25, Number(request.perObject ?? 5)));
const objectsFilter = request.objects && request.objects.length
? new Set(request.objects)
: null;
// Tokenise: each token must match (LIKE %term%) at least one searchable field
const terms = q.split(/\s+/).filter(Boolean).slice(0, 8);
const allObjects = (this.engine as any).registry?.getAllObjects?.() ?? [];
const hits: Array<{ object: string; id: string; title: string; snippet?: string; record: any }> = [];
let objectsScanned = 0;
for (const obj of allObjects) {
if (hits.length >= overallLimit) break;
if (!obj?.name) continue;
if (objectsFilter && !objectsFilter.has(obj.name)) continue;
// Skip platform/system tables and opt-outs
const enable = obj.enable ?? {};
if (enable.searchable === false) continue;
if (enable.apiEnabled === false) continue;
// Skip noisy system tables by name prefix
if (obj.name.startsWith('sys_audit_log')
|| obj.name.startsWith('sys_activity')
|| obj.name.startsWith('sys_session')
|| obj.name.startsWith('sys_presence')
|| obj.name.startsWith('sys_metadata')
|| obj.name.startsWith('sys_account')) {
continue;
}
const fieldsRaw = obj.fields;
const fields: Array<{ name: string; type: string; searchable?: boolean }> =
Array.isArray(fieldsRaw)
? fieldsRaw
: (fieldsRaw && typeof fieldsRaw === 'object'
? Object.entries(fieldsRaw).map(([name, f]: [string, any]) => ({ name, ...(f || {}) }))
: []);
const TEXT_TYPES = new Set(['text', 'textarea', 'string', 'email', 'url', 'phone', 'markdown', 'html']);
const fieldByName = new Map(fields.map(f => [f.name, f]));
const hasField = (n: string) => fieldByName.has(n);
// Resolve title for a record using titleFormat → displayNameField →
// common conventional fields → id. titleFormat supports simple
// `{field}` placeholders (the `template` dialect); unresolved
// placeholders fall through to the next strategy.
const titleFormatSource = (obj.titleFormat && (obj.titleFormat.source || obj.titleFormat))
|| undefined;
const renderTitle = (row: any): string => {
if (typeof titleFormatSource === 'string') {
let allResolved = true;
const rendered = titleFormatSource.replace(/\{\{?\s*([a-zA-Z0-9_.]+)\s*\}?\}/g, (_m, key) => {
const v = row[key];
if (v == null || v === '') { allResolved = false; return ''; }
return String(v);
}).trim();
if (rendered && allResolved) return rendered;
if (rendered) return rendered.replace(/\s+-\s+$/, '').replace(/^\s+-\s+/, '').trim() || row.id;
}
const candidates = [
obj.displayNameField,
'name', 'full_name', 'title', 'subject', 'label', 'company',
].filter((c): c is string => typeof c === 'string' && hasField(c));
for (const c of candidates) {
const v = row[c];
if (v != null && String(v).trim()) return String(v);
}
const fn = row.first_name, ln = row.last_name;
if (fn || ln) return `${fn ?? ''} ${ln ?? ''}`.trim();
return String(row.id);
};
const titleFieldName = obj.displayNameField
|| (hasField('name') ? 'name' : undefined)
|| (hasField('title') ? 'title' : undefined)
|| fields.find(f => TEXT_TYPES.has(f.type))?.name;
let searchableFields = fields
.filter(f => f && TEXT_TYPES.has(f.type) && f.searchable === true)
.map(f => f.name as string);
// Fallback: if no field is explicitly searchable, scan the title field
if (searchableFields.length === 0 && titleFieldName) {
searchableFields = [titleFieldName];
}
if (searchableFields.length === 0) continue;
objectsScanned++;
// Build AND-of-OR filter: every term must hit at least one field.
// ObjectQL exposes case-insensitive substring matching via `$contains`.
const andClauses = terms.map(term => ({
$or: searchableFields.map(f => ({ [f]: { $contains: term } })),
}));
const where = andClauses.length === 1 ? andClauses[0] : { $and: andClauses };
try {
const opts: any = {
where,
limit: perObject,
orderBy: [{ field: 'updated_at', direction: 'desc' }],
};
if (request.context !== undefined) opts.context = request.context;
const rows = await this.engine.find(obj.name, opts);
for (const row of rows || []) {
if (hits.length >= overallLimit) break;
const title = renderTitle(row);
// Build snippet from first searchable field that contains a term
let snippet: string | undefined;
for (const f of searchableFields) {
const v = row[f];
if (typeof v === 'string' && v) {
const lc = v.toLowerCase();
const idx = terms.map(t => lc.indexOf(t.toLowerCase())).find(i => i >= 0);
if (idx != null && idx >= 0) {
const start = Math.max(0, idx - 30);
const end = Math.min(v.length, idx + 90);
snippet = (start > 0 ? '…' : '') + v.slice(start, end) + (end < v.length ? '…' : '');
break;
}
}
}
hits.push({