@stndrds/schema 1.0.0-alpha.166 → 1.0.0-alpha.169

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. package/dist/filters-DRXk4dLI.d.mts +1575 -0
  2. package/dist/filters-zzsF0GxK.d.ts +1575 -0
  3. package/dist/helpers-64gmAyw0.d.ts +61 -0
  4. package/dist/helpers-DOjqrfWE.d.mts +61 -0
  5. package/dist/index.d.mts +33 -101
  6. package/dist/index.d.ts +33 -101
  7. package/dist/index.js +118 -50
  8. package/dist/index.mjs +109 -52
  9. package/dist/{types-CUbVw7X2.d.ts → types-Bemfgle3.d.ts} +1 -1
  10. package/dist/{types-DT8dfR2I.d.mts → types-DxEobsMy.d.mts} +1 -1
  11. package/dist/validation/all.d.mts +3 -3
  12. package/dist/validation/all.d.ts +3 -3
  13. package/dist/validation/all.js +4 -0
  14. package/dist/validation/all.mjs +1 -1
  15. package/dist/validation/complex/currency.d.mts +2 -2
  16. package/dist/validation/complex/currency.d.ts +2 -2
  17. package/dist/validation/complex/file.d.mts +2 -2
  18. package/dist/validation/complex/file.d.ts +2 -2
  19. package/dist/validation/complex/location.d.mts +2 -2
  20. package/dist/validation/complex/location.d.ts +2 -2
  21. package/dist/validation/complex/phone.d.mts +2 -2
  22. package/dist/validation/complex/phone.d.ts +2 -2
  23. package/dist/validation/complex/relation.d.mts +2 -2
  24. package/dist/validation/complex/relation.d.ts +2 -2
  25. package/dist/validation/complex/richtext.d.mts +2 -2
  26. package/dist/validation/complex/richtext.d.ts +2 -2
  27. package/dist/validation/complex/select.d.mts +2 -2
  28. package/dist/validation/complex/select.d.ts +2 -2
  29. package/dist/validation/complex/user.d.mts +2 -2
  30. package/dist/validation/complex/user.d.ts +2 -2
  31. package/dist/validation/computed/formula.d.mts +2 -2
  32. package/dist/validation/computed/formula.d.ts +2 -2
  33. package/dist/validation/computed/rollup.d.mts +2 -2
  34. package/dist/validation/computed/rollup.d.ts +2 -2
  35. package/dist/validation/config/index.d.mts +1 -1
  36. package/dist/validation/config/index.d.ts +1 -1
  37. package/dist/validation/core/index.d.mts +3 -3
  38. package/dist/validation/core/index.d.ts +3 -3
  39. package/dist/validation/object/index.d.mts +3 -4
  40. package/dist/validation/object/index.d.ts +3 -4
  41. package/dist/validation/primitives/checkbox.d.mts +2 -2
  42. package/dist/validation/primitives/checkbox.d.ts +2 -2
  43. package/dist/validation/primitives/date.d.mts +2 -2
  44. package/dist/validation/primitives/date.d.ts +2 -2
  45. package/dist/validation/primitives/number.d.mts +2 -2
  46. package/dist/validation/primitives/number.d.ts +2 -2
  47. package/dist/validation/primitives/rating.d.mts +2 -2
  48. package/dist/validation/primitives/rating.d.ts +2 -2
  49. package/dist/validation/primitives/text.d.mts +2 -2
  50. package/dist/validation/primitives/text.d.ts +2 -2
  51. package/package.json +2 -2
  52. package/dist/attributes-CNpcbVbv.d.ts +0 -667
  53. package/dist/attributes-DcHM27jS.d.mts +0 -667
  54. package/dist/helpers-BDn1PUC2.d.mts +0 -860
  55. package/dist/helpers-oaW8DBAh.d.ts +0 -860
@@ -0,0 +1,1575 @@
1
+ import { IconName, CountryIso3, CurrencyCode, ColorId, MimeType } from '@stndrds/constants';
2
+ import { Uuid } from './utils.mjs';
3
+
4
+ /**
5
+ * Type of view - determines the config structure
6
+ */
7
+ type ViewType = "detail" | "list";
8
+ /**
9
+ * Creation behavior when clicking the "+" button
10
+ * - `redirect`: Create the record then navigate to its detail page
11
+ * - `inline`: Insert an empty row in the table (no navigation)
12
+ * - `modal`: Open a stacked modal for creation
13
+ */
14
+ type CreateMode = "redirect" | "inline" | "modal";
15
+ /**
16
+ * Inline attribute group configuration
17
+ * Groups multiple attributes into a single composite field with dropdown editing
18
+ */
19
+ interface AttributeGroupField {
20
+ /** Unique identifier for the group */
21
+ id: string;
22
+ /** Display label for the composite field */
23
+ label: string;
24
+ /** Description shown in the dropdown */
25
+ description?: string;
26
+ /** Attribute names to include in this group */
27
+ attributes: string[];
28
+ /**
29
+ * Template for the display value
30
+ * Uses {attributeName} syntax for interpolation
31
+ * @example "{billing_street}, {billing_city} {billing_postal_code}"
32
+ */
33
+ displayTemplate?: string;
34
+ }
35
+ /**
36
+ * Field definition within a form group
37
+ * Can be either a single attribute or an inline attribute group
38
+ */
39
+ interface Field {
40
+ /** Attribute name to display (for single attribute fields) */
41
+ attribute?: string;
42
+ /** Inline attribute group (groups multiple attributes into one composite field) */
43
+ attributeGroup?: AttributeGroupField;
44
+ /** Grid span (1-12 columns) */
45
+ span?: 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12;
46
+ /** Override label for this view (only for single attribute fields) */
47
+ label?: string;
48
+ /** Force read-only display */
49
+ readOnly?: boolean;
50
+ }
51
+ /**
52
+ * Base properties shared by all group types
53
+ */
54
+ interface BaseGroup {
55
+ id: string;
56
+ label: string;
57
+ description?: string;
58
+ collapsible?: boolean;
59
+ collapsed?: boolean;
60
+ order?: number;
61
+ }
62
+ /**
63
+ * Group of fields for organizing forms (default group type)
64
+ */
65
+ interface FieldGroup extends BaseGroup {
66
+ /** Discriminant — optional for backward compatibility with existing data */
67
+ type?: "fields";
68
+ fields: Field[];
69
+ }
70
+ /**
71
+ * Group that displays related records for a relation attribute
72
+ */
73
+ interface RelationGroup extends BaseGroup {
74
+ type: "relation";
75
+ /** Relation attribute name on the source object */
76
+ attribute: string;
77
+ /** Columns to display (auto-detected from target object if empty) */
78
+ columns?: string[];
79
+ /** Read-only mode */
80
+ readOnly?: boolean;
81
+ /** Allow creating new related records */
82
+ allowCreate?: boolean;
83
+ /**
84
+ * Two-level traversal — display records from the target's relation.
85
+ * When set, parent rows become grouping headers and the sub-rows
86
+ * (from `through.attribute`) are the primary display.
87
+ *
88
+ * @example attribute = "members", through.attribute = "companies"
89
+ * → displays companies of each member
90
+ */
91
+ through?: {
92
+ /** Relation attribute on the first-level target object */
93
+ attribute: string;
94
+ };
95
+ }
96
+ /**
97
+ * Discriminated union of all group types
98
+ */
99
+ type Group = FieldGroup | RelationGroup;
100
+ type TabType = "form" | "table" | "custom" | "activity" | "richtext" | "documents" | "forms";
101
+ /**
102
+ * Base properties shared by all tab types
103
+ */
104
+ interface BaseTab {
105
+ id: string;
106
+ name: string;
107
+ label: string;
108
+ icon?: IconName;
109
+ order?: number;
110
+ }
111
+ /**
112
+ * Form layout density
113
+ */
114
+ type FormDensity = "compact" | "comfortable" | "spacious";
115
+ /**
116
+ * Form tab - displays attributes organized in groups
117
+ */
118
+ interface FormTab extends BaseTab {
119
+ type: "form";
120
+ groups: Group[];
121
+ /** Number of grid columns (1, 2, or 3). Default: 2 */
122
+ formColumns?: 1 | 2 | 3;
123
+ /** Layout density. Default: "comfortable" */
124
+ density?: FormDensity;
125
+ }
126
+ /**
127
+ * Direct relation on the current object
128
+ *
129
+ * @example Contact.companies → shows Companies linked via the "companies" relation
130
+ */
131
+ interface RelationSource {
132
+ type: "relation";
133
+ /** Relation attribute name on the current object */
134
+ attribute: string;
135
+ }
136
+ /**
137
+ * Inverse lookup — records from another object that point to us
138
+ *
139
+ * @example On Company, show Contacts where Contact.company = this Company
140
+ */
141
+ interface InverseSource {
142
+ type: "inverse";
143
+ /** Object name that has the relation to us */
144
+ object: string;
145
+ /** Relation attribute name on the source object that points to us */
146
+ attribute: string;
147
+ }
148
+ /**
149
+ * Where table data comes from — either a direct relation or an inverse lookup
150
+ */
151
+ type TableSource = RelationSource | InverseSource;
152
+ /**
153
+ * Table tab - displays related records in a table
154
+ *
155
+ * The `source` field determines where data comes from.
156
+ *
157
+ * @example Direct: source = { type: "relation", attribute: "members" }
158
+ * @example Inverse: source = { type: "inverse", object: "contacts", attribute: "company" }
159
+ */
160
+ interface TableTab extends BaseTab {
161
+ type: "table";
162
+ /** Where the data comes from */
163
+ source: TableSource;
164
+ /** Columns to display (attribute names from the resolved target object) */
165
+ columns: string[];
166
+ /**
167
+ * Traverse a 2nd-level relation to display nested data.
168
+ * When active, `columns` stores the 2nd-level object's attribute names.
169
+ *
170
+ * @example source.attribute = "members", through.attribute = "companies"
171
+ * → displays companies of each member
172
+ */
173
+ through?: {
174
+ /** Relation attribute on the first-level target object */
175
+ attribute: string;
176
+ /** Show _source and _target columns */
177
+ showSourceTarget?: boolean;
178
+ };
179
+ /** Allow creating new records */
180
+ allowCreate?: boolean;
181
+ /** Creation behavior when allowCreate is true. Default: "redirect" */
182
+ createMode?: CreateMode;
183
+ /** Allow inline editing */
184
+ allowEdit?: boolean;
185
+ /** Allow deleting records */
186
+ allowDelete?: boolean;
187
+ /** Default filters applied to the table */
188
+ filters?: FilterState;
189
+ /** Default sort rules */
190
+ sorts?: SortRule[];
191
+ }
192
+ /**
193
+ * Custom tab - renders a developer-defined component
194
+ */
195
+ interface CustomTab extends BaseTab {
196
+ type: "custom";
197
+ /** Component identifier to render */
198
+ component: string;
199
+ /** Props to pass to the component */
200
+ props?: Record<string, unknown>;
201
+ }
202
+ /**
203
+ * Activity tab - displays activity feed for the current record
204
+ */
205
+ interface ActivityTab extends BaseTab {
206
+ type: "activity";
207
+ limit?: number;
208
+ }
209
+ /**
210
+ * Richtext tab - displays a block editor for a richtext attribute
211
+ */
212
+ interface RichtextTab extends BaseTab {
213
+ type: "richtext";
214
+ /** Richtext attribute to display in the BlockEditor */
215
+ attribute: string;
216
+ /** Optional text attribute for an editable title input above the editor */
217
+ titleAttribute?: string;
218
+ }
219
+ /**
220
+ * Documents tab - displays all documents attached to the record
221
+ */
222
+ interface DocumentsTab extends BaseTab {
223
+ type: "documents";
224
+ allowUpload?: boolean;
225
+ allowRemove?: boolean;
226
+ hideAttachments?: boolean;
227
+ }
228
+ /**
229
+ * Forms tab - displays available forms for creating related records
230
+ */
231
+ interface FormsTab extends BaseTab {
232
+ type: "forms";
233
+ /** Object name to filter forms by slot (derived from record context, but can be overridden) */
234
+ objectName?: string;
235
+ }
236
+ /**
237
+ * Union of all tab types (for detail views)
238
+ */
239
+ type Tab = FormTab | TableTab | CustomTab | ActivityTab | RichtextTab | DocumentsTab | FormsTab;
240
+ /**
241
+ * Detail view layout mode
242
+ * - `page`: Full view with multiple tabs
243
+ * - `modal`: Simplified view for modals (single FormTab, no tabs UI)
244
+ */
245
+ type DetailViewLayout = "page" | "modal";
246
+ /**
247
+ * List view layout mode
248
+ * - `table`: Table/grid layout
249
+ * - `kanban`: Kanban board layout (grouped by attribute)
250
+ */
251
+ type ListViewLayout = "table" | "kanban";
252
+ /**
253
+ * Tab within a list view — each tab carries its own full display configuration.
254
+ *
255
+ * @example
256
+ * ```typescript
257
+ * const tabs: ListViewTab[] = [
258
+ * { id: "all", label: "All Contacts", default: true, layout: "table", columns: ["name", "email", "status"] },
259
+ * { id: "active", label: "Active", layout: "table", columns: ["name", "email"], filters: activeFilter },
260
+ * { id: "pipeline", label: "Pipeline", layout: "kanban", columns: ["name", "amount"], groupByAttribute: "stage" },
261
+ * ];
262
+ * ```
263
+ */
264
+ interface ListViewTab {
265
+ /** Unique identifier */
266
+ id: string;
267
+ /** Display label */
268
+ label: string;
269
+ /** Icon */
270
+ icon?: IconName;
271
+ /** Default tab (shown on load) */
272
+ default?: boolean;
273
+ /** Layout mode */
274
+ layout: ListViewLayout;
275
+ /** Attribute names to display as columns */
276
+ columns: string[];
277
+ /** Column widths in pixels */
278
+ columnSizing?: Record<string, number>;
279
+ /** Filters applied to this tab */
280
+ filters?: FilterGroup;
281
+ /** Sort rules for this tab */
282
+ sorts?: SortRule[];
283
+ /** Attribute to group by (required when layout is "kanban") */
284
+ groupByAttribute?: string;
285
+ /** When true, the tab is read-only: no cell editing, no create, no delete */
286
+ readOnly?: boolean;
287
+ /** Creation behavior when clicking "+". Default: "redirect" */
288
+ createMode?: CreateMode;
289
+ /** User attribute to display on kanban cards (bottom-left) */
290
+ cardUserAttribute?: string;
291
+ /** Date attribute to display on kanban cards (bottom-right) */
292
+ cardDateAttribute?: string;
293
+ /** Order of kanban columns (by option value) - for kanban layout only */
294
+ kanbanColumnOrder?: string[];
295
+ /** Visibility of kanban columns (by option value) - for kanban layout only */
296
+ kanbanColumnVisibility?: Record<string, boolean>;
297
+ /** Pinned kanban columns (by option value) - for kanban layout only */
298
+ kanbanPinnedColumns?: string[];
299
+ }
300
+ /**
301
+ * Configuration for the side panel displayed alongside tab content.
302
+ * When present, a right-side panel shows the configured attributes as flat fields.
303
+ */
304
+ interface SidePanelConfig {
305
+ /** Attribute names to display as flat fields in the panel */
306
+ attributes: string[];
307
+ /** Width in pixels. @default 320 */
308
+ width?: number;
309
+ }
310
+ /**
311
+ * Configuration for detail views (RecordEditView)
312
+ */
313
+ interface DetailViewConfig {
314
+ /** Layout mode */
315
+ layout: DetailViewLayout;
316
+ /** Tabs in this view */
317
+ tabs: Tab[];
318
+ /** Optional side panel with flat attribute fields (not available for modal layout) */
319
+ sidePanel?: SidePanelConfig;
320
+ }
321
+ /**
322
+ * Configuration for list views (RecordsView)
323
+ *
324
+ * Each tab carries its own full config (layout, columns, filters, sorts, groupBy).
325
+ * The view only holds shared base filters applied to ALL tabs.
326
+ */
327
+ interface ListViewConfig {
328
+ /** Base filters applied to ALL tabs (scoping, tenant, etc.) */
329
+ defaultFilters?: FilterGroup;
330
+ /** Tabs — at least one required. Each carries its own full config. */
331
+ tabs: ListViewTab[];
332
+ }
333
+ /**
334
+ * Union of all view configs
335
+ */
336
+ type ViewConfig = DetailViewConfig | ListViewConfig;
337
+ /**
338
+ * Base view properties shared by all view types
339
+ */
340
+ interface BaseViewDefinition {
341
+ /** Unique identifier (UUID, assigned by database) */
342
+ id?: string;
343
+ /** Technical name (kebab-case) */
344
+ name: string;
345
+ /** Display label */
346
+ label: string;
347
+ /** Description */
348
+ description?: string;
349
+ /** Icon */
350
+ icon?: IconName;
351
+ /** Object this view belongs to (object name) */
352
+ object: string;
353
+ /** Default view for this object+type combination */
354
+ default?: boolean;
355
+ /** Extensible metadata */
356
+ metadata?: Record<string, unknown>;
357
+ /** Current schema version of this view definition */
358
+ schema_version: number;
359
+ }
360
+ /**
361
+ * Detail view definition
362
+ */
363
+ interface DetailViewDefinition extends BaseViewDefinition {
364
+ type: "detail";
365
+ config: DetailViewConfig;
366
+ }
367
+ /**
368
+ * List view definition
369
+ */
370
+ interface ListViewDefinition extends BaseViewDefinition {
371
+ type: "list";
372
+ config: ListViewConfig;
373
+ }
374
+ /**
375
+ * Unified view definition - discriminated union by type
376
+ */
377
+ type ViewDefinition = DetailViewDefinition | ListViewDefinition;
378
+ /**
379
+ * Configuration overrides for user customizations
380
+ * Only stores the delta from the source view
381
+ */
382
+ interface ConfigOverrides {
383
+ tabs?: ListViewTab[];
384
+ hiddenTabIds?: string[];
385
+ detailTabs?: Tab[];
386
+ hiddenDetailTabIds?: string[];
387
+ }
388
+ /**
389
+ * User customization overlay for a view
390
+ * Stored per user, merged at runtime with the source view
391
+ */
392
+ interface ViewOverlay {
393
+ /** Unique identifier */
394
+ id: string;
395
+ /** View ID this overlay applies to (UUID or virtual ID) */
396
+ viewId: string;
397
+ /** User ID who owns this overlay */
398
+ userId: string;
399
+ /** Configuration overrides (delta only) */
400
+ configOverrides: ConfigOverrides;
401
+ /** User's default view for this object (stored in overlay) */
402
+ isUserDefault?: boolean;
403
+ /** Created timestamp */
404
+ createdAt: Date;
405
+ /** Updated timestamp */
406
+ updatedAt: Date;
407
+ }
408
+ /**
409
+ * Check if a view is a detail view
410
+ */
411
+ declare function isDetailView(view: ViewDefinition): view is DetailViewDefinition;
412
+ /**
413
+ * Check if a view is a list view
414
+ */
415
+ declare function isListView(view: ViewDefinition): view is ListViewDefinition;
416
+ /**
417
+ * Check if a group is a field group (default type)
418
+ */
419
+ declare function isFieldGroup(group: Group): group is FieldGroup;
420
+ /**
421
+ * Check if a group is a relation group
422
+ */
423
+ declare function isRelationGroup(group: Group): group is RelationGroup;
424
+
425
+ type TransformSource = "system" | "runtime" | "rollback" | "seed";
426
+ type BuiltInTransform = "toString" | "toNumber" | "toDate" | "toBoolean" | "toISOString";
427
+ type SchemaOperation = {
428
+ type: "add_attribute";
429
+ attribute: Attribute;
430
+ } | {
431
+ type: "remove_attribute";
432
+ name: string;
433
+ backup_config: Attribute;
434
+ } | {
435
+ type: "rename_attribute";
436
+ from: string;
437
+ to: string;
438
+ } | {
439
+ type: "change_type";
440
+ name: string;
441
+ from: AttributeType;
442
+ to: AttributeType;
443
+ transform?: BuiltInTransform;
444
+ } | {
445
+ type: "update_config";
446
+ name: string;
447
+ from: Partial<Record<string, unknown>>;
448
+ to: Partial<Record<string, unknown>>;
449
+ } | {
450
+ type: "remove_object";
451
+ backup: Record<string, unknown>;
452
+ } | {
453
+ type: "rename_object";
454
+ from: string;
455
+ to: string;
456
+ };
457
+ type ViewOperation = {
458
+ type: "update_config";
459
+ from: ViewConfig;
460
+ to: ViewConfig;
461
+ } | {
462
+ type: "update_tabs";
463
+ from: (ListViewTab | Tab)[];
464
+ to: (ListViewTab | Tab)[];
465
+ } | {
466
+ type: "force_reset";
467
+ config: ViewConfig;
468
+ } | {
469
+ type: "remove_view";
470
+ backup: Record<string, unknown>;
471
+ };
472
+ interface MigrationDefinition {
473
+ version: number;
474
+ operations: SchemaOperation[];
475
+ reverse_operations: SchemaOperation[];
476
+ }
477
+ interface SchemaTransform {
478
+ id: string;
479
+ tenantId: string;
480
+ objectId: string;
481
+ fromVersion: number;
482
+ toVersion: number;
483
+ operations: SchemaOperation[];
484
+ reverseOperations: SchemaOperation[];
485
+ source: TransformSource;
486
+ appliedAt: Date;
487
+ fullyMigrated: boolean;
488
+ }
489
+ interface ViewTransform {
490
+ id: string;
491
+ tenantId: string;
492
+ viewId: string;
493
+ fromVersion: number;
494
+ toVersion: number;
495
+ operations: ViewOperation[];
496
+ reverseOperations: ViewOperation[];
497
+ source: TransformSource;
498
+ appliedAt: Date;
499
+ }
500
+ interface MigrationError {
501
+ id: string;
502
+ tenantId: string;
503
+ transformId: string;
504
+ recordId: string;
505
+ attributeName: string;
506
+ originalValue: unknown;
507
+ error: string;
508
+ resolvedAt: Date | null;
509
+ resolvedValue: unknown | null;
510
+ }
511
+
512
+ /**
513
+ * Timestamps for tracking creation and updates
514
+ */
515
+ interface Timestamps {
516
+ createdAt: Date;
517
+ updatedAt: Date;
518
+ }
519
+ /**
520
+ * Object definition - Represents a database table/entity
521
+ */
522
+ interface ObjectDefinition {
523
+ id?: Uuid;
524
+ name: string;
525
+ label: string;
526
+ pluralLabel?: string;
527
+ description?: string;
528
+ icon?: IconName;
529
+ /**
530
+ * Template expression used to compute the object's display label.
531
+ * Supports variable interpolation and pipes for formatting.
532
+ *
533
+ * @example
534
+ * ```typescript
535
+ * // Simple attribute reference
536
+ * labelExpression: "{{ name }}"
537
+ *
538
+ * // Multiple attributes
539
+ * labelExpression: "{{ firstName }} {{ lastName }}"
540
+ *
541
+ * // With pipes for formatting
542
+ * labelExpression: "{{ code | UPPER }} - {{ name | capitalize }}"
543
+ * ```
544
+ *
545
+ * Available pipes: UPPER, LOWER, capitalize, trim
546
+ */
547
+ labelExpression: string;
548
+ attributes: Attribute[];
549
+ system?: boolean;
550
+ metadata?: Record<string, unknown>;
551
+ /** Current schema version (incremented with each migration) */
552
+ schema_version: number;
553
+ /** Ordered list of migrations applied to this object's schema */
554
+ migrations: MigrationDefinition[];
555
+ }
556
+ /**
557
+ * Links an attribute to an object
558
+ */
559
+ interface ObjectAttribute {
560
+ objectId: Uuid;
561
+ attributeId: Uuid;
562
+ order?: number;
563
+ required?: boolean;
564
+ }
565
+ /**
566
+ * Completion status of a record based on data completeness.
567
+ *
568
+ * - `draft`: Record is missing one or more required attribute values.
569
+ * Can be saved but is considered incomplete.
570
+ * - `complete`: All required attribute values are present and valid.
571
+ * Record is ready for use.
572
+ *
573
+ * This is different from workflow status (e.g., "pending", "approved").
574
+ * Completion status is computed dynamically based on the object schema.
575
+ */
576
+ type CompletionStatus = "draft" | "complete";
577
+ /**
578
+ * Record - Instance of an Object (a row in the database)
579
+ */
580
+ interface ObjectRecord extends Timestamps {
581
+ id: Uuid;
582
+ objectId: Uuid;
583
+ /**
584
+ * Display label computed from the object's labelExpression.
585
+ * Computed dynamically based on record values.
586
+ *
587
+ * @example "John Doe" (from "{{ firstName }} {{ lastName }}")
588
+ */
589
+ label: string;
590
+ /**
591
+ * Completion status of the record.
592
+ * - `draft`: Missing required values, record is incomplete
593
+ * - `complete`: All required values present and valid
594
+ *
595
+ * Computed dynamically based on the object's schema.
596
+ */
597
+ completionStatus: CompletionStatus;
598
+ values: Record<string, unknown>;
599
+ /**
600
+ * Custom metadata for the record.
601
+ * Use this for UI/UX state, feature flags, or any application-specific data.
602
+ * Unlike system fields (id, createdAt, updatedAt), metadata can be updated.
603
+ */
604
+ metadata?: Record<string, unknown>;
605
+ /**
606
+ * Soft delete timestamp.
607
+ * If set, the record is considered deleted but can be restored.
608
+ * Queries exclude soft-deleted records by default.
609
+ */
610
+ deletedAt?: Date | null;
611
+ /**
612
+ * Actor ID who created this record.
613
+ * Automatically set by RecordService when actorId is configured.
614
+ * Optional for backward compatibility with existing records.
615
+ */
616
+ createdBy?: string;
617
+ /**
618
+ * Actor ID who last updated this record.
619
+ * Automatically set by RecordService when actorId is configured.
620
+ * Optional for backward compatibility with existing records.
621
+ */
622
+ lastUpdatedBy?: string;
623
+ /** Schema version at the time this record was last migrated */
624
+ schemaVersion: number;
625
+ /**
626
+ * Values archived during attribute removal or type changes.
627
+ * Retained according to the retention policy before permanent deletion.
628
+ */
629
+ archivedValues?: Record<string, unknown>;
630
+ }
631
+ /**
632
+ * System-managed field names on ObjectRecord.
633
+ * These are stored as SQL columns (not in JSONB `values`).
634
+ *
635
+ * Use this in adapters to determine if a filter/sort attribute is a table column
636
+ * vs. a JSONB value field.
637
+ *
638
+ * @example
639
+ * ```typescript
640
+ * if (SYSTEM_FIELD_NAMES.includes(filter.attribute)) {
641
+ * // Filter on SQL column (e.g., WHERE created_at > ...)
642
+ * } else {
643
+ * // Filter on JSONB field (e.g., WHERE values->>'name' = ...)
644
+ * }
645
+ * ```
646
+ */
647
+ declare const SYSTEM_FIELD_NAMES: readonly ["id", "createdAt", "updatedAt", "createdBy", "lastUpdatedBy"];
648
+ /**
649
+ * Type for system field names
650
+ */
651
+ type SystemFieldName = (typeof SYSTEM_FIELD_NAMES)[number];
652
+ /**
653
+ * Reserved attribute names that cannot be used for custom attributes.
654
+ * These names conflict with ObjectRecord properties.
655
+ *
656
+ * Includes:
657
+ * - System fields (id, createdAt, updatedAt, createdBy, lastUpdatedBy)
658
+ * - Other ObjectRecord properties (objectId, label, completionStatus, values, metadata, deletedAt)
659
+ *
660
+ * @example
661
+ * ```typescript
662
+ * if (RESERVED_ATTRIBUTE_NAMES.includes(attributeName)) {
663
+ * throw new Error(`"${attributeName}" is a reserved name`);
664
+ * }
665
+ * ```
666
+ */
667
+ declare const RESERVED_ATTRIBUTE_NAMES: readonly ["id", "createdAt", "updatedAt", "createdBy", "lastUpdatedBy", "objectId", "label", "completionStatus", "values", "metadata", "deletedAt", "schemaVersion", "archivedValues"];
668
+ /**
669
+ * Type for reserved attribute names
670
+ */
671
+ type ReservedAttributeName = (typeof RESERVED_ATTRIBUTE_NAMES)[number];
672
+
673
+ interface Document extends Timestamps {
674
+ id: Uuid;
675
+ tenantId: Uuid;
676
+ title: string;
677
+ contentHash?: string;
678
+ createdBy?: Uuid;
679
+ updatedBy?: Uuid;
680
+ deletedAt?: Date | null;
681
+ values: Record<string, unknown>;
682
+ }
683
+ /**
684
+ * Configuration for a single named slot on a DocumentAttribute.
685
+ * Slots are placeholders for files within a Document; declared at design-time
686
+ * on the attribute and validated at attach time.
687
+ */
688
+ interface DocumentSlotConfig {
689
+ /** Stable identifier referenced in DB. */
690
+ name: string;
691
+ /** Display label in UI. Falls back to `name` if absent. */
692
+ label?: string;
693
+ /** Description shown to users and to the AI in tool context. */
694
+ description?: string;
695
+ /** Surfaced to UI/AI but not enforced by the system. */
696
+ required?: boolean;
697
+ /** MIME prefixes or globs (e.g. "image/*", "application/pdf"). */
698
+ acceptedMimeTypes?: string[];
699
+ /** Hard ceiling enforced by the service before upload. */
700
+ maxSizeBytes?: number;
701
+ }
702
+ /** Default applied by the document() builder when no slots are configured. */
703
+ declare const DEFAULT_DOCUMENT_SLOT: DocumentSlotConfig;
704
+ interface DocumentSlot extends Timestamps {
705
+ id: Uuid;
706
+ tenantId: Uuid;
707
+ documentId: Uuid;
708
+ slotName: string;
709
+ isAdditional: boolean;
710
+ fileId: Uuid;
711
+ status: SlotStatus;
712
+ ocrText?: string;
713
+ ocrConfidence?: number;
714
+ processedAt?: Date;
715
+ }
716
+ type SlotStatus = "uploaded" | "processing" | "completed" | "failed";
717
+ interface ProcessingJob extends Timestamps {
718
+ id: Uuid;
719
+ tenantId: Uuid;
720
+ documentId: Uuid;
721
+ slotName?: string | null;
722
+ type: ProcessingJobType;
723
+ provider: string;
724
+ status: ProcessingJobStatus;
725
+ input?: Record<string, unknown>;
726
+ result?: Record<string, unknown>;
727
+ error?: string;
728
+ startedAt?: Date | null;
729
+ completedAt?: Date | null;
730
+ createdBy?: Uuid;
731
+ }
732
+ type ProcessingJobType = "ocr";
733
+ type ProcessingJobStatus = "pending" | "processing" | "completed" | "failed" | "cancelled";
734
+ interface CreateDocument {
735
+ title: string;
736
+ values?: Record<string, unknown>;
737
+ }
738
+ interface UpdateDocument {
739
+ title?: string;
740
+ values?: Record<string, unknown>;
741
+ }
742
+ interface CreateDocumentSlot {
743
+ documentId: Uuid;
744
+ slotName: string;
745
+ fileId: Uuid;
746
+ isAdditional?: boolean;
747
+ }
748
+ interface UpdateDocumentSlot {
749
+ status?: SlotStatus;
750
+ ocrText?: string;
751
+ ocrConfidence?: number;
752
+ }
753
+ interface CreateProcessingJob {
754
+ documentId: Uuid;
755
+ slotName?: string;
756
+ type: ProcessingJobType;
757
+ provider: string;
758
+ input?: Record<string, unknown>;
759
+ }
760
+ interface UpdateProcessingJob {
761
+ status?: ProcessingJobStatus;
762
+ result?: Record<string, unknown>;
763
+ error?: string;
764
+ startedAt?: Date;
765
+ completedAt?: Date;
766
+ }
767
+ interface DocumentListOptions {
768
+ limit?: number;
769
+ offset?: number;
770
+ }
771
+ interface DocumentWithSlots extends Document {
772
+ slots: DocumentSlot[];
773
+ }
774
+ interface RecordDocuments {
775
+ /** Documents grouped by attribute name (includes system 'attachments' attribute) */
776
+ byAttribute: Record<string, DocumentWithSlots[]>;
777
+ }
778
+
779
+ /**
780
+ * Feature flag levels (resolution priority: user > tenant > global).
781
+ *
782
+ * - `global`: Applies to all tenants and users
783
+ * - `tenant`: Applies to a specific tenant
784
+ * - `user`: Applies to a specific user within a tenant
785
+ */
786
+ type FlagLevel = "global" | "tenant" | "user";
787
+ /**
788
+ * Flag value types supported by the system.
789
+ */
790
+ type FlagValueType = "boolean" | "string" | "number" | "json";
791
+ /**
792
+ * Definition of a feature flag.
793
+ * Created using the flag builders (booleanFlag, stringFlag, etc.)
794
+ */
795
+ interface FeatureFlagDefinition<T = unknown> {
796
+ /** Unique identifier for the flag (kebab-case) */
797
+ name: string;
798
+ /** Human-readable label */
799
+ label: string;
800
+ /** Optional description */
801
+ description?: string;
802
+ /** Type of the flag value */
803
+ valueType: FlagValueType;
804
+ /** Default value when no override exists */
805
+ defaultValue: T;
806
+ /** Levels at which this flag can be overridden */
807
+ allowedLevels: FlagLevel[];
808
+ /** Grouping category for UI */
809
+ category?: string;
810
+ /** System flag - cannot be modified via API */
811
+ system?: boolean;
812
+ }
813
+ /**
814
+ * Stored override for a feature flag.
815
+ * Represents a row in the feature_flag_overrides table.
816
+ */
817
+ interface FlagOverride<T = unknown> {
818
+ /** Name of the flag being overridden */
819
+ flagName: string;
820
+ /** Level of the override */
821
+ level: FlagLevel;
822
+ /** Target ID (tenantId for tenant-level, userId for user-level) */
823
+ targetId?: string;
824
+ /** Override value */
825
+ value: T;
826
+ /** Optional expiration date */
827
+ expiresAt?: Date;
828
+ /** Who created this override */
829
+ createdBy?: string;
830
+ /** When the override was created */
831
+ createdAt: Date;
832
+ /** When the override was last updated */
833
+ updatedAt: Date;
834
+ }
835
+ /**
836
+ * Resolved flag value with source information.
837
+ * Result of flag resolution including where the value came from.
838
+ */
839
+ interface ResolvedFlag<T = unknown> {
840
+ /** Flag name */
841
+ name: string;
842
+ /** Resolved value */
843
+ value: T;
844
+ /** Where the value came from */
845
+ source: FlagLevel | "default";
846
+ /** ID of the source (tenantId or userId) if not default */
847
+ sourceId?: string;
848
+ }
849
+ /**
850
+ * Feature gate configuration for conditional attribute visibility.
851
+ * Used with the `.featureGate()` builder method.
852
+ */
853
+ interface FeatureGate {
854
+ /** Name of the flag to check */
855
+ flag: string;
856
+ /**
857
+ * Expected value for the gate to pass.
858
+ * For boolean flags, defaults to `true`.
859
+ * For other types, compares with strict equality.
860
+ */
861
+ expectedValue?: unknown;
862
+ /**
863
+ * Behavior when the gate fails.
864
+ * - `hide`: Attribute is completely hidden (default)
865
+ * - `show`: Attribute is shown regardless (no gating)
866
+ * - `disable`: Attribute is visible but read-only
867
+ */
868
+ fallback?: "hide" | "show" | "disable";
869
+ }
870
+ /**
871
+ * Repository interface for feature flag overrides storage.
872
+ * Added to DatabaseAdapter as an optional repository.
873
+ *
874
+ * If not provided, only static defaults from module config are used.
875
+ */
876
+ interface FeatureFlagsRepository {
877
+ /**
878
+ * Get all overrides matching the criteria.
879
+ * Returns overrides from the database (global, tenant, or user level).
880
+ */
881
+ getOverrides(options: {
882
+ /** Filter by level */
883
+ level?: FlagLevel;
884
+ /** Filter by target ID (tenantId or userId) */
885
+ targetId?: string;
886
+ /** Filter by flag names (for efficient single/batch lookups) */
887
+ flagNames?: string[];
888
+ }): Promise<FlagOverride[]>;
889
+ /**
890
+ * Create or update an override.
891
+ * Uses upsert semantics based on (flagName, level, targetId).
892
+ */
893
+ setOverride(override: Omit<FlagOverride, "createdAt" | "updatedAt">): Promise<FlagOverride>;
894
+ /**
895
+ * Delete an override.
896
+ */
897
+ deleteOverride(flagName: string, level: FlagLevel, targetId?: string): Promise<void>;
898
+ }
899
+ /**
900
+ * Static flag default value for module configuration.
901
+ */
902
+ interface StaticFlagDefault {
903
+ /** Flag name */
904
+ name: string;
905
+ /** Default value */
906
+ value: unknown;
907
+ }
908
+ /**
909
+ * Feature flags configuration for SchemaModule.
910
+ */
911
+ interface FeatureFlagsConfig {
912
+ /**
913
+ * Static default values for flags.
914
+ * These are always applied and used when no database override exists.
915
+ *
916
+ * @example
917
+ * ```typescript
918
+ * featureFlags: {
919
+ * defaults: [
920
+ * { name: "architect-mode", value: false },
921
+ * { name: "ai-chat", value: false },
922
+ * { name: "tier", value: "free" },
923
+ * ],
924
+ * }
925
+ * ```
926
+ */
927
+ defaults?: StaticFlagDefault[];
928
+ }
929
+
930
+ /**
931
+ * Allowed attribute types in .qualifyWith()
932
+ *
933
+ * IMPORTANT: Complex types (formula, rollup, relation, file, user, document, richtext)
934
+ * are NOT supported to avoid duplicating backend behavior.
935
+ */
936
+ type PropertyType = "text" | "textarea" | "number" | "checkbox" | "date" | "phone" | "currency" | "status" | "select" | "multiselect" | "rating" | "location";
937
+ /**
938
+ * Union of attribute types allowed as qualified relation properties.
939
+ *
940
+ * These are the same Attribute types used for object attributes,
941
+ * restricted to simple types that don't require complex backend duplication.
942
+ */
943
+ type PropertyAttribute = TextAttribute | TextAreaAttribute | NumberAttribute | CheckboxAttribute | DateAttribute | PhoneAttribute | CurrencyAttribute | StatusAttribute | SelectAttribute | MultiselectAttribute | RatingAttribute | LocationAttribute;
944
+ /**
945
+ * Schema defining properties for a qualified relation.
946
+ *
947
+ * Uses the same Attribute types as object attributes, enabling DRY builders:
948
+ *
949
+ * @example
950
+ * ```typescript
951
+ * relation({ name: "companies", label: "Companies" })
952
+ * .to("companies").many()
953
+ * .qualifyWith(
954
+ * select({ name: "role", label: "Role" }).options([...]).required(),
955
+ * number({ name: "shares", label: "Shares" }).min(0),
956
+ * )
957
+ * ```
958
+ */
959
+ interface PropertySchema {
960
+ definitions: PropertyAttribute[];
961
+ }
962
+ /**
963
+ * Property attribute types that have an `options` array.
964
+ */
965
+ type OptionPropertyAttribute = SelectAttribute | StatusAttribute | MultiselectAttribute;
966
+ /**
967
+ * Type guard to check if a property attribute has options.
968
+ *
969
+ * @param attr - The property attribute to check
970
+ * @returns true if the attribute is a select, status, or multiselect type with options
971
+ *
972
+ * @example
973
+ * ```typescript
974
+ * for (const def of definitions) {
975
+ * if (hasOptions(def)) {
976
+ * // TypeScript knows def.options exists and is Option[]
977
+ * for (const option of def.options) {
978
+ * console.log(option.value);
979
+ * }
980
+ * }
981
+ * }
982
+ * ```
983
+ */
984
+ declare function hasOptions(attr: PropertyAttribute): attr is OptionPropertyAttribute;
985
+
986
+ type AttributeType = "text" | "textarea" | "richtext" | "number" | "checkbox" | "date" | "phone" | "currency" | "status" | "location" | "select" | "multiselect" | "file" | "user" | "relation" | "rating" | "formula" | "rollup" | "document";
987
+ /**
988
+ * Status group categorization
989
+ */
990
+ type StatusGroup = "idle" | "in_progress" | "finished";
991
+ /**
992
+ * Unified option type for select-like fields
993
+ */
994
+ interface Option {
995
+ id: string;
996
+ label: string;
997
+ value: string;
998
+ color?: ColorId;
999
+ icon?: IconName;
1000
+ description?: string;
1001
+ group?: StatusGroup;
1002
+ /** Value of the inverse option for bilateral relations (e.g. "parent" → "child") */
1003
+ inverse?: string;
1004
+ }
1005
+ /**
1006
+ * Attribute grouping for UI organization
1007
+ */
1008
+ interface AttributeGroup {
1009
+ id: string;
1010
+ label: string;
1011
+ description?: string;
1012
+ attributeIds: string[];
1013
+ collapsible?: boolean;
1014
+ collapsed?: boolean;
1015
+ order?: number;
1016
+ }
1017
+ interface BaseAttribute<DefaultValueType = unknown> {
1018
+ id: Uuid;
1019
+ name: string;
1020
+ label: string;
1021
+ type: AttributeType;
1022
+ required: boolean;
1023
+ disabled?: boolean;
1024
+ placeholder?: string;
1025
+ description?: string;
1026
+ defaultValue?: DefaultValueType;
1027
+ icon?: IconName;
1028
+ order?: number;
1029
+ hidden?: boolean;
1030
+ archived?: boolean;
1031
+ deprecated?: boolean;
1032
+ system?: boolean;
1033
+ /**
1034
+ * Feature gate to conditionally show/hide/disable this attribute.
1035
+ * When the flag condition is not met, the attribute behavior depends on `fallback`:
1036
+ * - "hide" (default): Attribute is completely hidden
1037
+ * - "disable": Attribute is visible but read-only
1038
+ * - "show": No gating (useful for overriding parent settings)
1039
+ */
1040
+ featureGate?: FeatureGate;
1041
+ metadata?: Record<string, unknown>;
1042
+ }
1043
+ interface TextAttribute extends BaseAttribute<string> {
1044
+ type: "text";
1045
+ minLength?: number;
1046
+ maxLength?: number;
1047
+ pattern?: string;
1048
+ }
1049
+ type NumberUnit = "integer" | "decimal" | "percentage";
1050
+ interface NumberAttribute extends BaseAttribute<number> {
1051
+ type: "number";
1052
+ min?: number;
1053
+ max?: number;
1054
+ unit?: NumberUnit;
1055
+ decimals?: number;
1056
+ }
1057
+ interface CheckboxAttribute extends BaseAttribute<boolean> {
1058
+ type: "checkbox";
1059
+ }
1060
+ type DateFormat = "short" | "long" | "full" | "relative";
1061
+ type DateValue = string | "today";
1062
+ interface DateAttribute extends BaseAttribute<string> {
1063
+ type: "date";
1064
+ dateFormat?: DateFormat;
1065
+ minDate?: DateValue;
1066
+ maxDate?: DateValue;
1067
+ }
1068
+ interface Phone {
1069
+ countryCode: CountryIso3;
1070
+ phoneNumber: string;
1071
+ }
1072
+ interface PhoneAttribute extends BaseAttribute<Phone> {
1073
+ type: "phone";
1074
+ defaultCountryCode?: CountryIso3;
1075
+ }
1076
+ interface Currency {
1077
+ code: CurrencyCode;
1078
+ value: number;
1079
+ }
1080
+ interface CurrencyAttribute extends BaseAttribute<Currency> {
1081
+ type: "currency";
1082
+ defaultCurrency?: CurrencyCode;
1083
+ allowedCurrencies?: CurrencyCode[];
1084
+ /** Allow negative currency values (e.g. refunds, credits). Defaults to false. */
1085
+ allowNegative?: boolean;
1086
+ }
1087
+ /**
1088
+ * StatusAttribute - For workflow states with semantic grouping (idle/in_progress/finished)
1089
+ * Use this for: Task status, Order status, Project phases, Process states
1090
+ * Use SelectAttribute for: Categories, Types, simple choices without workflow
1091
+ */
1092
+ interface StatusAttribute extends BaseAttribute<string> {
1093
+ type: "status";
1094
+ options: Option[];
1095
+ }
1096
+ interface Location {
1097
+ address?: string;
1098
+ address2?: string;
1099
+ city?: string;
1100
+ state?: string;
1101
+ postalCode?: string;
1102
+ country?: CountryIso3;
1103
+ latitude?: number;
1104
+ longitude?: number;
1105
+ }
1106
+ type LocationGranularity = "full" | "address" | "city" | "state" | "country" | "coordinates";
1107
+ interface LocationAttribute extends BaseAttribute<Location> {
1108
+ type: "location";
1109
+ granularity: LocationGranularity;
1110
+ enableAutocomplete?: boolean;
1111
+ enableMap?: boolean;
1112
+ defaultCountry?: CountryIso3;
1113
+ allowedCountries?: CountryIso3[];
1114
+ displayFormat?: "single_line" | "multi_line" | "compact";
1115
+ }
1116
+ /**
1117
+ * SelectAttribute - For simple single-choice selection
1118
+ * Use this for: Categories, Document types, Departments, Priorities
1119
+ * Options can be grouped (e.g., countries by continent) but no workflow logic
1120
+ */
1121
+ interface SelectAttribute extends BaseAttribute<string> {
1122
+ type: "select";
1123
+ options: Option[];
1124
+ }
1125
+ interface MultiselectAttribute extends BaseAttribute<string[]> {
1126
+ type: "multiselect";
1127
+ options: Option[];
1128
+ }
1129
+ interface FileAttribute extends BaseAttribute<string> {
1130
+ type: "file";
1131
+ maxFiles?: number;
1132
+ maxSize?: number;
1133
+ allowedTypes?: MimeType[] | readonly MimeType[];
1134
+ multiple?: boolean;
1135
+ }
1136
+ interface UserAttribute extends BaseAttribute<string> {
1137
+ type: "user";
1138
+ allowedRoles?: string[];
1139
+ multiple?: boolean;
1140
+ }
1141
+ /**
1142
+ * Wildcard marker for universal relations (can link to any object)
1143
+ * Use with `.toAny()` builder method
1144
+ */
1145
+ declare const RELATION_TARGET_ANY: "*";
1146
+ /**
1147
+ * Configuration for bilateral synchronization (bidirectional relations)
1148
+ */
1149
+ interface BilateralConfig {
1150
+ /** Target object containing the inverse attribute */
1151
+ object: string;
1152
+ /** Name of the inverse attribute */
1153
+ attribute: string;
1154
+ /** Optional cardinality override (inferred by default) */
1155
+ cardinality?: "one" | "many";
1156
+ /** When true, this side owns the storage direction for qualified properties.
1157
+ * Set to false on the inverse side (enriched at read time). */
1158
+ storageOwner?: boolean;
1159
+ }
1160
+ /**
1161
+ * Target object for a relation - defines which objects can be linked
1162
+ */
1163
+ interface RelationTarget {
1164
+ /** Object name (e.g., "companies", "contacts") or "*" for any object */
1165
+ object: string;
1166
+ /**
1167
+ * Display template for the label using mustache-like syntax
1168
+ * @example "{name}" or "{firstName} {lastName} — {email}"
1169
+ */
1170
+ displayTemplate?: string;
1171
+ /**
1172
+ * Optional filter to restrict available records
1173
+ * @example { status: "active" }
1174
+ */
1175
+ filter?: Record<string, unknown>;
1176
+ }
1177
+ /**
1178
+ * Base properties shared by both single and multi relation attributes
1179
+ *
1180
+ * Note: Deletion behavior is always "restrict" - if a record is referenced
1181
+ * by other records, it cannot be deleted until those references are removed.
1182
+ * This is enforced by RecordService.deleteRecord() which throws
1183
+ * RecordReferencedError when attempting to delete a referenced record.
1184
+ */
1185
+ interface RelationAttributeBase extends Omit<BaseAttribute<unknown>, "defaultValue"> {
1186
+ type: "relation";
1187
+ /** Target objects that can be linked */
1188
+ targets: RelationTarget[];
1189
+ /** Optional properties schema for qualified relations */
1190
+ properties?: PropertySchema;
1191
+ /** Configuration for bilateral synchronization (opt-in) */
1192
+ bilateral?: BilateralConfig;
1193
+ }
1194
+ /**
1195
+ * Single relation attribute (one-to-one or many-to-one)
1196
+ * Stores a single record ID or null
1197
+ */
1198
+ interface SingleRelationAttribute extends RelationAttributeBase {
1199
+ cardinality: "one";
1200
+ defaultValue?: string | null;
1201
+ }
1202
+ /**
1203
+ * Multi relation attribute (one-to-many or many-to-many)
1204
+ * Stores an array of record IDs
1205
+ */
1206
+ interface MultiRelationAttribute extends RelationAttributeBase {
1207
+ cardinality: "many";
1208
+ defaultValue?: string[];
1209
+ /** Minimum number of relations required */
1210
+ minItems?: number;
1211
+ /** Maximum number of relations allowed */
1212
+ maxItems?: number;
1213
+ }
1214
+ /**
1215
+ * RelationAttribute links to other objects/records
1216
+ * Discriminated union by cardinality for type-safe value handling
1217
+ *
1218
+ * @example Single relation (many-to-one)
1219
+ * ```typescript
1220
+ * relation({ name: "company", label: "Company" })
1221
+ * .to("companies")
1222
+ * .required()
1223
+ * // → Value: "rec-uuid-123" | null
1224
+ * ```
1225
+ *
1226
+ * @example Multi relation (many-to-many)
1227
+ * ```typescript
1228
+ * relation({ name: "contacts", label: "Contacts" })
1229
+ * .to("contacts", { displayTemplate: "{firstName} {lastName}" })
1230
+ * .many()
1231
+ * .maxItems(5)
1232
+ * // → Value: ["rec-1", "rec-2", ...]
1233
+ * ```
1234
+ *
1235
+ * @example Polymorphic relation (multiple target objects)
1236
+ * ```typescript
1237
+ * relation({ name: "linked", label: "Linked Items" })
1238
+ * .to("companies")
1239
+ * .to("contacts")
1240
+ * .to("deals")
1241
+ * .many()
1242
+ * // → Can link to records from any of these objects
1243
+ * ```
1244
+ */
1245
+ type RelationAttribute = SingleRelationAttribute | MultiRelationAttribute;
1246
+ /**
1247
+ * Check if a relation attribute is universal (can link to any object)
1248
+ * Universal relations have `targets: [{ object: "*" }]`
1249
+ */
1250
+ declare function isUniversalRelation(attr: RelationAttribute): boolean;
1251
+ /**
1252
+ * Check if a relation attribute has bilateral synchronization enabled
1253
+ */
1254
+ declare function isBilateralRelation(attr: RelationAttribute): attr is RelationAttribute & {
1255
+ bilateral: BilateralConfig;
1256
+ };
1257
+ /**
1258
+ * Infer the cardinality of the inverse relation
1259
+ * - one → many (contact.company ↔ company.contacts)
1260
+ * - many → many (contact.tags ↔ tag.contacts)
1261
+ */
1262
+ declare function inferInverseCardinality(cardinality: "one" | "many"): "one" | "many";
1263
+ interface TextAreaAttribute extends BaseAttribute<string> {
1264
+ type: "textarea";
1265
+ }
1266
+ /**
1267
+ * Available features for richtext editor
1268
+ */
1269
+ type RichtextFeature = "headings" | "bold" | "italic" | "lists" | "links" | "images" | "codeBlocks" | "tables";
1270
+ /**
1271
+ * RichtextAttribute - Rich text content using semantic markdown
1272
+ *
1273
+ * Stores content as semantic markdown string (with directives like :::callout).
1274
+ * Parsed at runtime to Tiptap JSON for editing.
1275
+ * Use this for: Notes, articles, descriptions, long-form content.
1276
+ *
1277
+ * @example
1278
+ * ```typescript
1279
+ * richtext({ name: "content", label: "Content" })
1280
+ * .features(["headings", "bold", "italic", "lists", "links"])
1281
+ * .required()
1282
+ * ```
1283
+ */
1284
+ interface RichtextAttribute extends BaseAttribute<string> {
1285
+ type: "richtext";
1286
+ /** Enabled features. If undefined, all features are enabled. */
1287
+ features?: RichtextFeature[];
1288
+ }
1289
+ interface RatingAttribute extends BaseAttribute<number> {
1290
+ type: "rating";
1291
+ max?: number;
1292
+ iconType?: "star" | "heart" | "thumbs" | "number";
1293
+ }
1294
+ /**
1295
+ * Return type for formula expressions
1296
+ */
1297
+ type FormulaReturnType = "text" | "number" | "boolean" | "date";
1298
+ /**
1299
+ * FormulaAttribute - Computed value based on other attributes
1300
+ *
1301
+ * Formulas are calculated at read-time and are always read-only.
1302
+ * Users cannot directly edit formula values.
1303
+ *
1304
+ * @example Simple calculation
1305
+ * ```typescript
1306
+ * formula({ name: "total", label: "Total" })
1307
+ * .expression("price * quantity")
1308
+ * .returns("number")
1309
+ * .decimals(2)
1310
+ * ```
1311
+ *
1312
+ * @example With functions
1313
+ * ```typescript
1314
+ * formula({ name: "fullName", label: "Full Name" })
1315
+ * .expression("CONCAT(firstName, ' ', lastName)")
1316
+ * .returns("text")
1317
+ * ```
1318
+ */
1319
+ interface FormulaAttribute extends Omit<BaseAttribute<never>, "defaultValue" | "required"> {
1320
+ type: "formula";
1321
+ /** Expression to evaluate (e.g., "price * quantity") */
1322
+ expression: string;
1323
+ /** Expected return type for formatting */
1324
+ returnType: FormulaReturnType;
1325
+ /** Decimal places for number results */
1326
+ decimals?: number;
1327
+ /** Whether to allow relation references in the expression (e.g., "company.name") */
1328
+ allowRelations?: boolean;
1329
+ /** Formula is always not required (read-only) */
1330
+ required: false;
1331
+ }
1332
+ /**
1333
+ * Aggregation functions for rollup attributes
1334
+ *
1335
+ * Categories:
1336
+ * - Numeric (sum, avg): Only for number, currency, rating types
1337
+ * - Date (earliest, latest): Only for date type
1338
+ * - Count (count, countValues, countUniqueValues, countEmpty): Universal
1339
+ * - Percent (percentEmpty, percentNotEmpty): Universal
1340
+ * - Lookup (original): Returns all values as array, rendered as target type
1341
+ */
1342
+ type RollupFunction = "sum" | "avg" | "earliest" | "latest" | "count" | "countValues" | "countUniqueValues" | "countEmpty" | "percentEmpty" | "percentNotEmpty" | "original";
1343
+ /**
1344
+ * RollupAttribute - Aggregates values from related records
1345
+ *
1346
+ * Rollups are calculated and stored (denormalized) for performance.
1347
+ * They are automatically recalculated when related records change.
1348
+ * Users cannot directly edit rollup values.
1349
+ *
1350
+ * @example Sum of related amounts
1351
+ * ```typescript
1352
+ * rollup({ name: "totalOrders", label: "Total Orders" })
1353
+ * .from("orders") // relation attribute name
1354
+ * .aggregate("amount") // target attribute to sum
1355
+ * .using("sum")
1356
+ * .decimals(2)
1357
+ * ```
1358
+ *
1359
+ * @example Count of related records
1360
+ * ```typescript
1361
+ * rollup({ name: "orderCount", label: "Number of Orders" })
1362
+ * .from("orders")
1363
+ * .using("count")
1364
+ * ```
1365
+ */
1366
+ interface RollupAttribute extends Omit<BaseAttribute<never>, "defaultValue" | "required"> {
1367
+ type: "rollup";
1368
+ /** Name of the relation attribute on this object */
1369
+ relationAttribute: string;
1370
+ /**
1371
+ * Dot notation path for multi-level traversal (Phase 4+)
1372
+ * @example "orders.items" - traverse through orders to items
1373
+ */
1374
+ relationPath?: string;
1375
+ /** Attribute name on the target object to aggregate */
1376
+ targetAttribute: string;
1377
+ /** Aggregation function to apply */
1378
+ function: RollupFunction;
1379
+ /** Decimal places for numeric results */
1380
+ decimals?: number;
1381
+ /** Rollup is always not required (read-only) */
1382
+ required: false;
1383
+ /**
1384
+ * Cached type of the target attribute for display purposes
1385
+ * Used when function="original" to render values as the target type
1386
+ */
1387
+ targetAttributeType?: AttributeType;
1388
+ /**
1389
+ * Cached options from target attribute (for select/status/multiselect display)
1390
+ * Required when function="original" and target is a select-like type
1391
+ */
1392
+ targetAttributeOptions?: Option[];
1393
+ }
1394
+ /**
1395
+ * DocumentAttribute - References one or multiple structured documents.
1396
+ *
1397
+ * Unlike FileAttribute which stores raw file references, DocumentAttribute
1398
+ * provides structured document handling with multi-file support and
1399
+ * optional agent-compatible processing (for example OCR).
1400
+ *
1401
+ * @example Single document
1402
+ * ```typescript
1403
+ * document({ name: "identityDocument", label: "Pièce d'identité" })
1404
+ * .autoProcess()
1405
+ * .required()
1406
+ * ```
1407
+ *
1408
+ * @example Multiple documents
1409
+ * ```typescript
1410
+ * document({ name: "contracts", label: "Contrats" })
1411
+ * .multiple()
1412
+ * .maxDocuments(10)
1413
+ * ```
1414
+ */
1415
+ interface DocumentAttribute extends BaseAttribute<string | string[]> {
1416
+ type: "document";
1417
+ /**
1418
+ * Allow multiple documents.
1419
+ * If true, value is string[] (document IDs).
1420
+ * If false/undefined, value is string (single document ID).
1421
+ */
1422
+ multiple?: boolean;
1423
+ /**
1424
+ * Maximum number of documents when multiple: true.
1425
+ */
1426
+ maxDocuments?: number;
1427
+ /**
1428
+ * Automatically trigger agent-compatible processing on upload.
1429
+ */
1430
+ autoProcess?: boolean;
1431
+ /** Child attribute definitions for per-document metadata. */
1432
+ attributes?: Attribute[];
1433
+ /**
1434
+ * File slots declared on this attribute. Builder injects
1435
+ * [DEFAULT_DOCUMENT_SLOT] when omitted. Always non-empty in practice.
1436
+ */
1437
+ slots?: DocumentSlotConfig[];
1438
+ }
1439
+ type Attribute = TextAttribute | TextAreaAttribute | RichtextAttribute | NumberAttribute | CheckboxAttribute | DateAttribute | PhoneAttribute | CurrencyAttribute | StatusAttribute | LocationAttribute | SelectAttribute | MultiselectAttribute | FileAttribute | UserAttribute | RelationAttribute | RatingAttribute | FormulaAttribute | RollupAttribute | DocumentAttribute;
1440
+ /**
1441
+ * Check if an attribute supports sorting based on its type.
1442
+ */
1443
+ declare function isAttributeSortable(attr: {
1444
+ type: AttributeType;
1445
+ }): boolean;
1446
+
1447
+ /** Operators for text-based attributes */
1448
+ type TextFilterOperator = "is" | "is_not" | "contains" | "not_contains" | "starts_with" | "ends_with" | "is_empty" | "is_not_empty";
1449
+ /** Operators for number-based attributes */
1450
+ type NumberFilterOperator = "eq" | "neq" | "lt" | "gt" | "lte" | "gte" | "is_empty" | "is_not_empty";
1451
+ /** Operators for checkbox */
1452
+ type CheckboxFilterOperator = "is_checked" | "is_not_checked";
1453
+ /** Operators for date-based attributes */
1454
+ type DateFilterOperator = "is" | "is_not" | "before" | "after" | "on_or_before" | "on_or_after" | "is_within" | "day_month_eq" | "is_empty" | "is_not_empty";
1455
+ /** Operators for select-based attributes (supports single or multi-value filtering) */
1456
+ type SelectFilterOperator = "is" | "is_not" | "any_of" | "none_of" | "is_empty" | "is_not_empty";
1457
+ /** Operators for multiselect-based attributes */
1458
+ type MultiselectFilterOperator = "contains" | "not_contains" | "is_empty" | "is_not_empty";
1459
+ /** Operators for relation-based attributes (supports single or multi-value filtering) */
1460
+ type RelationFilterOperator = "any_of" | "none_of" | "contains" | "not_contains" | "is_empty" | "is_not_empty";
1461
+ /** All possible filter operators */
1462
+ type FilterOperator = TextFilterOperator | NumberFilterOperator | CheckboxFilterOperator | DateFilterOperator | SelectFilterOperator | MultiselectFilterOperator | RelationFilterOperator;
1463
+ /** Relative date value for "is_within" operator */
1464
+ interface RelativeDateValue {
1465
+ amount: number;
1466
+ unit: "days" | "weeks" | "months" | "years";
1467
+ direction: "past" | "future";
1468
+ }
1469
+ /** Currency filter value with amount and optional currency codes
1470
+ * - code: undefined or [] = any currency
1471
+ * - code: string[] = filter by specific currencies
1472
+ */
1473
+ interface CurrencyFilterValue {
1474
+ value: number | null;
1475
+ code?: string[];
1476
+ }
1477
+ /** Phone filter value with number and optional country code */
1478
+ interface PhoneFilterValue {
1479
+ phoneNumber: string | null;
1480
+ countryCode?: string;
1481
+ }
1482
+ /** Filter value can be various types depending on the attribute */
1483
+ type FilterValue = string | number | boolean | string[] | RelativeDateValue | CurrencyFilterValue | PhoneFilterValue | null;
1484
+ /** A single filter rule */
1485
+ interface FilterRule {
1486
+ /** Attribute name to filter on */
1487
+ attribute: string;
1488
+ /** Filter operator */
1489
+ operator: FilterOperator;
1490
+ /** Filter value (null for operators like is_empty) */
1491
+ value: FilterValue;
1492
+ }
1493
+ /**
1494
+ * Extended filter rule with optional attribute definition.
1495
+ * When provided, enables smarter type-aware filtering (e.g., array operators for multiselect).
1496
+ */
1497
+ interface ExtendedFilterRule extends FilterRule {
1498
+ /** Full attribute definition for type-aware filtering */
1499
+ attributeDef?: Attribute;
1500
+ }
1501
+ /** Combinator for filter rules */
1502
+ type FilterCombinator = "and" | "or";
1503
+ /** Complete filter state (simple mode) */
1504
+ interface FilterState {
1505
+ /** How to combine rules */
1506
+ combinator: FilterCombinator;
1507
+ /** List of filter rules */
1508
+ rules: FilterRule[];
1509
+ }
1510
+ /**
1511
+ * A filter group containing rules (used in advanced mode)
1512
+ * Groups can be nested up to 2 levels deep
1513
+ */
1514
+ interface FilterGroup {
1515
+ /** Unique identifier for this group */
1516
+ id: string;
1517
+ /** How to combine rules within this group */
1518
+ combinator: FilterCombinator;
1519
+ /** List of filter rules in this group */
1520
+ rules: FilterRule[];
1521
+ }
1522
+ /**
1523
+ * Advanced filter state with nested groups
1524
+ * Structure: AdvancedFilterState -> FilterGroup[] -> FilterRule[]
1525
+ * Maximum 2 levels of nesting
1526
+ */
1527
+ interface AdvancedFilterState {
1528
+ /** How to combine groups at the top level */
1529
+ combinator: FilterCombinator;
1530
+ /** List of filter groups */
1531
+ groups: FilterGroup[];
1532
+ }
1533
+ /** Sort direction */
1534
+ type SortDirection = "asc" | "desc";
1535
+ /** A single sort rule */
1536
+ interface SortRule {
1537
+ /** Attribute name to sort by */
1538
+ attribute: string;
1539
+ /** Sort direction */
1540
+ direction: SortDirection;
1541
+ }
1542
+ /** Complete query state with search, filters, sorts, and pagination */
1543
+ interface QueryState {
1544
+ /** Full-text search query */
1545
+ search?: string;
1546
+ /** Filter configuration (simple mode) */
1547
+ filters?: FilterState;
1548
+ /** Advanced filter configuration (grouped mode) */
1549
+ advancedFilters?: AdvancedFilterState;
1550
+ /** Sort configuration (multiple sorts supported) */
1551
+ sorts?: SortRule[];
1552
+ /** Pagination */
1553
+ limit?: number;
1554
+ offset?: number;
1555
+ }
1556
+ /** Mapping of attribute types to their valid operators (rollup excluded — use getRollupFilterOperators()) */
1557
+ declare const OPERATORS_BY_TYPE: Record<Exclude<AttributeType, "rollup">, readonly FilterOperator[]>;
1558
+ /** Check if an operator requires a value */
1559
+ type NoValueOperator = "is_empty" | "is_not_empty" | "is_checked" | "is_not_checked";
1560
+ /** Operators that don't require a value */
1561
+ declare const NO_VALUE_OPERATORS: readonly NoValueOperator[];
1562
+ /**
1563
+ * Check if an operator requires a value
1564
+ */
1565
+ declare function isNoValueOperator(operator: FilterOperator): operator is NoValueOperator;
1566
+ /**
1567
+ * Get the filter operators for a rollup attribute based on its aggregation function and target type.
1568
+ *
1569
+ * - earliest / latest → date operators
1570
+ * - original → operators matching targetAttributeType (falls back to numeric if unknown)
1571
+ * - all other functions → numeric operators (sum, avg, count, percent, etc.)
1572
+ */
1573
+ declare function getRollupFilterOperators(attr: RollupAttribute): readonly FilterOperator[];
1574
+
1575
+ export { type Group as $, type Attribute as A, type BilateralConfig as B, type CurrencyAttribute as C, type DateAttribute as D, type RelationTarget as E, type FileAttribute as F, type RichtextFeature as G, type RollupFunction as H, type MigrationDefinition as I, type DetailViewConfig as J, type DetailViewDefinition as K, type LocationAttribute as L, type MultiRelationAttribute as M, type NumberAttribute as N, type ObjectDefinition as O, type PhoneAttribute as P, type DetailViewLayout as Q, type RelationAttribute as R, type SingleRelationAttribute as S, type TextAreaAttribute as T, type UserAttribute as U, type ViewType as V, type SidePanelConfig as W, type Field as X, type AttributeGroupField as Y, type FieldGroup as Z, type RelationGroup as _, type RichtextAttribute as a, type RelativeDateValue as a$, type TableTab as a0, type CreateMode as a1, type Tab as a2, type ListViewConfig as a3, type ListViewDefinition as a4, type FlagValueType as a5, type FeatureFlagDefinition as a6, type FlagLevel as a7, type FeatureFlagsRepository as a8, type StaticFlagDefault as a9, type FilterGroup as aA, type FilterRule as aB, type FlagOverride as aC, type FormDensity as aD, type FormTab as aE, type FormsTab as aF, type InverseSource as aG, type ListViewLayout as aH, type MigrationError as aI, NO_VALUE_OPERATORS as aJ, type NoValueOperator as aK, type NumberUnit as aL, OPERATORS_BY_TYPE as aM, type ObjectAttribute as aN, type OptionPropertyAttribute as aO, type PhoneFilterValue as aP, type ProcessingJob as aQ, type ProcessingJobStatus as aR, type ProcessingJobType as aS, type PropertyAttribute as aT, type PropertySchema as aU, type PropertyType as aV, type QueryState as aW, RELATION_TARGET_ANY as aX, RESERVED_ATTRIBUTE_NAMES as aY, type RecordDocuments as aZ, type RelationSource as a_, type ResolvedFlag as aa, type ViewDefinition as ab, type ListViewTab as ac, type FilterOperator as ad, type FilterValue as ae, type ActivityTab as af, type AdvancedFilterState as ag, type AttributeGroup as ah, type BaseAttribute as ai, type BuiltInTransform as aj, type CreateDocument as ak, type CreateDocumentSlot as al, type CreateProcessingJob as am, type CurrencyFilterValue as an, type CustomTab as ao, DEFAULT_DOCUMENT_SLOT as ap, type DateFormat as aq, type DateValue as ar, type Document as as, type DocumentListOptions as at, type DocumentSlot as au, type DocumentWithSlots as av, type DocumentsTab as aw, type ExtendedFilterRule as ax, type FeatureFlagsConfig as ay, type FilterCombinator as az, type MultiselectAttribute as b, type ReservedAttributeName as b0, type RichtextTab as b1, SYSTEM_FIELD_NAMES as b2, type SchemaOperation as b3, type SchemaTransform as b4, type SlotStatus as b5, type SortDirection as b6, type StatusGroup as b7, type SystemFieldName as b8, type TabType as b9, type TableSource as ba, type TransformSource as bb, type UpdateDocument as bc, type UpdateDocumentSlot as bd, type UpdateProcessingJob as be, type ViewOperation as bf, type ViewOverlay as bg, type ViewTransform as bh, getRollupFilterOperators as bi, hasOptions as bj, inferInverseCardinality as bk, isAttributeSortable as bl, isBilateralRelation as bm, isDetailView as bn, isFieldGroup as bo, isListView as bp, isNoValueOperator as bq, isRelationGroup as br, isUniversalRelation as bs, type SelectAttribute as c, type StatusAttribute as d, type FormulaAttribute as e, type RollupAttribute as f, type CheckboxAttribute as g, type RatingAttribute as h, type TextAttribute as i, type CompletionStatus as j, type SortRule as k, type FilterState as l, type Timestamps as m, type AttributeType as n, type ViewConfig as o, type ConfigOverrides as p, type LocationGranularity as q, type Location as r, type Phone as s, type Currency as t, type ObjectRecord as u, type DocumentAttribute as v, type DocumentSlotConfig as w, type FeatureGate as x, type FormulaReturnType as y, type Option as z };