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