@stndrds/schema 0.1.0-alpha.14

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 (128) hide show
  1. package/dist/chunk-3ABIOLKO.mjs +4624 -0
  2. package/dist/chunk-3IRX2BDY.mjs +3970 -0
  3. package/dist/chunk-4OTLPWSP.mjs +4448 -0
  4. package/dist/chunk-54ODQBUN.mjs +3867 -0
  5. package/dist/chunk-6HIA3FR2.mjs +4230 -0
  6. package/dist/chunk-6P3XHNLD.mjs +4171 -0
  7. package/dist/chunk-7LJECNAS.mjs +4167 -0
  8. package/dist/chunk-A2WNLUKV.mjs +4475 -0
  9. package/dist/chunk-AA3234RM.mjs +4475 -0
  10. package/dist/chunk-ADNXDLLD.mjs +3136 -0
  11. package/dist/chunk-B4DCDQUI.mjs +4695 -0
  12. package/dist/chunk-B4PSXY6I.mjs +4527 -0
  13. package/dist/chunk-BJHJBZCM.mjs +4228 -0
  14. package/dist/chunk-C3ZWTO6G.mjs +4474 -0
  15. package/dist/chunk-CLOGNKDD.mjs +4040 -0
  16. package/dist/chunk-EW4V63PA.mjs +3053 -0
  17. package/dist/chunk-FR2LCO6R.mjs +2485 -0
  18. package/dist/chunk-GJSF2RKL.mjs +2786 -0
  19. package/dist/chunk-GO5NPP2X.mjs +4726 -0
  20. package/dist/chunk-H3ZYJUDS.mjs +3050 -0
  21. package/dist/chunk-IDDLSFSK.mjs +4230 -0
  22. package/dist/chunk-JRADUJQ7.mjs +4726 -0
  23. package/dist/chunk-NEDR6N7R.mjs +3118 -0
  24. package/dist/chunk-NESPRMDF.mjs +2482 -0
  25. package/dist/chunk-NWFGRJBW.mjs +4612 -0
  26. package/dist/chunk-NXJ57GSN.mjs +2918 -0
  27. package/dist/chunk-O4C5FCTS.mjs +3961 -0
  28. package/dist/chunk-O4PRB27Q.mjs +2513 -0
  29. package/dist/chunk-OJDFNUCR.mjs +4463 -0
  30. package/dist/chunk-OSEKVBHC.mjs +4627 -0
  31. package/dist/chunk-QX4U6U6K.mjs +2484 -0
  32. package/dist/chunk-RMDQ6LKV.mjs +3046 -0
  33. package/dist/chunk-SBXKDATH.mjs +2673 -0
  34. package/dist/chunk-SKMP3AP3.mjs +2918 -0
  35. package/dist/chunk-STMS7WZD.mjs +2623 -0
  36. package/dist/chunk-T3T6PTFG.mjs +3057 -0
  37. package/dist/chunk-TPW72RAH.mjs +4624 -0
  38. package/dist/chunk-TUQEGNGV.mjs +2534 -0
  39. package/dist/chunk-TVKFS3YN.mjs +2449 -0
  40. package/dist/chunk-TZTH3BHG.mjs +3110 -0
  41. package/dist/chunk-W6MU3XPG.mjs +4612 -0
  42. package/dist/chunk-WL7Z3YFR.mjs +4603 -0
  43. package/dist/chunk-XNVVYHH3.mjs +4602 -0
  44. package/dist/chunk-XTA3WY64.mjs +2918 -0
  45. package/dist/chunk-YV7DEZFZ.mjs +2528 -0
  46. package/dist/chunk-ZLJPJND6.mjs +4474 -0
  47. package/dist/chunk-ZNZXTCEX.mjs +4234 -0
  48. package/dist/index.d.mts +1222 -0
  49. package/dist/index.d.ts +1222 -0
  50. package/dist/index.js +5320 -0
  51. package/dist/index.mjs +635 -0
  52. package/dist/runtime-2iKarXtl.d.mts +1924 -0
  53. package/dist/runtime-2iKarXtl.d.ts +1924 -0
  54. package/dist/runtime-4l2ddHZ7.d.mts +2242 -0
  55. package/dist/runtime-4l2ddHZ7.d.ts +2243 -0
  56. package/dist/runtime-8hKS6zAv.d.mts +2226 -0
  57. package/dist/runtime-8hKS6zAv.d.ts +2226 -0
  58. package/dist/runtime-B6yjtoR3.d.mts +4142 -0
  59. package/dist/runtime-B6yjtoR3.d.ts +4142 -0
  60. package/dist/runtime-BGCShrZB.d.mts +2001 -0
  61. package/dist/runtime-BGCShrZB.d.ts +2001 -0
  62. package/dist/runtime-BRW4NGAk.d.mts +1668 -0
  63. package/dist/runtime-BRW4NGAk.d.ts +1668 -0
  64. package/dist/runtime-BnfBr314.d.mts +1683 -0
  65. package/dist/runtime-BnfBr314.d.ts +1683 -0
  66. package/dist/runtime-BrqhiJUF.d.mts +4151 -0
  67. package/dist/runtime-BrqhiJUF.d.ts +4151 -0
  68. package/dist/runtime-Bvj8c-BE.d.mts +4277 -0
  69. package/dist/runtime-Bvj8c-BE.d.ts +4277 -0
  70. package/dist/runtime-C03qT4qU.d.mts +4267 -0
  71. package/dist/runtime-C03qT4qU.d.ts +4267 -0
  72. package/dist/runtime-CaCZ7mSf.d.mts +2974 -0
  73. package/dist/runtime-CaCZ7mSf.d.ts +2974 -0
  74. package/dist/runtime-CaIzNX0Z.d.mts +4091 -0
  75. package/dist/runtime-CaIzNX0Z.d.ts +4091 -0
  76. package/dist/runtime-ChPTgmLP.d.mts +4320 -0
  77. package/dist/runtime-ChPTgmLP.d.ts +4320 -0
  78. package/dist/runtime-CnImZ1Vv.d.mts +4267 -0
  79. package/dist/runtime-CnImZ1Vv.d.ts +4267 -0
  80. package/dist/runtime-Cp-B26Nj.d.mts +2890 -0
  81. package/dist/runtime-Cp-B26Nj.d.ts +2890 -0
  82. package/dist/runtime-Cq8jfk3c.d.mts +4277 -0
  83. package/dist/runtime-Cq8jfk3c.d.ts +4277 -0
  84. package/dist/runtime-CqDFXhhP.d.mts +1685 -0
  85. package/dist/runtime-CqDFXhhP.d.ts +1685 -0
  86. package/dist/runtime-CqtpZLdL.d.mts +4280 -0
  87. package/dist/runtime-CqtpZLdL.d.ts +4280 -0
  88. package/dist/runtime-D-4DblaZ.d.mts +4147 -0
  89. package/dist/runtime-D-4DblaZ.d.ts +4147 -0
  90. package/dist/runtime-D59sSqNl.d.mts +4146 -0
  91. package/dist/runtime-D59sSqNl.d.ts +4146 -0
  92. package/dist/runtime-DEfPk3wT.d.mts +1840 -0
  93. package/dist/runtime-DEfPk3wT.d.ts +1840 -0
  94. package/dist/runtime-DGV-7vES.d.mts +1685 -0
  95. package/dist/runtime-DGV-7vES.d.ts +1685 -0
  96. package/dist/runtime-DNacghqc.d.mts +3971 -0
  97. package/dist/runtime-DNacghqc.d.ts +3971 -0
  98. package/dist/runtime-DPLsUHYK.d.mts +3977 -0
  99. package/dist/runtime-DPLsUHYK.d.ts +3977 -0
  100. package/dist/runtime-DTxCw60F.d.mts +2973 -0
  101. package/dist/runtime-DTxCw60F.d.ts +2973 -0
  102. package/dist/runtime-DUXJ-zNS.d.mts +2788 -0
  103. package/dist/runtime-DUXJ-zNS.d.ts +2788 -0
  104. package/dist/runtime-DbljInhV.d.mts +2237 -0
  105. package/dist/runtime-DbljInhV.d.ts +2237 -0
  106. package/dist/runtime-DcH3y6Yu.d.mts +4272 -0
  107. package/dist/runtime-DcH3y6Yu.d.ts +4272 -0
  108. package/dist/runtime-DdBFz85g.d.mts +4229 -0
  109. package/dist/runtime-DdBFz85g.d.ts +4229 -0
  110. package/dist/runtime-DjMWhjkm.d.mts +4321 -0
  111. package/dist/runtime-DjMWhjkm.d.ts +4321 -0
  112. package/dist/runtime-Djz3fOBE.d.mts +2078 -0
  113. package/dist/runtime-Djz3fOBE.d.ts +2078 -0
  114. package/dist/runtime-Dli8g3Aq.d.mts +2082 -0
  115. package/dist/runtime-Dli8g3Aq.d.ts +2082 -0
  116. package/dist/runtime-a8J378im.d.mts +4123 -0
  117. package/dist/runtime-a8J378im.d.ts +4123 -0
  118. package/dist/runtime-dp3rb3Lf.d.mts +2968 -0
  119. package/dist/runtime-dp3rb3Lf.d.ts +2968 -0
  120. package/dist/runtime-iWXlSN_H.d.mts +1683 -0
  121. package/dist/runtime-iWXlSN_H.d.ts +1683 -0
  122. package/dist/runtime-yMql0npY.d.mts +4321 -0
  123. package/dist/runtime-yMql0npY.d.ts +4321 -0
  124. package/dist/runtime.d.mts +3 -0
  125. package/dist/runtime.d.ts +3 -0
  126. package/dist/runtime.js +3626 -0
  127. package/dist/runtime.mjs +48 -0
  128. package/package.json +58 -0
@@ -0,0 +1,2973 @@
1
+ import { ColorId, IconName, CountryIso3, CurrencyCode, MimeType } from '@stndrds/constants';
2
+ import { z } from 'zod';
3
+
4
+ /**
5
+ * UUID string type for all identifiers
6
+ */
7
+ type Uuid = string;
8
+ /**
9
+ * Tenant identifier for multi-tenant isolation
10
+ * Phase 1: Type defined but not yet used in interfaces
11
+ * Phase 2+: Will be added to ObjectRecord and services for SaaS mode
12
+ */
13
+ type TenantId = string;
14
+ /**
15
+ * Generate a unique UUID v4
16
+ * Uses crypto.randomUUID() when available (Node.js 19+, modern browsers)
17
+ * Falls back to a manual implementation for older environments
18
+ *
19
+ * @returns A UUID v4 string
20
+ *
21
+ * @example
22
+ * ```typescript
23
+ * const id = generateId();
24
+ * // "a1b2c3d4-e5f6-4a7b-8c9d-0e1f2a3b4c5d"
25
+ * ```
26
+ */
27
+ declare function generateId(): Uuid;
28
+ /**
29
+ * Generate a prefixed ID for better debugging and readability
30
+ *
31
+ * @param prefix - Prefix for the ID (e.g., "obj", "attr", "rec")
32
+ * @returns A prefixed UUID string
33
+ *
34
+ * @example
35
+ * ```typescript
36
+ * const objectId = generatePrefixedId("obj");
37
+ * // "obj_a1b2c3d4-e5f6-4a7b-8c9d-0e1f2a3b4c5d"
38
+ *
39
+ * const attrId = generatePrefixedId("attr");
40
+ * // "attr_a1b2c3d4-e5f6-4a7b-8c9d-0e1f2a3b4c5d"
41
+ * ```
42
+ */
43
+ declare function generatePrefixedId(prefix: string): Uuid;
44
+
45
+ type AttributeType = "text" | "textarea" | "number" | "checkbox" | "date" | "phone" | "currency" | "status" | "location" | "timestamp" | "select" | "multiselect" | "file" | "user" | "relation" | "rating";
46
+ /**
47
+ * Status group categorization
48
+ */
49
+ type StatusGroup = "idle" | "in_progress" | "finished";
50
+ /**
51
+ * Unified option type for select-like fields
52
+ */
53
+ interface Option {
54
+ id: string;
55
+ label: string;
56
+ value: string;
57
+ color?: ColorId;
58
+ icon?: IconName;
59
+ description?: string;
60
+ group?: StatusGroup;
61
+ }
62
+ /**
63
+ * Attribute grouping for UI organization
64
+ */
65
+ interface AttributeGroup {
66
+ id: string;
67
+ label: string;
68
+ description?: string;
69
+ attributeIds: string[];
70
+ collapsible?: boolean;
71
+ collapsed?: boolean;
72
+ order?: number;
73
+ }
74
+ interface BaseAttribute<DefaultValueType = unknown> {
75
+ id: Uuid;
76
+ name: string;
77
+ label: string;
78
+ type: AttributeType;
79
+ required: boolean;
80
+ disabled?: boolean;
81
+ placeholder?: string;
82
+ description?: string;
83
+ defaultValue?: DefaultValueType;
84
+ icon?: IconName;
85
+ order?: number;
86
+ hidden?: boolean;
87
+ archived?: boolean;
88
+ deprecated?: boolean;
89
+ system?: boolean;
90
+ metadata?: Record<string, unknown>;
91
+ }
92
+ interface TextAttribute extends BaseAttribute<string> {
93
+ type: "text";
94
+ minLength?: number;
95
+ maxLength?: number;
96
+ pattern?: string;
97
+ }
98
+ type NumberUnit = "integer" | "decimal" | "percentage";
99
+ interface NumberAttribute extends BaseAttribute<number> {
100
+ type: "number";
101
+ min?: number;
102
+ max?: number;
103
+ unit?: NumberUnit;
104
+ decimals?: number;
105
+ }
106
+ interface CheckboxAttribute extends BaseAttribute<boolean> {
107
+ type: "checkbox";
108
+ }
109
+ type DateFormat = "short" | "long" | "full" | "relative";
110
+ type DateValue = string | "today";
111
+ interface DateAttribute extends BaseAttribute<string> {
112
+ type: "date";
113
+ dateFormat?: DateFormat;
114
+ minDate?: DateValue;
115
+ maxDate?: DateValue;
116
+ }
117
+ interface Phone {
118
+ countryCode: CountryIso3;
119
+ phoneNumber: string;
120
+ }
121
+ interface PhoneAttribute extends BaseAttribute<Phone> {
122
+ type: "phone";
123
+ defaultCountryCode?: CountryIso3;
124
+ }
125
+ interface Currency {
126
+ code: CurrencyCode;
127
+ value: number;
128
+ }
129
+ interface CurrencyAttribute extends BaseAttribute<Currency> {
130
+ type: "currency";
131
+ defaultCurrency?: CurrencyCode;
132
+ allowedCurrencies?: CurrencyCode[];
133
+ }
134
+ /**
135
+ * StatusAttribute - For workflow states with semantic grouping (idle/in_progress/finished)
136
+ * Use this for: Task status, Order status, Project phases, Process states
137
+ * Use SelectAttribute for: Categories, Types, simple choices without workflow
138
+ */
139
+ interface StatusAttribute extends BaseAttribute<string> {
140
+ type: "status";
141
+ options: Option[];
142
+ }
143
+ interface Location {
144
+ address?: string;
145
+ address2?: string;
146
+ city?: string;
147
+ state?: string;
148
+ postalCode?: string;
149
+ country?: CountryIso3;
150
+ latitude?: number;
151
+ longitude?: number;
152
+ }
153
+ type LocationGranularity = "full" | "address" | "city" | "state" | "country" | "coordinates";
154
+ interface LocationAttribute extends BaseAttribute<Location> {
155
+ type: "location";
156
+ granularity: LocationGranularity;
157
+ enableAutocomplete?: boolean;
158
+ enableMap?: boolean;
159
+ defaultCountry?: CountryIso3;
160
+ allowedCountries?: CountryIso3[];
161
+ displayFormat?: "single_line" | "multi_line" | "compact";
162
+ }
163
+ interface TimestampAttribute extends BaseAttribute<number> {
164
+ type: "timestamp";
165
+ autoUpdate?: boolean;
166
+ }
167
+ /**
168
+ * SelectAttribute - For simple single-choice selection
169
+ * Use this for: Categories, Document types, Departments, Priorities
170
+ * Options can be grouped (e.g., countries by continent) but no workflow logic
171
+ */
172
+ interface SelectAttribute extends BaseAttribute<string> {
173
+ type: "select";
174
+ options: Option[];
175
+ }
176
+ interface MultiselectAttribute extends BaseAttribute<string[]> {
177
+ type: "multiselect";
178
+ options: Option[];
179
+ }
180
+ type DocumentType = "id_card" | "passport" | "incorporation_certificate" | "driver_license" | "birth_certificate" | "residence_permit" | "bank_statement" | "proof_of_address" | "custom";
181
+ type DocumentFace = "front" | "back" | "single";
182
+ interface DocumentTypeConfig {
183
+ type: DocumentType;
184
+ label: string;
185
+ faces: DocumentFace[];
186
+ attributeMapping?: {
187
+ attributeId: string;
188
+ extractedKey: string;
189
+ face?: DocumentFace;
190
+ required?: boolean;
191
+ }[];
192
+ }
193
+ interface FileVerificationConfig {
194
+ enabled: boolean;
195
+ documentTypes: DocumentTypeConfig[];
196
+ autoExtract?: boolean;
197
+ autoValidate?: boolean;
198
+ }
199
+ interface FileAttribute extends BaseAttribute<string> {
200
+ type: "file";
201
+ maxFiles?: number;
202
+ maxSize?: number;
203
+ allowedTypes?: MimeType[] | readonly MimeType[];
204
+ verification?: FileVerificationConfig;
205
+ }
206
+ interface UserAttribute extends BaseAttribute<string> {
207
+ type: "user";
208
+ allowedRoles?: string[];
209
+ }
210
+ /**
211
+ * Target object for a relation - defines which objects can be linked
212
+ */
213
+ interface RelationTarget {
214
+ /** Object name (e.g., "companies", "contacts") */
215
+ object: string;
216
+ /**
217
+ * Display template for the label using mustache-like syntax
218
+ * @example "{name}" or "{firstName} {lastName} — {email}"
219
+ */
220
+ displayTemplate?: string;
221
+ /**
222
+ * Optional filter to restrict available records
223
+ * @example { status: "active" }
224
+ */
225
+ filter?: Record<string, unknown>;
226
+ }
227
+ /**
228
+ * Strategy when a target record is deleted
229
+ * - "restrict": Prevent deletion if relations exist (default)
230
+ * - "cascade": Delete this record too
231
+ * - "set_null": Set the relation value to null
232
+ */
233
+ type RelationOnDelete = "restrict" | "cascade" | "set_null";
234
+ /**
235
+ * Base properties shared by both single and multi relation attributes
236
+ */
237
+ interface RelationAttributeBase extends Omit<BaseAttribute<unknown>, "defaultValue"> {
238
+ type: "relation";
239
+ /** Target objects that can be linked */
240
+ targets: RelationTarget[];
241
+ /** Deletion strategy when target record is deleted */
242
+ onDelete?: RelationOnDelete;
243
+ }
244
+ /**
245
+ * Single relation attribute (one-to-one or many-to-one)
246
+ * Stores a single record ID or null
247
+ */
248
+ interface SingleRelationAttribute extends RelationAttributeBase {
249
+ cardinality: "one";
250
+ defaultValue?: string | null;
251
+ }
252
+ /**
253
+ * Multi relation attribute (one-to-many or many-to-many)
254
+ * Stores an array of record IDs
255
+ */
256
+ interface MultiRelationAttribute extends RelationAttributeBase {
257
+ cardinality: "many";
258
+ defaultValue?: string[];
259
+ /** Minimum number of relations required */
260
+ minItems?: number;
261
+ /** Maximum number of relations allowed */
262
+ maxItems?: number;
263
+ }
264
+ /**
265
+ * RelationAttribute links to other objects/records
266
+ * Discriminated union by cardinality for type-safe value handling
267
+ *
268
+ * @example Single relation (many-to-one)
269
+ * ```typescript
270
+ * relation({ name: "company", label: "Company" })
271
+ * .to("companies")
272
+ * .required()
273
+ * // → Value: "rec-uuid-123" | null
274
+ * ```
275
+ *
276
+ * @example Multi relation (many-to-many)
277
+ * ```typescript
278
+ * relation({ name: "contacts", label: "Contacts" })
279
+ * .to("contacts", { displayTemplate: "{firstName} {lastName}" })
280
+ * .many()
281
+ * .maxItems(5)
282
+ * // → Value: ["rec-1", "rec-2", ...]
283
+ * ```
284
+ *
285
+ * @example Polymorphic relation (multiple target objects)
286
+ * ```typescript
287
+ * relation({ name: "linked", label: "Linked Items" })
288
+ * .to("companies")
289
+ * .to("contacts")
290
+ * .to("deals")
291
+ * .many()
292
+ * // → Can link to records from any of these objects
293
+ * ```
294
+ */
295
+ type RelationAttribute = SingleRelationAttribute | MultiRelationAttribute;
296
+ interface TextAreaAttribute extends BaseAttribute<string> {
297
+ type: "textarea";
298
+ }
299
+ interface RatingAttribute extends BaseAttribute<number> {
300
+ type: "rating";
301
+ max?: number;
302
+ iconType?: "star" | "heart" | "thumbs" | "number";
303
+ }
304
+ type Attribute = TextAttribute | TextAreaAttribute | NumberAttribute | CheckboxAttribute | DateAttribute | PhoneAttribute | CurrencyAttribute | StatusAttribute | LocationAttribute | TimestampAttribute | SelectAttribute | MultiselectAttribute | FileAttribute | UserAttribute | RelationAttribute | RatingAttribute;
305
+
306
+ /**
307
+ * Timestamps for tracking creation and updates
308
+ */
309
+ interface Timestamps {
310
+ createdAt: Date;
311
+ updatedAt: Date;
312
+ }
313
+ /**
314
+ * Object definition - Represents a database table/entity
315
+ */
316
+ interface ObjectDefinition {
317
+ id?: Uuid;
318
+ name: string;
319
+ label: string;
320
+ description?: string;
321
+ icon?: IconName;
322
+ /**
323
+ * Template expression used to compute the object's display label.
324
+ * Supports variable interpolation and pipes for formatting.
325
+ *
326
+ * @example
327
+ * ```typescript
328
+ * // Simple attribute reference
329
+ * labelExpression: "{{ name }}"
330
+ *
331
+ * // Multiple attributes
332
+ * labelExpression: "{{ firstName }} {{ lastName }}"
333
+ *
334
+ * // With pipes for formatting
335
+ * labelExpression: "{{ code | UPPER }} - {{ name | capitalize }}"
336
+ * ```
337
+ *
338
+ * Available pipes: UPPER, LOWER, capitalize, trim
339
+ */
340
+ labelExpression: string;
341
+ attributes: Attribute[];
342
+ system?: boolean;
343
+ metadata?: Record<string, unknown>;
344
+ }
345
+ /**
346
+ * Links an attribute to an object
347
+ */
348
+ interface ObjectAttribute {
349
+ objectId: Uuid;
350
+ attributeId: Uuid;
351
+ order?: number;
352
+ required?: boolean;
353
+ }
354
+ /**
355
+ * Completion status of a record based on data completeness.
356
+ *
357
+ * - `draft`: Record is missing one or more required attribute values.
358
+ * Can be saved but is considered incomplete.
359
+ * - `complete`: All required attribute values are present and valid.
360
+ * Record is ready for use.
361
+ *
362
+ * This is different from workflow status (e.g., "pending", "approved").
363
+ * Completion status is computed dynamically based on the object schema.
364
+ */
365
+ type CompletionStatus = "draft" | "complete";
366
+ /**
367
+ * Record - Instance of an Object (a row in the database)
368
+ */
369
+ interface ObjectRecord extends Timestamps {
370
+ id: Uuid;
371
+ objectId: Uuid;
372
+ /**
373
+ * Display label computed from the object's labelExpression.
374
+ * Computed dynamically based on record values.
375
+ *
376
+ * @example "John Doe" (from "{{ firstName }} {{ lastName }}")
377
+ */
378
+ label: string;
379
+ /**
380
+ * Completion status of the record.
381
+ * - `draft`: Missing required values, record is incomplete
382
+ * - `complete`: All required values present and valid
383
+ *
384
+ * Computed dynamically based on the object's schema.
385
+ */
386
+ completionStatus: CompletionStatus;
387
+ values: Record<string, unknown>;
388
+ }
389
+
390
+ /**
391
+ * Storage provider type
392
+ */
393
+ type StorageProvider = "s3" | "gcs" | "azure" | "local" | "cloudflare-r2" | string;
394
+ /**
395
+ * File visibility level
396
+ */
397
+ type FileVisibility = "public" | "private" | "restricted";
398
+ /**
399
+ * File - Represents uploaded file metadata and storage info
400
+ *
401
+ * ARCHITECTURE:
402
+ * - Fixed table (no custom attributes)
403
+ * - Manages file storage, permissions, and metadata
404
+ * - uploadedBy links to user_profiles table
405
+ * - Supports soft delete via deletedAt
406
+ *
407
+ * @example
408
+ * ```typescript
409
+ * const file: File = {
410
+ * id: "file-123",
411
+ * tenantId: "tenant-456",
412
+ * name: "contract-2025.pdf",
413
+ * originalName: "Contract Acme Corp 2025.pdf",
414
+ * mimeType: "application/pdf",
415
+ * size: 2458624,
416
+ * storageProvider: "s3",
417
+ * storagePath: "tenants/456/files/2025/11/contract-2025.pdf",
418
+ * storageBucket: "my-app-files",
419
+ * url: "https://cdn.example.com/files/file-123",
420
+ * uploadedBy: "profile-789",
421
+ * folderPath: "/contracts/2025",
422
+ * tags: ["contract", "legal"],
423
+ * visibility: "restricted",
424
+ * allowedUsers: ["profile-789", "profile-456"],
425
+ * createdAt: new Date(),
426
+ * updatedAt: new Date(),
427
+ * };
428
+ * ```
429
+ */
430
+ interface File extends Timestamps {
431
+ id: Uuid;
432
+ tenantId: Uuid;
433
+ /**
434
+ * File name (sanitized for storage)
435
+ */
436
+ name: string;
437
+ /**
438
+ * Original file name (as uploaded by user)
439
+ */
440
+ originalName: string;
441
+ /**
442
+ * MIME type (e.g., "application/pdf", "image/jpeg")
443
+ */
444
+ mimeType: MimeType | string;
445
+ /**
446
+ * File size in bytes
447
+ */
448
+ size: number;
449
+ /**
450
+ * Storage provider (s3, gcs, azure, local, etc.)
451
+ */
452
+ storageProvider: StorageProvider;
453
+ /**
454
+ * Path in the storage bucket
455
+ */
456
+ storagePath: string;
457
+ /**
458
+ * Storage bucket name (if applicable)
459
+ */
460
+ storageBucket?: string;
461
+ /**
462
+ * Public or signed URL to access the file
463
+ */
464
+ url: string;
465
+ /**
466
+ * User who uploaded the file (FK to user_profiles)
467
+ */
468
+ uploadedBy: Uuid;
469
+ /**
470
+ * Folder path for organization (e.g., "/contracts/2025")
471
+ */
472
+ folderPath?: string;
473
+ /**
474
+ * Tags for search and categorization
475
+ */
476
+ tags?: string[];
477
+ /**
478
+ * File visibility level
479
+ * - public: Anyone with the URL can access
480
+ * - private: Only uploadedBy can access
481
+ * - restricted: Only specific users (allowedUsers) can access
482
+ */
483
+ visibility: FileVisibility;
484
+ /**
485
+ * List of user IDs authorized to access this file (if visibility = "restricted")
486
+ */
487
+ allowedUsers?: Uuid[];
488
+ /**
489
+ * Soft delete timestamp (null = not deleted)
490
+ */
491
+ deletedAt?: Date;
492
+ }
493
+ /**
494
+ * Data required to create a new file record
495
+ */
496
+ interface CreateFile {
497
+ tenantId: Uuid;
498
+ name: string;
499
+ originalName: string;
500
+ mimeType: MimeType | string;
501
+ size: number;
502
+ storageProvider: StorageProvider;
503
+ storagePath: string;
504
+ storageBucket?: string;
505
+ url: string;
506
+ uploadedBy: Uuid;
507
+ folderPath?: string;
508
+ tags?: string[];
509
+ visibility?: FileVisibility;
510
+ allowedUsers?: Uuid[];
511
+ }
512
+ /**
513
+ * Data for updating an existing file record
514
+ */
515
+ interface UpdateFile {
516
+ name?: string;
517
+ folderPath?: string;
518
+ tags?: string[];
519
+ visibility?: FileVisibility;
520
+ allowedUsers?: Uuid[];
521
+ }
522
+
523
+ /**
524
+ * Autocomplete suggestion from geocoding service
525
+ */
526
+ interface GeocodingSuggestion {
527
+ /** Unique identifier from the provider */
528
+ id: string;
529
+ /** Human-readable label for display */
530
+ label: string;
531
+ /** Structured location data */
532
+ location: Location;
533
+ /** Optional match score/confidence (0-1) */
534
+ score?: number;
535
+ /** Optional additional metadata from the provider */
536
+ metadata?: Record<string, unknown>;
537
+ }
538
+ /**
539
+ * Parameters for autocomplete search
540
+ */
541
+ interface GeocodingAutocompleteParams {
542
+ /** Search query */
543
+ query: string;
544
+ /** Restrict results to specific countries */
545
+ countries?: CountryIso3[];
546
+ /** Preferred language for results (ISO 639-1) */
547
+ language?: string;
548
+ /** Maximum number of results */
549
+ limit?: number;
550
+ /** Bias results toward a specific location */
551
+ biasLocation?: {
552
+ latitude: number;
553
+ longitude: number;
554
+ };
555
+ /** Session token for billing optimization (some providers) */
556
+ sessionToken?: string;
557
+ /**
558
+ * Level of address detail expected
559
+ * Adapters can use this to filter/optimize results
560
+ * - "full": Full address with street, city, postal code, etc.
561
+ * - "address": Street address without postal code
562
+ * - "city": City level only
563
+ * - "state": State/region level only
564
+ * - "country": Country level only
565
+ * - "coordinates": Only coordinates (lat/lng)
566
+ */
567
+ granularity?: LocationGranularity;
568
+ }
569
+ /**
570
+ * Parameters for reverse geocoding
571
+ */
572
+ interface ReverseGeocodingParams {
573
+ /** Latitude */
574
+ latitude: number;
575
+ /** Longitude */
576
+ longitude: number;
577
+ /** Preferred language for results */
578
+ language?: string;
579
+ }
580
+ /**
581
+ * Parameters for geocoding a structured address
582
+ */
583
+ interface GeocodingParams {
584
+ /** Structured address components */
585
+ address: Partial<Location>;
586
+ /** Preferred language for results */
587
+ language?: string;
588
+ }
589
+ /**
590
+ * Abstract geocoding adapter interface
591
+ * Implement this interface for different geocoding providers
592
+ *
593
+ * @example Google Maps implementation
594
+ * ```typescript
595
+ * class GoogleMapsGeocodingAdapter implements GeocodingAdapter {
596
+ * async autocomplete(params) {
597
+ * const response = await fetch(
598
+ * `https://maps.googleapis.com/maps/api/place/autocomplete/json?input=${params.query}&key=${this.apiKey}`
599
+ * );
600
+ * // Transform response to GeocodingSuggestion[]
601
+ * }
602
+ * }
603
+ * ```
604
+ *
605
+ * @example Mapbox implementation
606
+ * ```typescript
607
+ * class MapboxGeocodingAdapter implements GeocodingAdapter {
608
+ * async autocomplete(params) {
609
+ * const response = await fetch(
610
+ * `https://api.mapbox.com/geocoding/v5/mapbox.places/${params.query}.json?access_token=${this.token}`
611
+ * );
612
+ * // Transform response to GeocodingSuggestion[]
613
+ * }
614
+ * }
615
+ * ```
616
+ */
617
+ interface GeocodingAdapter {
618
+ /**
619
+ * Autocomplete address search
620
+ * Returns suggestions as the user types
621
+ */
622
+ autocomplete(params: GeocodingAutocompleteParams): Promise<GeocodingSuggestion[]>;
623
+ /**
624
+ * Reverse geocode coordinates to an address
625
+ * Optional - some providers may not support this
626
+ */
627
+ reverse?(params: ReverseGeocodingParams): Promise<GeocodingSuggestion | null>;
628
+ /**
629
+ * Geocode a structured address to coordinates
630
+ * Optional - some providers may not support this
631
+ */
632
+ geocode?(params: GeocodingParams): Promise<GeocodingSuggestion | null>;
633
+ }
634
+ /**
635
+ * No-op geocoding adapter
636
+ * Returns empty results when no geocoding provider is configured
637
+ */
638
+ declare class NoopGeocodingAdapter implements GeocodingAdapter {
639
+ autocomplete(): Promise<GeocodingSuggestion[]>;
640
+ reverse(): Promise<null>;
641
+ geocode(): Promise<null>;
642
+ }
643
+
644
+ /**
645
+ * User role in the application
646
+ * Can be extended with custom roles as needed
647
+ */
648
+ type UserRole = "admin" | "member" | "guest" | string;
649
+ /**
650
+ * User status for account management
651
+ */
652
+ type UserStatus = "active" | "pending" | "inactive" | "suspended";
653
+ /**
654
+ * User Profile - Represents application user data (authorization)
655
+ *
656
+ * ARCHITECTURE:
657
+ * - authId links to external auth provider (Supabase, Clerk, Auth0, etc.)
658
+ * - email is denormalized from auth provider for performance
659
+ * - Auth provider handles authentication (passwords, sessions, OAuth)
660
+ * - This type handles authorization (roles, permissions, tenant membership)
661
+ *
662
+ * @example
663
+ * ```typescript
664
+ * const profile: UserProfile = {
665
+ * id: "profile-123",
666
+ * tenantId: "tenant-456",
667
+ * authId: "supabase-auth-uuid-789",
668
+ * email: "john@example.com",
669
+ * firstName: "John",
670
+ * lastName: "Doe",
671
+ * role: "admin",
672
+ * status: "active",
673
+ * createdAt: new Date(),
674
+ * updatedAt: new Date(),
675
+ * };
676
+ * ```
677
+ */
678
+ interface UserProfile extends Timestamps {
679
+ id: Uuid;
680
+ tenantId: Uuid;
681
+ /**
682
+ * Link to external auth provider (Supabase auth.users.id, Clerk user ID, etc.)
683
+ * This is the bridge between authentication (provider) and authorization (your app)
684
+ */
685
+ authId: string;
686
+ /**
687
+ * Email address (denormalized from auth provider)
688
+ * Allows efficient querying and filtering without hitting auth provider API
689
+ */
690
+ email: string;
691
+ /**
692
+ * User's first name
693
+ */
694
+ firstName?: string;
695
+ /**
696
+ * User's last name
697
+ */
698
+ lastName?: string;
699
+ /**
700
+ * Avatar/profile picture URL
701
+ */
702
+ avatarUrl?: string;
703
+ /**
704
+ * User role for authorization
705
+ * Common values: "admin", "member", "guest"
706
+ * Can be extended with custom roles
707
+ */
708
+ role: UserRole;
709
+ /**
710
+ * Account status
711
+ * - active: Normal user, full access
712
+ * - pending: Awaiting activation/approval
713
+ * - inactive: Deactivated account
714
+ * - suspended: Temporarily blocked
715
+ */
716
+ status: UserStatus;
717
+ /**
718
+ * Last login timestamp (updated on each successful auth)
719
+ */
720
+ lastLoginAt?: Date;
721
+ }
722
+ /**
723
+ * Data required to create a new user profile
724
+ */
725
+ interface CreateUserProfile {
726
+ tenantId: Uuid;
727
+ authId: string;
728
+ email: string;
729
+ firstName?: string;
730
+ lastName?: string;
731
+ avatarUrl?: string;
732
+ role?: UserRole;
733
+ status?: UserStatus;
734
+ }
735
+ /**
736
+ * Data for updating an existing user profile
737
+ */
738
+ interface UpdateUserProfile {
739
+ firstName?: string;
740
+ lastName?: string;
741
+ avatarUrl?: string;
742
+ role?: UserRole;
743
+ status?: UserStatus;
744
+ lastLoginAt?: Date;
745
+ }
746
+
747
+ /**
748
+ * Field definition within a form group
749
+ */
750
+ interface Field {
751
+ /** Attribute name to display */
752
+ attribute: string;
753
+ /** Grid span (1-12 columns) */
754
+ span?: 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12;
755
+ /** Override label for this view */
756
+ label?: string;
757
+ /** Force read-only display */
758
+ readOnly?: boolean;
759
+ }
760
+ /**
761
+ * Group of fields for organizing forms
762
+ */
763
+ interface Group {
764
+ id: string;
765
+ label: string;
766
+ description?: string;
767
+ fields: Field[];
768
+ collapsible?: boolean;
769
+ collapsed?: boolean;
770
+ order?: number;
771
+ }
772
+ type TabType = "form" | "table" | "custom";
773
+ /**
774
+ * Base properties shared by all tab types
775
+ */
776
+ interface BaseTab {
777
+ id: string;
778
+ name: string;
779
+ label: string;
780
+ icon?: IconName;
781
+ order?: number;
782
+ /** If true, tab is defined by developer (protected) */
783
+ system?: boolean;
784
+ }
785
+ /**
786
+ * Form tab - displays attributes organized in groups
787
+ */
788
+ interface FormTab extends BaseTab {
789
+ type: "form";
790
+ groups: Group[];
791
+ }
792
+ /**
793
+ * Table tab - displays records from a relation attribute
794
+ */
795
+ interface TableTab extends BaseTab {
796
+ type: "table";
797
+ /** Name of the relation attribute */
798
+ relation: string;
799
+ /** Columns to display (attribute names from target object) */
800
+ columns: string[];
801
+ /** Allow creating new records */
802
+ allowCreate?: boolean;
803
+ /** Allow inline editing */
804
+ allowEdit?: boolean;
805
+ /** Allow deleting records */
806
+ allowDelete?: boolean;
807
+ /** Default filters */
808
+ filters?: Record<string, unknown>;
809
+ /** Default sort */
810
+ sort?: {
811
+ field: string;
812
+ order: "asc" | "desc";
813
+ };
814
+ }
815
+ /**
816
+ * Custom tab - renders a developer-defined component
817
+ */
818
+ interface CustomTab extends BaseTab {
819
+ type: "custom";
820
+ /** Component identifier to render */
821
+ component: string;
822
+ /** Props to pass to the component */
823
+ props?: Record<string, unknown>;
824
+ }
825
+ /**
826
+ * Union of all tab types
827
+ */
828
+ type Tab = FormTab | TableTab | CustomTab;
829
+ /**
830
+ * View definition - organizes object attributes into tabs/pages
831
+ *
832
+ * @example
833
+ * ```typescript
834
+ * const companyView: ViewDefinition = {
835
+ * name: "detail",
836
+ * label: "Company Detail",
837
+ * object: "companies",
838
+ * tabs: [
839
+ * { type: "form", name: "general", label: "Info", groups: [...] },
840
+ * { type: "table", name: "contacts", label: "Contacts", relation: "contacts", columns: [...] }
841
+ * ],
842
+ * default: true,
843
+ * system: true
844
+ * };
845
+ * ```
846
+ */
847
+ interface ViewDefinition {
848
+ id?: Uuid;
849
+ /** Technical name (kebab-case) */
850
+ name: string;
851
+ /** Display label */
852
+ label: string;
853
+ /** Description */
854
+ description?: string;
855
+ /** Icon */
856
+ icon?: IconName;
857
+ /** Object this view belongs to (object name) */
858
+ object: string;
859
+ /** Tabs in this view */
860
+ tabs: Tab[];
861
+ /** Default view for this object */
862
+ default?: boolean;
863
+ /** System view (defined by developer, protected) */
864
+ system?: boolean;
865
+ /** Extensible metadata */
866
+ metadata?: Record<string, unknown>;
867
+ }
868
+ /**
869
+ * Check if a tab is a form tab
870
+ */
871
+ declare function isFormTab(tab: Tab): tab is FormTab;
872
+ /**
873
+ * Check if a tab is a table tab
874
+ */
875
+ declare function isTableTab(tab: Tab): tab is TableTab;
876
+ /**
877
+ * Check if a tab is a custom tab
878
+ */
879
+ declare function isCustomTab(tab: Tab): tab is CustomTab;
880
+
881
+ /**
882
+ * Registry for native objects defined in code
883
+ * Native objects are system objects that cannot be deleted/modified by clients
884
+ * They are defined by developers and synced to the database at startup
885
+ */
886
+ declare class NativeObjectRegistryClass {
887
+ private objects;
888
+ /**
889
+ * Register one or more native objects
890
+ * Auto-builds if ObjectBuilder is passed instead of ObjectDefinition
891
+ * @param objects - Single object/builder or array of objects/builders to register
892
+ * @returns this (for chaining)
893
+ * @throws Error if object is invalid or already registered
894
+ *
895
+ * @example
896
+ * ```typescript
897
+ * // No .build() needed - registry auto-builds!
898
+ * const PRODUCT = object({ id: "obj-product", name: "products", label: "Product" })
899
+ * .system()
900
+ * .attribute(text({ id: "attr-name", name: "name", label: "Name" }));
901
+ *
902
+ * registry.register(PRODUCT); // ← Auto-builds here
903
+ *
904
+ * // Can still explicitly .build() if you want
905
+ * registry.register(PRODUCT.build());
906
+ *
907
+ * // Register multiple
908
+ * registry.register([PRODUCT, ORDER, CUSTOMER]);
909
+ * ```
910
+ */
911
+ register(objects: ObjectDefinition | ObjectDefinition[] | {
912
+ build: () => ObjectDefinition;
913
+ } | Array<{
914
+ build: () => ObjectDefinition;
915
+ }>): this;
916
+ /**
917
+ * Validate and register a single object
918
+ * @internal
919
+ */
920
+ private validateAndRegister;
921
+ /**
922
+ * Get a native object by its name
923
+ * @param name - The object name
924
+ * @returns The object definition or undefined if not found
925
+ *
926
+ * @example
927
+ * ```typescript
928
+ * const product = registry.getByName("products");
929
+ * if (product) {
930
+ * console.log(product.label); // "Product"
931
+ * }
932
+ * ```
933
+ */
934
+ getByName(name: string): ObjectDefinition | undefined;
935
+ /**
936
+ * Get a native object or throw if not found
937
+ * @param name - The object name
938
+ * @returns The object definition
939
+ * @throws Error if not found
940
+ */
941
+ getByNameOrThrow(name: string): ObjectDefinition;
942
+ /**
943
+ * Get all registered native objects
944
+ * @returns Array of all registered object definitions
945
+ */
946
+ getAll(): ObjectDefinition[];
947
+ /**
948
+ * Get all registered native object names
949
+ * @returns Array of object names
950
+ */
951
+ listNames(): string[];
952
+ /**
953
+ * Check if a native object is registered
954
+ * @param name - The object name
955
+ * @returns true if registered, false otherwise
956
+ */
957
+ has(name: string): boolean;
958
+ /**
959
+ * Get the number of registered objects
960
+ */
961
+ get size(): number;
962
+ /**
963
+ * Clear all registered objects (useful for testing)
964
+ * @internal
965
+ */
966
+ clear(): void;
967
+ /**
968
+ * Get registry summary for debugging
969
+ */
970
+ summary(): string;
971
+ /**
972
+ * Log registry summary to console
973
+ */
974
+ debug(): void;
975
+ }
976
+ /**
977
+ * Singleton instance of the registry
978
+ * Use this to register and retrieve native objects
979
+ *
980
+ * @example
981
+ * ```typescript
982
+ * import { registry } from "@stndrds/schema";
983
+ *
984
+ * // Register objects
985
+ * registry.register([PRODUCT, ORDER, CUSTOMER]);
986
+ *
987
+ * // Get object by name
988
+ * const product = registry.getByName("products");
989
+ *
990
+ * // List all
991
+ * console.log(registry.listNames()); // ["products", "orders", ...]
992
+ *
993
+ * // Debug
994
+ * registry.debug();
995
+ * ```
996
+ */
997
+ declare const registry: NativeObjectRegistryClass;
998
+
999
+ /**
1000
+ * Registry for native view definitions
1001
+ *
1002
+ * Views registered here are considered "system" views, defined by the developer.
1003
+ * They are protected from modification by end-users and synced to the database
1004
+ * at application startup.
1005
+ *
1006
+ * @example
1007
+ * ```typescript
1008
+ * import { view, group, viewRegistry } from "@stndrds/schema";
1009
+ *
1010
+ * const COMPANY_DETAIL = view("detail", "Detail")
1011
+ * .for("companies")
1012
+ * .system()
1013
+ * .tab("general", "Info")
1014
+ * .form(group("main", "Main").fields("name", "status"))
1015
+ * .build();
1016
+ *
1017
+ * viewRegistry.register(COMPANY_DETAIL);
1018
+ * ```
1019
+ */
1020
+ declare class ViewRegistry {
1021
+ private views;
1022
+ private byObject;
1023
+ /**
1024
+ * Register a native view
1025
+ * @param viewOrViews - Single view or array of views
1026
+ * @throws Error if view is not marked as system
1027
+ * @throws Error if view with same name already exists for the object
1028
+ */
1029
+ register(viewOrViews: ViewDefinition | ViewDefinition[]): this;
1030
+ private registerSingle;
1031
+ /**
1032
+ * Get all views for an object
1033
+ */
1034
+ getByObjectName(objectName: string): ViewDefinition[];
1035
+ /**
1036
+ * Get a specific view by object and view name
1037
+ */
1038
+ get(objectName: string, viewName: string): ViewDefinition | undefined;
1039
+ /**
1040
+ * Get a view or throw if not found
1041
+ */
1042
+ getOrThrow(objectName: string, viewName: string): ViewDefinition;
1043
+ /**
1044
+ * Get all registered views
1045
+ */
1046
+ getAll(): ViewDefinition[];
1047
+ /**
1048
+ * Check if a view exists
1049
+ */
1050
+ has(objectName: string, viewName: string): boolean;
1051
+ /**
1052
+ * Check if any views exist for an object
1053
+ */
1054
+ hasObject(objectName: string): boolean;
1055
+ /**
1056
+ * Get number of registered views
1057
+ */
1058
+ get size(): number;
1059
+ /**
1060
+ * List all object names that have views
1061
+ */
1062
+ listObjectNames(): string[];
1063
+ /**
1064
+ * Get default view for an object (if any)
1065
+ */
1066
+ getDefault(objectName: string): ViewDefinition | undefined;
1067
+ /**
1068
+ * Clear all registered views (for testing)
1069
+ */
1070
+ clear(): void;
1071
+ /**
1072
+ * Generate summary string for debugging
1073
+ */
1074
+ summary(): string;
1075
+ /**
1076
+ * Log summary to console
1077
+ */
1078
+ debug(): void;
1079
+ private makeKey;
1080
+ }
1081
+ /**
1082
+ * Global registry for native views
1083
+ */
1084
+ declare const viewRegistry: ViewRegistry;
1085
+
1086
+ /**
1087
+ * Create a Zod schema for a text attribute
1088
+ */
1089
+ declare function createTextValidator(attr: TextAttribute): z.ZodString;
1090
+ /**
1091
+ * Create a Zod schema for a number attribute
1092
+ */
1093
+ declare function createNumberValidator(attr: NumberAttribute): z.ZodNumber;
1094
+ /**
1095
+ * Create a Zod schema for a checkbox attribute
1096
+ */
1097
+ declare function createCheckboxValidator(_attr: CheckboxAttribute): z.ZodBoolean;
1098
+ /**
1099
+ * Create a Zod schema for a date attribute
1100
+ */
1101
+ declare function createDateValidator(attr: DateAttribute): z.ZodString;
1102
+ /**
1103
+ * Create a Zod schema for a phone attribute
1104
+ */
1105
+ declare function createPhoneValidator(_attr: PhoneAttribute): z.ZodType<{
1106
+ countryCode: string;
1107
+ phoneNumber: string;
1108
+ }>;
1109
+ /**
1110
+ * Create a Zod schema for a currency attribute
1111
+ */
1112
+ declare function createCurrencyValidator(_attr: CurrencyAttribute): z.ZodType<{
1113
+ code: string;
1114
+ value: number;
1115
+ }>;
1116
+ /**
1117
+ * Create a Zod schema for a status attribute
1118
+ */
1119
+ declare function createStatusValidator(attr: StatusAttribute): z.ZodEnum<[string, ...string[]]>;
1120
+ /**
1121
+ * Create a Zod schema for a select attribute
1122
+ */
1123
+ declare function createSelectValidator(attr: SelectAttribute): z.ZodEnum<[string, ...string[]]>;
1124
+ /**
1125
+ * Create a Zod schema for a multiselect attribute
1126
+ */
1127
+ declare function createMultiselectValidator(attr: MultiselectAttribute): z.ZodArray<z.ZodEnum<[string, ...string[]]>>;
1128
+ /**
1129
+ * Create a Zod schema for a location attribute
1130
+ */
1131
+ type LocationShape = {
1132
+ address?: string;
1133
+ address2?: string;
1134
+ city?: string;
1135
+ state?: string;
1136
+ postalCode?: string;
1137
+ country?: string;
1138
+ latitude?: number;
1139
+ longitude?: number;
1140
+ };
1141
+ declare function createLocationValidator(_attr: LocationAttribute): z.ZodType<LocationShape>;
1142
+ /**
1143
+ * Create a Zod schema for a timestamp attribute
1144
+ */
1145
+ declare function createTimestampValidator(_attr: TimestampAttribute): z.ZodNumber;
1146
+ /**
1147
+ * Create a Zod schema for a file attribute
1148
+ */
1149
+ declare function createFileValidator(_attr: FileAttribute): z.ZodString;
1150
+ /**
1151
+ * Create a Zod schema for a user attribute
1152
+ */
1153
+ declare function createUserValidator(_attr: UserAttribute): z.ZodString;
1154
+ /**
1155
+ * Create a Zod schema for a single relation attribute (cardinality: "one")
1156
+ */
1157
+ declare function createSingleRelationValidator(attr: SingleRelationAttribute): z.ZodUnion<[z.ZodString, z.ZodNull]>;
1158
+ /**
1159
+ * Create a Zod schema for a multi relation attribute (cardinality: "many")
1160
+ */
1161
+ declare function createMultiRelationValidator(attr: MultiRelationAttribute): z.ZodArray<z.ZodString>;
1162
+ /**
1163
+ * Create a Zod schema for a relation attribute
1164
+ * Dispatches to single or multi validator based on cardinality
1165
+ */
1166
+ declare function createRelationValidator(attr: RelationAttribute): z.ZodUnion<[z.ZodString, z.ZodNull]> | z.ZodArray<z.ZodString>;
1167
+ /**
1168
+ * Create a Zod schema for a rating attribute
1169
+ */
1170
+ declare function createRatingValidator(attr: RatingAttribute): z.ZodNumber;
1171
+ /**
1172
+ * Create a Zod schema for any attribute type
1173
+ */
1174
+ declare function createAttributeValidator(attr: Attribute): z.ZodTypeAny;
1175
+ /**
1176
+ * Create a Zod schema for an entire object
1177
+ */
1178
+ declare function createObjectValidator(objectDef: ObjectDefinition): z.ZodType<Record<string, unknown>>;
1179
+ /**
1180
+ * Validation result
1181
+ */
1182
+ interface ValidationResult {
1183
+ success: boolean;
1184
+ data?: Record<string, unknown>;
1185
+ errors?: Array<{
1186
+ path: string[];
1187
+ message: string;
1188
+ }>;
1189
+ }
1190
+ /**
1191
+ * Validate data against an attribute schema
1192
+ */
1193
+ declare function validateAttribute(attr: Attribute, value: unknown): ValidationResult;
1194
+ /**
1195
+ * Validate data against an object schema
1196
+ */
1197
+ declare function validateObject(objectDef: ObjectDefinition, data: Record<string, unknown>): ValidationResult;
1198
+ /**
1199
+ * Validate and throw if invalid
1200
+ */
1201
+ declare function validateObjectOrThrow(objectDef: ObjectDefinition, data: Record<string, unknown>): Record<string, unknown>;
1202
+ /**
1203
+ * Create a Zod schema for draft validation.
1204
+ * All attributes become optional, but provided values are still validated.
1205
+ */
1206
+ declare function createDraftValidator(objectDef: ObjectDefinition): z.ZodType<Record<string, unknown>>;
1207
+ /**
1208
+ * Validate data in draft mode.
1209
+ * - All attributes are treated as optional (no required validation)
1210
+ * - Provided values are still validated for format/type correctness
1211
+ *
1212
+ * Use this when creating records that may be incomplete (drafts).
1213
+ *
1214
+ * @example
1215
+ * ```typescript
1216
+ * const result = validateDraft(PRODUCT, { name: "Draft" });
1217
+ * // → success even if "price" is required but missing
1218
+ *
1219
+ * const result2 = validateDraft(PRODUCT, { price: -10 });
1220
+ * // → fails because price must be >= 0 (format validation still applies)
1221
+ * ```
1222
+ */
1223
+ declare function validateDraft(objectDef: ObjectDefinition, data: Record<string, unknown>): ValidationResult;
1224
+ /**
1225
+ * Validate draft data and throw if format validation fails.
1226
+ */
1227
+ declare function validateDraftOrThrow(objectDef: ObjectDefinition, data: Record<string, unknown>): Record<string, unknown>;
1228
+ /**
1229
+ * Get the list of required attributes that are missing values.
1230
+ *
1231
+ * @example
1232
+ * ```typescript
1233
+ * const missing = getMissingRequiredAttributes(PRODUCT, { name: "Test" });
1234
+ * // → [priceAttribute, statusAttribute] if price and status are required but missing
1235
+ * ```
1236
+ */
1237
+ declare function getMissingRequiredAttributes(objectDef: ObjectDefinition, data: Record<string, unknown>): Attribute[];
1238
+ /**
1239
+ * Check if a record is complete (all required attributes have valid values).
1240
+ *
1241
+ * @returns `true` if all required values are present and valid, `false` otherwise
1242
+ */
1243
+ declare function isRecordComplete(objectDef: ObjectDefinition, data: Record<string, unknown>): boolean;
1244
+ /**
1245
+ * Compute the completion status of a record based on its data.
1246
+ *
1247
+ * - `"complete"`: All required values are present and valid
1248
+ * - `"draft"`: One or more required values are missing or invalid
1249
+ *
1250
+ * This function is used to dynamically determine the status when
1251
+ * creating or updating records.
1252
+ *
1253
+ * @example
1254
+ * ```typescript
1255
+ * const status = computeRecordStatus(PRODUCT, {
1256
+ * name: "Nike Air Max",
1257
+ * price: 129.99,
1258
+ * status: "active"
1259
+ * });
1260
+ * // → "complete"
1261
+ *
1262
+ * const status2 = computeRecordStatus(PRODUCT, { name: "Draft Product" });
1263
+ * // → "draft" (missing required fields)
1264
+ * ```
1265
+ */
1266
+ declare function computeRecordStatus(objectDef: ObjectDefinition, data: Record<string, unknown>): CompletionStatus;
1267
+
1268
+ /**
1269
+ * Object as stored in database (metadata)
1270
+ */
1271
+ interface DBObject extends Timestamps {
1272
+ id: Uuid;
1273
+ tenantId: TenantId;
1274
+ name: string;
1275
+ label: string;
1276
+ description?: string;
1277
+ icon?: IconName;
1278
+ labelExpression: string;
1279
+ system: boolean;
1280
+ metadata?: Record<string, unknown>;
1281
+ }
1282
+ interface CreateDBObject {
1283
+ tenantId: TenantId;
1284
+ name: string;
1285
+ label: string;
1286
+ description?: string;
1287
+ icon?: IconName;
1288
+ labelExpression: string;
1289
+ system?: boolean;
1290
+ metadata?: Record<string, unknown>;
1291
+ }
1292
+ interface UpdateDBObject {
1293
+ label?: string;
1294
+ description?: string;
1295
+ icon?: IconName;
1296
+ metadata?: Record<string, unknown>;
1297
+ }
1298
+ interface UpsertDBObject extends CreateDBObject {
1299
+ system: boolean;
1300
+ }
1301
+ /**
1302
+ * Attribute as stored in database (metadata)
1303
+ */
1304
+ interface DBAttribute extends Timestamps {
1305
+ id: Uuid;
1306
+ objectId: Uuid;
1307
+ name: string;
1308
+ label: string;
1309
+ type: AttributeType;
1310
+ description?: string;
1311
+ icon?: IconName;
1312
+ system: boolean;
1313
+ required: boolean;
1314
+ unique: boolean;
1315
+ order: number;
1316
+ hidden?: boolean;
1317
+ archived?: boolean;
1318
+ deprecated?: boolean;
1319
+ defaultValue?: unknown;
1320
+ config: Record<string, unknown>;
1321
+ }
1322
+ interface CreateDBAttribute {
1323
+ objectId: Uuid;
1324
+ name: string;
1325
+ label: string;
1326
+ type: AttributeType;
1327
+ description?: string;
1328
+ icon?: IconName;
1329
+ system?: boolean;
1330
+ required?: boolean;
1331
+ unique?: boolean;
1332
+ order?: number;
1333
+ hidden?: boolean;
1334
+ archived?: boolean;
1335
+ deprecated?: boolean;
1336
+ defaultValue?: unknown;
1337
+ config?: Record<string, unknown>;
1338
+ }
1339
+ interface UpdateDBAttribute {
1340
+ label?: string;
1341
+ description?: string;
1342
+ icon?: IconName;
1343
+ required?: boolean;
1344
+ order?: number;
1345
+ hidden?: boolean;
1346
+ archived?: boolean;
1347
+ deprecated?: boolean;
1348
+ defaultValue?: unknown;
1349
+ config?: Record<string, unknown>;
1350
+ }
1351
+ interface UpsertDBAttribute extends CreateDBAttribute {
1352
+ objectId: Uuid;
1353
+ name: string;
1354
+ }
1355
+
1356
+ /**
1357
+ * Object record creation data
1358
+ */
1359
+ interface CreateObjectRecord {
1360
+ tenantId: TenantId;
1361
+ objectId: Uuid;
1362
+ data: Record<string, unknown>;
1363
+ /**
1364
+ * Computed display label from labelExpression.
1365
+ * Stored for performance - avoids recomputation on every read.
1366
+ */
1367
+ label: string;
1368
+ /**
1369
+ * Completion status of the record.
1370
+ * - `draft`: Record is incomplete (missing required values)
1371
+ * - `complete`: All required values are present and valid
1372
+ */
1373
+ completionStatus: "draft" | "complete";
1374
+ }
1375
+ /**
1376
+ * Generic list options for pagination and sorting
1377
+ */
1378
+ interface ListOptions {
1379
+ limit?: number;
1380
+ offset?: number;
1381
+ orderBy?: string;
1382
+ orderDirection?: "asc" | "desc";
1383
+ }
1384
+ /**
1385
+ * Search options for full-text search
1386
+ */
1387
+ interface SearchOptions extends ListOptions {
1388
+ filters?: Record<string, unknown>;
1389
+ highlight?: boolean;
1390
+ }
1391
+ /**
1392
+ * Global search options
1393
+ */
1394
+ interface GlobalSearchOptions extends ListOptions {
1395
+ /**
1396
+ * Limit results to specific object names
1397
+ */
1398
+ objectNames?: string[];
1399
+ /**
1400
+ * Whether to include object metadata in results
1401
+ */
1402
+ includeObjectInfo?: boolean;
1403
+ }
1404
+ /**
1405
+ * Global search result item
1406
+ */
1407
+ interface GlobalSearchResultItem {
1408
+ objectId: string;
1409
+ objectName: string;
1410
+ objectLabel: string;
1411
+ /** Computed label from labelExpression */
1412
+ label: string;
1413
+ recordId: string;
1414
+ values: Record<string, unknown>;
1415
+ completionStatus: "draft" | "complete";
1416
+ createdAt: Date;
1417
+ updatedAt: Date;
1418
+ }
1419
+ /**
1420
+ * File-specific list options
1421
+ */
1422
+ interface FileListOptions extends ListOptions {
1423
+ folderPath?: string;
1424
+ mimeType?: string;
1425
+ uploadedBy?: Uuid;
1426
+ includeDeleted?: boolean;
1427
+ }
1428
+ /**
1429
+ * View as stored in database
1430
+ */
1431
+ interface DBView extends Timestamps {
1432
+ id: Uuid;
1433
+ tenantId: TenantId;
1434
+ objectId?: Uuid;
1435
+ objectName: string;
1436
+ name: string;
1437
+ label: string;
1438
+ description?: string;
1439
+ icon?: IconName;
1440
+ tabs: Tab[];
1441
+ default: boolean;
1442
+ system: boolean;
1443
+ metadata?: Record<string, unknown>;
1444
+ }
1445
+ interface CreateDBView {
1446
+ tenantId: TenantId;
1447
+ objectId?: Uuid;
1448
+ objectName: string;
1449
+ name: string;
1450
+ label: string;
1451
+ description?: string;
1452
+ icon?: IconName;
1453
+ tabs: Tab[];
1454
+ default?: boolean;
1455
+ system?: boolean;
1456
+ metadata?: Record<string, unknown>;
1457
+ }
1458
+ interface UpdateDBView {
1459
+ label?: string;
1460
+ description?: string;
1461
+ icon?: IconName;
1462
+ tabs?: Tab[];
1463
+ default?: boolean;
1464
+ metadata?: Record<string, unknown>;
1465
+ }
1466
+ interface UpsertDBView {
1467
+ tenantId: TenantId;
1468
+ objectName: string;
1469
+ name: string;
1470
+ label: string;
1471
+ description?: string;
1472
+ icon?: IconName;
1473
+ tabs: Tab[];
1474
+ default?: boolean;
1475
+ system?: boolean;
1476
+ metadata?: Record<string, unknown>;
1477
+ }
1478
+ /**
1479
+ * Result of an operation
1480
+ */
1481
+ interface OperationResult<T = unknown> {
1482
+ success: boolean;
1483
+ data?: T;
1484
+ error?: {
1485
+ code: string;
1486
+ message: string;
1487
+ details?: Record<string, unknown>;
1488
+ };
1489
+ }
1490
+
1491
+ /**
1492
+ * Repository for objects table (metadata)
1493
+ */
1494
+ interface ObjectsRepository {
1495
+ /**
1496
+ * Find object by ID
1497
+ */
1498
+ findById(id: Uuid): Promise<DBObject | null>;
1499
+ /**
1500
+ * Find object by name and tenant
1501
+ */
1502
+ findByName(tenantId: TenantId, name: string): Promise<DBObject | null>;
1503
+ /**
1504
+ * Find system/native object by name (system=true, for sync)
1505
+ */
1506
+ findSystemByName(name: string): Promise<DBObject | null>;
1507
+ /**
1508
+ * Create object
1509
+ */
1510
+ create(data: CreateDBObject): Promise<DBObject>;
1511
+ /**
1512
+ * Update object
1513
+ */
1514
+ update(id: Uuid, data: Partial<UpdateDBObject>): Promise<DBObject>;
1515
+ /**
1516
+ * Delete object
1517
+ */
1518
+ delete(id: Uuid): Promise<void>;
1519
+ /**
1520
+ * List all objects for a tenant
1521
+ */
1522
+ list(tenantId: TenantId): Promise<DBObject[]>;
1523
+ /**
1524
+ * Upsert object (create or update based on nativeObjectId)
1525
+ */
1526
+ upsert(data: UpsertDBObject): Promise<DBObject>;
1527
+ }
1528
+ /**
1529
+ * Repository for attributes table (metadata)
1530
+ */
1531
+ interface AttributesRepository {
1532
+ /**
1533
+ * Find attribute by ID
1534
+ */
1535
+ findById(id: Uuid): Promise<DBAttribute | null>;
1536
+ /**
1537
+ * Find attributes by object ID
1538
+ */
1539
+ findByObjectId(objectId: Uuid): Promise<DBAttribute[]>;
1540
+ /**
1541
+ * Create attribute
1542
+ */
1543
+ create(data: CreateDBAttribute): Promise<DBAttribute>;
1544
+ /**
1545
+ * Update attribute
1546
+ */
1547
+ update(id: Uuid, data: Partial<UpdateDBAttribute>): Promise<DBAttribute>;
1548
+ /**
1549
+ * Delete attribute
1550
+ */
1551
+ delete(id: Uuid): Promise<void>;
1552
+ /**
1553
+ * Delete multiple attributes by names (for sync cleanup)
1554
+ */
1555
+ deleteByNames(objectId: Uuid, excludeNames: string[]): Promise<number>;
1556
+ /**
1557
+ * Upsert attribute (create or update based on objectId + name)
1558
+ */
1559
+ upsert(data: UpsertDBAttribute): Promise<DBAttribute>;
1560
+ }
1561
+ /**
1562
+ * Repository for user_profiles table
1563
+ */
1564
+ interface UserProfilesRepository {
1565
+ /**
1566
+ * Find user profile by ID
1567
+ */
1568
+ findById(id: Uuid): Promise<UserProfile | null>;
1569
+ /**
1570
+ * Find user profile by auth ID (external auth provider)
1571
+ */
1572
+ findByAuthId(authId: string): Promise<UserProfile | null>;
1573
+ /**
1574
+ * Find user profile by email
1575
+ */
1576
+ findByEmail(tenantId: TenantId, email: string): Promise<UserProfile | null>;
1577
+ /**
1578
+ * Create user profile
1579
+ */
1580
+ create(data: CreateUserProfile): Promise<UserProfile>;
1581
+ /**
1582
+ * Update user profile
1583
+ */
1584
+ update(id: Uuid, data: UpdateUserProfile): Promise<UserProfile>;
1585
+ /**
1586
+ * Delete user profile
1587
+ */
1588
+ delete(id: Uuid): Promise<void>;
1589
+ /**
1590
+ * List all user profiles for a tenant
1591
+ */
1592
+ list(tenantId: TenantId, options?: ListOptions): Promise<UserProfile[]>;
1593
+ /**
1594
+ * Update last login timestamp
1595
+ */
1596
+ updateLastLogin(id: Uuid): Promise<void>;
1597
+ }
1598
+ /**
1599
+ * Repository for files table
1600
+ */
1601
+ interface FilesRepository {
1602
+ /**
1603
+ * Find file by ID
1604
+ */
1605
+ findById(id: Uuid): Promise<File | null>;
1606
+ /**
1607
+ * Create file
1608
+ */
1609
+ create(data: CreateFile): Promise<File>;
1610
+ /**
1611
+ * Update file
1612
+ */
1613
+ update(id: Uuid, data: UpdateFile): Promise<File>;
1614
+ /**
1615
+ * Delete file (soft delete)
1616
+ */
1617
+ delete(id: Uuid): Promise<void>;
1618
+ /**
1619
+ * Hard delete file (permanent)
1620
+ */
1621
+ hardDelete(id: Uuid): Promise<void>;
1622
+ /**
1623
+ * List files for a tenant
1624
+ */
1625
+ list(tenantId: TenantId, options?: FileListOptions): Promise<File[]>;
1626
+ /**
1627
+ * Find files by folder path
1628
+ */
1629
+ findByFolder(tenantId: TenantId, folderPath: string): Promise<File[]>;
1630
+ /**
1631
+ * Find files by uploader
1632
+ */
1633
+ findByUploader(uploadedBy: Uuid): Promise<File[]>;
1634
+ }
1635
+ /**
1636
+ * Repository for object_records table (unified JSONB)
1637
+ */
1638
+ interface ObjectRecordsRepository {
1639
+ /**
1640
+ * Find record by ID
1641
+ */
1642
+ findById(id: Uuid): Promise<ObjectRecord | null>;
1643
+ /**
1644
+ * Create record
1645
+ */
1646
+ create(data: CreateObjectRecord): Promise<ObjectRecord>;
1647
+ /**
1648
+ * Update record
1649
+ */
1650
+ update(id: Uuid, data: Partial<Record<string, unknown>>): Promise<ObjectRecord>;
1651
+ /**
1652
+ * Delete record
1653
+ */
1654
+ delete(id: Uuid): Promise<void>;
1655
+ /**
1656
+ * List records for an object
1657
+ */
1658
+ list(tenantId: TenantId, objectId: Uuid, options?: ListOptions): Promise<{
1659
+ records: ObjectRecord[];
1660
+ total: number;
1661
+ }>;
1662
+ /**
1663
+ * Search records using PostgreSQL full-text search
1664
+ */
1665
+ search(tenantId: TenantId, objectId: Uuid, query: string, options?: SearchOptions): Promise<{
1666
+ records: ObjectRecord[];
1667
+ total: number;
1668
+ }>;
1669
+ /**
1670
+ * Global search across all object records for a tenant
1671
+ * Searches in all objects or a subset specified by objectNames
1672
+ */
1673
+ globalSearch(tenantId: TenantId, query: string, options?: GlobalSearchOptions): Promise<{
1674
+ results: GlobalSearchResultItem[];
1675
+ total: number;
1676
+ }>;
1677
+ }
1678
+ /**
1679
+ * Repository for views table
1680
+ */
1681
+ interface ViewsRepository {
1682
+ /**
1683
+ * Find view by ID
1684
+ */
1685
+ findById(id: Uuid): Promise<DBView | null>;
1686
+ /**
1687
+ * Find view by name for an object and tenant
1688
+ */
1689
+ findByName(tenantId: TenantId, objectName: string, viewName: string): Promise<DBView | null>;
1690
+ /**
1691
+ * Find all views for an object and tenant
1692
+ */
1693
+ findByObjectName(tenantId: TenantId, objectName: string): Promise<DBView[]>;
1694
+ /**
1695
+ * Find all views for a tenant
1696
+ */
1697
+ findAllForTenant(tenantId: TenantId): Promise<DBView[]>;
1698
+ /**
1699
+ * Find system view by name (for sync)
1700
+ */
1701
+ findSystemByName(objectName: string, viewName: string): Promise<DBView | null>;
1702
+ /**
1703
+ * Find all system views for an object
1704
+ */
1705
+ findSystemByObjectName(objectName: string): Promise<DBView[]>;
1706
+ /**
1707
+ * Create view
1708
+ */
1709
+ create(data: CreateDBView): Promise<DBView>;
1710
+ /**
1711
+ * Update view
1712
+ */
1713
+ update(id: Uuid, data: Partial<UpdateDBView>): Promise<DBView>;
1714
+ /**
1715
+ * Delete view
1716
+ */
1717
+ delete(id: Uuid): Promise<void>;
1718
+ /**
1719
+ * Delete views not in the list (for sync cleanup)
1720
+ * @returns Number of deleted views
1721
+ */
1722
+ deleteNotIn(objectName: string, keepViewNames: string[]): Promise<number>;
1723
+ /**
1724
+ * Upsert view (create or update based on objectName + name)
1725
+ */
1726
+ upsert(data: UpsertDBView): Promise<DBView>;
1727
+ }
1728
+
1729
+ /**
1730
+ * Generic database adapter interface
1731
+ * Any ORM (Drizzle, Prisma, Kysely, TypeORM) can implement this interface
1732
+ * to work with @stndrds/schema runtime services
1733
+ *
1734
+ * @example
1735
+ * ```typescript
1736
+ * // Drizzle implementation
1737
+ * import { createDrizzleAdapter } from "./adapters/drizzle";
1738
+ * import { db } from "./db";
1739
+ *
1740
+ * const adapter = createDrizzleAdapter(db);
1741
+ *
1742
+ * // Prisma implementation
1743
+ * import { createPrismaAdapter } from "./adapters/prisma";
1744
+ * import { prisma } from "./db";
1745
+ *
1746
+ * const adapter = createPrismaAdapter(prisma);
1747
+ * ```
1748
+ */
1749
+ interface DatabaseAdapter {
1750
+ objects: ObjectsRepository;
1751
+ attributes: AttributesRepository;
1752
+ views: ViewsRepository;
1753
+ userProfiles: UserProfilesRepository;
1754
+ files: FilesRepository;
1755
+ objectRecords: ObjectRecordsRepository;
1756
+ transaction<T>(callback: (adapter: DatabaseAdapter) => Promise<T>): Promise<T>;
1757
+ }
1758
+
1759
+ interface InternalObjectRecord extends ObjectRecord {
1760
+ tenantId: TenantId;
1761
+ }
1762
+ interface MockStores {
1763
+ objects: Map<Uuid, DBObject>;
1764
+ attributes: Map<Uuid, DBAttribute>;
1765
+ userProfiles: Map<Uuid, UserProfile>;
1766
+ files: Map<Uuid, File>;
1767
+ objectRecords: Map<Uuid, InternalObjectRecord>;
1768
+ views: Map<Uuid, DBView>;
1769
+ }
1770
+ /**
1771
+ * Create an in-memory mock adapter for testing and development
1772
+ *
1773
+ * This adapter stores all data in memory and is perfect for:
1774
+ * - Unit tests
1775
+ * - Integration tests
1776
+ * - Local development without a database
1777
+ * - Understanding the adapter interface
1778
+ *
1779
+ * @returns A DatabaseAdapter implementation using in-memory storage
1780
+ *
1781
+ * @example
1782
+ * ```typescript
1783
+ * import { createMockAdapter, RecordService } from "@stndrds/schema";
1784
+ *
1785
+ * // Create adapter
1786
+ * const adapter = createMockAdapter();
1787
+ *
1788
+ * // Use with services
1789
+ * const recordService = new RecordService(adapter, "tenant-123");
1790
+ *
1791
+ * // Create a record
1792
+ * const product = await recordService.createRecord("obj-product", {
1793
+ * name: "Nike Air Max",
1794
+ * price: 129.99
1795
+ * });
1796
+ *
1797
+ * // List records
1798
+ * const { records, total } = await recordService.listRecords("obj-product");
1799
+ * ```
1800
+ */
1801
+ declare function createMockAdapter(): DatabaseAdapter & {
1802
+ _stores: MockStores;
1803
+ reset(): void;
1804
+ };
1805
+
1806
+ /**
1807
+ * Service for managing files
1808
+ * Handles file metadata CRUD, permissions, and soft delete
1809
+ */
1810
+ declare class FileService {
1811
+ private adapter;
1812
+ private tenantId;
1813
+ constructor(adapter: DatabaseAdapter, tenantId: string);
1814
+ /**
1815
+ * Create a new file record (after upload to storage)
1816
+ *
1817
+ * @param data - File metadata
1818
+ * @returns Created file record
1819
+ *
1820
+ * @example
1821
+ * ```typescript
1822
+ * const service = new FileService(adapter, "tenant-123");
1823
+ *
1824
+ * // After uploading to S3
1825
+ * const file = await service.createFile({
1826
+ * tenantId: "tenant-123",
1827
+ * name: "contract-2025.pdf",
1828
+ * originalName: "Contract Acme Corp 2025.pdf",
1829
+ * mimeType: "application/pdf",
1830
+ * size: 2458624,
1831
+ * storageProvider: "s3",
1832
+ * storagePath: "tenants/123/files/2025/contract.pdf",
1833
+ * storageBucket: "my-app-files",
1834
+ * url: "https://cdn.example.com/files/file-123",
1835
+ * uploadedBy: "profile-456",
1836
+ * visibility: "private"
1837
+ * });
1838
+ * ```
1839
+ */
1840
+ createFile(data: CreateFile): Promise<File>;
1841
+ /**
1842
+ * Get file by ID
1843
+ */
1844
+ getFile(fileId: string): Promise<File | null>;
1845
+ /**
1846
+ * Get file by ID or throw
1847
+ */
1848
+ getFileOrThrow(fileId: string): Promise<File>;
1849
+ /**
1850
+ * Update file metadata
1851
+ *
1852
+ * @param fileId - File UUID
1853
+ * @param data - Data to update
1854
+ * @returns Updated file
1855
+ */
1856
+ updateFile(fileId: string, data: UpdateFile): Promise<File>;
1857
+ /**
1858
+ * Delete file (soft delete)
1859
+ *
1860
+ * @param fileId - File UUID
1861
+ * @param options - Delete options
1862
+ */
1863
+ deleteFile(fileId: string, options?: {
1864
+ hard?: boolean;
1865
+ checkOwnership?: boolean;
1866
+ userId?: string;
1867
+ }): Promise<void>;
1868
+ /**
1869
+ * List files for the tenant
1870
+ */
1871
+ listFiles(options?: FileListOptions): Promise<File[]>;
1872
+ /**
1873
+ * List files by folder
1874
+ */
1875
+ listFilesByFolder(folderPath: string): Promise<File[]>;
1876
+ /**
1877
+ * List files uploaded by a specific user
1878
+ */
1879
+ listFilesByUploader(uploadedBy: string): Promise<File[]>;
1880
+ /**
1881
+ * Change file visibility
1882
+ *
1883
+ * @param fileId - File UUID
1884
+ * @param visibility - New visibility level
1885
+ * @param allowedUsers - Users allowed to access (if restricted)
1886
+ */
1887
+ changeVisibility(fileId: string, visibility: "public" | "private" | "restricted", allowedUsers?: string[]): Promise<File>;
1888
+ /**
1889
+ * Grant access to a file for specific users
1890
+ *
1891
+ * @param fileId - File UUID
1892
+ * @param userIds - User IDs to grant access
1893
+ */
1894
+ grantAccess(fileId: string, userIds: string[]): Promise<File>;
1895
+ /**
1896
+ * Revoke access to a file for specific users
1897
+ *
1898
+ * @param fileId - File UUID
1899
+ * @param userIds - User IDs to revoke access
1900
+ */
1901
+ revokeAccess(fileId: string, userIds: string[]): Promise<File>;
1902
+ /**
1903
+ * Check if user has access to a file
1904
+ *
1905
+ * @param fileId - File UUID
1906
+ * @param userId - User ID to check
1907
+ * @returns true if user can access the file
1908
+ */
1909
+ canAccess(fileId: string, userId: string): Promise<boolean>;
1910
+ /**
1911
+ * Move file to different folder
1912
+ */
1913
+ moveToFolder(fileId: string, newFolderPath: string): Promise<File>;
1914
+ /**
1915
+ * Add tags to file
1916
+ */
1917
+ addTags(fileId: string, tags: string[]): Promise<File>;
1918
+ /**
1919
+ * Remove tags from file
1920
+ */
1921
+ removeTags(fileId: string, tags: string[]): Promise<File>;
1922
+ }
1923
+
1924
+ /**
1925
+ * Geocoding service for address autocomplete and geocoding operations
1926
+ *
1927
+ * @example
1928
+ * ```typescript
1929
+ * import { GeocodingService } from "@stndrds/schema";
1930
+ * import { GoogleMapsAdapter } from "./adapters/google-maps";
1931
+ *
1932
+ * const geocoding = new GeocodingService(new GoogleMapsAdapter({ apiKey: "..." }));
1933
+ *
1934
+ * const suggestions = await geocoding.autocomplete({
1935
+ * query: "40 Quai des Belges",
1936
+ * countries: ["FRA"],
1937
+ * limit: 5,
1938
+ * });
1939
+ * ```
1940
+ */
1941
+ declare class GeocodingService {
1942
+ private readonly adapter;
1943
+ constructor(adapter: GeocodingAdapter);
1944
+ /**
1945
+ * Search for address suggestions as the user types
1946
+ */
1947
+ autocomplete(params: GeocodingAutocompleteParams): Promise<GeocodingSuggestion[]>;
1948
+ /**
1949
+ * Reverse geocode coordinates to an address
1950
+ */
1951
+ reverse(params: ReverseGeocodingParams): Promise<GeocodingSuggestion | null>;
1952
+ /**
1953
+ * Geocode a structured address to coordinates
1954
+ */
1955
+ geocode(params: GeocodingParams): Promise<GeocodingSuggestion | null>;
1956
+ }
1957
+
1958
+ /**
1959
+ * Service for global search across all object records
1960
+ * Allows searching across all objects or a subset of objects for a tenant
1961
+ *
1962
+ * @example
1963
+ * ```typescript
1964
+ * const service = new GlobalSearchService(adapter, "tenant-123");
1965
+ *
1966
+ * // Search across all objects
1967
+ * const { results, total } = await service.search("nike");
1968
+ *
1969
+ * // Search only in specific objects
1970
+ * const { results, total } = await service.search("nike", {
1971
+ * objectNames: ["products", "orders"],
1972
+ * limit: 20
1973
+ * });
1974
+ * ```
1975
+ */
1976
+ declare class GlobalSearchService {
1977
+ private adapter;
1978
+ private tenantId;
1979
+ constructor(adapter: DatabaseAdapter, tenantId: string);
1980
+ /**
1981
+ * Search across all object records for the tenant
1982
+ *
1983
+ * @param query - Search query string
1984
+ * @param options - Search options (pagination, object filters)
1985
+ * @returns Matching records with object metadata and total count
1986
+ *
1987
+ * @example
1988
+ * ```typescript
1989
+ * // Basic search
1990
+ * const { results, total } = await service.search("nike air");
1991
+ *
1992
+ * // With pagination
1993
+ * const { results, total } = await service.search("nike", {
1994
+ * limit: 10,
1995
+ * offset: 20
1996
+ * });
1997
+ *
1998
+ * // Filter by object types
1999
+ * const { results, total } = await service.search("nike", {
2000
+ * objectNames: ["products", "orders"]
2001
+ * });
2002
+ * ```
2003
+ */
2004
+ search(query: string, options?: GlobalSearchOptions): Promise<{
2005
+ results: GlobalSearchResultItem[];
2006
+ total: number;
2007
+ }>;
2008
+ /**
2009
+ * Search and group results by object type
2010
+ *
2011
+ * @param query - Search query string
2012
+ * @param options - Search options
2013
+ * @returns Results grouped by object name
2014
+ */
2015
+ searchGrouped(query: string, options?: Omit<GlobalSearchOptions, "limit" | "offset">): Promise<{
2016
+ groups: Array<{
2017
+ objectName: string;
2018
+ objectLabel: string;
2019
+ results: GlobalSearchResultItem[];
2020
+ count: number;
2021
+ }>;
2022
+ total: number;
2023
+ }>;
2024
+ }
2025
+
2026
+ /**
2027
+ * Input for creating a custom object
2028
+ */
2029
+ interface CreateCustomObjectInput {
2030
+ name: string;
2031
+ label: string;
2032
+ /**
2033
+ * Template expression for computing record display labels.
2034
+ * Example: "{{ name }}" or "{{ firstName }} {{ lastName }}"
2035
+ */
2036
+ labelExpression: string;
2037
+ description?: string;
2038
+ icon?: IconName;
2039
+ attributes?: (Attribute | {
2040
+ build: () => Attribute;
2041
+ })[];
2042
+ metadata?: Record<string, unknown>;
2043
+ }
2044
+ /**
2045
+ * Input for adding an attribute to an object
2046
+ */
2047
+ interface AddAttributeInput {
2048
+ name: string;
2049
+ label: string;
2050
+ type: AttributeType;
2051
+ required?: boolean;
2052
+ unique?: boolean;
2053
+ description?: string;
2054
+ placeholder?: string;
2055
+ icon?: IconName;
2056
+ defaultValue?: unknown;
2057
+ metadata?: Record<string, unknown>;
2058
+ [key: string]: unknown;
2059
+ }
2060
+ /**
2061
+ * Service for managing object schemas
2062
+ * Handles fusion of native objects (from registry) and custom objects (from database)
2063
+ */
2064
+ declare class ObjectSchemaService {
2065
+ private adapter;
2066
+ private nativeRegistry;
2067
+ constructor(adapter: DatabaseAdapter, nativeRegistry: typeof registry);
2068
+ /**
2069
+ * Create a new custom object
2070
+ * Validates name format and ensures system=false
2071
+ *
2072
+ * @param definition - Object definition (attributes can be raw definitions or builders)
2073
+ * @param tenantId - Tenant ID owning the object
2074
+ * @returns Created ObjectDefinition
2075
+ */
2076
+ createCustomObject(definition: CreateCustomObjectInput, tenantId: string): Promise<ObjectDefinition>;
2077
+ /**
2078
+ * Add a custom attribute to an existing object
2079
+ * Can be used on both custom and native objects
2080
+ * Attributes added via API are always custom (system=false)
2081
+ *
2082
+ * @param objectId - Object UUID from database
2083
+ * @param attribute - Attribute definition
2084
+ * @returns Created Attribute
2085
+ */
2086
+ addAttributeToObject(objectId: string, attribute: AddAttributeInput): Promise<Attribute>;
2087
+ /**
2088
+ * Update an attribute
2089
+ * Can only update custom attributes (system=false)
2090
+ *
2091
+ * @param attributeId - Attribute UUID
2092
+ * @param updates - Partial attribute updates
2093
+ * @returns Updated Attribute
2094
+ */
2095
+ updateAttribute(attributeId: string, updates: Partial<AddAttributeInput>): Promise<Attribute>;
2096
+ /**
2097
+ * Delete an attribute
2098
+ * Can only delete custom attributes (system=false)
2099
+ *
2100
+ * @param attributeId - Attribute UUID
2101
+ */
2102
+ deleteAttribute(attributeId: string): Promise<void>;
2103
+ /**
2104
+ * List attributes for an object
2105
+ *
2106
+ * @param objectId - Object UUID
2107
+ * @param options - Filter options
2108
+ * @returns List of attributes
2109
+ */
2110
+ listAttributes(objectId: string, options?: {
2111
+ systemOnly?: boolean;
2112
+ customOnly?: boolean;
2113
+ }): Promise<Attribute[]>;
2114
+ /**
2115
+ * Validate attribute name format (variable identifier)
2116
+ * @internal
2117
+ */
2118
+ private validateAttributeName;
2119
+ /**
2120
+ * Get complete object schema (system + custom attributes)
2121
+ * If object is native, merges registry definition with DB custom attributes
2122
+ * If object is custom, returns DB definition only
2123
+ *
2124
+ * @param objectId - Object UUID from database
2125
+ * @returns Complete ObjectDefinition with all attributes
2126
+ *
2127
+ * @example
2128
+ * ```typescript
2129
+ * const service = new ObjectSchemaService(adapter, registry);
2130
+ * const productSchema = await service.getObjectSchema("obj-123");
2131
+ *
2132
+ * console.log(productSchema.attributes); // System + custom attributes
2133
+ * ```
2134
+ */
2135
+ getObjectSchema(objectId: string): Promise<ObjectDefinition>;
2136
+ /**
2137
+ * Get object schema by name (for system/native objects)
2138
+ * @deprecated Use getObjectSchemaByNameForTenant for custom objects support
2139
+ */
2140
+ getObjectSchemaByName(name: string): Promise<ObjectDefinition>;
2141
+ /**
2142
+ * Get object schema by name for a tenant (supports both native and custom objects)
2143
+ */
2144
+ getObjectSchemaByNameForTenant(name: string, tenantId: string): Promise<ObjectDefinition>;
2145
+ /**
2146
+ * List all object schemas for a tenant
2147
+ */
2148
+ listObjectSchemas(tenantId: string): Promise<ObjectDefinition[]>;
2149
+ /**
2150
+ * Merge native object from registry with custom attributes from DB
2151
+ * @internal
2152
+ */
2153
+ private mergeNativeObject;
2154
+ /**
2155
+ * Convert DB object + attributes to ObjectDefinition
2156
+ * @internal
2157
+ */
2158
+ private convertDBObjectToDefinition;
2159
+ /**
2160
+ * Convert DB attribute to Attribute type
2161
+ * @internal
2162
+ */
2163
+ private convertDBAttributeToAttribute;
2164
+ }
2165
+
2166
+ /**
2167
+ * Service for managing object records (CRUD operations)
2168
+ * Handles validation, dispatch to correct table, and data consistency
2169
+ */
2170
+ declare class RecordService {
2171
+ private adapter;
2172
+ private tenantId;
2173
+ private schemaService;
2174
+ private relationService;
2175
+ constructor(adapter: DatabaseAdapter, tenantId: string);
2176
+ /**
2177
+ * Compute display label from schema expression
2178
+ * @internal
2179
+ */
2180
+ private computeLabel;
2181
+ /**
2182
+ * Create a new record with validation
2183
+ *
2184
+ * @param objectId - Object UUID
2185
+ * @param data - Record data (attribute values)
2186
+ * @param options - Creation options
2187
+ * @returns Created record with computed completionStatus
2188
+ *
2189
+ * @example
2190
+ * ```typescript
2191
+ * const service = new RecordService(adapter, "tenant-123");
2192
+ *
2193
+ * // Create a complete record (strict validation)
2194
+ * const product = await service.createRecord("obj-product", {
2195
+ * name: "Nike Air Max",
2196
+ * price: 129.99,
2197
+ * status: "active"
2198
+ * });
2199
+ * // → product.completionStatus = "complete"
2200
+ *
2201
+ * // Create a draft record (allows missing required fields)
2202
+ * const draft = await service.createRecord("obj-product", {
2203
+ * name: "Draft Product"
2204
+ * }, { allowDraft: true });
2205
+ * // → draft.completionStatus = "draft"
2206
+ * ```
2207
+ */
2208
+ createRecord(objectId: string, data: Record<string, unknown>, options?: {
2209
+ /**
2210
+ * Allow creating records with missing required fields.
2211
+ * Format validation still applies to provided values.
2212
+ * @default false
2213
+ */
2214
+ allowDraft?: boolean;
2215
+ /**
2216
+ * Skip all validation (format + relations).
2217
+ * @default true
2218
+ */
2219
+ validate?: boolean;
2220
+ /**
2221
+ * Skip relation validation only.
2222
+ * Useful for bulk imports where relations are validated separately.
2223
+ * @default false
2224
+ */
2225
+ skipRelationValidation?: boolean;
2226
+ skipSystemCheck?: boolean;
2227
+ }): Promise<ObjectRecord>;
2228
+ /**
2229
+ * Get a record by ID
2230
+ *
2231
+ * @param recordId - Record UUID
2232
+ * @param options - Query options
2233
+ * @returns Record or null if not found
2234
+ */
2235
+ getRecord(recordId: string, options?: {
2236
+ includeSchema?: boolean;
2237
+ }): Promise<ObjectRecord | null>;
2238
+ /**
2239
+ * Get a record by ID or throw if not found
2240
+ */
2241
+ getRecordOrThrow(recordId: string): Promise<ObjectRecord>;
2242
+ /**
2243
+ * Update a record with validation
2244
+ *
2245
+ * The completion status is automatically recalculated after each update.
2246
+ * A draft record becomes complete when all required fields are filled.
2247
+ *
2248
+ * @param recordId - Record UUID
2249
+ * @param data - Partial data to update
2250
+ * @param options - Update options
2251
+ * @returns Updated record with recalculated completionStatus
2252
+ *
2253
+ * @example
2254
+ * ```typescript
2255
+ * // Update a draft record to make it complete
2256
+ * const updated = await service.updateRecord(draftId, {
2257
+ * price: 99.99,
2258
+ * status: "active"
2259
+ * });
2260
+ * // → updated.completionStatus = "complete" if all required fields now present
2261
+ * ```
2262
+ */
2263
+ updateRecord(recordId: string, data: Partial<Record<string, unknown>>, options?: {
2264
+ /**
2265
+ * Skip validation entirely (format + relations).
2266
+ * @default true
2267
+ */
2268
+ validate?: boolean;
2269
+ /**
2270
+ * Allow partial updates without strict validation.
2271
+ * Format validation still applies to provided values.
2272
+ * @default false
2273
+ */
2274
+ partial?: boolean;
2275
+ /**
2276
+ * Skip relation validation only.
2277
+ * @default false
2278
+ */
2279
+ skipRelationValidation?: boolean;
2280
+ }): Promise<ObjectRecord>;
2281
+ /**
2282
+ * Delete a record
2283
+ *
2284
+ * @param recordId - Record UUID
2285
+ * @param options - Delete options
2286
+ */
2287
+ deleteRecord(recordId: string, options?: {
2288
+ checkSystem?: boolean;
2289
+ }): Promise<void>;
2290
+ /**
2291
+ * List records for an object with pagination
2292
+ *
2293
+ * @param objectId - Object UUID
2294
+ * @param options - List options
2295
+ * @returns Records and total count
2296
+ */
2297
+ listRecords(objectId: string, options?: {
2298
+ limit?: number;
2299
+ offset?: number;
2300
+ orderBy?: string;
2301
+ orderDirection?: "asc" | "desc";
2302
+ }): Promise<{
2303
+ records: ObjectRecord[];
2304
+ total: number;
2305
+ }>;
2306
+ /**
2307
+ * Search records using full-text search
2308
+ *
2309
+ * @param objectId - Object UUID
2310
+ * @param query - Search query
2311
+ * @param options - Search options
2312
+ * @returns Matching records and total count
2313
+ */
2314
+ searchRecords(objectId: string, query: string, options?: {
2315
+ limit?: number;
2316
+ offset?: number;
2317
+ filters?: Record<string, unknown>;
2318
+ }): Promise<{
2319
+ records: ObjectRecord[];
2320
+ total: number;
2321
+ }>;
2322
+ /**
2323
+ * Validate data against object schema without saving
2324
+ *
2325
+ * @param objectId - Object UUID
2326
+ * @param data - Data to validate
2327
+ * @returns Validation result
2328
+ */
2329
+ validateData(objectId: string, data: Record<string, unknown>): Promise<ValidationResult>;
2330
+ /**
2331
+ * Compute the completion status for given data without saving.
2332
+ * Useful for UI to show draft/complete status before submitting.
2333
+ *
2334
+ * @param objectId - Object UUID
2335
+ * @param data - Data to check
2336
+ * @returns Computed completion status
2337
+ */
2338
+ computeStatus(objectId: string, data: Record<string, unknown>): Promise<CompletionStatus>;
2339
+ /**
2340
+ * Refresh the completion status of an existing record.
2341
+ * Useful when schema changes and you need to recompute statuses.
2342
+ *
2343
+ * @param recordId - Record UUID
2344
+ * @returns Updated completion status
2345
+ */
2346
+ refreshRecordStatus(recordId: string): Promise<CompletionStatus>;
2347
+ }
2348
+
2349
+ /**
2350
+ * Result of relation validation
2351
+ */
2352
+ interface RelationValidationResult {
2353
+ valid: boolean;
2354
+ errors: RelationValidationError[];
2355
+ }
2356
+ /**
2357
+ * Individual relation validation error
2358
+ */
2359
+ interface RelationValidationError {
2360
+ /** Attribute name */
2361
+ attribute: string;
2362
+ /** Error message */
2363
+ message: string;
2364
+ /** Invalid record IDs */
2365
+ invalidIds?: string[];
2366
+ }
2367
+ /**
2368
+ * Resolved relation option
2369
+ */
2370
+ interface RelationOption {
2371
+ /** Record ID */
2372
+ id: string;
2373
+ /** Object ID */
2374
+ objectId: string;
2375
+ /** Object name (technical name) */
2376
+ objectName: string;
2377
+ /** Object label (display name) */
2378
+ objectLabel: string;
2379
+ /** Object icon */
2380
+ objectIcon?: string;
2381
+ /** Display label (computed from labelExpression) */
2382
+ label: string;
2383
+ /** Additional record data */
2384
+ data?: Record<string, unknown>;
2385
+ }
2386
+ /**
2387
+ * Response for relation options
2388
+ */
2389
+ interface RelationOptionsResponse {
2390
+ options: RelationOption[];
2391
+ hasMore: boolean;
2392
+ total: number;
2393
+ }
2394
+ /**
2395
+ * Parameters for fetching relation options
2396
+ */
2397
+ interface GetRelationOptionsParams {
2398
+ /** Search query */
2399
+ query?: string;
2400
+ /** Page number (1-based) */
2401
+ page?: number;
2402
+ /** Page size */
2403
+ pageSize?: number;
2404
+ /** Filter by specific target object */
2405
+ targetObject?: string;
2406
+ }
2407
+ /**
2408
+ * Service for validating relation attributes
2409
+ * Ensures referenced records exist and belong to valid target objects
2410
+ */
2411
+ declare class RelationService {
2412
+ private adapter;
2413
+ private schemaService;
2414
+ constructor(adapter: DatabaseAdapter, nativeRegistry: typeof registry);
2415
+ /**
2416
+ * Validate all relation attributes in the data
2417
+ *
2418
+ * @param schema - Object schema containing attribute definitions
2419
+ * @param data - Record data to validate
2420
+ * @returns Validation result with errors if any
2421
+ *
2422
+ * @example
2423
+ * ```typescript
2424
+ * const result = await relationService.validateRelations(schema, {
2425
+ * company: "rec-123",
2426
+ * contacts: ["rec-456", "rec-789"]
2427
+ * });
2428
+ *
2429
+ * if (!result.valid) {
2430
+ * console.log(result.errors);
2431
+ * // [{ attribute: "company", message: "Record not found", invalidIds: ["rec-123"] }]
2432
+ * }
2433
+ * ```
2434
+ */
2435
+ validateRelations(schema: ObjectDefinition, data: Record<string, unknown>): Promise<RelationValidationResult>;
2436
+ /**
2437
+ * Validate a single relation attribute value
2438
+ */
2439
+ private validateRelationAttribute;
2440
+ /**
2441
+ * Extract IDs from relation value based on cardinality
2442
+ */
2443
+ private extractIds;
2444
+ /**
2445
+ * Get valid object IDs from relation targets
2446
+ */
2447
+ private getValidObjectIds;
2448
+ /**
2449
+ * Validate relations and throw if invalid
2450
+ */
2451
+ validateRelationsOrThrow(schema: ObjectDefinition, data: Record<string, unknown>): Promise<void>;
2452
+ /**
2453
+ * Get available options for a relation attribute
2454
+ * Searches across all target objects defined in the relation
2455
+ *
2456
+ * @param attribute - Relation attribute definition
2457
+ * @param tenantId - Tenant ID for multi-tenant isolation
2458
+ * @param params - Query parameters
2459
+ *
2460
+ * @example
2461
+ * ```typescript
2462
+ * const options = await relationService.getOptions(attribute, "tenant-1", {
2463
+ * query: "nike",
2464
+ * page: 1,
2465
+ * pageSize: 20
2466
+ * });
2467
+ * ```
2468
+ */
2469
+ getOptions(attribute: RelationAttribute, tenantId: string, params?: GetRelationOptionsParams): Promise<RelationOptionsResponse>;
2470
+ /**
2471
+ * Resolve record IDs to their display labels
2472
+ * Useful for displaying current values in the UI
2473
+ *
2474
+ * @param ids - Record IDs to resolve
2475
+ * @param tenantId - Tenant ID for multi-tenant isolation
2476
+ *
2477
+ * @example
2478
+ * ```typescript
2479
+ * const resolved = await relationService.resolveIds(["rec-1", "rec-2"], "tenant-1");
2480
+ * // [{ id: "rec-1", label: "Nike Air Max", objectName: "products", ... }]
2481
+ * ```
2482
+ */
2483
+ resolveIds(ids: string[], tenantId: string): Promise<RelationOption[]>;
2484
+ /**
2485
+ * Find a relation attribute by ID
2486
+ */
2487
+ findAttributeById(attributeId: string): Promise<RelationAttribute | null>;
2488
+ }
2489
+
2490
+ /**
2491
+ * Service for managing user profiles
2492
+ * Handles user profile CRUD, auth provider sync, and role management
2493
+ */
2494
+ declare class UserProfileService {
2495
+ private adapter;
2496
+ private tenantId;
2497
+ constructor(adapter: DatabaseAdapter, tenantId: string);
2498
+ /**
2499
+ * Create a new user profile (typically after first auth)
2500
+ *
2501
+ * @param data - User profile creation data
2502
+ * @returns Created user profile
2503
+ *
2504
+ * @example
2505
+ * ```typescript
2506
+ * const service = new UserProfileService(adapter, "tenant-123");
2507
+ *
2508
+ * // After Supabase auth
2509
+ * const profile = await service.createProfile({
2510
+ * tenantId: "tenant-123",
2511
+ * authId: authUser.id,
2512
+ * email: authUser.email,
2513
+ * firstName: authUser.user_metadata.first_name,
2514
+ * lastName: authUser.user_metadata.last_name,
2515
+ * role: "member",
2516
+ * status: "active"
2517
+ * });
2518
+ * ```
2519
+ */
2520
+ createProfile(data: CreateUserProfile): Promise<UserProfile>;
2521
+ /**
2522
+ * Get user profile by ID
2523
+ */
2524
+ getProfile(profileId: string): Promise<UserProfile | null>;
2525
+ /**
2526
+ * Get user profile by ID or throw
2527
+ */
2528
+ getProfileOrThrow(profileId: string): Promise<UserProfile>;
2529
+ /**
2530
+ * Get user profile by auth provider ID
2531
+ *
2532
+ * @param authId - Auth provider user ID (Supabase, Clerk, etc.)
2533
+ * @returns User profile or null
2534
+ */
2535
+ getProfileByAuthId(authId: string): Promise<UserProfile | null>;
2536
+ /**
2537
+ * Get or create user profile (idempotent operation)
2538
+ * Useful for auth callbacks - ensures profile exists
2539
+ *
2540
+ * @param authId - Auth provider user ID
2541
+ * @param data - Profile data to create if doesn't exist
2542
+ * @returns Existing or newly created profile
2543
+ *
2544
+ * @example
2545
+ * ```typescript
2546
+ * // In Supabase auth callback
2547
+ * const profile = await service.getOrCreateProfile(
2548
+ * authUser.id,
2549
+ * {
2550
+ * tenantId: "tenant-123",
2551
+ * authId: authUser.id,
2552
+ * email: authUser.email,
2553
+ * role: "member",
2554
+ * status: "active"
2555
+ * }
2556
+ * );
2557
+ * ```
2558
+ */
2559
+ getOrCreateProfile(authId: string, data: CreateUserProfile): Promise<UserProfile>;
2560
+ /**
2561
+ * Update user profile
2562
+ */
2563
+ updateProfile(profileId: string, data: UpdateUserProfile): Promise<UserProfile>;
2564
+ /**
2565
+ * Delete user profile
2566
+ *
2567
+ * @param profileId - Profile UUID
2568
+ * @param options - Delete options
2569
+ */
2570
+ deleteProfile(profileId: string, options?: {
2571
+ checkAdmin?: boolean;
2572
+ }): Promise<void>;
2573
+ /**
2574
+ * List all user profiles for the tenant
2575
+ */
2576
+ listProfiles(options?: ListOptions): Promise<UserProfile[]>;
2577
+ /**
2578
+ * Update last login timestamp
2579
+ *
2580
+ * @param profileId - Profile UUID
2581
+ *
2582
+ * @example
2583
+ * ```typescript
2584
+ * // After successful auth
2585
+ * await service.updateLastLogin(profile.id);
2586
+ * ```
2587
+ */
2588
+ updateLastLogin(profileId: string): Promise<void>;
2589
+ /**
2590
+ * Change user role
2591
+ *
2592
+ * @param profileId - Profile UUID
2593
+ * @param newRole - New role
2594
+ */
2595
+ changeRole(profileId: string, newRole: string): Promise<UserProfile>;
2596
+ /**
2597
+ * Change user status
2598
+ *
2599
+ * @param profileId - Profile UUID
2600
+ * @param newStatus - New status
2601
+ */
2602
+ changeStatus(profileId: string, newStatus: "active" | "pending" | "inactive" | "suspended"): Promise<UserProfile>;
2603
+ /**
2604
+ * Get user by email
2605
+ */
2606
+ getProfileByEmail(email: string): Promise<UserProfile | null>;
2607
+ /**
2608
+ * Check if user has role
2609
+ */
2610
+ hasRole(profileId: string, role: string): Promise<boolean>;
2611
+ /**
2612
+ * Check if user is admin
2613
+ */
2614
+ isAdmin(profileId: string): Promise<boolean>;
2615
+ }
2616
+
2617
+ /**
2618
+ * Input for creating a custom view
2619
+ */
2620
+ interface CreateViewInput {
2621
+ name: string;
2622
+ label: string;
2623
+ objectName: string;
2624
+ description?: string;
2625
+ icon?: IconName;
2626
+ tabs: Tab[];
2627
+ default?: boolean;
2628
+ metadata?: Record<string, unknown>;
2629
+ }
2630
+ /**
2631
+ * Input for updating a view
2632
+ */
2633
+ interface UpdateViewInput {
2634
+ label?: string;
2635
+ description?: string;
2636
+ icon?: IconName;
2637
+ tabs?: Tab[];
2638
+ default?: boolean;
2639
+ metadata?: Record<string, unknown>;
2640
+ }
2641
+ /**
2642
+ * Service for managing views
2643
+ * Handles fusion of native views (from registry) and custom views (from database)
2644
+ */
2645
+ declare class ViewService {
2646
+ private adapter;
2647
+ private nativeViews;
2648
+ constructor(adapter: DatabaseAdapter, nativeViews: typeof viewRegistry);
2649
+ /**
2650
+ * Get all views for an object (native + custom)
2651
+ *
2652
+ * @param objectName - Object name
2653
+ * @param tenantId - Tenant ID
2654
+ * @returns All views for the object
2655
+ */
2656
+ getViewsForObject(objectName: string, tenantId: string): Promise<ViewDefinition[]>;
2657
+ /**
2658
+ * Get a specific view by name
2659
+ *
2660
+ * @param objectName - Object name
2661
+ * @param viewName - View name
2662
+ * @param tenantId - Tenant ID
2663
+ * @returns View definition or null
2664
+ */
2665
+ getView(objectName: string, viewName: string, tenantId: string): Promise<ViewDefinition | null>;
2666
+ /**
2667
+ * Get the default view for an object
2668
+ *
2669
+ * Priority:
2670
+ * 1. Custom view marked as default
2671
+ * 2. Native view marked as default
2672
+ * 3. First available view
2673
+ *
2674
+ * @param objectName - Object name
2675
+ * @param tenantId - Tenant ID
2676
+ * @returns Default view or null
2677
+ */
2678
+ getDefaultView(objectName: string, tenantId: string): Promise<ViewDefinition | null>;
2679
+ /**
2680
+ * Create a custom view
2681
+ *
2682
+ * @param input - View definition
2683
+ * @param tenantId - Tenant ID
2684
+ * @returns Created view
2685
+ */
2686
+ createView(input: CreateViewInput, tenantId: string): Promise<ViewDefinition>;
2687
+ /**
2688
+ * Update a custom view
2689
+ *
2690
+ * @param viewId - View ID
2691
+ * @param input - Update data
2692
+ * @returns Updated view
2693
+ */
2694
+ updateView(viewId: string, input: UpdateViewInput): Promise<ViewDefinition>;
2695
+ /**
2696
+ * Delete a custom view
2697
+ *
2698
+ * @param viewId - View ID
2699
+ */
2700
+ deleteView(viewId: string): Promise<void>;
2701
+ /**
2702
+ * Set a view as default for its object
2703
+ *
2704
+ * @param viewId - View ID
2705
+ * @param tenantId - Tenant ID
2706
+ * @returns Updated view
2707
+ */
2708
+ setDefaultView(viewId: string, tenantId: string): Promise<ViewDefinition>;
2709
+ /**
2710
+ * Validate view name format (kebab-case)
2711
+ */
2712
+ private validateViewName;
2713
+ /**
2714
+ * Convert database view to ViewDefinition
2715
+ */
2716
+ private convertDBViewToDefinition;
2717
+ }
2718
+
2719
+ /**
2720
+ * Result of view sync operation
2721
+ */
2722
+ interface ViewSyncResult {
2723
+ success: boolean;
2724
+ viewsSynced: number;
2725
+ viewsCreated: number;
2726
+ viewsUpdated: number;
2727
+ viewsDeleted: number;
2728
+ errors: Array<{
2729
+ viewName: string;
2730
+ objectName: string;
2731
+ error: string;
2732
+ }>;
2733
+ }
2734
+ /**
2735
+ * Options for view sync
2736
+ */
2737
+ interface ViewSyncOptions {
2738
+ dryRun?: boolean;
2739
+ verbose?: boolean;
2740
+ tenantId?: string;
2741
+ }
2742
+ /**
2743
+ * Sync native views from registry to database
2744
+ *
2745
+ * This function:
2746
+ * 1. Reads all registered native views from the registry
2747
+ * 2. Upserts them into the database (views table)
2748
+ * 3. Marks them as system=true for protection
2749
+ * 4. Removes views that were deleted from code
2750
+ *
2751
+ * @param adapter - Database adapter implementing DatabaseAdapter interface
2752
+ * @param nativeViewRegistry - Registry containing native views
2753
+ * @param options - Sync options (dryRun, verbose, tenantId)
2754
+ * @returns Sync result with statistics
2755
+ *
2756
+ * @example
2757
+ * ```typescript
2758
+ * import { syncNativeViews, viewRegistry } from "@stndrds/schema";
2759
+ * import { drizzleAdapter } from "./db/adapter";
2760
+ *
2761
+ * const result = await syncNativeViews(drizzleAdapter, viewRegistry, {
2762
+ * verbose: true,
2763
+ * tenantId: "default"
2764
+ * });
2765
+ *
2766
+ * if (result.success) {
2767
+ * console.log(`✓ Synced ${result.viewsSynced} views`);
2768
+ * }
2769
+ * ```
2770
+ */
2771
+ declare function syncNativeViews(adapter: DatabaseAdapter, nativeViewRegistry: typeof viewRegistry, options?: ViewSyncOptions): Promise<ViewSyncResult>;
2772
+ /**
2773
+ * Verify that all native views are synced to database
2774
+ *
2775
+ * @param adapter - Database adapter
2776
+ * @param nativeViewRegistry - Registry containing native views
2777
+ * @returns true if all views are synced, false otherwise
2778
+ *
2779
+ * @example
2780
+ * ```typescript
2781
+ * const isSynced = await verifyNativeViewsSync(adapter, viewRegistry);
2782
+ * if (!isSynced) {
2783
+ * console.warn("Native views not synced, running sync...");
2784
+ * await syncNativeViews(adapter, viewRegistry);
2785
+ * }
2786
+ * ```
2787
+ */
2788
+ declare function verifyNativeViewsSync(adapter: DatabaseAdapter, nativeViewRegistry: typeof viewRegistry): Promise<boolean>;
2789
+ /**
2790
+ * Get sync preview without modifying database
2791
+ *
2792
+ * @param adapter - Database adapter
2793
+ * @param nativeViewRegistry - Registry containing native views
2794
+ * @returns Sync result (dry run)
2795
+ */
2796
+ declare function getViewSyncPreview(adapter: DatabaseAdapter, nativeViewRegistry: typeof viewRegistry): Promise<ViewSyncResult>;
2797
+
2798
+ /**
2799
+ * Result of sync operation
2800
+ */
2801
+ interface SyncResult {
2802
+ success: boolean;
2803
+ objectsSynced: number;
2804
+ attributesSynced: number;
2805
+ objectsCreated: number;
2806
+ objectsUpdated: number;
2807
+ attributesCreated: number;
2808
+ attributesUpdated: number;
2809
+ attributesDeleted: number;
2810
+ errors: Array<{
2811
+ objectName: string;
2812
+ error: string;
2813
+ }>;
2814
+ }
2815
+ /**
2816
+ * Sync options
2817
+ */
2818
+ interface SyncOptions {
2819
+ dryRun?: boolean;
2820
+ verbose?: boolean;
2821
+ tenantId?: string;
2822
+ }
2823
+ /**
2824
+ * Sync native objects from registry to database
2825
+ *
2826
+ * This function:
2827
+ * 1. Reads all registered native objects from the registry
2828
+ * 2. Upserts them into the database (objects + attributes tables)
2829
+ * 3. Marks them as system=true for protection
2830
+ * 4. Removes attributes that were deleted from code
2831
+ *
2832
+ * @param adapter - Database adapter implementing DatabaseAdapter interface
2833
+ * @param nativeRegistry - Registry containing native objects
2834
+ * @param options - Sync options (dryRun, verbose, tenantId)
2835
+ * @returns Sync result with statistics
2836
+ *
2837
+ * @example
2838
+ * ```typescript
2839
+ * import { syncNativeObjects } from "@stndrds/schema/runtime";
2840
+ * import { registry } from "./objects/native";
2841
+ * import { drizzleAdapter } from "./db/adapter";
2842
+ *
2843
+ * const result = await syncNativeObjects(drizzleAdapter, registry, {
2844
+ * verbose: true,
2845
+ * tenantId: "default"
2846
+ * });
2847
+ *
2848
+ * if (result.success) {
2849
+ * console.log(`✓ Synced ${result.objectsSynced} objects`);
2850
+ * } else {
2851
+ * console.error("Sync errors:", result.errors);
2852
+ * }
2853
+ * ```
2854
+ */
2855
+ declare function syncNativeObjects(adapter: DatabaseAdapter, nativeRegistry: typeof registry, options?: SyncOptions): Promise<SyncResult>;
2856
+ /**
2857
+ * Verify that all native objects are synced to database
2858
+ *
2859
+ * @param adapter - Database adapter
2860
+ * @param nativeRegistry - Registry containing native objects
2861
+ * @returns true if all objects are synced, false otherwise
2862
+ *
2863
+ * @example
2864
+ * ```typescript
2865
+ * const isSynced = await verifyNativeObjectsSync(adapter, registry);
2866
+ * if (!isSynced) {
2867
+ * console.warn("Native objects not synced, running sync...");
2868
+ * await syncNativeObjects(adapter, registry);
2869
+ * }
2870
+ * ```
2871
+ */
2872
+ declare function verifyNativeObjectsSync(adapter: DatabaseAdapter, nativeRegistry: typeof registry): Promise<boolean>;
2873
+ /**
2874
+ * Get sync statistics without modifying database
2875
+ *
2876
+ * @param adapter - Database adapter
2877
+ * @param nativeRegistry - Registry containing native objects
2878
+ * @returns Sync result (dry run)
2879
+ */
2880
+ declare function getSyncPreview(adapter: DatabaseAdapter, nativeRegistry: typeof registry): Promise<SyncResult>;
2881
+ /**
2882
+ * Result of full sync operation (objects + views)
2883
+ */
2884
+ interface FullSyncResult {
2885
+ success: boolean;
2886
+ objects: SyncResult;
2887
+ views: ViewSyncResult;
2888
+ }
2889
+ /**
2890
+ * Options for full sync
2891
+ */
2892
+ interface FullSyncOptions extends SyncOptions, ViewSyncOptions {
2893
+ }
2894
+ /**
2895
+ * Sync all native objects and views from registries to database
2896
+ *
2897
+ * This is a convenience function that:
2898
+ * 1. Syncs native objects first (views may depend on objects)
2899
+ * 2. Syncs native views
2900
+ *
2901
+ * @param adapter - Database adapter
2902
+ * @param objectRegistry - Registry containing native objects
2903
+ * @param nativeViewRegistry - Registry containing native views
2904
+ * @param options - Sync options
2905
+ * @returns Combined sync result
2906
+ *
2907
+ * @example
2908
+ * ```typescript
2909
+ * import { syncAll, registry, viewRegistry } from "@stndrds/schema";
2910
+ * import { adapter } from "./db";
2911
+ *
2912
+ * const result = await syncAll(adapter, registry, viewRegistry, {
2913
+ * verbose: true,
2914
+ * tenantId: "default"
2915
+ * });
2916
+ *
2917
+ * if (result.success) {
2918
+ * console.log(`✓ Synced ${result.objects.objectsSynced} objects, ${result.views.viewsSynced} views`);
2919
+ * }
2920
+ * ```
2921
+ */
2922
+ declare function syncAll(adapter: DatabaseAdapter, objectRegistry: typeof registry, nativeViewRegistry: typeof viewRegistry, options?: FullSyncOptions): Promise<FullSyncResult>;
2923
+
2924
+ /**
2925
+ * Default fallback value when expression resolves to empty string
2926
+ */
2927
+ declare const DEFAULT_LABEL_FALLBACK = "(Untitled)";
2928
+ /**
2929
+ * Render a label expression template with values
2930
+ *
2931
+ * Supports:
2932
+ * - Variable interpolation: `{{ fieldName }}`
2933
+ * - Dot notation: `{{ user.firstName }}`
2934
+ * - Pipes: `{{ name | UPPER }}`, `{{ name | capitalize | trim }}`
2935
+ *
2936
+ * @param template - The label expression template (e.g., "{{ firstName }} {{ lastName }}")
2937
+ * @param values - Record values to interpolate
2938
+ * @param fallback - Fallback value if result is empty (default: "(Untitled)")
2939
+ * @returns The rendered label string
2940
+ *
2941
+ * @example
2942
+ * ```typescript
2943
+ * const label = renderLabelExpression(
2944
+ * "{{ firstName }} {{ lastName | UPPER }}",
2945
+ * { firstName: "John", lastName: "Doe" }
2946
+ * );
2947
+ * // → "John DOE"
2948
+ *
2949
+ * // With missing values
2950
+ * const label = renderLabelExpression(
2951
+ * "{{ name }}",
2952
+ * { }
2953
+ * );
2954
+ * // → "(Untitled)"
2955
+ * ```
2956
+ */
2957
+ declare function renderLabelExpression(template: string, values: Record<string, unknown>, fallback?: string): string;
2958
+ /**
2959
+ * Check if a string is a valid label expression template
2960
+ * A valid template contains at least one {{ variable }} block with a non-empty variable
2961
+ */
2962
+ declare function isLabelExpression(value: string): boolean;
2963
+ /**
2964
+ * Extract attribute names referenced in a label expression
2965
+ * Useful for validation or dependency tracking
2966
+ *
2967
+ * @example
2968
+ * extractAttributeNames("{{ firstName }} {{ lastName | UPPER }}")
2969
+ * // → ["firstName", "lastName"]
2970
+ */
2971
+ declare function extractAttributeNames(template: string): string[];
2972
+
2973
+ export { type Timestamps as $, type Attribute as A, type BaseAttribute as B, type Currency as C, type DateAttribute as D, type StorageProvider as E, type FileAttribute as F, type Group as G, type FileVisibility as H, type File as I, type CreateFile as J, type UpdateFile as K, type Location as L, type MultiselectAttribute as M, type NumberAttribute as N, type Option as O, type Phone as P, type GeocodingSuggestion as Q, type RelationOnDelete as R, type StatusAttribute as S, type TextAttribute as T, type UserAttribute as U, type ViewDefinition as V, type GeocodingAutocompleteParams as W, type ReverseGeocodingParams as X, type GeocodingParams as Y, type GeocodingAdapter as Z, NoopGeocodingAdapter as _, type SelectAttribute as a, ObjectSchemaService as a$, type ObjectAttribute as a0, type CompletionStatus as a1, type ObjectRecord as a2, type UserRole as a3, type UserStatus as a4, type UserProfile as a5, type CreateUserProfile as a6, type UpdateUserProfile as a7, type TabType as a8, type FormTab as a9, createRelationValidator as aA, createRatingValidator as aB, createAttributeValidator as aC, createObjectValidator as aD, type ValidationResult as aE, validateAttribute as aF, validateObject as aG, validateObjectOrThrow as aH, createDraftValidator as aI, validateDraft as aJ, validateDraftOrThrow as aK, getMissingRequiredAttributes as aL, isRecordComplete as aM, computeRecordStatus as aN, type DatabaseAdapter as aO, createMockAdapter as aP, type ObjectsRepository as aQ, type AttributesRepository as aR, type UserProfilesRepository as aS, type FilesRepository as aT, type ObjectRecordsRepository as aU, type ViewsRepository as aV, FileService as aW, GeocodingService as aX, GlobalSearchService as aY, type CreateCustomObjectInput as aZ, type AddAttributeInput as a_, type TableTab as aa, type CustomTab as ab, isFormTab as ac, isTableTab as ad, isCustomTab as ae, type Uuid as af, type TenantId as ag, generateId as ah, generatePrefixedId as ai, registry as aj, viewRegistry as ak, createTextValidator as al, createNumberValidator as am, createCheckboxValidator as an, createDateValidator as ao, createPhoneValidator as ap, createCurrencyValidator as aq, createStatusValidator as ar, createSelectValidator as as, createMultiselectValidator as at, createLocationValidator as au, createTimestampValidator as av, createFileValidator as aw, createUserValidator as ax, createSingleRelationValidator as ay, createMultiRelationValidator as az, type TextAreaAttribute as b, RecordService as b0, type RelationValidationResult as b1, type RelationValidationError as b2, type RelationOption as b3, type RelationOptionsResponse as b4, type GetRelationOptionsParams as b5, RelationService as b6, UserProfileService as b7, type CreateViewInput as b8, type UpdateViewInput as b9, type FileListOptions as bA, type DBView as bB, type CreateDBView as bC, type UpdateDBView as bD, type UpsertDBView as bE, type OperationResult as bF, type ViewSyncResult as bG, type ViewSyncOptions as bH, syncNativeViews as bI, verifyNativeViewsSync as bJ, getViewSyncPreview as bK, ViewService as ba, type SyncResult as bb, type SyncOptions as bc, syncNativeObjects as bd, verifyNativeObjectsSync as be, getSyncPreview as bf, type FullSyncResult as bg, type FullSyncOptions as bh, syncAll as bi, DEFAULT_LABEL_FALLBACK as bj, renderLabelExpression as bk, isLabelExpression as bl, extractAttributeNames as bm, type DBObject as bn, type CreateDBObject as bo, type UpdateDBObject as bp, type UpsertDBObject as bq, type DBAttribute as br, type CreateDBAttribute as bs, type UpdateDBAttribute as bt, type UpsertDBAttribute as bu, type CreateObjectRecord as bv, type ListOptions as bw, type SearchOptions as bx, type GlobalSearchOptions as by, type GlobalSearchResultItem as bz, type CheckboxAttribute as c, type PhoneAttribute as d, type CurrencyAttribute as e, type LocationAttribute as f, type TimestampAttribute as g, type SingleRelationAttribute as h, type MultiRelationAttribute as i, type RelationTarget as j, type RatingAttribute as k, type ObjectDefinition as l, type Field as m, type Tab as n, type AttributeType as o, type StatusGroup as p, type AttributeGroup as q, type NumberUnit as r, type DateFormat as s, type DateValue as t, type LocationGranularity as u, type DocumentType as v, type DocumentFace as w, type DocumentTypeConfig as x, type FileVerificationConfig as y, type RelationAttribute as z };