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