@kyro-cms/core 0.10.3 → 0.10.5

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 (301) hide show
  1. package/dist/api-handler-graphql.cjs +1 -49
  2. package/dist/api-handler-graphql.js +1 -46
  3. package/dist/api-handler-trpc.cjs +1 -38
  4. package/dist/api-handler-trpc.js +1 -36
  5. package/dist/api-handler.cjs +1 -44
  6. package/dist/api-handler.js +1 -27
  7. package/dist/bootstrap-IVQWSJXZ.js +1 -0
  8. package/dist/bootstrap-OHGQGMRV.cjs +1 -0
  9. package/dist/chunk-2BTRHVT3.cjs +20 -0
  10. package/dist/chunk-2W4FK6CJ.js +122 -0
  11. package/dist/chunk-4ORJMSJU.cjs +1 -0
  12. package/dist/chunk-5J6HXUF6.js +1 -0
  13. package/dist/chunk-65G73T7Z.cjs +2 -0
  14. package/dist/chunk-6CLRVJPP.cjs +133 -0
  15. package/dist/chunk-7N6NKCRT.js +1 -0
  16. package/dist/chunk-7WOX27LK.js +259 -0
  17. package/dist/chunk-AE6GXUT7.js +1 -0
  18. package/dist/chunk-AHSFSERC.cjs +1 -0
  19. package/dist/chunk-AJAZ7D3W.cjs +259 -0
  20. package/dist/chunk-ATLSIYRH.cjs +1 -0
  21. package/dist/chunk-AU6IWTBO.js +2 -0
  22. package/dist/chunk-CIE3XMLH.cjs +2 -0
  23. package/dist/chunk-CVVW4LXZ.cjs +1 -0
  24. package/dist/chunk-DV4LFLPL.cjs +1 -0
  25. package/dist/chunk-ELICKLFM.cjs +3 -0
  26. package/dist/chunk-EQUQJBPP.cjs +2 -0
  27. package/dist/chunk-ET6NN2V2.cjs +122 -0
  28. package/dist/chunk-F3Z67QWS.cjs +86 -0
  29. package/dist/chunk-F7SR5IDT.cjs +1 -0
  30. package/dist/chunk-FO3HLBC7.js +1 -0
  31. package/dist/chunk-G6A7OSIG.js +2 -0
  32. package/dist/chunk-GFU7AOI3.cjs +1 -0
  33. package/dist/chunk-GYQMNXXW.cjs +114 -0
  34. package/dist/chunk-HLSB2MCK.js +1 -0
  35. package/dist/chunk-HVXO3OFB.cjs +1 -0
  36. package/dist/chunk-ISWMETHJ.cjs +1 -0
  37. package/dist/chunk-K6WUOU6P.js +1 -0
  38. package/dist/chunk-KDNYHLD2.js +1 -0
  39. package/dist/chunk-L6CZYN3L.cjs +20 -0
  40. package/dist/chunk-LZ6YFYQM.js +20 -0
  41. package/dist/chunk-MIOMMB23.cjs +1 -0
  42. package/dist/chunk-MSSRVZH6.js +1 -0
  43. package/dist/chunk-NGBJKZMT.js +90 -0
  44. package/dist/chunk-NRLIGDYF.js +1 -0
  45. package/dist/chunk-NY47CFVP.cjs +1 -0
  46. package/dist/chunk-NZ35PV5R.js +2 -0
  47. package/dist/chunk-OG7CNQGU.js +1 -0
  48. package/dist/chunk-P7CESLDJ.js +1 -0
  49. package/dist/chunk-POWTSLKC.js +21 -0
  50. package/dist/chunk-PP5S2UBV.js +0 -0
  51. package/dist/chunk-PWGS2GPI.js +86 -0
  52. package/dist/chunk-Q3Q7BJVQ.cjs +1 -0
  53. package/dist/chunk-Q4CSLXCO.cjs +90 -0
  54. package/dist/chunk-QRXDCV6K.js +0 -0
  55. package/dist/chunk-R6UUTH3T.js +2 -0
  56. package/dist/chunk-RHCWCG3O.js +114 -0
  57. package/dist/chunk-SL3LZQCF.js +1 -0
  58. package/dist/chunk-TD6RULJU.cjs +21 -0
  59. package/dist/chunk-UBHFUFD4.cjs +1 -0
  60. package/dist/chunk-UBRYJP2G.js +1 -0
  61. package/dist/chunk-UDSJGML2.cjs +2 -0
  62. package/dist/chunk-UHFDH3PG.js +20 -0
  63. package/dist/chunk-UJNSOOYZ.cjs +1 -0
  64. package/dist/chunk-UVTS2IWM.js +1 -0
  65. package/dist/chunk-V65NPSR5.cjs +1 -0
  66. package/dist/chunk-VKXQUYYV.js +133 -0
  67. package/dist/chunk-WIZ6C5QZ.cjs +1 -0
  68. package/dist/chunk-Y7K26TBA.cjs +1 -0
  69. package/dist/chunk-ZAQOSRP6.js +1 -0
  70. package/dist/chunk-ZELCS7IC.js +3 -0
  71. package/dist/cli/index.cjs +35 -405
  72. package/dist/cli/index.js +35 -402
  73. package/dist/client.cjs +1 -55
  74. package/dist/client.js +1 -6
  75. package/dist/drizzle/index.cjs +1 -50
  76. package/dist/drizzle/index.d.cts +1 -2
  77. package/dist/drizzle/index.d.ts +1 -2
  78. package/dist/drizzle/index.js +1 -9
  79. package/dist/fields/index.cjs +1 -89
  80. package/dist/fields/index.js +1 -4
  81. package/dist/graphql/index.cjs +1 -31
  82. package/dist/graphql/index.d.cts +1 -1
  83. package/dist/graphql/index.d.ts +1 -1
  84. package/dist/graphql/index.js +1 -6
  85. package/dist/{index-jLs0zlft.d.ts → index-DXr33e0x.d.ts} +1 -1
  86. package/dist/{index-DHbywDs-.d.cts → index-DuuUzWBq.d.cts} +1 -1
  87. package/dist/index.cjs +29 -2464
  88. package/dist/index.d.cts +2 -2
  89. package/dist/index.d.ts +2 -2
  90. package/dist/index.js +29 -1929
  91. package/dist/integration.cjs +1 -10
  92. package/dist/integration.js +1 -4
  93. package/dist/media-L5XDD47D.js +1 -0
  94. package/dist/media-OUBQTIQP.cjs +1 -0
  95. package/dist/mongo-auth-adapter-LG5O4LIH.js +1 -0
  96. package/dist/mongo-auth-adapter-YPONSOCY.cjs +1 -0
  97. package/dist/mongodb/index.cjs +1 -29
  98. package/dist/mongodb/index.d.cts +1 -2
  99. package/dist/mongodb/index.d.ts +1 -2
  100. package/dist/mongodb/index.js +1 -8
  101. package/dist/postgres-auth-adapter-33QOIRXT.js +1 -0
  102. package/dist/postgres-auth-adapter-JKDYYULH.cjs +1 -0
  103. package/dist/redis-adapter-KECGVSVX.cjs +1 -0
  104. package/dist/redis-adapter-VAXP43GR.js +1 -0
  105. package/dist/rest/index.cjs +1 -31
  106. package/dist/rest/index.d.cts +1 -1
  107. package/dist/rest/index.d.ts +1 -1
  108. package/dist/rest/index.js +1 -18
  109. package/dist/schema-HIUSHSUI.cjs +1 -0
  110. package/dist/schema-KFYUM674.js +1 -0
  111. package/dist/sqlite-adapter-FP45QCYK.js +1 -0
  112. package/dist/sqlite-adapter-Z3IBBI4X.cjs +1 -0
  113. package/dist/templates/index.cjs +1 -207
  114. package/dist/templates/index.js +1 -6
  115. package/dist/trpc/index.cjs +1 -48
  116. package/dist/trpc/index.js +1 -7
  117. package/dist/ws/index.cjs +1 -25
  118. package/dist/ws/index.js +1 -4
  119. package/package.json +49 -12
  120. package/dist/api-handler-graphql.cjs.map +0 -1
  121. package/dist/api-handler-graphql.js.map +0 -1
  122. package/dist/api-handler-trpc.cjs.map +0 -1
  123. package/dist/api-handler-trpc.js.map +0 -1
  124. package/dist/api-handler.cjs.map +0 -1
  125. package/dist/api-handler.js.map +0 -1
  126. package/dist/bootstrap-FUAPY2OF.cjs +0 -32
  127. package/dist/bootstrap-FUAPY2OF.cjs.map +0 -1
  128. package/dist/bootstrap-OXNVM7FP.js +0 -7
  129. package/dist/bootstrap-OXNVM7FP.js.map +0 -1
  130. package/dist/chunk-2HFJUUFZ.js +0 -250
  131. package/dist/chunk-2HFJUUFZ.js.map +0 -1
  132. package/dist/chunk-354ISGA4.js +0 -6457
  133. package/dist/chunk-354ISGA4.js.map +0 -1
  134. package/dist/chunk-3AKCVYDB.js +0 -162
  135. package/dist/chunk-3AKCVYDB.js.map +0 -1
  136. package/dist/chunk-3KTWGODI.cjs +0 -178
  137. package/dist/chunk-3KTWGODI.cjs.map +0 -1
  138. package/dist/chunk-3P5AHK2U.cjs +0 -2749
  139. package/dist/chunk-3P5AHK2U.cjs.map +0 -1
  140. package/dist/chunk-3YELQL7Z.cjs +0 -4
  141. package/dist/chunk-3YELQL7Z.cjs.map +0 -1
  142. package/dist/chunk-4CV4JOE5.js +0 -24
  143. package/dist/chunk-4CV4JOE5.js.map +0 -1
  144. package/dist/chunk-4OCMVGEY.cjs +0 -173
  145. package/dist/chunk-4OCMVGEY.cjs.map +0 -1
  146. package/dist/chunk-4PWRCMTQ.cjs +0 -15
  147. package/dist/chunk-4PWRCMTQ.cjs.map +0 -1
  148. package/dist/chunk-526M5MOA.js +0 -103
  149. package/dist/chunk-526M5MOA.js.map +0 -1
  150. package/dist/chunk-53NYVYVX.js +0 -3243
  151. package/dist/chunk-53NYVYVX.js.map +0 -1
  152. package/dist/chunk-5GFQPHGT.cjs +0 -156
  153. package/dist/chunk-5GFQPHGT.cjs.map +0 -1
  154. package/dist/chunk-5RPRLTTN.js +0 -861
  155. package/dist/chunk-5RPRLTTN.js.map +0 -1
  156. package/dist/chunk-7OGPN7MP.js +0 -352
  157. package/dist/chunk-7OGPN7MP.js.map +0 -1
  158. package/dist/chunk-7OS7TX2Q.cjs +0 -495
  159. package/dist/chunk-7OS7TX2Q.cjs.map +0 -1
  160. package/dist/chunk-ADLJSJSN.cjs +0 -13
  161. package/dist/chunk-ADLJSJSN.cjs.map +0 -1
  162. package/dist/chunk-AN2L2CJZ.js +0 -2728
  163. package/dist/chunk-AN2L2CJZ.js.map +0 -1
  164. package/dist/chunk-BYBMTIMT.js +0 -419
  165. package/dist/chunk-BYBMTIMT.js.map +0 -1
  166. package/dist/chunk-CF7OL6HR.js +0 -355
  167. package/dist/chunk-CF7OL6HR.js.map +0 -1
  168. package/dist/chunk-CJX74IYK.js +0 -489
  169. package/dist/chunk-CJX74IYK.js.map +0 -1
  170. package/dist/chunk-CKVOU6MX.cjs +0 -52
  171. package/dist/chunk-CKVOU6MX.cjs.map +0 -1
  172. package/dist/chunk-CZLDE2OZ.cjs +0 -28
  173. package/dist/chunk-CZLDE2OZ.cjs.map +0 -1
  174. package/dist/chunk-DPA3KWPY.cjs +0 -205
  175. package/dist/chunk-DPA3KWPY.cjs.map +0 -1
  176. package/dist/chunk-EEJUFDMF.cjs +0 -424
  177. package/dist/chunk-EEJUFDMF.cjs.map +0 -1
  178. package/dist/chunk-FIAMXNTH.js +0 -220
  179. package/dist/chunk-FIAMXNTH.js.map +0 -1
  180. package/dist/chunk-GAOXD3XT.js +0 -175
  181. package/dist/chunk-GAOXD3XT.js.map +0 -1
  182. package/dist/chunk-GTGRLD4Y.js +0 -3
  183. package/dist/chunk-GTGRLD4Y.js.map +0 -1
  184. package/dist/chunk-GUUB5EAG.cjs +0 -223
  185. package/dist/chunk-GUUB5EAG.cjs.map +0 -1
  186. package/dist/chunk-GXFOGU7N.cjs +0 -359
  187. package/dist/chunk-GXFOGU7N.cjs.map +0 -1
  188. package/dist/chunk-GYIJ3JJM.cjs +0 -1069
  189. package/dist/chunk-GYIJ3JJM.cjs.map +0 -1
  190. package/dist/chunk-GZS4LMR7.js +0 -422
  191. package/dist/chunk-GZS4LMR7.js.map +0 -1
  192. package/dist/chunk-HY6B7B5A.js +0 -150
  193. package/dist/chunk-HY6B7B5A.js.map +0 -1
  194. package/dist/chunk-IDVRRRAK.cjs +0 -824
  195. package/dist/chunk-IDVRRRAK.cjs.map +0 -1
  196. package/dist/chunk-ISKYUUP4.cjs +0 -6486
  197. package/dist/chunk-ISKYUUP4.cjs.map +0 -1
  198. package/dist/chunk-KC2GDBLS.cjs +0 -84
  199. package/dist/chunk-KC2GDBLS.cjs.map +0 -1
  200. package/dist/chunk-L4EZKIEX.js +0 -185
  201. package/dist/chunk-L4EZKIEX.js.map +0 -1
  202. package/dist/chunk-LNTFRAHF.cjs +0 -473
  203. package/dist/chunk-LNTFRAHF.cjs.map +0 -1
  204. package/dist/chunk-MTIRYI7F.cjs +0 -4
  205. package/dist/chunk-MTIRYI7F.cjs.map +0 -1
  206. package/dist/chunk-N4GN6Q3V.cjs +0 -869
  207. package/dist/chunk-N4GN6Q3V.cjs.map +0 -1
  208. package/dist/chunk-N4H37VN4.cjs +0 -259
  209. package/dist/chunk-N4H37VN4.cjs.map +0 -1
  210. package/dist/chunk-N5QSHUA6.js +0 -1135
  211. package/dist/chunk-N5QSHUA6.js.map +0 -1
  212. package/dist/chunk-NKPKR5BW.cjs +0 -188
  213. package/dist/chunk-NKPKR5BW.cjs.map +0 -1
  214. package/dist/chunk-NQJJYRLP.cjs +0 -110
  215. package/dist/chunk-NQJJYRLP.cjs.map +0 -1
  216. package/dist/chunk-OJ2AM75W.cjs +0 -253
  217. package/dist/chunk-OJ2AM75W.cjs.map +0 -1
  218. package/dist/chunk-OX6GOIPH.js +0 -516
  219. package/dist/chunk-OX6GOIPH.js.map +0 -1
  220. package/dist/chunk-P2YW545G.js +0 -11
  221. package/dist/chunk-P2YW545G.js.map +0 -1
  222. package/dist/chunk-PHJRNPHY.cjs +0 -3291
  223. package/dist/chunk-PHJRNPHY.cjs.map +0 -1
  224. package/dist/chunk-Q72BOAPK.js +0 -817
  225. package/dist/chunk-Q72BOAPK.js.map +0 -1
  226. package/dist/chunk-QU2RFFH4.js +0 -3
  227. package/dist/chunk-QU2RFFH4.js.map +0 -1
  228. package/dist/chunk-RP7VZUEL.js +0 -49
  229. package/dist/chunk-RP7VZUEL.js.map +0 -1
  230. package/dist/chunk-SHTTJMLT.cjs +0 -361
  231. package/dist/chunk-SHTTJMLT.cjs.map +0 -1
  232. package/dist/chunk-THBQG64D.cjs +0 -425
  233. package/dist/chunk-THBQG64D.cjs.map +0 -1
  234. package/dist/chunk-TQG7G7YI.cjs +0 -526
  235. package/dist/chunk-TQG7G7YI.cjs.map +0 -1
  236. package/dist/chunk-U3VVLYXG.cjs +0 -189
  237. package/dist/chunk-U3VVLYXG.cjs.map +0 -1
  238. package/dist/chunk-UUDTPZX6.js +0 -193
  239. package/dist/chunk-UUDTPZX6.js.map +0 -1
  240. package/dist/chunk-VKREAIBA.cjs +0 -1139
  241. package/dist/chunk-VKREAIBA.cjs.map +0 -1
  242. package/dist/chunk-WDTTHKDS.js +0 -458
  243. package/dist/chunk-WDTTHKDS.js.map +0 -1
  244. package/dist/chunk-WXVB364T.js +0 -218
  245. package/dist/chunk-WXVB364T.js.map +0 -1
  246. package/dist/chunk-X4BPPD6K.js +0 -181
  247. package/dist/chunk-X4BPPD6K.js.map +0 -1
  248. package/dist/chunk-XEB7PH2E.js +0 -81
  249. package/dist/chunk-XEB7PH2E.js.map +0 -1
  250. package/dist/chunk-XHAAAEXX.js +0 -1055
  251. package/dist/chunk-XHAAAEXX.js.map +0 -1
  252. package/dist/chunk-YT7HXXVN.js +0 -13
  253. package/dist/chunk-YT7HXXVN.js.map +0 -1
  254. package/dist/cli/index.cjs.map +0 -1
  255. package/dist/cli/index.js.map +0 -1
  256. package/dist/client.cjs.map +0 -1
  257. package/dist/client.js.map +0 -1
  258. package/dist/drizzle/index.cjs.map +0 -1
  259. package/dist/drizzle/index.js.map +0 -1
  260. package/dist/fields/index.cjs.map +0 -1
  261. package/dist/fields/index.js.map +0 -1
  262. package/dist/graphql/index.cjs.map +0 -1
  263. package/dist/graphql/index.js.map +0 -1
  264. package/dist/index.cjs.map +0 -1
  265. package/dist/index.js.map +0 -1
  266. package/dist/integration.cjs.map +0 -1
  267. package/dist/integration.js.map +0 -1
  268. package/dist/media-7WDX4BDJ.js +0 -4
  269. package/dist/media-7WDX4BDJ.js.map +0 -1
  270. package/dist/media-TUSLVRQ6.cjs +0 -17
  271. package/dist/media-TUSLVRQ6.cjs.map +0 -1
  272. package/dist/mongo-auth-adapter-GT4S7SCU.cjs +0 -17
  273. package/dist/mongo-auth-adapter-GT4S7SCU.cjs.map +0 -1
  274. package/dist/mongo-auth-adapter-M7VV4LNB.js +0 -4
  275. package/dist/mongo-auth-adapter-M7VV4LNB.js.map +0 -1
  276. package/dist/mongodb/index.cjs.map +0 -1
  277. package/dist/mongodb/index.js.map +0 -1
  278. package/dist/postgres-auth-adapter-AFAPISH7.js +0 -5
  279. package/dist/postgres-auth-adapter-AFAPISH7.js.map +0 -1
  280. package/dist/postgres-auth-adapter-SFDTLONT.cjs +0 -14
  281. package/dist/postgres-auth-adapter-SFDTLONT.cjs.map +0 -1
  282. package/dist/redis-adapter-UQX4EE3B.cjs +0 -13
  283. package/dist/redis-adapter-UQX4EE3B.cjs.map +0 -1
  284. package/dist/redis-adapter-XALOGWY3.js +0 -4
  285. package/dist/redis-adapter-XALOGWY3.js.map +0 -1
  286. package/dist/rest/index.cjs.map +0 -1
  287. package/dist/rest/index.js.map +0 -1
  288. package/dist/schema-6QL3USNB.cjs +0 -67
  289. package/dist/schema-6QL3USNB.cjs.map +0 -1
  290. package/dist/schema-FNNWEAAW.js +0 -6
  291. package/dist/schema-FNNWEAAW.js.map +0 -1
  292. package/dist/sqlite-adapter-AQB5TCGV.cjs +0 -13
  293. package/dist/sqlite-adapter-AQB5TCGV.cjs.map +0 -1
  294. package/dist/sqlite-adapter-N5H6IM2X.js +0 -4
  295. package/dist/sqlite-adapter-N5H6IM2X.js.map +0 -1
  296. package/dist/templates/index.cjs.map +0 -1
  297. package/dist/templates/index.js.map +0 -1
  298. package/dist/trpc/index.cjs.map +0 -1
  299. package/dist/trpc/index.js.map +0 -1
  300. package/dist/ws/index.cjs.map +0 -1
  301. package/dist/ws/index.js.map +0 -1
@@ -0,0 +1,114 @@
1
+ import {a,d,j,k,e,h,i}from'./chunk-OG7CNQGU.js';import {sql,eq,desc,and,gt}from'drizzle-orm';import O from'bcryptjs';import {randomBytes}from'crypto';var D=false,S=class{db;prefix;sessionTTL;refreshTokenTTL;constructor(e){this.db=e.db,this.prefix=e.prefix||"kyro:",this.sessionTTL=e.sessionTTL||86400,this.refreshTokenTTL=e.refreshTokenTTL||604800;}async connect(){D||(await this.db.execute(sql`
2
+ CREATE TABLE IF NOT EXISTS "users" (
3
+ "id" UUID PRIMARY KEY DEFAULT gen_random_uuid(),
4
+ "name" VARCHAR(255),
5
+ "email" VARCHAR(255) NOT NULL,
6
+ "password_hash" VARCHAR(255),
7
+ "role" VARCHAR(50) NOT NULL DEFAULT 'customer',
8
+ "tenant_id" UUID,
9
+ "email_verified" BOOLEAN DEFAULT false,
10
+ "locked" BOOLEAN DEFAULT false,
11
+ "last_login" TIMESTAMP,
12
+ "failed_login_attempts" INTEGER DEFAULT 0,
13
+ "metadata" JSONB,
14
+ "avatar" VARCHAR(255),
15
+ "created_at" TIMESTAMP NOT NULL DEFAULT NOW(),
16
+ "updated_at" TIMESTAMP NOT NULL DEFAULT NOW()
17
+ )
18
+ `),await this.db.execute(sql`ALTER TABLE "users" ADD COLUMN IF NOT EXISTS "avatar" VARCHAR(255)`),await this.db.execute(sql`CREATE UNIQUE INDEX IF NOT EXISTS "users_email_idx" ON "users" ("email")`),await this.db.execute(sql`CREATE INDEX IF NOT EXISTS "users_tenant_idx" ON "users" ("tenant_id")`),await this.db.execute(sql`CREATE INDEX IF NOT EXISTS "users_role_idx" ON "users" ("role")`),await this.db.execute(sql`
19
+ CREATE TABLE IF NOT EXISTS "sessions" (
20
+ "id" UUID PRIMARY KEY DEFAULT gen_random_uuid(),
21
+ "user_id" UUID NOT NULL REFERENCES "users"("id") ON DELETE CASCADE,
22
+ "token" VARCHAR(512) NOT NULL UNIQUE,
23
+ "refresh_token" VARCHAR(512),
24
+ "ip_address" VARCHAR(45),
25
+ "user_agent" TEXT,
26
+ "expires_at" TIMESTAMP NOT NULL,
27
+ "created_at" TIMESTAMP NOT NULL DEFAULT NOW()
28
+ )
29
+ `),await this.db.execute(sql`CREATE INDEX IF NOT EXISTS "sessions_user_idx" ON "sessions" ("user_id")`),await this.db.execute(sql`CREATE INDEX IF NOT EXISTS "sessions_token_idx" ON "sessions" ("token")`),await this.db.execute(sql`CREATE INDEX IF NOT EXISTS "sessions_expires_idx" ON "sessions" ("expires_at")`),await this.db.execute(sql`
30
+ CREATE TABLE IF NOT EXISTS "audit_logs" (
31
+ "id" UUID PRIMARY KEY DEFAULT gen_random_uuid(),
32
+ "action" VARCHAR(100) NOT NULL,
33
+ "user_id" UUID REFERENCES "users"("id") ON DELETE SET NULL,
34
+ "user_email" VARCHAR(255),
35
+ "role" VARCHAR(50),
36
+ "resource" VARCHAR(100) NOT NULL,
37
+ "resource_id" VARCHAR(255),
38
+ "changes" JSONB,
39
+ "ip_address" VARCHAR(45),
40
+ "user_agent" TEXT,
41
+ "success" BOOLEAN NOT NULL DEFAULT true,
42
+ "error" TEXT,
43
+ "metadata" JSONB,
44
+ "timestamp" TIMESTAMP NOT NULL DEFAULT NOW()
45
+ )
46
+ `),await this.db.execute(sql`ALTER TABLE "audit_logs" ALTER COLUMN "resource_id" TYPE VARCHAR(255)`),await this.db.execute(sql`CREATE INDEX IF NOT EXISTS "audit_logs_user_idx" ON "audit_logs" ("user_id")`),await this.db.execute(sql`CREATE INDEX IF NOT EXISTS "audit_logs_action_idx" ON "audit_logs" ("action")`),await this.db.execute(sql`CREATE INDEX IF NOT EXISTS "audit_logs_resource_idx" ON "audit_logs" ("resource")`),await this.db.execute(sql`CREATE INDEX IF NOT EXISTS "audit_logs_timestamp_idx" ON "audit_logs" ("timestamp")`),await this.db.execute(sql`
47
+ CREATE TABLE IF NOT EXISTS "password_history" (
48
+ "id" UUID PRIMARY KEY DEFAULT gen_random_uuid(),
49
+ "user_id" UUID NOT NULL REFERENCES "users"("id") ON DELETE CASCADE,
50
+ "password_hash" VARCHAR(255) NOT NULL,
51
+ "created_at" TIMESTAMP NOT NULL DEFAULT NOW()
52
+ )
53
+ `),await this.db.execute(sql`CREATE INDEX IF NOT EXISTS "password_history_user_idx" ON "password_history" ("user_id")`),await this.db.execute(sql`
54
+ CREATE TABLE IF NOT EXISTS "lockouts" (
55
+ "id" UUID PRIMARY KEY DEFAULT gen_random_uuid(),
56
+ "user_id" UUID NOT NULL REFERENCES "users"("id") ON DELETE CASCADE,
57
+ "ip_address" VARCHAR(45),
58
+ "reason" VARCHAR(255),
59
+ "locked_until" TIMESTAMP NOT NULL,
60
+ "released_at" TIMESTAMP,
61
+ "created_at" TIMESTAMP NOT NULL DEFAULT NOW()
62
+ )
63
+ `),await this.db.execute(sql`CREATE INDEX IF NOT EXISTS "lockouts_user_idx" ON "lockouts" ("user_id")`),await this.db.execute(sql`CREATE INDEX IF NOT EXISTS "lockouts_locked_until_idx" ON "lockouts" ("locked_until")`),await this.db.execute(sql`
64
+ CREATE TABLE IF NOT EXISTS "roles" (
65
+ "id" UUID PRIMARY KEY DEFAULT gen_random_uuid(),
66
+ "name" VARCHAR(100) NOT NULL UNIQUE,
67
+ "level" INTEGER NOT NULL DEFAULT 0,
68
+ "inherits" TEXT[],
69
+ "description" TEXT,
70
+ "permissions" JSONB DEFAULT '[]',
71
+ "is_system" BOOLEAN DEFAULT false,
72
+ "created_at" TIMESTAMP NOT NULL DEFAULT NOW(),
73
+ "updated_at" TIMESTAMP NOT NULL DEFAULT NOW()
74
+ )
75
+ `),await this.db.execute(sql`CREATE INDEX IF NOT EXISTS "roles_level_idx" ON "roles" ("level")`),await this.db.execute(sql`
76
+ CREATE TABLE IF NOT EXISTS "tenants" (
77
+ "id" UUID PRIMARY KEY DEFAULT gen_random_uuid(),
78
+ "name" VARCHAR(255) NOT NULL,
79
+ "slug" VARCHAR(100) NOT NULL UNIQUE,
80
+ "settings" JSONB DEFAULT '{}',
81
+ "is_active" BOOLEAN DEFAULT true,
82
+ "created_at" TIMESTAMP NOT NULL DEFAULT NOW(),
83
+ "updated_at" TIMESTAMP NOT NULL DEFAULT NOW()
84
+ )
85
+ `),await this.db.execute(sql`
86
+ CREATE TABLE IF NOT EXISTS "api_keys" (
87
+ "id" UUID PRIMARY KEY DEFAULT gen_random_uuid(),
88
+ "user_id" UUID NOT NULL REFERENCES "users"("id") ON DELETE CASCADE,
89
+ "name" VARCHAR(255) NOT NULL,
90
+ "key" VARCHAR(64) NOT NULL UNIQUE,
91
+ "key_prefix" VARCHAR(8) NOT NULL,
92
+ "permissions" JSONB DEFAULT '[]',
93
+ "last_used_at" TIMESTAMP,
94
+ "expires_at" TIMESTAMP,
95
+ "created_at" TIMESTAMP NOT NULL DEFAULT NOW()
96
+ )
97
+ `),await this.db.execute(sql`
98
+ CREATE TABLE IF NOT EXISTS "email_verifications" (
99
+ "id" UUID PRIMARY KEY DEFAULT gen_random_uuid(),
100
+ "user_id" UUID NOT NULL REFERENCES "users"("id") ON DELETE CASCADE,
101
+ "token" VARCHAR(64) NOT NULL UNIQUE,
102
+ "expires_at" TIMESTAMP NOT NULL,
103
+ "created_at" TIMESTAMP NOT NULL DEFAULT NOW()
104
+ )
105
+ `),await this.db.execute(sql`
106
+ CREATE TABLE IF NOT EXISTS "password_resets" (
107
+ "id" UUID PRIMARY KEY DEFAULT gen_random_uuid(),
108
+ "user_id" UUID NOT NULL REFERENCES "users"("id") ON DELETE CASCADE,
109
+ "token" VARCHAR(64) NOT NULL UNIQUE,
110
+ "expires_at" TIMESTAMP NOT NULL,
111
+ "used_at" TIMESTAMP,
112
+ "created_at" TIMESTAMP NOT NULL DEFAULT NOW()
113
+ )
114
+ `),D=true);}async disconnect(){}async createUser(e){let s=await this.hashPassword(e.password),[t]=await this.db.insert(a).values({email:e.email.toLowerCase(),name:e.name,passwordHash:s,role:e.role||"customer",avatar:e.avatar,tenantId:e.tenantId}).returning();return this.userToAuthUser(t)}async findUserByEmail(e){let[s]=await this.db.select().from(a).where(eq(a.email,e.toLowerCase())).limit(1);return s?this.userToAuthUser(s):null}async findUserById(e){let[s]=await this.db.select().from(a).where(eq(a.id,e)).limit(1);return s?this.userToAuthUser(s):null}async updateUser(e,s){let t={updatedAt:new Date};s.name!==void 0&&(t.name=s.name),s.email!==void 0&&(t.email=s.email),s.passwordHash!==void 0&&(t.passwordHash=s.passwordHash),s.role!==void 0&&(t.role=s.role),s.tenantId!==void 0&&(t.tenantId=s.tenantId),s.avatar!==void 0&&(t.avatar=s.avatar),s.emailVerified!==void 0&&(t.emailVerified=s.emailVerified),s.locked!==void 0&&(t.locked=s.locked),s.lastLogin!==void 0&&(t.lastLogin=s.lastLogin?new Date(s.lastLogin):null),s.failedLoginAttempts!==void 0&&(t.failedLoginAttempts=s.failedLoginAttempts);let[r]=await this.db.update(a).set(t).where(eq(a.id,e)).returning();return r?this.userToAuthUser(r):null}async deleteUser(e){return await this.db.delete(a).where(eq(a.id,e)),true}async findUsers(e={}){let s=e.page??1,t=e.limit??10,r=(s-1)*t,u=e.search;if(u){let m=`%${u}%`,[U,[{count:f}]]=await Promise.all([this.db.select().from(a).where(sql`${a.email} ILIKE ${m}`).orderBy(desc(a.createdAt)).limit(t).offset(r),this.db.select({count:sql`count(*)`}).from(a).where(sql`${a.email} ILIKE ${m}`)]);return {users:U.map(c=>this.userToAuthUser(c)),total:Number(f)}}let[l,[{count:E}]]=await Promise.all([this.db.select().from(a).orderBy(desc(a.createdAt)).limit(t).offset(r),this.db.select({count:sql`count(*)`}).from(a)]);return {users:l.map(m=>this.userToAuthUser(m)),total:Number(E)}}async verifyPassword(e,s){let t=await this.findUserByEmail(e);if(!t)return null;let[r]=await this.db.select().from(a).where(eq(a.email,e.toLowerCase())).limit(1);return r?.passwordHash&&await O.compare(s,r.passwordHash)?t:null}async hashPassword(e){return O.hash(e,12)}async createSession(e,s){let t=randomBytes(32).toString("base64url"),r=randomBytes(32).toString("base64url"),u=new Date(Date.now()+this.sessionTTL*1e3);new Date(Date.now()+this.refreshTokenTTL*1e3);let [E]=await this.db.insert(d).values({userId:e,token:t,refreshToken:r,ipAddress:s?.ipAddress,userAgent:s?.userAgent,expiresAt:u}).returning();return this.sessionToSession(E)}async findSessionByToken(e){let[s]=await this.db.select().from(d).where(and(eq(d.token,e),gt(d.expiresAt,new Date))).limit(1);return s?this.sessionToSession(s):null}async findSessionByRefreshToken(e){let[s]=await this.db.select().from(d).where(and(eq(d.refreshToken,e),gt(d.expiresAt,new Date))).limit(1);return s?this.sessionToSession(s):null}async deleteSession(e){return await this.db.delete(d).where(eq(d.id,e)),true}async deleteUserSessions(e){return await this.db.delete(d).where(eq(d.userId,e)),1}async addPasswordToHistory(e,s){await this.db.insert(j).values({userId:e,passwordHash:s});}async getPasswordHistory(e,s=5){return (await this.db.select({passwordHash:j.passwordHash}).from(j).where(eq(j.userId,e)).orderBy(desc(j.createdAt)).limit(s)).map(r=>r.passwordHash)}async isPasswordInHistory(e,s,t=5){let r=await this.getPasswordHistory(s,t);for(let u of r)if(await this.verifyPassword(e,u))return true;return false}async isLocked(e){let[s]=await this.db.select().from(k).where(and(eq(k.userId,e),gt(k.lockedUntil,new Date))).limit(1);return !!s}async getLockout(e){let[s]=await this.db.select().from(k).where(and(eq(k.userId,e),gt(k.lockedUntil,new Date))).limit(1);return s?{lockedUntil:s.lockedUntil}:null}async recordFailedAttempt(e,s){let r=((await this.findUserById(e))?.failedLoginAttempts||0)+1;await this.updateUser(e,{failedLoginAttempts:r});let l=r>=5;return l&&await this.db.insert(k).values({userId:e,ipAddress:s,reason:"Too many failed login attempts",lockedUntil:new Date(Date.now()+9e5)}),{attempts:r,locked:l}}async resetAttempts(e){await this.updateUser(e,{failedLoginAttempts:0});}async findAuditLogs(e$1){let{limit:s=50,offset:t=0,userId:r,action:u,resource:l,resourceId:E,success:m,startDate:U,endDate:f}=e$1,c=[];r&&c.push(eq(e.userId,r)),u&&(Array.isArray(u)?c.push(sql`${e.action} = ANY(${u})`):c.push(eq(e.action,u))),l&&c.push(eq(e.resource,l)),E&&c.push(eq(e.resourceId,E)),m!==void 0&&c.push(eq(e.success,m)),U&&c.push(sql`${e.timestamp} >= ${U}`),f&&c.push(sql`${e.timestamp} <= ${f}`);let R=c.length>0?and(...c):void 0,_=await this.db.select({count:sql`count(*)`}).from(e).where(R);return {logs:(await this.db.select().from(e).where(R).orderBy(desc(e.timestamp)).limit(s).offset(t)).map(o=>({id:o.id,timestamp:o.timestamp,action:o.action,userId:o.userId||void 0,userEmail:o.userEmail||void 0,role:o.role||void 0,resource:o.resource,resourceId:o.resourceId||void 0,changes:o.changes||void 0,ipAddress:o.ipAddress||void 0,userAgent:o.userAgent||void 0,success:o.success,error:o.error||void 0,metadata:o.metadata||void 0})),total:Number(_[0]?.count||0)}}async createAuditLog(e$1){let s=crypto.randomUUID(),t=new Date;return await this.db.insert(e).values({id:s,action:e$1.action,userId:e$1.userId??null,userEmail:e$1.userEmail??null,role:e$1.role??null,resource:e$1.resource,resourceId:e$1.resourceId??null,changes:e$1.changes??null,ipAddress:e$1.ipAddress??null,userAgent:e$1.userAgent??null,success:e$1.success,error:e$1.error??null,metadata:e$1.metadata??null,timestamp:t}),{...e$1,id:s,timestamp:t}}userToAuthUser(e){return {id:e.id,name:e.name||void 0,email:e.email,passwordHash:e.passwordHash||void 0,role:e.role,avatar:e.avatar&&typeof e.avatar=="object"?e.avatar.id||void 0:e.avatar||void 0,tenantId:e.tenantId||void 0,emailVerified:e.emailVerified||false,locked:e.locked||false,lastLogin:e.lastLogin?new Date(e.lastLogin).toISOString():void 0,failedLoginAttempts:e.failedLoginAttempts||0,createdAt:new Date(e.createdAt).toISOString(),updatedAt:new Date(e.updatedAt).toISOString()}}sessionToSession(e){return {id:e.id,userId:e.userId,token:e.token,refreshToken:e.refreshToken||void 0,expiresAt:new Date(e.expiresAt).toISOString(),createdAt:new Date(e.createdAt).toISOString(),ipAddress:e.ipAddress||void 0,userAgent:e.userAgent||void 0}}async createEmailVerificationToken(e){let s=randomBytes(32).toString("hex"),t=new Date(Date.now()+1440*60*1e3);return await this.db.insert(h).values({userId:e,token:s,expiresAt:t}),{token:s,expiresAt:t}}async verifyEmailToken(e){let[s]=await this.db.select().from(h).where(eq(h.token,e)).limit(1);return s?s.expiresAt<new Date?{success:false,error:"Verification token has expired"}:(await this.db.update(a).set({emailVerified:true}).where(eq(a.id,s.userId)),await this.db.delete(h).where(eq(h.id,s.id)),{success:true,userId:s.userId}):{success:false,error:"Invalid verification token"}}async createPasswordResetToken(e){let s=await this.findUserByEmail(e);if(!s)return {token:"",expiresAt:new Date,error:"User not found"};let t=randomBytes(32).toString("hex"),r=new Date(Date.now()+3600*1e3);return await this.db.insert(i).values({userId:s.id,token:t,expiresAt:r}),{token:t,expiresAt:r}}async resetPasswordWithToken(e,s){let[t]=await this.db.select().from(i).where(eq(i.token,e)).limit(1);if(!t)return {success:false,error:"Invalid reset token"};if(t.expiresAt<new Date)return {success:false,error:"Reset token has expired"};if(t.usedAt)return {success:false,error:"Reset token has already been used"};let r=await this.hashPassword(s);return await this.db.update(a).set({passwordHash:r,updatedAt:new Date}).where(eq(a.id,t.userId)),await this.db.update(i).set({usedAt:new Date}).where(eq(i.id,t.id)),await this.db.delete(d).where(eq(d.userId,t.userId)),{success:true}}};export{S as a};
@@ -0,0 +1 @@
1
+ import {WebSocketServer,WebSocket}from'ws';var o=class{channels=new Map;maxListeners;constructor(e=100){this.maxListeners=e;}subscribe(e,t){this.channels.has(e)||this.channels.set(e,new Set);let s=this.channels.get(e);if(s.size>=this.maxListeners)throw new Error(`Max listeners (${this.maxListeners}) reached for channel "${e}"`);return s.add(t),()=>{s.delete(t),s.size===0&&this.channels.delete(e);}}publish(e,t){let s=this.channels.get(e);if(s)for(let n of s)try{let i=n(t);i instanceof Promise&&i.catch(l=>{console.error(`[PubSub] Error in handler for channel "${e}":`,l);});}catch(i){console.error(`[PubSub] Error in handler for channel "${e}":`,i);}}hasSubscribers(e){return this.channels.has(e)&&this.channels.get(e).size>0}getSubscriberCount(e){return this.channels.get(e)?.size||0}getChannels(){return Array.from(this.channels.keys())}clear(){this.channels.clear();}},c=class extends o{registry;constructor(e,t=100){super(t),this.registry=e;}publishCollectionEvent(e,t){this.publish(`collection:${e}`,t),this.publish("events:collection",t),t.tenantID&&(this.publish(`tenant:${t.tenantID}:collection:${e}`,t),this.publish(`tenant:${t.tenantID}:events`,t)),this.publish(`collection:${e}:${t.type}`,t);}subscribeToCollection(e,t){return this.subscribe(`collection:${e}`,t)}subscribeToCollectionEvent(e,t,s){return this.subscribe(`collection:${e}:${t}`,s)}subscribeToTenant(e,t){return this.subscribe(`tenant:${e}:events`,t)}subscribeToTenantCollection(e,t,s){return this.subscribe(`tenant:${e}:collection:${t}`,s)}subscribeToAllCollections(e){return this.subscribe("events:collection",e)}createAfterChangeHook(e){return async t=>{this.publishCollectionEvent(e,{type:t.operation==="create"?"create":"update",collection:e,doc:t.doc,originalDoc:t.originalDoc,id:t.id||t.doc?.id,tenantID:t.tenantID,timestamp:new Date().toISOString(),user:t.user});}}createAfterDeleteHook(e){return async t=>{this.publishCollectionEvent(e,{type:"delete",collection:e,doc:t.doc,originalDoc:t.originalDoc,id:t.id||t.doc?.id,tenantID:t.tenantID,timestamp:new Date().toISOString(),user:t.user});}}autoRegisterHooks(){let e=this.registry.getCollections();for(let t of e){let s=this.registry.getCollection(t.slug);s&&(s.hooks||(s.hooks={}),s.hooks.afterChange||(s.hooks.afterChange=[]),s.hooks.afterDelete||(s.hooks.afterDelete=[]),s.hooks.afterChange.push(this.createAfterChangeHook(t.slug)),s.hooks.afterDelete.push(this.createAfterDeleteHook(t.slug)));}}};var a=class{wss;clients=new Map;pubsub;options;pingTimer;constructor(e){this.options=e,this.pubsub=e.pubsub,this.wss=new WebSocketServer({port:e.port||8080}),this.setupServer(),this.startPingInterval();}setupServer(){this.wss.on("connection",(e,t)=>{let s=this.generateClientId();if(this.options.maxConnections&&this.clients.size>=this.options.maxConnections){e.close(1013,"Server at capacity");return}let n={id:s,ws:e,subscriptions:new Map,authenticated:false,connectedAt:new Date,lastActivity:new Date};this.clients.set(s,n),this.sendToClient(n,{type:"connected",clientId:s,timestamp:new Date().toISOString()}),e.on("message",i=>{this.handleMessage(n,i);}),e.on("error",i=>{console.error(`[WS] Client error ${s}:`,i);}),e.on("close",()=>{this.handleDisconnect(n);}),e.on("pong",()=>{n.lastActivity=new Date;});}),this.wss.on("error",e=>{console.error("[WS] Server error:",e);});}handleMessage(e,t){e.lastActivity=new Date;let s;try{s=JSON.parse(t.toString());}catch{this.sendToClient(e,{type:"error",error:"Invalid JSON"});return}switch(s.type){case "authenticate":this.handleAuthenticate(e,s);break;case "subscribe":this.handleSubscribe(e,s);break;case "unsubscribe":this.handleUnsubscribe(e,s);break;case "unsubscribeAll":this.handleUnsubscribeAll(e);break;case "list":this.handleList(e);break;case "ping":this.sendToClient(e,{type:"pong",timestamp:new Date().toISOString()});break;default:this.sendToClient(e,{type:"error",error:`Unknown message type: ${s.type}`});}}async handleAuthenticate(e,t){if(!this.options.requireAuth){e.authenticated=true,this.sendToClient(e,{type:"authenticated",success:true});return}if(!this.options.verifyToken){e.authenticated=true,this.sendToClient(e,{type:"authenticated",success:true});return}try{let s=await this.options.verifyToken(t.token);e.authenticated=!0,e.user=s,e.tenantID=s.tenantID,this.sendToClient(e,{type:"authenticated",success:!0,user:{id:s.id,email:s.email}});}catch(s){this.sendToClient(e,{type:"authenticated",success:false,error:s.message});}}handleSubscribe(e,t){if(this.options.requireAuth&&!e.authenticated){this.sendToClient(e,{type:"error",error:"Not authenticated"});return}let s=t.channel;if(!s){this.sendToClient(e,{type:"error",error:"Channel is required"});return}if(e.subscriptions.has(s)){this.sendToClient(e,{type:"subscribed",channel:s,success:true,message:"Already subscribed"});return}let n=this.pubsub.subscribe(s,i=>{this.sendToClient(e,{type:"event",channel:s,data:i,timestamp:new Date().toISOString()});});e.subscriptions.set(s,{channel:s,unsubscribe:n}),this.sendToClient(e,{type:"subscribed",channel:s,success:true});}handleUnsubscribe(e,t){let s=t.channel;if(!s){this.sendToClient(e,{type:"error",error:"Channel is required"});return}let n=e.subscriptions.get(s);n?(n.unsubscribe(),e.subscriptions.delete(s),this.sendToClient(e,{type:"unsubscribed",channel:s,success:true})):this.sendToClient(e,{type:"unsubscribed",channel:s,success:false,message:"Not subscribed"});}handleUnsubscribeAll(e){for(let[,t]of e.subscriptions)t.unsubscribe();e.subscriptions.clear(),this.sendToClient(e,{type:"unsubscribedAll",success:true});}handleList(e){let t=this.pubsub.getChannels();this.sendToClient(e,{type:"channels",channels:t,count:t.length});}handleDisconnect(e){for(let[,t]of e.subscriptions)t.unsubscribe();this.clients.delete(e.id);}sendToClient(e,t){e.ws.readyState===WebSocket.OPEN&&e.ws.send(JSON.stringify(t));}generateClientId(){return `ws_${Date.now()}_${Math.random().toString(36).slice(2,9)}`}startPingInterval(){this.options.pingInterval&&(this.pingTimer=setInterval(()=>{for(let[e,t]of this.clients)if(t.ws.readyState===WebSocket.OPEN){if(Date.now()-t.lastActivity.getTime()>this.options.pingInterval*3){t.ws.terminate(),this.handleDisconnect(t);continue}t.ws.ping();}},this.options.pingInterval));}broadcast(e,t){this.pubsub.publish(e,t);}getConnectedClients(){return Array.from(this.clients.values())}getClientCount(){return this.clients.size}getSubscriptionCount(){let e=0;for(let t of this.clients.values())e+=t.subscriptions.size;return e}async close(){this.pingTimer&&clearInterval(this.pingTimer);for(let e of this.clients.values())e.ws.close(1001,"Server shutting down");return new Promise(e=>{this.wss.close(()=>{e();});})}getServer(){return this.wss}};function p(r){return new a(r)}export{o as a,c as b,a as c,p as d};
@@ -0,0 +1,21 @@
1
+ 'use strict';var chunk65G73T7Z_cjs=require('./chunk-65G73T7Z.cjs'),chunkCVVW4LXZ_cjs=require('./chunk-CVVW4LXZ.cjs'),chunkCIE3XMLH_cjs=require('./chunk-CIE3XMLH.cjs'),chunkF3Z67QWS_cjs=require('./chunk-F3Z67QWS.cjs'),chunkISWMETHJ_cjs=require('./chunk-ISWMETHJ.cjs'),chunkNY47CFVP_cjs=require('./chunk-NY47CFVP.cjs'),chunkF7SR5IDT_cjs=require('./chunk-F7SR5IDT.cjs'),chunk6CLRVJPP_cjs=require('./chunk-6CLRVJPP.cjs'),chunkMIOMMB23_cjs=require('./chunk-MIOMMB23.cjs'),chunkDV4LFLPL_cjs=require('./chunk-DV4LFLPL.cjs'),zod=require('zod'),graphqlYoga=require('graphql-yoga'),module$1=require('module'),crypto=require('crypto');var _documentCurrentScript=typeof document!=='undefined'?document.currentScript:null;function O(n,e){for(let t of n){if(t.name===e)return true;if("tabs"in t&&t.tabs){for(let s of t.tabs)if(O(s.fields,e))return true}if("fields"in t&&t.fields&&O(t.fields,e))return true}return false}var K=class extends Error{errors;constructor(e){super(`Configuration validation failed:
2
+ ${e.join(`
3
+ `)}`),this.name="ConfigValidationError",this.errors=e;}};function V(n){let e=[];if(n.slug?/^[a-z][a-z0-9_-]*$/.test(n.slug)||e.push(`Collection slug "${n.slug}" must be lowercase alphanumeric with dashes`):e.push('Collection is missing a "slug" property'),!n.fields||n.fields.length===0)e.push(`Collection "${n.slug}" has no fields defined`);else {let t=x(n.fields,n.slug);e.push(...t);}if(n.access)for(let[t,s]of Object.entries(n.access))typeof s!="boolean"&&typeof s!="function"&&e.push(`Collection "${n.slug}" has invalid access.${t} (must be boolean or function)`);if(n.admin?.useAsTitle&&(O(n.fields,n.admin.useAsTitle)||e.push(`Collection "${n.slug}" admin.useAsTitle references unknown field "${n.admin.useAsTitle}"`)),n.admin?.defaultColumns)for(let t of n.admin.defaultColumns)O(n.fields,t)||e.push(`Collection "${n.slug}" admin.defaultColumns references unknown field "${t}"`);if(n.upload&&n.upload.fileSize&&n.upload.fileSize<=0&&e.push(`Collection "${n.slug}" upload.fileSize must be positive`),n.versions&&n.versions.maxPerDoc&&n.versions.maxPerDoc<=0&&e.push(`Collection "${n.slug}" versions.maxPerDoc must be positive`),n.auth){let t=n.fields.some(a=>a.name==="email"),s=n.fields.some(a=>a.name==="password");t||e.push(`Collection "${n.slug}" with auth enabled requires an "email" field`),s||e.push(`Collection "${n.slug}" with auth enabled requires a "password" field`);}return e}function B(n){let e=[];if(n.slug?/^[a-z][a-z0-9_-]*$/.test(n.slug)||e.push(`Global slug "${n.slug}" must be lowercase alphanumeric with dashes`):e.push('Global is missing a "slug" property'),!n.fields||n.fields.length===0)e.push(`Global "${n.slug}" has no fields defined`);else {let t=x(n.fields,`global:${n.slug}`);e.push(...t);}return e}function x(n,e){let t=[],s=new Set;for(let a=0;a<n.length;a++){let o=n[a];if(o.type==="row"||o.type==="collapsible"||o.type==="tabs"){if("fields"in o&&o.fields){let r=x(o.fields,e);t.push(...r);}else if("tabs"in o)for(let r of o.tabs){let c=x(r.fields,e);t.push(...c);}continue}let i=o.name;if(!i){t.push(`${e}: Field at index ${a} is missing a "name" property`);continue}if(s.has(i)&&t.push(`${e}: Duplicate field name "${i}"`),s.add(i),/^[a-zA-Z][a-zA-Z0-9_]*$/.test(i)||t.push(`${e}: Field name "${i}" must be alphanumeric with underscores`),!o.type){t.push(`${e}: Field "${i}" is missing a "type" property`);continue}switch(o.type){case "relationship":o.relationTo||t.push(`${e}: Relationship field "${i}" is missing "relationTo"`);break;case "array":if(!o.fields||o.fields.length===0)t.push(`${e}: Array field "${i}" has no fields defined`);else {let r=x(o.fields,`${e}.${i}`);t.push(...r);}break;case "group":if(!o.fields||o.fields.length===0)t.push(`${e}: Group field "${i}" has no fields defined`);else {let r=x(o.fields,`${e}.${i}`);t.push(...r);}break;case "blocks":if(!o.blocks||o.blocks.length===0)t.push(`${e}: Blocks field "${i}" has no blocks defined`);else {let r=ve(o.blocks,`${e}.${i}`);t.push(...r);}break;case "select":case "radio":if((!o.options||o.options.length===0)&&!o.dynamicOptions)t.push(`${e}: ${o.type} field "${i}" has no options defined`);else if(o.options){let r=o.options.map(d=>d.value),c=new Set(r);r.length!==c.size&&t.push(`${e}: ${o.type} field "${i}" has duplicate option values`);}break;case "upload":o.relationTo||t.push(`${e}: Upload field "${i}" is missing "relationTo"`);break}"min"in o&&"max"in o&&o.min>o.max&&t.push(`${e}: Field "${i}" has min greater than max`),"minLength"in o&&"maxLength"in o&&o.minLength>o.maxLength&&t.push(`${e}: Field "${i}" has minLength greater than maxLength`),"minRows"in o&&"maxRows"in o&&o.minRows>o.maxRows&&t.push(`${e}: Field "${i}" has minRows greater than maxRows`);}return t}function ve(n,e){let t=[],s=new Set;for(let a of n){if(!a.slug){t.push(`${e}: Block is missing a "slug" property`);continue}if(s.has(a.slug)&&t.push(`${e}: Duplicate block slug "${a.slug}"`),s.add(a.slug),a.label||t.push(`${e}: Block "${a.slug}" is missing a "label" property`),!a.fields||a.fields.length===0)t.push(`${e}: Block "${a.slug}" has no fields defined`);else {let o=x(a.fields,`${e}.${a.slug}`);t.push(...o);}}return t}function pe(n,e=[]){let t=[],s=new Set;for(let a of n)s.has(a.slug)&&t.push(`Duplicate collection slug "${a.slug}"`),s.add(a.slug);for(let a of e)s.has(a.slug)&&t.push(`Duplicate global slug "${a.slug}"`),s.add(a.slug);for(let a of n){let o=V(a);t.push(...o);}for(let a of e){let o=B(a);t.push(...o);}for(let a of n){let o=$(a.fields,n);t.push(...o);}if(t.length>0)throw new K(t)}function $(n,e){let t=[],s=new Set(e.map(a=>a.slug));for(let a of n){if(a.type==="relationship"){let o=Array.isArray(a.relationTo)?a.relationTo:[a.relationTo];for(let i of o)s.has(i)||console.warn(`[Kyro Config Warning]: Relationship field "${a.name}" references unknown collection "${i}". Select options will not be available until this collection is registered.`);}if(a.type==="upload"){let o=Array.isArray(a.relationTo)?a.relationTo:[a.relationTo];for(let i of o)s.has(i)||t.push(`Upload field "${a.name}" references unknown collection "${i}"`);}if("fields"in a&&a.fields){let o=$(a.fields,e);t.push(...o);}if("tabs"in a)for(let o of a.tabs){let i=$(o.fields,e);t.push(...i);}if("blocks"in a)for(let o of a.blocks){let i=$(o.fields,e);t.push(...i);}}return t}function C(n){switch(n.type){case "text":return De(n);case "number":return we(n);case "checkbox":return Fe(n);case "date":return Ie(n);case "email":return $e(n);case "password":return Oe(n);case "textarea":return Pe(n);case "select":return Le(n);case "radio":return ke(n);case "color":return _e(n);case "richtext":return je(n);case "json":return Ze(n);case "code":return qe(n);case "upload":return fe(n);case "image":return fe(n);case "markdown":return Ue(n);case "relationship":return ye(n);case "relationship-block":return ye(n);case "array":return Ge(n);case "list":return Ke(n);case "group":return Ve(n);case "blocks":return Be(n);case "row":return Me(n);case "collapsible":return ze(n);case "tabs":return We(n);default:return zod.z.any()}}function De(n){let e=zod.z.string();return n.minLength&&(e=e.min(n.minLength)),n.maxLength&&(e=e.max(n.maxLength)),n.pattern&&(e=e.regex(new RegExp(n.pattern))),n.variant==="email"&&(e=e.email()),n.variant==="url"&&(e=e.url()),n.hasMany&&(e=zod.z.array(e)),n.required||(e=e.optional().nullable()),n.validate&&(e=b(e,n.validate)),e}function we(n){let e=n.integer?zod.z.coerce.number().int():zod.z.coerce.number();return n.min!==void 0&&(e=e.min(n.min)),n.max!==void 0&&(e=e.max(n.max)),n.step&&(e=e.refine(t=>Number.isInteger(t/n.step),`Value must be divisible by ${n.step}`)),n.hasMany&&(e=zod.z.array(e)),n.required||(e=e.optional().nullable()),n.validate&&(e=b(e,n.validate)),e}function Fe(n){let e=zod.z.boolean();return n.required||(e=e.optional().nullable()),n.validate&&(e=b(e,n.validate)),e}function Ie(n){let e=zod.z.string().refine(t=>!isNaN(Date.parse(t)),"Invalid date format");return n.minDate&&(e=e.refine(t=>new Date(t)>=new Date(n.minDate),`Date must be after ${n.minDate}`)),n.maxDate&&(e=e.refine(t=>new Date(t)<=new Date(n.maxDate),`Date must be before ${n.maxDate}`)),n.required||(e=e.optional().nullable()),n.validate&&(e=b(e,n.validate)),e}function $e(n){let e=zod.z.string().email("Invalid email");return n.required||(e=e.optional().nullable()),n.validate&&(e=b(e,n.validate)),e}function Oe(n){let e=zod.z.string().min(6,"Password must be at least 6 characters");return n.required||(e=e.optional().nullable()),n.validate&&(e=b(e,n.validate)),e}function Pe(n){let e=zod.z.string();return n.minLength&&(e=e.min(n.minLength)),n.maxLength&&(e=e.max(n.maxLength)),n.required||(e=e.optional().nullable()),n.validate&&(e=b(e,n.validate)),e}function Le(n){let e;if(n.options&&n.options.length>0){let t=n.options.map(s=>s.value);n.hasMany?e=zod.z.array(zod.z.enum(t)):e=zod.z.enum(t);}else e=n.hasMany?zod.z.array(zod.z.string()):zod.z.string();return n.required||(e=e.optional().nullable()),n.validate&&(e=b(e,n.validate)),e}function ke(n){let e=n.options.map(s=>s.value),t=zod.z.enum(e);return n.required||(t=t.optional().nullable()),n.validate&&(t=b(t,n.validate)),t}function _e(n){let e=zod.z.string();return n.format==="hex"&&(e=e.regex(/^#[0-9A-Fa-f]{6}$/)),n.format==="rgb"&&(e=e.regex(/^rgb\(\s*\d{1,3}\s*,\s*\d{1,3}\s*,\s*\d{1,3}\s*\)$/)),n.format==="hsl"&&(e=e.regex(/^hsl\(\s*\d{1,3}\s*,\s*\d{1,3}%\s*,\s*\d{1,3}%\s*\)$/)),n.required||(e=e.optional().nullable()),n.validate&&(e=b(e,n.validate)),e}function je(n){let e=zod.z.array(zod.z.record(zod.z.any()));return n.required||(e=e.optional().nullable()),n.validate&&(e=b(e,n.validate)),e}function Ze(n){let e=zod.z.union([zod.z.record(zod.z.any()),zod.z.array(zod.z.any())]);return n.required||(e=e.optional().nullable()),n.validate&&(e=b(e,n.validate)),e}function qe(n){let e=zod.z.string();return n.required||(e=e.optional().nullable()),n.validate&&(e=b(e,n.validate)),e}function fe(n){let e;if(n.relationTo){let t=zod.z.object({id:zod.z.string(),url:zod.z.string().optional(),filename:zod.z.string().optional(),mimeType:zod.z.string().optional()});e=zod.z.union([zod.z.string(),t]);}else e=zod.z.string();return n.hasMany&&(e=zod.z.array(e)),n.required||(e=e.optional().nullable()),n.validate&&(e=b(e,n.validate)),e}function Ue(n){let e=zod.z.string();return n.required||(e=e.optional().nullable()),n.validate&&(e=b(e,n.validate)),e}function ye(n){let e;return Array.isArray(n.relationTo)?e=zod.z.object({relationTo:zod.z.enum(n.relationTo),value:zod.z.string()}):e=zod.z.union([zod.z.string(),zod.z.object({relationTo:zod.z.string(),value:zod.z.string()})]),n.hasMany&&(e=zod.z.array(e)),n.required||(e=e.optional().nullable()),n.validate&&(e=b(e,n.validate)),e}function Ge(n){let e=zod.z.object(Object.fromEntries(n.fields.filter(s=>s.name).map(s=>[s.name,C(s)]))),t=zod.z.array(e);return n.minRows&&(t=t.min(n.minRows)),n.maxRows&&(t=t.max(n.maxRows)),n.required||(t=t.optional().nullable()),n.validate&&(t=b(t,n.validate)),t}function Ke(n){let e=zod.z.array(zod.z.string());return n.required||(e=e.optional().nullable()),e}function Ve(n){let e=zod.z.object(Object.fromEntries(n.fields.filter(t=>t.name).map(t=>[t.name,C(t)])));return n.required?e:e.optional().nullable()}function Be(n){let e=n.blocks||[];e.map(o=>zod.z.object({blockType:zod.z.literal(o.slug),...Object.fromEntries(o.fields.filter(i=>i.name).map(i=>[i.name,C(i)]))}));let s=e.map(o=>o.slug),a;if(s.length>0){let o=zod.z.object({blockType:zod.z.enum(s)}).catchall(zod.z.any()),i=zod.z.object({blockType:zod.z.string()}).catchall(zod.z.any());a=zod.z.array(zod.z.union([o,i,zod.z.record(zod.z.any())]));}else a=zod.z.array(zod.z.union([zod.z.object({blockType:zod.z.string()}).catchall(zod.z.any()),zod.z.record(zod.z.any())]));return n.minRows&&(a=a.min(n.minRows)),n.maxRows&&(a=a.max(n.maxRows)),n.required||(a=a.optional().nullable()),n.validate&&(a=b(a,n.validate)),a}function Me(n){return zod.z.object(Object.fromEntries(n.fields.filter(t=>t.name).map(t=>[t.name,C(t)])))}function ze(n){return zod.z.object(Object.fromEntries(n.fields.filter(t=>t.name).map(t=>[t.name,C(t)])))}function We(n){let e={};for(let t of n.tabs)for(let s of t.fields)s.name&&(e[s.name]=C(s));return zod.z.object(e).passthrough().optional()}function b(n,e){return n.refine(async t=>await e(t,{required:false})===true,{message:"Custom validation failed"})}function R(n){let e={};for(let t of n)if(t.name)if(t.type==="tabs"&&"tabs"in t){let s={};for(let a of t.tabs){let o=R(a.fields);Object.assign(s,o);}e[t.name]=zod.z.object(s).passthrough().optional();}else if(t.type==="row"&&"fields"in t){let s=R(t.fields);Object.assign(e,s);}else t.type==="collapsible"&&"fields"in t?e[t.name]=zod.z.object(R(t.fields)).passthrough().optional():e[t.name]=C(t);return e}function E(n){let e={};for(let t of n)if(t.name)if(t.type==="tabs"&&"tabs"in t){let s={};for(let a of t.tabs){let o=E(a.fields);Object.assign(s,o);}e[t.name]=zod.z.object(s).passthrough().optional().nullable();}else if(t.type==="row"&&"fields"in t){let s=E(t.fields);Object.assign(e,s);}else t.type==="collapsible"&&"fields"in t?e[t.name]=zod.z.object(E(t.fields)).passthrough().optional().nullable():t.type==="group"&&"fields"in t?e[t.name]=zod.z.object(E(t.fields)).passthrough().optional().nullable():e[t.name]=C(t).optional().nullable();return e}function he(n){let e=R(n.fields);return n.timestamps&&(e.createdAt=zod.z.string().optional(),e.updatedAt=zod.z.string().optional()),n.tenantScoped&&(e.tenantID=zod.z.string().optional()),e.id=zod.z.string().optional(),zod.z.object(e).passthrough()}function ge(n){let e=R(n.fields);return zod.z.object(e).passthrough()}function me(n){let e={};for(let t of n.fields)if(t.name)if(t.type==="tabs"&&"tabs"in t){let s={};for(let a of t.tabs)for(let o of a.fields)o.name&&(s[o.name]=C(o).optional().nullable());e[t.name]=zod.z.object(s).optional().nullable();}else if(t.type==="row"&&"fields"in t){let s={};for(let a of t.fields)a.name&&(s[a.name]=C(a).optional().nullable());Object.assign(e,s);}else t.type==="collapsible"&&"fields"in t?e[t.name]=zod.z.object(E(t.fields)).optional().nullable():t.type==="group"&&"fields"in t?e[t.name]=zod.z.object(E(t.fields)).optional().nullable():e[t.name]=C(t).optional().nullable();return zod.z.object(e).passthrough()}function be(n){let e={};for(let t of n.fields)t.name&&(e[t.name]=zod.z.object({equals:zod.z.any().optional(),not_equals:zod.z.any().optional(),in:zod.z.array(zod.z.any()).optional(),not_in:zod.z.array(zod.z.any()).optional(),greater_than:zod.z.number().optional(),greater_than_equal:zod.z.number().optional(),less_than:zod.z.number().optional(),less_than_equal:zod.z.number().optional(),like:zod.z.string().optional(),not_like:zod.z.string().optional(),contains:zod.z.string().optional(),exists:zod.z.boolean().optional()}).optional());return e.AND=zod.z.array(zod.z.lazy(()=>zod.z.object(e))).optional(),e.OR=zod.z.array(zod.z.lazy(()=>zod.z.object(e))).optional(),zod.z.object(e).optional()}function Te(n){let e=R(n.fields);return e.id=zod.z.string().optional(),zod.z.object(e).passthrough()}function Ce(n){let e={};for(let t of n.fields)if(t.name)if(t.type==="tabs"&&"tabs"in t){let s={};for(let a of t.tabs)for(let o of a.fields)o.name&&(s[o.name]=C(o).optional().nullable());e[t.name]=zod.z.object(s).optional().nullable();}else t.type==="collapsible"&&"fields"in t?e[t.name]=zod.z.object(E(t.fields)).optional().nullable():t.type==="group"&&"fields"in t?e[t.name]=zod.z.object(E(t.fields)).optional().nullable():e[t.name]=C(t).optional().nullable();return zod.z.object(e).passthrough()}var w=class{storageProviders=chunkF3Z67QWS_cjs.f();collections=new Map;globals=new Map;plugins=[];schemaCache=new Map;initialized=false;addCollection(e){if(this.initialized)throw new Error("Cannot add collections after Registry has been initialized");if(this.collections.has(e.slug)){console.warn(`[Registry] Duplicate collection slug "${e.slug}" \u2014 skipping`);return}let t={...e};for(let a of this.plugins)a.extendCollection&&(t=a.extendCollection(t.slug,t));t.fields=this.applyFieldDefaults(t);let s=V(t);if(s.length>0)throw new Error(`Invalid collection config: ${s.join(", ")}`);this.collections.set(t.slug,t),this.clearSchemaCache(t.slug);}addCollections(e){for(let t of e)this.addCollection(t);}getCollection(e){return this.collections.get(e)}getCollections(){return Array.from(this.collections.values())}getCollectionSlugs(){return Array.from(this.collections.keys())}hasCollection(e){return this.collections.has(e)}removeCollection(e){if(this.initialized)throw new Error("Cannot remove collections after Registry has been initialized");return this.clearSchemaCache(e),this.collections.delete(e)}addGlobal(e){if(this.initialized)throw new Error("Cannot add globals after Registry has been initialized");this._addGlobalUnsafe(e);}addGlobalPostInit(e){this.globals.has(e.slug)&&this.globals.delete(e.slug),this._addGlobalUnsafe(e);}_addGlobalUnsafe(e){if(this.globals.has(e.slug)){console.warn(`[Registry] Duplicate global slug "${e.slug}" \u2014 skipping`);return}let t=B(e);if(t.length>0)throw new Error(`Invalid global config: ${t.join(", ")}`);let s={...e};for(let a of this.plugins)a.extendGlobal&&(s=a.extendGlobal(s.slug,s));this.globals.set(s.slug,s),this.clearSchemaCache(`global:${s.slug}`);}addGlobals(e){for(let t of e)this.addGlobal(t);}getGlobal(e){return this.globals.get(e)}getGlobals(){return Array.from(this.globals.values())}getGlobalSlugs(){return Array.from(this.globals.keys())}hasGlobal(e){return this.globals.has(e)}removeGlobal(e){if(this.initialized)throw new Error("Cannot remove globals after Registry has been initialized");return this.clearSchemaCache(`global:${e}`),this.globals.delete(e)}addPlugin(e){if(this.initialized)throw new Error("Cannot add plugins after Registry has been initialized");this.plugins.push(e);}getPlugins(){return [...this.plugins]}getZodSchema(e){let t=this.schemaCache.get(e);if(t)return t;let s=this.collections.get(e);if(s){let o=he(s);return this.schemaCache.set(e,o),o}let a=this.globals.get(e);if(a){let o=Te(a);return this.schemaCache.set(`global:${e}`,o),o}throw new Error(`No collection or global found with slug "${e}"`)}getCreateZodSchema(e){let t=`${e}:create`,s=this.schemaCache.get(t);if(s)return s;let a=this.collections.get(e);if(a){let o=ge(a);return this.schemaCache.set(t,o),o}throw new Error(`No collection found with slug "${e}"`)}getUpdateZodSchema(e){let t=`${e}:update`,s=this.schemaCache.get(t);if(s)return s;let a=this.collections.get(e);if(a){let i=me(a);return this.schemaCache.set(t,i),i}let o=this.globals.get(e);if(o){let i=Ce(o);return this.schemaCache.set(`global:${e}:update`,i),i}throw new Error(`No collection or global found with slug "${e}"`)}getWhereZodSchema(e){let t=`${e}:where`,s=this.schemaCache.get(t);if(s)return s;let a=this.collections.get(e);if(a){let o=be(a);return this.schemaCache.set(t,o),o}throw new Error(`No collection found with slug "${e}"`)}getFieldZodSchema(e){return C(e)}clearSchemaCache(e){this.schemaCache.delete(e),this.schemaCache.delete(`${e}:create`),this.schemaCache.delete(`${e}:update`),this.schemaCache.delete(`${e}:where`);}applyFieldDefaults(e){let t=[...e.fields];return t.some(s=>s.name==="id")||t.unshift({name:"id",type:"text",admin:{readOnly:true,hidden:true}}),e.tenantScoped&&!t.some(s=>s.name==="tenantID")&&t.push({name:"tenantID",type:"text",required:true,admin:{readOnly:true,hidden:true}}),e.timestamps&&!t.some(s=>s.name==="createdAt")&&(t.push({name:"createdAt",type:"date",admin:{readOnly:true,hidden:true}}),t.push({name:"updatedAt",type:"date",admin:{readOnly:true,hidden:true}})),e.versions?.drafts&&!t.some(s=>s.name==="status")&&t.push({name:"status",type:"select",options:[{value:"draft",label:"Draft"},{value:"published",label:"Published"}],admin:{readOnly:true,hidden:true}}),e.auth&&!t.some(s=>s.name==="password")&&t.push({name:"password",type:"password",required:true,admin:{hidden:true}}),t}getFields(e){let t=this.collections.get(e);if(t)return t.fields;let s=this.globals.get(e);if(s)return s.fields;throw new Error(`No collection or global found with slug "${e}"`)}getFieldMap(e){let t=this.getFields(e),s=new Map,a=o=>{for(let i of o){if(i.name&&s.set(i.name,i),"fields"in i&&i.fields&&a(i.fields),"tabs"in i)for(let r of i.tabs)a(r.fields);if("blocks"in i)for(let r of i.blocks)a(r.fields);}};return a(t),s}getVisibleFields(e){return this.getFields(e).filter(s=>!s.admin?.hidden)}validate(){let e=this.getCollections(),t=this.getGlobals();pe(e,t);}async init(e){this.validate();for(let t of this.plugins)t.init&&await t.init(e||this);this.initialized=true;}isInitialized(){return this.initialized}getPaginationDefaults(e){let t=this.collections.get(e);return {defaultLimit:t?.admin?.pagination?.defaultLimit||10,limits:t?.admin?.pagination?.limits||[10,25,50,100]}}getDefaultSort(e){let s=this.collections.get(e)?.admin?.useAsTitle;return s||"createdAt"}getDefaultColumns(e){let t=this.collections.get(e);return t?.admin?.defaultColumns?t.admin.defaultColumns:this.getVisibleFields(e).slice(0,4).map(a=>a.name)}getAdminTitle(e){let t=this.collections.get(e);return t?.label||t?.admin?.description||e}getAdminLabel(e){let t=this.collections.get(e);return t?.singularLabel||t?.label||e}getAdminGroup(e){return this.collections.get(e)?.admin?.group}getStats(){let e=0;for(let t of this.collections.values())e+=t.fields.length;for(let t of this.globals.values())e+=t.fields.length;return {collections:this.collections.size,globals:this.globals.size,plugins:this.plugins.length,fields:e}}toJSON(){return {collections:this.getCollections(),globals:this.getGlobals()}}},v=null;function Xe(){return v||(v=new w),v}function Je(){v=null;}function M(){return v=new w,v}var He={aws:{type:"aws",configKey:"s3",displayName:"S3 Compatible (AWS, Backblaze, Wasabi, etc.)",configFields:[{name:"bucket",type:"text",label:"Bucket Name",required:true},{name:"region",type:"text",label:"Region",defaultValue:"us-east-1",admin:{placeholder:"us-east-1"}},{name:"accessKeyId",type:"text",label:"Access Key ID",required:true},{name:"secretAccessKey",type:"password",label:"Secret Access Key",required:true},{name:"endpoint",type:"text",label:"Endpoint URL",admin:{placeholder:"https://s3.custom.com"}},{name:"cdnUrl",type:"text",label:"CDN URL",admin:{placeholder:"https://cdn.example.com"}},{name:"prefix",type:"text",label:"Path Prefix",admin:{placeholder:"uploads"}}]},r2:{type:"r2",configKey:"r2",displayName:"Cloudflare R2",configFields:[{name:"accountId",type:"text",label:"Account ID",required:true,admin:{placeholder:"Your Cloudflare Account ID"}},{name:"accessKeyId",type:"text",label:"Access Key ID",required:true},{name:"secretAccessKey",type:"password",label:"Secret Access Key",required:true},{name:"bucket",type:"text",label:"Bucket Name",required:true},{name:"publicDevUrl",type:"text",label:"Public Dev URL ID",admin:{placeholder:"pub-xxxxxxxxxxxxxxxx",description:"Enter ONLY the ID (e.g., pub-b8d8c4cc8bcf4d868ddd95efc1b305aa). Do NOT include https:// or the full URL. Found in R2 Dashboard \u2192 Public Dev URL."}},{name:"cdnUrl",type:"text",label:"Custom CDN URL",admin:{placeholder:"https://assets.example.com (optional)"}},{name:"prefix",type:"text",label:"Path Prefix",admin:{placeholder:"uploads (optional)",description:"Optional prefix for all object keys. Do not use '/' as prefix."}}]},gcs:{type:"gcs",configKey:"gcs",displayName:"Google Cloud Storage",configFields:[{name:"bucket",type:"text",label:"Bucket Name",required:true},{name:"projectId",type:"text",label:"Project ID"},{name:"clientEmail",type:"text",label:"Client Email"},{name:"privateKey",type:"password",label:"Private Key"},{name:"cdnUrl",type:"text",label:"CDN URL"},{name:"prefix",type:"text",label:"Path Prefix"}]},digitalocean:{type:"digitalocean",configKey:"digitalocean",displayName:"DigitalOcean Spaces",configFields:[{name:"bucket",type:"text",label:"Bucket Name",required:true},{name:"region",type:"text",label:"Region",defaultValue:"nyc3"},{name:"accessKeyId",type:"text",label:"Access Key ID",required:true},{name:"secretAccessKey",type:"password",label:"Secret Access Key",required:true},{name:"cdnUrl",type:"text",label:"CDN URL"},{name:"prefix",type:"text",label:"Path Prefix"}]},backblaze:{type:"backblaze",configKey:"backblaze",displayName:"Backblaze B2",configFields:[{name:"bucket",type:"text",label:"Bucket Name",required:true},{name:"accountId",type:"text",label:"Account ID"},{name:"applicationKeyId",type:"text",label:"Application Key ID",required:true},{name:"applicationKey",type:"password",label:"Application Key",required:true},{name:"cdnUrl",type:"text",label:"CDN URL"},{name:"prefix",type:"text",label:"Path Prefix"}]},wasabi:{type:"wasabi",configKey:"wasabi",displayName:"Wasabi",configFields:[{name:"bucket",type:"text",label:"Bucket Name",required:true},{name:"region",type:"text",label:"Region",defaultValue:"us-east-1"},{name:"accessKeyId",type:"text",label:"Access Key ID",required:true},{name:"secretAccessKey",type:"password",label:"Secret Access Key",required:true},{name:"cdnUrl",type:"text",label:"CDN URL"},{name:"prefix",type:"text",label:"Path Prefix"}]}};function Ye(n,e){switch(n){case "r2":return e?.endpoint||`https://${e?.accountId||""}.r2.cloudflarestorage.com`;case "digitalocean":return e?.endpoint||`https://${e?.region||"nyc3"}.digitaloceanspaces.com`;case "backblaze":return e?.endpoint||"https://s3.backblazeb2.com";case "wasabi":return e?.endpoint||`https://s3.${e?.region||"us-east-1"}.wasabisys.com`;default:return e?.endpoint}}function Ae(n,e){return {provider:n,bucket:e?.bucket||"",region:e?.region||"us-east-1",accessKeyId:e?.accessKeyId||e?.clientEmail||e?.applicationKeyId||"",secretAccessKey:e?.secretAccessKey||e?.privateKey||e?.applicationKey||"",endpoint:Ye(n,e),cdnUrl:e?.cdnUrl,prefix:e?.prefix,accountId:e?.accountId,publicDevUrl:e?.publicDevUrl}}function Qe(n,e,t){let s=t[e.configKey]||{};return Ae(n,s)}function et(n,e,t){let s=t?.[e.configKey]||t;return Ae(n,s)}var Se={name:"@kyro-cms/storage-s3",version:"1.0.0",description:"S3-compatible storage (AWS R2 GCS DigitalOcean Backblaze Wasabi)",init:n=>{let e=n.registry?.storageProviders;if(!e)return;let t="@kyro-cms/storage-s3";for(let s of Object.values(He))e.register({type:s.type,displayName:s.displayName,pluginName:t,configKey:s.configKey,configFields:s.configFields,extractConfig:a=>Qe(s.type,s,a),extractRawConfig:a=>et(s.type,s,a),factory:a=>chunkF3Z67QWS_cjs.a(a)});}};var Ee={name:"@kyro-cms/storage-cloudinary",version:"1.0.0",description:"Cloudinary image and video storage",init:n=>{let e=n.registry?.storageProviders;e&&e.register({type:"cloudinary",displayName:"Cloudinary",pluginName:"@kyro-cms/storage-cloudinary",configKey:"cloudinary",configFields:[{name:"cloudName",type:"text",label:"Cloud Name",required:true},{name:"apiKey",type:"text",label:"API Key",required:true},{name:"apiSecret",type:"password",label:"API Secret",required:true},{name:"folder",type:"text",label:"Folder",admin:{placeholder:"Optional folder path"}},{name:"uploadPreset",type:"text",label:"Upload Preset (optional)",admin:{placeholder:"Leave empty for signed uploads",description:"If not set, uploads will be signed with API Secret"}}],extractConfig:t=>({cloudName:t.cloudinary?.cloudName||"",apiKey:t.cloudinary?.apiKey||"",apiSecret:t.cloudinary?.apiSecret||"",folder:t.cloudinary?.folder,uploadPreset:t.cloudinary?.uploadPreset}),extractRawConfig:t=>{let s=t?.cloudinary||t;return {cloudName:s?.cloudName||"",apiKey:s?.apiKey||"",apiSecret:s?.apiSecret||"",folder:s?.folder,uploadPreset:s?.uploadPreset}},factory:t=>chunkF3Z67QWS_cjs.b(t)});}};var xe={name:"@kyro-cms/storage-ftp",version:"1.0.0",description:"FTP/SFTP storage provider",init:n=>{let e=n.registry?.storageProviders;e&&e.register({type:"ftp",displayName:"FTP",pluginName:"@kyro-cms/storage-ftp",configKey:"ftp",configFields:[{name:"host",type:"text",label:"Host",required:true,admin:{placeholder:"ftp.example.com"}},{name:"port",type:"number",label:"Port",defaultValue:21,admin:{placeholder:"21 for FTP"}},{name:"user",type:"text",label:"Username",required:true},{name:"password",type:"password",label:"Password",required:true},{name:"secure",type:"checkbox",label:"Use TLS/SSL",defaultValue:false,admin:{description:"Enable TLS/SSL for secure connections (FTP only)"}},{name:"baseUrl",type:"text",label:"Base URL",required:true,admin:{placeholder:"https://files.example.com"}},{name:"prefix",type:"text",label:"Path Prefix",admin:{placeholder:"uploads"}}],extractConfig:t=>({host:t.ftp?.host||"",port:t.ftp?.port||21,user:t.ftp?.user||"",password:t.ftp?.password||"",secure:t.ftp?.secure||false,baseUrl:t.ftp?.baseUrl||"",prefix:t.ftp?.prefix,type:"ftp"}),extractRawConfig:t=>{let s=t?.ftp||t;return {host:s?.host||"",port:s?.port||21,user:s?.user||"",password:s?.password||"",secure:s?.secure||false,baseUrl:s?.baseUrl||"",prefix:s?.prefix,type:"ftp"}},factory:t=>chunkF3Z67QWS_cjs.c(t)});}};var nt=[Se,Ee,xe];function z(n,e,t){let s=e.split(".");if(s.length===0)return false;let a=s[0],o=s.slice(1).join(".");for(let i of n)if(i.name===a)return o?i.fields&&Array.isArray(i.fields)||i.type==="array"&&i.fields&&Array.isArray(i.fields)?z(i.fields,o,t):false:(Object.assign(i,t),true);return false}function st(n,e){if(e)for(let t of n){let s=e[t.slug];if(s){let{fields:a,...o}=s;if(t.admin={...t.admin,...o},a&&t.fields&&Array.isArray(t.fields))for(let[i,r]of Object.entries(a))z(t.fields,i,r);}}}var W=class{registry;db;pubsub;webhookService;settings;wsServer;config;constructor(e){this.config=e,this.registry=M(),this.db=e.adapter,this.pubsub=new chunkF7SR5IDT_cjs.b(this.registry),this.webhookService=chunkISWMETHJ_cjs.n(this.db);for(let t of nt)this.registry.addPlugin(t);if(e.plugins)for(let t of e.plugins)this.registry.addPlugin(t);e.collections&&e.admin?.collectionOverrides&&st(e.collections,e.admin.collectionOverrides),e.collections&&this.registry.addCollections(e.collections),e.globals&&this.registry.addGlobals(e.globals);}async init(){await this.registry.init(this),this.registry.addGlobalPostInit(chunk65G73T7Z_cjs.a);let e={slug:"plugin-settings",admin:{hidden:true},fields:[{name:"states",type:"json"}]};if(this.registry.addGlobalPostInit(e),!this.db)throw new Error("Database adapter is null \u2014 failed to load at startup. Check the server console for the exact error.");let t={slug:chunkNY47CFVP_cjs.d,fields:[{name:"userId",type:"text",required:true},{name:"name",type:"text",required:true},{name:"key",type:"text",required:true},{name:"keyPrefix",type:"text",required:true},{name:"permissions",type:"json"},{name:"lastUsedAt",type:"date"},{name:"expiresAt",type:"date"}]},s={slug:chunkISWMETHJ_cjs.e,fields:[{name:"name",type:"text",required:true},{name:"url",type:"text",required:true},{name:"events",type:"json",required:true},{name:"status",type:"text",required:true},{name:"secret",type:"text"},{name:"headers",type:"json"},{name:"lastTriggered",type:"date"},{name:"lastError",type:"text"}]},a={slug:chunkISWMETHJ_cjs.f,fields:[{name:"webhookId",type:"text",required:true},{name:"event",type:"text",required:true},{name:"payload",type:"json",required:true},{name:"attempt",type:"number",required:true},{name:"status",type:"text",required:true},{name:"responseStatus",type:"number"},{name:"responseBody",type:"text"},{name:"error",type:"text"},{name:"duration",type:"number"},{name:"deliveredAt",type:"date"},{name:"nextRetryAt",type:"date"}]},o=this.registry.getGlobals();if(this.db instanceof chunk6CLRVJPP_cjs.c&&this.db.dialect==="postgres"){let i=this.db,r=chunkNY47CFVP_cjs.d.replace(/-/g,"_");i.schema[r]||(i.schema[r]=chunkMIOMMB23_cjs.g);}await this.db.init([...this.registry.getCollections(),t,s,a],o),await this.loadPluginState(),this.pubsub.autoRegisterHooks();}async loadSettings(){if(this.settings)return this.settings;try{let e=await this.db.findOne({collection:"_globals_access-settings",where:{},draft:!0});e&&(this.settings={access:e});}catch{}return this.settings||{}}async loadPluginState(){let e=this.registry.storageProviders,t=e.getAllPluginNames(),s={};try{let a=await this.db.findOne({collection:"_globals_plugin-settings",where:{},draft:!0});a&&a.states&&(s=a.states);}catch{}for(let a of t)s[a]!==void 0&&e.setPluginEnabled(a,s[a]);}getREST(e){let t=typeof this.config.auth=="object"?this.config.auth:null,s=t?.secret,a=t?.checkSession!==false;return chunkF3Z67QWS_cjs.s({registry:this.registry,db:this.db,authSecret:s,authAdapter:this.config.authAdapter,checkSession:a,...e,cors:this.config.cors,webhookService:this.webhookService,settings:this.settings})}getGraphQL(e){let t=chunkCIE3XMLH_cjs.c({registry:this.registry,db:this.db,settings:this.settings});return {fetch:graphqlYoga.createYoga({schema:t,context:async({request:a})=>{let o=chunkNY47CFVP_cjs.f(a),i,r;if(o&&this.db){let d=await chunkNY47CFVP_cjs.e(o,this.db);d.user&&(i=d.user,r=chunkNY47CFVP_cjs.g(d));}let c=e?.tenantID;return {db:this.db,registry:this.registry,user:i,req:a,tenantID:c,apiKey:r,relationLoader:new chunkCIE3XMLH_cjs.a({db:this.db,tenantID:c,user:i})}},graphiql:false,plugins:[]}).fetch,schema:t}}getTRPC(e){return {fetch:async(t,s)=>{let o=new URL(t.url).pathname.replace(/^\/api\/trpc\//,""),[i,...r]=o.split("."),c=r.join(".");if(c=c.replace(/\.(query|mutate|subscribe)$/,""),!i||!c)return new Response(JSON.stringify({error:{message:"Invalid tRPC path",code:-32600,data:{code:"BAD_REQUEST",httpStatus:400}}}),{status:400,headers:{"Content-Type":"application/json"}});let d=await chunkCVVW4LXZ_cjs.a({db:this.db,registry:this.registry,req:t,user:e?.user,tenantID:e?.tenantID,settings:this.settings}),h=chunkCVVW4LXZ_cjs.i(d)[i];if(!h)return new Response(JSON.stringify({error:{message:`Collection '${i}' not found`,code:-32601,data:{code:"NOT_FOUND",httpStatus:404}}}),{status:404,headers:{"Content-Type":"application/json"}});let g=h[c];if(typeof g!="function")return new Response(JSON.stringify({error:{message:`Procedure '${c}' not found`,code:-32601,data:{code:"NOT_FOUND",httpStatus:404}}}),{status:404,headers:{"Content-Type":"application/json"}});try{let p={};if(t.method==="POST"||t.method==="PATCH")p=await t.json().catch(()=>({}));else {let S=new URL(t.url).searchParams.get("input");if(S)try{p=JSON.parse(decodeURIComponent(S));}catch{}}let f=p?.["0"]??p,m=await g({...f,collection:i});return new Response(JSON.stringify({result:{data:m}}),{status:200,headers:{"Content-Type":"application/json"}})}catch(p){let f=p.message||"Internal error",m=f.includes("not found")?404:f.includes("denied")||f.includes("authentication required")?403:f.includes("conflict")?409:500,S=m===404?-32601:m===403?-32001:m===409?-32002:-32603;return new Response(JSON.stringify({error:{message:f,code:S,data:{code:"INTERNAL_SERVER_ERROR",httpStatus:m}}}),{status:m,headers:{"Content-Type":"application/json"}})}},router:null}}getWS(){return this.wsServer}async startWebSocket(e){let t=this.settings?.access?.apiAccess;if(t?.wsEnabled===false)return null;let s=async a=>{let o=await chunkNY47CFVP_cjs.e(a,this.db);if(!o.valid)throw new Error(o.error||"Invalid API key");if(!o.user)throw new Error("API key has no associated user");return o.user};return this.wsServer=chunkF7SR5IDT_cjs.d({pubsub:this.pubsub,port:e?.port||8080,requireAuth:e?.requireAuth??t?.requireAuth,verifyToken:e?.verifyToken||s}),this.wsServer}async shutdown(){this.wsServer&&await this.wsServer.close(),await this.db.disconnect();}};function Mt(n){return new W(n)}var it=module$1.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('chunk-TD6RULJU.cjs', document.baseURI).href))),ot="node:sqlite",{DatabaseSync:rt}=it(ot);function N(n){let e=[];for(let t of n)if(t.type==="tabs"&&"tabs"in t)for(let s of t.tabs)e.push(...N(s.fields));else t.type==="row"&&"fields"in t?e.push(...N(t.fields)):t.type==="collapsible"&&"fields"in t?e.push(...N(t.fields)):e.push(t);return e}function ct(n,e){let t=e,s=n[t.name];if(t.type==="json"||t.type==="richtext"||t.type==="array"||t.type==="group"||t.type==="blocks"||t.type==="list"||t.type==="relationship-block")try{s=s?JSON.parse(s):null;}catch{s=null;}if(t.type==="checkbox"&&(s=!!s),t.type==="date"&&s)try{let a=new Date(s);isNaN(a.getTime())?s=null:s=a.toISOString();}catch{s=null;}if((t.type==="upload"||t.type==="image")&&s)try{let a=JSON.parse(s);Array.isArray(a)?s=a.map(o=>typeof o=="object"&&o!==null?o:{id:o}):s=typeof a=="object"?a:{id:a};}catch{s={id:s};}if(t.type==="relationship"&&s)try{let a=JSON.parse(s);Array.isArray(a),s=a;}catch{s={relationTo:Array.isArray(t.relationTo)?t.relationTo[0]:t.relationTo,value:s};}if(t.type==="list"&&s)try{let a=JSON.parse(s);s=Array.isArray(a)?a:[];}catch{s=[];}if(t.type==="relationship-block"&&s)try{let a=JSON.parse(s);s=Array.isArray(a)?a:[];}catch{s=[];}return s}function X(n,e){try{return n.prepare(`PRAGMA table_info(${e})`).all().map(s=>s.name)}catch{return []}}var J=class extends chunkDV4LFLPL_cjs.a{db;path;migrations=new Map;versionsTableName="kyro_versions";constructor(e){super(),this.path=e.path,e.db?this.db=e.db:this.db=null;}async connect(){if(this.db||(this.db=new rt(this.path||":memory:")),this.db&&typeof this.db.prepare=="function"&&!this.db.prepare.__wrapped){let e=this.db.prepare.bind(this.db),t=s=>{let a=e(s),o=i=>typeof i=="boolean"?i?1:0:i===void 0?null:i;return new Proxy(a,{get(i,r,c){if(r==="all")return (...u)=>i.all(...u.map(o));if(r==="get")return (...u)=>i.get(...u.map(o));if(r==="run")return (...u)=>i.run(...u.map(o));let d=Reflect.get(i,r,c);return typeof d=="function"?d.bind(i):d}})};t.__wrapped=true,this.db.prepare=t;}this.db.exec("PRAGMA journal_mode = WAL"),this.db.exec("PRAGMA foreign_keys = ON"),this.connected=true;}async disconnect(){this.db&&this.db.close(),this.connected=false;}ensureTable(e,t){let s=t||this.getTableNameFor(e.slug),a=["id TEXT PRIMARY KEY"];for(let i of N(e.fields)){if(!i.name||i.name==="id")continue;let r=this.fieldToSQL(i);r&&a.push(r);}a.push(`${this.col("createdAt")} TEXT DEFAULT (datetime('now'))`),a.push(`${this.col("updatedAt")} TEXT DEFAULT (datetime('now'))`),a.push("status TEXT DEFAULT 'draft'"),a.push("hasDraft INTEGER DEFAULT 0"),e.tenantScoped&&a.push("tenant_id TEXT NOT NULL");let o=X(this.db,s);if(o.length===0){let i=`CREATE TABLE IF NOT EXISTS ${s} (${a.join(", ")})`;this.db.exec(i),this.db.exec(`CREATE INDEX IF NOT EXISTS idx_${s}_status ON ${s}(status)`);for(let r of N(e.fields))r.name&&r.indexed&&this.db.exec(`CREATE INDEX IF NOT EXISTS idx_${s}_${r.name} ON ${s}(${this.col(r.name)})`),r.name&&r.unique&&this.db.exec(`CREATE UNIQUE INDEX IF NOT EXISTS idx_${s}_${r.name}_unique ON ${s}(${this.col(r.name)})`);}else {let i=new Set(o);for(let r of a){let c=r.split(" ")[0].replace(/^"/,"").replace(/"$/,"");if(!i.has(c)&&c!=="id")try{c==="status"?this.db.exec(`ALTER TABLE ${s} ADD COLUMN ${this.col(c)} TEXT DEFAULT 'published'`):c==="hasDraft"?this.db.exec(`ALTER TABLE ${s} ADD COLUMN ${this.col(c)} INTEGER DEFAULT 0`):this.db.exec(`ALTER TABLE ${s} ADD COLUMN ${this.col(c)} TEXT`);}catch{}}}this.migrations.set(s,true);}ensureVersionsTable(){this.db.exec(`
4
+ CREATE TABLE IF NOT EXISTS ${this.versionsTableName} (
5
+ id TEXT PRIMARY KEY,
6
+ collection_slug TEXT NOT NULL,
7
+ document_id TEXT NOT NULL,
8
+ tenant_id TEXT,
9
+ version INTEGER NOT NULL,
10
+ status TEXT NOT NULL DEFAULT 'draft',
11
+ autosave INTEGER NOT NULL DEFAULT 0,
12
+ data TEXT NOT NULL,
13
+ created_by TEXT,
14
+ change_description TEXT,
15
+ published_at TEXT,
16
+ created_at TEXT DEFAULT (datetime('now')),
17
+ updated_at TEXT DEFAULT (datetime('now'))
18
+ )
19
+ `);try{this.db.exec(`ALTER TABLE ${this.versionsTableName} ADD COLUMN autosave INTEGER NOT NULL DEFAULT 0`);}catch{}this.db.exec(`CREATE INDEX IF NOT EXISTS idx_${this.versionsTableName}_doc ON ${this.versionsTableName}(collection_slug, document_id)`),this.db.exec(`CREATE INDEX IF NOT EXISTS idx_${this.versionsTableName}_status ON ${this.versionsTableName}(status)`),this.db.exec(`CREATE INDEX IF NOT EXISTS idx_${this.versionsTableName}_autosave ON ${this.versionsTableName}(autosave)`);}col(e){return `"${e}"`}fieldToSQL(e){switch(e.type){case "text":case "email":case "password":case "textarea":case "color":case "code":case "markdown":case "url":return this.col(e.name)+" TEXT";case "number":return this.col(e.name)+" REAL";case "checkbox":return this.col(e.name)+" INTEGER DEFAULT 0";case "date":return this.col(e.name)+" TEXT";case "select":case "radio":return this.col(e.name)+" TEXT";case "relationship":case "upload":return this.col(e.name)+" TEXT";case "json":case "richtext":case "array":case "group":case "blocks":return this.col(e.name)+" TEXT";default:return null}}parseGlobalsSlug(e){if(e.startsWith("_globals_")){let t=e.replace("_globals_","");return {isGlobal:true,globalSlug:t,tableName:`global_${t.replace(/-/g,"_")}`}}return {isGlobal:false,globalSlug:"",tableName:this.getTableNameFor(e)}}async find(e){let{collection:t,where:s={},sort:a,limit:o=10,page:i=1,tenantID:r,draft:c=false}=e,d=this.parseGlobalsSlug(t),u=d.isGlobal?this.globals.get(d.globalSlug):this.getCollection(t);this.ensureTable(u,d.tableName);let g=`SELECT * FROM ${d.tableName}`,p=[],f=[],m={...s};this.tenantContext&&u.tenantScoped&&(m=chunkDV4LFLPL_cjs.c({where:m},t,this.tenantContext,chunkDV4LFLPL_cjs.b).where||{}),c||(f.push("status = ?"),p.push("published")),r&&u.tenantScoped&&(f.push("tenant_id = ?"),p.push(r));for(let[T,A]of Object.entries(m))T==="AND"||T==="OR"||(typeof A=="object"&&A!==null?(A.equals!==void 0&&(f.push(`${this.col(T)} = ?`),p.push(A.equals)),A.in!==void 0&&(f.push(`${this.col(T)} IN (${A.in.map(()=>"?").join(", ")})`),p.push(...A.in)),A.not_equals!==void 0&&(f.push(`${this.col(T)} != ?`),p.push(A.not_equals))):(f.push(`${this.col(T)} = ?`),p.push(A)));f.length>0&&(g+=` WHERE ${f.join(" AND ")}`);let S=this.col(a?.replace("-","")||"createdAt"),y=a?.startsWith("-")?"DESC":"ASC";g+=` ORDER BY ${S} ${y}`;let Ne=g.replace("SELECT *","SELECT COUNT(*) as count"),F=this.db.prepare(Ne).get(...p)?.count||0;g+=" LIMIT ? OFFSET ?",p.push(o,(i-1)*o);let D=this.db.prepare(g).all(...p).map(T=>this.rowToDoc(T,u));return this.tenantContext&&!this.tenantContext.isSuperAdmin&&(D=D.filter(T=>chunkDV4LFLPL_cjs.d(T,t,this.tenantContext,chunkDV4LFLPL_cjs.b))),c&&(D=await Promise.all(D.map(async T=>{let A=this.db.prepare(`SELECT * FROM ${this.versionsTableName} WHERE collection_slug = ? AND document_id = ? AND tenant_id IS NULL ORDER BY version DESC LIMIT 1`).get(t,T.id);if(A){let Re=A.data?JSON.parse(A.data):{};return {...T,...Re,status:T.status}}return T}))),{docs:D,totalDocs:F,limit:o,totalPages:Math.ceil(F/o),page:i,pagingCounter:(i-1)*o+1,hasPrevPage:i>1,hasNextPage:i<Math.ceil(F/o),prevPage:i>1?i-1:null,nextPage:i<Math.ceil(F/o)?i+1:null}}async findByID(e){let{collection:t,id:s,tenantID:a,draft:o=false}=e,i=this.parseGlobalsSlug(t),r=i.isGlobal?this.globals.get(i.globalSlug):this.getCollection(t);this.ensureTable(r,i.tableName);let d=`SELECT * FROM ${i.tableName} WHERE id = ?`,u=[s];if(this.tenantContext&&r.tenantScoped){let p={id:s,tenant_id:this.tenantContext.tenantId};if(!chunkDV4LFLPL_cjs.d(p,t,this.tenantContext,chunkDV4LFLPL_cjs.b))return null}o||(d+=" AND status = ?",u.push("published")),a&&r.tenantScoped&&(d+=" AND tenant_id = ?",u.push(a));let h=this.db.prepare(d).get(...u);if(!h)return null;let g=this.rowToDoc(h,r);if(o){let p=this.db.prepare(`SELECT * FROM ${this.versionsTableName} WHERE collection_slug = ? AND document_id = ? AND tenant_id IS NULL ORDER BY version DESC LIMIT 1`).get(t,g.id);if(p){let f=p.data?JSON.parse(p.data):{};g={...g,...f,status:g.status};}}return g}async create(e){let{collection:t,data:s,tenantID:a}=e,o=this.parseGlobalsSlug(t),i=o.isGlobal?this.globals.get(o.globalSlug):this.getCollection(t);this.ensureTable(i,o.tableName);let r=o.tableName,c=o.isGlobal?o.globalSlug:s.id||this.generateId(),d=this.prepareData(s,i);d.id=c,d.created_at=new Date().toISOString(),d.updated_at=new Date().toISOString(),a&&i.tenantScoped&&(d.tenant_id=a);let u=Object.keys(d),h=X(this.db,r),g={};for(let y of u)h.includes(y)&&(g[y]=d[y]);let p=Object.keys(g),f=p.map(y=>this.col(y)),m=p.map(()=>"?").join(", "),S=Object.values(g).map(y=>y!==null&&typeof y=="object"?JSON.stringify(y):y);return this.db.prepare(`INSERT OR REPLACE INTO ${r} (${f.join(", ")}) VALUES (${m})`).run(...S),this.ensureVersionsTable(),this.findByID({collection:t,id:c,tenantID:a,draft:true})}async update(e){let{collection:t,id:s,data:a,tenantID:o}=e,i=this.parseGlobalsSlug(t),r=i.isGlobal?this.globals.get(i.globalSlug):this.getCollection(t);this.ensureTable(r,i.tableName);let c=i.tableName,d=this.prepareData(a,r);d.updated_at=new Date().toISOString();let u=X(this.db,c),h={};for(let y of Object.keys(d))u.includes(y)&&(h[y]=d[y]);let p=Object.keys(h).map(y=>`${this.col(y)} = ?`).join(", "),f=Object.values(h).map(y=>y!==null&&typeof y=="object"?JSON.stringify(y):y),m=`UPDATE ${c} SET ${p} WHERE id = ?`,S=[...f,s];return o&&r.tenantScoped&&(m+=" AND tenant_id = ?",S.push(o)),this.db.prepare(m).run(...S),this.ensureVersionsTable(),this.findByID({collection:t,id:s,tenantID:o,draft:true})}async delete(e){let{collection:t,id:s,tenantID:a}=e,o=this.parseGlobalsSlug(t),i=o.isGlobal?this.globals.get(o.globalSlug):this.getCollection(t);this.ensureTable(i,o.tableName),this.ensureVersionsTable();let r=await this.findByID({collection:t,id:s,tenantID:a,draft:true});if(!r)throw new Error(`Document not found: ${t}/${s}`);let d=`DELETE FROM ${o.tableName} WHERE id = ?`,u=[s];return a&&i.tenantScoped&&(d+=" AND tenant_id = ?",u.push(a)),this.db.prepare(d).run(...u),r}async count(e){let{collection:t,tenantID:s}=e,a=this.parseGlobalsSlug(t),o=a.isGlobal?this.globals.get(a.globalSlug):this.getCollection(t);this.ensureTable(o,a.tableName);let r=`SELECT COUNT(*) as count FROM ${a.tableName}`,c=[];return s&&o.tenantScoped&&(r+=" WHERE tenant_id = ?",c.push(s)),this.db.prepare(r).get(...c)?.count||0}async findOne(e){let t=this.parseGlobalsSlug(e.collection);if(t.isGlobal){let a=this.globals.get(t.globalSlug);if(!a)throw new Error(`Global "${t.globalSlug}" not found in adapter`);this.ensureTable(a,t.tableName);let o=`SELECT * FROM ${t.tableName}`,i=[],r=[];!e.draft&&a.versions&&i.push("status = 'published'"),i.length>0&&(o+=` WHERE ${i.join(" AND ")}`),o+=" LIMIT 1";let c=this.db.prepare(o).get(...r);if(c){let d=this.rowToDoc(c,a);if(e.draft){let u=this.db.prepare(`SELECT * FROM ${this.versionsTableName} WHERE collection_slug = ? AND document_id = ? AND tenant_id IS NULL ORDER BY version DESC LIMIT 1`).get(e.collection,t.globalSlug);if(u){let h=u.data?JSON.parse(u.data):{};d={...d,...h,status:d.status};}}return d}return null}return (await this.find({...e,limit:1})).docs[0]||null}async findVersions(e){this.ensureVersionsTable();let{collection:t,documentId:s,tenantID:a,limit:o=20,page:i=1}=e,r=["collection_slug = ?","document_id = ?","autosave = 0"],c=[t,s];a?(r.push("tenant_id = ?"),c.push(a)):r.push("tenant_id IS NULL");let d=`WHERE ${r.join(" AND ")}`,h=this.db.prepare(`SELECT COUNT(*) as count FROM ${this.versionsTableName} ${d}`).get(...c)?.count||0,g=(i-1)*o;return {docs:this.db.prepare(`SELECT * FROM ${this.versionsTableName} ${d} ORDER BY version DESC LIMIT ? OFFSET ?`).all(...c,o,g).map(m=>this.rowToVersion(m)),totalDocs:h,limit:o,totalPages:Math.ceil(h/o),page:i,pagingCounter:(i-1)*o+1,hasPrevPage:i>1,hasNextPage:i<Math.ceil(h/o),prevPage:i>1?i-1:null,nextPage:i<Math.ceil(h/o)?i+1:null}}async findVersionByID(e){this.ensureVersionsTable();let t=this.db.prepare(`SELECT * FROM ${this.versionsTableName} WHERE id = ? AND collection_slug = ? LIMIT 1`).get(e.versionId,e.collection);return t?this.rowToVersion(t):null}async createVersion(e){this.ensureVersionsTable();let t=new Date().toISOString();if(e.autosave){let r=`SELECT * FROM ${this.versionsTableName} WHERE collection_slug = ? AND document_id = ? AND autosave = 1`,c=[e.collection,e.documentId];e.tenantID?(r+=" AND tenant_id = ?",c.push(e.tenantID)):r+=" AND tenant_id IS NULL",r+=" LIMIT 1";let d=this.db.prepare(r).get(...c);if(d){this.db.prepare(`UPDATE ${this.versionsTableName} SET data = ?, status = ?, updated_at = ? WHERE id = ?`).run(JSON.stringify(e.data),e.status,t,d.id);let u=await this.findVersionByID({collection:e.collection,versionId:d.id});if(u)return u}}let s=this.generateId(),o=(this.db.prepare(`SELECT version FROM ${this.versionsTableName} WHERE collection_slug = ? AND document_id = ? AND autosave = 0 ORDER BY version DESC LIMIT 1`).get(e.collection,e.documentId)?.version??0)+1;if(this.db.prepare(`INSERT INTO ${this.versionsTableName} (
20
+ id, collection_slug, document_id, tenant_id, version, status, autosave, data, created_by, change_description, published_at, created_at, updated_at
21
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(s,e.collection,e.documentId,e.tenantID??null,o,e.status,e.autosave?1:0,JSON.stringify(e.data),e.createdBy??null,e.changeDescription??null,e.status==="published"?t:null,t,t),!e.autosave){let c=this.collections.get(e.collection)?.versions?.maxPerDoc;c&&c>0&&await this.deleteVersions({collection:e.collection,documentId:e.documentId,keepLatest:c,tenantID:e.tenantID});}return await this.findVersionByID({collection:e.collection,versionId:s})}async updateLatestVersion(e){return this.createVersion({...e,autosave:true})}async deleteVersions(e){this.ensureVersionsTable();let{collection:t,documentId:s,keepLatest:a,tenantID:o}=e;if(a&&a>0){let i=this.db.prepare(`SELECT id, status, autosave FROM ${this.versionsTableName} WHERE collection_slug = ? AND document_id = ? ORDER BY version DESC`).all(t,s),r=0,c=[];for(let d of i)d.status==="published"||d.autosave===1||(r++,r>a&&c.push(d.id));for(let d of c)this.db.prepare(`DELETE FROM ${this.versionsTableName} WHERE id = ?`).run(d);}else {let i=`DELETE FROM ${this.versionsTableName} WHERE collection_slug = ? AND document_id = ?`,r=[t,s];o&&(i+=" AND tenant_id = ?",r.push(o)),this.db.prepare(i).run(...r);}}rowToVersion(e){return {id:String(e.id),collection:e.collection_slug,documentId:e.document_id,version:e.version,status:e.status,data:e.data?JSON.parse(e.data):{},createdBy:e.created_by??void 0,changeDescription:e.change_description??void 0,publishedAt:e.published_at??null,createdAt:e.created_at,updatedAt:e.updated_at}}prepareData(e,t){let s={},a=N(t.fields),o=(i,r)=>{let c=i;if(c.type==="json"||c.type==="richtext"||c.type==="array"||c.type==="group"||c.type==="blocks"||c.type==="list"||c.type==="relationship-block")return r!=null?JSON.stringify(r):null;if(c.type==="checkbox")return r?1:0;if(c.type==="number")return r!==null&&r!==""?Number(r):null;if(c.type==="upload"||c.type==="image"){if(r==null)return null;if(Array.isArray(r)){let d=r.map(u=>typeof u=="string"?u:typeof u=="object"?u.id||u._id||u:String(u));return JSON.stringify(d)}return typeof r=="string"?r:typeof r=="object"?JSON.stringify(r):String(r)}else if(i.type==="relationship"){if(r==null)return null;if(Array.isArray(r)){let d=r.map(u=>typeof u=="string"?u:typeof u=="object"?JSON.stringify({relationTo:i.relationTo,value:u.id||u}):String(u));return JSON.stringify(d)}return typeof r=="string"?r:typeof r=="object"?JSON.stringify({relationTo:i.relationTo,value:r.id||r}):String(r)}return r};for(let i of a){if(!i.name||i.name==="id"||t.fields.some(d=>d.type==="tabs"&&"tabs"in d&&d.tabs.some(u=>u.fields.some(h=>h.name===i.name))))continue;let c=e[i.name];c!==void 0&&(s[i.name]=o(i,c));}for(let i of t.fields)if(i.type==="tabs"&&"tabs"in i&&i.name){let r=e[i.name];if(r&&typeof r=="object"){for(let c of i.tabs)for(let d of c.fields)if(d.name&&d.name!=="id"){let u=r[d.name];u!==void 0&&(s[d.name]=o(d,u));}}}return s}rowToDoc(e,t){let s={id:e.id};for(let a of N(t.fields)){if(!a.name||a.name==="id")continue;let o=a,i=e[o.name];if(o.type==="json"||o.type==="richtext"||o.type==="array"||o.type==="group"||o.type==="blocks"||o.type==="list"||o.type==="relationship-block")try{i=i?JSON.parse(i):null;}catch{i=null;}if(a.type==="checkbox"&&(i=!!i),a.type==="date"&&i)try{let r=new Date(i);isNaN(r.getTime())?(console.warn(`[LocalAdapter] Invalid date value for field "${a.name}":`,i),i=null):i=r.toISOString();}catch{i=null;}if((a.type==="upload"||a.type==="image")&&i)try{let r=JSON.parse(i);Array.isArray(r)?i=r.map(c=>typeof c=="object"&&c!==null?c:{id:c}):i=typeof r=="object"?r:{id:r};}catch{i={id:i};}if(a.type==="relationship"&&i)try{let r=JSON.parse(i);Array.isArray(r),i=r;}catch{i={relationTo:Array.isArray(a.relationTo)?a.relationTo[0]:a.relationTo,value:i};}s[a.name]=i;}for(let a of t.fields)if(!(!a.name||a.name==="id"||a.name==="row"||a.name==="collapsible")&&a.type==="tabs"&&"tabs"in a){let o={};for(let i of a.tabs)for(let r of i.fields)r.name&&r.name!=="id"&&(o[r.name]=ct(e,r));s[a.name]=o;}if(t.timestamps){let a=e.createdAt||e.created_at,o=e.updatedAt||e.updated_at;if(a)try{let i=new Date(a);isNaN(i.getTime())||(s.createdAt=i.toISOString());}catch{}if(o)try{let i=new Date(o);isNaN(i.getTime())||(s.updatedAt=i.toISOString());}catch{}}return t.tenantScoped&&(s.tenantID=e.tenant_id),s.status=e.status??"published",s.hasDraft=e.hasDraft?!!e.hasDraft:false,s}generateId(){let e=Date.now().toString(16).padStart(12,"0"),t=crypto.randomBytes(6).toString("hex");return e+t}getMediaById(e){try{let t=this.getTableNameFor("media"),s=this.db.prepare(`SELECT id, url, thumbnail_url FROM ${t} WHERE id = ?`).get(e);if(s)return {id:s.id,url:s.url,thumbnailUrl:s.thumbnail_url||s.url}}catch{}return null}getTableNameFor(e){return e.replace(/-/g,"_")}async migrate(){for(let e of this.collections.values())this.ensureTable(e);}async rollback(){}async transaction(e){return new Promise((t,s)=>{let a=this.db.transaction(async()=>e({db:this.db}));try{let o=a();t(o);}catch(o){s(o);}})}getDatabase(){return this.db}exec(e){this.db.exec(e);}prepare(e){return this.db.prepare(e)}};function ln(n){return new J(n||{})}exports.a=K;exports.b=V;exports.c=B;exports.d=x;exports.e=pe;exports.f=C;exports.g=he;exports.h=ge;exports.i=me;exports.j=be;exports.k=Te;exports.l=w;exports.m=Xe;exports.n=Je;exports.o=M;exports.p=W;exports.q=Mt;exports.r=J;exports.s=ln;
@@ -0,0 +1 @@
1
+ 'use strict';
@@ -0,0 +1 @@
1
+ import {pgTable,timestamp,jsonb,varchar,text,integer,uuid,index}from'drizzle-orm/pg-core';var m=pgTable("media",{id:uuid("id").primaryKey().defaultRandom(),filename:varchar("filename",{length:255}).notNull().unique(),title:varchar("title",{length:255}),originalName:varchar("original_name",{length:255}).notNull(),mimeType:varchar("mime_type",{length:100}).notNull(),fileSize:integer("file_size").notNull(),width:integer("width"),height:integer("height"),url:text("url").notNull().unique(),thumbnailUrl:text("thumbnail_url"),folder:varchar("folder",{length:255}),provider:varchar("provider",{length:50}).notNull(),alt:text("alt"),caption:text("caption"),type:varchar("type",{length:50}).notNull().default("other"),status:varchar("status",{length:20}).notNull().default("active"),metadata:jsonb("metadata").$type(),createdAt:timestamp("created_at").defaultNow().notNull(),updatedAt:timestamp("updated_at").defaultNow().notNull()},t=>[index("media_folder_idx").on(t.folder),index("media_provider_idx").on(t.provider),index("media_filename_idx").on(t.filename)]),p=pgTable("media_folders",{path:varchar("path",{length:500}).primaryKey(),name:varchar("name",{length:255}).notNull(),parentPath:varchar("parent_path",{length:500}),createdAt:timestamp("created_at").defaultNow().notNull()},t=>[index("media_folders_parent_idx").on(t.parentPath)]);export{m as a,p as b};
@@ -0,0 +1,2 @@
1
+ 'use strict';var chunkDV4LFLPL_cjs=require('./chunk-DV4LFLPL.cjs'),crypto=require('crypto');var _=class extends chunkDV4LFLPL_cjs.a{client;db;database;connectionString;constructor(i){if(super(),i.connectionString){this.connectionString=i.connectionString;try{let e=new URL(i.connectionString);this.database=e.pathname.replace(/^\//,"")||"kyro_cms";}catch{this.database="kyro_cms";}}else this.client=i.client,this.database=i.database;}async connect(){if(this.connectionString&&!this.client){let{MongoClient:i}=await import('mongodb');this.client=new i(this.connectionString),await this.client.connect();}this.db=this.client.db(this.database),this.connected=true;}async disconnect(){this.client&&(await this.client.close(),this.connected=false);}getMongoCollection(i){if(!this.db)throw new Error("MongoDB not connected");return this.db.collection(i)}async find(i){let{collection:e,where:n={},sort:s,limit:t=10,page:o=1,tenantID:r,select:a,draft:l}=i,c=this.getCollectionConfig(e),g=this.getMongoCollection(e),u={...n};this.tenantContext&&c.tenantScoped&&(u=chunkDV4LFLPL_cjs.c({where:u},e,this.tenantContext,chunkDV4LFLPL_cjs.b).where||{});let d=this.buildFilter(u,r);l||(d.status="published");let h=this.parseSort(s),p={[h.field]:h.direction==="asc"?1:-1},I=(o-1)*t,[R,b]=await Promise.all([g.find(d).sort(p).skip(I).limit(t).project(this.buildProjection(a)).toArray(),g.countDocuments(d)]),m=R.map(f=>this.processResult(f,c));return this.tenantContext&&!this.tenantContext.isSuperAdmin&&(m=m.filter(f=>chunkDV4LFLPL_cjs.d(f,e,this.tenantContext,chunkDV4LFLPL_cjs.b))),l&&(m=await Promise.all(m.map(async f=>{let D=await this.getMongoCollection(`${e}_versions`).findOne({document_id:f.id},{sort:{createdAt:-1}});if(D){let $=D.data||{};return {...f,...$,status:f.status}}return f}))),{docs:m,...this.calculatePagination(o,t,b)}}async findByID(i){let{collection:e,id:n,tenantID:s,draft:t}=i,o=this.getCollectionConfig(e),r=this.getMongoCollection(e);if(this.tenantContext&&o.tenantScoped){let g={_id:n,tenantId:this.tenantContext.tenantId};if(!chunkDV4LFLPL_cjs.d(g,e,this.tenantContext,chunkDV4LFLPL_cjs.b))return null}let a={_id:n};s&&(a.tenantId=s),t||(a.status="published");let l=await r.findOne(a);if(!l)return null;let c=this.processResult(l,o);if(t){let u=await this.getMongoCollection(`${e}_versions`).findOne({document_id:c.id},{sort:{createdAt:-1}});if(u){let d=u.data||{};c={...c,...d,status:c.status};}}return c}async create(i){let{collection:e,data:n,tenantID:s}=i,t=this.getCollectionConfig(e),o=this.getMongoCollection(e),r={...this.prepareData(n,t),_id:this.generateId()};return s&&(r.tenantId=s),await o.insertOne(r),this.processResult(r,t)}async update(i){let{collection:e,id:n,data:s,tenantID:t}=i,o=this.getCollectionConfig(e),r=this.getMongoCollection(e),a={_id:n};t&&(a.tenantId=t);let l=this.prepareData(s,o),c=await r.findOneAndUpdate(a,{$set:l},{returnDocument:"after"});if(!c)throw new Error(`Document not found: ${e}/${n}`);return this.processResult(c,o)}async delete(i){let{collection:e,id:n,tenantID:s}=i,t=this.getCollectionConfig(e),o=this.getMongoCollection(e),r={_id:n};s&&(r.tenantId=s);let a=await o.findOneAndDelete(r);if(!a)throw new Error(`Document not found: ${e}/${n}`);return this.processResult(a,t)}async count(i){let{collection:e,where:n={},tenantID:s}=i,t=this.getMongoCollection(e),o=this.buildFilter(n,s);return t.countDocuments(o)}async findOne(i){let{collection:e,where:n={},tenantID:s,draft:t}=i,o=this.getCollectionConfig(e),r=this.getMongoCollection(e),a=this.buildFilter(n,s);t||(a.status="published");let l=await r.findOne(a);if(!l)return null;let c=this.processResult(l,o);if(t){let u=await this.getMongoCollection(`${e}_versions`).findOne({document_id:c.id},{sort:{createdAt:-1}});if(u){let d=u.data||{};c={...c,...d,status:c.status};}}return c}async findVersions(i){let{collection:e,documentId:n,sort:s,limit:t=10,page:o=1,tenantID:r}=i,a=this.getMongoCollection(`${e}_versions`),l={document_id:n,autosave:{$ne:true}};r&&(l.tenant_id=r);let c=(o-1)*t,g=this.parseSort(s),u={[g.field]:g.direction==="asc"?1:-1},[d,h]=await Promise.all([a.find(l).sort(u).skip(c).limit(t).toArray(),a.countDocuments(l)]);return {docs:d.map(p=>this.processResult(p,{})),...this.calculatePagination(o,t,h)}}async findVersionByID(i){let{collection:e,versionId:n,tenantID:s}=i,t=this.getMongoCollection(`${e}_versions`),o={_id:n};s&&(o.tenant_id=s);let r=await t.findOne(o);return r?this.processResult(r,{}):null}async createVersion(i){let{collection:e,documentId:n,data:s,status:t,createdBy:o,changeDescription:r,tenantID:a,autosave:l}=i,c=this.getMongoCollection(`${e}_versions`);if(l){let d={document_id:n,collection_slug:e,autosave:true};a&&(d.tenant_id=a);let h=await c.findOne(d);if(h){let p=new Date().toISOString();return await c.updateOne({_id:h._id},{$set:{data:s,status:t,updatedAt:p}}),this.processResult({...h,data:s,status:t,updatedAt:p},{})}}let g=new Date().toISOString(),u={_id:this.generateId(),document_id:n,collection_slug:e,tenant_id:a,data:s,status:t,autosave:l===true,created_by:o,change_description:r,createdAt:g,updatedAt:g};if(await c.insertOne(u),!l){let d=this.getCollectionConfig(e);d.versions?.maxPerDoc&&await this.deleteVersions({collection:e,documentId:n,keepLatest:d.versions.maxPerDoc,tenantID:a});}return this.processResult(u,{})}async updateLatestVersion(i){return this.createVersion({...i,autosave:true})}async deleteVersions(i){let{collection:e,documentId:n,keepLatest:s,tenantID:t}=i,o=this.getMongoCollection(`${e}_versions`);if(s){let r={document_id:n,autosave:{$ne:true}};t&&(r.tenant_id=t);let l=(await o.find(r).sort({createdAt:-1}).limit(s).project({_id:1}).toArray()).map(c=>c._id);l.length>0&&await o.deleteMany({document_id:n,autosave:{$ne:true},_id:{$nin:l},...t?{tenant_id:t}:{}});}else {let r={document_id:n};t&&(r.tenant_id=t),await o.deleteMany(r);}}async migrate(){for(let i of this.collections.values()){let e=this.getMongoCollection(i.slug);await e.createIndex({_id:1}),i.tenantScoped&&await e.createIndex({tenantId:1}),i.timestamps&&await e.createIndex({createdAt:-1});for(let n of i.fields)n.unique&&n.name&&await e.createIndex({[n.name]:1},{unique:true}),n.indexed&&n.name&&await e.createIndex({[n.name]:1});}}getCollectionConfig(i){let e=this.collections.get(i);if(!e)throw new Error(`Collection "${i}" not found`);return e}buildFilter(i={},e){let n={};e&&(n.tenantId=e);for(let[s,t]of Object.entries(i))if(s==="AND"&&Array.isArray(t)){let o=t.map(r=>this.buildFilter(r));Object.assign(n,...o);}else if(s==="OR"&&Array.isArray(t))n.$or=t.map(o=>this.buildFilter(o));else if(typeof t=="object"&&t!==null&&!Array.isArray(t)){let o={};if(t.equals!==void 0){n[s==="id"?"_id":s]=t.equals;continue}t.not_equals!==void 0&&(o.$ne=t.not_equals),t.in!==void 0&&(o.$in=t.in),t.not_in!==void 0&&(o.$nin=t.not_in),t.greater_than!==void 0&&(o.$gt=t.greater_than),t.greater_than_equal!==void 0&&(o.$gte=t.greater_than_equal),t.less_than!==void 0&&(o.$lt=t.less_than),t.less_than_equal!==void 0&&(o.$lte=t.less_than_equal),t.like!==void 0&&(o.$regex=new RegExp(t.like.replace(/%/g,".*"),"i")),t.not_like!==void 0&&(o.$not=new RegExp(t.not_like.replace(/%/g,".*"),"i")),t.contains!==void 0&&(o.$regex=new RegExp(`.*${t.contains}.*`,"i")),t.exists!==void 0&&(o.$exists=t.exists),Object.keys(o).length>0&&(n[s==="id"?"_id":s]=o);}else n[s==="id"?"_id":s]=t;return n}buildProjection(i){if(!i||i.length===0)return;let e={_id:1};for(let n of i)e[n]=1;return e}processResult(i,e){if(!i)return null;let n={...i};return i._id&&(n.id=i._id,delete n._id),delete n.__v,n.createdAt&&(n.createdAt=new Date(n.createdAt).toISOString()),n.updatedAt&&(n.updatedAt=new Date(n.updatedAt).toISOString()),n}generateId(){let i=Date.now().toString(16).padStart(12,"0"),e=crypto.randomBytes(6).toString("hex");return i+e}};function M(w){return new _(w)}
2
+ exports.a=_;exports.b=M;
@@ -0,0 +1,20 @@
1
+ var a=class{constructor(s){this.config=s;}config;css=[];addRule(s,e){let n=Object.entries(e).map(([o,t])=>` ${o}: ${t};`).join(`
2
+ `);return this.css.push(`${s} {
3
+ ${n}
4
+ }`),this}addMediaQuery(s,e){return this.css.push(`@media (min-width: ${s}) {
5
+ ${e.join(`
6
+ `)}
7
+ }`),this}generate(){return this.css.join(`
8
+
9
+ `)}};function p(r){return {theme:{extend:{colors:r.colors||{},fontFamily:r.fonts||{},spacing:r.spacing||{},borderRadius:r.borderRadius||{},boxShadow:r.shadows||{},screens:r.breakpoints||{}}}}}var i={colors:{primary:"#3b82f6",secondary:"#6366f1",accent:"#ec4899",background:"#ffffff",surface:"#f9fafb",text:"#111827",textMuted:"#6b7280",border:"#e5e7eb",error:"#ef4444",warning:"#f59e0b",success:"#10b981",info:"#3b82f6"},fonts:{sans:"system-ui, -apple-system, sans-serif",serif:"Georgia, serif",mono:"Menlo, monospace"},spacing:{xs:"0.25rem",sm:"0.5rem",md:"1rem",lg:"1.5rem",xl:"2rem","2xl":"3rem","3xl":"4rem"},borderRadius:{sm:"0.125rem",md:"0.375rem",lg:"0.5rem",xl:"0.75rem",full:"9999px"},shadows:{sm:"0 1px 2px 0 rgb(0 0 0 / 0.05)",md:"0 4px 6px -1px rgb(0 0 0 / 0.1)",lg:"0 10px 15px -3px rgb(0 0 0 / 0.1)",xl:"0 20px 25px -5px rgb(0 0 0 / 0.1)"}},l={colors:{primary:"#60a5fa",secondary:"#818cf8",accent:"#f472b6",background:"#111827",surface:"#1f2937",text:"#f9fafb",textMuted:"#9ca3af",border:"#374151",error:"#f87171",warning:"#fbbf24",success:"#34d399",info:"#60a5fa"},fonts:i.fonts,spacing:i.spacing,borderRadius:i.borderRadius,shadows:{sm:"0 1px 2px 0 rgb(0 0 0 / 0.3)",md:"0 4px 6px -1px rgb(0 0 0 / 0.4)",lg:"0 10px 15px -3px rgb(0 0 0 / 0.5)",xl:"0 20px 25px -5px rgb(0 0 0 / 0.6)"}},m={colors:{primary:"#FF6B35",secondary:"#1A1A2E",accent:"#16C79A",background:"#FFFFFF",surface:"#F8F9FA",text:"#1A1A2E",textMuted:"#6B7280",border:"#E5E7EB",error:"#EF4444",warning:"#F59E0B",success:"#16C79A",info:"#3B82F6"},fonts:{sans:'"Inter", "Satoshi", system-ui, sans-serif',serif:'"Playfair Display", Georgia, serif',mono:'"JetBrains Mono", monospace'},spacing:{xs:"0.125rem",sm:"0.25rem",md:"0.5rem",lg:"1rem",xl:"1.5rem","2xl":"2rem","3xl":"3rem","4xl":"4rem"},borderRadius:{sm:"0",md:"0",lg:"0",xl:"0",full:"9999px"},shadows:{sm:"0 1px 2px rgba(0,0,0,0.05)",md:"0 4px 6px rgba(0,0,0,0.07)",lg:"0 10px 15px rgba(0,0,0,0.1)",xl:"0 20px 25px rgba(0,0,0,0.15)"}};function d(r){let s=[];if(r.colors)for(let[e,n]of Object.entries(r.colors))s.push(` --color-${e}: ${n};`);if(r.fonts)for(let[e,n]of Object.entries(r.fonts))s.push(` --font-${e}: ${n};`);if(r.spacing)for(let[e,n]of Object.entries(r.spacing))s.push(` --spacing-${e}: ${n};`);if(r.borderRadius)for(let[e,n]of Object.entries(r.borderRadius))s.push(` --radius-${e}: ${n};`);if(r.shadows)for(let[e,n]of Object.entries(r.shadows))s.push(` --shadow-${e}: ${n};`);return `:root {
10
+ ${s.join(`
11
+ `)}
12
+ }`}function f(r){let s=d(r.theme||i),e=[];if(r.componentOverrides)for(let[n,o]of Object.entries(r.componentOverrides)){let t=Object.entries(o).map(([g,c])=>` ${g}: ${c};`).join(`
13
+ `);e.push(`${n} {
14
+ ${t}
15
+ }`);}return `
16
+ ${s}
17
+ ${r.customStyles||""}
18
+ ${e.join(`
19
+ `)}
20
+ `}var x={text:{wrapper:{marginBottom:"var(--spacing-md)"},label:{display:"block",marginBottom:"var(--spacing-xs)",fontWeight:"500",color:"var(--color-text)"},input:{width:"100%",padding:"var(--spacing-sm) var(--spacing-md)",border:"1px solid var(--color-border)",borderRadius:"var(--radius-md)",fontSize:"0.875rem"},error:{color:"var(--color-error)",fontSize:"0.75rem",marginTop:"var(--spacing-xs)"}},number:{wrapper:{marginBottom:"var(--spacing-md)"},label:{display:"block",marginBottom:"var(--spacing-xs)",fontWeight:"500"},input:{width:"100%",padding:"var(--spacing-sm) var(--spacing-md)",border:"1px solid var(--color-border)",borderRadius:"var(--radius-md)"}},checkbox:{wrapper:{display:"flex",alignItems:"center",gap:"var(--spacing-sm)"},input:{width:"1rem",height:"1rem"},label:{cursor:"pointer"}},select:{wrapper:{marginBottom:"var(--spacing-md)"},input:{width:"100%",padding:"var(--spacing-sm) var(--spacing-md)",border:"1px solid var(--color-border)",borderRadius:"var(--radius-md)",backgroundColor:"white"}}};export{a,p as b,i as c,l as d,m as e,d as f,f as g,x as h};
@@ -0,0 +1 @@
1
+ 'use strict';var chunkAJAZ7D3W_cjs=require('./chunk-AJAZ7D3W.cjs'),chunkET6NN2V2_cjs=require('./chunk-ET6NN2V2.cjs');async function f(t){let{adminEmail:e,adminPassword:r,adminRole:o="super_admin",tenantId:n,emailConfig:s,sendWelcomeEmail:c=false}=t,a=t.authAdapter||new chunkET6NN2V2_cjs.a({path:t.authDbPath||"./data/auth.db"});try{await a.connect?.();}catch{return {success:false,error:"Failed to connect to auth storage"}}let l=new chunkAJAZ7D3W_cjs.c().validate(r);if(!l.valid)return await a.disconnect?.(),{success:false,error:`Invalid password: ${l.errors.join(", ")}`};if(await a.findUserByEmail(e))return await a.disconnect?.(),{success:false,error:"Admin user already exists"};try{let i=await a.createUser({email:e,password:r,role:o||"admin",tenantId:n});if(c&&s){let u=new chunkAJAZ7D3W_cjs.b(s),A=u.getTemplates().welcome(e.split("@")[0]);await u.send({to:e,...A});}return await a.disconnect?.(),{success:!0,user:i}}catch(i){return await a.disconnect?.(),{success:false,error:i instanceof Error?i.message:"Failed to create admin user"}}}async function y(t,e){return !await t.findUserByEmail(e)}function w(){let t=process.env.KYRO_ADMIN_EMAIL,e=process.env.KYRO_ADMIN_PASSWORD;return !t||!e?null:{authDbPath:process.env.KYRO_AUTH_DB_PATH||"./data/auth.db",adminEmail:t,adminPassword:e,adminRole:process.env.KYRO_ADMIN_ROLE||"super_admin",tenantId:process.env.KYRO_ADMIN_TENANT_ID,emailConfig:process.env.SMTP_HOST?{provider:"smtp",smtp:{host:process.env.SMTP_HOST,port:parseInt(process.env.SMTP_PORT||"587",10),secure:process.env.SMTP_SECURE==="true",auth:{user:process.env.SMTP_USER||"",pass:process.env.SMTP_PASS||""}},from:process.env.SMTP_FROM||"noreply@example.com",fromName:process.env.SMTP_FROM_NAME}:void 0,sendWelcomeEmail:process.env.KYRO_ADMIN_SEND_WELCOME==="true"}}async function T(t){let e=w();if(!e)return null;t&&(e.authAdapter=t);try{if(await e.authAdapter?.connect?.(),await e.authAdapter?.findUserByEmail(e.adminEmail))return await e.authAdapter?.disconnect?.(),{success:!1,error:"Admin user already exists"}}catch{}let r=await f(e);return r.success||console.error(`Bootstrap failed: ${r.error}`),r}async function v(t,e=3,r=2e3){let o="";for(let n=0;n<e;n++){let s=await f(t);if(s.success||(o=s.error||"Unknown error",o.includes("already exists")))return s;n<e-1&&await new Promise(c=>setTimeout(c,r));}return {success:false,error:`Failed after ${e} retries: ${o}`}}exports.a=f;exports.b=y;exports.c=w;exports.d=T;exports.e=v;
@@ -0,0 +1 @@
1
+ import {a,h as h$1}from'./chunk-HLSB2MCK.js';import {a as a$1}from'./chunk-KDNYHLD2.js';import {createHmac,randomBytes,randomUUID}from'crypto';var O={COLLECTION_CREATE:"collection.create",COLLECTION_UPDATE:"collection.update",COLLECTION_DELETE:"collection.delete",MEDIA_UPLOAD:"media.upload",MEDIA_DELETE:"media.delete",AUTH_LOGIN:"auth.login",AUTH_REGISTER:"auth.register",AUTH_LOGOUT:"auth.logout",ORDER_CREATED:"order.created",ORDER_PAID:"order.paid",ORDER_SHIPPED:"order.shipped",ORDER_DELIVERED:"order.delivered"},I=Object.values(O),h="_webhooks",b="_webhook_deliveries";function R(o,e){return `sha256=${createHmac("sha256",e).update(o).digest("hex")}`}function v(){return randomBytes(32).toString("hex")}async function A(o,e,s={}){let r=s.timeout||3e4,t=Date.now(),n=JSON.stringify(e),a={"Content-Type":"application/json","User-Agent":"Kyro-CMS-Webhook/1.0","X-Webhook-Event":e.event,"X-Webhook-Delivery":e.id,"X-Webhook-Timestamp":e.timestamp,...o.headers||{}};if(o.secret){let c=R(n,o.secret);a["X-Webhook-Signature"]=c;}let i=new AbortController,u=setTimeout(()=>i.abort(),r);try{let c=await fetch(o.url,{method:"POST",headers:a,body:n,signal:i.signal});clearTimeout(u);let g=Date.now()-t,d;try{d=(await c.text()).slice(0,1e3);}catch{}let l={success:c.ok,status:c.status,statusText:c.statusText,body:d,duration:g};return l.success&&s.onSuccess?s.onSuccess(l):!l.success&&s.onFailure&&s.onFailure(`HTTP ${c.status}: ${c.statusText}`),l}catch(c){clearTimeout(u);let g=Date.now()-t,d=c.name==="AbortError"?`Request timed out after ${r}ms`:c.message||"Unknown error";return s.onFailure&&s.onFailure(d),{success:false,status:0,duration:g,error:d}}}async function E(o,e,s,r={}){let t=r.maxRetries??5,n=r.retryDelay??1e3,a=null;for(let i=0;i<=t;i++){if(i>0){let u=Math.min(n*Math.pow(2,i-1),3e4);r.onRetry&&r.onRetry(i,`Retrying in ${u}ms...`),await _(u);}if(r.onRetry&&i>0&&r.onRetry(i,`Attempt ${i+1}/${t+1}`),a=await A(o,e,{...r,onRetry:void 0,onSuccess:void 0,onFailure:void 0}),a.success)return a;if(!(a.error?.includes("timed out")&&i<t)&&a.status>=400&&a.status<500)return a}return a||{success:false,status:0,duration:0,error:"All delivery attempts failed"}}function D(o,e,s,r,t,n){return {id:o,webhookId:e,event:s,payload:r,attempt:t,status:n.success?"success":"failed",responseStatus:n.status||void 0,responseBody:n.body,duration:n.duration,error:n.error,createdAt:new Date().toISOString(),deliveredAt:n.success?new Date().toISOString():void 0}}function _(o){return new Promise(e=>setTimeout(e,o))}function L(){return {id:`test_${Date.now()}`,event:"collection.create",timestamp:new Date().toISOString(),collection:"test",operation:"create",data:{message:"This is a test webhook delivery"},user:{id:"system",email:"system@kyro.dev",role:"super_admin"}}}var f=class{db;constructor(e){this.db=e;}async getWebhooks(e){let r=(await this.db.find({collection:h,where:e?.status?{status:{equals:e.status}}:{},limit:100,page:1,draft:true})).docs;return e?.event?r.filter(t=>t.events.includes(e.event)):r}async getWebhookById(e){return this.db.findByID({collection:h,id:e,draft:true})}async createWebhook(e){let s=new Date().toISOString(),r=e.secret||v(),t={id:randomUUID(),name:e.name,url:e.url,events:e.events,status:e.status||"active",secret:r,headers:e.headers||{},createdAt:s,updatedAt:s};return await this.db.create({collection:h,data:t}),t}async updateWebhook(e,s){let r=await this.getWebhookById(e);if(!r)return null;let t={...r,...s,updatedAt:new Date().toISOString()};return s.secret===""&&"secret"in s&&delete t.secret,await this.db.update({collection:h,id:e,data:t}),t}async deleteWebhook(e){await this.db.delete({collection:h,id:e});}async trigger(e,s){let r=await this.getWebhooks({status:"active",event:e});if(r.length===0)return [];let t={id:`wh_${Date.now()}_${randomUUID().slice(0,8)}`,event:e,timestamp:new Date().toISOString(),...s},n=[];for(let a of r){let i=await this.triggerWebhook(a,t);n.push(i);}return n}async triggerWebhook(e,s){let r=`dlv_${Date.now()}_${randomUUID().slice(0,8)}`;try{let t=await E(e,s,r,{maxRetries:5,retryDelay:1e3}),n=D(r,e.id,e.events[0],s,1,t);try{await this.db.create({collection:b,data:n});}catch{console.warn("[WebhookService] Failed to save delivery record:",r);}return t.success?await this.updateWebhook(e.id,{status:"active",lastTriggered:new Date().toISOString()}).catch(()=>{}):await this.updateWebhook(e.id,{status:"error",lastError:t.error}).catch(()=>{}),{deliveryId:r,webhookId:e.id,event:e.events[0],status:t.success?"success":"failed",responseStatus:t.status,duration:t.duration,error:t.error}}catch(t){return {deliveryId:r,webhookId:e.id,event:e.events[0],status:"failed",error:t.message}}}async testWebhook(e){let s=await this.getWebhookById(e);if(!s)return null;let r={id:`test_${Date.now()}`,event:s.events[0]||"collection.create",timestamp:new Date().toISOString(),collection:"test",operation:"create",data:{message:"This is a test webhook delivery from Kyro CMS"},user:{id:"system",email:"system@kyro.dev",role:"super_admin"}};return this.triggerWebhook(s,r)}async getDeliveryHistory(e,s=50){return (await this.db.find({collection:b,where:{webhookId:{equals:e}},sort:"-createdAt",limit:s,page:1})).docs}async retryDelivery(e){let s=await this.db.findByID({collection:b,id:e});if(!s)return null;let r=await this.getWebhookById(s.webhookId);return r?this.triggerWebhook(r,s.payload):null}};function B(o){return new f(o)}function C(o){return o==="read"?"read":o==="create"?"create":o==="update"?"update":"delete"}function H(o,e){return {none:false,read:o==="read",create:o==="read"||o==="create",update:o==="read"||o==="create"||o==="update",delete:o==="read"||o==="create"||o==="update"||o==="delete",admin:true}[e]||false}async function Q(o,e,s,r={}){let{user:t,req:n,tenantID:a$2,apiKey:i}=s,{enablePublicAccess:u=true,defaultAccess:c="none"}=r,g=o.access?.[e];if(g){let l=await a(g,{req:n,user:t,tenantID:a$2});return l===false?{allowed:false,error:"Access denied",status:403}:typeof l=="object"?{allowed:true,extraWhere:l}:{allowed:true}}if(i?.permissions?.length>0){let l=o.slug,m=C(e),p=`${l}:${m}`;return !h$1(i.permissions,p)&&!h$1(i.permissions,`${l}:admin`)?{allowed:false,error:"Access denied: insufficient permissions",status:403}:{allowed:true}}if(t){let l=o.slug,m=C(e),p=`${l}:${m}`,T=a$1({id:t.id,email:t.email,role:t.role},p),x=a$1({id:t.id,email:t.email,role:t.role},`${l}:admin`);return T||x?{allowed:true}:{allowed:false,error:"Access denied: missing RBAC permission",status:403}}let d=H(e,c);return u&&d?{allowed:true}:{allowed:false,error:"Authentication required",status:401}}async function Z(o,e,s,r={}){let{user:t,req:n,tenantID:a$2}=s,{enablePublicAccess:i=true}=r,u=o.access?.[e];if(u)return await a(u,{req:n,user:t,tenantID:a$2})===false?{allowed:false,error:"Access denied",status:403}:{allowed:true};if(t){let c=`globals:${e}`,g=a$1({id:t.id,email:t.email,role:t.role},c),d=a$1({id:t.id,email:t.email,role:t.role},"globals:admin");return g||d?{allowed:true}:{allowed:false,error:"Access denied: missing RBAC permission",status:403}}return i?{allowed:true}:{allowed:false,error:"Authentication required",status:401}}export{Q as a,Z as b,O as c,I as d,h as e,b as f,R as g,v as h,A as i,E as j,D as k,L as l,f as m,B as n};
@@ -0,0 +1 @@
1
+ 'use strict';var pgCore=require('drizzle-orm/pg-core');var m=pgCore.pgTable("media",{id:pgCore.uuid("id").primaryKey().defaultRandom(),filename:pgCore.varchar("filename",{length:255}).notNull().unique(),title:pgCore.varchar("title",{length:255}),originalName:pgCore.varchar("original_name",{length:255}).notNull(),mimeType:pgCore.varchar("mime_type",{length:100}).notNull(),fileSize:pgCore.integer("file_size").notNull(),width:pgCore.integer("width"),height:pgCore.integer("height"),url:pgCore.text("url").notNull().unique(),thumbnailUrl:pgCore.text("thumbnail_url"),folder:pgCore.varchar("folder",{length:255}),provider:pgCore.varchar("provider",{length:50}).notNull(),alt:pgCore.text("alt"),caption:pgCore.text("caption"),type:pgCore.varchar("type",{length:50}).notNull().default("other"),status:pgCore.varchar("status",{length:20}).notNull().default("active"),metadata:pgCore.jsonb("metadata").$type(),createdAt:pgCore.timestamp("created_at").defaultNow().notNull(),updatedAt:pgCore.timestamp("updated_at").defaultNow().notNull()},t=>[pgCore.index("media_folder_idx").on(t.folder),pgCore.index("media_provider_idx").on(t.provider),pgCore.index("media_filename_idx").on(t.filename)]),p=pgCore.pgTable("media_folders",{path:pgCore.varchar("path",{length:500}).primaryKey(),name:pgCore.varchar("name",{length:255}).notNull(),parentPath:pgCore.varchar("parent_path",{length:500}),createdAt:pgCore.timestamp("created_at").defaultNow().notNull()},t=>[pgCore.index("media_folders_parent_idx").on(t.parentPath)]);exports.a=m;exports.b=p;
@@ -0,0 +1,133 @@
1
+ import {a,c,b as b$1,d}from'./chunk-ZAQOSRP6.js';import {sql,eq,desc,and,or,ne,inArray,like,gt,gte,lt,lte}from'drizzle-orm';import {text,uuid,jsonb,timestamp,boolean,decimal,integer as integer$1,varchar,pgTable}from'drizzle-orm/pg-core';import {text as text$1,integer,numeric,sqliteTable}from'drizzle-orm/sqlite-core';import {drizzle}from'drizzle-orm/postgres-js';import ne$1 from'postgres';import {randomBytes}from'crypto';import {mkdir}from'fs/promises';import {resolve,dirname}from'path';import {createRequire}from'module';var F=false;function b(f,s="postgres"){switch(f.type){case "text":case "email":case "password":case "color":return s==="sqlite"?"text":"varchar";case "textarea":case "code":case "markdown":case "secret":return "text";case "number":return f.integer?"integer":"decimal";case "checkbox":return "boolean";case "date":return "timestamp";case "select":case "radio":return s==="sqlite"?"text":"varchar";case "richtext":case "json":case "array":case "group":case "blocks":case "row":case "collapsible":case "tabs":return "jsonb";case "relationship":return s==="sqlite"?"text":"varchar";case "upload":return "jsonb";default:return "jsonb"}}function Ee(f,s="postgres"){let n=f.slug.replace(/-/g,"_"),e=[];e.push(`export const ${n} = pgTable('${n}', {`),e.push(" id: uuid('id').primaryKey().defaultRandom(),");for(let t of f.fields){if(t.name==="id")continue;let o=b(t,s),r=t.required,a=` ${t.name}: pg.${o}('${t.name}')`;t.unique&&(a+=".unique()"),r||(a+=".nullable()"),t.defaultValue!==void 0&&(typeof t.defaultValue=="string"?a+=`.default('${t.defaultValue}')`:typeof t.defaultValue=="boolean"?a+=`.default(${t.defaultValue})`:a+=`.default(sql\`${JSON.stringify(t.defaultValue)}\`)`),a+=",",e.push(a);}return f.timestamps&&(e.push(" createdAt: pg.timestamp('created_at').defaultNow(),"),e.push(" updatedAt: pg.timestamp('updated_at').defaultNow(),")),e.push(` status: ${s==="sqlite"?"sqlite":"pg"}.varchar('status').default('draft'),`),e.push(` hasDraft: ${s==="sqlite"?"sqlite":"pg"}.boolean('hasDraft').default(false),`),e.push("});"),e.join(`
2
+ `)}var C=class extends a{client;schema;dialect;connectionString;versionsTableReady=false;constructor(s){if(super(),this.schema=s.schema||{},s.connectionString){this.connectionString=s.connectionString;let n=s.connectionString.toLowerCase();n.startsWith("postgres://")||n.startsWith("postgresql://")?this.dialect="postgres":n.includes(".db")||n.includes("sqlite")||n.includes("file:")?this.dialect="sqlite":this.dialect=s.type||"postgres";}else this.client=s.client,this.dialect=s.type||"sqlite";}prepareData(s,n){let e=super.prepareData(s,n);e.createdAt&&typeof e.createdAt=="string"&&(e.createdAt=new Date(e.createdAt)),e.updatedAt&&typeof e.updatedAt=="string"&&(e.updatedAt=new Date(e.updatedAt));for(let t of n.fields)if(t.type==="date"&&t.name){let o=e[t.name];o&&typeof o=="string"&&(e[t.name]=new Date(o));}for(let t of n.fields){let r=b(t,this.dialect)==="jsonb";if(t.type==="tabs"&&"tabs"in t&&t.name){let a=s[t.name];if(a&&typeof a=="object"){let i={};for(let[c,u]of Object.entries(a)){let l=t.tabs.flatMap(h=>h.fields).find(h=>h.name===c);(l?.type==="upload"||l?.type==="image"||l?.type==="list"||l?.type==="relationship-block")&&u?i[c]=Array.isArray(u)||typeof u=="object"?JSON.stringify(u):u:i[c]=u;}e[t.name]=r?i:JSON.stringify(i);}}if((t.type==="upload"||t.type==="image"||t.type==="list"||t.type==="relationship-block")&&t.name){let a=s[t.name];a&&(e[t.name]=r?a:Array.isArray(a)||typeof a=="object"?JSON.stringify(a):a);}}for(let t of n.fields)if(t.name&&e[t.name]===""){let o=b(t,this.dialect);(o==="timestamp"||o==="jsonb"||o==="decimal"||o==="integer"||o==="numeric"||o==="boolean")&&(e[t.name]=null);}return e}async connect(){if(this.connectionString&&!this.client){if(this.dialect==="postgres"){let{default:s}=await import('postgres'),{drizzle:n}=await import('drizzle-orm/postgres-js'),e=s(this.connectionString,{onnotice:()=>{}});this.client=n(e,{schema:this.schema});}else if(this.dialect==="sqlite"){let{default:s}=await import('better-sqlite3'),{drizzle:n}=await import('drizzle-orm/better-sqlite3'),e=new s(this.connectionString.replace("file:",""));this.client=n(e,{schema:this.schema});}}this.connected=true;}async init(s,n=[]){if(await super.init(s,n),this.connectionString&&!this.client&&await this.connect(),this.client&&!F){for(let t of s){let o=this.getTableName(t.slug);this.schema[o]||(this.schema[o]=this.createTableFromConfig(t));}await this.ensureCollectionTables(s);let e=n.map(t=>({slug:`_globals_${t.slug}`,fields:t.fields,label:t.label}));for(let t of e){let o=this.getTableName(t.slug);this.schema[o]||(this.schema[o]=this.createTableFromConfig(t,true)),this.collections.has(t.slug)||this.collections.set(t.slug,t);}await this.ensureCollectionTables(e),F=true;}}createTableFromConfig(s,n=false){let e=this.getTableName(s.slug),t={id:n?text("id").primaryKey():uuid("id").primaryKey().defaultRandom()};for(let o of s.fields){if(!o.name||o.name==="id")continue;let r=b(o,this.dialect),a=o.name.replace(/-/g,"_"),i=a.replace(/([A-Z])/g,"_$1").toLowerCase(),c;if(this.dialect==="sqlite")switch(r){case "varchar":case "text":c=text$1(i);break;case "integer":c=integer(i);break;case "decimal":case "numeric":c=numeric(i);break;case "boolean":c=integer(i,{mode:"boolean"});break;case "timestamp":c=text$1(i);break;case "jsonb":c=text$1(i);break;default:c=text$1(i);}else switch(r){case "varchar":c=varchar(i,{length:255});break;case "integer":c=integer$1(i);break;case "decimal":c=decimal(i);break;case "boolean":c=boolean(i);break;case "timestamp":c=timestamp(i);break;case "jsonb":c=jsonb(i);break;default:c=text(i);}o.required||(c=c.default(null)),t[a]=c;}return t.createdAt||(t.createdAt=this.dialect==="sqlite"?text$1("created_at").default(new Date().toISOString()):timestamp("created_at").defaultNow()),t.updatedAt||(t.updatedAt=this.dialect==="sqlite"?text$1("updated_at").default(new Date().toISOString()):timestamp("updated_at").defaultNow()),t.status=this.dialect==="sqlite"?text$1("status").default("draft"):varchar("status",{length:20}).default("draft"),t.hasDraft=this.dialect==="sqlite"?integer("hasDraft",{mode:"boolean"}).default(false):boolean("hasDraft").default(false),this.dialect==="sqlite"?sqliteTable(e,t):pgTable(e,t)}async ensureCollectionTables(s){let n=[];for(let e of s){let t=e.slug.startsWith("_globals_"),o=this.getTableName(e.slug),r=this.generateCreateColumns(e),a=e.fields.some(l=>l.name==="createdAt"),i=e.fields.some(l=>l.name==="updatedAt"),c=e.fields.some(l=>l.name==="status"),u=e.fields.some(l=>l.name==="hasDraft");if(this.dialect==="postgres"){let l=t?'"id" TEXT PRIMARY KEY':'"id" UUID PRIMARY KEY DEFAULT gen_random_uuid()';n.push(`
3
+ CREATE TABLE IF NOT EXISTS "${o}" (
4
+ ${l},
5
+ ${r}
6
+ ${a?"":'"created_at" TIMESTAMP NOT NULL DEFAULT NOW(),'}
7
+ ${i?"":'"updated_at" TIMESTAMP NOT NULL DEFAULT NOW(),'}
8
+ ${c?"":`"status" VARCHAR(20) DEFAULT 'draft',`}
9
+ ${u?"":'"hasDraft" BOOLEAN DEFAULT false'}
10
+ )
11
+ `);}else n.push(`
12
+ CREATE TABLE IF NOT EXISTS "${o}" (
13
+ "id" TEXT PRIMARY KEY,
14
+ ${r}
15
+ ${a?"":`"created_at" TEXT NOT NULL DEFAULT (datetime('now')),`}
16
+ ${i?"":`"updated_at" TEXT NOT NULL DEFAULT (datetime('now')),`}
17
+ ${c?"":`"status" TEXT DEFAULT 'draft',`}
18
+ ${u?"":'"hasDraft" INTEGER DEFAULT 0'}
19
+ )
20
+ `);}if(n.length>0)if(this.dialect==="postgres")await this.client.execute(sql.raw(n.join(`;
21
+ `)));else for(let e of n)await this.client.execute(sql.raw(e));for(let e of s){let t=this.getTableName(e.slug);t==="users"||t==="audit_logs"||await this.syncTableColumns(e,t);}}getColumnSqlDefinition(s,n){let e=b(s,n),t=s.name.replace(/-/g,"_").replace(/([A-Z])/g,"_$1").toLowerCase(),o=this.columnSqlType(e,n);return `"${t}" ${o} DEFAULT NULL`}columnSqlType(s,n){if(n==="sqlite")switch(s){case "varchar":return "TEXT";case "text":return "TEXT";case "integer":return "INTEGER";case "decimal":case "numeric":return "NUMERIC";case "boolean":return "INTEGER";case "timestamp":return "TEXT";case "jsonb":return "TEXT";default:return "TEXT"}switch(s){case "varchar":return "VARCHAR(255)";case "text":return "TEXT";case "integer":return "INTEGER";case "decimal":case "numeric":return "DECIMAL";case "boolean":return "BOOLEAN";case "timestamp":return "TIMESTAMP";case "jsonb":return "JSONB";default:return "TEXT"}}getExpectedColumnDefs(s,n){let e={},t=s.slug.startsWith("_globals_"),o=s.fields.some(c=>c.name==="createdAt"),r=s.fields.some(c=>c.name==="updatedAt"),a=s.fields.some(c=>c.name==="status"),i=s.fields.some(c=>c.name==="hasDraft");this.dialect==="postgres"?(e.id=t?'"id" TEXT PRIMARY KEY':'"id" UUID PRIMARY KEY DEFAULT gen_random_uuid()',o||(e.created_at='"created_at" TIMESTAMP DEFAULT NULL'),r||(e.updated_at='"updated_at" TIMESTAMP DEFAULT NULL'),a||(e.status='"status" VARCHAR(20) DEFAULT NULL'),i||(e.hasDraft='"hasDraft" BOOLEAN DEFAULT NULL')):(e.id='"id" TEXT PRIMARY KEY',o||(e.created_at='"created_at" TEXT DEFAULT NULL'),r||(e.updated_at='"updated_at" TEXT DEFAULT NULL'),a||(e.status='"status" TEXT DEFAULT NULL'),i||(e.hasDraft='"hasDraft" INTEGER DEFAULT NULL'));for(let c of s.fields){if(!c.name||c.name==="id")continue;let u=this.getColumnSqlDefinition(c,this.dialect),l=c.name.replace(/-/g,"_").replace(/([A-Z])/g,"_$1").toLowerCase();e[l]=u;}return e}async syncTableColumns(s,n){let e;try{if(this.dialect==="postgres"){let r=await this.client.execute(sql`SELECT column_name, data_type, character_maximum_length FROM information_schema.columns WHERE table_name = ${n}`);e=new Map(r.map(a=>[a.column_name,{type:a.data_type,maxLen:a.character_maximum_length}]));}else {let r=await this.client.execute(sql`PRAGMA table_info("${sql.raw(n)}")`);e=new Map(r.map(a=>[a.name,{type:a.type,maxLen:null}]));}}catch{return}let t=this.getExpectedColumnDefs(s,n),o=Object.keys(t).filter(r=>!e.has(r));if(o.length>0){let r=o.map(a=>`ALTER TABLE "${n}" ADD COLUMN ${t[a]}`);await this.executeRaw(sql.raw(r.join(`;
22
+ `)));}if(this.dialect==="postgres")for(let r of s.fields){if(!r.name||r.name==="id")continue;let a=b(r,this.dialect),i=r.name.replace(/-/g,"_").replace(/([A-Z])/g,"_$1").toLowerCase(),c=e.get(i);!c||c.type!=="character varying"||(a==="text"?await this.executeRaw(sql.raw(`ALTER TABLE "${n}" ALTER COLUMN "${i}" TYPE TEXT`)):a==="jsonb"&&(await this.executeRaw(sql.raw(`ALTER TABLE "${n}" ALTER COLUMN "${i}" DROP DEFAULT`)),await this.executeRaw(sql.raw(`ALTER TABLE "${n}" ALTER COLUMN "${i}" TYPE JSONB USING (CASE WHEN "${i}" IS NULL THEN NULL WHEN "${i}"::text ~ '^\\s*\\{' THEN "${i}"::jsonb ELSE jsonb_build_object('id', "${i}"::text) END)`))));}}generateCreateColumns(s){let n=[];for(let e of s.fields){if(!e.name||e.name==="id")continue;let t=b(e,this.dialect),o=e.name.replace(/-/g,"_").replace(/([A-Z])/g,"_$1").toLowerCase(),r=e.required?"NOT NULL":"DEFAULT NULL",a;if(this.dialect==="sqlite")switch(t){case "varchar":case "text":a=`TEXT ${r}`;break;case "integer":a=`INTEGER ${r}`;break;case "decimal":case "numeric":a=`NUMERIC ${r}`;break;case "boolean":a=`INTEGER ${r}`;break;case "timestamp":a=`TEXT ${r}`;break;case "jsonb":a=`TEXT ${r}`;break;default:a=`TEXT ${r}`;}else switch(t){case "varchar":a=`VARCHAR(255) ${r}`;break;case "integer":a=`INTEGER ${r}`;break;case "decimal":a=`DECIMAL ${r}`;break;case "boolean":a=`BOOLEAN ${r}`;break;case "timestamp":a=`TIMESTAMP ${r}`;break;case "jsonb":a=`JSONB ${r}`;break;default:a=`TEXT ${r}`;}n.push(`"${o}" ${a}`);}return n.join(`,
23
+ `)+(n.length>0?",":"")}async disconnect(){this.connected=false;}async find(s){let{collection:n,where:e={},sort:t,limit:o=10,page:r=1,tenantID:a,select:i,draft:c$1}=s,u=this.getCollection(n),l=this.getTable(n),p={...e};this.tenantContext&&u.tenantScoped&&(p=c({where:p},n,this.tenantContext,b$1).where||{});let h=this.buildWhereClause(p,u,l,a);!c$1&&l.status&&h.push(eq(l.status,"published"));let y=this.parseSort(t),N=!c$1&&l.status?{...p,status:"published"}:p,M=await this.count({collection:n,where:N,tenantID:a}),P=(r-1)*o,$=[];try{let m=l[y.field]||l.createdAt||l.id,L=y.direction==="asc"?m:desc(m),T=this.client.select().from(l);h.length>0&&(T=T.where(and(...h))),$=await T.orderBy(L).limit(o).offset(P);}catch(m){console.error("[DrizzleAdapter] Query error:",m);}let D=$.map(m=>this.processResult(m,u));return this.tenantContext&&!this.tenantContext.isSuperAdmin&&(D=D.filter(m=>d(m,n,this.tenantContext,b$1))),c$1&&(D=await Promise.all(D.map(async m=>{let L=await this.executeRaw(sql`
24
+ SELECT * FROM kyro_versions
25
+ WHERE collection_slug = ${n}
26
+ AND document_id = ${m.id}
27
+ ORDER BY created_at DESC
28
+ LIMIT 1
29
+ `);if(L.length>0){let T=L[0],j=typeof T.data=="string"?JSON.parse(T.data):T.data;return {...m,...j,status:m.status}}return m}))),{docs:D,...this.calculatePagination(r,o,M)}}async findByID(s){let{collection:n,id:e,tenantID:t,draft:o}=s,r=this.getCollection(n),a=this.getTable(n);if(this.tenantContext&&r.tenantScoped){let p={id:e,tenantId:this.tenantContext.tenantId};if(!d(p,n,this.tenantContext,b$1))return null}let i=[eq(a.id,e)];t&&a.tenantId&&i.push(eq(a.tenantId,t)),!o&&a.status&&i.push(eq(a.status,"published"));let c=i.length>1?and(...i):i[0],u=await this.client.select().from(a).where(c);if(u.length===0)return null;let l=this.processResult(u[0],r);if(o){let p=await this.executeRaw(sql`
30
+ SELECT * FROM kyro_versions
31
+ WHERE collection_slug = ${n}
32
+ AND document_id = ${l.id}
33
+ ORDER BY created_at DESC
34
+ LIMIT 1
35
+ `);if(p.length>0){let h=p[0],y=typeof h.data=="string"?JSON.parse(h.data):h.data;l={...l,...y,status:l.status};}}return l}async create(s){let{collection:n,data:e,tenantID:t}=s,o=this.getCollection(n),r=this.getTable(n),a=this.prepareData(e,o);t&&(a.tenantId=t);let i=await this.client.insert(r).values(a).returning();return this.processResult(i[0],o)}async update(s){let{collection:n,id:e,data:t,tenantID:o}=s,r=this.getCollection(n),a=this.getTable(n),i=this.prepareData(t,r);delete i.id;let c=[eq(a.id,e)];o&&a.tenantId&&c.push(eq(a.tenantId,o));let u=await this.client.update(a).set(i).where(and(...c)).returning();if(u.length===0)throw new Error(`Document not found: ${n}/${e}`);return this.processResult(u[0],r)}async delete(s){let{collection:n,id:e,tenantID:t}=s,o=this.getCollection(n),r=this.getTable(n),a=[eq(r.id,e)];t&&r.tenantId&&a.push(eq(r.tenantId,t));let i=await this.client.delete(r).where(and(...a)).returning();if(i.length===0)throw new Error(`Document not found: ${n}/${e}`);return this.processResult(i[0],o)}async count(s){let{collection:n,where:e={},tenantID:t}=s,o=this.getCollection(n),r=this.getTable(n),a=this.buildWhereClause(e,o,r,t);try{let i=this.client.select({count:sql`count(*)`}).from(r);a.length>0&&(i=i.where(and(...a)));let c=await i;return Number(c[0]?.count||0)}catch{return 0}}async findOne(s){let{collection:n,where:e={},tenantID:t,draft:o}=s;if(n.startsWith("_globals_")){let a=n.replace("_globals_",""),i=this.globals.get(a);if(!i)throw new Error(`Global "${a}" not found`);let c=this.getTable(n),u=this.client.select().from(c);!o&&c.status&&(u=u.where(eq(c.status,"published")));let l=await u.limit(1);if(l.length===0)return null;let p=this.processResult(l[0],i);if(o){let h=await this.executeRaw(sql`
36
+ SELECT * FROM kyro_versions
37
+ WHERE collection_slug = ${n}
38
+ AND document_id = ${a}
39
+ ORDER BY created_at DESC
40
+ LIMIT 1
41
+ `);if(h.length>0){let y=h[0],N=typeof y.data=="string"?JSON.parse(y.data):y.data;p={...p,...N,status:p.status};}}return p}return (await this.find({...s,limit:1})).docs[0]||null}async findVersions(s){await this.ensureVersionsTable();let{collection:n,documentId:e,limit:t=10,page:o=1,tenantID:r}=s,a=(o-1)*t,i=await this.executeRaw(sql`
42
+ SELECT count(*) as count
43
+ FROM kyro_versions
44
+ WHERE collection_slug = ${n}
45
+ AND document_id = ${e}
46
+ AND autosave = 0
47
+ ${r?sql`AND tenant_id = ${r}`:sql``}
48
+ `),c=parseInt(i[0]?.count||"0");return {docs:(await this.executeRaw(sql`
49
+ SELECT *
50
+ FROM kyro_versions
51
+ WHERE collection_slug = ${n}
52
+ AND document_id = ${e}
53
+ AND autosave = 0
54
+ ${r?sql`AND tenant_id = ${r}`:sql``}
55
+ ORDER BY created_at DESC
56
+ LIMIT ${t}
57
+ OFFSET ${a}
58
+ `)).map(l=>({...l,data:typeof l.data=="string"?JSON.parse(l.data):l.data})),...this.calculatePagination(o,t,c)}}async findVersionByID(s){await this.ensureVersionsTable();let n=await this.executeRaw(sql`
59
+ SELECT * FROM kyro_versions
60
+ WHERE id = ${s.versionId}
61
+ AND collection_slug = ${s.collection}
62
+ ${s.tenantID?sql`AND tenant_id = ${s.tenantID}`:sql``}
63
+ LIMIT 1
64
+ `);if(n.length===0)return null;let e=n[0];return {...e,data:typeof e.data=="string"?JSON.parse(e.data):e.data}}async createVersion(s){await this.ensureVersionsTable();let n=new Date().toISOString();if(s.autosave){let t=await this.executeRaw(sql`
65
+ SELECT * FROM kyro_versions
66
+ WHERE collection_slug = ${s.collection}
67
+ AND document_id = ${s.documentId}
68
+ AND autosave = 1
69
+ ${s.tenantID?sql`AND tenant_id = ${s.tenantID}`:sql``}
70
+ LIMIT 1
71
+ `);if(t.length>0)return await this.executeRaw(sql`
72
+ UPDATE kyro_versions
73
+ SET data = ${JSON.stringify(s.data)},
74
+ status = ${s.status},
75
+ updated_at = ${n}
76
+ WHERE id = ${t[0].id}
77
+ `),this.findVersionByID({collection:s.collection,versionId:t[0].id,tenantID:s.tenantID})}let e=Math.random().toString(36).substring(2,15);if(await this.executeRaw(sql`
78
+ INSERT INTO kyro_versions (
79
+ id, collection_slug, document_id, tenant_id, data, status, autosave, created_by, change_description, created_at, updated_at
80
+ ) VALUES (
81
+ ${e}, ${s.collection}, ${s.documentId}, ${s.tenantID||null},
82
+ ${JSON.stringify(s.data)}, ${s.status}, ${s.autosave?1:0}, ${s.createdBy||null},
83
+ ${s.changeDescription||null}, ${n}, ${n}
84
+ )
85
+ `),!s.autosave){let t=this.getCollection(s.collection);t.versions?.maxPerDoc&&await this.deleteVersions({collection:s.collection,documentId:s.documentId,keepLatest:t.versions.maxPerDoc,tenantID:s.tenantID});}return this.findVersionByID({collection:s.collection,versionId:e,tenantID:s.tenantID})}async updateLatestVersion(s){return this.createVersion({...s,autosave:true})}async deleteVersions(s){if(await this.ensureVersionsTable(),s.keepLatest){let e=(await this.executeRaw(sql`
86
+ SELECT id FROM kyro_versions
87
+ WHERE collection_slug = ${s.collection}
88
+ AND document_id = ${s.documentId}
89
+ AND autosave = 0
90
+ ${s.tenantID?sql`AND tenant_id = ${s.tenantID}`:sql``}
91
+ ORDER BY created_at DESC
92
+ LIMIT ${s.keepLatest}
93
+ `)).map(t=>t.id);e.length>0&&await this.executeRaw(sql`
94
+ DELETE FROM kyro_versions
95
+ WHERE collection_slug = ${s.collection}
96
+ AND document_id = ${s.documentId}
97
+ AND autosave = 0
98
+ AND id NOT IN (${sql.join(e.map(t=>sql`${t}`),sql`, `)})
99
+ `);}else await this.executeRaw(sql`
100
+ DELETE FROM kyro_versions
101
+ WHERE collection_slug = ${s.collection}
102
+ AND document_id = ${s.documentId}
103
+ ${s.tenantID?sql`AND tenant_id = ${s.tenantID}`:sql``}
104
+ `);}getTable(s){let n=this.getTableName(s),e=this.schema[n];if(!e)throw new Error(`Table "${n}" not found in schema`);return e}buildWhereClause(s,n,e,t){let o=[];t&&n.tenantScoped&&e.tenantId&&o.push(eq(e.tenantId,t));for(let[r,a]of Object.entries(s))if(r==="AND"&&Array.isArray(a)){let i=a.map(c=>this.buildWhereClause(c,n,e)).flat().filter(Boolean);i.length>0&&o.push(and(...i));}else if(r==="OR"&&Array.isArray(a)){let i=a.map(c=>this.buildWhereClause(c,n,e)).flat().filter(Boolean);i.length>0&&o.push(or(...i));}else if(typeof a=="object"&&a!==null&&!Array.isArray(a)){let i=e[r];if(!i)continue;a.equals!==void 0&&o.push(eq(i,a.equals)),a.not_equals!==void 0&&o.push(ne(i,a.not_equals)),a.in&&Array.isArray(a.in)&&o.push(inArray(i,a.in)),a.like!==void 0&&o.push(like(i,a.like)),a.contains!==void 0&&o.push(like(i,`%${a.contains}%`)),a.greater_than!==void 0&&o.push(gt(i,a.greater_than)),a.greater_than_equal!==void 0&&o.push(gte(i,a.greater_than_equal)),a.less_than!==void 0&&o.push(lt(i,a.less_than)),a.less_than_equal!==void 0&&o.push(lte(i,a.less_than_equal));}else {let i=e[r];i&&o.push(eq(i,a));}return o}processResult(s,n){if(!s)return null;let e={...s};s.id&&(e.id=String(s.id));for(let t of n.fields){if(!t.name)continue;let o=t.name.replace(/-/g,"_").replace(/([A-Z])/g,"_$1").toLowerCase();o!==t.name&&e[o]!==void 0&&e[t.name]===void 0&&(e[t.name]=e[o],delete e[o]);}for(let t of n.fields){if(["json","richtext","array","group","blocks","upload","image","list","relationship-block"].includes(t.type)){let o=t;if(e[o.name]&&typeof e[o.name]=="string")try{let r=JSON.parse(e[o.name]);e[o.name]=r;}catch{}}if(t.type==="tabs"&&"tabs"in t&&t.name){if(typeof e[t.name]=="object"&&e[t.name]!==null&&!Array.isArray(e[t.name])){for(let r of t.tabs)for(let a of r.fields)if((a.type==="upload"||a.type==="image")&&a.name){let i=e[t.name][a.name];if(typeof i=="string")try{let c=JSON.parse(i);e[t.name][a.name]=Array.isArray(c)?c.map(u=>u&&typeof u=="object"&&typeof u.id=="string"?u.id:String(u||"")):typeof c.id=="string"?c.id:String(c.id||"");}catch{}else i&&typeof i=="object"&&(e[t.name][a.name]=Array.isArray(i)?i.map(c=>c&&typeof c=="object"&&typeof c.id=="string"?c.id:String(c||"")):typeof i.id=="string"?i.id:String(i.id||""));}continue}if(typeof e[t.name]=="string")try{let r=JSON.parse(e[t.name]);if(typeof r=="object"&&r!==null){e[t.name]=r;continue}}catch{}let o={};for(let r of t.tabs)for(let a of r.fields)if(a.name&&e[a.name]!==void 0){let i=e[a.name];if(["json","richtext","array","group","blocks","upload","image","list","relationship-block"].includes(a.type)){if(i&&typeof i=="string")try{i=JSON.parse(i);}catch{}(a.type==="upload"||a.type==="image")&&i&&typeof i=="object"&&(i=Array.isArray(i)?i.map(c=>c&&typeof c=="object"&&typeof c.id=="string"?c.id:String(c||"")):typeof i.id=="string"?i.id:String(i.id||""));}o[a.name]=i,delete e[a.name];}e[t.name]=o;}}return e.createdAt&&(e.createdAt=new Date(e.createdAt).toISOString()),e.updatedAt&&(e.updatedAt=new Date(e.updatedAt).toISOString()),e}async ensureVersionsTable(){if(this.versionsTableReady)return;let s;this.dialect==="sqlite"?s=`
105
+ CREATE TABLE IF NOT EXISTS kyro_versions (
106
+ id text PRIMARY KEY,
107
+ collection_slug text NOT NULL,
108
+ document_id text NOT NULL,
109
+ tenant_id text,
110
+ data text NOT NULL,
111
+ status text NOT NULL DEFAULT 'draft',
112
+ autosave integer NOT NULL DEFAULT 0,
113
+ created_by text,
114
+ change_description text,
115
+ created_at text DEFAULT (datetime('now')),
116
+ updated_at text DEFAULT (datetime('now'))
117
+ )
118
+ `:s=`
119
+ CREATE TABLE IF NOT EXISTS kyro_versions (
120
+ id text PRIMARY KEY,
121
+ collection_slug text NOT NULL,
122
+ document_id text NOT NULL,
123
+ tenant_id text,
124
+ data text NOT NULL,
125
+ status text NOT NULL,
126
+ autosave integer NOT NULL DEFAULT 0,
127
+ created_by text,
128
+ change_description text,
129
+ created_at text NOT NULL,
130
+ updated_at text NOT NULL
131
+ )
132
+ `,await this.executeRaw(sql.raw(s));try{this.dialect==="postgres"?await this.executeRaw(sql.raw("ALTER TABLE kyro_versions ADD COLUMN IF NOT EXISTS autosave integer NOT NULL DEFAULT 0")):await this.executeRaw(sql.raw("ALTER TABLE kyro_versions ADD COLUMN autosave integer NOT NULL DEFAULT 0"));}catch{}this.versionsTableReady=true;}async executeRaw(s){let n=await this.client.execute(s);return Array.isArray(n)?n:Array.isArray(n?.rows)?n.rows:Array.isArray(n?.[0])?n[0]:[]}};function be(f){return new C(f)}var de=createRequire(import.meta.url),ue="node:sqlite",{DatabaseSync:fe}=de(ue);function pe(){return process.env.DB_TYPE==="postgres"?"postgres":"sqlite"}function k(){return randomBytes(16).toString("hex")}async function Ie(){let f=pe();if(f==="sqlite"){let r=resolve(process.cwd(),"data","kyro.db");await mkdir(dirname(r),{recursive:true});let a=new fe(r);return a.exec("PRAGMA journal_mode = WAL"),{db:a,dialect:f,genId:k}}let s=process.env.DATABASE_URL||"postgresql://postgres:postgres@localhost:5432/kyro_cms",n=parseInt(process.env.DB_POOL_MAX||"10",10),e=process.env.DB_SSL==="true",t=ne$1(s,{max:n,ssl:e?"require":false,onnotice:()=>{}});return {db:drizzle(t),dialect:f,genId:k}}async function Ce(f,s){}async function $e(f){let{roles:s}=await import('./schema-KFYUM674.js');await f.insert(s).values({name:"super_admin",level:100,inherits:[],description:"Full system access across all tenants",isSystem:true}).onConflictDoNothing();}
133
+ export{b as a,Ee as b,C as c,be as d,k as e,Ie as f,Ce as g,$e as h};
@@ -0,0 +1 @@
1
+ 'use strict';var pgCore=require('drizzle-orm/pg-core');var r=pgCore.pgTable("settings",{key:pgCore.varchar("key",{length:255}).primaryKey(),value:pgCore.text("value").notNull(),description:pgCore.text("description"),updatedAt:pgCore.timestamp("updated_at").defaultNow()});exports.a=r;
@@ -0,0 +1 @@
1
+ 'use strict';var chunkTD6RULJU_cjs=require('./chunk-TD6RULJU.cjs'),chunkUJNSOOYZ_cjs=require('./chunk-UJNSOOYZ.cjs'),chunkET6NN2V2_cjs=require('./chunk-ET6NN2V2.cjs'),chunk6CLRVJPP_cjs=require('./chunk-6CLRVJPP.cjs'),chunkGYQMNXXW_cjs=require('./chunk-GYQMNXXW.cjs'),chunkUDSJGML2_cjs=require('./chunk-UDSJGML2.cjs'),chunkATLSIYRH_cjs=require('./chunk-ATLSIYRH.cjs'),A=require('kyro:config');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var A__default=/*#__PURE__*/_interopDefault(A);exports.a=null;var n=null;async function _(){if(!exports.a)try{let e=A__default.default.default||A__default.default;exports.a=chunkTD6RULJU_cjs.q(e),await exports.a.init(),await exports.a.loadSettings();let o=exports.a.db,r;if(o instanceof chunk6CLRVJPP_cjs.c){if(o.dialect==="postgres")r=new chunkGYQMNXXW_cjs.a({db:o.client});else if(o.dialect==="sqlite"){let i=process.env.KYRO_AUTH_DB_PATH||"./data/auth.db";r=new chunkET6NN2V2_cjs.a({path:i});}}else if(o instanceof chunkTD6RULJU_cjs.r){let i=process.env.KYRO_AUTH_DB_PATH||"./data/auth.db";r=new chunkET6NN2V2_cjs.a({path:i});}else o instanceof chunkUDSJGML2_cjs.a&&(r=new chunkATLSIYRH_cjs.a({db:o.db}));r?.connect&&await r.connect(),(await chunkUJNSOOYZ_cjs.d(r))?.success,typeof exports.a.startWebSocket=="function"&&exports.a.startWebSocket().catch(i=>{console.error("[Kyro] WebSocket auto-start failed:",i);}),globalThis.__KYRO_INSTANCE__=exports.a;}catch(e){throw exports.a=null,n=null,console.error("[Kyro API] Init failed, will retry:",e),e}}async function v(){n||(n=_()),await n;}var D=async e=>{if(!exports.a){n||(n=_());try{await Promise.race([n,new Promise((l,a)=>setTimeout(()=>a(new Error("Initialization timeout")),3e4))]);}catch{return new Response(JSON.stringify({error:"Service Unavailable",message:"Kyro CMS is still starting up. Please try again in a moment."}),{status:503,headers:{"Content-Type":"application/json","Retry-After":"5"}})}}let r=new URL(e.request.url).pathname,s=__KYRO_API_PATH__;if(r===`${s}/graphql`&&typeof exports.a.getGraphQL=="function"){let a=await exports.a.getGraphQL().fetch(e.request,e.locals);return new Response(a.body,a)}if(r.startsWith(`${s}/trpc/`)&&typeof exports.a.getTRPC=="function"){let a=await exports.a.getTRPC().fetch(e.request,e.locals);return new Response(a.body,a)}return exports.a.getREST().fetch(e.request,e.locals)};exports.b=v;exports.c=D;