-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathobject.zod.ts
More file actions
755 lines (687 loc) · 32 KB
/
object.zod.ts
File metadata and controls
755 lines (687 loc) · 32 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
// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.
import { z } from 'zod';
import { FieldSchema } from './field.zod';
import { ValidationRuleSchema } from './validation.zod';
import { StateMachineSchema } from '../automation/state-machine.zod';
import { ActionSchema } from '../ui/action.zod';
import { ListViewSchema } from '../ui/view.zod';
/**
* API Operations Enum
*/
import { ExpressionInputSchema , TemplateExpressionInputSchema } from '../shared/expression.zod';
import { lazySchema } from '../shared/lazy-schema';
export const ApiMethod = z.enum([
'get', 'list', // Read
'create', 'update', 'delete', // Write
'upsert', // Idempotent Write
'bulk', // Batch operations
'aggregate', // Analytics (count, sum)
'history', // Audit access
'search', // Search access
'restore', 'purge', // Trash management
'import', 'export', // Data portability
]);
export type ApiMethod = z.infer<typeof ApiMethod>;
/**
* Capability Flags
* Defines what system features are enabled for this object.
*
* Optimized based on industry standards (Salesforce, ServiceNow):
* - Added `activities` (Tasks/Events)
* - Added `mru` (Recent Items)
* - Added `feeds` (Social/Chatter)
* - Grouped API permissions
*
* @example
* {
* trackHistory: true,
* searchable: true,
* apiEnabled: true,
* files: true
* }
*/
export const ObjectCapabilities = z.object({
/** Enable history tracking (Audit Trail) */
trackHistory: z.boolean().default(false).describe('Enable field history tracking for audit compliance'),
/** Enable global search indexing */
searchable: z.boolean().default(true).describe('Index records for global search'),
/** Enable REST/GraphQL API access */
apiEnabled: z.boolean().default(true).describe('Expose object via automatic APIs'),
/**
* API Supported Operations
* Granular control over API exposure.
*/
apiMethods: z.array(ApiMethod).optional().describe('Whitelist of allowed API operations'),
/** Enable standard attachments/files engine */
files: z.boolean().default(false).describe('Enable file attachments and document management'),
/** Enable social collaboration (Comments, Mentions, Feeds) */
feeds: z.boolean().default(false).describe('Enable social feed, comments, and mentions (Chatter-like)'),
/** Enable standard Activity suite (Tasks, Calendars, Events) */
activities: z.boolean().default(false).describe('Enable standard tasks and events tracking'),
/** Enable Recycle Bin / Soft Delete */
trash: z.boolean().default(true).describe('Enable soft-delete with restore capability'),
/** Enable "Recently Viewed" tracking */
mru: z.boolean().default(true).describe('Track Most Recently Used (MRU) list for users'),
/** Allow cloning records */
clone: z.boolean().default(true).describe('Allow record deep cloning'),
});
/**
* Schema for database indexes.
* Enhanced with additional index types and configuration options
*
* @example
* {
* name: "idx_account_name",
* fields: ["name"],
* type: "btree",
* unique: true
* }
*/
export const IndexSchema = lazySchema(() => z.object({
name: z.string().optional().describe('Index name (auto-generated if not provided)'),
fields: z.array(z.string()).describe('Fields included in the index'),
type: z.enum(['btree', 'hash', 'gin', 'gist', 'fulltext']).optional().default('btree').describe('Index algorithm type'),
unique: z.boolean().optional().default(false).describe('Whether the index enforces uniqueness'),
partial: z.string().optional().describe('Partial index condition (SQL WHERE clause for conditional indexes)'),
}));
/**
* Search Configuration
* Defines how this object behaves in search results.
*
* @example
* {
* fields: ["name", "email", "phone"],
* displayFields: ["name", "title"],
* filters: ["status = 'active'"]
* }
*/
export const SearchConfigSchema = lazySchema(() => z.object({
fields: z.array(z.string()).describe('Fields to index for full-text search weighting'),
displayFields: z.array(z.string()).optional().describe('Fields to display in search result cards'),
filters: z.array(z.string()).optional().describe('Default filters for search results'),
}));
/**
* Multi-Tenancy Configuration Schema
* Configures tenant isolation strategy for SaaS applications
*
* @example Shared database with tenant_id isolation
* {
* enabled: true,
* strategy: 'shared',
* tenantField: 'tenant_id',
* crossTenantAccess: false
* }
*/
export const TenancyConfigSchema = lazySchema(() => z.object({
enabled: z.boolean().describe('Enable multi-tenancy for this object'),
strategy: z.enum(['shared', 'isolated', 'hybrid']).describe('Tenant isolation strategy: shared (single DB, row-level), isolated (separate DB per tenant), hybrid (mix)'),
tenantField: z.string().default('tenant_id').describe('Field name for tenant identifier'),
crossTenantAccess: z.boolean().default(false).describe('Allow cross-tenant data access (with explicit permission)'),
}));
/**
* Soft Delete Configuration Schema
* Implements recycle bin / trash functionality
*
* @example Standard soft delete with cascade
* {
* enabled: true,
* field: 'deleted_at',
* cascadeDelete: true
* }
*/
export const SoftDeleteConfigSchema = lazySchema(() => z.object({
enabled: z.boolean().describe('Enable soft delete (trash/recycle bin)'),
field: z.string().default('deleted_at').describe('Field name for soft delete timestamp'),
cascadeDelete: z.boolean().default(false).describe('Cascade soft delete to related records'),
}));
/**
* Versioning Configuration Schema
* Implements record versioning and history tracking
*
* @example Snapshot versioning with 90-day retention
* {
* enabled: true,
* strategy: 'snapshot',
* retentionDays: 90,
* versionField: 'version'
* }
*/
export const VersioningConfigSchema = lazySchema(() => z.object({
enabled: z.boolean().describe('Enable record versioning'),
strategy: z.enum(['snapshot', 'delta', 'event-sourcing']).describe('Versioning strategy: snapshot (full copy), delta (changes only), event-sourcing (event log)'),
retentionDays: z.number().min(1).optional().describe('Number of days to retain old versions (undefined = infinite)'),
versionField: z.string().default('version').describe('Field name for version number/timestamp'),
}));
/**
* Partitioning Strategy Schema
* Configures table partitioning for performance at scale
*
* @example Range partitioning by date (monthly)
* {
* enabled: true,
* strategy: 'range',
* key: 'created_at',
* interval: '1 month'
* }
*/
export const PartitioningConfigSchema = lazySchema(() => z.object({
enabled: z.boolean().describe('Enable table partitioning'),
strategy: z.enum(['range', 'hash', 'list']).describe('Partitioning strategy: range (date ranges), hash (consistent hashing), list (predefined values)'),
key: z.string().describe('Field name to partition by'),
interval: z.string().optional().describe('Partition interval for range strategy (e.g., "1 month", "1 year")'),
}).refine((data) => {
// If strategy is 'range', interval must be provided
if (data.strategy === 'range' && !data.interval) {
return false;
}
return true;
}, {
message: 'interval is required when strategy is "range"',
}));
/**
* Change Data Capture (CDC) Configuration Schema
* Enables real-time data streaming to external systems
*
* @example Stream all changes to Kafka
* {
* enabled: true,
* events: ['insert', 'update', 'delete'],
* destination: 'kafka://events.objectstack'
* }
*/
export const CDCConfigSchema = lazySchema(() => z.object({
enabled: z.boolean().describe('Enable Change Data Capture'),
events: z.array(z.enum(['insert', 'update', 'delete'])).describe('Event types to capture'),
destination: z.string().describe('Destination endpoint (e.g., "kafka://topic", "webhook://url")'),
}));
/**
* Object Field Group Schema — MVP (data-layer protocol)
*
* Declares the set of logical field groups for an object. A group bundles
* related fields together for presentation in forms, detail pages, and
* editors (e.g., "Contact Info", "Billing", "System").
*
* Design rules (MVP):
* - Group **order** is the declaration order of this array — no `order` property.
* - Field → group mapping is derived automatically from `Field.group`
* matching `ObjectFieldGroup.key`; the **in-group display order** equals
* the traversal order of `ObjectSchema.fields`.
* - Fields whose `group` is unset (or references an undeclared key) are
* considered ungrouped and must be rendered by consumers in a default
* bucket after the declared groups, preserving their field declaration order.
* - Extension packages and runtime code use `Field.group` to assign fields
* to an existing group — no per-field order property is introduced at this
* layer.
*
* Migration operations supported by this MVP:
* - add / rename / delete / reorder groups (via the array)
* - assign an existing field to a group (via `Field.group`)
*
* Deferred (not part of MVP):
* - explicit per-field in-group ordering
* - nested groups / sub-groups
* - permission-scoped group visibility beyond `visibleOn`
*
* @example
* ```ts
* fieldGroups: [
* { key: 'contact_info', label: 'Contact Information', icon: 'user' },
* { key: 'billing', label: 'Billing', defaultExpanded: false },
* { key: 'system', label: 'System', visibleOn: '$user.isAdmin' },
* ]
* ```
*/
export const ObjectFieldGroupSchema = lazySchema(() => z.object({
/** Group key — referenced by `Field.group` to assign a field to this group. Must be snake_case. */
key: z.string().regex(/^[a-z_][a-z0-9_]*$/, {
message: 'Field group key must be lowercase snake_case (e.g., "contact_info", "billing", "system")',
}).describe('Group machine key (snake_case). Referenced by Field.group.'),
/** Human-readable label displayed as the group header. */
label: z.string().describe('Group display label'),
/** Optional Lucide/Material icon name for the group header. */
icon: z.string().optional().describe('Icon name (Lucide/Material) for the group header'),
/** Optional description / help text shown under the group header. */
description: z.string().optional().describe('Optional description shown under the group header'),
/** Whether the group is expanded by default. Defaults to `true`. */
defaultExpanded: z.boolean().optional().default(true).describe('Whether the group is expanded by default'),
/** Optional visibility expression — when false, the entire group is hidden (e.g., "$user.isAdmin", "status == \'closed\'"). */
visibleOn: ExpressionInputSchema.optional().describe('Visibility predicate (CEL); group is hidden when FALSE.'),
}));
export type ObjectFieldGroup = z.infer<typeof ObjectFieldGroupSchema>;
export type ObjectFieldGroupInput = z.input<typeof ObjectFieldGroupSchema>;
/**
* Base Object Schema Definition
*
* The Blueprint of a Business Object.
* Represents a table, a collection, or a virtual entity.
*
* @example
* ```yaml
* name: project_task
* label: Project Task
* icon: task
* fields:
* project:
* type: lookup
* reference: project
* status:
* type: select
* options: [todo, in_progress, done]
* enable:
* trackHistory: true
* files: true
* ```
*/
const ObjectSchemaBase = z.object({
/**
* Identity & Metadata
*/
name: z.string().regex(/^[a-z_][a-z0-9_]*$/).describe('Machine unique key (snake_case). Immutable.'),
label: z.string().optional().describe('Human readable singular label (e.g. "Account")'),
pluralLabel: z.string().optional().describe('Human readable plural label (e.g. "Accounts")'),
description: z.string().optional().describe('Developer documentation / description'),
icon: z.string().optional().describe('Icon name (Lucide/Material) for UI representation'),
/**
* Taxonomy & Organization
*/
tags: z.array(z.string()).optional().describe('Categorization tags (e.g. "sales", "system", "reference")'),
active: z.boolean().optional().default(true).describe('Is the object active and usable'),
isSystem: z.boolean().optional().default(false).describe('Is system object (protected from deletion)'),
abstract: z.boolean().optional().default(false).describe('Is abstract base object (cannot be instantiated)'),
/**
* Managed-by hint — declares which lifecycle bucket the object belongs
* to so UI clients render the appropriate set of CRUD affordances and
* the security layer can enforce matching defaults. Modelled after the
* way Salesforce / ServiceNow / Workday segregate user-owned business
* data from admin-authored configuration, system-driven runtime rows,
* and append-only audit trails.
*
* - `platform` — **Default.** User-owned business data. Generic
* New / Import / Edit / Delete affordances are all shown. Example:
* the user's own `sys_attachment`, `sys_comment`, `sys_saved_report`.
* - `config` — Admin-authored metadata / configuration. Generic
* New / Edit / Delete shown (admins author via wizard or form), but
* CSV Import is suppressed (config rows have nested JSON envelopes
* that don't round-trip through a flat sheet; clients should offer a
* purpose-built "Import definition (JSON)" action instead). Example:
* `sys_approval_process`, `sys_sharing_rule`, `sys_role`,
* `sys_permission_set`, `sys_view`, `sys_app`.
* - `system` — Runtime rows whose lifecycle is owned by a
* platform service (the approval engine, the sharing engine, the
* invitation service, …). Generic CRUD is hidden — users interact
* with these via *domain actions* invoked from the source record
* (e.g. "Submit for Approval" on an Opportunity creates an
* `sys_approval_request`; "Recall" on the request changes its
* state). Example: `sys_approval_request`, `sys_record_share`,
* `sys_notification`, `sys_invitation`,
* `sys_user_permission_set` / `sys_role_permission_set`.
* - `append-only` — Immutable audit log. No New / Import / Edit /
* Delete; only View and Export. Example: `sys_approval_action`,
* `sys_audit_log`, `sys_activity`, `sys_email`, `sys_presence`.
* - `better-auth` — Identity tables owned by the better-auth driver
* (sys_user, sys_session, sys_account, sys_member, sys_organization,
* sys_api_key, sys_jwks, sys_verification, sys_two_factor,
* sys_oauth_*, sys_device_code). Mutations must flow through the
* better-auth API so password hashing, token signing, email
* verification, and invitation flows fire correctly. Generic CRUD
* suppressed; replaced by purpose-built actions
* (Invite User, Reset Password, Revoke Session, Rotate Key, …).
*
* The flag is purely declarative on the schema. Enforcement happens in
* two places:
* 1. Default permission sets ({@link packages/platform-objects/src/security/default-permission-sets.ts})
* deny direct CRUD for `system` / `append-only` / `better-auth`.
* 2. UI clients honour {@link resolveCrudAffordances} to gate the
* New / Import / Edit / Delete / Export buttons accordingly.
*
* Use {@link userActions} to override the default matrix for a single
* field (e.g. an "append-only" table that should still allow Export).
*/
managedBy: z.enum(['platform', 'config', 'system', 'append-only', 'better-auth']).optional().describe(
'Lifecycle bucket — platform (user CRUD) | config (admin authored) | system (engine-managed) | append-only (audit) | better-auth (identity). UI clients honour the resolved affordance matrix.',
),
/**
* Per-object override of the generic CRUD affordances that the UI
* surfaces. Each flag overrides the default derived from
* {@link managedBy} via {@link resolveCrudAffordances}. Useful for the
* handful of objects whose lifecycle doesn't cleanly fit a single
* bucket — e.g. an `append-only` table that should still expose CSV
* Export, or a `config` table that admins legitimately want to bulk
* import via CSV.
*
* Omitting the block (or leaving individual flags `undefined`) keeps
* the {@link managedBy}-derived default.
*/
userActions: z.object({
create: z.boolean().optional().describe('Show generic "New" button.'),
import: z.boolean().optional().describe('Show CSV import wizard entry.'),
edit: z.boolean().optional().describe('Allow inline / form edit of existing rows.'),
delete: z.boolean().optional().describe('Show row-level delete + bulk delete.'),
exportCsv: z.boolean().optional().describe('Show CSV export entry.'),
}).optional().describe('Per-object override of the resolved CRUD affordance matrix.'),
/**
* System-field auto-injection control.
*
* The `SchemaRegistry` augments every user object with a small set of
* implicit system fields at registration time so authors don't have to
* declare them per-object (Salesforce-style). Currently injected:
*
* - `organization_id` — `lookup → sys_organization`. Injected only when
* the kernel runs in multi-tenant mode (`OS_MULTI_TENANT !== 'false'`).
* Required for the default `tenant_isolation` RLS policy and the
* SecurityPlugin's auto-fill on insert to take effect.
*
* Author-declared fields with the same name always win over injection
* (no overwrite). Objects with `managedBy` set are skipped entirely —
* better-auth/system/platform tables already declare what they need.
*
* Set `systemFields: false` to opt the object out completely. Pass an
* options object to selectively disable individual injections (currently
* only `tenant`, but reserved keys `owner`/`audit` are pre-defined for
* future expansion).
*
* @default undefined (= injection enabled, gated by kernel mode)
*/
systemFields: z
.union([
z.literal(false),
z.object({
tenant: z.boolean().optional().describe('Inject organization_id (multi-tenant only). Default true.'),
owner: z.boolean().optional().describe('Reserved for future owner_id auto-injection.'),
audit: z.boolean().optional().describe('Reserved for future created_by/updated_by auto-injection.'),
}),
])
.optional()
.describe('Opt out of, or selectively disable, registry-level system-field auto-injection.'),
/**
* Storage & Virtualization
*/
datasource: z.string().optional().default('default').describe('Target Datasource ID. "default" is the primary DB.'),
/**
* Data Model
*/
fields: z.record(z.string().regex(/^[a-z_][a-z0-9_]*$/, {
message: 'Field names must be lowercase snake_case (e.g., "first_name", "company", "annual_revenue")',
}), FieldSchema).describe('Field definitions map. Keys must be snake_case identifiers.'),
indexes: z.array(IndexSchema).optional().describe('Database performance indexes'),
/**
* Field Groups (MVP)
*
* Declares logical groups for presenting fields in forms and detail
* pages. The **array order is the group display order**. Each field's
* `Field.group` references an entry's `key` to assign it to a group;
* within a group, fields are displayed in their `ObjectSchema.fields`
* declaration order.
*
* See {@link ObjectFieldGroupSchema} for the full MVP contract and
* deferred features.
*/
fieldGroups: z.array(ObjectFieldGroupSchema).refine(
(groups) => new Set(groups.map(g => g.key)).size === groups.length,
{ message: 'fieldGroups[].key must be unique within an object' },
).optional().describe('Ordered list of field groups (array order = display order). See ObjectFieldGroupSchema.'),
/**
* Advanced Data Management
*/
// Multi-tenancy configuration
tenancy: TenancyConfigSchema.optional().describe('Multi-tenancy configuration for SaaS applications'),
// Soft delete configuration
softDelete: SoftDeleteConfigSchema.optional().describe('Soft delete (trash/recycle bin) configuration'),
// Versioning configuration
versioning: VersioningConfigSchema.optional().describe('Record versioning and history tracking configuration'),
// Partitioning strategy
partitioning: PartitioningConfigSchema.optional().describe('Table partitioning configuration for performance'),
// Change Data Capture
cdc: CDCConfigSchema.optional().describe('Change Data Capture (CDC) configuration for real-time data streaming'),
/**
* Logic & Validation (Co-located)
* Best Practice: Define rules close to data.
*/
validations: z.array(ValidationRuleSchema).optional().describe('Object-level validation rules'),
/**
* State Machine(s)
* Named record of state machines, where each key is a unique machine identifier.
* Multiple machines allow parallel lifecycles (e.g., status + payment_status + approval_status).
*
* @example stateMachines: { lifecycle: {...}, payment: {...}, approval: {...} }
*/
stateMachines: z.record(z.string(), StateMachineSchema).optional().describe('Named state machines for parallel lifecycles (e.g., status, payment, approval)'),
/**
* Display & UI Hints (Data-Layer)
*/
displayNameField: z.string().optional().describe('Field to use as the record display name (e.g., "name", "title"). Defaults to "name" if present.'),
recordName: z.object({
type: z.enum(['text', 'autonumber']).describe('Record name type: text (user-entered) or autonumber (system-generated)'),
displayFormat: z.string().optional().describe('Auto-number format pattern (e.g., "CASE-{0000}", "INV-{YYYY}-{0000}")'),
startNumber: z.number().int().min(0).optional().describe('Starting number for autonumber (default: 1)'),
}).optional().describe('Record name generation configuration (Salesforce pattern)'),
titleFormat: TemplateExpressionInputSchema.optional().describe('Title template — supports {{record.field}} interpolation. Overrides displayNameField.'),
compactLayout: z.array(z.string()).optional().describe('Primary fields for hover/cards/lookups'),
/**
* Built-in List Views
*
* Curated, platform-shipped list views (grid / kanban / calendar / …)
* keyed by view name. Rendered as segmented tabs in the console list page
* **before** any user-saved `sys_view` rows. Use this for system objects
* (audit, runtime, config) where the default "All records" grid lacks
* business context — e.g. an approval-request list should ship with
* "My pending", "I submitted", "Completed" tabs out of the box.
*
* Each value is a `ListViewSchema` (see `@objectstack/spec/ui`) so authors
* get the full tab/filter/sort/grouping vocabulary.
*
* @example
* ```ts
* listViews: {
* my_pending: {
* type: 'grid',
* label: 'My Pending',
* filter: [{ field: 'pending_approvers', operator: 'contains', value: '{current_user_id}' }],
* sort: [{ field: 'updated_at', order: 'desc' }],
* },
* }
* ```
*/
listViews: z.record(z.string(), ListViewSchema).optional().describe('Built-in named list views (segmented tabs) shipped with the object schema'),
/**
* Search Engine Config
*/
search: SearchConfigSchema.optional().describe('Search engine configuration'),
/**
* System Capabilities
*/
enable: ObjectCapabilities.optional().describe('Enabled system features modules'),
/** Record Types */
recordTypes: z.array(z.string()).optional().describe('Record type names for this object'),
/** Sharing Model */
sharingModel: z.enum(['private', 'read', 'read_write', 'full']).optional().describe('Default sharing model'),
/** Key Prefix */
keyPrefix: z.string().max(5).optional().describe('Short prefix for record IDs (e.g., "001" for Account)'),
/**
* Object Actions
*
* Actions associated with this object. Populated automatically by `defineStack()`
* when top-level actions specify `objectName` matching this object.
* Can also be defined directly on the object.
*
* Aligns with Salesforce/ServiceNow patterns where actions are part of the
* object schema, so API responses (e.g., `/api/v1/meta/objects/:name`)
* include the action list without requiring downstream merge.
*/
actions: z.array(ActionSchema).optional().describe('Actions associated with this object (auto-populated from top-level actions via objectName)'),
});
/**
* Converts a snake_case name to a human-readable Title Case label.
* @example snakeCaseToLabel('project_task') → 'Project Task'
*/
function snakeCaseToLabel(name: string): string {
return name
.split('_')
.map(word => word.charAt(0).toUpperCase() + word.slice(1))
.join(' ');
}
/**
* Enhanced ObjectSchema with Factory
*/
export const ObjectSchema = lazySchema(() => Object.assign(ObjectSchemaBase, {
/**
* Type-safe factory for creating business object definitions.
*
* Enhancements over raw schema:
* - **Auto-label**: Generates `label` from `name` if not provided (snake_case → Title Case).
* - **Validation**: Runs Zod `.parse()` to validate the config at creation time.
*
* @example
* ```ts
* const Task = ObjectSchema.create({
* name: 'project_task',
* // label auto-generated as 'Project Task'
* fields: {
* subject: { type: 'text', label: 'Subject', required: true },
* },
* });
* ```
*/
create: <const T extends z.input<typeof ObjectSchemaBase>>(config: T): Omit<ServiceObject, 'fields'> & Pick<T, 'fields'> => {
const withDefaults = {
...config,
label: config.label ?? snakeCaseToLabel(config.name),
};
return ObjectSchemaBase.parse(withDefaults) as Omit<ServiceObject, 'fields'> & Pick<T, 'fields'>;
},
}));
export type ServiceObject = z.infer<typeof ObjectSchemaBase>;
export type ServiceObjectInput = z.input<typeof ObjectSchemaBase>;
export type ObjectCapabilities = z.infer<typeof ObjectCapabilities>;
export type ObjectIndex = z.infer<typeof IndexSchema>;
export type TenancyConfig = z.infer<typeof TenancyConfigSchema>;
export type SoftDeleteConfig = z.infer<typeof SoftDeleteConfigSchema>;
export type VersioningConfig = z.infer<typeof VersioningConfigSchema>;
export type PartitioningConfig = z.infer<typeof PartitioningConfigSchema>;
export type CDCConfig = z.infer<typeof CDCConfigSchema>;
/**
* Resolved CRUD affordance matrix for an object — what generic
* lifecycle actions UI clients should expose in their toolbars.
*
* Use {@link resolveCrudAffordances} to compute this from a schema; the
* `managedBy` flag drives the defaults, and the optional `userActions`
* block per-flag-overrides them. UI clients (`ObjectView`,
* `RecordDetailView`, `RecordFormPage`, …) gate their buttons on this
* matrix in combination with the user's permissions.
*
* The presence of an affordance here means "the *object* permits this
* action conceptually"; the user still needs the matching permission
* grant to execute it.
*/
export interface CrudAffordances {
/** Generic "New" button (single record creation form). */
create: boolean;
/** CSV bulk-import wizard. Disabled for config / system / append-only / better-auth by default. */
import: boolean;
/** Inline + form editing of existing rows. */
edit: boolean;
/** Row-level + bulk delete. */
delete: boolean;
/** CSV / clipboard export. Allowed even on append-only audit tables by default. */
exportCsv: boolean;
}
/**
* Default affordance matrix per {@link ObjectSchemaBase.managedBy} bucket.
* Mirrors how Salesforce / ServiceNow / Workday / Notion expose CRUD on
* different categories of system tables.
*
* platform — full CRUD (user-owned business data)
* config — admin authored: New/Edit/Delete OK, no CSV import
* (definitions have nested envelopes; admins should use
* a purpose-built "Import definition" action instead)
* system — engine-managed runtime rows: no generic CRUD; users
* interact via domain actions on the source record
* append-only — audit log: View + Export only
* better-auth — identity tables owned by better-auth driver; CRUD
* routed through purpose-built actions (Invite, Reset
* PW, Revoke, …)
*/
const CRUD_AFFORDANCE_DEFAULTS: Record<NonNullable<ServiceObject['managedBy']> | 'platform', CrudAffordances> = {
platform: { create: true, import: true, edit: true, delete: true, exportCsv: true },
config: { create: true, import: false, edit: true, delete: true, exportCsv: true },
system: { create: false, import: false, edit: false, delete: false, exportCsv: true },
'append-only': { create: false, import: false, edit: false, delete: false, exportCsv: true },
'better-auth': { create: false, import: false, edit: false, delete: false, exportCsv: true },
};
/**
* Resolve the effective CRUD affordance matrix for an object schema.
*
* Starts from the bucket default keyed off `managedBy` (defaulting to
* `'platform'` if unset) and applies the per-flag overrides in
* `userActions`. Returns a fresh object so callers can mutate safely.
*
* @example
* ```ts
* const aff = resolveCrudAffordances(sysApprovalRequestSchema);
* // → { create:false, import:false, edit:false, delete:false, exportCsv:true }
* ```
*/
export function resolveCrudAffordances(
obj: Pick<ServiceObject, 'managedBy' | 'userActions'> | { managedBy?: string; userActions?: ServiceObject['userActions'] },
): CrudAffordances {
const bucket = (obj?.managedBy ?? 'platform') as keyof typeof CRUD_AFFORDANCE_DEFAULTS;
const base = CRUD_AFFORDANCE_DEFAULTS[bucket] ?? CRUD_AFFORDANCE_DEFAULTS.platform;
const overrides = obj?.userActions ?? {};
return {
create: overrides.create ?? base.create,
import: overrides.import ?? base.import,
edit: overrides.edit ?? base.edit,
delete: overrides.delete ?? base.delete,
exportCsv: overrides.exportCsv ?? base.exportCsv,
};
}
// =================================================================
// Object Ownership Model
// =================================================================
/**
* How a package relates to an object it references.
*
* - `own`: This package is the original author/owner of the object.
* Only one package may own a given object name. The owner defines
* the base schema (table name, primary key, core fields).
*
* - `extend`: This package adds fields, views, or actions to an
* existing object owned by another package. Multiple packages
* may extend the same object. Extensions are merged at boot time.
*
* Follows Salesforce/ServiceNow patterns:
* object name = database table name, globally unique, no namespace prefix.
*/
export const ObjectOwnershipEnum = z.enum(['own', 'extend']);
export type ObjectOwnership = z.infer<typeof ObjectOwnershipEnum>;
/**
* Object Extension Entry — used in `objectExtensions` array.
* Declares fields/config to merge into an existing object owned by another package.
*
* @example
* ```ts
* objectExtensions: [{
* extend: 'contact', // target object FQN
* fields: { sales_stage: Field.select([...]) },
* }]
* ```
*/
export const ObjectExtensionSchema = lazySchema(() => z.object({
/** The target object name (FQN) to extend */
extend: z.string().describe('Target object name (FQN) to extend'),
/** Fields to merge into the target object (additive) */
fields: z.record(z.string(), FieldSchema).optional().describe('Fields to add/override'),
/** Override label */
label: z.string().optional().describe('Override label for the extended object'),
/** Override plural label */
pluralLabel: z.string().optional().describe('Override plural label for the extended object'),
/** Override description */
description: z.string().optional().describe('Override description for the extended object'),
/** Additional validation rules to add */
validations: z.array(ValidationRuleSchema).optional().describe('Additional validation rules to merge into the target object'),
/** Additional indexes to add */
indexes: z.array(IndexSchema).optional().describe('Additional indexes to merge into the target object'),
/** Merge priority. Higher number applied later (wins on conflict). Default: 200 */
priority: z.number().int().min(0).max(999).default(200).describe('Merge priority (higher = applied later)'),
}));
export type ObjectExtension = z.infer<typeof ObjectExtensionSchema>;