@kyro-cms/core 0.10.4 → 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-3AKCVYDB.js +0 -162
  133. package/dist/chunk-3AKCVYDB.js.map +0 -1
  134. package/dist/chunk-3KTWGODI.cjs +0 -178
  135. package/dist/chunk-3KTWGODI.cjs.map +0 -1
  136. package/dist/chunk-3YELQL7Z.cjs +0 -4
  137. package/dist/chunk-3YELQL7Z.cjs.map +0 -1
  138. package/dist/chunk-4CV4JOE5.js +0 -24
  139. package/dist/chunk-4CV4JOE5.js.map +0 -1
  140. package/dist/chunk-4OCMVGEY.cjs +0 -173
  141. package/dist/chunk-4OCMVGEY.cjs.map +0 -1
  142. package/dist/chunk-4PWRCMTQ.cjs +0 -15
  143. package/dist/chunk-4PWRCMTQ.cjs.map +0 -1
  144. package/dist/chunk-53NYVYVX.js +0 -3243
  145. package/dist/chunk-53NYVYVX.js.map +0 -1
  146. package/dist/chunk-5GFQPHGT.cjs +0 -156
  147. package/dist/chunk-5GFQPHGT.cjs.map +0 -1
  148. package/dist/chunk-5RPRLTTN.js +0 -861
  149. package/dist/chunk-5RPRLTTN.js.map +0 -1
  150. package/dist/chunk-74YSDAWE.cjs +0 -2749
  151. package/dist/chunk-74YSDAWE.cjs.map +0 -1
  152. package/dist/chunk-7OGPN7MP.js +0 -352
  153. package/dist/chunk-7OGPN7MP.js.map +0 -1
  154. package/dist/chunk-7OS7TX2Q.cjs +0 -495
  155. package/dist/chunk-7OS7TX2Q.cjs.map +0 -1
  156. package/dist/chunk-ADLJSJSN.cjs +0 -13
  157. package/dist/chunk-ADLJSJSN.cjs.map +0 -1
  158. package/dist/chunk-B6X3LN25.cjs +0 -6486
  159. package/dist/chunk-B6X3LN25.cjs.map +0 -1
  160. package/dist/chunk-BYBMTIMT.js +0 -419
  161. package/dist/chunk-BYBMTIMT.js.map +0 -1
  162. package/dist/chunk-CF7OL6HR.js +0 -355
  163. package/dist/chunk-CF7OL6HR.js.map +0 -1
  164. package/dist/chunk-CJX74IYK.js +0 -489
  165. package/dist/chunk-CJX74IYK.js.map +0 -1
  166. package/dist/chunk-CKVOU6MX.cjs +0 -52
  167. package/dist/chunk-CKVOU6MX.cjs.map +0 -1
  168. package/dist/chunk-CZLDE2OZ.cjs +0 -28
  169. package/dist/chunk-CZLDE2OZ.cjs.map +0 -1
  170. package/dist/chunk-DPA3KWPY.cjs +0 -205
  171. package/dist/chunk-DPA3KWPY.cjs.map +0 -1
  172. package/dist/chunk-EEJUFDMF.cjs +0 -424
  173. package/dist/chunk-EEJUFDMF.cjs.map +0 -1
  174. package/dist/chunk-FIAMXNTH.js +0 -220
  175. package/dist/chunk-FIAMXNTH.js.map +0 -1
  176. package/dist/chunk-GAOXD3XT.js +0 -175
  177. package/dist/chunk-GAOXD3XT.js.map +0 -1
  178. package/dist/chunk-GTGRLD4Y.js +0 -3
  179. package/dist/chunk-GTGRLD4Y.js.map +0 -1
  180. package/dist/chunk-GUUB5EAG.cjs +0 -223
  181. package/dist/chunk-GUUB5EAG.cjs.map +0 -1
  182. package/dist/chunk-GXFOGU7N.cjs +0 -359
  183. package/dist/chunk-GXFOGU7N.cjs.map +0 -1
  184. package/dist/chunk-GZS4LMR7.js +0 -422
  185. package/dist/chunk-GZS4LMR7.js.map +0 -1
  186. package/dist/chunk-HY6B7B5A.js +0 -150
  187. package/dist/chunk-HY6B7B5A.js.map +0 -1
  188. package/dist/chunk-HZOMOK5Y.js +0 -2728
  189. package/dist/chunk-HZOMOK5Y.js.map +0 -1
  190. package/dist/chunk-IDVRRRAK.cjs +0 -824
  191. package/dist/chunk-IDVRRRAK.cjs.map +0 -1
  192. package/dist/chunk-KC2GDBLS.cjs +0 -84
  193. package/dist/chunk-KC2GDBLS.cjs.map +0 -1
  194. package/dist/chunk-L4EZKIEX.js +0 -185
  195. package/dist/chunk-L4EZKIEX.js.map +0 -1
  196. package/dist/chunk-LNTFRAHF.cjs +0 -473
  197. package/dist/chunk-LNTFRAHF.cjs.map +0 -1
  198. package/dist/chunk-MTIRYI7F.cjs +0 -4
  199. package/dist/chunk-MTIRYI7F.cjs.map +0 -1
  200. package/dist/chunk-N4GN6Q3V.cjs +0 -869
  201. package/dist/chunk-N4GN6Q3V.cjs.map +0 -1
  202. package/dist/chunk-N4H37VN4.cjs +0 -259
  203. package/dist/chunk-N4H37VN4.cjs.map +0 -1
  204. package/dist/chunk-N5QSHUA6.js +0 -1135
  205. package/dist/chunk-N5QSHUA6.js.map +0 -1
  206. package/dist/chunk-NKPKR5BW.cjs +0 -188
  207. package/dist/chunk-NKPKR5BW.cjs.map +0 -1
  208. package/dist/chunk-OIRG6ZRV.cjs +0 -1073
  209. package/dist/chunk-OIRG6ZRV.cjs.map +0 -1
  210. package/dist/chunk-OJ2AM75W.cjs +0 -253
  211. package/dist/chunk-OJ2AM75W.cjs.map +0 -1
  212. package/dist/chunk-OLV7K22H.js +0 -6457
  213. package/dist/chunk-OLV7K22H.js.map +0 -1
  214. package/dist/chunk-OX6GOIPH.js +0 -516
  215. package/dist/chunk-OX6GOIPH.js.map +0 -1
  216. package/dist/chunk-P2YW545G.js +0 -11
  217. package/dist/chunk-P2YW545G.js.map +0 -1
  218. package/dist/chunk-PHJRNPHY.cjs +0 -3291
  219. package/dist/chunk-PHJRNPHY.cjs.map +0 -1
  220. package/dist/chunk-Q72BOAPK.js +0 -817
  221. package/dist/chunk-Q72BOAPK.js.map +0 -1
  222. package/dist/chunk-QU2RFFH4.js +0 -3
  223. package/dist/chunk-QU2RFFH4.js.map +0 -1
  224. package/dist/chunk-RP7VZUEL.js +0 -49
  225. package/dist/chunk-RP7VZUEL.js.map +0 -1
  226. package/dist/chunk-SHTTJMLT.cjs +0 -361
  227. package/dist/chunk-SHTTJMLT.cjs.map +0 -1
  228. package/dist/chunk-SX76DNOO.js +0 -103
  229. package/dist/chunk-SX76DNOO.js.map +0 -1
  230. package/dist/chunk-THBQG64D.cjs +0 -425
  231. package/dist/chunk-THBQG64D.cjs.map +0 -1
  232. package/dist/chunk-TQG7G7YI.cjs +0 -526
  233. package/dist/chunk-TQG7G7YI.cjs.map +0 -1
  234. package/dist/chunk-U3VVLYXG.cjs +0 -189
  235. package/dist/chunk-U3VVLYXG.cjs.map +0 -1
  236. package/dist/chunk-UUDTPZX6.js +0 -193
  237. package/dist/chunk-UUDTPZX6.js.map +0 -1
  238. package/dist/chunk-V5AWATUP.js +0 -1059
  239. package/dist/chunk-V5AWATUP.js.map +0 -1
  240. package/dist/chunk-VAXLFZCV.cjs +0 -110
  241. package/dist/chunk-VAXLFZCV.cjs.map +0 -1
  242. package/dist/chunk-VKREAIBA.cjs +0 -1139
  243. package/dist/chunk-VKREAIBA.cjs.map +0 -1
  244. package/dist/chunk-WDTTHKDS.js +0 -458
  245. package/dist/chunk-WDTTHKDS.js.map +0 -1
  246. package/dist/chunk-WXVB364T.js +0 -218
  247. package/dist/chunk-WXVB364T.js.map +0 -1
  248. package/dist/chunk-X4BPPD6K.js +0 -181
  249. package/dist/chunk-X4BPPD6K.js.map +0 -1
  250. package/dist/chunk-XEB7PH2E.js +0 -81
  251. package/dist/chunk-XEB7PH2E.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
+ 'use strict';var chunkMIOMMB23_cjs=require('./chunk-MIOMMB23.cjs'),drizzleOrm=require('drizzle-orm'),O=require('bcryptjs'),crypto$1=require('crypto');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var O__default=/*#__PURE__*/_interopDefault(O);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(drizzleOrm.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(drizzleOrm.sql`ALTER TABLE "users" ADD COLUMN IF NOT EXISTS "avatar" VARCHAR(255)`),await this.db.execute(drizzleOrm.sql`CREATE UNIQUE INDEX IF NOT EXISTS "users_email_idx" ON "users" ("email")`),await this.db.execute(drizzleOrm.sql`CREATE INDEX IF NOT EXISTS "users_tenant_idx" ON "users" ("tenant_id")`),await this.db.execute(drizzleOrm.sql`CREATE INDEX IF NOT EXISTS "users_role_idx" ON "users" ("role")`),await this.db.execute(drizzleOrm.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(drizzleOrm.sql`CREATE INDEX IF NOT EXISTS "sessions_user_idx" ON "sessions" ("user_id")`),await this.db.execute(drizzleOrm.sql`CREATE INDEX IF NOT EXISTS "sessions_token_idx" ON "sessions" ("token")`),await this.db.execute(drizzleOrm.sql`CREATE INDEX IF NOT EXISTS "sessions_expires_idx" ON "sessions" ("expires_at")`),await this.db.execute(drizzleOrm.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(drizzleOrm.sql`ALTER TABLE "audit_logs" ALTER COLUMN "resource_id" TYPE VARCHAR(255)`),await this.db.execute(drizzleOrm.sql`CREATE INDEX IF NOT EXISTS "audit_logs_user_idx" ON "audit_logs" ("user_id")`),await this.db.execute(drizzleOrm.sql`CREATE INDEX IF NOT EXISTS "audit_logs_action_idx" ON "audit_logs" ("action")`),await this.db.execute(drizzleOrm.sql`CREATE INDEX IF NOT EXISTS "audit_logs_resource_idx" ON "audit_logs" ("resource")`),await this.db.execute(drizzleOrm.sql`CREATE INDEX IF NOT EXISTS "audit_logs_timestamp_idx" ON "audit_logs" ("timestamp")`),await this.db.execute(drizzleOrm.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(drizzleOrm.sql`CREATE INDEX IF NOT EXISTS "password_history_user_idx" ON "password_history" ("user_id")`),await this.db.execute(drizzleOrm.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(drizzleOrm.sql`CREATE INDEX IF NOT EXISTS "lockouts_user_idx" ON "lockouts" ("user_id")`),await this.db.execute(drizzleOrm.sql`CREATE INDEX IF NOT EXISTS "lockouts_locked_until_idx" ON "lockouts" ("locked_until")`),await this.db.execute(drizzleOrm.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(drizzleOrm.sql`CREATE INDEX IF NOT EXISTS "roles_level_idx" ON "roles" ("level")`),await this.db.execute(drizzleOrm.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(drizzleOrm.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(drizzleOrm.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(drizzleOrm.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(chunkMIOMMB23_cjs.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(chunkMIOMMB23_cjs.a).where(drizzleOrm.eq(chunkMIOMMB23_cjs.a.email,e.toLowerCase())).limit(1);return s?this.userToAuthUser(s):null}async findUserById(e){let[s]=await this.db.select().from(chunkMIOMMB23_cjs.a).where(drizzleOrm.eq(chunkMIOMMB23_cjs.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(chunkMIOMMB23_cjs.a).set(t).where(drizzleOrm.eq(chunkMIOMMB23_cjs.a.id,e)).returning();return r?this.userToAuthUser(r):null}async deleteUser(e){return await this.db.delete(chunkMIOMMB23_cjs.a).where(drizzleOrm.eq(chunkMIOMMB23_cjs.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(chunkMIOMMB23_cjs.a).where(drizzleOrm.sql`${chunkMIOMMB23_cjs.a.email} ILIKE ${m}`).orderBy(drizzleOrm.desc(chunkMIOMMB23_cjs.a.createdAt)).limit(t).offset(r),this.db.select({count:drizzleOrm.sql`count(*)`}).from(chunkMIOMMB23_cjs.a).where(drizzleOrm.sql`${chunkMIOMMB23_cjs.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(chunkMIOMMB23_cjs.a).orderBy(drizzleOrm.desc(chunkMIOMMB23_cjs.a.createdAt)).limit(t).offset(r),this.db.select({count:drizzleOrm.sql`count(*)`}).from(chunkMIOMMB23_cjs.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(chunkMIOMMB23_cjs.a).where(drizzleOrm.eq(chunkMIOMMB23_cjs.a.email,e.toLowerCase())).limit(1);return r?.passwordHash&&await O__default.default.compare(s,r.passwordHash)?t:null}async hashPassword(e){return O__default.default.hash(e,12)}async createSession(e,s){let t=crypto$1.randomBytes(32).toString("base64url"),r=crypto$1.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(chunkMIOMMB23_cjs.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(chunkMIOMMB23_cjs.d).where(drizzleOrm.and(drizzleOrm.eq(chunkMIOMMB23_cjs.d.token,e),drizzleOrm.gt(chunkMIOMMB23_cjs.d.expiresAt,new Date))).limit(1);return s?this.sessionToSession(s):null}async findSessionByRefreshToken(e){let[s]=await this.db.select().from(chunkMIOMMB23_cjs.d).where(drizzleOrm.and(drizzleOrm.eq(chunkMIOMMB23_cjs.d.refreshToken,e),drizzleOrm.gt(chunkMIOMMB23_cjs.d.expiresAt,new Date))).limit(1);return s?this.sessionToSession(s):null}async deleteSession(e){return await this.db.delete(chunkMIOMMB23_cjs.d).where(drizzleOrm.eq(chunkMIOMMB23_cjs.d.id,e)),true}async deleteUserSessions(e){return await this.db.delete(chunkMIOMMB23_cjs.d).where(drizzleOrm.eq(chunkMIOMMB23_cjs.d.userId,e)),1}async addPasswordToHistory(e,s){await this.db.insert(chunkMIOMMB23_cjs.j).values({userId:e,passwordHash:s});}async getPasswordHistory(e,s=5){return (await this.db.select({passwordHash:chunkMIOMMB23_cjs.j.passwordHash}).from(chunkMIOMMB23_cjs.j).where(drizzleOrm.eq(chunkMIOMMB23_cjs.j.userId,e)).orderBy(drizzleOrm.desc(chunkMIOMMB23_cjs.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(chunkMIOMMB23_cjs.k).where(drizzleOrm.and(drizzleOrm.eq(chunkMIOMMB23_cjs.k.userId,e),drizzleOrm.gt(chunkMIOMMB23_cjs.k.lockedUntil,new Date))).limit(1);return !!s}async getLockout(e){let[s]=await this.db.select().from(chunkMIOMMB23_cjs.k).where(drizzleOrm.and(drizzleOrm.eq(chunkMIOMMB23_cjs.k.userId,e),drizzleOrm.gt(chunkMIOMMB23_cjs.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(chunkMIOMMB23_cjs.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){let{limit:s=50,offset:t=0,userId:r,action:u,resource:l,resourceId:E,success:m,startDate:U,endDate:f}=e,c=[];r&&c.push(drizzleOrm.eq(chunkMIOMMB23_cjs.e.userId,r)),u&&(Array.isArray(u)?c.push(drizzleOrm.sql`${chunkMIOMMB23_cjs.e.action} = ANY(${u})`):c.push(drizzleOrm.eq(chunkMIOMMB23_cjs.e.action,u))),l&&c.push(drizzleOrm.eq(chunkMIOMMB23_cjs.e.resource,l)),E&&c.push(drizzleOrm.eq(chunkMIOMMB23_cjs.e.resourceId,E)),m!==void 0&&c.push(drizzleOrm.eq(chunkMIOMMB23_cjs.e.success,m)),U&&c.push(drizzleOrm.sql`${chunkMIOMMB23_cjs.e.timestamp} >= ${U}`),f&&c.push(drizzleOrm.sql`${chunkMIOMMB23_cjs.e.timestamp} <= ${f}`);let R=c.length>0?drizzleOrm.and(...c):void 0,_=await this.db.select({count:drizzleOrm.sql`count(*)`}).from(chunkMIOMMB23_cjs.e).where(R);return {logs:(await this.db.select().from(chunkMIOMMB23_cjs.e).where(R).orderBy(drizzleOrm.desc(chunkMIOMMB23_cjs.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){let s=crypto.randomUUID(),t=new Date;return await this.db.insert(chunkMIOMMB23_cjs.e).values({id:s,action:e.action,userId:e.userId??null,userEmail:e.userEmail??null,role:e.role??null,resource:e.resource,resourceId:e.resourceId??null,changes:e.changes??null,ipAddress:e.ipAddress??null,userAgent:e.userAgent??null,success:e.success,error:e.error??null,metadata:e.metadata??null,timestamp:t}),{...e,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=crypto$1.randomBytes(32).toString("hex"),t=new Date(Date.now()+1440*60*1e3);return await this.db.insert(chunkMIOMMB23_cjs.h).values({userId:e,token:s,expiresAt:t}),{token:s,expiresAt:t}}async verifyEmailToken(e){let[s]=await this.db.select().from(chunkMIOMMB23_cjs.h).where(drizzleOrm.eq(chunkMIOMMB23_cjs.h.token,e)).limit(1);return s?s.expiresAt<new Date?{success:false,error:"Verification token has expired"}:(await this.db.update(chunkMIOMMB23_cjs.a).set({emailVerified:true}).where(drizzleOrm.eq(chunkMIOMMB23_cjs.a.id,s.userId)),await this.db.delete(chunkMIOMMB23_cjs.h).where(drizzleOrm.eq(chunkMIOMMB23_cjs.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=crypto$1.randomBytes(32).toString("hex"),r=new Date(Date.now()+3600*1e3);return await this.db.insert(chunkMIOMMB23_cjs.i).values({userId:s.id,token:t,expiresAt:r}),{token:t,expiresAt:r}}async resetPasswordWithToken(e,s){let[t]=await this.db.select().from(chunkMIOMMB23_cjs.i).where(drizzleOrm.eq(chunkMIOMMB23_cjs.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(chunkMIOMMB23_cjs.a).set({passwordHash:r,updatedAt:new Date}).where(drizzleOrm.eq(chunkMIOMMB23_cjs.a.id,t.userId)),await this.db.update(chunkMIOMMB23_cjs.i).set({usedAt:new Date}).where(drizzleOrm.eq(chunkMIOMMB23_cjs.i.id,t.id)),await this.db.delete(chunkMIOMMB23_cjs.d).where(drizzleOrm.eq(chunkMIOMMB23_cjs.d.userId,t.userId)),{success:true}}};exports.a=S;
@@ -0,0 +1 @@
1
+ import {timingSafeEqual}from'crypto';async function u(e,r){return typeof e=="boolean"?e:typeof e=="function"?await e(r):true}function A(...e){let r={};for(let t of e)t&&typeof t=="object"&&Object.assign(r,t);return r}function g(e,r){return u(e,r).then(t=>{if(t!==true)return t===false?{_id:{$eq:null}}:t})}var c="api_keys";function f(e){return e.substring(0,8)}function p(e,r){if(e.length!==r.length)return false;try{return timingSafeEqual(Buffer.from(e),Buffer.from(r))}catch{return false}}async function x(e,r,t){if(!e||typeof e!="string")return {valid:false,error:"No API key provided"};if(!e.startsWith("kyro_"))return {valid:false,error:"Invalid API key format"};let a=f(e);try{let s=await r.find({collection:c,where:{keyPrefix:{equals:a}},limit:100,page:1});if(!s.docs||s.docs.length===0)return {valid:!1,error:"Invalid API key"};let n=null;for(let i of s.docs){let l=i;if(p(l.key,e)){n=l;break}}if(!n)return {valid:!1,error:"Invalid API key"};if(n.expiresAt&&new Date(n.expiresAt)<new Date)return {valid:!1,error:"API key has expired"};try{await r.update({collection:c,id:n.id,data:{lastUsedAt:new Date().toISOString()}});}catch{}let o={id:n.userId,role:n.role||"author",tenantId:n.tenantId};if(t){let i=await t(n.userId);i&&Object.assign(o,i);}return {valid:!0,userId:n.userId,user:o,permissions:n.permissions||[],apiKeyId:n.id,tenantId:o.tenantId,role:o.role}}catch(s){return console.error("[ApiKey] Validation error:",s),{valid:false,error:"Failed to validate API key"}}}function I(e){let r=e.headers.get("Authorization");if(r){if(r.startsWith("ApiKey "))return r.slice(7).trim();if(r.startsWith("Bearer "))return null}let t=e.headers.get("X-API-Key");return t?t.trim():null}function m(e){return !e.valid||!e.userId?null:{userId:e.userId,user:e.user||{},permissions:e.permissions||[],apiKeyId:e.apiKeyId||"",tenantId:e.tenantId,role:e.role}}function C(e,r){if(e.length===0)return false;if(e.includes("*")||e.includes(r))return true;let[t,a]=r.split(":");return !!e.includes(`${t}:*`)}function P(){let e="abcdefghijklmnopqrstuvwxyz0123456789",r="";for(let t=0;t<32;t++)r+=e[Math.floor(Math.random()*e.length)];return `kyro_${r}`}function K(e){return e.substring(0,8)}export{u as a,A as b,g as c,c as d,x as e,I as f,m as g,C as h,P as i,K as j};
@@ -0,0 +1 @@
1
+ 'use strict';function t(e){return {ipAddress:e.headers.get("x-forwarded-for")?.split(",")[0]?.trim()||e.headers.get("x-real-ip")||"unknown",userAgent:e.headers.get("user-agent")||"unknown"}}exports.a=t;
@@ -0,0 +1 @@
1
+ 'use strict';var chunkNY47CFVP_cjs=require('./chunk-NY47CFVP.cjs'),chunkQ3Q7BJVQ_cjs=require('./chunk-Q3Q7BJVQ.cjs'),crypto=require('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=${crypto.createHmac("sha256",e).update(o).digest("hex")}`}function v(){return crypto.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:crypto.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()}_${crypto.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()}_${crypto.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,apiKey:i}=s,{enablePublicAccess:u=true,defaultAccess:c="none"}=r,g=o.access?.[e];if(g){let l=await chunkNY47CFVP_cjs.a(g,{req:n,user:t,tenantID:a});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 !chunkNY47CFVP_cjs.h(i.permissions,p)&&!chunkNY47CFVP_cjs.h(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=chunkQ3Q7BJVQ_cjs.a({id:t.id,email:t.email,role:t.role},p),x=chunkQ3Q7BJVQ_cjs.a({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}=s,{enablePublicAccess:i=true}=r,u=o.access?.[e];if(u)return await chunkNY47CFVP_cjs.a(u,{req:n,user:t,tenantID:a})===false?{allowed:false,error:"Access denied",status:403}:{allowed:true};if(t){let c=`globals:${e}`,g=chunkQ3Q7BJVQ_cjs.a({id:t.id,email:t.email,role:t.role},c),d=chunkQ3Q7BJVQ_cjs.a({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}}exports.a=Q;exports.b=Z;exports.c=O;exports.d=I;exports.e=h;exports.f=b;exports.g=R;exports.h=v;exports.i=A;exports.j=E;exports.k=D;exports.l=L;exports.m=f;exports.n=B;
@@ -0,0 +1 @@
1
+ import {pgTable,timestamp,text,varchar}from'drizzle-orm/pg-core';var r=pgTable("settings",{key:varchar("key",{length:255}).primaryKey(),value:text("value").notNull(),description:text("description"),updatedAt:timestamp("updated_at").defaultNow()});export{r as a};
@@ -0,0 +1 @@
1
+ var d=[{name:"super_admin",level:100,inherits:[],description:"Full system access across all tenants"},{name:"admin",level:90,inherits:["editor"],description:"Full tenant access with all content permissions"},{name:"editor",level:70,inherits:["author"],description:"Edit and publish all content"},{name:"author",level:50,inherits:["customer"],description:"Create and edit own content"},{name:"customer",level:30,inherits:[],description:"Access own data and make purchases"},{name:"guest",level:10,inherits:[],description:"Public read-only access"}];var c={super_admin:["*"],admin:["users:admin","users:read","users:update","audit_logs:read","posts:admin","posts:read","posts:create","posts:update","posts:delete","pages:admin","pages:read","pages:create","pages:update","pages:delete","media:admin","media:read","media:create","media:update","media:delete","categories:admin","categories:read","categories:create","categories:update","categories:delete","products:admin","products:read","products:create","products:update","products:delete","orders:admin","orders:read","orders:update","customers:admin","customers:read","customers:update","coupons:admin","coupons:read","coupons:create","coupons:update","coupons:delete","navigation:admin","navigation:read","navigation:create","navigation:update","navigation:delete","settings:admin","settings:read","settings:update","profile:admin","profile:read","profile:update"],editor:["posts:admin","posts:read","posts:create","posts:update","posts:delete","pages:admin","pages:read","pages:create","pages:update","pages:delete","media:read","media:create","media:update","categories:read","categories:create","categories:update","products:read","orders:read","orders:update","navigation:read","navigation:create","navigation:update","profile:read","profile:update"],author:["posts:read","posts:create","posts:update","media:read","media:create","categories:read","profile:read","profile:update"],customer:["profile:read","profile:update","orders:read","orders:create"],guest:["posts:read","pages:read","products:read"]};function u(e,s=d){let t=[e],r=new Map(s.map(o=>[o.name,o])),n=o=>{let i=r.get(o);if(i&&i.inherits)for(let a of i.inherits)t.includes(a)||(t.push(a),n(a));};return n(e),t}function m(e,s,t=c){if(!e||!e.role)return false;let r=l(e,t);if(r.includes("*")||r.includes(s))return true;let[n,o]=s.split(":");return !!(r.includes(`${n}:*`)||r.includes(`${n}:admin`))}function f(e,s){if(!e||!e.role)return false;let t=u(e.role);return s.some(r=>t.includes(r))}function l(e,s=c){if(!e||!e.role)return [];let t=u(e.role),r=new Set;for(let n of t){let o=s[n];if(o)for(let i of o)r.add(i);}return Array.from(r)}export{m as a,f as b};
@@ -0,0 +1,20 @@
1
+ 'use strict';var s=require('path'),d=require('fs');var _documentCurrentScript=typeof document!=='undefined'?document.currentScript:null;function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var s__default=/*#__PURE__*/_interopDefault(s);var d__default=/*#__PURE__*/_interopDefault(d);var S=s__default.default.resolve(new URL(".",(typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('chunk-L6CZYN3L.cjs', document.baseURI).href))).pathname,"api-handler.js"),b=s__default.default.resolve(new URL(".",(typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('chunk-L6CZYN3L.cjs', document.baseURI).href))).pathname,"api-handler-graphql.js"),g=s__default.default.resolve(new URL(".",(typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('chunk-L6CZYN3L.cjs', document.baseURI).href))).pathname,"api-handler-trpc.js");function y(m={}){let{configPath:a="./kyro.config.ts",apiPath:e="/api",adminPath:r="/admin",admin:_=true,enableGraphQL:i=false,enableTRPC:l=false,enableWebSocket:p=false}=m;return {name:"@kyro-cms/core",hooks:{"astro:config:setup":async({config:h,updateConfig:f,injectRoute:o,logger:n})=>{if(n.info(`Setting up Kyro CMS (API: ${e}, Admin: ${r})`),e===r)throw new Error(`Kyro CMS: apiPath and adminPath cannot be the same ("${e}")`);let c=s__default.default.resolve(h.root.pathname,a),u=c;d__default.default.existsSync(c)||n.warn(`Kyro config file not found at ${a}. The API will fail to boot if collections are needed.`),f({vite:{ssr:{external:["better-sqlite3","pg","mongodb","ioredis","sharp","ssh2","cpu-features","ssh2-sftp-client","nodemailer","jsonwebtoken","@mapbox/node-pre-gyp","mock-aws-s3","aws-sdk","nock"]},build:{rollupOptions:{external:["better-sqlite3","pg","mongodb","ioredis","sharp","ssh2","cpu-features","ssh2-sftp-client","nodemailer","jsonwebtoken","@mapbox/node-pre-gyp","mock-aws-s3","aws-sdk","nock"]}},optimizeDeps:{exclude:["better-sqlite3","pg","mongodb","ioredis","sharp","ssh2","cpu-features","ssh2-sftp-client","nodemailer","jsonwebtoken","@mapbox/node-pre-gyp","mock-aws-s3","aws-sdk","nock"]},plugins:[{name:"use-sync-external-store-shim-fix",enforce:"pre",resolveId(t){if(t==="use-sync-external-store/shim"||t==="use-sync-external-store/shim/index.js")return "\0virtual:use-sync-external-store-shim";if(t==="use-sync-external-store/shim/with-selector"||t==="use-sync-external-store/shim/with-selector.js")return "\0virtual:use-sync-external-store-shim-with-selector"},load(t){if(t==="\0virtual:use-sync-external-store-shim")return 'export { useSyncExternalStore } from "react";';if(t==="\0virtual:use-sync-external-store-shim-with-selector")return `
2
+ import { useSyncExternalStore, useMemo } from "react";
3
+ export function useSyncExternalStoreWithSelector(subscribe, getSnapshot, getServerSnapshot, selector, isEqual) {
4
+ const memoizedSelector = useMemo(() => {
5
+ let last, lastSnap, hasMemo = false;
6
+ return (snap) => {
7
+ if (!hasMemo || !Object.is(lastSnap, snap)) {
8
+ const next = selector(snap);
9
+ if (!hasMemo || !(isEqual ? isEqual(last, next) : Object.is(last, next))) {
10
+ last = next; lastSnap = snap; hasMemo = true;
11
+ }
12
+ }
13
+ return last;
14
+ };
15
+ }, [selector, isEqual]);
16
+ const getSelection = () => memoizedSelector(getSnapshot());
17
+ const getServerSelection = getServerSnapshot != null ? () => memoizedSelector(getServerSnapshot()) : undefined;
18
+ return useSyncExternalStore(subscribe, getSelection, getServerSelection);
19
+ }
20
+ `}}],resolve:{alias:{"kyro:config":u}},define:{__KYRO_API_PATH__:JSON.stringify(e),__KYRO_ADMIN_PATH__:JSON.stringify(r),__KYRO_ENABLE_GRAPHQL__:JSON.stringify(i),__KYRO_ENABLE_TRPC__:JSON.stringify(l),__KYRO_ENABLE_WS__:JSON.stringify(p)}}}),o({pattern:`${e}/[...path]`,entrypoint:S}),i&&(o({pattern:`${e}/graphql`,entrypoint:b}),n.info(`GraphQL endpoint enabled at ${e}/graphql`)),l&&(o({pattern:`${e}/trpc/[...path]`,entrypoint:g}),n.info(`tRPC endpoint enabled at ${e}/trpc`)),p&&n.info("WebSocket support enabled (auto-starts at first request)");}}}}exports.a=y;
@@ -0,0 +1,20 @@
1
+ import s from'path';import d from'fs';var S=s.resolve(new URL(".",import.meta.url).pathname,"api-handler.js"),b=s.resolve(new URL(".",import.meta.url).pathname,"api-handler-graphql.js"),g=s.resolve(new URL(".",import.meta.url).pathname,"api-handler-trpc.js");function y(m={}){let{configPath:a="./kyro.config.ts",apiPath:e="/api",adminPath:r="/admin",admin:_=true,enableGraphQL:i=false,enableTRPC:l=false,enableWebSocket:p=false}=m;return {name:"@kyro-cms/core",hooks:{"astro:config:setup":async({config:h,updateConfig:f,injectRoute:o,logger:n})=>{if(n.info(`Setting up Kyro CMS (API: ${e}, Admin: ${r})`),e===r)throw new Error(`Kyro CMS: apiPath and adminPath cannot be the same ("${e}")`);let c=s.resolve(h.root.pathname,a),u=c;d.existsSync(c)||n.warn(`Kyro config file not found at ${a}. The API will fail to boot if collections are needed.`),f({vite:{ssr:{external:["better-sqlite3","pg","mongodb","ioredis","sharp","ssh2","cpu-features","ssh2-sftp-client","nodemailer","jsonwebtoken","@mapbox/node-pre-gyp","mock-aws-s3","aws-sdk","nock"]},build:{rollupOptions:{external:["better-sqlite3","pg","mongodb","ioredis","sharp","ssh2","cpu-features","ssh2-sftp-client","nodemailer","jsonwebtoken","@mapbox/node-pre-gyp","mock-aws-s3","aws-sdk","nock"]}},optimizeDeps:{exclude:["better-sqlite3","pg","mongodb","ioredis","sharp","ssh2","cpu-features","ssh2-sftp-client","nodemailer","jsonwebtoken","@mapbox/node-pre-gyp","mock-aws-s3","aws-sdk","nock"]},plugins:[{name:"use-sync-external-store-shim-fix",enforce:"pre",resolveId(t){if(t==="use-sync-external-store/shim"||t==="use-sync-external-store/shim/index.js")return "\0virtual:use-sync-external-store-shim";if(t==="use-sync-external-store/shim/with-selector"||t==="use-sync-external-store/shim/with-selector.js")return "\0virtual:use-sync-external-store-shim-with-selector"},load(t){if(t==="\0virtual:use-sync-external-store-shim")return 'export { useSyncExternalStore } from "react";';if(t==="\0virtual:use-sync-external-store-shim-with-selector")return `
2
+ import { useSyncExternalStore, useMemo } from "react";
3
+ export function useSyncExternalStoreWithSelector(subscribe, getSnapshot, getServerSnapshot, selector, isEqual) {
4
+ const memoizedSelector = useMemo(() => {
5
+ let last, lastSnap, hasMemo = false;
6
+ return (snap) => {
7
+ if (!hasMemo || !Object.is(lastSnap, snap)) {
8
+ const next = selector(snap);
9
+ if (!hasMemo || !(isEqual ? isEqual(last, next) : Object.is(last, next))) {
10
+ last = next; lastSnap = snap; hasMemo = true;
11
+ }
12
+ }
13
+ return last;
14
+ };
15
+ }, [selector, isEqual]);
16
+ const getSelection = () => memoizedSelector(getSnapshot());
17
+ const getServerSelection = getServerSnapshot != null ? () => memoizedSelector(getServerSnapshot()) : undefined;
18
+ return useSyncExternalStore(subscribe, getSelection, getServerSelection);
19
+ }
20
+ `}}],resolve:{alias:{"kyro:config":u}},define:{__KYRO_API_PATH__:JSON.stringify(e),__KYRO_ADMIN_PATH__:JSON.stringify(r),__KYRO_ENABLE_GRAPHQL__:JSON.stringify(i),__KYRO_ENABLE_TRPC__:JSON.stringify(l),__KYRO_ENABLE_WS__:JSON.stringify(p)}}}),o({pattern:`${e}/[...path]`,entrypoint:S}),i&&(o({pattern:`${e}/graphql`,entrypoint:b}),n.info(`GraphQL endpoint enabled at ${e}/graphql`)),l&&(o({pattern:`${e}/trpc/[...path]`,entrypoint:g}),n.info(`tRPC endpoint enabled at ${e}/trpc`)),p&&n.info("WebSocket support enabled (auto-starts at first request)");}}}}export{y as a};
@@ -0,0 +1 @@
1
+ 'use strict';var pgCore=require('drizzle-orm/pg-core');var d=pgCore.pgTable("users",{id:pgCore.uuid("id").primaryKey().defaultRandom(),name:pgCore.varchar("name",{length:255}),email:pgCore.varchar("email",{length:255}).notNull(),passwordHash:pgCore.varchar("password_hash",{length:255}),role:pgCore.varchar("role",{length:50}).notNull().default("customer"),tenantId:pgCore.uuid("tenant_id"),emailVerified:pgCore.boolean("email_verified").default(false),avatar:pgCore.varchar("avatar",{length:255}),locked:pgCore.boolean("locked").default(false),lastLogin:pgCore.timestamp("last_login"),failedLoginAttempts:pgCore.integer("failed_login_attempts").default(0),metadata:pgCore.jsonb("metadata").$type(),createdAt:pgCore.timestamp("created_at").defaultNow().notNull(),updatedAt:pgCore.timestamp("updated_at").defaultNow().notNull()},e=>[pgCore.uniqueIndex("users_email_idx").on(e.email),pgCore.index("users_tenant_idx").on(e.tenantId),pgCore.index("users_role_idx").on(e.role)]),c=pgCore.pgTable("roles",{id:pgCore.uuid("id").primaryKey().defaultRandom(),name:pgCore.varchar("name",{length:100}).notNull().unique(),level:pgCore.integer("level").notNull().default(0),inherits:pgCore.text("inherits").array(),description:pgCore.text("description"),permissions:pgCore.jsonb("permissions").$type().default([]),isSystem:pgCore.boolean("is_system").default(false),createdAt:pgCore.timestamp("created_at").defaultNow().notNull(),updatedAt:pgCore.timestamp("updated_at").defaultNow().notNull()},e=>[pgCore.index("roles_level_idx").on(e.level)]),f=pgCore.pgTable("permissions",{id:pgCore.uuid("id").primaryKey().defaultRandom(),roleId:pgCore.uuid("role_id").references(()=>c.id,{onDelete:"cascade"}),resource:pgCore.varchar("resource",{length:100}).notNull(),action:pgCore.varchar("action",{length:50}).notNull(),conditions:pgCore.jsonb("conditions").$type(),createdAt:pgCore.timestamp("created_at").defaultNow().notNull()},e=>[pgCore.index("permissions_role_idx").on(e.roleId),pgCore.index("permissions_resource_idx").on(e.resource)]),y=pgCore.pgTable("sessions",{id:pgCore.uuid("id").primaryKey().defaultRandom(),userId:pgCore.uuid("user_id").notNull().references(()=>d.id,{onDelete:"cascade"}),token:pgCore.varchar("token",{length:512}).notNull().unique(),refreshToken:pgCore.varchar("refresh_token",{length:512}),ipAddress:pgCore.varchar("ip_address",{length:45}),userAgent:pgCore.text("user_agent"),expiresAt:pgCore.timestamp("expires_at").notNull(),createdAt:pgCore.timestamp("created_at").defaultNow().notNull()},e=>[pgCore.index("sessions_user_idx").on(e.userId),pgCore.index("sessions_token_idx").on(e.token),pgCore.index("sessions_expires_idx").on(e.expiresAt)]),m=pgCore.pgTable("audit_logs",{id:pgCore.uuid("id").primaryKey().defaultRandom(),action:pgCore.varchar("action",{length:100}).notNull(),userId:pgCore.uuid("user_id").references(()=>d.id,{onDelete:"set null"}),userEmail:pgCore.varchar("user_email",{length:255}),role:pgCore.varchar("role",{length:50}),resource:pgCore.varchar("resource",{length:100}).notNull(),resourceId:pgCore.varchar("resource_id",{length:255}),changes:pgCore.jsonb("changes").$type(),ipAddress:pgCore.varchar("ip_address",{length:45}),userAgent:pgCore.text("user_agent"),success:pgCore.boolean("success").notNull().default(true),error:pgCore.text("error"),metadata:pgCore.jsonb("metadata").$type(),timestamp:pgCore.timestamp("timestamp").defaultNow().notNull()},e=>[pgCore.index("audit_logs_user_idx").on(e.userId),pgCore.index("audit_logs_action_idx").on(e.action),pgCore.index("audit_logs_resource_idx").on(e.resource),pgCore.index("audit_logs_timestamp_idx").on(e.timestamp)]),x=pgCore.pgTable("tenants",{id:pgCore.uuid("id").primaryKey().defaultRandom(),name:pgCore.varchar("name",{length:255}).notNull(),slug:pgCore.varchar("slug",{length:100}).notNull().unique(),settings:pgCore.jsonb("settings").$type().default({}),isActive:pgCore.boolean("is_active").default(true),createdAt:pgCore.timestamp("created_at").defaultNow().notNull(),updatedAt:pgCore.timestamp("updated_at").defaultNow().notNull()},e=>[pgCore.uniqueIndex("tenants_slug_idx").on(e.slug)]),g=pgCore.pgTable("api_keys",{id:pgCore.uuid("id").primaryKey().defaultRandom(),userId:pgCore.uuid("user_id").notNull().references(()=>d.id,{onDelete:"cascade"}),name:pgCore.varchar("name",{length:255}).notNull(),key:pgCore.varchar("key",{length:64}).notNull().unique(),keyPrefix:pgCore.varchar("key_prefix",{length:8}).notNull(),permissions:pgCore.jsonb("permissions").$type().default([]),lastUsedAt:pgCore.timestamp("last_used_at"),expiresAt:pgCore.timestamp("expires_at"),createdAt:pgCore.timestamp("created_at").defaultNow().notNull()},e=>[pgCore.index("api_keys_user_idx").on(e.userId),pgCore.index("api_keys_key_idx").on(e.key)]),N=pgCore.pgTable("email_verifications",{id:pgCore.uuid("id").primaryKey().defaultRandom(),userId:pgCore.uuid("user_id").notNull().references(()=>d.id,{onDelete:"cascade"}),token:pgCore.varchar("token",{length:64}).notNull().unique(),expiresAt:pgCore.timestamp("expires_at").notNull(),createdAt:pgCore.timestamp("created_at").defaultNow().notNull()},e=>[pgCore.index("email_verifications_token_idx").on(e.token),pgCore.index("email_verifications_user_idx").on(e.userId)]),h=pgCore.pgTable("password_resets",{id:pgCore.uuid("id").primaryKey().defaultRandom(),userId:pgCore.uuid("user_id").notNull().references(()=>d.id,{onDelete:"cascade"}),token:pgCore.varchar("token",{length:64}).notNull().unique(),expiresAt:pgCore.timestamp("expires_at").notNull(),usedAt:pgCore.timestamp("used_at"),createdAt:pgCore.timestamp("created_at").defaultNow().notNull()},e=>[pgCore.index("password_resets_token_idx").on(e.token),pgCore.index("password_resets_user_idx").on(e.userId)]),A=pgCore.pgTable("password_history",{id:pgCore.uuid("id").primaryKey().defaultRandom(),userId:pgCore.uuid("user_id").notNull().references(()=>d.id,{onDelete:"cascade"}),passwordHash:pgCore.varchar("password_hash",{length:255}).notNull(),createdAt:pgCore.timestamp("created_at").defaultNow().notNull()},e=>[pgCore.index("password_history_user_idx").on(e.userId)]),k=pgCore.pgTable("lockouts",{id:pgCore.uuid("id").primaryKey().defaultRandom(),userId:pgCore.uuid("user_id").notNull().references(()=>d.id,{onDelete:"cascade"}),ipAddress:pgCore.varchar("ip_address",{length:45}),reason:pgCore.varchar("reason",{length:255}),lockedUntil:pgCore.timestamp("locked_until").notNull(),releasedAt:pgCore.timestamp("released_at"),createdAt:pgCore.timestamp("created_at").defaultNow().notNull()},e=>[pgCore.index("lockouts_user_idx").on(e.userId),pgCore.index("lockouts_ip_idx").on(e.ipAddress),pgCore.index("lockouts_locked_until_idx").on(e.lockedUntil)]);exports.a=d;exports.b=c;exports.c=f;exports.d=y;exports.e=m;exports.f=x;exports.g=g;exports.h=N;exports.i=h;exports.j=A;exports.k=k;
@@ -0,0 +1 @@
1
+ import {q,r}from'./chunk-POWTSLKC.js';import {d}from'./chunk-FO3HLBC7.js';import {a as a$1}from'./chunk-2W4FK6CJ.js';import {c}from'./chunk-VKXQUYYV.js';import {a}from'./chunk-RHCWCG3O.js';import {a as a$2}from'./chunk-G6A7OSIG.js';import {a as a$3}from'./chunk-P7CESLDJ.js';import A from'kyro:config';var t=null,n=null;async function _(){if(!t)try{let e=A.default||A;t=q(e),await t.init(),await t.loadSettings();let o=t.db,r$1;if(o instanceof c){if(o.dialect==="postgres")r$1=new a({db:o.client});else if(o.dialect==="sqlite"){let i=process.env.KYRO_AUTH_DB_PATH||"./data/auth.db";r$1=new a$1({path:i});}}else if(o instanceof r){let i=process.env.KYRO_AUTH_DB_PATH||"./data/auth.db";r$1=new a$1({path:i});}else o instanceof a$2&&(r$1=new a$3({db:o.db}));r$1?.connect&&await r$1.connect(),(await d(r$1))?.success,typeof t.startWebSocket=="function"&&t.startWebSocket().catch(i=>{console.error("[Kyro] WebSocket auto-start failed:",i);}),globalThis.__KYRO_INSTANCE__=t;}catch(e){throw t=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(!t){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 t.getGraphQL=="function"){let a=await t.getGraphQL().fetch(e.request,e.locals);return new Response(a.body,a)}if(r.startsWith(`${s}/trpc/`)&&typeof t.getTRPC=="function"){let a=await t.getTRPC().fetch(e.request,e.locals);return new Response(a.body,a)}return t.getREST().fetch(e.request,e.locals)};export{t as a,v as b,D as c};
@@ -0,0 +1,90 @@
1
+ import {generateHTML}from'@tiptap/html';import d from'@tiptap/starter-kit';import s from'@tiptap/extension-link';import p from'@tiptap/extension-image';import c from'@tiptap/extension-text-align';import x from'@tiptap/extension-underline';import u from'@tiptap/extension-highlight';import m from'@tiptap/extension-task-list';import g from'@tiptap/extension-task-item';import {TextStyle}from'@tiptap/extension-text-style';import y from'@tiptap/extension-color';function b(e){return e.type==="text"}function h(e){return e.type==="number"}function k(e){return e.type==="relationship"}function R(e){return e.type==="array"}function B(e){return e.type==="group"}function T(e){return e.type==="blocks"}function w(e){return e.type==="upload"}function L(e){return e.type==="image"}function I(e){return e.type==="richtext"}function V(e){return e.type==="select"}function A(e){return e.type==="row"||e.type==="collapsible"||e.type==="tabs"}var r=["text","number","checkbox","date","email","password","textarea","select","radio","color"],n=["richtext","json","code","upload","image","markdown"],o=["relationship","array","group","blocks"],a=["row","collapsible","tabs"],C=[...r,...n,...o,...a];function S(e,t,i){return {name:e,type:"relationship",relationTo:t,...i,required:i?.required??false}}var Y=`
2
+ .kyro-richtext {
3
+ color: inherit;
4
+ line-height: 1.7;
5
+ }
6
+
7
+ .kyro-richtext > *:first-child {
8
+ margin-top: 0;
9
+ }
10
+
11
+ .kyro-richtext > *:last-child {
12
+ margin-bottom: 0;
13
+ }
14
+
15
+ .kyro-richtext p,
16
+ .kyro-richtext ul,
17
+ .kyro-richtext ol,
18
+ .kyro-richtext blockquote,
19
+ .kyro-richtext pre {
20
+ margin: 0 0 1rem;
21
+ }
22
+
23
+ .kyro-richtext h1,
24
+ .kyro-richtext h2,
25
+ .kyro-richtext h3,
26
+ .kyro-richtext h4,
27
+ .kyro-richtext h5,
28
+ .kyro-richtext h6 {
29
+ margin: 0 0 0.75rem;
30
+ line-height: 1.2;
31
+ }
32
+
33
+ .kyro-richtext ul,
34
+ .kyro-richtext ol {
35
+ padding-left: 1.5rem;
36
+ }
37
+
38
+ .kyro-richtext blockquote {
39
+ border-left: 4px solid rgba(148, 163, 184, 0.5);
40
+ margin-left: 0;
41
+ padding-left: 1rem;
42
+ font-style: italic;
43
+ }
44
+
45
+ .kyro-richtext pre {
46
+ overflow-x: auto;
47
+ border-radius: 0.75rem;
48
+ background: rgba(15, 23, 42, 0.92);
49
+ color: #f8fafc;
50
+ padding: 1rem;
51
+ }
52
+
53
+ .kyro-richtext code {
54
+ font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
55
+ }
56
+
57
+ .kyro-richtext img {
58
+ display: block;
59
+ max-width: 100%;
60
+ height: auto;
61
+ border-radius: 0.75rem;
62
+ }
63
+
64
+ .kyro-richtext ul[data-type="taskList"] {
65
+ list-style: none;
66
+ padding: 0;
67
+ }
68
+
69
+ .kyro-richtext li[data-type="taskItem"] {
70
+ display: flex;
71
+ align-items: flex-start;
72
+ gap: 0.5rem;
73
+ }
74
+
75
+ .kyro-richtext li[data-type="taskItem"] > label {
76
+ user-select: none;
77
+ pointer-events: none;
78
+ margin-top: 0.2rem;
79
+ }
80
+
81
+ .kyro-richtext li[data-type="taskItem"] > div {
82
+ flex: 1;
83
+ }
84
+
85
+ .kyro-richtext mark {
86
+ background-color: #fef08a;
87
+ border-radius: 0.25rem;
88
+ padding: 0.125rem 0.25rem;
89
+ }
90
+ `.trim(),f=[d,s.configure({openOnClick:false}),p,c.configure({types:["heading","paragraph"]}),x,u.configure({multicolor:true}),m,g.configure({nested:true}),TextStyle,y];function G(e){return typeof e=="object"&&e!==null?e:{}}function j(e){if(typeof e!="object"||e===null)return "";try{return `<div class="kyro-richtext">${generateHTML(e,f)}</div>`}catch(t){return console.error("Failed to render rich text:",t),""}}export{b as a,h as b,k as c,R as d,B as e,T as f,w as g,L as h,I as i,V as j,A as k,r as l,n as m,o as n,a as o,C as p,S as q,Y as r,G as s,j as t};
@@ -0,0 +1 @@
1
+ function t(e){return {ipAddress:e.headers.get("x-forwarded-for")?.split(",")[0]?.trim()||e.headers.get("x-real-ip")||"unknown",userAgent:e.headers.get("user-agent")||"unknown"}}export{t as a};
@@ -0,0 +1 @@
1
+ 'use strict';var crypto=require('crypto');async function u(e,r){return typeof e=="boolean"?e:typeof e=="function"?await e(r):true}function A(...e){let r={};for(let t of e)t&&typeof t=="object"&&Object.assign(r,t);return r}function g(e,r){return u(e,r).then(t=>{if(t!==true)return t===false?{_id:{$eq:null}}:t})}var c="api_keys";function f(e){return e.substring(0,8)}function p(e,r){if(e.length!==r.length)return false;try{return crypto.timingSafeEqual(Buffer.from(e),Buffer.from(r))}catch{return false}}async function x(e,r,t){if(!e||typeof e!="string")return {valid:false,error:"No API key provided"};if(!e.startsWith("kyro_"))return {valid:false,error:"Invalid API key format"};let a=f(e);try{let s=await r.find({collection:c,where:{keyPrefix:{equals:a}},limit:100,page:1});if(!s.docs||s.docs.length===0)return {valid:!1,error:"Invalid API key"};let n=null;for(let i of s.docs){let l=i;if(p(l.key,e)){n=l;break}}if(!n)return {valid:!1,error:"Invalid API key"};if(n.expiresAt&&new Date(n.expiresAt)<new Date)return {valid:!1,error:"API key has expired"};try{await r.update({collection:c,id:n.id,data:{lastUsedAt:new Date().toISOString()}});}catch{}let o={id:n.userId,role:n.role||"author",tenantId:n.tenantId};if(t){let i=await t(n.userId);i&&Object.assign(o,i);}return {valid:!0,userId:n.userId,user:o,permissions:n.permissions||[],apiKeyId:n.id,tenantId:o.tenantId,role:o.role}}catch(s){return console.error("[ApiKey] Validation error:",s),{valid:false,error:"Failed to validate API key"}}}function I(e){let r=e.headers.get("Authorization");if(r){if(r.startsWith("ApiKey "))return r.slice(7).trim();if(r.startsWith("Bearer "))return null}let t=e.headers.get("X-API-Key");return t?t.trim():null}function m(e){return !e.valid||!e.userId?null:{userId:e.userId,user:e.user||{},permissions:e.permissions||[],apiKeyId:e.apiKeyId||"",tenantId:e.tenantId,role:e.role}}function C(e,r){if(e.length===0)return false;if(e.includes("*")||e.includes(r))return true;let[t,a]=r.split(":");return !!e.includes(`${t}:*`)}function P(){let e="abcdefghijklmnopqrstuvwxyz0123456789",r="";for(let t=0;t<32;t++)r+=e[Math.floor(Math.random()*e.length)];return `kyro_${r}`}function K(e){return e.substring(0,8)}exports.a=u;exports.b=A;exports.c=g;exports.d=c;exports.e=x;exports.f=I;exports.g=m;exports.h=C;exports.i=P;exports.j=K;
@@ -0,0 +1,2 @@
1
+ var l=[{name:"uploadDir",type:"text",label:"Upload Directory",defaultValue:"./public/uploads"},{name:"baseUrl",type:"text",label:"Base URL",defaultValue:"/uploads"}],t=[{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"}}],r=[{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."}}],i=[{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"}}],o=[{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"}}],a=[{type:"local",displayName:"Local Server",configFields:l},{type:"aws",displayName:"S3 Compatible (AWS, Backblaze, Wasabi, etc.)",configFields:t},{type:"r2",displayName:"Cloudflare R2",configFields:r},{type:"cloudinary",displayName:"Cloudinary",configFields:i},{type:"ftp",displayName:"FTP",configFields:o}],d=a.map(e=>({label:e.displayName,value:e.type})),s=a.map(e=>({name:e.type,type:"group",label:`${e.displayName} Settings`,admin:{condition:{field:"provider",equals:e.type}},fields:e.configFields})),p={slug:"storage-settings",label:"Storage Settings",admin:{group:"settings"},access:{read:()=>true,update:()=>true},fields:[{name:"provider",type:"select",label:"Storage Provider",defaultValue:"local",options:d},...s,{name:"limits",type:"group",label:"Upload Limits",fields:[{name:"maxFileSize",type:"number",label:"Max File Size (bytes)",defaultValue:10485760},{name:"allowedTypes",type:"json",label:"Allowed MIME Types",defaultValue:["image/*","video/*","audio/*","application/pdf"]},{name:"maxFilesPerUpload",type:"number",label:"Max Files per Upload",defaultValue:10}]}]};
2
+ export{p as a};
@@ -0,0 +1 @@
1
+ import {pgTable,timestamp,jsonb,integer,boolean,varchar,uuid,uniqueIndex,index,text}from'drizzle-orm/pg-core';var d=pgTable("users",{id:uuid("id").primaryKey().defaultRandom(),name:varchar("name",{length:255}),email:varchar("email",{length:255}).notNull(),passwordHash:varchar("password_hash",{length:255}),role:varchar("role",{length:50}).notNull().default("customer"),tenantId:uuid("tenant_id"),emailVerified:boolean("email_verified").default(false),avatar:varchar("avatar",{length:255}),locked:boolean("locked").default(false),lastLogin:timestamp("last_login"),failedLoginAttempts:integer("failed_login_attempts").default(0),metadata:jsonb("metadata").$type(),createdAt:timestamp("created_at").defaultNow().notNull(),updatedAt:timestamp("updated_at").defaultNow().notNull()},e=>[uniqueIndex("users_email_idx").on(e.email),index("users_tenant_idx").on(e.tenantId),index("users_role_idx").on(e.role)]),c=pgTable("roles",{id:uuid("id").primaryKey().defaultRandom(),name:varchar("name",{length:100}).notNull().unique(),level:integer("level").notNull().default(0),inherits:text("inherits").array(),description:text("description"),permissions:jsonb("permissions").$type().default([]),isSystem:boolean("is_system").default(false),createdAt:timestamp("created_at").defaultNow().notNull(),updatedAt:timestamp("updated_at").defaultNow().notNull()},e=>[index("roles_level_idx").on(e.level)]),f=pgTable("permissions",{id:uuid("id").primaryKey().defaultRandom(),roleId:uuid("role_id").references(()=>c.id,{onDelete:"cascade"}),resource:varchar("resource",{length:100}).notNull(),action:varchar("action",{length:50}).notNull(),conditions:jsonb("conditions").$type(),createdAt:timestamp("created_at").defaultNow().notNull()},e=>[index("permissions_role_idx").on(e.roleId),index("permissions_resource_idx").on(e.resource)]),y=pgTable("sessions",{id:uuid("id").primaryKey().defaultRandom(),userId:uuid("user_id").notNull().references(()=>d.id,{onDelete:"cascade"}),token:varchar("token",{length:512}).notNull().unique(),refreshToken:varchar("refresh_token",{length:512}),ipAddress:varchar("ip_address",{length:45}),userAgent:text("user_agent"),expiresAt:timestamp("expires_at").notNull(),createdAt:timestamp("created_at").defaultNow().notNull()},e=>[index("sessions_user_idx").on(e.userId),index("sessions_token_idx").on(e.token),index("sessions_expires_idx").on(e.expiresAt)]),m=pgTable("audit_logs",{id:uuid("id").primaryKey().defaultRandom(),action:varchar("action",{length:100}).notNull(),userId:uuid("user_id").references(()=>d.id,{onDelete:"set null"}),userEmail:varchar("user_email",{length:255}),role:varchar("role",{length:50}),resource:varchar("resource",{length:100}).notNull(),resourceId:varchar("resource_id",{length:255}),changes:jsonb("changes").$type(),ipAddress:varchar("ip_address",{length:45}),userAgent:text("user_agent"),success:boolean("success").notNull().default(true),error:text("error"),metadata:jsonb("metadata").$type(),timestamp:timestamp("timestamp").defaultNow().notNull()},e=>[index("audit_logs_user_idx").on(e.userId),index("audit_logs_action_idx").on(e.action),index("audit_logs_resource_idx").on(e.resource),index("audit_logs_timestamp_idx").on(e.timestamp)]),x=pgTable("tenants",{id:uuid("id").primaryKey().defaultRandom(),name:varchar("name",{length:255}).notNull(),slug:varchar("slug",{length:100}).notNull().unique(),settings:jsonb("settings").$type().default({}),isActive:boolean("is_active").default(true),createdAt:timestamp("created_at").defaultNow().notNull(),updatedAt:timestamp("updated_at").defaultNow().notNull()},e=>[uniqueIndex("tenants_slug_idx").on(e.slug)]),g=pgTable("api_keys",{id:uuid("id").primaryKey().defaultRandom(),userId:uuid("user_id").notNull().references(()=>d.id,{onDelete:"cascade"}),name:varchar("name",{length:255}).notNull(),key:varchar("key",{length:64}).notNull().unique(),keyPrefix:varchar("key_prefix",{length:8}).notNull(),permissions:jsonb("permissions").$type().default([]),lastUsedAt:timestamp("last_used_at"),expiresAt:timestamp("expires_at"),createdAt:timestamp("created_at").defaultNow().notNull()},e=>[index("api_keys_user_idx").on(e.userId),index("api_keys_key_idx").on(e.key)]),N=pgTable("email_verifications",{id:uuid("id").primaryKey().defaultRandom(),userId:uuid("user_id").notNull().references(()=>d.id,{onDelete:"cascade"}),token:varchar("token",{length:64}).notNull().unique(),expiresAt:timestamp("expires_at").notNull(),createdAt:timestamp("created_at").defaultNow().notNull()},e=>[index("email_verifications_token_idx").on(e.token),index("email_verifications_user_idx").on(e.userId)]),h=pgTable("password_resets",{id:uuid("id").primaryKey().defaultRandom(),userId:uuid("user_id").notNull().references(()=>d.id,{onDelete:"cascade"}),token:varchar("token",{length:64}).notNull().unique(),expiresAt:timestamp("expires_at").notNull(),usedAt:timestamp("used_at"),createdAt:timestamp("created_at").defaultNow().notNull()},e=>[index("password_resets_token_idx").on(e.token),index("password_resets_user_idx").on(e.userId)]),A=pgTable("password_history",{id:uuid("id").primaryKey().defaultRandom(),userId:uuid("user_id").notNull().references(()=>d.id,{onDelete:"cascade"}),passwordHash:varchar("password_hash",{length:255}).notNull(),createdAt:timestamp("created_at").defaultNow().notNull()},e=>[index("password_history_user_idx").on(e.userId)]),k=pgTable("lockouts",{id:uuid("id").primaryKey().defaultRandom(),userId:uuid("user_id").notNull().references(()=>d.id,{onDelete:"cascade"}),ipAddress:varchar("ip_address",{length:45}),reason:varchar("reason",{length:255}),lockedUntil:timestamp("locked_until").notNull(),releasedAt:timestamp("released_at"),createdAt:timestamp("created_at").defaultNow().notNull()},e=>[index("lockouts_user_idx").on(e.userId),index("lockouts_ip_idx").on(e.ipAddress),index("lockouts_locked_until_idx").on(e.lockedUntil)]);export{d as a,c as b,f as c,y as d,m as e,x as f,g,N as h,h as i,A as j,k};
@@ -0,0 +1 @@
1
+ import h from'bcryptjs';import {randomUUID,randomBytes}from'crypto';var w=class{db;prefix;sessionTTL;refreshTokenTTL;indexesEnsured=false;constructor(e){this.db=e.db,this.prefix=e.collectionPrefix||"",this.sessionTTL=e.sessionTTL||86400,this.refreshTokenTTL=e.refreshTokenTTL||604800;}col(e){return this.db.collection(`${this.prefix}${e}`)}async connect(){this.indexesEnsured||await this.ensureIndexes();}async disconnect(){}async ensureIndexes(){await this.col("users").createIndex({email:1},{unique:true}),await this.col("users").createIndex({tenantId:1}),await this.col("users").createIndex({role:1}),await this.col("sessions").createIndex({token:1},{unique:true}),await this.col("sessions").createIndex({refreshToken:1}),await this.col("sessions").createIndex({userId:1}),await this.col("sessions").createIndex({expiresAt:1},{expireAfterSeconds:0}),await this.col("audit_logs").createIndex({timestamp:-1}),await this.col("audit_logs").createIndex({userId:1}),await this.col("audit_logs").createIndex({action:1}),await this.col("audit_logs").createIndex({resource:1}),await this.col("password_history").createIndex({userId:1,createdAt:-1}),await this.col("lockouts").createIndex({userId:1},{unique:true}),await this.col("lockouts").createIndex({lockedUntil:1}),this.indexesEnsured=true;}async createUser(e){let s=randomUUID(),t=new Date,i=await this.hashPassword(e.password),n={_id:s,name:e.name||null,email:e.email.toLowerCase(),passwordHash:i,role:e.role||"customer",avatar:e.avatar||null,tenantId:e.tenantId||null,emailVerified:false,locked:false,lastLogin:null,failedLoginAttempts:0,createdAt:t,updatedAt:t};return await this.col("users").insertOne(n),this.docToAuthUser(n)}async findUserByEmail(e){let s=await this.col("users").findOne({email:e.toLowerCase()});return s?this.docToAuthUser(s):null}async findUserById(e){let s=await this.col("users").findOne({_id:e});return s?this.docToAuthUser(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.avatar!==void 0&&(t.avatar=s.avatar),s.tenantId!==void 0&&(t.tenantId=s.tenantId),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 i=await this.col("users").findOneAndUpdate({_id:e},{$set:t},{returnDocument:"after"});return i?this.docToAuthUser(i):null}async deleteUser(e){return (await this.col("users").deleteOne({_id:e})).deletedCount>0}async verifyPassword(e,s){let t=await this.findUserByEmail(e);if(!t)return null;let i=await this.col("users").findOne({email:e.toLowerCase()},{projection:{passwordHash:1}});return i?.passwordHash&&await h.compare(s,i.passwordHash)?t:null}async hashPassword(e){return h.hash(e,12)}async createSession(e,s){let t=randomUUID(),i=randomBytes(32).toString("base64url"),n=randomBytes(32).toString("base64url"),a=new Date,u=new Date(a.getTime()+this.sessionTTL*1e3),d={_id:t,userId:e,token:i,refreshToken:n,ipAddress:s?.ipAddress||null,userAgent:s?.userAgent||null,expiresAt:u,createdAt:a};return await this.col("sessions").insertOne(d),this.docToSession(d)}async findSessionByToken(e){let s=await this.col("sessions").findOne({token:e,expiresAt:{$gt:new Date}});return s?this.docToSession(s):null}async findSessionByRefreshToken(e){let s=await this.col("sessions").findOne({refreshToken:e,expiresAt:{$gt:new Date}});return s?this.docToSession(s):null}async deleteSession(e){return (await this.col("sessions").deleteOne({_id:e})).deletedCount>0}async deleteUserSessions(e){return (await this.col("sessions").deleteMany({userId:e})).deletedCount}async hasAnyUsers(){return await this.col("users").countDocuments()>0}async addPasswordToHistory(e,s){await this.col("password_history").insertOne({userId:e,passwordHash:s,createdAt:new Date});}async getPasswordHistory(e,s=5){return (await this.col("password_history").find({userId:e}).sort({createdAt:-1}).limit(s).toArray()).map(i=>i.passwordHash)}async isPasswordInHistory(e,s,t=5){let i=await this.getPasswordHistory(s,t);for(let n of i)if(await h.compare(e,n))return true;return false}async findAuditLogs(e){let{limit:s=50,offset:t=0,userId:i,action:n,resource:a,resourceId:u,success:d,startDate:c,endDate:f}=e,o={};i&&(o.userId=i),n&&(Array.isArray(n)?o.action={$in:n}:o.action=n),a&&(o.resource=a),u&&(o.resourceId=u),d!==void 0&&(o.success=d),(c||f)&&(o.timestamp={},c&&(o.timestamp.$gte=c),f&&(o.timestamp.$lte=f));let g=await this.col("audit_logs").countDocuments(o);return {logs:(await this.col("audit_logs").find(o).sort({timestamp:-1}).skip(t).limit(s).toArray()).map(r=>({id:r._id,timestamp:r.timestamp,action:r.action,userId:r.userId||void 0,userEmail:r.userEmail||void 0,role:r.role||void 0,resource:r.resource,resourceId:r.resourceId||void 0,changes:r.changes||void 0,ipAddress:r.ipAddress||void 0,userAgent:r.userAgent||void 0,success:r.success,error:r.error||void 0,metadata:r.metadata||void 0})),total:g}}async createAuditLog(e){let s=randomUUID(),t=new Date;return await this.col("audit_logs").insertOne({_id:s,action:e.action,userId:e.userId||null,userEmail:e.userEmail||null,role:e.role||null,resource:e.resource,resourceId:e.resourceId||null,changes:e.changes||null,ipAddress:e.ipAddress||null,userAgent:e.userAgent||null,success:e.success,error:e.error||null,metadata:e.metadata||null,timestamp:t}),{...e,id:s,timestamp:t}}docToAuthUser(e){return {id:e._id,name:e.name||void 0,email:e.email,passwordHash:e.passwordHash||void 0,role:e.role,tenantId:e.tenantId||void 0,avatar:e.avatar||void 0,emailVerified:e.emailVerified||false,locked:e.locked||false,lastLogin:e.lastLogin?.toISOString?.()||e.lastLogin||void 0,failedLoginAttempts:e.failedLoginAttempts||0,createdAt:e.createdAt?.toISOString?.()||e.createdAt,updatedAt:e.updatedAt?.toISOString?.()||e.updatedAt}}docToSession(e){return {id:e._id,userId:e.userId,token:e.token,refreshToken:e.refreshToken||void 0,expiresAt:e.expiresAt?.toISOString?.()||e.expiresAt,createdAt:e.createdAt?.toISOString?.()||e.createdAt,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.collection("email_verifications").insertOne({userId:new(await import('mongodb')).ObjectId(e),token:s,expiresAt:t,createdAt:new Date}),{token:s,expiresAt:t}}async verifyEmailToken(e){let s=await this.db.collection("email_verifications").findOne({token:e});return s?s.expiresAt<new Date?{success:false,error:"Verification token has expired"}:(await this.db.collection("users").updateOne({_id:s.userId},{$set:{emailVerified:true}}),await this.db.collection("email_verifications").deleteOne({_id:s._id}),{success:true,userId:s.userId.toString()}):{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"),i=new Date(Date.now()+3600*1e3);return await this.db.collection("password_resets").insertOne({userId:new(await import('mongodb')).ObjectId(s.id),token:t,expiresAt:i,createdAt:new Date}),{token:t,expiresAt:i}}async resetPasswordWithToken(e,s){let t=await this.db.collection("password_resets").findOne({token:e});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 i=await this.hashPassword(s);return await this.db.collection("users").updateOne({_id:t.userId},{$set:{passwordHash:i,updatedAt:new Date}}),await this.db.collection("password_resets").updateOne({_id:t._id},{$set:{usedAt:new Date}}),await this.db.collection("sessions").deleteMany({userId:t.userId}),{success:true}}};export{w as a};
@@ -0,0 +1,21 @@
1
+ import {a}from'./chunk-NZ35PV5R.js';import {a as a$2,i}from'./chunk-7N6NKCRT.js';import {c as c$1,a as a$1}from'./chunk-R6UUTH3T.js';import {f,s,a as a$4,b as b$3,c as c$3}from'./chunk-PWGS2GPI.js';import {n,e,f as f$1}from'./chunk-UVTS2IWM.js';import {d,f as f$2,e as e$1,g as g$1}from'./chunk-HLSB2MCK.js';import {b as b$1,d as d$1}from'./chunk-SL3LZQCF.js';import {c}from'./chunk-VKXQUYYV.js';import {g}from'./chunk-OG7CNQGU.js';import {a as a$3,c as c$2,b as b$2,d as d$2}from'./chunk-ZAQOSRP6.js';import {z as z$1}from'zod';import {createYoga}from'graphql-yoga';import {createRequire}from'module';import {randomBytes}from'crypto';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 z$1.any()}}function De(n){let e=z$1.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=z$1.array(e)),n.required||(e=e.optional().nullable()),n.validate&&(e=b(e,n.validate)),e}function we(n){let e=n.integer?z$1.coerce.number().int():z$1.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=z$1.array(e)),n.required||(e=e.optional().nullable()),n.validate&&(e=b(e,n.validate)),e}function Fe(n){let e=z$1.boolean();return n.required||(e=e.optional().nullable()),n.validate&&(e=b(e,n.validate)),e}function Ie(n){let e=z$1.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=z$1.string().email("Invalid email");return n.required||(e=e.optional().nullable()),n.validate&&(e=b(e,n.validate)),e}function Oe(n){let e=z$1.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=z$1.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=z$1.array(z$1.enum(t)):e=z$1.enum(t);}else e=n.hasMany?z$1.array(z$1.string()):z$1.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=z$1.enum(e);return n.required||(t=t.optional().nullable()),n.validate&&(t=b(t,n.validate)),t}function _e(n){let e=z$1.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=z$1.array(z$1.record(z$1.any()));return n.required||(e=e.optional().nullable()),n.validate&&(e=b(e,n.validate)),e}function Ze(n){let e=z$1.union([z$1.record(z$1.any()),z$1.array(z$1.any())]);return n.required||(e=e.optional().nullable()),n.validate&&(e=b(e,n.validate)),e}function qe(n){let e=z$1.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=z$1.object({id:z$1.string(),url:z$1.string().optional(),filename:z$1.string().optional(),mimeType:z$1.string().optional()});e=z$1.union([z$1.string(),t]);}else e=z$1.string();return n.hasMany&&(e=z$1.array(e)),n.required||(e=e.optional().nullable()),n.validate&&(e=b(e,n.validate)),e}function Ue(n){let e=z$1.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=z$1.object({relationTo:z$1.enum(n.relationTo),value:z$1.string()}):e=z$1.union([z$1.string(),z$1.object({relationTo:z$1.string(),value:z$1.string()})]),n.hasMany&&(e=z$1.array(e)),n.required||(e=e.optional().nullable()),n.validate&&(e=b(e,n.validate)),e}function Ge(n){let e=z$1.object(Object.fromEntries(n.fields.filter(s=>s.name).map(s=>[s.name,C(s)]))),t=z$1.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=z$1.array(z$1.string());return n.required||(e=e.optional().nullable()),e}function Ve(n){let e=z$1.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=>z$1.object({blockType:z$1.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=z$1.object({blockType:z$1.enum(s)}).catchall(z$1.any()),i=z$1.object({blockType:z$1.string()}).catchall(z$1.any());a=z$1.array(z$1.union([o,i,z$1.record(z$1.any())]));}else a=z$1.array(z$1.union([z$1.object({blockType:z$1.string()}).catchall(z$1.any()),z$1.record(z$1.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 z$1.object(Object.fromEntries(n.fields.filter(t=>t.name).map(t=>[t.name,C(t)])))}function ze(n){return z$1.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 z$1.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]=z$1.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]=z$1.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]=z$1.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]=z$1.object(E(t.fields)).passthrough().optional().nullable():t.type==="group"&&"fields"in t?e[t.name]=z$1.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=z$1.string().optional(),e.updatedAt=z$1.string().optional()),n.tenantScoped&&(e.tenantID=z$1.string().optional()),e.id=z$1.string().optional(),z$1.object(e).passthrough()}function ge(n){let e=R(n.fields);return z$1.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]=z$1.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]=z$1.object(E(t.fields)).optional().nullable():t.type==="group"&&"fields"in t?e[t.name]=z$1.object(E(t.fields)).optional().nullable():e[t.name]=C(t).optional().nullable();return z$1.object(e).passthrough()}function be(n){let e={};for(let t of n.fields)t.name&&(e[t.name]=z$1.object({equals:z$1.any().optional(),not_equals:z$1.any().optional(),in:z$1.array(z$1.any()).optional(),not_in:z$1.array(z$1.any()).optional(),greater_than:z$1.number().optional(),greater_than_equal:z$1.number().optional(),less_than:z$1.number().optional(),less_than_equal:z$1.number().optional(),like:z$1.string().optional(),not_like:z$1.string().optional(),contains:z$1.string().optional(),exists:z$1.boolean().optional()}).optional());return e.AND=z$1.array(z$1.lazy(()=>z$1.object(e))).optional(),e.OR=z$1.array(z$1.lazy(()=>z$1.object(e))).optional(),z$1.object(e).optional()}function Te(n){let e=R(n.fields);return e.id=z$1.string().optional(),z$1.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]=z$1.object(s).optional().nullable();}else t.type==="collapsible"&&"fields"in t?e[t.name]=z$1.object(E(t.fields)).optional().nullable():t.type==="group"&&"fields"in t?e[t.name]=z$1.object(E(t.fields)).optional().nullable():e[t.name]=C(t).optional().nullable();return z$1.object(e).passthrough()}var w=class{storageProviders=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=>a$4(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=>b$3(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=>c$3(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 b$1(this.registry),this.webhookService=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(a);let e$1={slug:"plugin-settings",admin:{hidden:true},fields:[{name:"states",type:"json"}]};if(this.registry.addGlobalPostInit(e$1),!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: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: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$1={slug:f$1,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 c&&this.db.dialect==="postgres"){let i=this.db,r=d.replace(/-/g,"_");i.schema[r]||(i.schema[r]=g);}await this.db.init([...this.registry.getCollections(),t,s,a$1],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$1=t?.secret,a=t?.checkSession!==false;return s({registry:this.registry,db:this.db,authSecret:s$1,authAdapter:this.config.authAdapter,checkSession:a,...e,cors:this.config.cors,webhookService:this.webhookService,settings:this.settings})}getGraphQL(e){let t=c$1({registry:this.registry,db:this.db,settings:this.settings});return {fetch:createYoga({schema:t,context:async({request:a})=>{let o=f$2(a),i,r;if(o&&this.db){let d=await e$1(o,this.db);d.user&&(i=d.user,r=g$1(d));}let c=e?.tenantID;return {db:this.db,registry:this.registry,user:i,req:a,tenantID:c,apiKey:r,relationLoader:new a$1({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$1,...r]=o.split("."),c=r.join(".");if(c=c.replace(/\.(query|mutate|subscribe)$/,""),!i$1||!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 a$2({db:this.db,registry:this.registry,req:t,user:e?.user,tenantID:e?.tenantID,settings:this.settings}),h=i(d)[i$1];if(!h)return new Response(JSON.stringify({error:{message:`Collection '${i$1}' 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$1});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 e$1(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=d$1({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=createRequire(import.meta.url),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 a$3{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=c$2({where:m},t,this.tenantContext,b$2).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=>d$2(T,t,this.tenantContext,b$2))),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(!d$2(p,t,this.tenantContext,b$2))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=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||{})}export{K as a,V as b,B as c,x as d,pe as e,C as f,he as g,ge as h,me as i,be as j,Te as k,w as l,Xe as m,Je as n,M as o,W as p,Mt as q,J as r,ln as s};
File without changes