-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathdata-protocol.ts
More file actions
1671 lines (1421 loc) · 29.7 KB
/
Copy pathdata-protocol.ts
File metadata and controls
1671 lines (1421 loc) · 29.7 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
/**
* ObjectUI
* Copyright (c) 2024-present ObjectStack Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
/**
* @object-ui/types - Data Protocol Advanced Types
*
* Phase 3: Complete implementation of QuerySchema, FilterSchema,
* ValidationSchema, DriverInterface, and DatasourceSchema.
*
* @module data-protocol
* @packageDocumentation
*/
// Import existing base types to avoid duplication
import type { SortConfig as BaseSortConfig } from './objectql';
import type { FilterOperator as BaseFilterOperator } from './complex';
// Spec-owned vocabulary, bound rather than re-declared (objectstack#4115). The
// spec exports both of these as zod enums, not as types, so they are derived
// through `z.infer` — `export type { … } from` would not compile against a value.
import type { z } from 'zod';
import type {
JoinStrategy as SpecJoinStrategy,
WindowFunction as SpecWindowFunction,
} from '@objectstack/spec/data';
/**
* =============================================================================
* Phase 3.3: QuerySchema AST Implementation
* =============================================================================
*/
/**
* Query AST Node Types
*/
export type QueryASTNodeType =
| 'select'
| 'from'
| 'where'
| 'join'
| 'group_by'
| 'order_by'
| 'limit'
| 'offset'
| 'subquery'
| 'aggregate'
| 'window'
| 'field'
| 'literal'
| 'operator'
| 'function';
/**
* Base Query AST Node
*/
export interface QueryASTNode {
type: QueryASTNodeType;
[key: string]: any;
}
/**
* SELECT clause node
*/
export interface SelectNode extends QueryASTNode {
type: 'select';
fields: (FieldNode | AggregateNode | WindowNode)[];
distinct?: boolean;
}
/**
* FROM clause node
*/
export interface FromNode extends QueryASTNode {
type: 'from';
table: string;
alias?: string;
}
/**
* WHERE clause node
*/
export interface WhereNode extends QueryASTNode {
type: 'where';
condition: OperatorNode;
}
/**
* Join execution strategy hint — derived from the spec's `JoinStrategy` zod enum.
*/
export type JoinStrategy = z.infer<typeof SpecJoinStrategy>;
/**
* JOIN clause node (Phase 3.3.4)
*/
export interface JoinNode extends QueryASTNode {
type: 'join';
join_type: 'inner' | 'left' | 'right' | 'full' | 'cross';
table: string;
alias?: string;
on: OperatorNode;
strategy?: JoinStrategy; // Execution strategy hint for cross-datasource joins
}
/**
* GROUP BY clause node
*/
export interface GroupByNode extends QueryASTNode {
type: 'group_by';
fields: FieldNode[];
having?: OperatorNode;
}
/**
* ORDER BY clause node
*/
export interface OrderByNode extends QueryASTNode {
type: 'order_by';
fields: Array<{
field: FieldNode;
direction: 'asc' | 'desc';
}>;
}
/**
* LIMIT clause node
*/
export interface LimitNode extends QueryASTNode {
type: 'limit';
value: number;
}
/**
* OFFSET clause node
*/
export interface OffsetNode extends QueryASTNode {
type: 'offset';
value: number;
}
/**
* Subquery node (Phase 3.3.3)
*/
export interface SubqueryNode extends QueryASTNode {
type: 'subquery';
query: QueryAST;
alias?: string;
}
/**
* Aggregate function node (Phase 3.3.5)
*/
export interface AggregateNode extends QueryASTNode {
type: 'aggregate';
function: 'count' | 'sum' | 'avg' | 'min' | 'max' | 'first' | 'last' | 'count_distinct' | 'array_agg' | 'string_agg';
field?: FieldNode;
alias?: string;
distinct?: boolean;
separator?: string; // For string_agg function
}
/**
* Window function type — derived from the spec's `WindowFunction` zod enum.
*/
export type WindowFunction = z.infer<typeof SpecWindowFunction>;
/**
* Window frame unit (ObjectStack Spec v2.0.1)
*/
export type WindowFrameUnit = 'rows' | 'range';
/**
* Window frame boundary (ObjectStack Spec v2.0.1)
*/
export type WindowFrameBoundary =
| 'unbounded_preceding'
| 'unbounded_following'
| 'current_row'
| { type: 'preceding'; offset: number }
| { type: 'following'; offset: number };
/**
* Window frame specification (ObjectStack Spec v2.0.1)
*/
export interface WindowFrame {
unit: WindowFrameUnit;
start: WindowFrameBoundary;
end?: WindowFrameBoundary; // Defaults to CURRENT ROW if not specified
}
/**
* Window function node (ObjectStack Spec v2.0.1)
*/
export interface WindowNode extends QueryASTNode {
type: 'window';
function: WindowFunction;
field?: FieldNode; // For aggregate window functions
alias: string;
partitionBy?: FieldNode[];
orderBy?: Array<{
field: FieldNode;
direction: 'asc' | 'desc';
}>;
frame?: WindowFrame;
// For LAG/LEAD functions
offset?: number;
defaultValue?: LiteralNode;
}
/**
* Field reference node
*/
export interface FieldNode extends QueryASTNode {
type: 'field';
table?: string;
name: string;
alias?: string;
}
/**
* Literal value node
*/
export interface LiteralNode extends QueryASTNode {
type: 'literal';
value: any;
data_type?: 'string' | 'number' | 'boolean' | 'date' | 'null';
}
/**
* Operator node
*/
export interface OperatorNode extends QueryASTNode {
type: 'operator';
operator: ComparisonOperator | LogicalOperator;
operands: (FieldNode | LiteralNode | OperatorNode | FunctionNode)[];
}
/**
* Function call node
*/
export interface FunctionNode extends QueryASTNode {
type: 'function';
name: string;
arguments: (FieldNode | LiteralNode | FunctionNode)[];
alias?: string;
}
/**
* Comparison operators
*/
export type ComparisonOperator =
| '='
| '!='
| '<>'
| '>'
| '>='
| '<'
| '<='
| 'like'
| 'ilike'
| 'in'
| 'not_in'
| 'is_null'
| 'is_not_null'
| 'between'
| 'contains'
| 'starts_with'
| 'ends_with';
/**
* Logical operators
*/
export type LogicalOperator = 'and' | 'or' | 'not';
/**
* Complete Query AST (Phase 3.3.1)
*/
export interface QueryAST {
select: SelectNode;
from: FromNode;
joins?: JoinNode[];
where?: WhereNode;
group_by?: GroupByNode;
order_by?: OrderByNode;
limit?: LimitNode;
offset?: OffsetNode;
}
/**
* Query Schema - High-level query configuration
*/
export interface QuerySchema {
/**
* Target object/table
*/
object: string;
/**
* Fields to select
*/
fields?: string[];
/**
* Filter conditions
*/
filter?: AdvancedFilterSchema;
/**
* Sort configuration
*/
sort?: QuerySortConfig[];
/**
* Pagination
*/
limit?: number;
offset?: number;
/**
* Joins (Phase 3.3.4)
*/
joins?: JoinConfig[];
/**
* Aggregations (Phase 3.3.5)
*/
aggregations?: AggregationConfig[];
/**
* Group by fields
*/
group_by?: string[];
/**
* Window functions (ObjectStack Spec v2.0.1)
*/
windows?: WindowConfig[];
/**
* Related objects to expand
*/
expand?: string[];
/**
* Full-text search
*/
search?: string;
}
/**
* Sort configuration (extends base SortConfig)
*/
export interface QuerySortConfig extends BaseSortConfig {
nulls?: 'first' | 'last';
}
/**
* Join configuration
*/
export interface JoinConfig {
type: 'inner' | 'left' | 'right' | 'full';
object: string;
on: {
local_field: string;
foreign_field: string;
};
alias?: string;
}
/**
* Aggregation configuration
*/
export interface AggregationConfig {
function: 'count' | 'sum' | 'avg' | 'min' | 'max' | 'count_distinct' | 'array_agg' | 'string_agg';
field?: string;
alias?: string;
distinct?: boolean;
separator?: string; // For string_agg function
}
/**
* Window function configuration (ObjectStack Spec v2.0.1)
*/
export interface WindowConfig {
/** Window function name */
function: WindowFunction;
/** Field to operate on (not required for row_number, rank, etc.) */
field?: string;
/** Result alias */
alias: string;
/** PARTITION BY fields */
partitionBy?: string[];
/** ORDER BY clause */
orderBy?: Array<{ field: string; direction: 'asc' | 'desc' }>;
/** Window frame specification */
frame?: WindowFrame;
/** Offset for lag/lead functions */
offset?: number;
/** Default value for lag/lead when no previous/next row */
defaultValue?: any;
}
/**
* =============================================================================
* Phase 3.4: FilterSchema - Advanced Filtering
* =============================================================================
*/
/**
* Filter Schema - Complex filtering support (extends base)
*/
export interface AdvancedFilterSchema {
/**
* Logical operator for combining conditions
*/
operator?: 'and' | 'or' | 'not';
/**
* Filter conditions
*/
conditions?: AdvancedFilterCondition[];
/**
* Nested filter groups
*/
groups?: AdvancedFilterSchema[];
}
/**
* Individual filter condition (extends base)
*/
export interface AdvancedFilterCondition {
/**
* Field to filter on
*/
field: string;
/**
* Comparison operator (extended)
*/
operator: AdvancedFilterOperator;
/**
* Value to compare against
*/
value?: any;
/**
* For BETWEEN and IN operators
*/
values?: any[];
/**
* Case sensitivity for string comparisons
*/
case_sensitive?: boolean;
}
/**
* Filter operators (Phase 3.4.1-3.4.4) - Extended from base
*/
export type AdvancedFilterOperator =
| BaseFilterOperator
// Additional operators
| 'like'
| 'ilike'
| 'is_null'
| 'is_not_null'
| 'between'
| 'not_between'
// Date-specific (Phase 3.4.2)
| 'date_equals'
| 'date_after'
| 'date_before'
| 'date_in_range'
| 'date_today'
| 'date_yesterday'
| 'date_tomorrow'
| 'date_this_week'
| 'date_last_week'
| 'date_next_week'
| 'date_this_month'
| 'date_last_month'
| 'date_next_month'
| 'date_this_year'
| 'date_last_year'
| 'date_next_year'
// Lookup field filters (Phase 3.4.3)
| 'lookup_equals'
| 'lookup_contains'
| 'lookup_starts_with'
// Full-text search (Phase 3.4.4)
| 'search'
| 'search_phrase'
| 'search_proximity';
/**
* Date range filter (Phase 3.4.2)
*/
export interface DateRangeFilter {
start?: Date | string;
end?: Date | string;
preset?: DateRangePreset;
}
/**
* Date range presets
*/
export type DateRangePreset =
| 'today'
| 'yesterday'
| 'tomorrow'
| 'this_week'
| 'last_week'
| 'next_week'
| 'this_month'
| 'last_month'
| 'next_month'
| 'this_quarter'
| 'last_quarter'
| 'next_quarter'
| 'this_year'
| 'last_year'
| 'next_year'
| 'last_7_days'
| 'last_30_days'
| 'last_90_days'
| 'next_7_days'
| 'next_30_days'
| 'next_90_days';
/**
* Filter builder configuration (Phase 3.4.5)
*/
export interface FilterBuilderConfig {
/**
* Available fields for filtering
*/
fields: FilterFieldConfig[];
/**
* Default operator
*/
default_operator?: 'and' | 'or';
/**
* Allow nested groups
*/
allow_groups?: boolean;
/**
* Maximum nesting depth
*/
max_depth?: number;
}
/**
* Filter field configuration
*/
export interface FilterFieldConfig {
/**
* Field name
*/
name: string;
/**
* Display label
*/
label: string;
/**
* Field type
*/
type: string;
/**
* Available operators for this field
*/
operators?: AdvancedFilterOperator[];
/**
* Options for select fields
*/
options?: Array<{ label: string; value: any }>;
}
/**
* =============================================================================
* Phase 3.5: ValidationSchema - Complete Validation Engine
* =============================================================================
*/
/**
* Validation Schema (Phase 3.5)
*/
export interface AdvancedValidationSchema {
/**
* Field name to validate
*/
field?: string;
/**
* Validation rules
*/
rules: AdvancedValidationRule[];
/**
* Custom error messages
*/
messages?: Record<string, string>;
/**
* Validation triggers
*/
on?: ('blur' | 'change' | 'submit')[];
/**
* Whether validation is async
*/
async?: boolean;
/**
* Debounce time for async validation (ms)
*/
debounce?: number;
}
/**
* Validation rule (Phase 3.5.1-3.5.4) - Extended
*/
export interface AdvancedValidationRule {
/**
* Rule type
*/
type: ValidationRuleType;
/**
* Rule parameters
*/
params?: any;
/**
* Error message
*/
message?: string;
/**
* Custom validation function (Phase 3.5.2)
*/
validator?: ValidationFunction;
/**
* Async validation function (Phase 3.5.3)
*/
async_validator?: AsyncValidationFunction;
/**
* Cross-field dependencies (Phase 3.5.4)
*/
depends_on?: string[];
/**
* Validation severity
*/
severity?: 'error' | 'warning' | 'info';
}
/**
* Validation rule types
*/
export type ValidationRuleType =
// Required
| 'required'
// String validations
| 'min_length'
| 'max_length'
| 'pattern'
| 'email'
| 'url'
| 'phone'
// Number validations
| 'min'
| 'max'
| 'integer'
| 'positive'
| 'negative'
// Date validations
| 'date_min'
| 'date_max'
| 'date_range'
| 'date_future'
| 'date_past'
// Array validations
| 'min_items'
| 'max_items'
| 'unique_items'
// Object validations
| 'object_schema'
// Cross-field validations (Phase 3.5.4)
| 'field_match'
| 'field_compare'
| 'conditional'
// Custom validations (Phase 3.5.2)
| 'custom'
// Async validations (Phase 3.5.3)
| 'async_custom'
| 'remote_validation'
| 'unique_check'
| 'exists_check';
/**
* Validation function signature used by AdvancedValidationRule in the data protocol.
*
* This type is defined in this module and may differ from similarly named
* validation function types in other packages (e.g., in `field-types`).
*
* @param value - The value to validate
* @param context - Optional validation context with access to other field values
* @returns true if valid, false or error message string if invalid
*/
export type ValidationFunction = (value: any, context?: ValidationContext) => boolean | string;
/**
* Async validation function (Phase 3.5.3)
*/
export type AsyncValidationFunction = (
value: any,
context?: ValidationContext
) => Promise<boolean | string>;
/**
* Validation context (Phase 3.5.4)
*/
export interface ValidationContext {
/**
* All form values
*/
values?: Record<string, any>;
/**
* Field metadata
*/
field?: any;
/**
* Parent object data
*/
parent?: any;
/**
* Current user context
*/
user?: any;
}
/**
* Validation result
*/
export interface AdvancedValidationResult {
/**
* Whether validation passed
*/
valid: boolean;
/**
* Validation errors
*/
errors: AdvancedValidationError[];
/**
* Validation warnings
*/
warnings?: AdvancedValidationError[];
}
/**
* Validation error (Phase 3.5.5: Improved error messages)
*/
export interface AdvancedValidationError {
/**
* Field path
*/
field: string;
/**
* Error message
*/
message: string;
/**
* Error code
*/
code?: string;
/**
* Rule type that failed
*/
rule?: ValidationRuleType;
/**
* Error severity
*/
severity?: 'error' | 'warning' | 'info';
/**
* Additional context
*/
context?: Record<string, any>;
}
/**
* =============================================================================
* ObjectStack Spec v2.0.1: Object-Level Validation Framework
* =============================================================================
*/
/**
* Base validation interface (ObjectStack Spec v2.0.1)
*/
export interface BaseValidation {
/** Unique validation name (snake_case) */
name: string;
/** Display label for the validation */
label?: string;
/** Description of what this validation does */
description?: string;
/** Whether this validation is currently active */
active: boolean;
/** When this validation should run */
events: Array<'insert' | 'update' | 'delete'>;
/** Severity of validation failure */
severity: 'error' | 'warning' | 'info';
/** Error message to display on failure */
message: string;
/** Tags for categorization */
tags?: string[];
}
/**
* Script-based validation (ObjectStack Spec v2.0.1)
* Uses expression language to define conditions
*/
export interface ScriptValidation extends BaseValidation {
type: 'script';
/** Expression that must evaluate to true */
condition: string;
}
/**
* Uniqueness validation (ObjectStack Spec v2.0.1)
* Ensures field combinations are unique
*/
export interface UniquenessValidation extends BaseValidation {
type: 'unique';
/** Fields that must be unique together */
fields: string[];
/** Optional scope expression (e.g., "tenant_id = ${current_tenant}") */
scope?: string;
/** Whether comparison is case-sensitive */
caseSensitive?: boolean;
}
/**
* State machine validation (ObjectStack Spec — ADR-0020)
* Enforces valid state transitions on a single state field.
*
* ADR-0020 converged record state machines onto this one flat rule: a state
* `field` plus a `transitions` map of `{ fromState: [allowedToStates] }`.
* (The legacy `{ stateField, transitions: Array<{from,to,condition}> }`
* shape and the separate `workflow` metadata type were retired.)
*/
export interface StateMachineValidation extends BaseValidation {
type: 'state_machine';
/** Field containing the state (e.g. `status`). */
field: string;
/** Map of `{ fromState: [allowedToStates] }`. */
transitions: Record<string, string[]>;
}
/**
* Cross-field validation (ObjectStack Spec v2.0.1)
* Validates relationships between multiple fields
*/
export interface CrossFieldValidation extends BaseValidation {
type: 'cross_field';
/** Fields involved in the validation */
fields: string[];
/** Condition expression involving multiple fields */
condition: string;
}
/**
* Async/remote validation (ObjectStack Spec v2.0.1)
* Calls external endpoint for validation
*/
export interface AsyncValidation extends BaseValidation {
type: 'async';
/** API endpoint to call */
endpoint: string;
/** HTTP method */
method?: 'GET' | 'POST';
/** Debounce delay in milliseconds */
debounce?: number;
/** Cache configuration */
cache?: {
enabled: boolean;
ttl?: number; // Time to live in seconds
};
}
/**
* Conditional validation (ObjectStack Spec v2.0.1)
* Applies nested rules only when condition is met
*/
export interface ConditionalValidation extends BaseValidation {
type: 'conditional';
/** Condition that determines if rules should apply */
condition: string;
/** Nested validation rules to apply when condition is true */
rules: ObjectValidationRule[];
}
/**
* Format validation (ObjectStack Spec v2.0.1)
* Validates field format using regex or predefined patterns
*/
export interface FormatValidation extends BaseValidation {
type: 'format';
/** Field to validate */
field: string;
/** Regex pattern or predefined format name */
pattern: string | RegExp;
/** Predefined format (email, url, phone, etc.) */
format?: 'email' | 'url' | 'phone' | 'ipv4' | 'ipv6' | 'uuid' | 'iso_date' | 'credit_card';
/** Validation flags for regex (i, g, m, etc.) */
flags?: string;
}
/**
* Range validation (ObjectStack Spec v2.0.1)
* Validates numeric or date ranges
*/
export interface RangeValidation extends BaseValidation {
type: 'range';
/** Field to validate */
field: string;
/** Minimum value (inclusive) */
min?: number | string | Date;
/** Maximum value (inclusive) */
max?: number | string | Date;
/** Whether min is exclusive */
minExclusive?: boolean;
/** Whether max is exclusive */
maxExclusive?: boolean;
}
/**
* Union type for all validation rules (ObjectStack Spec v2.0.1)