@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,4726 @@
1
+ // src/runtime/hooks/hook.registry.ts
2
+ var NoopHookRegistry = class {
3
+ async execute() {
4
+ }
5
+ };
6
+
7
+ // src/utils.ts
8
+ function generateId() {
9
+ if (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function") {
10
+ return crypto.randomUUID();
11
+ }
12
+ return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => {
13
+ const r = Math.random() * 16 | 0;
14
+ const v = c === "x" ? r : r & 3 | 8;
15
+ return v.toString(16);
16
+ });
17
+ }
18
+ function generatePrefixedId(prefix) {
19
+ return `${prefix}_${generateId()}`;
20
+ }
21
+
22
+ // src/runtime/template.ts
23
+ var pipes = {
24
+ /** Convert to uppercase */
25
+ UPPER: (v) => String(v).toUpperCase(),
26
+ /** Convert to lowercase */
27
+ LOWER: (v) => String(v).toLowerCase(),
28
+ /** Capitalize first letter of each word */
29
+ capitalize: (v) => String(v).replace(/\b\w/g, (c) => c.toUpperCase()),
30
+ /** Trim whitespace from both ends */
31
+ trim: (v) => String(v).trim()
32
+ };
33
+ function getValue(obj, path) {
34
+ return path.split(".").reduce((acc, key) => {
35
+ if (acc == null || typeof acc !== "object") return void 0;
36
+ return acc[key];
37
+ }, obj);
38
+ }
39
+ var DEFAULT_LABEL_FALLBACK = "(Untitled)";
40
+ function renderLabelExpression(template, values, fallback = DEFAULT_LABEL_FALLBACK) {
41
+ const result = template.replace(/\{\{\s*([^}]+)\s*\}\}/g, (_, expr) => {
42
+ const parts = expr.split("|").map((s) => s.trim());
43
+ const path = parts[0];
44
+ let value = getValue(values, path);
45
+ if (value == null || value === "") return "";
46
+ for (let i = 1; i < parts.length; i++) {
47
+ const pipeName = parts[i].trim();
48
+ const fn = pipes[pipeName];
49
+ if (fn) {
50
+ value = fn(String(value));
51
+ }
52
+ }
53
+ return String(value);
54
+ }).trim();
55
+ return result || fallback;
56
+ }
57
+ function isLabelExpression(value) {
58
+ return /\{\{\s*\S+.*\}\}/.test(value);
59
+ }
60
+ function extractAttributeNames(template) {
61
+ const names = [];
62
+ const regex = /\{\{\s*([^|}]+)/g;
63
+ let match;
64
+ while ((match = regex.exec(template)) !== null) {
65
+ const path = match[1].trim();
66
+ const rootName = path.split(".")[0];
67
+ if (rootName && !names.includes(rootName)) {
68
+ names.push(rootName);
69
+ }
70
+ }
71
+ return names;
72
+ }
73
+
74
+ // src/runtime/mock-adapter.ts
75
+ function createMockObjectsRepository(stores) {
76
+ return {
77
+ findById(id) {
78
+ return Promise.resolve(stores.objects.get(id) ?? null);
79
+ },
80
+ findByName(tenantId, name) {
81
+ for (const obj of stores.objects.values()) {
82
+ if (obj.tenantId === tenantId && obj.name === name) {
83
+ return Promise.resolve(obj);
84
+ }
85
+ }
86
+ return Promise.resolve(null);
87
+ },
88
+ findSystemByName(name) {
89
+ for (const obj of stores.objects.values()) {
90
+ if (obj.system && obj.name === name) {
91
+ return Promise.resolve(obj);
92
+ }
93
+ }
94
+ return Promise.resolve(null);
95
+ },
96
+ create(data) {
97
+ const obj = {
98
+ id: generateId(),
99
+ tenantId: data.tenantId,
100
+ name: data.name,
101
+ label: data.label,
102
+ pluralLabel: data.pluralLabel,
103
+ description: data.description,
104
+ icon: data.icon,
105
+ labelExpression: data.labelExpression,
106
+ system: data.system ?? false,
107
+ metadata: data.metadata,
108
+ createdAt: /* @__PURE__ */ new Date(),
109
+ updatedAt: /* @__PURE__ */ new Date()
110
+ };
111
+ stores.objects.set(obj.id, obj);
112
+ return Promise.resolve(obj);
113
+ },
114
+ update(id, data) {
115
+ const existing = stores.objects.get(id);
116
+ if (!existing) {
117
+ return Promise.reject(new Error(`Object ${id} not found`));
118
+ }
119
+ const updated = {
120
+ ...existing,
121
+ ...data,
122
+ updatedAt: /* @__PURE__ */ new Date()
123
+ };
124
+ stores.objects.set(id, updated);
125
+ return Promise.resolve(updated);
126
+ },
127
+ delete(id) {
128
+ stores.objects.delete(id);
129
+ return Promise.resolve();
130
+ },
131
+ list(tenantId) {
132
+ const results = Array.from(stores.objects.values()).filter(
133
+ (obj) => obj.tenantId === tenantId
134
+ );
135
+ return Promise.resolve(results);
136
+ },
137
+ upsert(data) {
138
+ for (const obj of stores.objects.values()) {
139
+ if (obj.system && obj.name === data.name) {
140
+ const updated = {
141
+ ...obj,
142
+ label: data.label,
143
+ pluralLabel: data.pluralLabel,
144
+ description: data.description,
145
+ icon: data.icon,
146
+ metadata: data.metadata,
147
+ updatedAt: /* @__PURE__ */ new Date()
148
+ };
149
+ stores.objects.set(obj.id, updated);
150
+ return Promise.resolve(updated);
151
+ }
152
+ }
153
+ const newObj = {
154
+ id: generateId(),
155
+ tenantId: data.tenantId,
156
+ name: data.name,
157
+ label: data.label,
158
+ pluralLabel: data.pluralLabel,
159
+ description: data.description,
160
+ icon: data.icon,
161
+ labelExpression: data.labelExpression,
162
+ system: data.system,
163
+ metadata: data.metadata,
164
+ createdAt: /* @__PURE__ */ new Date(),
165
+ updatedAt: /* @__PURE__ */ new Date()
166
+ };
167
+ stores.objects.set(newObj.id, newObj);
168
+ return Promise.resolve(newObj);
169
+ }
170
+ };
171
+ }
172
+ function createMockAttributesRepository(stores) {
173
+ return {
174
+ findById(id) {
175
+ return Promise.resolve(stores.attributes.get(id) ?? null);
176
+ },
177
+ findByObjectId(objectId) {
178
+ const results = Array.from(stores.attributes.values()).filter(
179
+ (attr) => attr.objectId === objectId
180
+ );
181
+ return Promise.resolve(results);
182
+ },
183
+ create(data) {
184
+ const attr = {
185
+ id: generateId(),
186
+ objectId: data.objectId,
187
+ name: data.name,
188
+ label: data.label,
189
+ type: data.type,
190
+ description: data.description,
191
+ icon: data.icon,
192
+ system: data.system ?? false,
193
+ required: data.required ?? false,
194
+ unique: data.unique ?? false,
195
+ order: data.order ?? 0,
196
+ hidden: data.hidden,
197
+ archived: data.archived,
198
+ deprecated: data.deprecated,
199
+ defaultValue: data.defaultValue,
200
+ config: data.config ?? {},
201
+ createdAt: /* @__PURE__ */ new Date(),
202
+ updatedAt: /* @__PURE__ */ new Date()
203
+ };
204
+ stores.attributes.set(attr.id, attr);
205
+ return Promise.resolve(attr);
206
+ },
207
+ update(id, data) {
208
+ const existing = stores.attributes.get(id);
209
+ if (!existing) {
210
+ return Promise.reject(new Error(`Attribute ${id} not found`));
211
+ }
212
+ const updated = {
213
+ ...existing,
214
+ ...data,
215
+ updatedAt: /* @__PURE__ */ new Date()
216
+ };
217
+ stores.attributes.set(id, updated);
218
+ return Promise.resolve(updated);
219
+ },
220
+ delete(id) {
221
+ stores.attributes.delete(id);
222
+ return Promise.resolve();
223
+ },
224
+ deleteByNames(objectId, excludeNames) {
225
+ let count = 0;
226
+ for (const [id, attr] of stores.attributes.entries()) {
227
+ if (attr.objectId === objectId && !excludeNames.includes(attr.name)) {
228
+ stores.attributes.delete(id);
229
+ count++;
230
+ }
231
+ }
232
+ return Promise.resolve(count);
233
+ },
234
+ upsert(data) {
235
+ for (const attr of stores.attributes.values()) {
236
+ if (attr.objectId === data.objectId && attr.name === data.name) {
237
+ const updated = {
238
+ ...attr,
239
+ label: data.label ?? attr.label,
240
+ type: data.type ?? attr.type,
241
+ description: data.description ?? attr.description,
242
+ icon: data.icon ?? attr.icon,
243
+ system: data.system ?? attr.system,
244
+ required: data.required ?? attr.required,
245
+ unique: data.unique ?? attr.unique,
246
+ order: data.order ?? attr.order,
247
+ hidden: data.hidden ?? attr.hidden,
248
+ archived: data.archived ?? attr.archived,
249
+ deprecated: data.deprecated ?? attr.deprecated,
250
+ defaultValue: data.defaultValue ?? attr.defaultValue,
251
+ config: data.config ?? attr.config,
252
+ updatedAt: /* @__PURE__ */ new Date()
253
+ };
254
+ stores.attributes.set(attr.id, updated);
255
+ return Promise.resolve(updated);
256
+ }
257
+ }
258
+ return this.create(data);
259
+ }
260
+ };
261
+ }
262
+ function createMockUserProfilesRepository(stores) {
263
+ return {
264
+ findById(id) {
265
+ return Promise.resolve(stores.userProfiles.get(id) ?? null);
266
+ },
267
+ findByAuthId(authId) {
268
+ for (const profile of stores.userProfiles.values()) {
269
+ if (profile.authId === authId) {
270
+ return Promise.resolve(profile);
271
+ }
272
+ }
273
+ return Promise.resolve(null);
274
+ },
275
+ findByEmail(tenantId, email) {
276
+ for (const profile of stores.userProfiles.values()) {
277
+ if (profile.tenantId === tenantId && profile.email === email) {
278
+ return Promise.resolve(profile);
279
+ }
280
+ }
281
+ return Promise.resolve(null);
282
+ },
283
+ create(data) {
284
+ const profile = {
285
+ id: generateId(),
286
+ tenantId: data.tenantId,
287
+ authId: data.authId,
288
+ email: data.email,
289
+ firstName: data.firstName,
290
+ lastName: data.lastName,
291
+ avatarUrl: data.avatarUrl,
292
+ role: data.role ?? "member",
293
+ status: data.status ?? "active",
294
+ createdAt: /* @__PURE__ */ new Date(),
295
+ updatedAt: /* @__PURE__ */ new Date()
296
+ };
297
+ stores.userProfiles.set(profile.id, profile);
298
+ return Promise.resolve(profile);
299
+ },
300
+ update(id, data) {
301
+ const existing = stores.userProfiles.get(id);
302
+ if (!existing) {
303
+ return Promise.reject(new Error(`UserProfile ${id} not found`));
304
+ }
305
+ const updated = {
306
+ ...existing,
307
+ ...data,
308
+ updatedAt: /* @__PURE__ */ new Date()
309
+ };
310
+ stores.userProfiles.set(id, updated);
311
+ return Promise.resolve(updated);
312
+ },
313
+ delete(id) {
314
+ stores.userProfiles.delete(id);
315
+ return Promise.resolve();
316
+ },
317
+ list(tenantId, options) {
318
+ let results = Array.from(stores.userProfiles.values()).filter((p) => p.tenantId === tenantId);
319
+ if (options?.limit) {
320
+ results = results.slice(options.offset ?? 0, (options.offset ?? 0) + options.limit);
321
+ }
322
+ return Promise.resolve(results);
323
+ },
324
+ updateLastLogin(id) {
325
+ const profile = stores.userProfiles.get(id);
326
+ if (profile) {
327
+ profile.lastLoginAt = /* @__PURE__ */ new Date();
328
+ stores.userProfiles.set(id, profile);
329
+ }
330
+ return Promise.resolve();
331
+ }
332
+ };
333
+ }
334
+ function createMockFilesRepository(stores) {
335
+ return {
336
+ findById(id) {
337
+ const file2 = stores.files.get(id);
338
+ if (file2?.deletedAt) return Promise.resolve(null);
339
+ return Promise.resolve(file2 ?? null);
340
+ },
341
+ create(data) {
342
+ const file2 = {
343
+ id: generateId(),
344
+ tenantId: data.tenantId,
345
+ name: data.name,
346
+ originalName: data.originalName,
347
+ mimeType: data.mimeType,
348
+ size: data.size,
349
+ storageProvider: data.storageProvider,
350
+ storagePath: data.storagePath,
351
+ storageBucket: data.storageBucket,
352
+ url: data.url,
353
+ uploadedBy: data.uploadedBy,
354
+ folderPath: data.folderPath,
355
+ tags: data.tags,
356
+ visibility: data.visibility ?? "private",
357
+ allowedUsers: data.allowedUsers,
358
+ createdAt: /* @__PURE__ */ new Date(),
359
+ updatedAt: /* @__PURE__ */ new Date()
360
+ };
361
+ stores.files.set(file2.id, file2);
362
+ return Promise.resolve(file2);
363
+ },
364
+ update(id, data) {
365
+ const existing = stores.files.get(id);
366
+ if (!existing) {
367
+ return Promise.reject(new Error(`File ${id} not found`));
368
+ }
369
+ const updated = {
370
+ ...existing,
371
+ ...data,
372
+ updatedAt: /* @__PURE__ */ new Date()
373
+ };
374
+ stores.files.set(id, updated);
375
+ return Promise.resolve(updated);
376
+ },
377
+ delete(id) {
378
+ const file2 = stores.files.get(id);
379
+ if (file2) {
380
+ file2.deletedAt = /* @__PURE__ */ new Date();
381
+ stores.files.set(id, file2);
382
+ }
383
+ return Promise.resolve();
384
+ },
385
+ hardDelete(id) {
386
+ stores.files.delete(id);
387
+ return Promise.resolve();
388
+ },
389
+ list(tenantId, options) {
390
+ let results = Array.from(stores.files.values()).filter(
391
+ (f) => f.tenantId === tenantId && !f.deletedAt
392
+ );
393
+ if (options?.mimeType) {
394
+ results = results.filter((f) => f.mimeType === options.mimeType);
395
+ }
396
+ if (options?.limit) {
397
+ results = results.slice(options.offset ?? 0, (options.offset ?? 0) + options.limit);
398
+ }
399
+ return Promise.resolve(results);
400
+ },
401
+ findByFolder(tenantId, folderPath) {
402
+ const results = Array.from(stores.files.values()).filter(
403
+ (f) => f.tenantId === tenantId && f.folderPath === folderPath && !f.deletedAt
404
+ );
405
+ return Promise.resolve(results);
406
+ },
407
+ findByUploader(uploadedBy) {
408
+ const results = Array.from(stores.files.values()).filter(
409
+ (f) => f.uploadedBy === uploadedBy && !f.deletedAt
410
+ );
411
+ return Promise.resolve(results);
412
+ }
413
+ };
414
+ }
415
+ function createMockObjectRecordsRepository(stores) {
416
+ return {
417
+ findById(id) {
418
+ const internal = stores.objectRecords.get(id);
419
+ if (!internal) return Promise.resolve(null);
420
+ const { tenantId: _, ...record } = internal;
421
+ return Promise.resolve(record);
422
+ },
423
+ create(data) {
424
+ const internal = {
425
+ id: generateId(),
426
+ tenantId: data.tenantId,
427
+ objectId: data.objectId,
428
+ label: data.label,
429
+ completionStatus: data.completionStatus,
430
+ values: data.data,
431
+ createdAt: /* @__PURE__ */ new Date(),
432
+ updatedAt: /* @__PURE__ */ new Date()
433
+ };
434
+ stores.objectRecords.set(internal.id, internal);
435
+ const { tenantId: _, ...record } = internal;
436
+ return Promise.resolve(record);
437
+ },
438
+ update(id, data) {
439
+ const existing = stores.objectRecords.get(id);
440
+ if (!existing) {
441
+ return Promise.reject(new Error(`ObjectRecord ${id} not found`));
442
+ }
443
+ const { __completionStatus, __label, ...valueData } = data;
444
+ const updated = {
445
+ ...existing,
446
+ label: __label ?? existing.label,
447
+ completionStatus: __completionStatus ?? existing.completionStatus,
448
+ values: { ...existing.values, ...valueData },
449
+ updatedAt: /* @__PURE__ */ new Date()
450
+ };
451
+ stores.objectRecords.set(id, updated);
452
+ const { tenantId: _, ...record } = updated;
453
+ return Promise.resolve(record);
454
+ },
455
+ delete(id) {
456
+ stores.objectRecords.delete(id);
457
+ return Promise.resolve();
458
+ },
459
+ list(tenantId, objectId, options) {
460
+ let results = Array.from(stores.objectRecords.values()).filter(
461
+ (r) => r.tenantId === tenantId && r.objectId === objectId
462
+ );
463
+ const total = results.length;
464
+ if (options?.limit) {
465
+ results = results.slice(options.offset ?? 0, (options.offset ?? 0) + options.limit);
466
+ }
467
+ const records = results.map(({ tenantId: _, ...r }) => r);
468
+ return Promise.resolve({ records, total });
469
+ },
470
+ search(tenantId, objectId, query, options) {
471
+ const lowerQuery = query.toLowerCase();
472
+ let results = Array.from(stores.objectRecords.values()).filter((r) => {
473
+ if (r.tenantId !== tenantId || r.objectId !== objectId) return false;
474
+ return Object.values(r.values).some(
475
+ (val) => String(val).toLowerCase().includes(lowerQuery)
476
+ );
477
+ });
478
+ const total = results.length;
479
+ if (options?.limit) {
480
+ results = results.slice(options.offset ?? 0, (options.offset ?? 0) + options.limit);
481
+ }
482
+ const records = results.map(({ tenantId: _, ...r }) => r);
483
+ return Promise.resolve({ records, total });
484
+ },
485
+ globalSearch(tenantId, query, options) {
486
+ const lowerQuery = query.toLowerCase();
487
+ const objectsMap = /* @__PURE__ */ new Map();
488
+ for (const obj of stores.objects.values()) {
489
+ if (obj.tenantId === tenantId) {
490
+ objectsMap.set(obj.id, obj);
491
+ }
492
+ }
493
+ const allowedObjectIds = /* @__PURE__ */ new Set();
494
+ if (options?.objectNames && options.objectNames.length > 0) {
495
+ for (const obj of objectsMap.values()) {
496
+ if (options.objectNames.includes(obj.name)) {
497
+ allowedObjectIds.add(obj.id);
498
+ }
499
+ }
500
+ } else {
501
+ for (const obj of objectsMap.values()) {
502
+ allowedObjectIds.add(obj.id);
503
+ }
504
+ }
505
+ let matchingRecords = Array.from(stores.objectRecords.values()).filter((r) => {
506
+ if (r.tenantId !== tenantId) return false;
507
+ if (!allowedObjectIds.has(r.objectId)) return false;
508
+ return Object.values(r.values).some(
509
+ (val) => String(val).toLowerCase().includes(lowerQuery)
510
+ );
511
+ });
512
+ const total = matchingRecords.length;
513
+ if (options?.limit) {
514
+ matchingRecords = matchingRecords.slice(
515
+ options.offset ?? 0,
516
+ (options.offset ?? 0) + options.limit
517
+ );
518
+ }
519
+ const results = matchingRecords.map((r) => {
520
+ const obj = objectsMap.get(r.objectId);
521
+ const labelExpression = obj?.labelExpression ?? "{{ name }}";
522
+ return {
523
+ objectId: r.objectId,
524
+ objectName: obj?.name ?? "unknown",
525
+ objectLabel: obj?.label ?? "Unknown",
526
+ label: renderLabelExpression(labelExpression, r.values),
527
+ recordId: r.id,
528
+ values: r.values,
529
+ completionStatus: r.completionStatus,
530
+ createdAt: r.createdAt,
531
+ updatedAt: r.updatedAt
532
+ };
533
+ });
534
+ return Promise.resolve({ results, total });
535
+ }
536
+ };
537
+ }
538
+ function createMockViewsRepository(stores) {
539
+ return {
540
+ findById(id) {
541
+ return Promise.resolve(stores.views.get(id) ?? null);
542
+ },
543
+ findByName(tenantId, objectName, viewName) {
544
+ return Promise.resolve(
545
+ Array.from(stores.views.values()).find(
546
+ (v) => v.tenantId === tenantId && v.objectName === objectName && v.name === viewName
547
+ ) ?? null
548
+ );
549
+ },
550
+ findByObjectName(tenantId, objectName) {
551
+ return Promise.resolve(
552
+ Array.from(stores.views.values()).filter(
553
+ (v) => v.tenantId === tenantId && v.objectName === objectName
554
+ )
555
+ );
556
+ },
557
+ findAllForTenant(tenantId) {
558
+ return Promise.resolve(
559
+ Array.from(stores.views.values()).filter((v) => v.tenantId === tenantId)
560
+ );
561
+ },
562
+ findSystemByName(objectName, viewName) {
563
+ return Promise.resolve(
564
+ Array.from(stores.views.values()).find(
565
+ (v) => v.objectName === objectName && v.name === viewName && v.system
566
+ ) ?? null
567
+ );
568
+ },
569
+ findSystemByObjectName(objectName) {
570
+ return Promise.resolve(
571
+ Array.from(stores.views.values()).filter((v) => v.objectName === objectName && v.system)
572
+ );
573
+ },
574
+ create(data) {
575
+ const id = generateId();
576
+ const now = /* @__PURE__ */ new Date();
577
+ const dbView = {
578
+ id,
579
+ tenantId: data.tenantId,
580
+ objectName: data.objectName,
581
+ name: data.name,
582
+ label: data.label,
583
+ description: data.description,
584
+ icon: data.icon,
585
+ tabs: data.tabs,
586
+ default: data.default ?? false,
587
+ system: data.system ?? false,
588
+ metadata: data.metadata,
589
+ createdAt: now,
590
+ updatedAt: now
591
+ };
592
+ stores.views.set(id, dbView);
593
+ return Promise.resolve(dbView);
594
+ },
595
+ update(id, data) {
596
+ const view2 = stores.views.get(id);
597
+ if (!view2) {
598
+ return Promise.reject(new Error(`View not found: ${id}`));
599
+ }
600
+ const updated = {
601
+ ...view2,
602
+ ...data,
603
+ updatedAt: /* @__PURE__ */ new Date()
604
+ };
605
+ stores.views.set(id, updated);
606
+ return Promise.resolve(updated);
607
+ },
608
+ delete(id) {
609
+ stores.views.delete(id);
610
+ return Promise.resolve();
611
+ },
612
+ deleteNotIn(objectName, keepViewNames) {
613
+ let deleted = 0;
614
+ for (const [id, view2] of stores.views.entries()) {
615
+ if (view2.objectName === objectName && view2.system && !keepViewNames.includes(view2.name)) {
616
+ stores.views.delete(id);
617
+ deleted++;
618
+ }
619
+ }
620
+ return Promise.resolve(deleted);
621
+ },
622
+ async upsert(data) {
623
+ const existing = data.system ? await this.findSystemByName(data.objectName, data.name) : await this.findByName(data.tenantId, data.objectName, data.name);
624
+ if (existing) {
625
+ return this.update(existing.id, {
626
+ label: data.label,
627
+ description: data.description,
628
+ icon: data.icon,
629
+ tabs: data.tabs,
630
+ default: data.default,
631
+ metadata: data.metadata
632
+ });
633
+ }
634
+ return this.create(data);
635
+ }
636
+ };
637
+ }
638
+ function createMockAdapter() {
639
+ const stores = {
640
+ objects: /* @__PURE__ */ new Map(),
641
+ attributes: /* @__PURE__ */ new Map(),
642
+ userProfiles: /* @__PURE__ */ new Map(),
643
+ files: /* @__PURE__ */ new Map(),
644
+ objectRecords: /* @__PURE__ */ new Map(),
645
+ views: /* @__PURE__ */ new Map()
646
+ };
647
+ const adapter = {
648
+ objects: createMockObjectsRepository(stores),
649
+ attributes: createMockAttributesRepository(stores),
650
+ userProfiles: createMockUserProfilesRepository(stores),
651
+ files: createMockFilesRepository(stores),
652
+ objectRecords: createMockObjectRecordsRepository(stores),
653
+ views: createMockViewsRepository(stores),
654
+ async transaction(callback) {
655
+ return await callback(adapter);
656
+ },
657
+ // Expose stores for testing inspection
658
+ _stores: stores,
659
+ // Reset all stores (useful between tests)
660
+ reset() {
661
+ stores.objects.clear();
662
+ stores.attributes.clear();
663
+ stores.userProfiles.clear();
664
+ stores.files.clear();
665
+ stores.objectRecords.clear();
666
+ stores.views.clear();
667
+ }
668
+ };
669
+ return adapter;
670
+ }
671
+
672
+ // src/runtime/services/file.service.ts
673
+ var FileService = class {
674
+ constructor(adapter, tenantId) {
675
+ this.adapter = adapter;
676
+ this.tenantId = tenantId;
677
+ }
678
+ /**
679
+ * Create a new file record (after upload to storage)
680
+ *
681
+ * @param data - File metadata
682
+ * @returns Created file record
683
+ *
684
+ * @example
685
+ * ```typescript
686
+ * const service = new FileService(adapter, "tenant-123");
687
+ *
688
+ * // After uploading to S3
689
+ * const file = await service.createFile({
690
+ * tenantId: "tenant-123",
691
+ * name: "contract-2025.pdf",
692
+ * originalName: "Contract Acme Corp 2025.pdf",
693
+ * mimeType: "application/pdf",
694
+ * size: 2458624,
695
+ * storageProvider: "s3",
696
+ * storagePath: "tenants/123/files/2025/contract.pdf",
697
+ * storageBucket: "my-app-files",
698
+ * url: "https://cdn.example.com/files/file-123",
699
+ * uploadedBy: "profile-456",
700
+ * visibility: "private"
701
+ * });
702
+ * ```
703
+ */
704
+ async createFile(data) {
705
+ if (data.tenantId !== this.tenantId) {
706
+ throw new Error(
707
+ `Tenant mismatch: service initialized with "${this.tenantId}" but data has "${data.tenantId}"`
708
+ );
709
+ }
710
+ return await this.adapter.files.create(data);
711
+ }
712
+ /**
713
+ * Get file by ID
714
+ */
715
+ async getFile(fileId) {
716
+ const file2 = await this.adapter.files.findById(fileId);
717
+ if (file2?.deletedAt) {
718
+ return null;
719
+ }
720
+ return file2;
721
+ }
722
+ /**
723
+ * Get file by ID or throw
724
+ */
725
+ async getFileOrThrow(fileId) {
726
+ const file2 = await this.getFile(fileId);
727
+ if (!file2) {
728
+ throw new Error(`File with id "${fileId}" not found`);
729
+ }
730
+ return file2;
731
+ }
732
+ /**
733
+ * Update file metadata
734
+ *
735
+ * @param fileId - File UUID
736
+ * @param data - Data to update
737
+ * @returns Updated file
738
+ */
739
+ async updateFile(fileId, data) {
740
+ await this.getFileOrThrow(fileId);
741
+ return await this.adapter.files.update(fileId, data);
742
+ }
743
+ /**
744
+ * Delete file (soft delete)
745
+ *
746
+ * @param fileId - File UUID
747
+ * @param options - Delete options
748
+ */
749
+ async deleteFile(fileId, options) {
750
+ if (options?.checkOwnership && options.userId) {
751
+ const file2 = await this.getFileOrThrow(fileId);
752
+ if (file2.uploadedBy !== options.userId) {
753
+ throw new Error("You can only delete files you uploaded");
754
+ }
755
+ }
756
+ if (options?.hard) {
757
+ await this.adapter.files.hardDelete(fileId);
758
+ } else {
759
+ await this.adapter.files.delete(fileId);
760
+ }
761
+ }
762
+ /**
763
+ * List files for the tenant
764
+ */
765
+ async listFiles(options) {
766
+ return await this.adapter.files.list(this.tenantId, options);
767
+ }
768
+ /**
769
+ * List files by folder
770
+ */
771
+ async listFilesByFolder(folderPath) {
772
+ return await this.adapter.files.findByFolder(this.tenantId, folderPath);
773
+ }
774
+ /**
775
+ * List files uploaded by a specific user
776
+ */
777
+ async listFilesByUploader(uploadedBy) {
778
+ return await this.adapter.files.findByUploader(uploadedBy);
779
+ }
780
+ /**
781
+ * Change file visibility
782
+ *
783
+ * @param fileId - File UUID
784
+ * @param visibility - New visibility level
785
+ * @param allowedUsers - Users allowed to access (if restricted)
786
+ */
787
+ async changeVisibility(fileId, visibility, allowedUsers) {
788
+ const updateData = { visibility };
789
+ if (visibility === "restricted" && allowedUsers) {
790
+ updateData.allowedUsers = allowedUsers;
791
+ }
792
+ return await this.updateFile(fileId, updateData);
793
+ }
794
+ /**
795
+ * Grant access to a file for specific users
796
+ *
797
+ * @param fileId - File UUID
798
+ * @param userIds - User IDs to grant access
799
+ */
800
+ async grantAccess(fileId, userIds) {
801
+ const file2 = await this.getFileOrThrow(fileId);
802
+ const currentAllowed = file2.allowedUsers || [];
803
+ const newAllowed = [.../* @__PURE__ */ new Set([...currentAllowed, ...userIds])];
804
+ return await this.updateFile(fileId, {
805
+ visibility: "restricted",
806
+ allowedUsers: newAllowed
807
+ });
808
+ }
809
+ /**
810
+ * Revoke access to a file for specific users
811
+ *
812
+ * @param fileId - File UUID
813
+ * @param userIds - User IDs to revoke access
814
+ */
815
+ async revokeAccess(fileId, userIds) {
816
+ const file2 = await this.getFileOrThrow(fileId);
817
+ const currentAllowed = file2.allowedUsers || [];
818
+ const newAllowed = currentAllowed.filter((id) => !userIds.includes(id));
819
+ return await this.updateFile(fileId, {
820
+ allowedUsers: newAllowed
821
+ });
822
+ }
823
+ /**
824
+ * Check if user has access to a file
825
+ *
826
+ * @param fileId - File UUID
827
+ * @param userId - User ID to check
828
+ * @returns true if user can access the file
829
+ */
830
+ async canAccess(fileId, userId) {
831
+ const file2 = await this.getFile(fileId);
832
+ if (!file2) {
833
+ return false;
834
+ }
835
+ if (file2.visibility === "public") {
836
+ return true;
837
+ }
838
+ if (file2.uploadedBy === userId) {
839
+ return true;
840
+ }
841
+ if (file2.visibility === "restricted") {
842
+ return file2.allowedUsers?.includes(userId) ?? false;
843
+ }
844
+ return false;
845
+ }
846
+ /**
847
+ * Move file to different folder
848
+ */
849
+ async moveToFolder(fileId, newFolderPath) {
850
+ return await this.updateFile(fileId, { folderPath: newFolderPath });
851
+ }
852
+ /**
853
+ * Add tags to file
854
+ */
855
+ async addTags(fileId, tags) {
856
+ const file2 = await this.getFileOrThrow(fileId);
857
+ const currentTags = file2.tags || [];
858
+ const newTags = [.../* @__PURE__ */ new Set([...currentTags, ...tags])];
859
+ return await this.updateFile(fileId, { tags: newTags });
860
+ }
861
+ /**
862
+ * Remove tags from file
863
+ */
864
+ async removeTags(fileId, tags) {
865
+ const file2 = await this.getFileOrThrow(fileId);
866
+ const currentTags = file2.tags || [];
867
+ const newTags = currentTags.filter((tag) => !tags.includes(tag));
868
+ return await this.updateFile(fileId, { tags: newTags });
869
+ }
870
+ };
871
+
872
+ // src/runtime/services/geocoding.service.ts
873
+ var GeocodingService = class {
874
+ constructor(adapter) {
875
+ this.adapter = adapter;
876
+ }
877
+ /**
878
+ * Search for address suggestions as the user types
879
+ */
880
+ async autocomplete(params) {
881
+ if (!params.query || params.query.trim().length < 2) {
882
+ return [];
883
+ }
884
+ return await this.adapter.autocomplete({
885
+ ...params,
886
+ query: params.query.trim(),
887
+ limit: params.limit ?? 5
888
+ });
889
+ }
890
+ /**
891
+ * Reverse geocode coordinates to an address
892
+ */
893
+ async reverse(params) {
894
+ if (!this.adapter.reverse) {
895
+ throw new Error("Reverse geocoding is not supported by the configured adapter");
896
+ }
897
+ return await this.adapter.reverse(params);
898
+ }
899
+ /**
900
+ * Geocode a structured address to coordinates
901
+ */
902
+ async geocode(params) {
903
+ if (!this.adapter.geocode) {
904
+ throw new Error("Geocoding is not supported by the configured adapter");
905
+ }
906
+ return await this.adapter.geocode(params);
907
+ }
908
+ };
909
+
910
+ // src/runtime/services/global-search.service.ts
911
+ var GlobalSearchService = class {
912
+ constructor(adapter, tenantId) {
913
+ this.adapter = adapter;
914
+ this.tenantId = tenantId;
915
+ }
916
+ /**
917
+ * Search across all object records for the tenant
918
+ *
919
+ * @param query - Search query string
920
+ * @param options - Search options (pagination, object filters)
921
+ * @returns Matching records with object metadata and total count
922
+ *
923
+ * @example
924
+ * ```typescript
925
+ * // Basic search
926
+ * const { results, total } = await service.search("nike air");
927
+ *
928
+ * // With pagination
929
+ * const { results, total } = await service.search("nike", {
930
+ * limit: 10,
931
+ * offset: 20
932
+ * });
933
+ *
934
+ * // Filter by object types
935
+ * const { results, total } = await service.search("nike", {
936
+ * objectNames: ["products", "orders"]
937
+ * });
938
+ * ```
939
+ */
940
+ async search(query, options) {
941
+ if (!query || query.trim().length === 0) {
942
+ return { results: [], total: 0 };
943
+ }
944
+ return await this.adapter.objectRecords.globalSearch(this.tenantId, query.trim(), {
945
+ limit: options?.limit ?? 20,
946
+ offset: options?.offset ?? 0,
947
+ objectNames: options?.objectNames,
948
+ includeObjectInfo: options?.includeObjectInfo ?? true
949
+ });
950
+ }
951
+ /**
952
+ * Search and group results by object type
953
+ *
954
+ * @param query - Search query string
955
+ * @param options - Search options
956
+ * @returns Results grouped by object name
957
+ */
958
+ async searchGrouped(query, options) {
959
+ const { results, total } = await this.search(query, {
960
+ ...options,
961
+ limit: 100,
962
+ // Get more for grouping
963
+ offset: 0
964
+ });
965
+ const groupMap = /* @__PURE__ */ new Map();
966
+ for (const result of results) {
967
+ const existing = groupMap.get(result.objectName);
968
+ if (existing) {
969
+ existing.results.push(result);
970
+ } else {
971
+ groupMap.set(result.objectName, {
972
+ objectName: result.objectName,
973
+ objectLabel: result.objectLabel,
974
+ results: [result]
975
+ });
976
+ }
977
+ }
978
+ const groups = Array.from(groupMap.values()).map((g) => ({
979
+ ...g,
980
+ count: g.results.length
981
+ }));
982
+ groups.sort((a, b) => b.count - a.count);
983
+ return { groups, total };
984
+ }
985
+ };
986
+
987
+ // src/builders/attribute-validators.ts
988
+ import { ICONS } from "@stndrds/constants";
989
+ var VALID_ICONS = new Set(ICONS);
990
+ var ATTRIBUTE_NAME_REGEX = /^[a-zA-Z_][a-zA-Z0-9_]*$/;
991
+ var MAX_NAME_LENGTH = 63;
992
+ var MAX_LABEL_LENGTH = 128;
993
+ function validateAttributeName(name) {
994
+ if (!name || name.length === 0) {
995
+ throw new Error("[AttributeBuilder] Attribute name cannot be empty");
996
+ }
997
+ if (name.length > MAX_NAME_LENGTH) {
998
+ throw new Error(
999
+ `[AttributeBuilder] Attribute name is too long (max ${MAX_NAME_LENGTH} characters)`
1000
+ );
1001
+ }
1002
+ if (!ATTRIBUTE_NAME_REGEX.test(name)) {
1003
+ throw new Error(
1004
+ "[AttributeBuilder] Invalid attribute name format.\nName must be a valid variable identifier:\n \u2705 Valid: 'firstName', 'first_name', 'FirstName', 'FIRST_NAME'\n \u274C Invalid: 'first-name', 'first name', '123name', 'first.name'"
1005
+ );
1006
+ }
1007
+ }
1008
+ function validateLabel(label) {
1009
+ if (!label || label.length === 0) {
1010
+ throw new Error("[AttributeBuilder] Attribute label cannot be empty");
1011
+ }
1012
+ if (label.length > MAX_LABEL_LENGTH) {
1013
+ throw new Error(
1014
+ `[AttributeBuilder] Attribute label is too long (max ${MAX_LABEL_LENGTH} characters)`
1015
+ );
1016
+ }
1017
+ }
1018
+ function validateIconName(icon, context) {
1019
+ if (!VALID_ICONS.has(icon)) {
1020
+ throw new Error(
1021
+ `[AttributeBuilder] Invalid icon "${icon}" in ${context}.
1022
+ Icon must be one of the predefined icons from @stndrds/constants.`
1023
+ );
1024
+ }
1025
+ }
1026
+ function validateOptions(options, attributeName) {
1027
+ if (options.length === 0) return;
1028
+ const ids = /* @__PURE__ */ new Set();
1029
+ const values = /* @__PURE__ */ new Set();
1030
+ for (const option of options) {
1031
+ if (!option.id?.trim()) {
1032
+ throw new Error(
1033
+ `[AttributeBuilder] Option in "${attributeName}" has an empty or missing id.`
1034
+ );
1035
+ }
1036
+ if (!option.value?.trim()) {
1037
+ throw new Error(
1038
+ `[AttributeBuilder] Option "${option.id}" in "${attributeName}" has an empty or missing value.`
1039
+ );
1040
+ }
1041
+ if (!option.label?.trim()) {
1042
+ throw new Error(
1043
+ `[AttributeBuilder] Option "${option.id}" in "${attributeName}" has an empty or missing label.`
1044
+ );
1045
+ }
1046
+ if (ids.has(option.id)) {
1047
+ throw new Error(
1048
+ `[AttributeBuilder] Duplicate option id "${option.id}" in "${attributeName}".`
1049
+ );
1050
+ }
1051
+ ids.add(option.id);
1052
+ if (values.has(option.value)) {
1053
+ throw new Error(
1054
+ `[AttributeBuilder] Duplicate option value "${option.value}" in "${attributeName}".`
1055
+ );
1056
+ }
1057
+ values.add(option.value);
1058
+ if (option.icon) {
1059
+ validateIconName(option.icon, `option "${option.id}" of "${attributeName}"`);
1060
+ }
1061
+ }
1062
+ }
1063
+
1064
+ // src/builders/attribute-builders.ts
1065
+ var BaseAttributeBuilder = class {
1066
+ constructor(type, name, label) {
1067
+ validateAttributeName(name);
1068
+ validateLabel(label);
1069
+ this.attr = {
1070
+ name,
1071
+ label,
1072
+ type,
1073
+ required: false
1074
+ };
1075
+ }
1076
+ setRequired(value) {
1077
+ this.attr.required = value;
1078
+ }
1079
+ system() {
1080
+ this.attr.system = true;
1081
+ return this;
1082
+ }
1083
+ disabled() {
1084
+ this.attr.disabled = true;
1085
+ return this;
1086
+ }
1087
+ hidden() {
1088
+ this.attr.hidden = true;
1089
+ return this;
1090
+ }
1091
+ placeholder(value) {
1092
+ this.attr.placeholder = value;
1093
+ return this;
1094
+ }
1095
+ description(value) {
1096
+ this.attr.description = value;
1097
+ return this;
1098
+ }
1099
+ icon(value) {
1100
+ validateIconName(value, `attribute "${this.attr.name}"`);
1101
+ this.attr.icon = value;
1102
+ return this;
1103
+ }
1104
+ order(value) {
1105
+ this.attr.order = value;
1106
+ return this;
1107
+ }
1108
+ defaultValue(value) {
1109
+ this.attr.defaultValue = value;
1110
+ return this;
1111
+ }
1112
+ metadata(value) {
1113
+ this.attr.metadata = value;
1114
+ return this;
1115
+ }
1116
+ build() {
1117
+ return this.attr;
1118
+ }
1119
+ };
1120
+ var TextAttributeBuilder = class extends BaseAttributeBuilder {
1121
+ constructor(name, label) {
1122
+ super("text", name, label);
1123
+ }
1124
+ minLength(value) {
1125
+ this.attr.minLength = value;
1126
+ return this;
1127
+ }
1128
+ maxLength(value) {
1129
+ this.attr.maxLength = value;
1130
+ return this;
1131
+ }
1132
+ pattern(value) {
1133
+ this.attr.pattern = value;
1134
+ return this;
1135
+ }
1136
+ required() {
1137
+ this.setRequired(true);
1138
+ return this;
1139
+ }
1140
+ optional() {
1141
+ this.setRequired(false);
1142
+ return this;
1143
+ }
1144
+ /**
1145
+ * Set email validation pattern
1146
+ */
1147
+ email() {
1148
+ this.attr.pattern = "^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$";
1149
+ return this;
1150
+ }
1151
+ /**
1152
+ * Set URL validation pattern
1153
+ */
1154
+ url() {
1155
+ this.attr.pattern = "^https?:\\/\\/[\\w\\-]+(\\.[\\w\\-]+)+[/#?]?.*$";
1156
+ return this;
1157
+ }
1158
+ /**
1159
+ * Set slug validation pattern
1160
+ */
1161
+ slug() {
1162
+ this.attr.pattern = "^[a-z0-9]+(?:-[a-z0-9]+)*$";
1163
+ return this;
1164
+ }
1165
+ };
1166
+ function text(config) {
1167
+ return new TextAttributeBuilder(config.name, config.label);
1168
+ }
1169
+ var TextAreaAttributeBuilder = class extends BaseAttributeBuilder {
1170
+ constructor(name, label) {
1171
+ super("textarea", name, label);
1172
+ }
1173
+ required() {
1174
+ this.setRequired(true);
1175
+ return this;
1176
+ }
1177
+ optional() {
1178
+ this.setRequired(false);
1179
+ return this;
1180
+ }
1181
+ };
1182
+ function textarea(config) {
1183
+ return new TextAreaAttributeBuilder(config.name, config.label);
1184
+ }
1185
+ var NumberAttributeBuilder = class extends BaseAttributeBuilder {
1186
+ constructor(name, label) {
1187
+ super("number", name, label);
1188
+ }
1189
+ min(value) {
1190
+ this.attr.min = value;
1191
+ return this;
1192
+ }
1193
+ max(value) {
1194
+ this.attr.max = value;
1195
+ return this;
1196
+ }
1197
+ integer() {
1198
+ this.attr.unit = "integer";
1199
+ this.attr.decimals = 0;
1200
+ return this;
1201
+ }
1202
+ decimal(decimals = 2) {
1203
+ this.attr.unit = "decimal";
1204
+ this.attr.decimals = decimals;
1205
+ return this;
1206
+ }
1207
+ percentage() {
1208
+ this.attr.unit = "percentage";
1209
+ return this;
1210
+ }
1211
+ required() {
1212
+ this.setRequired(true);
1213
+ return this;
1214
+ }
1215
+ optional() {
1216
+ this.setRequired(false);
1217
+ return this;
1218
+ }
1219
+ };
1220
+ function number(config) {
1221
+ return new NumberAttributeBuilder(config.name, config.label);
1222
+ }
1223
+ var CheckboxAttributeBuilder = class extends BaseAttributeBuilder {
1224
+ constructor(name, label) {
1225
+ super("checkbox", name, label);
1226
+ }
1227
+ required() {
1228
+ this.setRequired(true);
1229
+ return this;
1230
+ }
1231
+ optional() {
1232
+ this.setRequired(false);
1233
+ return this;
1234
+ }
1235
+ };
1236
+ function checkbox(config) {
1237
+ return new CheckboxAttributeBuilder(config.name, config.label);
1238
+ }
1239
+ var DateAttributeBuilder = class extends BaseAttributeBuilder {
1240
+ constructor(name, label) {
1241
+ super("date", name, label);
1242
+ }
1243
+ format(value) {
1244
+ this.attr.dateFormat = value;
1245
+ return this;
1246
+ }
1247
+ minDate(value) {
1248
+ this.attr.minDate = value;
1249
+ return this;
1250
+ }
1251
+ maxDate(value) {
1252
+ this.attr.maxDate = value;
1253
+ return this;
1254
+ }
1255
+ required() {
1256
+ this.setRequired(true);
1257
+ return this;
1258
+ }
1259
+ optional() {
1260
+ this.setRequired(false);
1261
+ return this;
1262
+ }
1263
+ };
1264
+ function date(config) {
1265
+ return new DateAttributeBuilder(config.name, config.label);
1266
+ }
1267
+ var PhoneAttributeBuilder = class extends BaseAttributeBuilder {
1268
+ constructor(name, label) {
1269
+ super("phone", name, label);
1270
+ }
1271
+ defaultCountry(value) {
1272
+ this.attr.defaultCountryCode = value;
1273
+ return this;
1274
+ }
1275
+ required() {
1276
+ this.setRequired(true);
1277
+ return this;
1278
+ }
1279
+ optional() {
1280
+ this.setRequired(false);
1281
+ return this;
1282
+ }
1283
+ };
1284
+ function phone(config) {
1285
+ return new PhoneAttributeBuilder(config.name, config.label);
1286
+ }
1287
+ var CurrencyAttributeBuilder = class extends BaseAttributeBuilder {
1288
+ constructor(name, label) {
1289
+ super("currency", name, label);
1290
+ }
1291
+ defaultCurrency(value) {
1292
+ this.attr.defaultCurrency = value;
1293
+ return this;
1294
+ }
1295
+ allowedCurrencies(value) {
1296
+ this.attr.allowedCurrencies = value;
1297
+ return this;
1298
+ }
1299
+ required() {
1300
+ this.setRequired(true);
1301
+ return this;
1302
+ }
1303
+ optional() {
1304
+ this.setRequired(false);
1305
+ return this;
1306
+ }
1307
+ };
1308
+ function currency(config) {
1309
+ return new CurrencyAttributeBuilder(config.name, config.label);
1310
+ }
1311
+ var StatusAttributeBuilder = class extends BaseAttributeBuilder {
1312
+ constructor(name, label) {
1313
+ super("status", name, label);
1314
+ }
1315
+ /**
1316
+ * Set all options at once (preserves literal types for values)
1317
+ */
1318
+ options(value) {
1319
+ validateOptions(value, this.attr.name ?? "unknown");
1320
+ this.attr.options = value;
1321
+ return this;
1322
+ }
1323
+ option(config) {
1324
+ if (!this.attr.options) {
1325
+ this.attr.options = [];
1326
+ }
1327
+ const allOptions = [...this.attr.options, config];
1328
+ validateOptions(allOptions, this.attr.name ?? "unknown");
1329
+ this.attr.options.push(config);
1330
+ return this;
1331
+ }
1332
+ required() {
1333
+ this.setRequired(true);
1334
+ return this;
1335
+ }
1336
+ optional() {
1337
+ this.setRequired(false);
1338
+ return this;
1339
+ }
1340
+ };
1341
+ function status(config) {
1342
+ return new StatusAttributeBuilder(config.name, config.label);
1343
+ }
1344
+ var SelectAttributeBuilder = class extends BaseAttributeBuilder {
1345
+ constructor(name, label) {
1346
+ super("select", name, label);
1347
+ }
1348
+ /**
1349
+ * Set all options at once (preserves literal types for values)
1350
+ */
1351
+ options(value) {
1352
+ validateOptions(value, this.attr.name ?? "unknown");
1353
+ this.attr.options = value;
1354
+ return this;
1355
+ }
1356
+ option(config) {
1357
+ if (!this.attr.options) {
1358
+ this.attr.options = [];
1359
+ }
1360
+ const allOptions = [...this.attr.options, config];
1361
+ validateOptions(allOptions, this.attr.name ?? "unknown");
1362
+ this.attr.options.push(config);
1363
+ return this;
1364
+ }
1365
+ required() {
1366
+ this.setRequired(true);
1367
+ return this;
1368
+ }
1369
+ optional() {
1370
+ this.setRequired(false);
1371
+ return this;
1372
+ }
1373
+ };
1374
+ function select(config) {
1375
+ return new SelectAttributeBuilder(config.name, config.label);
1376
+ }
1377
+ var MultiselectAttributeBuilder = class extends BaseAttributeBuilder {
1378
+ constructor(name, label) {
1379
+ super("multiselect", name, label);
1380
+ }
1381
+ /**
1382
+ * Set all options at once (preserves literal types for values)
1383
+ */
1384
+ options(value) {
1385
+ validateOptions(value, this.attr.name ?? "unknown");
1386
+ this.attr.options = value;
1387
+ return this;
1388
+ }
1389
+ option(config) {
1390
+ if (!this.attr.options) {
1391
+ this.attr.options = [];
1392
+ }
1393
+ const allOptions = [...this.attr.options, config];
1394
+ validateOptions(allOptions, this.attr.name ?? "unknown");
1395
+ this.attr.options.push(config);
1396
+ return this;
1397
+ }
1398
+ required() {
1399
+ this.setRequired(true);
1400
+ return this;
1401
+ }
1402
+ optional() {
1403
+ this.setRequired(false);
1404
+ return this;
1405
+ }
1406
+ };
1407
+ function multiselect(config) {
1408
+ return new MultiselectAttributeBuilder(config.name, config.label);
1409
+ }
1410
+ var LocationAttributeBuilder = class extends BaseAttributeBuilder {
1411
+ constructor(name, label) {
1412
+ super("location", name, label);
1413
+ }
1414
+ granularity(value) {
1415
+ this.attr.granularity = value;
1416
+ return this;
1417
+ }
1418
+ enableAutocomplete() {
1419
+ this.attr.enableAutocomplete = true;
1420
+ return this;
1421
+ }
1422
+ enableMap() {
1423
+ this.attr.enableMap = true;
1424
+ return this;
1425
+ }
1426
+ defaultCountry(value) {
1427
+ this.attr.defaultCountry = value;
1428
+ return this;
1429
+ }
1430
+ allowedCountries(value) {
1431
+ this.attr.allowedCountries = value;
1432
+ return this;
1433
+ }
1434
+ displayFormat(value) {
1435
+ this.attr.displayFormat = value;
1436
+ return this;
1437
+ }
1438
+ required() {
1439
+ this.setRequired(true);
1440
+ return this;
1441
+ }
1442
+ optional() {
1443
+ this.setRequired(false);
1444
+ return this;
1445
+ }
1446
+ };
1447
+ function location(config) {
1448
+ return new LocationAttributeBuilder(config.name, config.label);
1449
+ }
1450
+ var TimestampAttributeBuilder = class extends BaseAttributeBuilder {
1451
+ constructor(name, label) {
1452
+ super("timestamp", name, label);
1453
+ }
1454
+ autoUpdate() {
1455
+ this.attr.autoUpdate = true;
1456
+ return this;
1457
+ }
1458
+ required() {
1459
+ this.setRequired(true);
1460
+ return this;
1461
+ }
1462
+ optional() {
1463
+ this.setRequired(false);
1464
+ return this;
1465
+ }
1466
+ };
1467
+ function timestamp(config) {
1468
+ return new TimestampAttributeBuilder(config.name, config.label);
1469
+ }
1470
+ var FileAttributeBuilder = class extends BaseAttributeBuilder {
1471
+ constructor(name, label) {
1472
+ super("file", name, label);
1473
+ }
1474
+ maxFiles(value) {
1475
+ this.attr.maxFiles = value;
1476
+ return this;
1477
+ }
1478
+ maxSize(bytes) {
1479
+ this.attr.maxSize = bytes;
1480
+ return this;
1481
+ }
1482
+ allowedTypes(types) {
1483
+ this.attr.allowedTypes = types;
1484
+ return this;
1485
+ }
1486
+ verification(config) {
1487
+ this.attr.verification = config;
1488
+ return this;
1489
+ }
1490
+ required() {
1491
+ this.setRequired(true);
1492
+ return this;
1493
+ }
1494
+ optional() {
1495
+ this.setRequired(false);
1496
+ return this;
1497
+ }
1498
+ };
1499
+ function file(config) {
1500
+ return new FileAttributeBuilder(config.name, config.label);
1501
+ }
1502
+ var UserAttributeBuilder = class extends BaseAttributeBuilder {
1503
+ constructor(name, label) {
1504
+ super("user", name, label);
1505
+ }
1506
+ allowedRoles(roles) {
1507
+ this.attr.allowedRoles = roles;
1508
+ return this;
1509
+ }
1510
+ required() {
1511
+ this.setRequired(true);
1512
+ return this;
1513
+ }
1514
+ optional() {
1515
+ this.setRequired(false);
1516
+ return this;
1517
+ }
1518
+ };
1519
+ function user(config) {
1520
+ return new UserAttributeBuilder(config.name, config.label);
1521
+ }
1522
+ var SingleRelationAttributeBuilder = class extends BaseAttributeBuilder {
1523
+ constructor(name, label) {
1524
+ super("relation", name, label);
1525
+ this.attr.cardinality = "one";
1526
+ this.attr.targets = [];
1527
+ }
1528
+ /**
1529
+ * Add a target object that can be linked
1530
+ * @param objectName - Name of the object (e.g., "companies")
1531
+ * @param options - Display template and filter options
1532
+ */
1533
+ to(objectName, options) {
1534
+ const target = {
1535
+ object: objectName,
1536
+ ...options
1537
+ };
1538
+ this.attr.targets?.push(target);
1539
+ return this;
1540
+ }
1541
+ /**
1542
+ * Set the deletion strategy when target record is deleted
1543
+ * @param strategy - "restrict" (default), "cascade", or "set_null"
1544
+ */
1545
+ onDelete(strategy) {
1546
+ this.attr.onDelete = strategy;
1547
+ return this;
1548
+ }
1549
+ /**
1550
+ * Convert to a multi-relation (cardinality: "many")
1551
+ */
1552
+ many() {
1553
+ const multiBuilder = new MultiRelationAttributeBuilder(
1554
+ this.attr.name,
1555
+ this.attr.label ?? "",
1556
+ {
1557
+ targets: this.attr.targets,
1558
+ onDelete: this.attr.onDelete,
1559
+ isRequired: this.attr.required
1560
+ }
1561
+ );
1562
+ return multiBuilder;
1563
+ }
1564
+ required() {
1565
+ this.setRequired(true);
1566
+ return this;
1567
+ }
1568
+ optional() {
1569
+ this.setRequired(false);
1570
+ return this;
1571
+ }
1572
+ };
1573
+ var MultiRelationAttributeBuilder = class extends BaseAttributeBuilder {
1574
+ constructor(name, label, initOptions) {
1575
+ super("relation", name, label);
1576
+ this.attr.cardinality = "many";
1577
+ this.attr.targets = initOptions?.targets ?? [];
1578
+ this.attr.defaultValue = [];
1579
+ if (initOptions?.onDelete) {
1580
+ this.attr.onDelete = initOptions.onDelete;
1581
+ }
1582
+ if (initOptions?.isRequired) {
1583
+ this.setRequired(true);
1584
+ }
1585
+ }
1586
+ /**
1587
+ * Add a target object that can be linked
1588
+ * @param objectName - Name of the object (e.g., "companies")
1589
+ * @param options - Display template and filter options
1590
+ */
1591
+ to(objectName, options) {
1592
+ const target = {
1593
+ object: objectName,
1594
+ ...options
1595
+ };
1596
+ this.attr.targets?.push(target);
1597
+ return this;
1598
+ }
1599
+ /**
1600
+ * Set the deletion strategy when target record is deleted
1601
+ * @param strategy - "restrict" (default), "cascade", or "set_null"
1602
+ */
1603
+ onDelete(strategy) {
1604
+ this.attr.onDelete = strategy;
1605
+ return this;
1606
+ }
1607
+ /**
1608
+ * Set minimum number of relations required
1609
+ */
1610
+ minItems(count) {
1611
+ this.attr.minItems = count;
1612
+ return this;
1613
+ }
1614
+ /**
1615
+ * Set maximum number of relations allowed
1616
+ */
1617
+ maxItems(count) {
1618
+ this.attr.maxItems = count;
1619
+ return this;
1620
+ }
1621
+ required() {
1622
+ this.setRequired(true);
1623
+ return this;
1624
+ }
1625
+ optional() {
1626
+ this.setRequired(false);
1627
+ return this;
1628
+ }
1629
+ };
1630
+ function relation(config) {
1631
+ return new SingleRelationAttributeBuilder(config.name, config.label);
1632
+ }
1633
+ var RatingAttributeBuilder = class extends BaseAttributeBuilder {
1634
+ constructor(name, label) {
1635
+ super("rating", name, label);
1636
+ }
1637
+ max(value) {
1638
+ this.attr.max = value;
1639
+ return this;
1640
+ }
1641
+ iconType(value) {
1642
+ this.attr.iconType = value;
1643
+ return this;
1644
+ }
1645
+ required() {
1646
+ this.setRequired(true);
1647
+ return this;
1648
+ }
1649
+ optional() {
1650
+ this.setRequired(false);
1651
+ return this;
1652
+ }
1653
+ };
1654
+ function rating(config) {
1655
+ return new RatingAttributeBuilder(config.name, config.label);
1656
+ }
1657
+
1658
+ // src/builders/object-builder.ts
1659
+ import z from "zod";
1660
+ var ObjectBuilder = class {
1661
+ constructor(config) {
1662
+ this.validateName(config.name);
1663
+ this.obj = {
1664
+ name: config.name,
1665
+ label: config.label,
1666
+ attributes: [],
1667
+ system: false
1668
+ };
1669
+ }
1670
+ /**
1671
+ * Set object description
1672
+ */
1673
+ description(value) {
1674
+ this.obj.description = value;
1675
+ return this;
1676
+ }
1677
+ /**
1678
+ * Set the plural form of the label (e.g., "Products" for "Product")
1679
+ * Used in UI when displaying collections
1680
+ */
1681
+ pluralLabel(value) {
1682
+ this._pluralLabel = value;
1683
+ return this;
1684
+ }
1685
+ /**
1686
+ * Set object icon
1687
+ */
1688
+ icon(value) {
1689
+ this.obj.icon = value;
1690
+ return this;
1691
+ }
1692
+ /**
1693
+ * Mark as system/native object (defined in code, protected)
1694
+ * System objects cannot be deleted/modified by clients
1695
+ */
1696
+ system() {
1697
+ this.obj.system = true;
1698
+ return this;
1699
+ }
1700
+ /**
1701
+ * Add an attribute to the object with type accumulation
1702
+ *
1703
+ * The return type accumulates the attribute's name and value type
1704
+ * into the TRecord generic, enabling full inference.
1705
+ *
1706
+ * @param attr - Attribute definition or builder (auto-builds if builder)
1707
+ */
1708
+ attribute(attr) {
1709
+ if (!this.obj.attributes) {
1710
+ this.obj.attributes = [];
1711
+ }
1712
+ const finalAttr = "build" in attr && typeof attr.build === "function" ? attr.build() : attr;
1713
+ this.obj.attributes.push(finalAttr);
1714
+ return this;
1715
+ }
1716
+ /**
1717
+ * Add multiple attributes at once
1718
+ * Note: For full type inference, prefer chaining .attribute() calls
1719
+ */
1720
+ attributes(attrs) {
1721
+ if (!this.obj.attributes) {
1722
+ this.obj.attributes = [];
1723
+ }
1724
+ const finalAttrs = attrs.map((attr) => "build" in attr ? attr.build() : attr);
1725
+ this.obj.attributes.push(...finalAttrs);
1726
+ return this;
1727
+ }
1728
+ /**
1729
+ * Set metadata
1730
+ */
1731
+ metadata(value) {
1732
+ this.obj.metadata = value;
1733
+ return this;
1734
+ }
1735
+ /**
1736
+ * Set the label expression template for displaying records
1737
+ * This is REQUIRED for every object.
1738
+ *
1739
+ * Supports variable interpolation with `{{ attribute }}` syntax
1740
+ * and pipes for formatting: `{{ name | UPPER }}`, `{{ name | capitalize }}`
1741
+ *
1742
+ * Available pipes: UPPER, LOWER, capitalize, trim
1743
+ *
1744
+ * @param template - The label expression template
1745
+ *
1746
+ * @example
1747
+ * ```typescript
1748
+ * object({ name: "contacts", label: "Contact" })
1749
+ * .labelExpression("{{ firstName }} {{ lastName }}")
1750
+ * .attribute(text({ name: "firstName", label: "First Name" }).required())
1751
+ * .attribute(text({ name: "lastName", label: "Last Name" }).required())
1752
+ * ```
1753
+ */
1754
+ labelExpression(template) {
1755
+ this._labelExpression = template;
1756
+ return this;
1757
+ }
1758
+ /**
1759
+ * Build the final ObjectDefinition
1760
+ * @throws Error if required fields are missing or invalid
1761
+ */
1762
+ build() {
1763
+ if (!this.obj.name) {
1764
+ throw new Error("[ObjectBuilder] Missing required field: name");
1765
+ }
1766
+ if (!this.obj.label) {
1767
+ throw new Error("[ObjectBuilder] Missing required field: label");
1768
+ }
1769
+ if (!this._labelExpression) {
1770
+ throw new Error(
1771
+ `[ObjectBuilder] Object "${this.obj.name}" must have a labelExpression.
1772
+ The labelExpression defines how records are displayed in lists and relations.
1773
+ \u2705 Example: .labelExpression("{{ name }}")
1774
+ \u2705 Example: .labelExpression("{{ firstName }} {{ lastName }}")`
1775
+ );
1776
+ }
1777
+ return {
1778
+ ...this.obj,
1779
+ pluralLabel: this._pluralLabel,
1780
+ labelExpression: this._labelExpression
1781
+ };
1782
+ }
1783
+ /**
1784
+ * Validate object name format
1785
+ * Must be kebab-case (slug format), max 63 characters
1786
+ * @internal
1787
+ */
1788
+ validateName(name) {
1789
+ if (name === void 0) {
1790
+ return;
1791
+ }
1792
+ const objectNameSchema = z.string().min(1, "Object name cannot be empty").max(63, "Object name is too long (max 63 characters)").regex(/^[a-z][a-z0-9-]*$/, {
1793
+ message: "Invalid object name format.\nName must be in kebab-case (slug format):\n \u2705 Valid: 'products', 'user-profiles', 'order-items'\n \u274C Invalid: 'Products', 'userProfiles', 'user_profiles'"
1794
+ });
1795
+ try {
1796
+ objectNameSchema.parse(name);
1797
+ } catch (error) {
1798
+ if (error instanceof z.ZodError) {
1799
+ throw new Error(`[ObjectBuilder] ${error.errors[0].message}`);
1800
+ }
1801
+ throw error;
1802
+ }
1803
+ }
1804
+ };
1805
+ function object(config) {
1806
+ return new ObjectBuilder(config);
1807
+ }
1808
+
1809
+ // src/builders/view-builder.ts
1810
+ import { z as z2 } from "zod";
1811
+ var GroupBuilder = class {
1812
+ constructor(id, label) {
1813
+ this.data = { fields: [] };
1814
+ this.data.id = id;
1815
+ this.data.label = label;
1816
+ }
1817
+ /**
1818
+ * Set group description
1819
+ */
1820
+ description(value) {
1821
+ this.data.description = value;
1822
+ return this;
1823
+ }
1824
+ /**
1825
+ * Make group collapsible
1826
+ * @param collapsed - Initial collapsed state (default: false)
1827
+ */
1828
+ collapsible(collapsed = false) {
1829
+ this.data.collapsible = true;
1830
+ this.data.collapsed = collapsed;
1831
+ return this;
1832
+ }
1833
+ /**
1834
+ * Set display order
1835
+ */
1836
+ order(value) {
1837
+ this.data.order = value;
1838
+ return this;
1839
+ }
1840
+ /**
1841
+ * Add multiple fields with default options
1842
+ * @example .fields("name", "email", "phone")
1843
+ */
1844
+ fields(...names) {
1845
+ for (const name of names) {
1846
+ this.data.fields?.push({ attribute: name });
1847
+ }
1848
+ return this;
1849
+ }
1850
+ /**
1851
+ * Add a single field with options
1852
+ * @example .field("name", { span: 8, readOnly: true })
1853
+ */
1854
+ field(attribute, options) {
1855
+ this.data.fields?.push({ attribute, ...options });
1856
+ return this;
1857
+ }
1858
+ /**
1859
+ * Add an inline attribute group (composite field with dropdown)
1860
+ * Groups multiple attributes into a single field
1861
+ * @example .attributeGroup({ id: "address", label: "Address", attributes: ["street", "city", "postal_code"], displayTemplate: "{street}, {city}" })
1862
+ */
1863
+ attributeGroup(config, options) {
1864
+ this.data.fields?.push({ attributeGroup: config, ...options });
1865
+ return this;
1866
+ }
1867
+ /**
1868
+ * Build the group definition
1869
+ */
1870
+ build() {
1871
+ if (!this.data.id) {
1872
+ throw new Error("[GroupBuilder] id is required");
1873
+ }
1874
+ if (!this.data.label) {
1875
+ throw new Error("[GroupBuilder] label is required");
1876
+ }
1877
+ if (!this.data.fields || this.data.fields.length === 0) {
1878
+ throw new Error("[GroupBuilder] At least one field is required");
1879
+ }
1880
+ return this.data;
1881
+ }
1882
+ };
1883
+ var TableTabConfig = class {
1884
+ /** @internal */
1885
+ constructor(view2, base, relation2) {
1886
+ this.view = view2;
1887
+ this.tabData = { ...base, type: "table", relation: relation2, columns: [] };
1888
+ }
1889
+ /**
1890
+ * Set columns to display
1891
+ * @example .columns("firstName", "lastName", "email")
1892
+ */
1893
+ columns(...names) {
1894
+ this.tabData.columns = names;
1895
+ return this;
1896
+ }
1897
+ /**
1898
+ * Allow creating new records
1899
+ */
1900
+ create() {
1901
+ this.tabData.allowCreate = true;
1902
+ return this;
1903
+ }
1904
+ /**
1905
+ * Allow inline editing
1906
+ */
1907
+ edit() {
1908
+ this.tabData.allowEdit = true;
1909
+ return this;
1910
+ }
1911
+ /**
1912
+ * Allow deleting records
1913
+ */
1914
+ delete() {
1915
+ this.tabData.allowDelete = true;
1916
+ return this;
1917
+ }
1918
+ /**
1919
+ * Enable all CRUD operations (create, edit, delete)
1920
+ */
1921
+ crud() {
1922
+ this.tabData.allowCreate = true;
1923
+ this.tabData.allowEdit = true;
1924
+ this.tabData.allowDelete = true;
1925
+ return this;
1926
+ }
1927
+ /**
1928
+ * Set default filters
1929
+ */
1930
+ filters(value) {
1931
+ this.tabData.filters = value;
1932
+ return this;
1933
+ }
1934
+ /**
1935
+ * Set default sort
1936
+ * @example .sort("lastName") or .sort("createdAt", "desc")
1937
+ */
1938
+ sort(field, order = "asc") {
1939
+ this.tabData.sort = { field, order };
1940
+ return this;
1941
+ }
1942
+ /**
1943
+ * Continue building with a new tab
1944
+ */
1945
+ tab(name, label) {
1946
+ this.finalize();
1947
+ return new TabBuilder(this.view, name, label);
1948
+ }
1949
+ /**
1950
+ * Finish this tab and return to ViewBuilder
1951
+ */
1952
+ done() {
1953
+ this.finalize();
1954
+ return this.view;
1955
+ }
1956
+ /**
1957
+ * Build the final view definition
1958
+ */
1959
+ build() {
1960
+ this.finalize();
1961
+ return this.view.build();
1962
+ }
1963
+ finalize() {
1964
+ if (!this.tabData.columns || this.tabData.columns.length === 0) {
1965
+ throw new Error(`[TableTabConfig] columns() is required for tab "${this.tabData.name}"`);
1966
+ }
1967
+ this.view._addTab(this.tabData);
1968
+ }
1969
+ };
1970
+ var CustomTabConfig = class {
1971
+ /** @internal */
1972
+ constructor(view2, base, component) {
1973
+ this.view = view2;
1974
+ this.tabData = { ...base, type: "custom", component };
1975
+ }
1976
+ /**
1977
+ * Set props to pass to the component
1978
+ */
1979
+ props(value) {
1980
+ this.tabData.props = value;
1981
+ return this;
1982
+ }
1983
+ /**
1984
+ * Continue building with a new tab
1985
+ */
1986
+ tab(name, label) {
1987
+ this.view._addTab(this.tabData);
1988
+ return new TabBuilder(this.view, name, label);
1989
+ }
1990
+ /**
1991
+ * Finish this tab and return to ViewBuilder
1992
+ */
1993
+ done() {
1994
+ this.view._addTab(this.tabData);
1995
+ return this.view;
1996
+ }
1997
+ /**
1998
+ * Build the final view definition
1999
+ */
2000
+ build() {
2001
+ this.view._addTab(this.tabData);
2002
+ return this.view.build();
2003
+ }
2004
+ };
2005
+ var TabBuilder = class {
2006
+ /** @internal */
2007
+ constructor(view2, name, label) {
2008
+ this.view = view2;
2009
+ this.base = {
2010
+ id: name,
2011
+ name,
2012
+ label
2013
+ };
2014
+ }
2015
+ /**
2016
+ * Set tab icon
2017
+ */
2018
+ icon(value) {
2019
+ this.base.icon = value;
2020
+ return this;
2021
+ }
2022
+ /**
2023
+ * Set display order
2024
+ */
2025
+ order(value) {
2026
+ this.base.order = value;
2027
+ return this;
2028
+ }
2029
+ /**
2030
+ * Mark as system tab (protected)
2031
+ */
2032
+ system() {
2033
+ this.base.system = true;
2034
+ return this;
2035
+ }
2036
+ // ─────────────────────────────────────────────────────────────────────────
2037
+ // TYPE DISCRIMINATORS
2038
+ // ─────────────────────────────────────────────────────────────────────────
2039
+ /**
2040
+ * Create a form tab with groups
2041
+ * @example .form(group("info", "Info").fields("name", "email"))
2042
+ */
2043
+ form(...groups) {
2044
+ if (groups.length === 0) {
2045
+ throw new Error(
2046
+ `[TabBuilder] form() requires at least one group for tab "${this.base.name}"`
2047
+ );
2048
+ }
2049
+ const tab = {
2050
+ ...this.base,
2051
+ type: "form",
2052
+ groups: groups.map((g) => g instanceof GroupBuilder ? g.build() : g)
2053
+ };
2054
+ return this.view._addTab(tab);
2055
+ }
2056
+ /**
2057
+ * Create a table tab for a relation
2058
+ * @example .table("contacts").columns("name", "email").crud()
2059
+ */
2060
+ table(relation2) {
2061
+ return new TableTabConfig(this.view, this.base, relation2);
2062
+ }
2063
+ /**
2064
+ * Create a custom tab with a component
2065
+ * @example .custom("AnalyticsWidget").props({ period: "12m" })
2066
+ */
2067
+ custom(component) {
2068
+ return new CustomTabConfig(this.view, this.base, component);
2069
+ }
2070
+ };
2071
+ var ViewBuilder = class {
2072
+ constructor(name, label) {
2073
+ this.data = { tabs: [] };
2074
+ this.validated = false;
2075
+ this.validateName(name);
2076
+ this.data.name = name;
2077
+ this.data.label = label;
2078
+ }
2079
+ /**
2080
+ * Set view description
2081
+ */
2082
+ description(value) {
2083
+ this.data.description = value;
2084
+ return this;
2085
+ }
2086
+ /**
2087
+ * Set view icon
2088
+ */
2089
+ icon(value) {
2090
+ this.data.icon = value;
2091
+ return this;
2092
+ }
2093
+ /**
2094
+ * Associate view with an object
2095
+ * @param objectName - Object name (kebab-case)
2096
+ */
2097
+ for(objectName) {
2098
+ this.data.object = objectName;
2099
+ return this;
2100
+ }
2101
+ /**
2102
+ * Mark as default view for the object
2103
+ */
2104
+ default() {
2105
+ this.data.default = true;
2106
+ return this;
2107
+ }
2108
+ /**
2109
+ * Mark as system view (protected, defined by developer)
2110
+ */
2111
+ system() {
2112
+ this.data.system = true;
2113
+ return this;
2114
+ }
2115
+ /**
2116
+ * Set metadata
2117
+ */
2118
+ metadata(value) {
2119
+ this.data.metadata = value;
2120
+ return this;
2121
+ }
2122
+ /**
2123
+ * Start building a new tab
2124
+ */
2125
+ tab(name, label) {
2126
+ return new TabBuilder(this, name, label);
2127
+ }
2128
+ /**
2129
+ * Add a pre-built tab
2130
+ */
2131
+ addTab(tab) {
2132
+ this.data.tabs?.push(tab);
2133
+ return this;
2134
+ }
2135
+ /**
2136
+ * @internal Used by TabBuilder to add tabs
2137
+ */
2138
+ _addTab(tab) {
2139
+ this.data.tabs?.push(tab);
2140
+ return this;
2141
+ }
2142
+ /**
2143
+ * Build the final view definition
2144
+ */
2145
+ build() {
2146
+ if (!this.data.object) {
2147
+ throw new Error("[ViewBuilder] for() is required - specify the target object");
2148
+ }
2149
+ if (!this.data.tabs || this.data.tabs.length === 0) {
2150
+ throw new Error("[ViewBuilder] At least one tab is required");
2151
+ }
2152
+ const tabNames = /* @__PURE__ */ new Set();
2153
+ for (const tab of this.data.tabs) {
2154
+ if (tabNames.has(tab.name)) {
2155
+ throw new Error(`[ViewBuilder] Duplicate tab name "${tab.name}"`);
2156
+ }
2157
+ tabNames.add(tab.name);
2158
+ }
2159
+ this.validated = true;
2160
+ return this.data;
2161
+ }
2162
+ /**
2163
+ * Validate view name format (kebab-case)
2164
+ */
2165
+ validateName(name) {
2166
+ const viewNameSchema = z2.string().min(1, "View name cannot be empty").max(63, "View name is too long (max 63 characters)").regex(/^[a-z][a-z0-9-]*$/, {
2167
+ message: "Invalid view name format.\nName must be in kebab-case:\n \u2705 Valid: 'detail', 'list-view', 'company-detail'\n \u274C Invalid: 'Detail', 'listView', 'list_view'"
2168
+ });
2169
+ try {
2170
+ viewNameSchema.parse(name);
2171
+ } catch (error) {
2172
+ if (error instanceof z2.ZodError) {
2173
+ throw new Error(`[ViewBuilder] ${error.errors[0].message}`);
2174
+ }
2175
+ throw error;
2176
+ }
2177
+ }
2178
+ };
2179
+ function view(name, label) {
2180
+ return new ViewBuilder(name, label);
2181
+ }
2182
+ function group(id, label) {
2183
+ return new GroupBuilder(id, label);
2184
+ }
2185
+
2186
+ // src/validation/validators.ts
2187
+ import { z as z3 } from "zod";
2188
+ var baseConfigSchema = z3.object({
2189
+ disabled: z3.boolean().optional(),
2190
+ placeholder: z3.string().optional(),
2191
+ description: z3.string().optional(),
2192
+ defaultValue: z3.unknown().optional(),
2193
+ icon: z3.string().optional(),
2194
+ order: z3.number().int().optional(),
2195
+ hidden: z3.boolean().optional(),
2196
+ archived: z3.boolean().optional(),
2197
+ deprecated: z3.boolean().optional(),
2198
+ metadata: z3.record(z3.unknown()).optional()
2199
+ });
2200
+ var optionSchema = z3.object({
2201
+ id: z3.string().min(1),
2202
+ label: z3.string().min(1),
2203
+ value: z3.string().min(1),
2204
+ color: z3.string().optional(),
2205
+ icon: z3.string().optional(),
2206
+ description: z3.string().optional(),
2207
+ group: z3.enum(["idle", "in_progress", "finished"]).optional()
2208
+ });
2209
+ var relationTargetSchema = z3.object({
2210
+ object: z3.string().min(1),
2211
+ displayTemplate: z3.string().optional(),
2212
+ filter: z3.record(z3.unknown()).optional()
2213
+ });
2214
+ var documentTypeConfigSchema = z3.object({
2215
+ type: z3.enum([
2216
+ "id_card",
2217
+ "passport",
2218
+ "incorporation_certificate",
2219
+ "driver_license",
2220
+ "birth_certificate",
2221
+ "residence_permit",
2222
+ "bank_statement",
2223
+ "proof_of_address",
2224
+ "custom"
2225
+ ]),
2226
+ label: z3.string(),
2227
+ faces: z3.array(z3.enum(["front", "back", "single"])),
2228
+ attributeMapping: z3.array(
2229
+ z3.object({
2230
+ attributeId: z3.string(),
2231
+ extractedKey: z3.string(),
2232
+ face: z3.enum(["front", "back", "single"]).optional(),
2233
+ required: z3.boolean().optional()
2234
+ })
2235
+ ).optional()
2236
+ });
2237
+ var fileVerificationConfigSchema = z3.object({
2238
+ enabled: z3.boolean(),
2239
+ documentTypes: z3.array(documentTypeConfigSchema),
2240
+ autoExtract: z3.boolean().optional(),
2241
+ autoValidate: z3.boolean().optional()
2242
+ });
2243
+ var textConfigSchema = baseConfigSchema.extend({
2244
+ minLength: z3.number().int().min(0).optional(),
2245
+ maxLength: z3.number().int().min(1).optional(),
2246
+ pattern: z3.string().optional()
2247
+ });
2248
+ var textareaConfigSchema = baseConfigSchema;
2249
+ var numberConfigSchema = baseConfigSchema.extend({
2250
+ min: z3.number().optional(),
2251
+ max: z3.number().optional(),
2252
+ unit: z3.enum(["integer", "decimal", "percentage"]).optional(),
2253
+ decimals: z3.number().int().min(0).optional()
2254
+ });
2255
+ var checkboxConfigSchema = baseConfigSchema;
2256
+ var dateConfigSchema = baseConfigSchema.extend({
2257
+ dateFormat: z3.enum(["short", "long", "full", "relative"]).optional(),
2258
+ minDate: z3.string().optional(),
2259
+ maxDate: z3.string().optional()
2260
+ });
2261
+ var phoneConfigSchema = baseConfigSchema.extend({
2262
+ defaultCountryCode: z3.string().length(3).optional()
2263
+ });
2264
+ var currencyConfigSchema = baseConfigSchema.extend({
2265
+ defaultCurrency: z3.string().length(3).optional(),
2266
+ allowedCurrencies: z3.array(z3.string().length(3)).optional()
2267
+ });
2268
+ var statusConfigSchema = baseConfigSchema.extend({
2269
+ options: z3.array(optionSchema).min(1)
2270
+ });
2271
+ var locationConfigSchema = baseConfigSchema.extend({
2272
+ granularity: z3.enum(["full", "address", "city", "state", "country", "coordinates"]),
2273
+ enableAutocomplete: z3.boolean().optional(),
2274
+ enableMap: z3.boolean().optional(),
2275
+ defaultCountry: z3.string().length(3).optional(),
2276
+ allowedCountries: z3.array(z3.string().length(3)).optional(),
2277
+ displayFormat: z3.enum(["single_line", "multi_line", "compact"]).optional()
2278
+ });
2279
+ var timestampConfigSchema = baseConfigSchema.extend({
2280
+ autoUpdate: z3.boolean().optional()
2281
+ });
2282
+ var selectConfigSchema = baseConfigSchema.extend({
2283
+ options: z3.array(optionSchema).min(1)
2284
+ });
2285
+ var multiselectConfigSchema = baseConfigSchema.extend({
2286
+ options: z3.array(optionSchema).min(1)
2287
+ });
2288
+ var fileConfigSchema = baseConfigSchema.extend({
2289
+ maxFiles: z3.number().int().min(1).optional(),
2290
+ maxSize: z3.number().int().min(1).optional(),
2291
+ allowedTypes: z3.array(z3.string()).optional(),
2292
+ verification: fileVerificationConfigSchema.optional()
2293
+ });
2294
+ var userConfigSchema = baseConfigSchema.extend({
2295
+ allowedRoles: z3.array(z3.string()).optional()
2296
+ });
2297
+ var relationConfigSchema = baseConfigSchema.extend({
2298
+ targets: z3.array(relationTargetSchema).min(1),
2299
+ onDelete: z3.enum(["restrict", "cascade", "set_null"]).optional(),
2300
+ cardinality: z3.enum(["one", "many"]),
2301
+ minItems: z3.number().int().min(0).optional(),
2302
+ maxItems: z3.number().int().min(1).optional()
2303
+ });
2304
+ var ratingConfigSchema = baseConfigSchema.extend({
2305
+ max: z3.number().int().min(1).optional(),
2306
+ iconType: z3.enum(["star", "heart", "thumbs", "number"]).optional()
2307
+ });
2308
+ var attributeConfigSchemas = {
2309
+ text: textConfigSchema,
2310
+ textarea: textareaConfigSchema,
2311
+ number: numberConfigSchema,
2312
+ checkbox: checkboxConfigSchema,
2313
+ date: dateConfigSchema,
2314
+ phone: phoneConfigSchema,
2315
+ currency: currencyConfigSchema,
2316
+ status: statusConfigSchema,
2317
+ location: locationConfigSchema,
2318
+ timestamp: timestampConfigSchema,
2319
+ select: selectConfigSchema,
2320
+ multiselect: multiselectConfigSchema,
2321
+ file: fileConfigSchema,
2322
+ user: userConfigSchema,
2323
+ relation: relationConfigSchema,
2324
+ rating: ratingConfigSchema
2325
+ };
2326
+ function getAttributeConfigSchema(type) {
2327
+ return attributeConfigSchemas[type];
2328
+ }
2329
+ function validateAttributeConfig(type, config) {
2330
+ const schema = getAttributeConfigSchema(type);
2331
+ const result = schema.safeParse(config);
2332
+ if (result.success) {
2333
+ return { success: true, data: result.data };
2334
+ }
2335
+ return {
2336
+ success: false,
2337
+ errors: result.error.errors.map((err) => `${err.path.join(".")}: ${err.message}`)
2338
+ };
2339
+ }
2340
+ function parseAttributeConfig(type, config) {
2341
+ const schema = getAttributeConfigSchema(type);
2342
+ return schema.strip().parse(config);
2343
+ }
2344
+ function safeParseAttributeConfig(type, config) {
2345
+ const schema = getAttributeConfigSchema(type);
2346
+ const result = schema.strip().safeParse(config);
2347
+ return result.success ? result.data : void 0;
2348
+ }
2349
+ function createTextValidator(attr) {
2350
+ let schema = z3.string();
2351
+ if (attr.minLength !== void 0) {
2352
+ schema = schema.min(
2353
+ attr.minLength,
2354
+ `${attr.label} must be at least ${attr.minLength} characters`
2355
+ );
2356
+ }
2357
+ if (attr.maxLength !== void 0) {
2358
+ schema = schema.max(
2359
+ attr.maxLength,
2360
+ `${attr.label} must be at most ${attr.maxLength} characters`
2361
+ );
2362
+ }
2363
+ if (attr.pattern) {
2364
+ schema = schema.regex(new RegExp(attr.pattern), `${attr.label} format is invalid`);
2365
+ }
2366
+ return schema;
2367
+ }
2368
+ function createNumberValidator(attr) {
2369
+ let schema = z3.number();
2370
+ if (attr.min !== void 0) {
2371
+ schema = schema.min(attr.min, `${attr.label} must be at least ${attr.min}`);
2372
+ }
2373
+ if (attr.max !== void 0) {
2374
+ schema = schema.max(attr.max, `${attr.label} must be at most ${attr.max}`);
2375
+ }
2376
+ if (attr.unit === "integer") {
2377
+ schema = schema.int(`${attr.label} must be an integer`);
2378
+ }
2379
+ return schema;
2380
+ }
2381
+ function createCheckboxValidator(_attr) {
2382
+ return z3.boolean();
2383
+ }
2384
+ function createDateValidator(attr) {
2385
+ return z3.string().datetime({ message: `${attr.label} must be a valid ISO date` });
2386
+ }
2387
+ function createPhoneValidator(_attr) {
2388
+ return z3.object({
2389
+ countryCode: z3.string().length(3),
2390
+ phoneNumber: z3.string().min(1)
2391
+ });
2392
+ }
2393
+ function createCurrencyValidator(_attr) {
2394
+ return z3.object({
2395
+ code: z3.string().length(3),
2396
+ value: z3.number().min(0)
2397
+ });
2398
+ }
2399
+ function createStatusValidator(attr) {
2400
+ const validValues = attr.options.map((opt) => opt.value);
2401
+ return z3.enum(validValues, {
2402
+ errorMap: () => ({
2403
+ message: `${attr.label} must be one of: ${validValues.join(", ")}`
2404
+ })
2405
+ });
2406
+ }
2407
+ function createSelectValidator(attr) {
2408
+ const validValues = attr.options.map((opt) => opt.value);
2409
+ return z3.enum(validValues, {
2410
+ errorMap: () => ({
2411
+ message: `${attr.label} must be one of: ${validValues.join(", ")}`
2412
+ })
2413
+ });
2414
+ }
2415
+ function createMultiselectValidator(attr) {
2416
+ const validValues = attr.options.map((opt) => opt.value);
2417
+ return z3.array(
2418
+ z3.enum(validValues, {
2419
+ errorMap: () => ({
2420
+ message: `Each value must be one of: ${validValues.join(", ")}`
2421
+ })
2422
+ })
2423
+ );
2424
+ }
2425
+ function createLocationValidator(_attr) {
2426
+ return z3.object({
2427
+ address: z3.string().optional(),
2428
+ address2: z3.string().optional(),
2429
+ city: z3.string().optional(),
2430
+ state: z3.string().optional(),
2431
+ postalCode: z3.string().optional(),
2432
+ country: z3.string().length(3).optional(),
2433
+ latitude: z3.number().optional(),
2434
+ longitude: z3.number().optional()
2435
+ });
2436
+ }
2437
+ function createTimestampValidator(_attr) {
2438
+ return z3.number().int().positive();
2439
+ }
2440
+ function createFileValidator(_attr) {
2441
+ return z3.string().uuid();
2442
+ }
2443
+ function createUserValidator(_attr) {
2444
+ return z3.string().uuid();
2445
+ }
2446
+ function createSingleRelationValidator(attr) {
2447
+ const uuidSchema = z3.string().uuid({
2448
+ message: `${attr.label} must be a valid record ID`
2449
+ });
2450
+ return z3.union([uuidSchema, z3.null()]);
2451
+ }
2452
+ function createMultiRelationValidator(attr) {
2453
+ const uuidSchema = z3.string().uuid({
2454
+ message: `Each ${attr.label} item must be a valid record ID`
2455
+ });
2456
+ let arraySchema = z3.array(uuidSchema);
2457
+ if (attr.minItems !== void 0) {
2458
+ arraySchema = arraySchema.min(
2459
+ attr.minItems,
2460
+ `${attr.label} must have at least ${attr.minItems} item${attr.minItems > 1 ? "s" : ""}`
2461
+ );
2462
+ }
2463
+ if (attr.maxItems !== void 0) {
2464
+ arraySchema = arraySchema.max(
2465
+ attr.maxItems,
2466
+ `${attr.label} must have at most ${attr.maxItems} item${attr.maxItems > 1 ? "s" : ""}`
2467
+ );
2468
+ }
2469
+ return arraySchema;
2470
+ }
2471
+ function createRelationValidator(attr) {
2472
+ if (attr.cardinality === "many") {
2473
+ return createMultiRelationValidator(attr);
2474
+ }
2475
+ return createSingleRelationValidator(attr);
2476
+ }
2477
+ function createRatingValidator(attr) {
2478
+ let schema = z3.number().int().min(0);
2479
+ if (attr.max !== void 0) {
2480
+ schema = schema.max(attr.max, `${attr.label} must be at most ${attr.max}`);
2481
+ }
2482
+ return schema;
2483
+ }
2484
+ function createAttributeValidator(attr) {
2485
+ switch (attr.type) {
2486
+ case "text":
2487
+ return createTextValidator(attr);
2488
+ case "number":
2489
+ return createNumberValidator(attr);
2490
+ case "checkbox":
2491
+ return createCheckboxValidator(attr);
2492
+ case "date":
2493
+ return createDateValidator(attr);
2494
+ case "phone":
2495
+ return createPhoneValidator(attr);
2496
+ case "currency":
2497
+ return createCurrencyValidator(attr);
2498
+ case "status":
2499
+ return createStatusValidator(attr);
2500
+ case "location":
2501
+ return createLocationValidator(attr);
2502
+ case "timestamp":
2503
+ return createTimestampValidator(attr);
2504
+ case "select":
2505
+ return createSelectValidator(attr);
2506
+ case "multiselect":
2507
+ return createMultiselectValidator(attr);
2508
+ case "file":
2509
+ return createFileValidator(attr);
2510
+ case "user":
2511
+ return createUserValidator(attr);
2512
+ case "relation":
2513
+ return createRelationValidator(attr);
2514
+ case "rating":
2515
+ return createRatingValidator(attr);
2516
+ default:
2517
+ return z3.unknown();
2518
+ }
2519
+ }
2520
+ function createObjectValidator(objectDef) {
2521
+ const shape = {};
2522
+ for (const attr of objectDef.attributes) {
2523
+ let validator = createAttributeValidator(attr);
2524
+ if (!attr.required) {
2525
+ validator = validator.optional();
2526
+ }
2527
+ shape[attr.name] = validator;
2528
+ }
2529
+ return z3.object(shape);
2530
+ }
2531
+ function validateAttribute(attr, value) {
2532
+ const validator = createAttributeValidator(attr);
2533
+ if (!attr.required && (value === void 0 || value === null)) {
2534
+ return { success: true, data: { [attr.name]: value } };
2535
+ }
2536
+ const result = validator.safeParse(value);
2537
+ if (result.success) {
2538
+ return {
2539
+ success: true,
2540
+ data: { [attr.name]: result.data }
2541
+ };
2542
+ }
2543
+ return {
2544
+ success: false,
2545
+ errors: result.error.errors.map((err) => ({
2546
+ path: [attr.name, ...err.path.map(String)],
2547
+ message: err.message
2548
+ }))
2549
+ };
2550
+ }
2551
+ function validateObject(objectDef, data) {
2552
+ const validator = createObjectValidator(objectDef);
2553
+ const result = validator.safeParse(data);
2554
+ if (result.success) {
2555
+ return {
2556
+ success: true,
2557
+ data: result.data
2558
+ };
2559
+ }
2560
+ return {
2561
+ success: false,
2562
+ errors: result.error.errors.map((err) => ({
2563
+ path: err.path.map(String),
2564
+ message: err.message
2565
+ }))
2566
+ };
2567
+ }
2568
+ function validateObjectOrThrow(objectDef, data) {
2569
+ const result = validateObject(objectDef, data);
2570
+ if (!result.success) {
2571
+ const errorMessages = result.errors?.map((err) => `${err.path.join(".")}: ${err.message}`).join("\n") || "Unknown validation error";
2572
+ throw new Error(`Validation failed for ${objectDef.label}:
2573
+ ${errorMessages}`);
2574
+ }
2575
+ return result.data;
2576
+ }
2577
+ function createDraftValidator(objectDef) {
2578
+ const shape = {};
2579
+ for (const attr of objectDef.attributes) {
2580
+ const validator = createAttributeValidator(attr).optional();
2581
+ shape[attr.name] = validator;
2582
+ }
2583
+ return z3.object(shape);
2584
+ }
2585
+ function validateDraft(objectDef, data) {
2586
+ const validator = createDraftValidator(objectDef);
2587
+ const result = validator.safeParse(data);
2588
+ if (result.success) {
2589
+ return {
2590
+ success: true,
2591
+ data: result.data
2592
+ };
2593
+ }
2594
+ return {
2595
+ success: false,
2596
+ errors: result.error.errors.map((err) => ({
2597
+ path: err.path.map(String),
2598
+ message: err.message
2599
+ }))
2600
+ };
2601
+ }
2602
+ function validateDraftOrThrow(objectDef, data) {
2603
+ const result = validateDraft(objectDef, data);
2604
+ if (!result.success) {
2605
+ const errorMessages = result.errors?.map((err) => `${err.path.join(".")}: ${err.message}`).join("\n") || "Unknown validation error";
2606
+ throw new Error(`Draft validation failed for ${objectDef.label}:
2607
+ ${errorMessages}`);
2608
+ }
2609
+ return result.data;
2610
+ }
2611
+ function isValuePresent(value) {
2612
+ if (value === void 0 || value === null) {
2613
+ return false;
2614
+ }
2615
+ if (typeof value === "string" && value.trim() === "") {
2616
+ return false;
2617
+ }
2618
+ return true;
2619
+ }
2620
+ function getMissingRequiredAttributes(objectDef, data) {
2621
+ const missing = [];
2622
+ for (const attr of objectDef.attributes) {
2623
+ if (attr.required && !isValuePresent(data[attr.name])) {
2624
+ missing.push(attr);
2625
+ }
2626
+ }
2627
+ return missing;
2628
+ }
2629
+ function isRecordComplete(objectDef, data) {
2630
+ const missing = getMissingRequiredAttributes(objectDef, data);
2631
+ if (missing.length > 0) {
2632
+ return false;
2633
+ }
2634
+ const validation = validateObject(objectDef, data);
2635
+ return validation.success;
2636
+ }
2637
+ function computeRecordStatus(objectDef, data) {
2638
+ return isRecordComplete(objectDef, data) ? "complete" : "draft";
2639
+ }
2640
+
2641
+ // src/runtime/services/object-schema.service.ts
2642
+ var ObjectSchemaService = class {
2643
+ constructor(adapter, nativeRegistry) {
2644
+ this.adapter = adapter;
2645
+ this.nativeRegistry = nativeRegistry;
2646
+ }
2647
+ /**
2648
+ * Create a new custom object
2649
+ * Validates name format and ensures system=false
2650
+ *
2651
+ * @param definition - Object definition (attributes can be raw definitions or builders)
2652
+ * @param tenantId - Tenant ID owning the object
2653
+ * @returns Created ObjectDefinition
2654
+ */
2655
+ async createCustomObject(definition, tenantId) {
2656
+ const builder = object({
2657
+ name: definition.name,
2658
+ label: definition.label
2659
+ });
2660
+ if (definition.pluralLabel) builder.pluralLabel(definition.pluralLabel);
2661
+ if (definition.description) builder.description(definition.description);
2662
+ if (definition.icon) builder.icon(definition.icon);
2663
+ if (definition.metadata) builder.metadata(definition.metadata);
2664
+ builder.labelExpression(definition.labelExpression);
2665
+ if (definition.attributes && definition.attributes.length > 0) {
2666
+ builder.attributes(definition.attributes);
2667
+ }
2668
+ const objectDef = builder.build();
2669
+ const existing = await this.adapter.objects.findByName(tenantId, objectDef.name);
2670
+ if (existing) {
2671
+ throw new Error(`Object with name "${objectDef.name}" already exists`);
2672
+ }
2673
+ const validatedConfigs = [];
2674
+ if (objectDef.attributes.length > 0) {
2675
+ for (const attr of objectDef.attributes) {
2676
+ const config = await this.validateAttributeInput(
2677
+ attr,
2678
+ tenantId
2679
+ );
2680
+ validatedConfigs.push(config);
2681
+ }
2682
+ }
2683
+ const metadata = {
2684
+ ...objectDef.metadata,
2685
+ icon: objectDef.icon
2686
+ };
2687
+ const dbObject = await this.adapter.objects.create({
2688
+ tenantId,
2689
+ name: objectDef.name,
2690
+ label: objectDef.label,
2691
+ pluralLabel: objectDef.pluralLabel,
2692
+ description: objectDef.description,
2693
+ labelExpression: objectDef.labelExpression,
2694
+ system: false,
2695
+ // Always false for custom objects
2696
+ metadata
2697
+ });
2698
+ const createdAttributes = [];
2699
+ if (objectDef.attributes.length > 0) {
2700
+ for (let i = 0; i < objectDef.attributes.length; i++) {
2701
+ const attr = objectDef.attributes[i];
2702
+ const config = validatedConfigs[i];
2703
+ const dbAttr = await this.adapter.attributes.create({
2704
+ objectId: dbObject.id,
2705
+ name: attr.name,
2706
+ label: attr.label,
2707
+ type: attr.type,
2708
+ required: attr.required ?? false,
2709
+ unique: false,
2710
+ system: false,
2711
+ config
2712
+ });
2713
+ createdAttributes.push(this.convertDBAttributeToAttribute(dbAttr));
2714
+ }
2715
+ }
2716
+ return {
2717
+ ...objectDef,
2718
+ id: dbObject.id,
2719
+ attributes: createdAttributes,
2720
+ system: false
2721
+ };
2722
+ }
2723
+ /**
2724
+ * Add a custom attribute to an existing object
2725
+ * Can be used on both custom and native objects
2726
+ * Attributes added via API are always custom (system=false)
2727
+ *
2728
+ * @param objectId - Object UUID from database
2729
+ * @param attribute - Attribute definition
2730
+ * @param tenantId - Tenant ID (required for relation validation)
2731
+ * @returns Created Attribute
2732
+ */
2733
+ async addAttributeToObject(objectId, attribute, tenantId) {
2734
+ const dbObject = await this.adapter.objects.findById(objectId);
2735
+ if (!dbObject) {
2736
+ throw new Error(`Object with id "${objectId}" not found`);
2737
+ }
2738
+ const existingAttributes = await this.adapter.attributes.findByObjectId(objectId);
2739
+ const duplicate = existingAttributes.find((attr) => attr.name === attribute.name);
2740
+ if (duplicate) {
2741
+ throw new Error(
2742
+ `Attribute with name "${attribute.name}" already exists on object "${dbObject.name}"`
2743
+ );
2744
+ }
2745
+ const config = await this.validateAttributeInput(attribute, tenantId);
2746
+ const dbAttr = await this.adapter.attributes.create({
2747
+ objectId,
2748
+ name: attribute.name,
2749
+ label: attribute.label,
2750
+ type: attribute.type,
2751
+ required: attribute.required ?? false,
2752
+ unique: attribute.unique ?? false,
2753
+ system: false,
2754
+ // Always false for attributes added via API
2755
+ config
2756
+ });
2757
+ return this.convertDBAttributeToAttribute(dbAttr);
2758
+ }
2759
+ /**
2760
+ * Update an attribute
2761
+ * Can only update custom attributes (system=false)
2762
+ *
2763
+ * @param attributeId - Attribute UUID
2764
+ * @param updates - Partial attribute updates
2765
+ * @param tenantId - Tenant ID (required for relation validation)
2766
+ * @returns Updated Attribute
2767
+ */
2768
+ async updateAttribute(attributeId, updates, tenantId) {
2769
+ const dbAttr = await this.adapter.attributes.findById(attributeId);
2770
+ if (!dbAttr) {
2771
+ throw new Error(`Attribute with id "${attributeId}" not found`);
2772
+ }
2773
+ if (dbAttr.system) {
2774
+ throw new Error(
2775
+ `Cannot modify system attribute "${dbAttr.name}". System attributes are protected.`
2776
+ );
2777
+ }
2778
+ if (updates.name && updates.name !== dbAttr.name) {
2779
+ throw new Error(
2780
+ "Attribute name cannot be changed after creation. Create a new attribute instead."
2781
+ );
2782
+ }
2783
+ if (updates.type && updates.type !== dbAttr.type) {
2784
+ throw new Error(
2785
+ "Attribute type cannot be changed after creation. Create a new attribute instead."
2786
+ );
2787
+ }
2788
+ const mergedInput = {
2789
+ name: dbAttr.name,
2790
+ label: updates.label ?? dbAttr.label,
2791
+ type: dbAttr.type,
2792
+ required: updates.required ?? dbAttr.required,
2793
+ ...dbAttr.config,
2794
+ ...updates
2795
+ };
2796
+ const config = this.buildAttributeConfig(mergedInput);
2797
+ if (dbAttr.type === "relation" && updates.targets) {
2798
+ await this.validateRelationTargets(mergedInput, tenantId);
2799
+ }
2800
+ const updatedDbAttr = await this.adapter.attributes.update(attributeId, {
2801
+ label: updates.label,
2802
+ required: updates.required,
2803
+ config
2804
+ });
2805
+ return this.convertDBAttributeToAttribute(updatedDbAttr);
2806
+ }
2807
+ /**
2808
+ * Delete an attribute
2809
+ * Can only delete custom attributes (system=false)
2810
+ *
2811
+ * @param attributeId - Attribute UUID
2812
+ */
2813
+ async deleteAttribute(attributeId) {
2814
+ const dbAttr = await this.adapter.attributes.findById(attributeId);
2815
+ if (!dbAttr) {
2816
+ throw new Error(`Attribute with id "${attributeId}" not found`);
2817
+ }
2818
+ if (dbAttr.system) {
2819
+ throw new Error(
2820
+ `Cannot delete system attribute "${dbAttr.name}". System attributes are protected.`
2821
+ );
2822
+ }
2823
+ await this.adapter.attributes.delete(attributeId);
2824
+ }
2825
+ /**
2826
+ * List attributes for an object
2827
+ *
2828
+ * @param objectId - Object UUID
2829
+ * @param options - Filter options
2830
+ * @returns List of attributes
2831
+ */
2832
+ async listAttributes(objectId, options) {
2833
+ const dbAttributes = await this.adapter.attributes.findByObjectId(objectId);
2834
+ let filtered = dbAttributes;
2835
+ if (options?.systemOnly) {
2836
+ filtered = dbAttributes.filter((attr) => attr.system);
2837
+ } else if (options?.customOnly) {
2838
+ filtered = dbAttributes.filter((attr) => !attr.system);
2839
+ }
2840
+ return filtered.map((attr) => this.convertDBAttributeToAttribute(attr));
2841
+ }
2842
+ /**
2843
+ * Update a custom object
2844
+ * Can only update custom objects (system=false)
2845
+ *
2846
+ * @param objectId - Object UUID
2847
+ * @param updates - Partial object updates
2848
+ * @returns Updated ObjectDefinition
2849
+ *
2850
+ * @example
2851
+ * ```typescript
2852
+ * const updated = await service.updateObject("obj-123", {
2853
+ * label: "Updated Label",
2854
+ * description: "New description",
2855
+ * });
2856
+ * ```
2857
+ */
2858
+ async updateObject(objectId, updates) {
2859
+ const dbObject = await this.adapter.objects.findById(objectId);
2860
+ if (!dbObject) {
2861
+ throw new Error(`Object with id "${objectId}" not found`);
2862
+ }
2863
+ if (dbObject.system) {
2864
+ throw new Error(
2865
+ `Cannot modify system object "${dbObject.name}". System objects are protected.`
2866
+ );
2867
+ }
2868
+ let metadata = dbObject.metadata;
2869
+ if (updates.icon !== void 0 || updates.metadata !== void 0) {
2870
+ metadata = {
2871
+ ...dbObject.metadata,
2872
+ ...updates.metadata,
2873
+ icon: updates.icon ?? dbObject.metadata?.icon
2874
+ };
2875
+ }
2876
+ const updatedDbObject = await this.adapter.objects.update(objectId, {
2877
+ label: updates.label,
2878
+ pluralLabel: updates.pluralLabel,
2879
+ description: updates.description,
2880
+ labelExpression: updates.labelExpression,
2881
+ metadata
2882
+ });
2883
+ const dbAttributes = await this.adapter.attributes.findByObjectId(objectId);
2884
+ return this.convertDBObjectToDefinition(updatedDbObject, dbAttributes);
2885
+ }
2886
+ /**
2887
+ * Delete a custom object
2888
+ * Can only delete custom objects (system=false)
2889
+ * This will also delete all associated attributes and records
2890
+ *
2891
+ * @param objectId - Object UUID
2892
+ *
2893
+ * @example
2894
+ * ```typescript
2895
+ * await service.deleteObject("obj-123");
2896
+ * ```
2897
+ */
2898
+ async deleteObject(objectId) {
2899
+ const dbObject = await this.adapter.objects.findById(objectId);
2900
+ if (!dbObject) {
2901
+ throw new Error(`Object with id "${objectId}" not found`);
2902
+ }
2903
+ if (dbObject.system) {
2904
+ throw new Error(
2905
+ `Cannot delete system object "${dbObject.name}". System objects are protected.`
2906
+ );
2907
+ }
2908
+ await this.adapter.objects.delete(objectId);
2909
+ }
2910
+ /**
2911
+ * Validate attribute name format (variable identifier)
2912
+ * @internal
2913
+ */
2914
+ validateAttributeName(name) {
2915
+ const variableNameRegex = /^[a-zA-Z_][a-zA-Z0-9_]*$/;
2916
+ if (!name || name.length === 0) {
2917
+ throw new Error("Attribute name cannot be empty");
2918
+ }
2919
+ if (name.length > 63) {
2920
+ throw new Error("Attribute name is too long (max 63 characters)");
2921
+ }
2922
+ if (!variableNameRegex.test(name)) {
2923
+ throw new Error(
2924
+ "Invalid attribute name format.\nName must be a valid variable identifier:\n \u2705 Valid: 'firstName', 'first_name', 'FirstName', 'FIRST_NAME'\n \u274C Invalid: 'first-name', 'first name', '123name', 'first.name'"
2925
+ );
2926
+ }
2927
+ }
2928
+ /**
2929
+ * Get complete object schema (system + custom attributes)
2930
+ * If object is native, merges registry definition with DB custom attributes
2931
+ * If object is custom, returns DB definition only
2932
+ *
2933
+ * @param objectId - Object UUID from database
2934
+ * @returns Complete ObjectDefinition with all attributes
2935
+ *
2936
+ * @example
2937
+ * ```typescript
2938
+ * const service = new ObjectSchemaService(adapter, registry);
2939
+ * const productSchema = await service.getObjectSchema("obj-123");
2940
+ *
2941
+ * console.log(productSchema.attributes); // System + custom attributes
2942
+ * ```
2943
+ */
2944
+ async getObjectSchema(objectId) {
2945
+ const dbObject = await this.adapter.objects.findById(objectId);
2946
+ if (!dbObject) {
2947
+ throw new Error(`Object with id "${objectId}" not found`);
2948
+ }
2949
+ const dbAttributes = await this.adapter.attributes.findByObjectId(objectId);
2950
+ if (dbObject.system) {
2951
+ return this.mergeNativeObject(dbObject, dbAttributes);
2952
+ }
2953
+ return this.convertDBObjectToDefinition(dbObject, dbAttributes);
2954
+ }
2955
+ /**
2956
+ * Get object schema by name (for system/native objects)
2957
+ * @deprecated Use getObjectSchemaByNameForTenant for custom objects support
2958
+ */
2959
+ async getObjectSchemaByName(name) {
2960
+ const dbObject = await this.adapter.objects.findSystemByName(name);
2961
+ if (!dbObject) {
2962
+ throw new Error(`Native object "${name}" not found in database`);
2963
+ }
2964
+ const dbAttributes = await this.adapter.attributes.findByObjectId(dbObject.id);
2965
+ return this.mergeNativeObject(dbObject, dbAttributes);
2966
+ }
2967
+ /**
2968
+ * Get object schema by name for a tenant (supports both native and custom objects)
2969
+ */
2970
+ async getObjectSchemaByNameForTenant(name, tenantId) {
2971
+ let dbObject = await this.adapter.objects.findByName(tenantId, name);
2972
+ if (!dbObject) {
2973
+ dbObject = await this.adapter.objects.findSystemByName(name);
2974
+ }
2975
+ if (!dbObject) {
2976
+ throw new Error(`Object "${name}" not found`);
2977
+ }
2978
+ const dbAttributes = await this.adapter.attributes.findByObjectId(dbObject.id);
2979
+ if (dbObject.system) {
2980
+ return this.mergeNativeObject(dbObject, dbAttributes);
2981
+ }
2982
+ return this.convertDBObjectToDefinition(dbObject, dbAttributes);
2983
+ }
2984
+ /**
2985
+ * List all object schemas for a tenant
2986
+ */
2987
+ async listObjectSchemas(tenantId) {
2988
+ const dbObjects = await this.adapter.objects.list(tenantId);
2989
+ const schemas = await Promise.all(
2990
+ dbObjects.map(async (dbObject) => {
2991
+ const dbAttributes = await this.adapter.attributes.findByObjectId(dbObject.id);
2992
+ if (dbObject.system) {
2993
+ return this.mergeNativeObject(dbObject, dbAttributes);
2994
+ }
2995
+ return this.convertDBObjectToDefinition(dbObject, dbAttributes);
2996
+ })
2997
+ );
2998
+ return schemas;
2999
+ }
3000
+ /**
3001
+ * Merge native object from registry with custom attributes from DB
3002
+ * @internal
3003
+ */
3004
+ mergeNativeObject(dbObject, dbAttributes) {
3005
+ const nativeObject = this.nativeRegistry.getByName(dbObject.name);
3006
+ if (!nativeObject) {
3007
+ throw new Error(
3008
+ `Native object "${dbObject.name}" not found in registry. Make sure to register it before querying.`
3009
+ );
3010
+ }
3011
+ const systemAttributesFromDB = dbAttributes.filter((attr) => attr.system);
3012
+ const customAttributes = dbAttributes.filter((attr) => !attr.system);
3013
+ const dbAttrByName = new Map(systemAttributesFromDB.map((attr) => [attr.name, attr]));
3014
+ const systemAttrs = nativeObject.attributes.map((registryAttr) => {
3015
+ const dbAttr = dbAttrByName.get(registryAttr.name);
3016
+ if (dbAttr) {
3017
+ return {
3018
+ ...registryAttr,
3019
+ id: dbAttr.id
3020
+ };
3021
+ }
3022
+ return registryAttr;
3023
+ });
3024
+ const customAttrs = customAttributes.map(
3025
+ (dbAttr) => this.convertDBAttributeToAttribute(dbAttr)
3026
+ );
3027
+ return {
3028
+ ...nativeObject,
3029
+ id: dbObject.id,
3030
+ attributes: [
3031
+ ...systemAttrs,
3032
+ // System attributes from registry (with DB IDs if synced)
3033
+ ...customAttrs
3034
+ // Custom attributes from DB
3035
+ ]
3036
+ };
3037
+ }
3038
+ /**
3039
+ * Convert DB object + attributes to ObjectDefinition
3040
+ * @internal
3041
+ */
3042
+ convertDBObjectToDefinition(dbObject, dbAttributes) {
3043
+ const attributes = dbAttributes.map(
3044
+ (dbAttr) => this.convertDBAttributeToAttribute(dbAttr)
3045
+ );
3046
+ return {
3047
+ id: dbObject.id,
3048
+ name: dbObject.name,
3049
+ label: dbObject.label,
3050
+ pluralLabel: dbObject.pluralLabel,
3051
+ description: dbObject.description,
3052
+ icon: dbObject.metadata?.icon,
3053
+ labelExpression: dbObject.labelExpression,
3054
+ attributes,
3055
+ system: dbObject.system,
3056
+ metadata: dbObject.metadata
3057
+ };
3058
+ }
3059
+ /**
3060
+ * Validate attribute input and return parsed config
3061
+ * Validates: name format, config schema, relation targets
3062
+ * @internal
3063
+ */
3064
+ async validateAttributeInput(attribute, tenantId) {
3065
+ this.validateAttributeName(attribute.name);
3066
+ const config = this.buildAttributeConfig(attribute);
3067
+ if (attribute.type === "relation") {
3068
+ await this.validateRelationTargets(attribute, tenantId);
3069
+ }
3070
+ return config;
3071
+ }
3072
+ /**
3073
+ * Build and validate attribute config from input
3074
+ * Uses Zod schema to validate and strip unknown properties
3075
+ * @internal
3076
+ */
3077
+ buildAttributeConfig(attribute) {
3078
+ const {
3079
+ name: _,
3080
+ label: __,
3081
+ type: ___,
3082
+ required: ____,
3083
+ unique: _____,
3084
+ ...configInput
3085
+ } = attribute;
3086
+ try {
3087
+ return parseAttributeConfig(attribute.type, configInput);
3088
+ } catch (error) {
3089
+ if (error instanceof Error) {
3090
+ throw new Error(`Invalid config for ${attribute.type} attribute: ${error.message}`);
3091
+ }
3092
+ throw error;
3093
+ }
3094
+ }
3095
+ /**
3096
+ * Validate that relation target objects exist
3097
+ * @internal
3098
+ */
3099
+ async validateRelationTargets(attribute, tenantId) {
3100
+ const targets = attribute.targets;
3101
+ if (!targets || targets.length === 0) {
3102
+ throw new Error("Relation attribute must have at least one target object");
3103
+ }
3104
+ const cardinality = attribute.cardinality;
3105
+ if (!(cardinality && ["one", "many"].includes(cardinality))) {
3106
+ throw new Error("Relation attribute must specify cardinality: 'one' or 'many'");
3107
+ }
3108
+ for (const target of targets) {
3109
+ if (!target.object) {
3110
+ throw new Error("Each relation target must specify an object name");
3111
+ }
3112
+ let targetObject = tenantId ? await this.adapter.objects.findByName(tenantId, target.object) : null;
3113
+ if (!targetObject) {
3114
+ targetObject = await this.adapter.objects.findSystemByName(target.object);
3115
+ }
3116
+ if (!targetObject) {
3117
+ const nativeObject = this.nativeRegistry.getByName(target.object);
3118
+ if (!nativeObject) {
3119
+ throw new Error(
3120
+ `Relation target object "${target.object}" does not exist. Make sure the object is created before adding a relation to it.`
3121
+ );
3122
+ }
3123
+ }
3124
+ }
3125
+ }
3126
+ /**
3127
+ * Convert DB attribute to Attribute type
3128
+ * @internal
3129
+ */
3130
+ convertDBAttributeToAttribute(dbAttr) {
3131
+ const baseAttr = {
3132
+ ...dbAttr.config,
3133
+ id: dbAttr.id,
3134
+ name: dbAttr.name,
3135
+ label: dbAttr.label,
3136
+ type: dbAttr.type,
3137
+ required: dbAttr.required,
3138
+ system: dbAttr.system,
3139
+ unique: dbAttr.unique
3140
+ };
3141
+ return baseAttr;
3142
+ }
3143
+ };
3144
+
3145
+ // src/native/registry.ts
3146
+ var NativeObjectRegistryClass = class {
3147
+ constructor() {
3148
+ this.objects = /* @__PURE__ */ new Map();
3149
+ }
3150
+ /**
3151
+ * Register one or more native objects
3152
+ * Auto-builds if ObjectBuilder is passed instead of ObjectDefinition
3153
+ * @param objects - Single object/builder or array of objects/builders to register
3154
+ * @returns this (for chaining)
3155
+ * @throws Error if object is invalid or already registered
3156
+ *
3157
+ * @example
3158
+ * ```typescript
3159
+ * // No .build() needed - registry auto-builds!
3160
+ * const PRODUCT = object({ id: "obj-product", name: "products", label: "Product" })
3161
+ * .system()
3162
+ * .attribute(text({ id: "attr-name", name: "name", label: "Name" }));
3163
+ *
3164
+ * registry.register(PRODUCT); // ← Auto-builds here
3165
+ *
3166
+ * // Can still explicitly .build() if you want
3167
+ * registry.register(PRODUCT.build());
3168
+ *
3169
+ * // Register multiple
3170
+ * registry.register([PRODUCT, ORDER, CUSTOMER]);
3171
+ * ```
3172
+ */
3173
+ register(objects) {
3174
+ const objectsArray = Array.isArray(objects) ? objects : [objects];
3175
+ for (const obj of objectsArray) {
3176
+ const object2 = "build" in obj && typeof obj.build === "function" ? obj.build() : obj;
3177
+ this.validateAndRegister(object2);
3178
+ }
3179
+ return this;
3180
+ }
3181
+ /**
3182
+ * Validate and register a single object
3183
+ * @internal
3184
+ */
3185
+ validateAndRegister(object2) {
3186
+ if (!object2.system) {
3187
+ throw new Error(
3188
+ `[NativeObjectRegistry] Cannot register object "${object2.name}" (id: ${object2.id}): missing system flag.
3189
+ Native objects must have system=true. Did you forget to call .system() in your builder?`
3190
+ );
3191
+ }
3192
+ if (this.objects.has(object2.name)) {
3193
+ const existing = this.objects.get(object2.name);
3194
+ throw new Error(
3195
+ `[NativeObjectRegistry] Duplicate object name "${object2.name}":
3196
+ - Existing: "${existing?.label}" (id: ${existing?.id})
3197
+ - New: "${object2.label}" (id: ${object2.id})
3198
+ Please use unique names for each native object.`
3199
+ );
3200
+ }
3201
+ this.objects.set(object2.name, object2);
3202
+ }
3203
+ /**
3204
+ * Get a native object by its name
3205
+ * @param name - The object name
3206
+ * @returns The object definition or undefined if not found
3207
+ *
3208
+ * @example
3209
+ * ```typescript
3210
+ * const product = registry.getByName("products");
3211
+ * if (product) {
3212
+ * console.log(product.label); // "Product"
3213
+ * }
3214
+ * ```
3215
+ */
3216
+ getByName(name) {
3217
+ return this.objects.get(name);
3218
+ }
3219
+ /**
3220
+ * Get a native object or throw if not found
3221
+ * @param name - The object name
3222
+ * @returns The object definition
3223
+ * @throws Error if not found
3224
+ */
3225
+ getByNameOrThrow(name) {
3226
+ const object2 = this.objects.get(name);
3227
+ if (!object2) {
3228
+ throw new Error(
3229
+ `[NativeObjectRegistry] Native object "${name}" not found.
3230
+ Available objects: ${this.listNames().join(", ")}`
3231
+ );
3232
+ }
3233
+ return object2;
3234
+ }
3235
+ /**
3236
+ * Get all registered native objects
3237
+ * @returns Array of all registered object definitions
3238
+ */
3239
+ getAll() {
3240
+ return Array.from(this.objects.values());
3241
+ }
3242
+ /**
3243
+ * Get all registered native object names
3244
+ * @returns Array of object names
3245
+ */
3246
+ listNames() {
3247
+ return Array.from(this.objects.keys());
3248
+ }
3249
+ /**
3250
+ * Check if a native object is registered
3251
+ * @param name - The object name
3252
+ * @returns true if registered, false otherwise
3253
+ */
3254
+ has(name) {
3255
+ return this.objects.has(name);
3256
+ }
3257
+ /**
3258
+ * Get the number of registered objects
3259
+ */
3260
+ get size() {
3261
+ return this.objects.size;
3262
+ }
3263
+ /**
3264
+ * Clear all registered objects (useful for testing)
3265
+ * @internal
3266
+ */
3267
+ clear() {
3268
+ this.objects.clear();
3269
+ }
3270
+ /**
3271
+ * Get registry summary for debugging
3272
+ */
3273
+ summary() {
3274
+ const objects = this.getAll();
3275
+ return [
3276
+ `[NativeObjectRegistry] ${this.size} native object(s) registered:`,
3277
+ ...objects.map(
3278
+ (obj) => ` - ${obj.name}: "${obj.label}" (${obj.attributes.length} attributes)`
3279
+ )
3280
+ ].join("\n");
3281
+ }
3282
+ /**
3283
+ * Log registry summary to console
3284
+ */
3285
+ debug() {
3286
+ console.info(this.summary());
3287
+ }
3288
+ };
3289
+ var registry = new NativeObjectRegistryClass();
3290
+
3291
+ // src/runtime/services/relation.service.ts
3292
+ var RelationService = class {
3293
+ constructor(adapter, nativeRegistry) {
3294
+ this.adapter = adapter;
3295
+ this.schemaService = new ObjectSchemaService(adapter, nativeRegistry);
3296
+ }
3297
+ /**
3298
+ * Validate all relation attributes in the data
3299
+ *
3300
+ * @param schema - Object schema containing attribute definitions
3301
+ * @param data - Record data to validate
3302
+ * @returns Validation result with errors if any
3303
+ *
3304
+ * @example
3305
+ * ```typescript
3306
+ * const result = await relationService.validateRelations(schema, {
3307
+ * company: "rec-123",
3308
+ * contacts: ["rec-456", "rec-789"]
3309
+ * });
3310
+ *
3311
+ * if (!result.valid) {
3312
+ * console.log(result.errors);
3313
+ * // [{ attribute: "company", message: "Record not found", invalidIds: ["rec-123"] }]
3314
+ * }
3315
+ * ```
3316
+ */
3317
+ async validateRelations(schema, data) {
3318
+ const errors = [];
3319
+ const relationAttrs = schema.attributes.filter(
3320
+ (attr) => attr.type === "relation"
3321
+ );
3322
+ for (const attr of relationAttrs) {
3323
+ const value = data[attr.name];
3324
+ if (value === void 0 || value === null) {
3325
+ continue;
3326
+ }
3327
+ const attrErrors = await this.validateRelationAttribute(attr, value);
3328
+ errors.push(...attrErrors);
3329
+ }
3330
+ return {
3331
+ valid: errors.length === 0,
3332
+ errors
3333
+ };
3334
+ }
3335
+ /**
3336
+ * Validate a single relation attribute value
3337
+ */
3338
+ async validateRelationAttribute(attr, value) {
3339
+ const errors = [];
3340
+ const ids = this.extractIds(attr, value);
3341
+ if (ids.length === 0) {
3342
+ return errors;
3343
+ }
3344
+ const validObjectIds = await this.getValidObjectIds(attr.targets);
3345
+ if (validObjectIds.size === 0) {
3346
+ errors.push({
3347
+ attribute: attr.name,
3348
+ message: `No valid target objects found for ${attr.label}`
3349
+ });
3350
+ return errors;
3351
+ }
3352
+ const invalidIds = [];
3353
+ for (const id of ids) {
3354
+ const record = await this.adapter.objectRecords.findById(id);
3355
+ if (!record) {
3356
+ invalidIds.push(id);
3357
+ continue;
3358
+ }
3359
+ if (!validObjectIds.has(record.objectId)) {
3360
+ invalidIds.push(id);
3361
+ }
3362
+ }
3363
+ if (invalidIds.length > 0) {
3364
+ errors.push({
3365
+ attribute: attr.name,
3366
+ message: `Invalid or non-existent records for ${attr.label}`,
3367
+ invalidIds
3368
+ });
3369
+ }
3370
+ return errors;
3371
+ }
3372
+ /**
3373
+ * Extract IDs from relation value based on cardinality
3374
+ */
3375
+ extractIds(attr, value) {
3376
+ if (attr.cardinality === "many") {
3377
+ if (!Array.isArray(value)) {
3378
+ return [];
3379
+ }
3380
+ return value.filter((v) => typeof v === "string");
3381
+ }
3382
+ if (typeof value === "string") {
3383
+ return [value];
3384
+ }
3385
+ return [];
3386
+ }
3387
+ /**
3388
+ * Get valid object IDs from relation targets
3389
+ */
3390
+ async getValidObjectIds(targets) {
3391
+ const objectIds = /* @__PURE__ */ new Set();
3392
+ for (const target of targets) {
3393
+ try {
3394
+ const objectSchema = await this.schemaService.getObjectSchemaByName(target.object);
3395
+ if (objectSchema?.id) {
3396
+ objectIds.add(objectSchema.id);
3397
+ }
3398
+ } catch {
3399
+ }
3400
+ }
3401
+ return objectIds;
3402
+ }
3403
+ /**
3404
+ * Validate relations and throw if invalid
3405
+ */
3406
+ async validateRelationsOrThrow(schema, data) {
3407
+ const result = await this.validateRelations(schema, data);
3408
+ if (!result.valid) {
3409
+ const messages = result.errors.map((e) => `${e.attribute}: ${e.message}`).join("; ");
3410
+ throw new Error(`Relation validation failed: ${messages}`);
3411
+ }
3412
+ }
3413
+ // ============================================================================
3414
+ // OPTIONS & RESOLUTION
3415
+ // ============================================================================
3416
+ /**
3417
+ * Get available options for a relation attribute
3418
+ * Searches across all target objects defined in the relation
3419
+ *
3420
+ * @param attribute - Relation attribute definition
3421
+ * @param tenantId - Tenant ID for multi-tenant isolation
3422
+ * @param params - Query parameters
3423
+ *
3424
+ * @example
3425
+ * ```typescript
3426
+ * const options = await relationService.getOptions(attribute, "tenant-1", {
3427
+ * query: "nike",
3428
+ * page: 1,
3429
+ * pageSize: 20
3430
+ * });
3431
+ * ```
3432
+ */
3433
+ async getOptions(attribute, tenantId, params = {}) {
3434
+ const { query = "", page = 1, pageSize = 20, targetObject } = params;
3435
+ const targets = attribute.targets;
3436
+ const filteredTargets = targetObject ? targets.filter((t) => t.object === targetObject) : targets;
3437
+ if (filteredTargets.length === 0) {
3438
+ return { options: [], hasMore: false, total: 0 };
3439
+ }
3440
+ const allOptions = [];
3441
+ let totalCount = 0;
3442
+ const recordService = new RecordService(this.adapter, tenantId);
3443
+ for (const target of filteredTargets) {
3444
+ const objectSchema = await this.schemaService.getObjectSchemaByName(target.object);
3445
+ if (!objectSchema?.id) {
3446
+ continue;
3447
+ }
3448
+ const result = query ? await recordService.searchRecords(objectSchema.id, query, {
3449
+ limit: pageSize,
3450
+ offset: (page - 1) * pageSize
3451
+ }) : await recordService.listRecords(objectSchema.id, {
3452
+ limit: pageSize,
3453
+ offset: (page - 1) * pageSize
3454
+ });
3455
+ totalCount += result.total;
3456
+ for (const record of result.records) {
3457
+ const template = target.displayTemplate || objectSchema.labelExpression;
3458
+ const label = renderLabelExpression(template, record.values);
3459
+ allOptions.push({
3460
+ id: record.id,
3461
+ objectId: objectSchema.id,
3462
+ objectName: objectSchema.name,
3463
+ objectLabel: objectSchema.label,
3464
+ objectIcon: objectSchema.icon,
3465
+ label,
3466
+ data: record.values
3467
+ });
3468
+ }
3469
+ }
3470
+ const hasMore = totalCount > page * pageSize;
3471
+ return {
3472
+ options: allOptions.slice(0, pageSize),
3473
+ hasMore,
3474
+ total: totalCount
3475
+ };
3476
+ }
3477
+ /**
3478
+ * Resolve record IDs to their display labels
3479
+ * Useful for displaying current values in the UI
3480
+ *
3481
+ * @param ids - Record IDs to resolve
3482
+ * @param tenantId - Tenant ID for multi-tenant isolation
3483
+ *
3484
+ * @example
3485
+ * ```typescript
3486
+ * const resolved = await relationService.resolveIds(["rec-1", "rec-2"], "tenant-1");
3487
+ * // [{ id: "rec-1", label: "Nike Air Max", objectName: "products", ... }]
3488
+ * ```
3489
+ */
3490
+ async resolveIds(ids, tenantId) {
3491
+ if (!ids || ids.length === 0) {
3492
+ return [];
3493
+ }
3494
+ const recordService = new RecordService(this.adapter, tenantId);
3495
+ const resolved = [];
3496
+ for (const id of ids) {
3497
+ const record = await recordService.getRecord(id);
3498
+ if (!record) {
3499
+ continue;
3500
+ }
3501
+ const objectSchema = await this.schemaService.getObjectSchema(record.objectId);
3502
+ if (!objectSchema) {
3503
+ continue;
3504
+ }
3505
+ const label = renderLabelExpression(objectSchema.labelExpression, record.values);
3506
+ resolved.push({
3507
+ id: record.id,
3508
+ objectId: record.objectId,
3509
+ objectName: objectSchema.name,
3510
+ objectLabel: objectSchema.label,
3511
+ objectIcon: objectSchema.icon,
3512
+ label,
3513
+ data: record.values
3514
+ });
3515
+ }
3516
+ return resolved;
3517
+ }
3518
+ /**
3519
+ * Find a relation attribute by ID
3520
+ */
3521
+ async findAttributeById(attributeId) {
3522
+ const attribute = await this.adapter.attributes.findById(attributeId);
3523
+ if (!attribute || attribute.type !== "relation") {
3524
+ return null;
3525
+ }
3526
+ return {
3527
+ ...attribute.config,
3528
+ ...attribute
3529
+ };
3530
+ }
3531
+ };
3532
+
3533
+ // src/runtime/services/record.service.ts
3534
+ var RecordService = class {
3535
+ constructor(adapter, tenantId, options) {
3536
+ this.adapter = adapter;
3537
+ this.tenantId = tenantId;
3538
+ this.schemaService = new ObjectSchemaService(adapter, registry);
3539
+ this.relationService = new RelationService(adapter, registry);
3540
+ this.hookRegistry = options?.hookRegistry ?? new NoopHookRegistry();
3541
+ }
3542
+ /**
3543
+ * Compute display label from schema expression
3544
+ * Automatically resolves relation attribute values to their labels
3545
+ * @internal
3546
+ */
3547
+ async computeLabel(schema, values) {
3548
+ const attrNames = extractAttributeNames(schema.labelExpression);
3549
+ const relationAttrs = schema.attributes.filter(
3550
+ (attr) => attr.type === "relation" && attrNames.includes(attr.name)
3551
+ );
3552
+ if (relationAttrs.length === 0) {
3553
+ return renderLabelExpression(schema.labelExpression, values);
3554
+ }
3555
+ const idsToResolve = [];
3556
+ for (const attr of relationAttrs) {
3557
+ const val = values[attr.name];
3558
+ if (typeof val === "string") {
3559
+ idsToResolve.push(val);
3560
+ } else if (Array.isArray(val) && typeof val[0] === "string") {
3561
+ idsToResolve.push(val[0]);
3562
+ }
3563
+ }
3564
+ if (idsToResolve.length === 0) {
3565
+ return renderLabelExpression(schema.labelExpression, values);
3566
+ }
3567
+ const resolved = await this.relationService.resolveIds(idsToResolve, this.tenantId);
3568
+ const resolvedMap = new Map(resolved.map((r) => [r.id, r.label]));
3569
+ const enrichedValues = { ...values };
3570
+ for (const attr of relationAttrs) {
3571
+ const val = values[attr.name];
3572
+ if (typeof val === "string" && resolvedMap.has(val)) {
3573
+ enrichedValues[attr.name] = resolvedMap.get(val);
3574
+ } else if (Array.isArray(val) && typeof val[0] === "string" && resolvedMap.has(val[0])) {
3575
+ enrichedValues[attr.name] = resolvedMap.get(val[0]);
3576
+ }
3577
+ }
3578
+ return renderLabelExpression(schema.labelExpression, enrichedValues);
3579
+ }
3580
+ /**
3581
+ * Create a new record with validation
3582
+ *
3583
+ * Triggers beforeCreate and afterCreate hooks if a HookRegistry is configured.
3584
+ *
3585
+ * @param objectId - Object UUID
3586
+ * @param data - Record data (attribute values)
3587
+ * @param options - Creation options
3588
+ * @returns Created record with computed completionStatus
3589
+ *
3590
+ * @example
3591
+ * ```typescript
3592
+ * const service = new RecordService(adapter, "tenant-123");
3593
+ *
3594
+ * // Create a complete record (strict validation)
3595
+ * const product = await service.createRecord("obj-product", {
3596
+ * name: "Nike Air Max",
3597
+ * price: 129.99,
3598
+ * status: "active"
3599
+ * });
3600
+ * // → product.completionStatus = "complete"
3601
+ *
3602
+ * // Create a draft record (allows missing required fields)
3603
+ * const draft = await service.createRecord("obj-product", {
3604
+ * name: "Draft Product"
3605
+ * }, { allowDraft: true });
3606
+ * // → draft.completionStatus = "draft"
3607
+ * ```
3608
+ */
3609
+ async createRecord(objectId, data, options) {
3610
+ const schema = await this.schemaService.getObjectSchema(objectId);
3611
+ const hookCtx = this.buildCreateHookContext(schema, data, options?.hookMetadata);
3612
+ if (!options?.skipHooks) {
3613
+ await this.hookRegistry.execute("beforeCreate", schema.name, hookCtx);
3614
+ }
3615
+ if (options?.validate !== false) {
3616
+ if (options?.allowDraft) {
3617
+ validateDraftOrThrow(schema, data);
3618
+ } else {
3619
+ validateObjectOrThrow(schema, data);
3620
+ }
3621
+ if (!options?.skipRelationValidation) {
3622
+ await this.relationService.validateRelationsOrThrow(schema, data);
3623
+ }
3624
+ }
3625
+ const completionStatus = computeRecordStatus(schema, data);
3626
+ const label = await this.computeLabel(schema, data);
3627
+ const record = await this.adapter.objectRecords.create({
3628
+ tenantId: this.tenantId,
3629
+ objectId,
3630
+ data,
3631
+ label,
3632
+ completionStatus
3633
+ });
3634
+ if (!options?.skipHooks) {
3635
+ const afterCtx = {
3636
+ ...hookCtx,
3637
+ recordId: record.id,
3638
+ record
3639
+ };
3640
+ await this.hookRegistry.execute("afterCreate", schema.name, afterCtx);
3641
+ }
3642
+ return record;
3643
+ }
3644
+ /**
3645
+ * Get a record by ID
3646
+ *
3647
+ * @param recordId - Record UUID
3648
+ * @param options - Query options
3649
+ * @returns Record or null if not found
3650
+ */
3651
+ async getRecord(recordId, options) {
3652
+ const record = await this.adapter.objectRecords.findById(recordId);
3653
+ if (!record) {
3654
+ return null;
3655
+ }
3656
+ if (options?.includeSchema) {
3657
+ const schema = await this.schemaService.getObjectSchema(record.objectId);
3658
+ const recordWithSchema = record;
3659
+ recordWithSchema.schema = schema;
3660
+ return recordWithSchema;
3661
+ }
3662
+ return record;
3663
+ }
3664
+ /**
3665
+ * Get a record by ID or throw if not found
3666
+ */
3667
+ async getRecordOrThrow(recordId) {
3668
+ const record = await this.getRecord(recordId);
3669
+ if (!record) {
3670
+ throw new Error(`Record with id "${recordId}" not found`);
3671
+ }
3672
+ return record;
3673
+ }
3674
+ /**
3675
+ * Update a record with validation
3676
+ *
3677
+ * The completion status is automatically recalculated after each update.
3678
+ * A draft record becomes complete when all required fields are filled.
3679
+ *
3680
+ * Triggers beforeUpdate and afterUpdate hooks if a HookRegistry is configured.
3681
+ *
3682
+ * @param recordId - Record UUID
3683
+ * @param data - Partial data to update
3684
+ * @param options - Update options
3685
+ * @returns Updated record with recalculated completionStatus
3686
+ *
3687
+ * @example
3688
+ * ```typescript
3689
+ * // Update a draft record to make it complete
3690
+ * const updated = await service.updateRecord(draftId, {
3691
+ * price: 99.99,
3692
+ * status: "active"
3693
+ * });
3694
+ * // → updated.completionStatus = "complete" if all required fields now present
3695
+ * ```
3696
+ */
3697
+ async updateRecord(recordId, data, options) {
3698
+ const existing = await this.getRecordOrThrow(recordId);
3699
+ const schema = await this.schemaService.getObjectSchema(existing.objectId);
3700
+ const mergedData = { ...existing.values, ...data };
3701
+ const changedAttributes = Object.keys(data).filter((key) => existing.values[key] !== data[key]);
3702
+ const hookCtx = this.buildHookContext(
3703
+ schema,
3704
+ existing,
3705
+ data,
3706
+ mergedData,
3707
+ changedAttributes,
3708
+ options?.hookMetadata
3709
+ );
3710
+ if (!options?.skipHooks) {
3711
+ await this.hookRegistry.execute("beforeUpdate", schema.name, hookCtx);
3712
+ }
3713
+ if (options?.validate !== false) {
3714
+ if (options?.partial) {
3715
+ validateDraftOrThrow(schema, mergedData);
3716
+ } else {
3717
+ validateObjectOrThrow(schema, mergedData);
3718
+ }
3719
+ if (!options?.skipRelationValidation) {
3720
+ await this.relationService.validateRelationsOrThrow(schema, data);
3721
+ }
3722
+ }
3723
+ const completionStatus = computeRecordStatus(schema, mergedData);
3724
+ const label = await this.computeLabel(schema, mergedData);
3725
+ const updated = await this.adapter.objectRecords.update(recordId, {
3726
+ ...data,
3727
+ __completionStatus: completionStatus,
3728
+ __label: label
3729
+ });
3730
+ if (!options?.skipHooks) {
3731
+ const afterCtx = {
3732
+ ...hookCtx,
3733
+ record: updated
3734
+ };
3735
+ await this.hookRegistry.execute("afterUpdate", schema.name, afterCtx);
3736
+ }
3737
+ return updated;
3738
+ }
3739
+ /**
3740
+ * Build hook context for update operations
3741
+ * @internal
3742
+ */
3743
+ buildHookContext(schema, existing, newData, mergedData, changedAttributes, metadata) {
3744
+ const oldValuesSnapshot = { ...existing.values };
3745
+ return {
3746
+ objectId: schema.id,
3747
+ objectName: schema.name,
3748
+ recordId: existing.id,
3749
+ tenantId: this.tenantId,
3750
+ record: existing,
3751
+ oldValues: oldValuesSnapshot,
3752
+ newValues: mergedData,
3753
+ changedAttributes,
3754
+ getChange: (attr) => ({
3755
+ oldValue: oldValuesSnapshot[attr],
3756
+ newValue: newData[attr] ?? oldValuesSnapshot[attr],
3757
+ changed: changedAttributes.includes(attr)
3758
+ }),
3759
+ metadata: metadata ?? {},
3760
+ timestamp: /* @__PURE__ */ new Date()
3761
+ };
3762
+ }
3763
+ /**
3764
+ * Build hook context for create operations (no existing record)
3765
+ * @internal
3766
+ */
3767
+ buildCreateHookContext(schema, data, metadata) {
3768
+ const attributeNames = Object.keys(data);
3769
+ return {
3770
+ objectId: schema.id,
3771
+ objectName: schema.name,
3772
+ recordId: "",
3773
+ // Will be set after creation
3774
+ tenantId: this.tenantId,
3775
+ record: null,
3776
+ // Will be set after creation
3777
+ oldValues: {},
3778
+ newValues: data,
3779
+ changedAttributes: attributeNames,
3780
+ // All attributes are "new"
3781
+ getChange: (attr) => ({
3782
+ oldValue: void 0,
3783
+ newValue: data[attr],
3784
+ changed: attributeNames.includes(attr)
3785
+ }),
3786
+ metadata: metadata ?? {},
3787
+ timestamp: /* @__PURE__ */ new Date()
3788
+ };
3789
+ }
3790
+ /**
3791
+ * Build hook context for delete operations
3792
+ * @internal
3793
+ */
3794
+ buildDeleteHookContext(schema, record, metadata) {
3795
+ const attributeNames = Object.keys(record.values);
3796
+ return {
3797
+ objectId: schema.id,
3798
+ objectName: schema.name,
3799
+ recordId: record.id,
3800
+ tenantId: this.tenantId,
3801
+ record,
3802
+ oldValues: record.values,
3803
+ newValues: {},
3804
+ changedAttributes: attributeNames,
3805
+ // All attributes are being "removed"
3806
+ getChange: (attr) => ({
3807
+ oldValue: record.values[attr],
3808
+ newValue: void 0,
3809
+ changed: attributeNames.includes(attr)
3810
+ }),
3811
+ metadata: metadata ?? {},
3812
+ timestamp: /* @__PURE__ */ new Date()
3813
+ };
3814
+ }
3815
+ /**
3816
+ * Delete a record
3817
+ *
3818
+ * Triggers beforeDelete and afterDelete hooks if a HookRegistry is configured.
3819
+ *
3820
+ * @param recordId - Record UUID
3821
+ * @param options - Delete options
3822
+ */
3823
+ async deleteRecord(recordId, options) {
3824
+ const record = await this.getRecordOrThrow(recordId);
3825
+ const schema = await this.schemaService.getObjectSchema(record.objectId);
3826
+ if (options?.checkSystem) {
3827
+ if (schema.system) {
3828
+ throw new Error(`Cannot delete record of system object "${schema.label}"`);
3829
+ }
3830
+ }
3831
+ const hookCtx = this.buildDeleteHookContext(schema, record, options?.hookMetadata);
3832
+ if (!options?.skipHooks) {
3833
+ await this.hookRegistry.execute("beforeDelete", schema.name, hookCtx);
3834
+ }
3835
+ await this.adapter.objectRecords.delete(recordId);
3836
+ if (!options?.skipHooks) {
3837
+ await this.hookRegistry.execute("afterDelete", schema.name, hookCtx);
3838
+ }
3839
+ }
3840
+ /**
3841
+ * List records for an object with pagination
3842
+ *
3843
+ * @param objectId - Object UUID
3844
+ * @param options - List options
3845
+ * @returns Records and total count
3846
+ */
3847
+ async listRecords(objectId, options) {
3848
+ return await this.adapter.objectRecords.list(this.tenantId, objectId, options);
3849
+ }
3850
+ /**
3851
+ * Search records using full-text search
3852
+ *
3853
+ * @param objectId - Object UUID
3854
+ * @param query - Search query
3855
+ * @param options - Search options
3856
+ * @returns Matching records and total count
3857
+ */
3858
+ async searchRecords(objectId, query, options) {
3859
+ return await this.adapter.objectRecords.search(this.tenantId, objectId, query, options);
3860
+ }
3861
+ /**
3862
+ * Validate data against object schema without saving
3863
+ *
3864
+ * @param objectId - Object UUID
3865
+ * @param data - Data to validate
3866
+ * @returns Validation result
3867
+ */
3868
+ async validateData(objectId, data) {
3869
+ const schema = await this.schemaService.getObjectSchema(objectId);
3870
+ return validateObject(schema, data);
3871
+ }
3872
+ /**
3873
+ * Compute the completion status for given data without saving.
3874
+ * Useful for UI to show draft/complete status before submitting.
3875
+ *
3876
+ * @param objectId - Object UUID
3877
+ * @param data - Data to check
3878
+ * @returns Computed completion status
3879
+ */
3880
+ async computeStatus(objectId, data) {
3881
+ const schema = await this.schemaService.getObjectSchema(objectId);
3882
+ return computeRecordStatus(schema, data);
3883
+ }
3884
+ /**
3885
+ * Refresh the completion status of an existing record.
3886
+ * Useful when schema changes and you need to recompute statuses.
3887
+ *
3888
+ * @param recordId - Record UUID
3889
+ * @returns Updated completion status
3890
+ */
3891
+ async refreshRecordStatus(recordId) {
3892
+ const record = await this.getRecordOrThrow(recordId);
3893
+ const schema = await this.schemaService.getObjectSchema(record.objectId);
3894
+ const newStatus = computeRecordStatus(schema, record.values);
3895
+ if (record.completionStatus !== newStatus) {
3896
+ await this.adapter.objectRecords.update(recordId, {
3897
+ __completionStatus: newStatus
3898
+ });
3899
+ }
3900
+ return newStatus;
3901
+ }
3902
+ };
3903
+
3904
+ // src/runtime/services/user-profile.service.ts
3905
+ var UserProfileService = class {
3906
+ constructor(adapter, tenantId) {
3907
+ this.adapter = adapter;
3908
+ this.tenantId = tenantId;
3909
+ }
3910
+ /**
3911
+ * Create a new user profile (typically after first auth)
3912
+ *
3913
+ * @param data - User profile creation data
3914
+ * @returns Created user profile
3915
+ *
3916
+ * @example
3917
+ * ```typescript
3918
+ * const service = new UserProfileService(adapter, "tenant-123");
3919
+ *
3920
+ * // After Supabase auth
3921
+ * const profile = await service.createProfile({
3922
+ * tenantId: "tenant-123",
3923
+ * authId: authUser.id,
3924
+ * email: authUser.email,
3925
+ * firstName: authUser.user_metadata.first_name,
3926
+ * lastName: authUser.user_metadata.last_name,
3927
+ * role: "member",
3928
+ * status: "active"
3929
+ * });
3930
+ * ```
3931
+ */
3932
+ async createProfile(data) {
3933
+ if (data.tenantId !== this.tenantId) {
3934
+ throw new Error(
3935
+ `Tenant mismatch: service initialized with "${this.tenantId}" but data has "${data.tenantId}"`
3936
+ );
3937
+ }
3938
+ const existing = await this.adapter.userProfiles.findByAuthId(data.authId);
3939
+ if (existing) {
3940
+ throw new Error(`User profile with authId "${data.authId}" already exists`);
3941
+ }
3942
+ const existingEmail = await this.adapter.userProfiles.findByEmail(this.tenantId, data.email);
3943
+ if (existingEmail) {
3944
+ throw new Error(`User profile with email "${data.email}" already exists in this tenant`);
3945
+ }
3946
+ return await this.adapter.userProfiles.create(data);
3947
+ }
3948
+ /**
3949
+ * Get user profile by ID
3950
+ */
3951
+ async getProfile(profileId) {
3952
+ return await this.adapter.userProfiles.findById(profileId);
3953
+ }
3954
+ /**
3955
+ * Get user profile by ID or throw
3956
+ */
3957
+ async getProfileOrThrow(profileId) {
3958
+ const profile = await this.getProfile(profileId);
3959
+ if (!profile) {
3960
+ throw new Error(`User profile with id "${profileId}" not found`);
3961
+ }
3962
+ return profile;
3963
+ }
3964
+ /**
3965
+ * Get user profile by auth provider ID
3966
+ *
3967
+ * @param authId - Auth provider user ID (Supabase, Clerk, etc.)
3968
+ * @returns User profile or null
3969
+ */
3970
+ async getProfileByAuthId(authId) {
3971
+ return await this.adapter.userProfiles.findByAuthId(authId);
3972
+ }
3973
+ /**
3974
+ * Get or create user profile (idempotent operation)
3975
+ * Useful for auth callbacks - ensures profile exists
3976
+ *
3977
+ * @param authId - Auth provider user ID
3978
+ * @param data - Profile data to create if doesn't exist
3979
+ * @returns Existing or newly created profile
3980
+ *
3981
+ * @example
3982
+ * ```typescript
3983
+ * // In Supabase auth callback
3984
+ * const profile = await service.getOrCreateProfile(
3985
+ * authUser.id,
3986
+ * {
3987
+ * tenantId: "tenant-123",
3988
+ * authId: authUser.id,
3989
+ * email: authUser.email,
3990
+ * role: "member",
3991
+ * status: "active"
3992
+ * }
3993
+ * );
3994
+ * ```
3995
+ */
3996
+ async getOrCreateProfile(authId, data) {
3997
+ const existing = await this.getProfileByAuthId(authId);
3998
+ if (existing) {
3999
+ return existing;
4000
+ }
4001
+ return await this.createProfile(data);
4002
+ }
4003
+ /**
4004
+ * Update user profile
4005
+ */
4006
+ async updateProfile(profileId, data) {
4007
+ await this.getProfileOrThrow(profileId);
4008
+ return await this.adapter.userProfiles.update(profileId, data);
4009
+ }
4010
+ /**
4011
+ * Delete user profile
4012
+ *
4013
+ * @param profileId - Profile UUID
4014
+ * @param options - Delete options
4015
+ */
4016
+ async deleteProfile(profileId, options) {
4017
+ if (options?.checkAdmin) {
4018
+ const profile = await this.getProfileOrThrow(profileId);
4019
+ if (profile.role === "admin") {
4020
+ const allProfiles = await this.listProfiles();
4021
+ const adminCount = allProfiles.filter((p) => p.role === "admin").length;
4022
+ if (adminCount <= 1) {
4023
+ throw new Error("Cannot delete the last admin user");
4024
+ }
4025
+ }
4026
+ }
4027
+ await this.adapter.userProfiles.delete(profileId);
4028
+ }
4029
+ /**
4030
+ * List all user profiles for the tenant
4031
+ */
4032
+ async listProfiles(options) {
4033
+ return await this.adapter.userProfiles.list(this.tenantId, options);
4034
+ }
4035
+ /**
4036
+ * Update last login timestamp
4037
+ *
4038
+ * @param profileId - Profile UUID
4039
+ *
4040
+ * @example
4041
+ * ```typescript
4042
+ * // After successful auth
4043
+ * await service.updateLastLogin(profile.id);
4044
+ * ```
4045
+ */
4046
+ async updateLastLogin(profileId) {
4047
+ await this.adapter.userProfiles.updateLastLogin(profileId);
4048
+ }
4049
+ /**
4050
+ * Change user role
4051
+ *
4052
+ * @param profileId - Profile UUID
4053
+ * @param newRole - New role
4054
+ */
4055
+ async changeRole(profileId, newRole) {
4056
+ return await this.updateProfile(profileId, { role: newRole });
4057
+ }
4058
+ /**
4059
+ * Change user status
4060
+ *
4061
+ * @param profileId - Profile UUID
4062
+ * @param newStatus - New status
4063
+ */
4064
+ async changeStatus(profileId, newStatus) {
4065
+ return await this.updateProfile(profileId, { status: newStatus });
4066
+ }
4067
+ /**
4068
+ * Get user by email
4069
+ */
4070
+ async getProfileByEmail(email) {
4071
+ return await this.adapter.userProfiles.findByEmail(this.tenantId, email);
4072
+ }
4073
+ /**
4074
+ * Check if user has role
4075
+ */
4076
+ async hasRole(profileId, role) {
4077
+ const profile = await this.getProfile(profileId);
4078
+ return profile?.role === role;
4079
+ }
4080
+ /**
4081
+ * Check if user is admin
4082
+ */
4083
+ async isAdmin(profileId) {
4084
+ return await this.hasRole(profileId, "admin");
4085
+ }
4086
+ };
4087
+
4088
+ // src/runtime/services/view.service.ts
4089
+ var ViewService = class {
4090
+ constructor(adapter, nativeViews) {
4091
+ this.adapter = adapter;
4092
+ this.nativeViews = nativeViews;
4093
+ }
4094
+ /**
4095
+ * Get all views for an object (native + custom)
4096
+ *
4097
+ * @param objectName - Object name
4098
+ * @param tenantId - Tenant ID
4099
+ * @returns All views for the object
4100
+ */
4101
+ async getViewsForObject(objectName, tenantId) {
4102
+ const nativeViewDefs = this.nativeViews.getByObjectName(objectName);
4103
+ const dbViews = await this.adapter.views.findByObjectName(tenantId, objectName);
4104
+ const customViews = dbViews.filter((v) => !v.system).map(this.convertDBViewToDefinition);
4105
+ return [...nativeViewDefs, ...customViews];
4106
+ }
4107
+ /**
4108
+ * Get a specific view by name
4109
+ *
4110
+ * @param objectName - Object name
4111
+ * @param viewName - View name
4112
+ * @param tenantId - Tenant ID
4113
+ * @returns View definition or null
4114
+ */
4115
+ async getView(objectName, viewName, tenantId) {
4116
+ const nativeView = this.nativeViews.get(objectName, viewName);
4117
+ if (nativeView) {
4118
+ return nativeView;
4119
+ }
4120
+ const dbView = await this.adapter.views.findByName(tenantId, objectName, viewName);
4121
+ if (dbView) {
4122
+ return this.convertDBViewToDefinition(dbView);
4123
+ }
4124
+ return null;
4125
+ }
4126
+ /**
4127
+ * Get the default view for an object
4128
+ *
4129
+ * Priority:
4130
+ * 1. Custom view marked as default
4131
+ * 2. Native view marked as default
4132
+ * 3. First available view
4133
+ *
4134
+ * @param objectName - Object name
4135
+ * @param tenantId - Tenant ID
4136
+ * @returns Default view or null
4137
+ */
4138
+ async getDefaultView(objectName, tenantId) {
4139
+ const views = await this.getViewsForObject(objectName, tenantId);
4140
+ const customDefault = views.find((v) => v.default && !v.system);
4141
+ if (customDefault) return customDefault;
4142
+ const nativeDefault = views.find((v) => v.default && v.system);
4143
+ if (nativeDefault) return nativeDefault;
4144
+ return views[0] ?? null;
4145
+ }
4146
+ /**
4147
+ * Create a custom view
4148
+ *
4149
+ * @param input - View definition
4150
+ * @param tenantId - Tenant ID
4151
+ * @returns Created view
4152
+ */
4153
+ async createView(input, tenantId) {
4154
+ this.validateViewName(input.name);
4155
+ const existing = await this.adapter.views.findByName(tenantId, input.objectName, input.name);
4156
+ if (existing) {
4157
+ throw new Error(`View "${input.name}" already exists for object "${input.objectName}"`);
4158
+ }
4159
+ if (this.nativeViews.has(input.objectName, input.name)) {
4160
+ throw new Error(
4161
+ `Cannot create view "${input.name}": a system view with this name already exists`
4162
+ );
4163
+ }
4164
+ if (!input.tabs || input.tabs.length === 0) {
4165
+ throw new Error("View must have at least one tab");
4166
+ }
4167
+ const dbView = await this.adapter.views.create({
4168
+ tenantId,
4169
+ objectName: input.objectName,
4170
+ name: input.name,
4171
+ label: input.label,
4172
+ description: input.description,
4173
+ icon: input.icon,
4174
+ tabs: input.tabs,
4175
+ default: input.default ?? false,
4176
+ system: false,
4177
+ // Custom views are never system
4178
+ metadata: input.metadata
4179
+ });
4180
+ return this.convertDBViewToDefinition(dbView);
4181
+ }
4182
+ /**
4183
+ * Update a custom view
4184
+ *
4185
+ * @param viewId - View ID
4186
+ * @param input - Update data
4187
+ * @returns Updated view
4188
+ */
4189
+ async updateView(viewId, input) {
4190
+ const dbView = await this.adapter.views.findById(viewId);
4191
+ if (!dbView) {
4192
+ throw new Error(`View with id "${viewId}" not found`);
4193
+ }
4194
+ if (dbView.system) {
4195
+ throw new Error("Cannot modify system views. System views are protected.");
4196
+ }
4197
+ if (input.tabs && input.tabs.length === 0) {
4198
+ throw new Error("View must have at least one tab");
4199
+ }
4200
+ const updated = await this.adapter.views.update(viewId, {
4201
+ label: input.label,
4202
+ description: input.description,
4203
+ icon: input.icon,
4204
+ tabs: input.tabs,
4205
+ default: input.default,
4206
+ metadata: input.metadata
4207
+ });
4208
+ return this.convertDBViewToDefinition(updated);
4209
+ }
4210
+ /**
4211
+ * Delete a custom view
4212
+ *
4213
+ * @param viewId - View ID
4214
+ */
4215
+ async deleteView(viewId) {
4216
+ const dbView = await this.adapter.views.findById(viewId);
4217
+ if (!dbView) {
4218
+ throw new Error(`View with id "${viewId}" not found`);
4219
+ }
4220
+ if (dbView.system) {
4221
+ throw new Error("Cannot delete system views. System views are protected.");
4222
+ }
4223
+ await this.adapter.views.delete(viewId);
4224
+ }
4225
+ /**
4226
+ * Set a view as default for its object
4227
+ *
4228
+ * @param viewId - View ID
4229
+ * @param tenantId - Tenant ID
4230
+ * @returns Updated view
4231
+ */
4232
+ async setDefaultView(viewId, tenantId) {
4233
+ const dbView = await this.adapter.views.findById(viewId);
4234
+ if (!dbView) {
4235
+ throw new Error(`View with id "${viewId}" not found`);
4236
+ }
4237
+ const currentViews = await this.adapter.views.findByObjectName(tenantId, dbView.objectName);
4238
+ for (const v of currentViews) {
4239
+ if (v.default && v.id !== viewId && !v.system) {
4240
+ await this.adapter.views.update(v.id, { default: false });
4241
+ }
4242
+ }
4243
+ const updated = await this.adapter.views.update(viewId, { default: true });
4244
+ return this.convertDBViewToDefinition(updated);
4245
+ }
4246
+ // ============================================================================
4247
+ // PRIVATE HELPERS
4248
+ // ============================================================================
4249
+ /**
4250
+ * Validate view name format (kebab-case)
4251
+ */
4252
+ validateViewName(name) {
4253
+ if (!name || name.length === 0) {
4254
+ throw new Error("View name cannot be empty");
4255
+ }
4256
+ if (name.length > 63) {
4257
+ throw new Error("View name is too long (max 63 characters)");
4258
+ }
4259
+ const kebabCaseRegex = /^[a-z][a-z0-9-]*$/;
4260
+ if (!kebabCaseRegex.test(name)) {
4261
+ throw new Error(
4262
+ "Invalid view name format. Name must be in kebab-case (e.g., 'detail', 'list-view')"
4263
+ );
4264
+ }
4265
+ }
4266
+ /**
4267
+ * Convert database view to ViewDefinition
4268
+ */
4269
+ convertDBViewToDefinition(dbView) {
4270
+ return {
4271
+ id: dbView.id,
4272
+ name: dbView.name,
4273
+ label: dbView.label,
4274
+ description: dbView.description,
4275
+ icon: dbView.icon,
4276
+ object: dbView.objectName,
4277
+ tabs: dbView.tabs,
4278
+ default: dbView.default,
4279
+ system: dbView.system,
4280
+ metadata: dbView.metadata
4281
+ };
4282
+ }
4283
+ };
4284
+
4285
+ // src/runtime/view-sync.ts
4286
+ async function syncNativeViews(adapter, nativeViewRegistry, options = {}) {
4287
+ const result = {
4288
+ success: true,
4289
+ viewsSynced: 0,
4290
+ viewsCreated: 0,
4291
+ viewsUpdated: 0,
4292
+ viewsDeleted: 0,
4293
+ errors: []
4294
+ };
4295
+ const nativeViews = nativeViewRegistry.getAll();
4296
+ if (options.verbose) {
4297
+ console.info(`[ViewSync] Starting sync for ${nativeViews.length} native views...`);
4298
+ }
4299
+ try {
4300
+ await adapter.transaction(async (tx) => {
4301
+ const viewsByObject = await syncAllViews(tx, nativeViews, result, options);
4302
+ await cleanupRemovedViews(tx, viewsByObject, result, options);
4303
+ });
4304
+ } catch (error) {
4305
+ handleTransactionError(result, error);
4306
+ }
4307
+ logSyncComplete(result, options);
4308
+ return result;
4309
+ }
4310
+ async function syncAllViews(tx, nativeViews, result, options) {
4311
+ const viewsByObject = /* @__PURE__ */ new Map();
4312
+ for (const nativeView of nativeViews) {
4313
+ try {
4314
+ await syncSingleView(tx, nativeView, result, options);
4315
+ trackViewByObject(viewsByObject, nativeView);
4316
+ } catch (error) {
4317
+ handleViewSyncError(result, nativeView, error, options);
4318
+ }
4319
+ }
4320
+ return viewsByObject;
4321
+ }
4322
+ function trackViewByObject(viewsByObject, nativeView) {
4323
+ const objectViews = viewsByObject.get(nativeView.object) ?? [];
4324
+ objectViews.push(nativeView.name);
4325
+ viewsByObject.set(nativeView.object, objectViews);
4326
+ }
4327
+ function handleViewSyncError(result, nativeView, error, options) {
4328
+ result.success = false;
4329
+ result.errors.push({
4330
+ viewName: nativeView.name,
4331
+ objectName: nativeView.object,
4332
+ error: error instanceof Error ? error.message : String(error)
4333
+ });
4334
+ if (options.verbose) {
4335
+ console.error(`[ViewSync] \u2717 Failed to sync ${nativeView.object}:${nativeView.name}:`, error);
4336
+ }
4337
+ }
4338
+ async function cleanupRemovedViews(tx, viewsByObject, result, options) {
4339
+ if (options.dryRun) return;
4340
+ for (const [objectName, viewNames] of viewsByObject) {
4341
+ const deletedCount = await tx.views.deleteNotIn(objectName, viewNames);
4342
+ result.viewsDeleted += deletedCount;
4343
+ if (options.verbose && deletedCount > 0) {
4344
+ console.info(`[ViewSync] Deleted ${deletedCount} obsolete views for ${objectName}`);
4345
+ }
4346
+ }
4347
+ }
4348
+ function handleTransactionError(result, error) {
4349
+ result.success = false;
4350
+ result.errors.push({
4351
+ viewName: "transaction",
4352
+ objectName: "",
4353
+ error: error instanceof Error ? error.message : String(error)
4354
+ });
4355
+ }
4356
+ function logSyncComplete(result, options) {
4357
+ if (options.verbose) {
4358
+ console.info(
4359
+ `[ViewSync] ${result.success ? "\u2713" : "\u2717"} Sync complete:
4360
+ Views: ${result.viewsCreated} created, ${result.viewsUpdated} updated, ${result.viewsDeleted} deleted
4361
+ Errors: ${result.errors.length}`
4362
+ );
4363
+ }
4364
+ }
4365
+ async function syncSingleView(adapter, nativeView, result, options) {
4366
+ if (!nativeView.system) {
4367
+ throw new Error(`View ${nativeView.name} is not marked as system`);
4368
+ }
4369
+ const existingView = await adapter.views.findSystemByName(nativeView.object, nativeView.name);
4370
+ const isNew = !existingView;
4371
+ if (isNew) {
4372
+ result.viewsCreated++;
4373
+ } else {
4374
+ result.viewsUpdated++;
4375
+ }
4376
+ result.viewsSynced++;
4377
+ if (options.dryRun) {
4378
+ if (options.verbose) {
4379
+ console.info(
4380
+ `[ViewSync] Would ${isNew ? "create" : "update"} view: ${nativeView.object}:${nativeView.name}`
4381
+ );
4382
+ }
4383
+ return;
4384
+ }
4385
+ await adapter.views.upsert({
4386
+ tenantId: options.tenantId || "default",
4387
+ objectName: nativeView.object,
4388
+ name: nativeView.name,
4389
+ label: nativeView.label,
4390
+ description: nativeView.description,
4391
+ icon: nativeView.icon,
4392
+ tabs: nativeView.tabs,
4393
+ default: nativeView.default ?? false,
4394
+ system: true,
4395
+ metadata: nativeView.metadata
4396
+ });
4397
+ if (options.verbose) {
4398
+ console.info(
4399
+ `[ViewSync] \u2713 Synced ${nativeView.object}:${nativeView.name}: ${nativeView.tabs.length} tabs`
4400
+ );
4401
+ }
4402
+ }
4403
+ async function verifyNativeViewsSync(adapter, nativeViewRegistry) {
4404
+ const nativeViews = nativeViewRegistry.getAll();
4405
+ for (const view2 of nativeViews) {
4406
+ if (!view2.system) continue;
4407
+ const existing = await adapter.views.findSystemByName(view2.object, view2.name);
4408
+ if (!existing) {
4409
+ return false;
4410
+ }
4411
+ }
4412
+ return true;
4413
+ }
4414
+ async function getViewSyncPreview(adapter, nativeViewRegistry) {
4415
+ return await syncNativeViews(adapter, nativeViewRegistry, { dryRun: true });
4416
+ }
4417
+
4418
+ // src/runtime/sync.ts
4419
+ var BASE_ATTRIBUTE_KEYS = /* @__PURE__ */ new Set([
4420
+ "id",
4421
+ "name",
4422
+ "label",
4423
+ "type",
4424
+ "required",
4425
+ "system",
4426
+ "unique",
4427
+ "order"
4428
+ ]);
4429
+ function extractAttributeConfig(attr) {
4430
+ return Object.fromEntries(
4431
+ Object.entries(attr).filter(
4432
+ ([key, value]) => !BASE_ATTRIBUTE_KEYS.has(key) && value !== void 0
4433
+ )
4434
+ );
4435
+ }
4436
+ async function syncNativeObjects(adapter, nativeRegistry, options = {}) {
4437
+ const result = {
4438
+ success: true,
4439
+ objectsSynced: 0,
4440
+ attributesSynced: 0,
4441
+ objectsCreated: 0,
4442
+ objectsUpdated: 0,
4443
+ attributesCreated: 0,
4444
+ attributesUpdated: 0,
4445
+ attributesDeleted: 0,
4446
+ errors: []
4447
+ };
4448
+ const nativeObjects = nativeRegistry.getAll();
4449
+ if (options.verbose) {
4450
+ console.info(`[SyncService] Starting sync for ${nativeObjects.length} native objects...`);
4451
+ }
4452
+ try {
4453
+ await adapter.transaction(async (tx) => {
4454
+ for (const nativeObject of nativeObjects) {
4455
+ try {
4456
+ await syncSingleObject(tx, nativeObject, result, options);
4457
+ } catch (error) {
4458
+ result.success = false;
4459
+ result.errors.push({
4460
+ objectName: nativeObject.name,
4461
+ error: error instanceof Error ? error.message : String(error)
4462
+ });
4463
+ if (options.verbose) {
4464
+ console.error(`[SyncService] \u2717 Failed to sync ${nativeObject.name}:`, error);
4465
+ }
4466
+ }
4467
+ }
4468
+ });
4469
+ } catch (error) {
4470
+ result.success = false;
4471
+ result.errors.push({
4472
+ objectName: "transaction",
4473
+ error: error instanceof Error ? error.message : String(error)
4474
+ });
4475
+ }
4476
+ if (options.verbose) {
4477
+ console.info(
4478
+ `[SyncService] ${result.success ? "\u2713" : "\u2717"} Sync complete:
4479
+ Objects: ${result.objectsCreated} created, ${result.objectsUpdated} updated
4480
+ Attributes: ${result.attributesCreated} created, ${result.attributesUpdated} updated, ${result.attributesDeleted} deleted
4481
+ Errors: ${result.errors.length}`
4482
+ );
4483
+ }
4484
+ return result;
4485
+ }
4486
+ async function syncSingleObject(adapter, nativeObject, result, options) {
4487
+ if (!nativeObject.system) {
4488
+ throw new Error(`Object ${nativeObject.name} is not marked as system`);
4489
+ }
4490
+ const existingObject = await adapter.objects.findSystemByName(nativeObject.name);
4491
+ const isNew = !existingObject;
4492
+ updateObjectStats(result, isNew);
4493
+ if (options.dryRun) {
4494
+ await handleDryRun(adapter, nativeObject, existingObject, result, options, isNew);
4495
+ return;
4496
+ }
4497
+ const dbObject = await upsertObject(adapter, nativeObject, options);
4498
+ await syncAttributes(adapter, nativeObject, dbObject, existingObject, result);
4499
+ if (!isNew) {
4500
+ await cleanupAttributes(adapter, dbObject.id, nativeObject, result);
4501
+ }
4502
+ logSyncSuccess(nativeObject, options);
4503
+ }
4504
+ function updateObjectStats(result, isNew) {
4505
+ if (isNew) {
4506
+ result.objectsCreated++;
4507
+ } else {
4508
+ result.objectsUpdated++;
4509
+ }
4510
+ result.objectsSynced++;
4511
+ }
4512
+ async function handleDryRun(adapter, nativeObject, existingObject, result, options, isNew) {
4513
+ if (options.verbose) {
4514
+ console.info(`[SyncService] Would ${isNew ? "create" : "update"} object: ${nativeObject.name}`);
4515
+ }
4516
+ for (const attr of nativeObject.attributes) {
4517
+ const existingAttr = existingObject ? await adapter.attributes.findByObjectId(existingObject.id).then((attrs) => attrs.find((a) => a.name === attr.name)) : null;
4518
+ if (existingAttr) {
4519
+ result.attributesUpdated++;
4520
+ } else {
4521
+ result.attributesCreated++;
4522
+ }
4523
+ result.attributesSynced++;
4524
+ }
4525
+ }
4526
+ async function upsertObject(adapter, nativeObject, options) {
4527
+ return await adapter.objects.upsert({
4528
+ tenantId: options.tenantId || "default",
4529
+ system: true,
4530
+ name: nativeObject.name,
4531
+ label: nativeObject.label,
4532
+ description: nativeObject.description,
4533
+ labelExpression: nativeObject.labelExpression,
4534
+ icon: nativeObject.icon,
4535
+ metadata: nativeObject.metadata
4536
+ });
4537
+ }
4538
+ async function syncAttributes(adapter, nativeObject, dbObject, existingObject, result) {
4539
+ for (const [index, attr] of nativeObject.attributes.entries()) {
4540
+ const existingAttr = existingObject ? await adapter.attributes.findByObjectId(dbObject.id).then((attrs) => attrs.find((a) => a.name === attr.name)) : null;
4541
+ await adapter.attributes.upsert({
4542
+ objectId: dbObject.id,
4543
+ name: attr.name,
4544
+ label: attr.label,
4545
+ type: attr.type,
4546
+ description: attr.description,
4547
+ icon: attr.icon,
4548
+ system: attr.system ?? true,
4549
+ required: attr.required ?? false,
4550
+ order: attr.order ?? index,
4551
+ hidden: attr.hidden,
4552
+ archived: attr.archived,
4553
+ deprecated: attr.deprecated,
4554
+ defaultValue: attr.defaultValue,
4555
+ config: extractAttributeConfig(attr)
4556
+ });
4557
+ if (existingAttr) {
4558
+ result.attributesUpdated++;
4559
+ } else {
4560
+ result.attributesCreated++;
4561
+ }
4562
+ result.attributesSynced++;
4563
+ }
4564
+ }
4565
+ async function cleanupAttributes(adapter, objectId, nativeObject, result) {
4566
+ const attributeNames = nativeObject.attributes.map((attr) => attr.name);
4567
+ const deletedCount = await adapter.attributes.deleteByNames(objectId, attributeNames);
4568
+ result.attributesDeleted += deletedCount;
4569
+ }
4570
+ function logSyncSuccess(nativeObject, options) {
4571
+ if (options.verbose) {
4572
+ console.info(
4573
+ `[SyncService] \u2713 Synced ${nativeObject.name}: ${nativeObject.attributes.length} attributes`
4574
+ );
4575
+ }
4576
+ }
4577
+ async function verifyNativeObjectsSync(adapter, nativeRegistry) {
4578
+ const nativeObjects = nativeRegistry.getAll();
4579
+ for (const obj of nativeObjects) {
4580
+ if (!obj.system) continue;
4581
+ const existing = await adapter.objects.findSystemByName(obj.name);
4582
+ if (!existing) {
4583
+ return false;
4584
+ }
4585
+ }
4586
+ return true;
4587
+ }
4588
+ async function getSyncPreview(adapter, nativeRegistry) {
4589
+ return await syncNativeObjects(adapter, nativeRegistry, { dryRun: true });
4590
+ }
4591
+ async function syncAll(adapter, objectRegistry, nativeViewRegistry, options = {}) {
4592
+ if (options.verbose) {
4593
+ console.info("[SyncAll] Starting full sync...");
4594
+ }
4595
+ const objectsResult = await syncNativeObjects(adapter, objectRegistry, options);
4596
+ const viewsResult = await syncNativeViews(adapter, nativeViewRegistry, options);
4597
+ const result = {
4598
+ success: objectsResult.success && viewsResult.success,
4599
+ objects: objectsResult,
4600
+ views: viewsResult
4601
+ };
4602
+ if (options.verbose) {
4603
+ console.info(
4604
+ `[SyncAll] ${result.success ? "\u2713" : "\u2717"} Full sync complete:
4605
+ Objects: ${objectsResult.objectsSynced} synced (${objectsResult.objectsCreated} created, ${objectsResult.objectsUpdated} updated)
4606
+ Views: ${viewsResult.viewsSynced} synced (${viewsResult.viewsCreated} created, ${viewsResult.viewsUpdated} updated)
4607
+ Errors: ${objectsResult.errors.length + viewsResult.errors.length}`
4608
+ );
4609
+ }
4610
+ return result;
4611
+ }
4612
+
4613
+ // src/types/geocoding.ts
4614
+ var NoopGeocodingAdapter = class {
4615
+ async autocomplete() {
4616
+ return await Promise.resolve([]);
4617
+ }
4618
+ async reverse() {
4619
+ return await Promise.resolve(null);
4620
+ }
4621
+ async geocode() {
4622
+ return await Promise.resolve(null);
4623
+ }
4624
+ };
4625
+
4626
+ export {
4627
+ NoopGeocodingAdapter,
4628
+ generateId,
4629
+ generatePrefixedId,
4630
+ text,
4631
+ textarea,
4632
+ number,
4633
+ checkbox,
4634
+ date,
4635
+ phone,
4636
+ currency,
4637
+ status,
4638
+ select,
4639
+ multiselect,
4640
+ location,
4641
+ timestamp,
4642
+ file,
4643
+ user,
4644
+ relation,
4645
+ rating,
4646
+ ObjectBuilder,
4647
+ object,
4648
+ GroupBuilder,
4649
+ TableTabConfig,
4650
+ CustomTabConfig,
4651
+ TabBuilder,
4652
+ ViewBuilder,
4653
+ view,
4654
+ group,
4655
+ registry,
4656
+ textConfigSchema,
4657
+ textareaConfigSchema,
4658
+ numberConfigSchema,
4659
+ checkboxConfigSchema,
4660
+ dateConfigSchema,
4661
+ phoneConfigSchema,
4662
+ currencyConfigSchema,
4663
+ statusConfigSchema,
4664
+ locationConfigSchema,
4665
+ timestampConfigSchema,
4666
+ selectConfigSchema,
4667
+ multiselectConfigSchema,
4668
+ fileConfigSchema,
4669
+ userConfigSchema,
4670
+ relationConfigSchema,
4671
+ ratingConfigSchema,
4672
+ attributeConfigSchemas,
4673
+ getAttributeConfigSchema,
4674
+ validateAttributeConfig,
4675
+ parseAttributeConfig,
4676
+ safeParseAttributeConfig,
4677
+ createTextValidator,
4678
+ createNumberValidator,
4679
+ createCheckboxValidator,
4680
+ createDateValidator,
4681
+ createPhoneValidator,
4682
+ createCurrencyValidator,
4683
+ createStatusValidator,
4684
+ createSelectValidator,
4685
+ createMultiselectValidator,
4686
+ createLocationValidator,
4687
+ createTimestampValidator,
4688
+ createFileValidator,
4689
+ createUserValidator,
4690
+ createSingleRelationValidator,
4691
+ createMultiRelationValidator,
4692
+ createRelationValidator,
4693
+ createRatingValidator,
4694
+ createAttributeValidator,
4695
+ createObjectValidator,
4696
+ validateAttribute,
4697
+ validateObject,
4698
+ validateObjectOrThrow,
4699
+ createDraftValidator,
4700
+ validateDraft,
4701
+ validateDraftOrThrow,
4702
+ getMissingRequiredAttributes,
4703
+ isRecordComplete,
4704
+ computeRecordStatus,
4705
+ NoopHookRegistry,
4706
+ DEFAULT_LABEL_FALLBACK,
4707
+ renderLabelExpression,
4708
+ isLabelExpression,
4709
+ extractAttributeNames,
4710
+ createMockAdapter,
4711
+ FileService,
4712
+ GeocodingService,
4713
+ GlobalSearchService,
4714
+ ObjectSchemaService,
4715
+ RelationService,
4716
+ RecordService,
4717
+ UserProfileService,
4718
+ ViewService,
4719
+ syncNativeViews,
4720
+ verifyNativeViewsSync,
4721
+ getViewSyncPreview,
4722
+ syncNativeObjects,
4723
+ verifyNativeObjectsSync,
4724
+ getSyncPreview,
4725
+ syncAll
4726
+ };