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