-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathprotocol.ts
More file actions
5646 lines (5372 loc) · 263 KB
/
Copy pathprotocol.ts
File metadata and controls
5646 lines (5372 loc) · 263 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 { readEnvWithDeprecation } from '@objectstack/types';
import type { ObjectQL } from './engine.js';
import { SysMetadataRepository, type SysMetadataEngine } from './sys-metadata-repository.js';
import { ConflictError } from '@objectstack/metadata-core';
import type {
BatchUpdateRequest,
BatchUpdateResponse,
UpdateManyDataRequest,
DeleteManyDataRequest,
InstallPackageRequest,
InstallPackageResponse
} 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 { type FormView, isAggregatedViewContainer } from '@objectstack/spec/ui';
import { METADATA_FORM_REGISTRY } from '@objectstack/spec/system';
import { DEFAULT_METADATA_TYPE_REGISTRY, getMetadataTypeSchema, getMetadataTypeActions, getMetadataCreateSeed } from '@objectstack/spec/kernel';
import {
extractProtection,
evaluateLockForWrite,
evaluateLockForDelete,
resolveLockState,
type MetadataLock,
type MetadataProvenance,
} from '@objectstack/spec/kernel';
import { z } from 'zod';
import {
computeMetadataDiagnostics,
computeViewReferenceDiagnostics,
decorateMetadataItem,
decorateMetadataItems,
type MetadataDiagnostics,
} from './metadata-diagnostics.js';
/**
* Canonical Zod schema per metadata type lives in
* `@objectstack/spec/kernel/metadata-type-schemas` and is exposed through
* {@link getMetadataTypeSchema}. Both save-time validation
* ({@link resolveOverlaySchema}) and the `/meta/types/:type` JSON Schema
* emitter consult that single source of truth, so adding a new
* metadata-type schema requires editing exactly one file (or calling
* `registerMetadataTypeSchema()` from a plugin).
*/
// (TYPE_TO_SCHEMA removed — use `getMetadataTypeSchema(type)` directly.)
/**
* Canonical {@link FormView} layout per metadata type. Sourced from the
* shared {@link METADATA_FORM_REGISTRY} in `@objectstack/spec/system` so
* the runtime form payload, the i18n extractor, and Studio all read from
* a single source of truth.
*
* Types without an entry render with the auto-generated single-section
* layout derived from their JSON Schema (acceptable for simple types).
*/
const TYPE_TO_FORM: Readonly<Record<string, FormView>> = METADATA_FORM_REGISTRY;
/**
* Convert a Zod schema to a JSON Schema, returning `undefined` if conversion
* fails (e.g. unsupported constructs). Cached per schema reference.
*/
const _jsonSchemaCache = new WeakMap<z.ZodTypeAny, Record<string, unknown> | null>();
function toJsonSchemaSafe(schema: z.ZodTypeAny): Record<string, unknown> | undefined {
const cached = _jsonSchemaCache.get(schema);
if (cached !== undefined) return cached ?? undefined;
try {
const result = z.toJSONSchema(schema, { unrepresentable: 'any' }) as Record<string, unknown>;
_jsonSchemaCache.set(schema, result);
return result;
} catch {
_jsonSchemaCache.set(schema, null);
return undefined;
}
}
/**
* Hand-crafted fallback JSON Schemas for metadata types whose Zod schema
* cannot be safely converted via `z.toJSONSchema()` (e.g. due to recursive
* references or non-representable constructs like `z.lazy()` chains).
*
* These mirror the shape consumed by the corresponding `*.form.ts` layouts,
* so the SchemaForm renderer can still produce a real form (instead of
* falling back to the raw JSON editor). All fields use lenient types
* (`string | object | array`) because the widget hint in the form layout
* is what actually drives the UI control selection — the JSON Schema is
* only used to (a) seed defaults and (b) report which property names exist.
*/
const HAND_CRAFTED_SCHEMAS: Record<string, Record<string, unknown>> = {
object: {
type: 'object',
properties: {
name: { type: 'string' },
label: { type: 'string' },
pluralLabel: { type: 'string' },
icon: { type: 'string' },
description: { type: 'string' },
tags: { type: 'array', items: { type: 'string' } },
active: { type: 'boolean', default: true },
isSystem: { type: 'boolean', default: false },
abstract: { type: 'boolean', default: false },
datasource: { type: 'string' },
fields: {
// Canonical Object.fields is a name-keyed map
// (Record<string, FieldDefinition>) — insertion order is
// display order. The SchemaForm engine recognises
// `additionalProperties` as a Record and dispatches to
// the `record` form-field renderer (ADR-0007). The form
// layout in `object.form.ts` declares `type: 'record'`
// so the inner `additionalProperties` schema is used to
// shape each value.
type: 'object',
default: {},
additionalProperties: {
type: 'object',
properties: {
name: { type: 'string' },
label: { type: 'string' },
type: { type: 'string' },
required: { type: 'boolean', default: false },
unique: { type: 'boolean', default: false },
defaultValue: {},
description: { type: 'string' },
},
required: ['type'],
},
},
capabilities: { type: 'object', additionalProperties: true },
},
required: ['name'],
additionalProperties: true,
},
action: {
type: 'object',
properties: {
name: { type: 'string' },
label: { type: 'string' },
objectName: { type: 'string' },
icon: { type: 'string' },
type: { type: 'string', enum: ['url', 'flow', 'api', 'script'] },
variant: { type: 'string', enum: ['primary', 'secondary', 'danger', 'ghost', 'outline'] },
target: { type: 'string' },
method: { type: 'string', enum: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE'] },
body: {
type: 'array',
default: [],
items: {
type: 'object',
properties: {
line: { type: 'string' },
},
},
},
params: {
type: 'array',
default: [],
items: {
type: 'object',
properties: {
name: { type: 'string' },
label: { type: 'string' },
type: { type: 'string' },
required: { type: 'boolean', default: false },
},
required: ['name'],
},
},
confirmText: { type: 'string' },
successMessage: { type: 'string' },
refreshAfter: { type: 'boolean', default: true },
locations: {
type: 'array',
default: [],
items: {
type: 'object',
properties: {
location: { type: 'string' },
},
},
},
component: { type: 'string' },
visible: { type: 'string' },
disabled: { type: 'string' },
shortcut: { type: 'string' },
bulkEnabled: { type: 'boolean', default: false },
aiExposed: { type: 'boolean', default: false },
recordIdParam: { type: 'string' },
recordIdField: { type: 'string' },
bodyShape: { type: 'string', enum: ['flat', 'nested'] },
},
required: ['name', 'label', 'type'],
additionalProperties: true,
},
// Validation rules live inside `object.validations[]`. The canonical
// ValidationRuleSchema is a discriminated union of 9 variants; the
// generic SchemaForm renderer treats unions as opaque JSON, so we
// ship a *flat* form-friendly schema covering the common base
// properties plus every variant-specific field as optional. Save-time
// validation is unaffected — the union schema is still authoritative
// at write time.
validation: {
type: 'object',
properties: {
// --- Base fields (all variants) ---
name: { type: 'string', description: 'Unique rule name (snake_case)' },
label: { type: 'string' },
description: { type: 'string' },
type: {
type: 'string',
enum: [
'script',
'unique',
'state_machine',
'format',
'cross_field',
'json',
'async',
'custom',
'conditional',
],
default: 'script',
description: 'Validation variant',
},
active: { type: 'boolean', default: true },
events: {
type: 'array',
items: { type: 'string', enum: ['insert', 'update', 'delete'] },
default: ['insert', 'update'],
},
priority: { type: 'number', default: 100, minimum: 0, maximum: 9999 },
severity: {
type: 'string',
enum: ['error', 'warning', 'info'],
default: 'error',
},
message: { type: 'string' },
tags: { type: 'array', items: { type: 'string' } },
// --- Variant-specific (all optional, gated by `type`) ---
condition: {
type: 'string',
description: 'CEL predicate (type=script). True ⇒ validation fails.',
},
fields: {
type: 'array',
items: { type: 'string' },
description: 'Fields (type=unique / cross_field).',
},
scope: { type: 'string', description: 'CEL scope predicate (type=unique).' },
caseSensitive: { type: 'boolean', default: true },
field: { type: 'string', description: 'Single field (type=state_machine / format).' },
transitions: {
type: 'object',
additionalProperties: { type: 'array', items: { type: 'string' } },
description: 'Map { OldState: [AllowedNewStates] } (type=state_machine).',
},
regex: { type: 'string', description: 'Regex (type=format).' },
format: {
type: 'string',
enum: ['email', 'url', 'phone', 'json'],
description: 'Built-in format (type=format).',
},
url: { type: 'string', description: 'Endpoint URL (type=async).' },
handler: { type: 'string', description: 'Handler reference (type=custom).' },
when: { type: 'string', description: 'Outer condition (type=conditional).' },
},
required: ['name', 'type', 'message'],
additionalProperties: true,
},
};
/**
* Zod schemas used to validate overlay items before they are persisted into
* `sys_metadata` by {@link ObjectStackProtocolImplementation.saveMetaItem}.
*
* Single source of truth: the spec-side {@link getMetadataTypeSchema}
* registry (`@objectstack/spec/kernel/metadata-type-schemas`). Every
* metadata type whose payload should round-trip through Studio's
* generic editor maps to its canonical Zod schema there; this function
* is a plural→singular adapter on top of it.
*
* 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.
* - Types without a registered schema (the wiring-layer types
* `function`/`service`/`router`, and any plugin types that have not
* yet called `registerMetadataTypeSchema()`) fall through unvalidated.
*/
function resolveOverlaySchema(type: string, _item: unknown): z.ZodTypeAny | null {
const singular = PLURAL_TO_SINGULAR[type] ?? type;
return getMetadataTypeSchema(singular) ?? null;
}
/**
* Guarantee a `view` body carries a top-level `name`.
*
* {@link ObjectStackProtocolImplementation.getMetaItems} only surfaces a
* sys_metadata overlay row when its parsed body has a top-level `name` (objects
* and dashboards include one; some view producers — notably loose `{ list }`
* fragments — do not, so the view is silently dropped from the object's view
* list and never appears as a tab). We stamp the save name here, at the single
* write chokepoint, without otherwise reshaping the document.
*
* Deliberately does NOT convert shape: both the `defineView` container form
* (`{ list, listViews, … }`) and the `{ name, object, viewKind, config }`
* record form are valid and the console consumes both — reshaping a container
* into a record risks producing an invalid record (e.g. a non-`<object>.<key>`
* name). Structural validity is enforced separately by the view metadata schema
* during the spec-validation step. No-op for non-view types and bodies that
* already carry a `name`.
*/
export function normalizeViewMetadata(type: string, item: unknown, saveName: string): unknown {
const singular = PLURAL_TO_SINGULAR[type] ?? type;
if (singular !== 'view') return item;
if (!item || typeof item !== 'object' || Array.isArray(item)) return item;
const it = item as Record<string, unknown>;
return it.name ? it : { ...it, name: saveName };
}
/**
* ADR-0010 §3.3 — Overlay the artifact's metadata-protection envelope
* onto a returned item so artifact-level lock/packageId/provenance
* always wins over whatever was persisted in the `sys_metadata` overlay
* row. Returns `item` unchanged when no artifact baseline is available.
*
* The artifact's `_lock`, `_lockReason`, `_packageId`, `_packageVersion`,
* and `_provenance` are the source of truth — an overlay copy may
* pre-date the artifact's protection declaration and would otherwise
* mask it.
*/
function mergeArtifactProtection(item: unknown, artifactItem: unknown): unknown {
if (item === undefined || item === null) return item;
if (artifactItem === undefined || artifactItem === null) return item;
const a = artifactItem as Record<string, unknown>;
if (typeof a !== 'object') return item;
const out: Record<string, unknown> = { ...(item as Record<string, unknown>) };
if (a._lock !== undefined) out._lock = a._lock;
if (a._lockReason !== undefined) out._lockReason = a._lockReason;
if (a._lockDocsUrl !== undefined) out._lockDocsUrl = a._lockDocsUrl;
if (a._lockSource !== undefined) out._lockSource = a._lockSource;
if (a._packageId !== undefined) out._packageId = a._packageId;
if (a._packageVersion !== undefined) out._packageVersion = a._packageVersion;
if (a._provenance !== undefined) out._provenance = a._provenance;
return out;
}
/**
* 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);
}
/**
* Thrown by `updateData` / `deleteData` when the caller supplies an
* `expectedVersion` that does not match the current record's `updated_at`.
*
* The HTTP layer maps this to `409 Conflict` with code `CONCURRENT_UPDATE`,
* and includes both the current server-side version and the current record
* payload so the client can render an informed conflict-resolution UI
* ("Reload latest" vs. "Overwrite anyway").
*
* NOTE: This is an *application-level* compare-and-set — not an atomic
* storage-layer CAS. There is a small TOCTOU window between the version
* check and the subsequent write. For the conflict frequency this targets
* (different users seconds-to-minutes apart in B2B record editing) this
* is more than adequate; a future revision can push the check into the
* driver's UPDATE statement (`WHERE id=? AND updated_at=?`) for true
* atomicity.
*/
export class ConcurrentUpdateError extends Error {
readonly code = 'CONCURRENT_UPDATE';
readonly status = 409;
readonly currentVersion: string | null;
readonly currentRecord: unknown;
constructor(opts: { currentVersion: string | null; currentRecord: unknown; message?: string }) {
super(opts.message ?? 'Record was modified by another user');
this.name = 'ConcurrentUpdateError';
this.currentVersion = opts.currentVersion;
this.currentRecord = opts.currentRecord;
}
}
/**
* Normalises a version token for comparison. Strips RFC-7232-style quotes
* (`"…"`) that an HTTP `If-Match` header may carry, trims whitespace, and
* returns null for empty / nullish input.
*/
function normaliseVersionToken(v: unknown): string | null {
if (v === null || v === undefined) return null;
const s = String(v).trim();
if (!s) return null;
if (s.length >= 2 && s.startsWith('"') && s.endsWith('"')) {
return s.slice(1, -1);
}
return s;
}
// Lifecycle columns the engine always owns; the clone path drops them by NAME
// so the insert re-stamps fresh values instead of copying the source's. Mirrors
// record-validator's SKIP_FIELDS (system-injected, never author-supplied).
const CLONE_STRIP_FIELDS: readonly string[] = [
'id', 'created_at', 'created_by', 'updated_at', 'updated_by',
];
/**
* 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' },
};
/**
* Phase 3a-references: hand-curated reference path registry.
*
* Maps a *target* metadata type to the list of *source* type+path tuples
* that may point at it. Used by {@link findReferencesToMeta} to scan all
* loaded metadata and surface "what depends on this?" before a user
* deletes or renames an artifact.
*
* Path syntax:
* - `'foo'` → item.foo
* - `'foo.bar'` → item.foo.bar
* - `'foo[]'` → each element of array item.foo
* - `'foo[].bar'` → bar of each element of array item.foo
* - `'foo{}'` → each value of Record item.foo
* - `'foo{}.bar'` → bar of each value of Record item.foo
*
* Coverage is intentionally narrow — covers the highest-value references
* for MVP. Add more entries as new editors are built.
*/
const REFERENCE_PATHS: Record<string, Array<{ fromType: string; paths: string[]; kind: string }>> = {
object: [
{ fromType: 'view', paths: ['object', 'objectName'], kind: 'view' },
{ fromType: 'dashboard', paths: ['widgets[].object', 'widgets[].objectName'], kind: 'dashboard widget' },
{ fromType: 'flow', paths: ['object', 'context.object', 'trigger.object', 'targetObject'], kind: 'flow' },
{ fromType: 'workflow', paths: ['object', 'targetObject'], kind: 'workflow' },
{ fromType: 'permission', paths: ['objects[].name', 'objects[].object'], kind: 'permission' },
{ fromType: 'app', paths: ['navItems[].objectName', 'navItems[].object', 'tabs[].objectName', 'tabs[].object'], kind: 'app nav' },
{ fromType: 'page', paths: ['object', 'objectName'], kind: 'page' },
{ fromType: 'report', paths: ['object', 'objectName'], kind: 'report' },
{ fromType: 'action', paths: ['object', 'objectName'], kind: 'action' },
{ fromType: 'validation', paths: ['object', 'objectName'], kind: 'validation' },
{ fromType: 'hook', paths: ['object', 'objectName'], kind: 'hook' },
{ fromType: 'object', paths: ['fields[].referenceTo', 'fields{}.referenceTo', 'fields{}.reference'], kind: 'field reference' },
],
view: [
{ fromType: 'dashboard', paths: ['widgets[].view', 'widgets[].viewName'], kind: 'dashboard widget' },
{ fromType: 'app', paths: ['navItems[].viewName', 'tabs[].viewName'], kind: 'app nav' },
{ fromType: 'page', paths: ['viewName'], kind: 'page' },
],
tool: [
{ fromType: 'agent', paths: ['tools[]', 'tools[].name'], kind: 'agent tool' },
],
skill: [
{ fromType: 'agent', paths: ['skills[]', 'skills[].name'], kind: 'agent skill' },
],
flow: [
{ fromType: 'app', paths: ['navItems[].flowName', 'tabs[].flowName'], kind: 'app nav' },
],
dashboard: [
{ fromType: 'app', paths: ['navItems[].dashboardName', 'tabs[].dashboardName'], kind: 'app nav' },
],
page: [
{ fromType: 'app', paths: ['navItems[].pageName', 'tabs[].pageName'], kind: 'app nav' },
],
};
/**
* Extract one or more string values from `item` at `path`. Supports
* `'a.b'` (nested object access) and `'a[].b'` (array element access).
* Returns an empty array if any segment is missing.
*/
function extractPathValues(item: unknown, path: string): string[] {
if (!item || typeof item !== 'object') return [];
const segments = path.split('.');
let current: unknown[] = [item];
for (const rawSeg of segments) {
let kind: 'value' | 'array' | 'record' = 'value';
let seg = rawSeg;
if (seg.endsWith('[]')) {
kind = 'array';
seg = seg.slice(0, -2);
} else if (seg.endsWith('{}')) {
kind = 'record';
seg = seg.slice(0, -2);
}
const next: unknown[] = [];
for (const node of current) {
if (!node || typeof node !== 'object') continue;
let value: unknown;
if (seg === '') {
value = node;
} else {
value = (node as Record<string, unknown>)[seg];
}
if (value === undefined || value === null) continue;
if (kind === 'array') {
if (Array.isArray(value)) {
for (const v of value) next.push(v);
}
} else if (kind === 'record') {
if (Array.isArray(value)) {
for (const v of value) next.push(v);
} else if (typeof value === 'object') {
for (const v of Object.values(value as Record<string, unknown>)) next.push(v);
}
} else {
next.push(value);
}
}
current = next;
if (current.length === 0) return [];
}
// Coerce final values to strings, dropping non-string non-object leaves.
const out: string[] = [];
for (const v of current) {
if (typeof v === 'string' && v.length > 0) out.push(v);
else if (v && typeof v === 'object' && 'name' in (v as any) && typeof (v as any).name === 'string') {
out.push((v as any).name);
}
}
return out;
}
/**
* Phase 3a-destructive: detect changes between an existing object schema
* and an incoming overlay that would break runtime data — removed fields,
* field type narrowing, required toggled on without a default. Returned
* issues are surfaced as HTTP 409 `destructive_change` unless the caller
* sets `force: true`, letting the admin UI render a warning dialog before
* proceeding.
*
* Scope is intentionally narrow for MVP: covers the most common
* data-loss footguns for `object` and `field` types. Subsequent passes
* can layer in relationship changes, enum-value removals, etc.
*/
/**
* Shallow JSON diff used by `diffMetaItem`. Compares the top-level
* keys of `from` vs `to`; primitive value changes are reported as
* `changed`, nested objects/arrays that differ structurally are also
* reported as a single `changed` entry (deep structural diffs are out
* of scope — Studio renders the full bodies for a side-by-side view).
*/
function diffShallow(
from: Record<string, unknown>,
to: Record<string, unknown>,
): {
added: Array<{ path: string; value: unknown }>;
removed: Array<{ path: string; value: unknown }>;
changed: Array<{ path: string; from: unknown; to: unknown }>;
} {
const added: Array<{ path: string; value: unknown }> = [];
const removed: Array<{ path: string; value: unknown }> = [];
const changed: Array<{ path: string; from: unknown; to: unknown }> = [];
const fromKeys = new Set(Object.keys(from ?? {}));
const toKeys = new Set(Object.keys(to ?? {}));
for (const k of toKeys) {
if (!fromKeys.has(k)) {
added.push({ path: k, value: (to as any)[k] });
} else {
const a = (from as any)[k];
const b = (to as any)[k];
const aStr = JSON.stringify(a);
const bStr = JSON.stringify(b);
if (aStr !== bStr) {
changed.push({ path: k, from: a, to: b });
}
}
}
for (const k of fromKeys) {
if (!toKeys.has(k)) {
removed.push({ path: k, value: (from as any)[k] });
}
}
return { added, removed, changed };
}
function detectDestructiveObjectChanges(prev: any, next: any): Array<{
code: string;
field?: string;
message: string;
}> {
if (!prev || typeof prev !== 'object' || !next || typeof next !== 'object') return [];
const prevFields = (prev.fields && typeof prev.fields === 'object') ? prev.fields as Record<string, any> : {};
const nextFields = (next.fields && typeof next.fields === 'object') ? next.fields as Record<string, any> : {};
const issues: Array<{ code: string; field?: string; message: string }> = [];
// Removed fields — silently dropping a column is a data-loss event.
for (const fname of Object.keys(prevFields)) {
// Skip system fields — those are managed by applySystemFields and
// re-injected on every registerObject call; they will look "removed"
// in any user-supplied overlay.
if (prevFields[fname]?.system) continue;
if (!(fname in nextFields)) {
issues.push({
code: 'field_removed',
field: fname,
message: `Field '${fname}' removed — existing data in this column will become inaccessible.`,
});
}
}
// Field type changes — narrowing or incompatible conversions.
const TYPE_COMPATIBILITY: Record<string, Set<string>> = {
text: new Set(['textarea', 'markdown', 'html', 'code']),
number: new Set([]),
boolean: new Set([]),
date: new Set(['datetime']),
datetime: new Set(['date']),
};
for (const fname of Object.keys(nextFields)) {
const prevField = prevFields[fname];
const nextField = nextFields[fname];
if (!prevField) continue; // brand-new field — non-destructive
const prevType = prevField.type;
const nextType = nextField.type;
if (prevType && nextType && prevType !== nextType) {
const compatible = TYPE_COMPATIBILITY[prevType]?.has(nextType);
if (!compatible) {
issues.push({
code: 'field_type_change',
field: fname,
message: `Field '${fname}' type changed from '${prevType}' to '${nextType}' — existing values may not convert cleanly.`,
});
}
}
// required toggled on without a default — new inserts will start
// to fail validation, and any null rows already in the table will
// fail on next save.
if (!prevField.required && nextField.required && nextField.defaultValue === undefined) {
issues.push({
code: 'field_required_no_default',
field: fname,
message: `Field '${fname}' is now required but has no default value — existing rows with null values may fail validation.`,
});
}
}
return issues;
}
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 (`environment_id IS NULL`). When set, every
* saveMetaItem insert/update and loadMetaFromDb query is filtered by
* `environment_id = environmentId`, so per-project kernels see only their own
* metadata even if several projects share the same physical database.
*/
private environmentId?: string;
/**
* Lazily-instantiated SysMetadataRepository per organization. Keyed by
* `${organizationId ?? '__env__'}`. Repositories are stateful — they
* carry the per-org `seqCounter` and watch subscribers — so we cache
* them rather than constructing one per call.
*/
private overlayRepos = new Map<string, SysMetadataRepository>();
constructor(
engine: IDataEngine,
getServicesRegistry?: () => Map<string, any>,
getFeedService?: () => IFeedService | undefined,
environmentId?: string,
) {
this.engine = engine as ObjectQL;
this.getServicesRegistry = getServicesRegistry;
this.getFeedService = getFeedService;
this.environmentId = environmentId;
}
/**
* Lazily obtain a SysMetadataRepository for the given organization.
* Env-wide overlays (organizationId == null) share a singleton under
* the `__env__` key.
*/
private getOverlayRepo(organizationId: string | null): SysMetadataRepository {
const key = organizationId ?? '__env__';
let repo = this.overlayRepos.get(key);
if (!repo) {
repo = new SysMetadataRepository({
engine: this.engine as unknown as SysMetadataEngine,
organizationId,
orgLabel: organizationId ?? 'env',
});
this.overlayRepos.set(key, repo);
}
return repo;
}
/**
* One-time guard for ensuring the overlay-uniqueness UNIQUE INDEX exists
* on `sys_metadata`. ADR-0005: scopes overlays by
* `(type, name, organization_id, environment_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');
}
};
// ADR-0005 (revised 2026-05) + ADR-0048: per-env DBs replace the old
// "per-project" isolation, so `environment_id` is no longer a
// discriminator. Overlay uniqueness is `(type, name,
// organization_id, COALESCE(package_id,''))` filtered to active
// rows — `package_id` is in the key so two installed packages
// shipping the same name each get their own overlay, while
// `COALESCE(...,'')` keeps the package-less (global) rows unique
// among themselves (a plain unique index would treat NULLs as
// distinct and allow duplicate globals). Drop the legacy composite
// index first so the new partial UNIQUE can claim the same name —
// DROP INDEX IF EXISTS is idempotent.
try { await exec("DROP INDEX IF EXISTS idx_sys_metadata_overlay_active"); } catch { /* best-effort */ }
const partialSql =
"CREATE UNIQUE INDEX IF NOT EXISTS idx_sys_metadata_overlay_active " +
"ON sys_metadata (type, name, organization_id, COALESCE(package_id, '')) " +
"WHERE state = 'active'";
const fallbackSql =
"CREATE INDEX IF NOT EXISTS idx_sys_metadata_overlay_active " +
"ON sys_metadata (type, name, organization_id, package_id)";
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
}
// Mirror the same partial-UNIQUE for draft rows so a second
// simultaneous draft cannot be inserted for the same
// (type,name,org,package). The unique-active index above already
// guards published rows; the two never collide because the
// `state` predicate disambiguates them. DROP first so an existing
// legacy 3-column draft index is replaced in-place (ADR-0048).
try { await exec("DROP INDEX IF EXISTS idx_sys_metadata_overlay_draft"); } catch { /* best-effort */ }
const draftPartialSql =
"CREATE UNIQUE INDEX IF NOT EXISTS idx_sys_metadata_overlay_draft " +
"ON sys_metadata (type, name, organization_id, COALESCE(package_id, '')) " +
"WHERE state = 'draft'";
try {
await exec(draftPartialSql);
} catch (err: any) {
const msg = err instanceof Error ? err.message : String(err);
if (/partial|where clause|syntax/i.test(msg)) {
try {
await exec(
"CREATE INDEX IF NOT EXISTS idx_sys_metadata_overlay_draft " +
"ON sys_metadata (type, name, organization_id, package_id)",
);
} catch {
// ignore — 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 environment_id-filtered lookup.
*/
getProjectId(): string | undefined {
return this.environmentId;
}
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]));
// Phase 3a-1: enrich response with per-type registry metadata so admin
// UI can render directory pages, filter by domain, decide which types
// expose write actions, etc. Existing clients keep working — the
// `types: string[]` field is preserved alongside the new `entries`.
//
// Phase 3a-env-writable: `OS_METADATA_WRITABLE` env var (comma
// separated singular type names) flips `allowOrgOverride` on listed
// types so admins can self-serve. The same env var is consulted by
// `isOverlayAllowed()` at write time — they must stay in sync.
const writableOverrides = ObjectStackProtocolImplementation.envWritableTypes();
const registryByType = new Map(
DEFAULT_METADATA_TYPE_REGISTRY.map((e) => [e.type, e] as const)
);
const entries = allTypes.map((type) => {
const singular = (PLURAL_TO_SINGULAR[type] ?? type) as string;
// Phase 3a-schema: emit a JSON Schema per type so the generic
// metadata admin UI can render real forms (no more raw-JSON
// textareas for new resources). The canonical schema for every
// built-in (and plugin-registered) metadata type lives in the
// central `getMetadataTypeSchema()` registry; we delegate so
// Studio's editor and the runtime overlay validator stay in
// lock-step (one source of truth).
const zodSchema = getMetadataTypeSchema(singular);
const schema = (zodSchema ? toJsonSchemaSafe(zodSchema) : undefined)
?? HAND_CRAFTED_SCHEMAS[singular];
const form = TYPE_TO_FORM[singular];
// Phase 2: the authoritative minimal create seed (single source of
// truth in @objectstack/spec). Studio/CLI derive create defaults
// from this via /meta/types instead of re-inventing them.
const createSeed = getMetadataCreateSeed(singular);
// Type-level actions: merge the registry's declarative actions