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