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