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