@kyro-cms/core 0.12.21 → 0.12.23

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 (36) hide show
  1. package/README.md +7 -0
  2. package/dist/api-handler-graphql.cjs +1 -1
  3. package/dist/api-handler-graphql.js +1 -1
  4. package/dist/api-handler-trpc.cjs +1 -1
  5. package/dist/api-handler-trpc.js +1 -1
  6. package/dist/api-handler.cjs +1 -1
  7. package/dist/api-handler.js +1 -1
  8. package/dist/{bootstrap-KFGRTJSD.js → bootstrap-6G6HI26Z.js} +1 -1
  9. package/dist/bootstrap-ETJ6QNGR.cjs +1 -0
  10. package/dist/{chunk-4D6FG2J6.js → chunk-3IOJVXWI.js} +1 -1
  11. package/dist/chunk-4XZABBHF.cjs +1 -0
  12. package/dist/chunk-6MSPBK3W.js +1 -0
  13. package/dist/{chunk-GXVCCKOL.js → chunk-6ROHVUXF.js} +1 -1
  14. package/dist/{chunk-QJZQOLRN.js → chunk-HY5FILVL.js} +1 -1
  15. package/dist/{chunk-O3OYZQN7.cjs → chunk-MR5BDZKI.cjs} +2 -2
  16. package/dist/{chunk-BVG6VSAJ.cjs → chunk-QCA3AP3M.cjs} +1 -1
  17. package/dist/{chunk-XALG5H27.cjs → chunk-RHNLFONF.cjs} +1 -1
  18. package/dist/{chunk-YVM5BDRD.js → chunk-YYL2U3HJ.js} +1 -1
  19. package/dist/{chunk-XTRY75KC.cjs → chunk-ZLGWJ4TK.cjs} +2 -2
  20. package/dist/cli/index.cjs +3 -3
  21. package/dist/cli/index.js +3 -3
  22. package/dist/index.cjs +3 -3
  23. package/dist/index.d.cts +6 -3
  24. package/dist/index.d.ts +6 -3
  25. package/dist/index.js +1 -1
  26. package/dist/mongo-auth-adapter-5TJO5J5U.js +1 -0
  27. package/dist/{mongo-auth-adapter-C62QYCYV.cjs → mongo-auth-adapter-JVE5M3S4.cjs} +1 -1
  28. package/dist/mongodb/index.cjs +1 -1
  29. package/dist/mongodb/index.js +1 -1
  30. package/dist/rest/index.cjs +1 -1
  31. package/dist/rest/index.js +1 -1
  32. package/package.json +2 -2
  33. package/dist/bootstrap-4WXRKXMO.cjs +0 -1
  34. package/dist/chunk-KJT6VTTN.cjs +0 -1
  35. package/dist/chunk-OOQGI3T7.js +0 -1
  36. package/dist/mongo-auth-adapter-AIMZTNG6.js +0 -1
package/README.md CHANGED
@@ -8,6 +8,13 @@
8
8
  [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
9
9
  [![TypeScript](https://img.shields.io/badge/TypeScript-5.7-blue.svg)](https://www.typescriptlang.org/)
10
10
 
11
+ <br />
12
+
13
+ [![Cloudflare](https://img.shields.io/badge/Deploy_to-Cloudflare-18181B?style=for-the-badge&logo=cloudflare&logoColor=F38020)](https://deploy.workers.cloudflare.com/?url=https://github.com/danielDozie/kyro-cms)
14
+ [![Vercel](https://img.shields.io/badge/Deploy_with-Vercel-18181B?style=for-the-badge&logo=vercel&logoColor=white)](https://vercel.com/new/clone?repository-url=https%3A%2F%2Fgithub.com%2FdanielDozie%2Fkyro-cms)
15
+ [![Netlify](https://img.shields.io/badge/Deploy_to-Netlify-18181B?style=for-the-badge&logo=netlify&logoColor=00C7B7)](https://app.netlify.com/start/deploy?repository=https://github.com/danielDozie/kyro-cms)
16
+ [![Railway](https://img.shields.io/badge/Deploy_on-Railway-18181B?style=for-the-badge&logo=railway&logoColor=white)](https://railway.app/new/template?template=https%3A%2F%2Fgithub.com%2FdanielDozie%2Fkyro-cms)
17
+
11
18
  </div>
12
19
 
13
20
  ---
@@ -1 +1 @@
1
- 'use strict';var chunkXALG5H27_cjs=require('./chunk-XALG5H27.cjs');require('./chunk-O3OYZQN7.cjs'),require('./chunk-KJT6VTTN.cjs'),require('./chunk-65G73T7Z.cjs'),require('./chunk-KD7LUCFY.cjs'),require('./chunk-ZUVP4UK7.cjs'),require('./chunk-HS2KNFAB.cjs'),require('./chunk-XTRY75KC.cjs'),require('./chunk-5K4YG5DA.cjs'),require('./chunk-WIZ6C5QZ.cjs'),require('./chunk-GO34AOBZ.cjs'),require('./chunk-HOP4D5XZ.cjs'),require('./chunk-HVXO3OFB.cjs'),require('./chunk-ILEZ3NYX.cjs'),require('./chunk-NY47CFVP.cjs'),require('./chunk-G3J2EU5D.cjs'),require('./chunk-4ORJMSJU.cjs'),require('./chunk-WG3UQEV7.cjs'),require('./chunk-GYQMNXXW.cjs'),require('./chunk-MIOMMB23.cjs'),require('./chunk-3Q2WUG63.cjs'),require('./chunk-BVG6VSAJ.cjs'),require('./chunk-FHJJKFAU.cjs'),require('./chunk-D5P2IPGX.cjs'),require('./chunk-G7SSHELM.cjs'),require('./chunk-Q3Q7BJVQ.cjs'),require('./chunk-AHSFSERC.cjs');function n(e){return new Response(e.body,e)}var p={graphqlEnabled:false,trpcEnabled:false,wsEnabled:false,requireAuth:false};function r(){return new Response(JSON.stringify({error:"GraphQL is disabled"}),{status:503,headers:{"Content-Type":"application/json"}})}async function o(){try{return (await chunkXALG5H27_cjs.a.db.findOne({collection:"_globals_access-settings",where:{},draft:!0}))?.apiAccess?.graphqlEnabled??p.graphqlEnabled}catch{return true}}var l=async e=>{if(await chunkXALG5H27_cjs.b(),!await o())return r();let t=await chunkXALG5H27_cjs.a.getGraphQL().fetch(e.request,e.locals);return n(t)},u=async e=>{if(await chunkXALG5H27_cjs.b(),!await o())return r();let t=await chunkXALG5H27_cjs.a.getGraphQL().fetch(e.request,e.locals);return n(t)};exports.GET=u;exports.POST=l;
1
+ 'use strict';var chunkRHNLFONF_cjs=require('./chunk-RHNLFONF.cjs');require('./chunk-MR5BDZKI.cjs'),require('./chunk-4XZABBHF.cjs'),require('./chunk-65G73T7Z.cjs'),require('./chunk-KD7LUCFY.cjs'),require('./chunk-ZUVP4UK7.cjs'),require('./chunk-HS2KNFAB.cjs'),require('./chunk-ZLGWJ4TK.cjs'),require('./chunk-5K4YG5DA.cjs'),require('./chunk-WIZ6C5QZ.cjs'),require('./chunk-GO34AOBZ.cjs'),require('./chunk-HOP4D5XZ.cjs'),require('./chunk-HVXO3OFB.cjs'),require('./chunk-ILEZ3NYX.cjs'),require('./chunk-NY47CFVP.cjs'),require('./chunk-G3J2EU5D.cjs'),require('./chunk-4ORJMSJU.cjs'),require('./chunk-WG3UQEV7.cjs'),require('./chunk-GYQMNXXW.cjs'),require('./chunk-MIOMMB23.cjs'),require('./chunk-3Q2WUG63.cjs'),require('./chunk-QCA3AP3M.cjs'),require('./chunk-FHJJKFAU.cjs'),require('./chunk-D5P2IPGX.cjs'),require('./chunk-G7SSHELM.cjs'),require('./chunk-Q3Q7BJVQ.cjs'),require('./chunk-AHSFSERC.cjs');function n(e){return new Response(e.body,e)}var p={graphqlEnabled:false,trpcEnabled:false,wsEnabled:false,requireAuth:false};function r(){return new Response(JSON.stringify({error:"GraphQL is disabled"}),{status:503,headers:{"Content-Type":"application/json"}})}async function o(){try{return (await chunkRHNLFONF_cjs.a.db.findOne({collection:"_globals_access-settings",where:{},draft:!0}))?.apiAccess?.graphqlEnabled??p.graphqlEnabled}catch{return true}}var l=async e=>{if(await chunkRHNLFONF_cjs.b(),!await o())return r();let t=await chunkRHNLFONF_cjs.a.getGraphQL().fetch(e.request,e.locals);return n(t)},u=async e=>{if(await chunkRHNLFONF_cjs.b(),!await o())return r();let t=await chunkRHNLFONF_cjs.a.getGraphQL().fetch(e.request,e.locals);return n(t)};exports.GET=u;exports.POST=l;
@@ -1 +1 @@
1
- import {b,a}from'./chunk-4D6FG2J6.js';import'./chunk-QJZQOLRN.js';import'./chunk-OOQGI3T7.js';import'./chunk-NZ35PV5R.js';import'./chunk-5SEHX7ON.js';import'./chunk-LHW4R367.js';import'./chunk-PP7W5UKL.js';import'./chunk-YVM5BDRD.js';import'./chunk-6J27P5D6.js';import'./chunk-K6WUOU6P.js';import'./chunk-IETGL7WJ.js';import'./chunk-IKOXCJYO.js';import'./chunk-NRLIGDYF.js';import'./chunk-FVZ5RFLO.js';import'./chunk-HLSB2MCK.js';import'./chunk-GKYEJ2UF.js';import'./chunk-PP5S2UBV.js';import'./chunk-DKESD4HI.js';import'./chunk-RHCWCG3O.js';import'./chunk-OG7CNQGU.js';import'./chunk-VGQ4VUG6.js';import'./chunk-GXVCCKOL.js';import'./chunk-5KOQYQEE.js';import'./chunk-6SPPR5JZ.js';import'./chunk-4RMFCTWH.js';import'./chunk-KDNYHLD2.js';import'./chunk-5J6HXUF6.js';function n(e){return new Response(e.body,e)}var p={graphqlEnabled:false,trpcEnabled:false,wsEnabled:false,requireAuth:false};function r(){return new Response(JSON.stringify({error:"GraphQL is disabled"}),{status:503,headers:{"Content-Type":"application/json"}})}async function o(){try{return (await a.db.findOne({collection:"_globals_access-settings",where:{},draft:!0}))?.apiAccess?.graphqlEnabled??p.graphqlEnabled}catch{return true}}var l=async e=>{if(await b(),!await o())return r();let t=await a.getGraphQL().fetch(e.request,e.locals);return n(t)},u=async e=>{if(await b(),!await o())return r();let t=await a.getGraphQL().fetch(e.request,e.locals);return n(t)};export{u as GET,l as POST};
1
+ import {b,a}from'./chunk-3IOJVXWI.js';import'./chunk-HY5FILVL.js';import'./chunk-6MSPBK3W.js';import'./chunk-NZ35PV5R.js';import'./chunk-5SEHX7ON.js';import'./chunk-LHW4R367.js';import'./chunk-PP7W5UKL.js';import'./chunk-YYL2U3HJ.js';import'./chunk-6J27P5D6.js';import'./chunk-K6WUOU6P.js';import'./chunk-IETGL7WJ.js';import'./chunk-IKOXCJYO.js';import'./chunk-NRLIGDYF.js';import'./chunk-FVZ5RFLO.js';import'./chunk-HLSB2MCK.js';import'./chunk-GKYEJ2UF.js';import'./chunk-PP5S2UBV.js';import'./chunk-DKESD4HI.js';import'./chunk-RHCWCG3O.js';import'./chunk-OG7CNQGU.js';import'./chunk-VGQ4VUG6.js';import'./chunk-6ROHVUXF.js';import'./chunk-5KOQYQEE.js';import'./chunk-6SPPR5JZ.js';import'./chunk-4RMFCTWH.js';import'./chunk-KDNYHLD2.js';import'./chunk-5J6HXUF6.js';function n(e){return new Response(e.body,e)}var p={graphqlEnabled:false,trpcEnabled:false,wsEnabled:false,requireAuth:false};function r(){return new Response(JSON.stringify({error:"GraphQL is disabled"}),{status:503,headers:{"Content-Type":"application/json"}})}async function o(){try{return (await a.db.findOne({collection:"_globals_access-settings",where:{},draft:!0}))?.apiAccess?.graphqlEnabled??p.graphqlEnabled}catch{return true}}var l=async e=>{if(await b(),!await o())return r();let t=await a.getGraphQL().fetch(e.request,e.locals);return n(t)},u=async e=>{if(await b(),!await o())return r();let t=await a.getGraphQL().fetch(e.request,e.locals);return n(t)};export{u as GET,l as POST};
@@ -1 +1 @@
1
- 'use strict';var chunkXALG5H27_cjs=require('./chunk-XALG5H27.cjs');require('./chunk-O3OYZQN7.cjs'),require('./chunk-KJT6VTTN.cjs'),require('./chunk-65G73T7Z.cjs'),require('./chunk-KD7LUCFY.cjs'),require('./chunk-ZUVP4UK7.cjs'),require('./chunk-HS2KNFAB.cjs'),require('./chunk-XTRY75KC.cjs'),require('./chunk-5K4YG5DA.cjs'),require('./chunk-WIZ6C5QZ.cjs'),require('./chunk-GO34AOBZ.cjs'),require('./chunk-HOP4D5XZ.cjs'),require('./chunk-HVXO3OFB.cjs'),require('./chunk-ILEZ3NYX.cjs'),require('./chunk-NY47CFVP.cjs'),require('./chunk-G3J2EU5D.cjs'),require('./chunk-4ORJMSJU.cjs'),require('./chunk-WG3UQEV7.cjs'),require('./chunk-GYQMNXXW.cjs'),require('./chunk-MIOMMB23.cjs'),require('./chunk-3Q2WUG63.cjs'),require('./chunk-BVG6VSAJ.cjs'),require('./chunk-FHJJKFAU.cjs'),require('./chunk-D5P2IPGX.cjs'),require('./chunk-G7SSHELM.cjs'),require('./chunk-Q3Q7BJVQ.cjs'),require('./chunk-AHSFSERC.cjs');function n(){return new Response(JSON.stringify({error:"tRPC is disabled"}),{status:503,headers:{"Content-Type":"application/json"}})}var r={graphqlEnabled:false,trpcEnabled:false,wsEnabled:false,requireAuth:false};async function s(){try{return (await chunkXALG5H27_cjs.a.db.findOne({collection:"_globals_access-settings",where:{},draft:!0}))?.apiAccess?.trpcEnabled??r.trpcEnabled}catch{return true}}var i=async e=>(await chunkXALG5H27_cjs.b(),await s()?chunkXALG5H27_cjs.a.getTRPC().fetch(e.request,e.locals):n());exports.ALL=i;
1
+ 'use strict';var chunkRHNLFONF_cjs=require('./chunk-RHNLFONF.cjs');require('./chunk-MR5BDZKI.cjs'),require('./chunk-4XZABBHF.cjs'),require('./chunk-65G73T7Z.cjs'),require('./chunk-KD7LUCFY.cjs'),require('./chunk-ZUVP4UK7.cjs'),require('./chunk-HS2KNFAB.cjs'),require('./chunk-ZLGWJ4TK.cjs'),require('./chunk-5K4YG5DA.cjs'),require('./chunk-WIZ6C5QZ.cjs'),require('./chunk-GO34AOBZ.cjs'),require('./chunk-HOP4D5XZ.cjs'),require('./chunk-HVXO3OFB.cjs'),require('./chunk-ILEZ3NYX.cjs'),require('./chunk-NY47CFVP.cjs'),require('./chunk-G3J2EU5D.cjs'),require('./chunk-4ORJMSJU.cjs'),require('./chunk-WG3UQEV7.cjs'),require('./chunk-GYQMNXXW.cjs'),require('./chunk-MIOMMB23.cjs'),require('./chunk-3Q2WUG63.cjs'),require('./chunk-QCA3AP3M.cjs'),require('./chunk-FHJJKFAU.cjs'),require('./chunk-D5P2IPGX.cjs'),require('./chunk-G7SSHELM.cjs'),require('./chunk-Q3Q7BJVQ.cjs'),require('./chunk-AHSFSERC.cjs');function n(){return new Response(JSON.stringify({error:"tRPC is disabled"}),{status:503,headers:{"Content-Type":"application/json"}})}var r={graphqlEnabled:false,trpcEnabled:false,wsEnabled:false,requireAuth:false};async function s(){try{return (await chunkRHNLFONF_cjs.a.db.findOne({collection:"_globals_access-settings",where:{},draft:!0}))?.apiAccess?.trpcEnabled??r.trpcEnabled}catch{return true}}var i=async e=>(await chunkRHNLFONF_cjs.b(),await s()?chunkRHNLFONF_cjs.a.getTRPC().fetch(e.request,e.locals):n());exports.ALL=i;
@@ -1 +1 @@
1
- import {b,a}from'./chunk-4D6FG2J6.js';import'./chunk-QJZQOLRN.js';import'./chunk-OOQGI3T7.js';import'./chunk-NZ35PV5R.js';import'./chunk-5SEHX7ON.js';import'./chunk-LHW4R367.js';import'./chunk-PP7W5UKL.js';import'./chunk-YVM5BDRD.js';import'./chunk-6J27P5D6.js';import'./chunk-K6WUOU6P.js';import'./chunk-IETGL7WJ.js';import'./chunk-IKOXCJYO.js';import'./chunk-NRLIGDYF.js';import'./chunk-FVZ5RFLO.js';import'./chunk-HLSB2MCK.js';import'./chunk-GKYEJ2UF.js';import'./chunk-PP5S2UBV.js';import'./chunk-DKESD4HI.js';import'./chunk-RHCWCG3O.js';import'./chunk-OG7CNQGU.js';import'./chunk-VGQ4VUG6.js';import'./chunk-GXVCCKOL.js';import'./chunk-5KOQYQEE.js';import'./chunk-6SPPR5JZ.js';import'./chunk-4RMFCTWH.js';import'./chunk-KDNYHLD2.js';import'./chunk-5J6HXUF6.js';function n(){return new Response(JSON.stringify({error:"tRPC is disabled"}),{status:503,headers:{"Content-Type":"application/json"}})}var r={graphqlEnabled:false,trpcEnabled:false,wsEnabled:false,requireAuth:false};async function s(){try{return (await a.db.findOne({collection:"_globals_access-settings",where:{},draft:!0}))?.apiAccess?.trpcEnabled??r.trpcEnabled}catch{return true}}var i=async e=>(await b(),await s()?a.getTRPC().fetch(e.request,e.locals):n());export{i as ALL};
1
+ import {b,a}from'./chunk-3IOJVXWI.js';import'./chunk-HY5FILVL.js';import'./chunk-6MSPBK3W.js';import'./chunk-NZ35PV5R.js';import'./chunk-5SEHX7ON.js';import'./chunk-LHW4R367.js';import'./chunk-PP7W5UKL.js';import'./chunk-YYL2U3HJ.js';import'./chunk-6J27P5D6.js';import'./chunk-K6WUOU6P.js';import'./chunk-IETGL7WJ.js';import'./chunk-IKOXCJYO.js';import'./chunk-NRLIGDYF.js';import'./chunk-FVZ5RFLO.js';import'./chunk-HLSB2MCK.js';import'./chunk-GKYEJ2UF.js';import'./chunk-PP5S2UBV.js';import'./chunk-DKESD4HI.js';import'./chunk-RHCWCG3O.js';import'./chunk-OG7CNQGU.js';import'./chunk-VGQ4VUG6.js';import'./chunk-6ROHVUXF.js';import'./chunk-5KOQYQEE.js';import'./chunk-6SPPR5JZ.js';import'./chunk-4RMFCTWH.js';import'./chunk-KDNYHLD2.js';import'./chunk-5J6HXUF6.js';function n(){return new Response(JSON.stringify({error:"tRPC is disabled"}),{status:503,headers:{"Content-Type":"application/json"}})}var r={graphqlEnabled:false,trpcEnabled:false,wsEnabled:false,requireAuth:false};async function s(){try{return (await a.db.findOne({collection:"_globals_access-settings",where:{},draft:!0}))?.apiAccess?.trpcEnabled??r.trpcEnabled}catch{return true}}var i=async e=>(await b(),await s()?a.getTRPC().fetch(e.request,e.locals):n());export{i as ALL};
@@ -1 +1 @@
1
- 'use strict';var chunkXALG5H27_cjs=require('./chunk-XALG5H27.cjs');require('./chunk-O3OYZQN7.cjs'),require('./chunk-KJT6VTTN.cjs'),require('./chunk-65G73T7Z.cjs'),require('./chunk-KD7LUCFY.cjs'),require('./chunk-ZUVP4UK7.cjs'),require('./chunk-HS2KNFAB.cjs'),require('./chunk-XTRY75KC.cjs'),require('./chunk-5K4YG5DA.cjs'),require('./chunk-WIZ6C5QZ.cjs'),require('./chunk-GO34AOBZ.cjs'),require('./chunk-HOP4D5XZ.cjs'),require('./chunk-HVXO3OFB.cjs'),require('./chunk-ILEZ3NYX.cjs'),require('./chunk-NY47CFVP.cjs'),require('./chunk-G3J2EU5D.cjs'),require('./chunk-4ORJMSJU.cjs'),require('./chunk-WG3UQEV7.cjs'),require('./chunk-GYQMNXXW.cjs'),require('./chunk-MIOMMB23.cjs'),require('./chunk-3Q2WUG63.cjs'),require('./chunk-BVG6VSAJ.cjs'),require('./chunk-FHJJKFAU.cjs'),require('./chunk-D5P2IPGX.cjs'),require('./chunk-G7SSHELM.cjs'),require('./chunk-Q3Q7BJVQ.cjs'),require('./chunk-AHSFSERC.cjs');Object.defineProperty(exports,"ALL",{enumerable:true,get:function(){return chunkXALG5H27_cjs.c}});Object.defineProperty(exports,"kyroInstance",{enumerable:true,get:function(){return chunkXALG5H27_cjs.a}});Object.defineProperty(exports,"warmKyroInstance",{enumerable:true,get:function(){return chunkXALG5H27_cjs.b}});
1
+ 'use strict';var chunkRHNLFONF_cjs=require('./chunk-RHNLFONF.cjs');require('./chunk-MR5BDZKI.cjs'),require('./chunk-4XZABBHF.cjs'),require('./chunk-65G73T7Z.cjs'),require('./chunk-KD7LUCFY.cjs'),require('./chunk-ZUVP4UK7.cjs'),require('./chunk-HS2KNFAB.cjs'),require('./chunk-ZLGWJ4TK.cjs'),require('./chunk-5K4YG5DA.cjs'),require('./chunk-WIZ6C5QZ.cjs'),require('./chunk-GO34AOBZ.cjs'),require('./chunk-HOP4D5XZ.cjs'),require('./chunk-HVXO3OFB.cjs'),require('./chunk-ILEZ3NYX.cjs'),require('./chunk-NY47CFVP.cjs'),require('./chunk-G3J2EU5D.cjs'),require('./chunk-4ORJMSJU.cjs'),require('./chunk-WG3UQEV7.cjs'),require('./chunk-GYQMNXXW.cjs'),require('./chunk-MIOMMB23.cjs'),require('./chunk-3Q2WUG63.cjs'),require('./chunk-QCA3AP3M.cjs'),require('./chunk-FHJJKFAU.cjs'),require('./chunk-D5P2IPGX.cjs'),require('./chunk-G7SSHELM.cjs'),require('./chunk-Q3Q7BJVQ.cjs'),require('./chunk-AHSFSERC.cjs');Object.defineProperty(exports,"ALL",{enumerable:true,get:function(){return chunkRHNLFONF_cjs.c}});Object.defineProperty(exports,"kyroInstance",{enumerable:true,get:function(){return chunkRHNLFONF_cjs.a}});Object.defineProperty(exports,"warmKyroInstance",{enumerable:true,get:function(){return chunkRHNLFONF_cjs.b}});
@@ -1 +1 @@
1
- export{c as ALL,a as kyroInstance,b as warmKyroInstance}from'./chunk-4D6FG2J6.js';import'./chunk-QJZQOLRN.js';import'./chunk-OOQGI3T7.js';import'./chunk-NZ35PV5R.js';import'./chunk-5SEHX7ON.js';import'./chunk-LHW4R367.js';import'./chunk-PP7W5UKL.js';import'./chunk-YVM5BDRD.js';import'./chunk-6J27P5D6.js';import'./chunk-K6WUOU6P.js';import'./chunk-IETGL7WJ.js';import'./chunk-IKOXCJYO.js';import'./chunk-NRLIGDYF.js';import'./chunk-FVZ5RFLO.js';import'./chunk-HLSB2MCK.js';import'./chunk-GKYEJ2UF.js';import'./chunk-PP5S2UBV.js';import'./chunk-DKESD4HI.js';import'./chunk-RHCWCG3O.js';import'./chunk-OG7CNQGU.js';import'./chunk-VGQ4VUG6.js';import'./chunk-GXVCCKOL.js';import'./chunk-5KOQYQEE.js';import'./chunk-6SPPR5JZ.js';import'./chunk-4RMFCTWH.js';import'./chunk-KDNYHLD2.js';import'./chunk-5J6HXUF6.js';
1
+ export{c as ALL,a as kyroInstance,b as warmKyroInstance}from'./chunk-3IOJVXWI.js';import'./chunk-HY5FILVL.js';import'./chunk-6MSPBK3W.js';import'./chunk-NZ35PV5R.js';import'./chunk-5SEHX7ON.js';import'./chunk-LHW4R367.js';import'./chunk-PP7W5UKL.js';import'./chunk-YYL2U3HJ.js';import'./chunk-6J27P5D6.js';import'./chunk-K6WUOU6P.js';import'./chunk-IETGL7WJ.js';import'./chunk-IKOXCJYO.js';import'./chunk-NRLIGDYF.js';import'./chunk-FVZ5RFLO.js';import'./chunk-HLSB2MCK.js';import'./chunk-GKYEJ2UF.js';import'./chunk-PP5S2UBV.js';import'./chunk-DKESD4HI.js';import'./chunk-RHCWCG3O.js';import'./chunk-OG7CNQGU.js';import'./chunk-VGQ4VUG6.js';import'./chunk-6ROHVUXF.js';import'./chunk-5KOQYQEE.js';import'./chunk-6SPPR5JZ.js';import'./chunk-4RMFCTWH.js';import'./chunk-KDNYHLD2.js';import'./chunk-5J6HXUF6.js';
@@ -1 +1 @@
1
- export{d as autoBootstrap,a as bootstrapAdmin,e as bootstrapWithRetry,b as checkBootstrapRequired,c as getBootstrapFromEnv}from'./chunk-OOQGI3T7.js';import'./chunk-6J27P5D6.js';import'./chunk-K6WUOU6P.js';import'./chunk-IKOXCJYO.js';import'./chunk-5J6HXUF6.js';
1
+ export{d as autoBootstrap,a as bootstrapAdmin,e as bootstrapWithRetry,b as checkBootstrapRequired,c as getBootstrapFromEnv}from'./chunk-6MSPBK3W.js';import'./chunk-6J27P5D6.js';import'./chunk-K6WUOU6P.js';import'./chunk-IKOXCJYO.js';import'./chunk-5J6HXUF6.js';
@@ -0,0 +1 @@
1
+ 'use strict';var chunk4XZABBHF_cjs=require('./chunk-4XZABBHF.cjs');require('./chunk-5K4YG5DA.cjs'),require('./chunk-WIZ6C5QZ.cjs'),require('./chunk-HOP4D5XZ.cjs'),require('./chunk-AHSFSERC.cjs');Object.defineProperty(exports,"autoBootstrap",{enumerable:true,get:function(){return chunk4XZABBHF_cjs.d}});Object.defineProperty(exports,"bootstrapAdmin",{enumerable:true,get:function(){return chunk4XZABBHF_cjs.a}});Object.defineProperty(exports,"bootstrapWithRetry",{enumerable:true,get:function(){return chunk4XZABBHF_cjs.e}});Object.defineProperty(exports,"checkBootstrapRequired",{enumerable:true,get:function(){return chunk4XZABBHF_cjs.b}});Object.defineProperty(exports,"getBootstrapFromEnv",{enumerable:true,get:function(){return chunk4XZABBHF_cjs.c}});
@@ -1 +1 @@
1
- import {z,A as A$1}from'./chunk-QJZQOLRN.js';import {d}from'./chunk-OOQGI3T7.js';import {a as a$1}from'./chunk-IKOXCJYO.js';import {c}from'./chunk-DKESD4HI.js';import {a}from'./chunk-RHCWCG3O.js';import {a as a$2}from'./chunk-VGQ4VUG6.js';import {a as a$3}from'./chunk-GXVCCKOL.js';import m from'kyro:config';var e=null,n=null;async function b(){if(!e){if(globalThis.__KYRO_INSTANCE__)try{await globalThis.__KYRO_INSTANCE__.shutdown();}catch{}try{let t=m.default||m;e=z(t),await e.init(),await e.loadSettings();let a$4=e.db,r;if(a$4 instanceof c){if(a$4.dialect==="postgres")r=new a({db:a$4.client});else if(a$4.dialect==="sqlite"){let s=process.env.KYRO_AUTH_DB_PATH||"./data/auth.db";r=new a$1({path:s});}}else if(a$4 instanceof A$1){let s=process.env.KYRO_AUTH_DB_PATH||"./data/auth.db";r=new a$1({path:s});}else a$4 instanceof a$2&&(r=new a$3({db:a$4.db}));r?.connect&&await r.connect(),(await d(r))?.success,typeof e.startWebSocket=="function"&&e.startWebSocket().catch(s=>{console.error("[Kyro] WebSocket auto-start failed:",s);}),globalThis.__KYRO_INSTANCE__=e;}catch(t){throw e=null,n=null,console.error("[Kyro API] Init failed, will retry:",t),t}}}async function O(){n||(n=b()),await n;}var g={graphqlEnabled:false,trpcEnabled:false,wsEnabled:false,requireAuth:false};async function A(t){try{return (await e.db.findOne({collection:"_globals_access-settings",where:{},draft:!0}))?.apiAccess?.[t]??g[t]??!0}catch{return true}}var q=async t=>{if(!e){n||(n=b());try{await Promise.race([n,new Promise((l,o)=>setTimeout(()=>o(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(t.request.url).pathname,i=__KYRO_API_PATH__;if(r===`${i}/graphql`&&typeof e.getGraphQL=="function"){if(!await A("graphqlEnabled"))return new Response(JSON.stringify({error:"GraphQL is disabled"}),{status:503,headers:{"Content-Type":"application/json"}});let o=await e.getGraphQL().fetch(t.request,t.locals);return new Response(o.body,o)}if(r.startsWith(`${i}/trpc/`)&&typeof e.getTRPC=="function"){if(!await A("trpcEnabled"))return new Response(JSON.stringify({error:"tRPC is disabled"}),{status:503,headers:{"Content-Type":"application/json"}});let o=await e.getTRPC().fetch(t.request,t.locals);return new Response(o.body,o)}return e.getREST().fetch(t.request,t.locals)};export{e as a,O as b,q as c};
1
+ import {z,A as A$1}from'./chunk-HY5FILVL.js';import {d}from'./chunk-6MSPBK3W.js';import {a as a$1}from'./chunk-IKOXCJYO.js';import {c}from'./chunk-DKESD4HI.js';import {a}from'./chunk-RHCWCG3O.js';import {a as a$2}from'./chunk-VGQ4VUG6.js';import {a as a$3}from'./chunk-6ROHVUXF.js';import m from'kyro:config';var e=null,n=null;async function b(){if(!e){if(globalThis.__KYRO_INSTANCE__)try{await globalThis.__KYRO_INSTANCE__.shutdown();}catch{}try{let t=m.default||m;e=z(t),await e.init(),await e.loadSettings();let a$4=e.db,r;if(a$4 instanceof c){if(a$4.dialect==="postgres")r=new a({db:a$4.client});else if(a$4.dialect==="sqlite"){let s=process.env.KYRO_AUTH_DB_PATH||"./data/auth.db";r=new a$1({path:s});}}else if(a$4 instanceof A$1){let s=process.env.KYRO_AUTH_DB_PATH||"./data/auth.db";r=new a$1({path:s});}else a$4 instanceof a$2&&(r=new a$3({db:a$4.db}));r?.connect&&await r.connect(),(await d(r))?.success,typeof e.startWebSocket=="function"&&e.startWebSocket().catch(s=>{console.error("[Kyro] WebSocket auto-start failed:",s);}),globalThis.__KYRO_INSTANCE__=e;}catch(t){throw e=null,n=null,console.error("[Kyro API] Init failed, will retry:",t),t}}}async function O(){n||(n=b()),await n;}var g={graphqlEnabled:false,trpcEnabled:false,wsEnabled:false,requireAuth:false};async function A(t){try{return (await e.db.findOne({collection:"_globals_access-settings",where:{},draft:!0}))?.apiAccess?.[t]??g[t]??!0}catch{return true}}var q=async t=>{if(!e){n||(n=b());try{await Promise.race([n,new Promise((l,o)=>setTimeout(()=>o(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(t.request.url).pathname,i=__KYRO_API_PATH__;if(r===`${i}/graphql`&&typeof e.getGraphQL=="function"){if(!await A("graphqlEnabled"))return new Response(JSON.stringify({error:"GraphQL is disabled"}),{status:503,headers:{"Content-Type":"application/json"}});let o=await e.getGraphQL().fetch(t.request,t.locals);return new Response(o.body,o)}if(r.startsWith(`${i}/trpc/`)&&typeof e.getTRPC=="function"){if(!await A("trpcEnabled"))return new Response(JSON.stringify({error:"tRPC is disabled"}),{status:503,headers:{"Content-Type":"application/json"}});let o=await e.getTRPC().fetch(t.request,t.locals);return new Response(o.body,o)}return e.getREST().fetch(t.request,t.locals)};export{e as a,O as b,q as c};
@@ -0,0 +1 @@
1
+ 'use strict';var chunk5K4YG5DA_cjs=require('./chunk-5K4YG5DA.cjs'),chunkHOP4D5XZ_cjs=require('./chunk-HOP4D5XZ.cjs');async function f(t){let{adminEmail:e,adminPassword:r,adminRole:o="super_admin",tenantId:i,emailConfig:a,sendWelcomeEmail:c=false}=t,s=t.authAdapter||new chunkHOP4D5XZ_cjs.a({path:t.authDbPath||"./data/auth.db"});try{await s.connect?.();}catch{return {success:false,error:"Failed to connect to auth storage"}}let l=new chunk5K4YG5DA_cjs.l().validate(r);if(!l.valid)return await s.disconnect?.(),{success:false,error:`Invalid password: ${l.errors.join(", ")}`};if(await s.findUserByEmail(e))return await s.disconnect?.(),{success:false,error:"Admin user already exists"};try{let n=await s.createUser({email:e,password:r,role:o||"admin",tenantId:i});if(await s.updateUser?.(n.id,{emailVerified:!0}),c&&a){let u=new chunk5K4YG5DA_cjs.k(a),w=u.getTemplates().welcome(e.split("@")[0]);await u.send({to:e,...w});}return await s.disconnect?.(),{success:!0,user:n}}catch(n){return await s.disconnect?.(),{success:false,error:n instanceof Error?n.message:"Failed to create admin user"}}}async function y(t,e){return !await t.findUserByEmail(e)}function A(){let t=process.env.KYRO_ADMIN_EMAIL,e=process.env.KYRO_ADMIN_PASSWORD;return !t||!e?null:{authDbPath:process.env.KYRO_AUTH_DB_PATH||"./data/auth.db",adminEmail:t,adminPassword:e,adminRole:process.env.KYRO_ADMIN_ROLE||"super_admin",tenantId:process.env.KYRO_ADMIN_TENANT_ID,emailConfig:process.env.SMTP_HOST?{provider:"smtp",smtp:{host:process.env.SMTP_HOST,port:parseInt(process.env.SMTP_PORT||"587",10),secure:process.env.SMTP_SECURE==="true",auth:{user:process.env.SMTP_USER||"",pass:process.env.SMTP_PASS||""}},from:process.env.SMTP_FROM||"noreply@example.com",fromName:process.env.SMTP_FROM_NAME}:void 0,sendWelcomeEmail:process.env.KYRO_ADMIN_SEND_WELCOME==="true"}}async function T(t){let e=A();if(!e)return null;t&&(e.authAdapter=t);try{if(await e.authAdapter?.connect?.(),await e.authAdapter?.findUserByEmail(e.adminEmail))return await e.authAdapter?.disconnect?.(),{success:!1,error:"Admin user already exists"}}catch{}let r=await f(e);return r.success||console.error(`Bootstrap failed: ${r.error}`),r}async function v(t,e=3,r=2e3){let o="";for(let i=0;i<e;i++){let a=await f(t);if(a.success||(o=a.error||"Unknown error",o.includes("already exists")))return a;i<e-1&&await new Promise(c=>setTimeout(c,r));}return {success:false,error:`Failed after ${e} retries: ${o}`}}exports.a=f;exports.b=y;exports.c=A;exports.d=T;exports.e=v;
@@ -0,0 +1 @@
1
+ import {l,k}from'./chunk-6J27P5D6.js';import {a}from'./chunk-IKOXCJYO.js';async function f(t){let{adminEmail:e,adminPassword:r,adminRole:o="super_admin",tenantId:i,emailConfig:a$1,sendWelcomeEmail:c=false}=t,s=t.authAdapter||new a({path:t.authDbPath||"./data/auth.db"});try{await s.connect?.();}catch{return {success:false,error:"Failed to connect to auth storage"}}let l$1=new l().validate(r);if(!l$1.valid)return await s.disconnect?.(),{success:false,error:`Invalid password: ${l$1.errors.join(", ")}`};if(await s.findUserByEmail(e))return await s.disconnect?.(),{success:false,error:"Admin user already exists"};try{let n=await s.createUser({email:e,password:r,role:o||"admin",tenantId:i});if(await s.updateUser?.(n.id,{emailVerified:!0}),c&&a$1){let u=new k(a$1),w=u.getTemplates().welcome(e.split("@")[0]);await u.send({to:e,...w});}return await s.disconnect?.(),{success:!0,user:n}}catch(n){return await s.disconnect?.(),{success:false,error:n instanceof Error?n.message:"Failed to create admin user"}}}async function y(t,e){return !await t.findUserByEmail(e)}function A(){let t=process.env.KYRO_ADMIN_EMAIL,e=process.env.KYRO_ADMIN_PASSWORD;return !t||!e?null:{authDbPath:process.env.KYRO_AUTH_DB_PATH||"./data/auth.db",adminEmail:t,adminPassword:e,adminRole:process.env.KYRO_ADMIN_ROLE||"super_admin",tenantId:process.env.KYRO_ADMIN_TENANT_ID,emailConfig:process.env.SMTP_HOST?{provider:"smtp",smtp:{host:process.env.SMTP_HOST,port:parseInt(process.env.SMTP_PORT||"587",10),secure:process.env.SMTP_SECURE==="true",auth:{user:process.env.SMTP_USER||"",pass:process.env.SMTP_PASS||""}},from:process.env.SMTP_FROM||"noreply@example.com",fromName:process.env.SMTP_FROM_NAME}:void 0,sendWelcomeEmail:process.env.KYRO_ADMIN_SEND_WELCOME==="true"}}async function T(t){let e=A();if(!e)return null;t&&(e.authAdapter=t);try{if(await e.authAdapter?.connect?.(),await e.authAdapter?.findUserByEmail(e.adminEmail))return await e.authAdapter?.disconnect?.(),{success:!1,error:"Admin user already exists"}}catch{}let r=await f(e);return r.success||console.error(`Bootstrap failed: ${r.error}`),r}async function v(t,e=3,r=2e3){let o="";for(let i=0;i<e;i++){let a=await f(t);if(a.success||(o=a.error||"Unknown error",o.includes("already exists")))return a;i<e-1&&await new Promise(c=>setTimeout(c,r));}return {success:false,error:`Failed after ${e} retries: ${o}`}}export{f as a,y as b,A as c,T as d,v as e};
@@ -1 +1 @@
1
- import h from'bcryptjs';import {randomUUID,randomBytes}from'crypto';var p=class{db;adapter;prefix;sessionTTL;refreshTokenTTL;indexesEnsured=false;constructor(e){this.db=e.db,this.adapter=e.adapter,this.prefix=e.collectionPrefix||"",this.sessionTTL=e.sessionTTL||86400,this.refreshTokenTTL=e.refreshTokenTTL||604800;}getDatabase(){let e=typeof this.db=="function"?this.db():this.db;if(!e&&this.adapter&&(this.adapter.db?e=this.adapter.db:this.adapter.client&&(this.adapter.db=this.adapter.client.db(this.adapter.database||"kyro_cms"),e=this.adapter.db)),!e)throw new Error("MongoDB database not initialized");return e}col(e){return this.getDatabase().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"),o=new Date,u=new Date(o.getTime()+this.sessionTTL*1e3),d={_id:t,userId:e,token:i,refreshToken:n,ipAddress:s?.ipAddress||null,userAgent:s?.userAgent||null,expiresAt:u,createdAt:o};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:o,resourceId:u,success:d,startDate:c,endDate:f}=e,a={};i&&(a.userId=i),n&&(Array.isArray(n)?a.action={$in:n}:a.action=n),o&&(a.resource=o),u&&(a.resourceId=u),d!==void 0&&(a.success=d),(c||f)&&(a.timestamp={},c&&(a.timestamp.$gte=c),f&&(a.timestamp.$lte=f));let w=await this.col("audit_logs").countDocuments(a);return {logs:(await this.col("audit_logs").find(a).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:w}}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{p as a};
1
+ import h from'bcryptjs';import {randomUUID,randomBytes}from'crypto';var p=class{db;adapter;prefix;sessionTTL;refreshTokenTTL;indexesEnsured=false;constructor(e){this.db=e.db,this.adapter=e.adapter,this.prefix=e.collectionPrefix||"",this.sessionTTL=e.sessionTTL||86400,this.refreshTokenTTL=e.refreshTokenTTL||604800;}getDatabase(){let e=typeof this.db=="function"?this.db():this.db;if(!e&&this.adapter&&(this.adapter.db?e=this.adapter.db:this.adapter.client&&(this.adapter.db=this.adapter.client.db(this.adapter.database||"kyro_cms"),e=this.adapter.db)),!e)throw new Error("MongoDB database not initialized");return e}col(e){return this.getDatabase().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),r={_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(r),this.docToAuthUser(r)}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"),r=randomBytes(32).toString("base64url"),o=new Date,u=new Date(o.getTime()+this.sessionTTL*1e3),d={_id:t,userId:e,token:i,refreshToken:r,ipAddress:s?.ipAddress||null,userAgent:s?.userAgent||null,expiresAt:u,createdAt:o};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 r of i)if(await h.compare(e,r))return true;return false}async findAuditLogs(e){let{limit:s=50,offset:t=0,userId:i,action:r,resource:o,resourceId:u,success:d,startDate:c,endDate:f}=e,a={};i&&(a.userId=i),r&&(Array.isArray(r)?a.action={$in:r}:a.action=r),o&&(a.resource=o),u&&(a.resourceId=u),d!==void 0&&(a.success=d),(c||f)&&(a.timestamp={},c&&(a.timestamp.$gte=c),f&&(a.timestamp.$lte=f));let g=await this.col("audit_logs").countDocuments(a);return {logs:(await this.col("audit_logs").find(a).sort({timestamp:-1}).skip(t).limit(s).toArray()).map(n=>({id:n._id,timestamp:n.timestamp,action:n.action,userId:n.userId||void 0,userEmail:n.userEmail||void 0,role:n.role||void 0,resource:n.resource,resourceId:n.resourceId||void 0,changes:n.changes||void 0,ipAddress:n.ipAddress||void 0,userAgent:n.userAgent||void 0,success:n.success,error:n.error||void 0,metadata:n.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),i=await import('mongodb');return await this.db.collection("email_verifications").insertOne({userId:new i.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),r=await import('mongodb');return await this.db.collection("password_resets").insertOne({userId:new r.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{p as a};
@@ -1,4 +1,4 @@
1
- import {a as a$2}from'./chunk-NZ35PV5R.js';import {a as a$1}from'./chunk-5SEHX7ON.js';import {a as a$4,i}from'./chunk-LHW4R367.js';import {c as c$2,a as a$3}from'./chunk-PP7W5UKL.js';import {a,b,c,f,t}from'./chunk-YVM5BDRD.js';import {o,f as f$1,g as g$1}from'./chunk-FVZ5RFLO.js';import {d,f as f$2,e,g as g$2}from'./chunk-HLSB2MCK.js';import {b as b$1,d as d$1}from'./chunk-GKYEJ2UF.js';import {c as c$1}from'./chunk-DKESD4HI.js';import {g}from'./chunk-OG7CNQGU.js';import {a as a$5,c as c$3,b as b$2,d as d$2}from'./chunk-5KOQYQEE.js';import {a as a$6}from'./chunk-4RMFCTWH.js';import {z as z$1}from'zod';import {createYoga}from'graphql-yoga';import {createRequire}from'module';import {randomBytes}from'crypto';function L(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(L(s.fields,e))return true}if("fields"in t&&t.fields&&L(t.fields,e))return true}return false}var z=class extends Error{errors;constructor(e){super(`Configuration validation failed:
1
+ import {a as a$2}from'./chunk-NZ35PV5R.js';import {a as a$1}from'./chunk-5SEHX7ON.js';import {a as a$4,i}from'./chunk-LHW4R367.js';import {c as c$2,a as a$3}from'./chunk-PP7W5UKL.js';import {a,b,c,f,t}from'./chunk-YYL2U3HJ.js';import {o,f as f$1,g as g$1}from'./chunk-FVZ5RFLO.js';import {d,f as f$2,e,g as g$2}from'./chunk-HLSB2MCK.js';import {b as b$1,d as d$1}from'./chunk-GKYEJ2UF.js';import {c as c$1}from'./chunk-DKESD4HI.js';import {g}from'./chunk-OG7CNQGU.js';import {a as a$5,c as c$3,b as b$2,d as d$2}from'./chunk-5KOQYQEE.js';import {a as a$6}from'./chunk-4RMFCTWH.js';import {z as z$1}from'zod';import {createYoga}from'graphql-yoga';import {createRequire}from'module';import {randomBytes}from'crypto';function L(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(L(s.fields,e))return true}if("fields"in t&&t.fields&&L(t.fields,e))return true}return false}var z=class extends Error{errors;constructor(e){super(`Configuration validation failed:
2
2
  ${e.join(`
3
3
  `)}`),this.name="ConfigValidationError",this.errors=e;}};function X(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=R(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&&(L(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)L(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(i=>i.name==="email"),s=n.fields.some(i=>i.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 J(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=R(n.fields,`global:${n.slug}`);e.push(...t);}return e}function R(n,e){let t=[],s=new Set;for(let i=0;i<n.length;i++){let a=n[i];if(a.type==="row"||a.type==="collapsible"||a.type==="tabs"){if("fields"in a&&a.fields){let r=R(a.fields,e);t.push(...r);}else if("tabs"in a)for(let r of a.tabs){let c=R(r.fields,e);t.push(...c);}continue}let o=a.name;if(!o){t.push(`${e}: Field at index ${i} is missing a "name" property`);continue}if(s.has(o)&&t.push(`${e}: Duplicate field name "${o}"`),s.add(o),/^[a-zA-Z][a-zA-Z0-9_]*$/.test(o)||t.push(`${e}: Field name "${o}" must be alphanumeric with underscores`),!a.type){t.push(`${e}: Field "${o}" is missing a "type" property`);continue}switch(a.type){case "relationship":a.relationTo||t.push(`${e}: Relationship field "${o}" is missing "relationTo"`);break;case "array":if(!a.fields||a.fields.length===0)t.push(`${e}: Array field "${o}" has no fields defined`);else {let r=R(a.fields,`${e}.${o}`);t.push(...r);}break;case "group":if(!a.fields||a.fields.length===0)t.push(`${e}: Group field "${o}" has no fields defined`);else {let r=R(a.fields,`${e}.${o}`);t.push(...r);}break;case "blocks":if(!a.blocks||a.blocks.length===0)t.push(`${e}: Blocks field "${o}" has no blocks defined`);else {let r=Ke(a.blocks,`${e}.${o}`);t.push(...r);}break;case "select":case "radio":if(typeof a.options=="function")break;if((!a.options||a.options.length===0)&&!a.dynamicOptions)t.push(`${e}: ${a.type} field "${o}" has no options defined`);else if(Array.isArray(a.options)){let r=a.options.map(d=>d.value),c=new Set(r);r.length!==c.size&&t.push(`${e}: ${a.type} field "${o}" has duplicate option values`);}break;case "upload":a.relationTo||t.push(`${e}: Upload field "${o}" is missing "relationTo"`);break}"min"in a&&"max"in a&&a.min>a.max&&t.push(`${e}: Field "${o}" has min greater than max`),"minLength"in a&&"maxLength"in a&&a.minLength>a.maxLength&&t.push(`${e}: Field "${o}" has minLength greater than maxLength`),"minRows"in a&&"maxRows"in a&&a.minRows>a.maxRows&&t.push(`${e}: Field "${o}" has minRows greater than maxRows`);}return t}function Ke(n,e){let t=[],s=new Set;for(let i of n){if(!i.slug){t.push(`${e}: Block is missing a "slug" property`);continue}if(s.has(i.slug)&&t.push(`${e}: Duplicate block slug "${i.slug}"`),s.add(i.slug),i.label||t.push(`${e}: Block "${i.slug}" is missing a "label" property`),!i.fields||i.fields.length===0)t.push(`${e}: Block "${i.slug}" has no fields defined`);else {let a=R(i.fields,`${e}.${i.slug}`);t.push(...a);}}return t}function we(n,e=[]){let t=[],s=new Set;for(let i of n)s.has(i.slug)&&t.push(`Duplicate collection slug "${i.slug}"`),s.add(i.slug);for(let i of e)s.has(i.slug)&&t.push(`Duplicate global slug "${i.slug}"`),s.add(i.slug);for(let i of n){let a=X(i);t.push(...a);}for(let i of e){let a=J(i);t.push(...a);}for(let i of n){let a=_(i.fields,n);t.push(...a);}if(t.length>0)throw new z(t)}function _(n,e){let t=[],s=new Set(e.map(i=>i.slug));for(let i of n){if(i.type==="relationship"){let a=Array.isArray(i.relationTo)?i.relationTo:[i.relationTo];for(let o of a)o!=="*"&&!s.has(o)&&console.warn(`[Kyro Config Warning]: Relationship field "${i.name}" references unknown collection "${o}". Select options will not be available until this collection is registered.`);}if(i.type==="upload"){let a=Array.isArray(i.relationTo)?i.relationTo:[i.relationTo];for(let o of a)s.has(o)||t.push(`Upload field "${i.name}" references unknown collection "${o}"`);}if("fields"in i&&i.fields){let a=_(i.fields,e);t.push(...a);}if("tabs"in i)for(let a of i.tabs){let o=_(a.fields,e);t.push(...o);}if("blocks"in i)for(let a of i.blocks){let o=_(a.fields,e);t.push(...o);}}return t}function A(n){switch(n.type){case "text":return Me(n);case "number":return Ve(n);case "checkbox":return Be(n);case "date":return He(n);case "email":return We(n);case "password":return ze(n);case "textarea":return Xe(n);case "select":return Je(n);case "radio":return Ye(n);case "color":return Qe(n);case "richtext":return et(n);case "json":return tt(n);case "code":return st(n);case "upload":return Re(n);case "image":return Re(n);case "markdown":return nt(n);case "relationship":return Ne(n);case "relationship-block":return Ne(n);case "array":return it(n);case "list":return at(n);case "group":return ot(n);case "blocks":return rt(n);case "row":return lt(n);case "collapsible":return ct(n);case "tabs":return dt(n);default:return z$1.any()}}function Me(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=T(e,n.validate)),e}function Ve(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=T(e,n.validate)),e}function Be(n){let e=z$1.boolean();return n.required||(e=e.optional().nullable()),n.validate&&(e=T(e,n.validate)),e}function He(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=T(e,n.validate)),e}function We(n){let e=z$1.string().email("Invalid email");return n.required||(e=e.optional().nullable()),n.validate&&(e=T(e,n.validate)),e}function ze(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=T(e,n.validate)),e}function Xe(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=T(e,n.validate)),e}function Je(n){let e;if(Array.isArray(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=T(e,n.validate)),e}function Ye(n){let e;if(Array.isArray(n.options)&&n.options.length>0){let t=n.options.map(s=>s.value);e=z$1.enum(t);}else e=z$1.string();return n.required||(e=e.optional().nullable()),n.validate&&(e=T(e,n.validate)),e}function Qe(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=T(e,n.validate)),e}function et(n){let e=z$1.array(z$1.record(z$1.any()));return n.required||(e=e.optional().nullable()),n.validate&&(e=T(e,n.validate)),e}function tt(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=T(e,n.validate)),e}function st(n){let e=z$1.string();return n.required||(e=e.optional().nullable()),n.validate&&(e=T(e,n.validate)),e}function Re(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=T(e,n.validate)),e}function nt(n){let e=z$1.string();return n.required||(e=e.optional().nullable()),n.validate&&(e=T(e,n.validate)),e}function Ne(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=T(e,n.validate)),e}function it(n){let e=z$1.object(Object.fromEntries(n.fields.filter(s=>s.name).map(s=>[s.name,A(s)]))).passthrough(),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=T(t,n.validate)),t}function at(n){let e=z$1.array(z$1.string());return n.required||(e=e.optional().nullable()),e}function ot(n){let e=z$1.object(Object.fromEntries(n.fields.filter(t=>t.name).map(t=>[t.name,A(t)])));return n.required?e:e.optional().nullable()}function rt(n){let e=n.blocks||[];e.map(a=>z$1.object({blockType:z$1.literal(a.slug),...Object.fromEntries(a.fields.filter(o=>o.name).map(o=>[o.name,A(o)]))}));let s=e.map(a=>a.slug),i;if(s.length>0){let a=z$1.object({blockType:z$1.enum(s)}).catchall(z$1.any()),o=z$1.object({blockType:z$1.string()}).catchall(z$1.any());i=z$1.array(z$1.union([a,o,z$1.record(z$1.any())]));}else i=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&&(i=i.min(n.minRows)),n.maxRows&&(i=i.max(n.maxRows)),n.required||(i=i.optional().nullable()),n.validate&&(i=T(i,n.validate)),i}function lt(n){return z$1.object(Object.fromEntries(n.fields.filter(t=>t.name).map(t=>[t.name,A(t)])))}function ct(n){return z$1.object(Object.fromEntries(n.fields.filter(t=>t.name).map(t=>[t.name,A(t)])))}function dt(n){let e={};for(let t of n.tabs)for(let s of t.fields)s.name&&(e[s.name]=A(s));return z$1.object(e).passthrough().optional()}function T(n,e){return n.refine(async t=>await e(t,{required:false})===true,{message:"Custom validation failed"})}function F(n){let e={};for(let t of n)if(t.type==="tabs"&&"tabs"in t){let s={};for(let i of t.tabs){let a=F(i.fields);Object.assign(s,a);}t.name?e[t.name]=z$1.object(s).passthrough().optional():Object.assign(e,s);}else if(t.type==="row"&&"fields"in t){let s=F(t.fields);t.name?e[t.name]=z$1.object(s).passthrough().optional():Object.assign(e,s);}else if(t.type==="collapsible"&&"fields"in t){let s=F(t.fields);t.name?e[t.name]=z$1.object(s).passthrough().optional():Object.assign(e,s);}else {if(!t.name)continue;e[t.name]=A(t);}return e}function v(n){let e={};for(let t of n)if(t.type==="tabs"&&"tabs"in t){let s={};for(let i of t.tabs){let a=v(i.fields);Object.assign(s,a);}t.name?e[t.name]=z$1.object(s).passthrough().optional().nullable():Object.assign(e,s);}else if(t.type==="row"&&"fields"in t){let s=v(t.fields);t.name?e[t.name]=z$1.object(s).passthrough().optional().nullable():Object.assign(e,s);}else if(t.type==="collapsible"&&"fields"in t){let s=v(t.fields);t.name?e[t.name]=z$1.object(s).passthrough().optional().nullable():Object.assign(e,s);}else if(t.type==="group"&&"fields"in t)t.name?e[t.name]=z$1.object(v(t.fields)).passthrough().optional().nullable():Object.assign(e,v(t.fields));else {if(!t.name)continue;e[t.name]=A(t).optional().nullable();}return e}function De(n){let e=F(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 Fe(n){let e=F(n.fields);return z$1.object(e).passthrough()}function ke(n){let e={};for(let t of n.fields)if(t.name)if(t.type==="tabs"&&"tabs"in t){let s={};for(let i of t.tabs)for(let a of i.fields)a.name&&(s[a.name]=A(a).optional().nullable());e[t.name]=z$1.object(s).optional().nullable();}else if(t.type==="row"&&"fields"in t){let s={};for(let i of t.fields)i.name&&(s[i.name]=A(i).optional().nullable());Object.assign(e,s);}else t.type==="collapsible"&&"fields"in t?e[t.name]=z$1.object(v(t.fields)).optional().nullable():t.type==="group"&&"fields"in t?e[t.name]=z$1.object(v(t.fields)).optional().nullable():e[t.name]=A(t).optional().nullable();return z$1.object(e).passthrough()}function Ie(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 Pe(n){let e=F(n.fields);return e.id=z$1.string().optional(),z$1.object(e).passthrough()}function Oe(n){let e={};for(let t of n.fields)if(t.name)if(t.type==="tabs"&&"tabs"in t){let s={};for(let i of t.tabs)for(let a of i.fields)a.name&&(s[a.name]=A(a).optional().nullable());e[t.name]=z$1.object(s).optional().nullable();}else t.type==="collapsible"&&"fields"in t?e[t.name]=z$1.object(v(t.fields)).optional().nullable():t.type==="group"&&"fields"in t?e[t.name]=z$1.object(v(t.fields)).optional().nullable():e[t.name]=A(t).optional().nullable();return z$1.object(e).passthrough()}var I=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,fields:[...e.fields]};for(let i of this.plugins){let a=i.extensions?.collections?.find(o=>o.slug===t.slug);a&&(t={...t,...a.config,fields:[...t.fields,...a.config.fields||[]]});}if(t.seo){let i=a$1(),a=t.fields.findIndex(o=>o.type==="tabs");if(a!==-1){let o=t.fields[a];t.fields[a]={...o,tabs:[...o.tabs,{label:"SEO Settings",fields:i.fields}]};}else t.fields.push(i);}t.fields=this.applyFieldDefaults(t);let s=X(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=J(e);if(t.length>0)throw new Error(`Invalid global config: ${t.join(", ")}`);let s={...e};for(let i of this.plugins){let a=i.extensions?.globals?.find(o=>o.slug===s.slug);a&&(s={...s,...a.config,fields:[...s.fields||[],...a.config.fields||[]]});}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 a=De(s);return this.schemaCache.set(e,a),a}let i=this.globals.get(e);if(i){let a=Pe(i);return this.schemaCache.set(`global:${e}`,a),a}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 i=this.collections.get(e);if(i){let a=Fe(i);return this.schemaCache.set(t,a),a}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 i=this.collections.get(e);if(i){let o=ke(i);return this.schemaCache.set(t,o),o}let a=this.globals.get(e);if(a){let o=Oe(a);return this.schemaCache.set(`global:${e}:update`,o),o}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 i=this.collections.get(e);if(i){let a=Ie(i);return this.schemaCache.set(t,a),a}throw new Error(`No collection found with slug "${e}"`)}getFieldZodSchema(e){return A(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,i=a=>{for(let o of a){if(o.name&&s.set(o.name,o),"fields"in o&&o.fields&&i(o.fields),"tabs"in o)for(let r of o.tabs)i(r.fields);if("blocks"in o)for(let r of o.blocks)i(r.fields);}};return i(t),s}getVisibleFields(e){return this.getFields(e).filter(s=>!s.admin?.hidden)}validate(){let e=this.getCollections(),t=this.getGlobals();we(e,t);}async init(e){this.validate();for(let t of this.plugins){t.init&&await t.init(e||this);let s=t.collections||[];for(let a of s)a.slug&&!this.hasCollection(a.slug)&&this.addCollection(a);let i=t.globals||[];for(let a of i)a.slug&&!this.hasGlobal(a.slug)&&this.addGlobal(a);}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(i=>i.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()}}},k=null;function ut(){return k||(k=new I),k}function pt(){k=null;}function Y(){return k=new I,k}var x=class{name;displayName;adminEntry;version;description;hooks={};collections=[];globals=[];fields=[];extensions={collections:[],globals:[]};adminComponents={};adminStyles=[];serverMiddleware;clientMiddleware;constructor(e){this.name=e;}async init(e){}async beforeInit(e){}async afterInit(e){}getCollections(){return this.collections}getGlobals(){return this.globals}getHooks(){return this.hooks}},j=class{plugins=new Map;hooks=new Map;register(e){if(this.plugins.has(e.name))throw new Error(`Plugin "${e.name}" is already registered`);this.plugins.set(e.name,e);let t=e.getHooks?.()||{};for(let[s,i]of Object.entries(t))if(Array.isArray(i))for(let a of i)this.registerHook(s,a);}unregister(e){let t=this.plugins.get(e);if(!t)return;let s=t.getHooks?.()||{};for(let[i,a]of Object.entries(s))if(Array.isArray(a))for(let o of a)this.unregisterHook(i,o);this.plugins.delete(e);}get(e){return this.plugins.get(e)}getAll(){return Array.from(this.plugins.values())}has(e){return this.plugins.has(e)}registerHook(e,t){this.hooks.has(e)||this.hooks.set(e,[]),this.hooks.get(e).push(t);}unregisterHook(e,t){let s=this.hooks.get(e);if(s){let i=s.indexOf(t);i>-1&&s.splice(i,1);}}async executeHook(e,t){let s=this.hooks.get(e)||[],i=t;for(let a of s)try{let o=await a({...t,data:i});o!==void 0&&(i=o);}catch(o){console.error(`[PluginManager] Error in hook "${e}":`,o);}return i}getAllCollections(){let e=[];for(let t of this.plugins.values()){let s=t.getCollections?.()||[];e.push(...s);}return e}getAllGlobals(){let e=[];for(let t of this.plugins.values()){let s=t.getGlobals?.()||[];e.push(...s);}return e}getAllFields(){let e=[];for(let t of this.plugins.values())e.push(...t.fields);return e}getAdminComponents(){let e={};for(let t of this.plugins.values())Object.assign(e,t.adminComponents);return e}getAdminStyles(){let e=[];for(let t of this.plugins.values())e.push(...t.adminStyles);return e}},Q=class extends x{constructor(){super("seo"),this.displayName="Core SEO",this.description="Advanced SEO features including sitemaps, robots.txt, and structured data",this.adminEntry="@kyro-cms/admin/plugins/seo-admin",this.collections.push({slug:"seo-settings",label:"SEO Settings",fields:[{name:"sitemap",type:"checkbox",label:"Enable Sitemap",defaultValue:true},{name:"robotsTxt",type:"richtext",label:"robots.txt Content"},{name:"canonicalUrl",type:"text",variant:"url",label:"Canonical URL"},{name:"ogImage",type:"text",label:"Default OG Image URL"}]});}},ee=class extends x{constructor(){super("analytics"),this.displayName="Core Analytics",this.description="Built-in privacy-friendly analytics and dashboards",this.collections.push({slug:"analytics-events",label:"Analytics Events",fields:[{name:"name",type:"text",required:true},{name:"properties",type:"json",label:"Event Properties"},{name:"timestamp",type:"date",required:true},{name:"userId",type:"text",label:"User ID"},{name:"sessionId",type:"text",label:"Session ID"}]}),this.adminComponents.AnalyticsDashboard={};}},te=class extends x{constructor(){super("comments"),this.description="Commenting system for products and posts",this.collections.push({slug:"comments",label:"Comments",fields:[{name:"content",type:"richtext",required:true},{name:"author",type:"text",required:true},{name:"email",type:"email"},{name:"approved",type:"checkbox",defaultValue:false},{name:"parent",type:"text",label:"Parent Comment ID"},{name:"resourceType",type:"text",required:true},{name:"resourceId",type:"text",required:true}]}),this.adminComponents.CommentModeration={};}},se=class extends x{constructor(){super("reviews"),this.description="Product reviews and ratings",this.collections.push({slug:"reviews",label:"Reviews",fields:[{name:"rating",type:"number",required:true,min:1,max:5},{name:"title",type:"text"},{name:"content",type:"richtext",required:true},{name:"author",type:"relationship",relationTo:"customers"},{name:"product",type:"relationship",relationTo:"products",required:true},{name:"approved",type:"checkbox",defaultValue:false},{name:"verified",type:"checkbox",label:"Verified Purchase"},{name:"helpful",type:"number",label:"Helpful Count",defaultValue:0}]}),this.adminComponents.ReviewModeration={};}},ne=class extends x{constructor(){super("wishlist"),this.description="Customer wishlists",this.collections.push({slug:"wishlists",label:"Wishlists",fields:[{name:"customer",type:"relationship",relationTo:"customers",required:true},{name:"name",type:"text",label:"Wishlist Name",defaultValue:"My Wishlist"},{name:"items",type:"blocks",label:"Items",blocks:[{slug:"wishlist-item",label:"Item",fields:[{name:"product",type:"relationship",relationTo:"products"},{name:"quantity",type:"number",defaultValue:1},{name:"addedAt",type:"date"},{name:"priority",type:"select",options:[{label:"Low",value:"low"},{label:"Medium",value:"medium"},{label:"High",value:"high"}]}]}]}]});}},_t={SEO:Q,Analytics:ee,Comments:te,Reviews:se,Wishlist:ne};var ft={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 yt(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 $e(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:yt(n,e),cdnUrl:e?.cdnUrl,prefix:e?.prefix,accountId:e?.accountId,publicDevUrl:e?.publicDevUrl}}function gt(n,e,t){let s=t[e.configKey]||{};return $e(n,s)}function ht(n,e,t){let s=t?.[e.configKey]||t;return $e(n,s)}var ie=class extends x{constructor(){super("@kyro-cms/storage-s3"),this.version="1.0.0",this.description="S3-compatible storage (AWS R2 GCS DigitalOcean Backblaze Wasabi)";}async init(e){let t=e.registry?.storageProviders;if(!t)return;let s=this.name;for(let i of Object.values(ft))t.register({type:i.type,displayName:i.displayName,pluginName:s,configKey:i.configKey,configFields:i.configFields,extractConfig:a=>gt(i.type,i,a),extractRawConfig:a=>ht(i.type,i,a),factory:a$1=>a(a$1)});}},_e=new ie;var ae=class extends x{constructor(){super("@kyro-cms/storage-cloudinary"),this.version="1.0.0",this.description="Cloudinary image and video storage";}async init(e){let t=e.registry?.storageProviders;t&&t.register({type:"cloudinary",displayName:"Cloudinary",pluginName:this.name,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:s=>({cloudName:s.cloudinary?.cloudName||"",apiKey:s.cloudinary?.apiKey||"",apiSecret:s.cloudinary?.apiSecret||"",folder:s.cloudinary?.folder,uploadPreset:s.cloudinary?.uploadPreset}),extractRawConfig:s=>{let i=s?.cloudinary||s;return {cloudName:i?.cloudName||"",apiKey:i?.apiKey||"",apiSecret:i?.apiSecret||"",folder:i?.folder,uploadPreset:i?.uploadPreset}},factory:s=>b(s)});}},Le=new ae;var oe=class extends x{constructor(){super("@kyro-cms/storage-ftp"),this.version="1.0.0",this.description="FTP/SFTP storage provider";}async init(e){let t=e.registry?.storageProviders;t&&t.register({type:"ftp",displayName:"FTP",pluginName:this.name,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:s=>({host:s.ftp?.host||"",port:s.ftp?.port||21,user:s.ftp?.user||"",password:s.ftp?.password||"",secure:s.ftp?.secure||false,baseUrl:s.ftp?.baseUrl||"",prefix:s.ftp?.prefix,type:"ftp"}),extractRawConfig:s=>{let i=s?.ftp||s;return {host:i?.host||"",port:i?.port||21,user:i?.user||"",password:i?.password||"",secure:i?.secure||false,baseUrl:i?.baseUrl||"",prefix:i?.prefix,type:"ftp"}},factory:s=>c(s)});}},je=new oe;var bt=[_e,Le,je];function N(n,e,t){let s=e.split(".");if(s.length===0)return false;let i=s[0],a=s.slice(1).join(".");for(let o of n)if(o.name===i)if(a){if(o.fields&&Array.isArray(o.fields))return N(o.fields,a,t);if(o.type==="tabs"&&o.tabs&&Array.isArray(o.tabs)){for(let r of o.tabs)if(r.fields&&Array.isArray(r.fields)&&N(r.fields,a,t))return true;return false}if(o.type==="blocks"&&o.blocks&&Array.isArray(o.blocks)){let r=a.split(".")[0],c=a.split(".").slice(1).join(".");if(!c)return false;for(let d of o.blocks)if(d.slug===r&&d.fields&&Array.isArray(d.fields))return N(d.fields,c,t);return false}return o.type==="array"&&o.fields&&Array.isArray(o.fields)?N(o.fields,a,t):false}else return Object.assign(o,t),true;for(let o of n)if(!o.name||o.type==="tabs"||o.type==="row"||o.type==="collapsible"){if(o.fields&&Array.isArray(o.fields)&&N(o.fields,e,t))return true;if(o.type==="tabs"&&o.tabs&&Array.isArray(o.tabs)){for(let c of o.tabs)if(c.fields&&Array.isArray(c.fields)&&N(c.fields,e,t))return true}}return a?false:(n.push({name:i,...t}),true)}function Tt(n,e){if(e)for(let t of n){let s=e[t.slug];if(s){let{fields:i,...a}=s;if(t.admin={...t.admin,...a},i&&t.fields&&Array.isArray(t.fields))for(let[o,r]of Object.entries(i))N(t.fields,o,r);}}}var re=class{registry;db;pubsub;webhookService;settings;pluginManager;wsServer;config;constructor(e){this.config=e,this.registry=Y(),this.db=e.adapter,this.pubsub=new b$1(this.registry),this.webhookService=o(this.db),this.pluginManager=new j;for(let t of bt)this.pluginManager.register(t),this.registry.addPlugin(t);if(e.plugins)for(let t of e.plugins)this.pluginManager.register(t),this.registry.addPlugin(t);e.collections&&e.admin?.collectionOverrides&&Tt(e.collections,e.admin.collectionOverrides),e.collections&&this.registry.addCollections(e.collections),e.globals&&this.registry.addGlobals(e.globals);}async init(){await this.pluginManager.executeHook("beforeInit",{kyro:this}),await this.registry.init(this),await this.pluginManager.executeHook("afterInit",{kyro:this}),this.registry.addGlobalPostInit(a$2);let e={slug:"plugin-settings",admin:{hidden:true},fields:[{name:"states",type:"json"}]};if(this.registry.addGlobalPostInit(e),!this.db)throw new Error("Database adapter is null \u2014 failed to load at startup. Check the server console for the exact error.");let t={slug: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:f$1,fields:[{name:"name",type:"text",required:true},{name:"url",type:"text",required:true},{name:"events",type:"json",required:true},{name:"collections",type:"json"},{name:"status",type:"text",required:true},{name:"secret",type:"text"},{name:"headers",type:"json"},{name:"action",type:"text"},{name:"config",type:"json"},{name:"lastTriggered",type:"date"},{name:"lastError",type:"text"}]},i={slug:g$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"}]},a=this.registry.getGlobals();if(this.db instanceof c$1&&this.db.dialect==="postgres"){let o=this.db,r=d.replace(/-/g,"_");o.schema[r]||(o.schema[r]=g);}await this.db.init([...this.registry.getCollections(),t,s,i],a),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 i=await this.db.findOne({collection:"_globals_plugin-settings",where:{},draft:!0});i&&i.states&&(s=i.states);}catch{}for(let i of t)s[i]!==void 0&&e.setPluginEnabled(i,s[i]);}getREST(e){let t$1=typeof this.config.auth=="object"?this.config.auth:null,s=t$1?.secret,i=t$1?.checkSession!==false;return t({registry:this.registry,db:this.db,authSecret:s,authAdapter:this.config.authAdapter,checkSession:i,...e,cors:this.config.cors,webhookService:this.webhookService,settings:this.settings})}getGraphQL(e$1){let t=c$2({registry:this.registry,db:this.db,settings:this.settings});return {fetch:createYoga({schema:t,context:async({request:i})=>{let a=f$2(i),o,r;if(a&&this.db){let d=await e(a,this.db);d.user&&(o=d.user,r=g$2(d));}let c=e$1?.tenantId;return {db:this.db,registry:this.registry,user:o,req:i,tenantId:c,apiKey:r,relationLoader:new a$3({db:this.db,tenantId:c,user:o})}},graphiql:this.config.graphQL?.disablePlayground!==true,plugins:[]}).fetch,schema:t}}getTRPC(e){return {fetch:async(t,s)=>{let a=new URL(t.url).pathname.replace(/^\/api\/trpc\//,""),[o,...r]=a.split("."),c=r.join(".");if(c=c.replace(/\.(query|mutate|subscribe)$/,""),!o||!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$4({db:this.db,registry:this.registry,req:t,user:e?.user,tenantId:e?.tenantId,settings:this.settings}),p=i(d)[o];if(!p)return new Response(JSON.stringify({error:{message:`Collection '${o}' not found`,code:-32601,data:{code:"NOT_FOUND",httpStatus:404}}}),{status:404,headers:{"Content-Type":"application/json"}});let m=p[c];if(typeof m!="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 y={};if(t.method==="POST"||t.method==="PATCH")y=await t.json().catch(()=>({}));else {let C=new URL(t.url).searchParams.get("input");if(C)try{y=JSON.parse(decodeURIComponent(C));}catch{}}let g=y?.["0"]??y,f=await m({...g,collection:o});return new Response(JSON.stringify({result:{data:f}}),{status:200,headers:{"Content-Type":"application/json"}})}catch(y){let g=y.message||"Internal error",f=g.includes("not found")?404:g.includes("denied")||g.includes("authentication required")?403:g.includes("conflict")?409:500,C=f===404?-32601:f===403?-32001:f===409?-32002:-32603;return new Response(JSON.stringify({error:{message:g,code:C,data:{code:"INTERNAL_SERVER_ERROR",httpStatus:f}}}),{status:f,headers:{"Content-Type":"application/json"}})}},router:null}}getWS(){return this.wsServer}async startWebSocket(e$1){let t=this.settings?.access?.apiAccess;if(t?.wsEnabled===false)return null;let s=async a=>{let o=await e(a,this.db);if(!o.valid)throw new Error(o.error||"Invalid API key");if(!o.user)throw new Error("API key has no associated user");return o.user},i=e$1?.port||8080;if(globalThis.__KYRO_WS_SERVER__)try{await globalThis.__KYRO_WS_SERVER__.close();}catch{}return this.wsServer=d$1({pubsub:this.pubsub,port:i,requireAuth:e$1?.requireAuth??t?.requireAuth,verifyToken:e$1?.verifyToken||s}),globalThis.__KYRO_WS_SERVER__=this.wsServer,this.wsServer}async shutdown(){await this.pluginManager.executeHook("beforeServerStop",{kyro:this}),this.wsServer&&await this.wsServer.close(),await this.db.disconnect(),await this.pluginManager.executeHook("afterServerStop",{kyro:this});}};function gs(n){return new re(n)}var At=createRequire(import.meta.url),St="node:sqlite",{DatabaseSync:xt}=At(St);function E(n){let e=[];for(let t of n)if(t.type==="tabs"&&"tabs"in t)for(let s of t.tabs)e.push(...E(s.fields));else t.type==="row"&&"fields"in t?e.push(...E(t.fields)):t.type==="collapsible"&&"fields"in t?e.push(...E(t.fields)):e.push(t);return e}function Et(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 i=new Date(s);isNaN(i.getTime())?s=null:s=i.toISOString();}catch{s=null;}if((t.type==="upload"||t.type==="image")&&s)try{let i=JSON.parse(s);Array.isArray(i)?s=i.map(a=>typeof a=="object"&&a!==null?a:{id:a}):s=typeof i=="object"?i:{id:i};}catch{s={id:s};}if(t.type==="relationship"&&s)try{let i=JSON.parse(s);Array.isArray(i),s=i;}catch{s={relationTo:Array.isArray(t.relationTo)?t.relationTo[0]:t.relationTo,value:s};}if(t.type==="list"&&s)try{let i=JSON.parse(s);s=Array.isArray(i)?i:[];}catch{s=[];}if(t.type==="relationship-block"&&s)try{let i=JSON.parse(s);s=Array.isArray(i)?i:[];}catch{s=[];}return s}function qe(n,e){return Array.isArray(n)?n.map(t=>{if(!t||typeof t!="object")return t;let s=t.data?{...t.data}:void 0;if(!s)return t;let i=e.find(a=>a.slug===t.type||a.slug===t.slug);if(!i||!Array.isArray(i.fields))return t;for(let a of i.fields){if(a.name&&(a.type==="upload"||a.type==="image")&&s[a.name]){let o=s[a.name];Array.isArray(o)?s[a.name]=o.map(r=>typeof r=="string"?{id:r}:r):typeof o=="string"&&(s[a.name]={id:o});}if(a.type==="blocks"&&a.name&&s[a.name]){let o=a.blocks||[];s[a.name]=qe(s[a.name],o);}}return {...t,data:s}}):n}function q(n,e){try{return n.prepare(`PRAGMA table_info(${e})`).all().map(s=>s.name)}catch{return []}}var le=class extends a$5{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 xt(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 i=e(s),a=o=>typeof o=="boolean"?o?1:0:o===void 0?null:o;return new Proxy(i,{get(o,r,c){if(r==="all")return (...u)=>o.all(...u.map(a));if(r==="get")return (...u)=>o.get(...u.map(a));if(r==="run")return (...u)=>o.run(...u.map(a));let d=Reflect.get(o,r,c);return typeof d=="function"?d.bind(o):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),i=["id TEXT PRIMARY KEY"];for(let r of E(e.fields)){if(!r.name||r.name==="id")continue;let c=this.fieldToSQL(r);c&&i.push(c);}let a=E(e.fields);a.some(r=>r.name==="createdAt")||i.push(`${this.col("createdAt")} TEXT DEFAULT (datetime('now'))`),a.some(r=>r.name==="updatedAt")||i.push(`${this.col("updatedAt")} TEXT DEFAULT (datetime('now'))`),a.some(r=>r.name==="status")||i.push("status TEXT DEFAULT 'draft'"),a.some(r=>r.name==="hasDraft")||i.push("hasDraft INTEGER DEFAULT 0"),e.tenantScoped&&i.push("tenant_id TEXT NOT NULL");let o=q(this.db,s);if(o.length===0){let r=`CREATE TABLE IF NOT EXISTS ${s} (${i.join(", ")})`;this.db.exec(r),this.db.exec(`CREATE INDEX IF NOT EXISTS idx_${s}_status ON ${s}(status)`);for(let c of E(e.fields))c.name&&c.indexed&&this.db.exec(`CREATE INDEX IF NOT EXISTS idx_${s}_${c.name} ON ${s}(${this.col(c.name)})`),c.name&&c.unique&&this.db.exec(`CREATE UNIQUE INDEX IF NOT EXISTS idx_${s}_${c.name}_unique ON ${s}(${this.col(c.name)})`);}else {let r=new Set(o);for(let c of i){let d=c.split(" ")[0].replace(/^"/,"").replace(/"$/,"");if(!r.has(d)&&d!=="id")try{d==="status"?this.db.exec(`ALTER TABLE ${s} ADD COLUMN ${this.col(d)} TEXT DEFAULT 'published'`):d==="hasDraft"?this.db.exec(`ALTER TABLE ${s} ADD COLUMN ${this.col(d)} INTEGER DEFAULT 0`):this.db.exec(`ALTER TABLE ${s} ADD COLUMN ${this.col(d)} TEXT`);}catch{}}}this.migrations.set(s,true);}ensureVersionsTable(){this.db.exec(`
4
4
  CREATE TABLE IF NOT EXISTS ${this.versionsTableName} (
@@ -1,6 +1,6 @@
1
- 'use strict';var chunk65G73T7Z_cjs=require('./chunk-65G73T7Z.cjs'),chunkKD7LUCFY_cjs=require('./chunk-KD7LUCFY.cjs'),chunkZUVP4UK7_cjs=require('./chunk-ZUVP4UK7.cjs'),chunkHS2KNFAB_cjs=require('./chunk-HS2KNFAB.cjs'),chunkXTRY75KC_cjs=require('./chunk-XTRY75KC.cjs'),chunkILEZ3NYX_cjs=require('./chunk-ILEZ3NYX.cjs'),chunkNY47CFVP_cjs=require('./chunk-NY47CFVP.cjs'),chunkG3J2EU5D_cjs=require('./chunk-G3J2EU5D.cjs'),chunkWG3UQEV7_cjs=require('./chunk-WG3UQEV7.cjs'),chunkMIOMMB23_cjs=require('./chunk-MIOMMB23.cjs'),chunkFHJJKFAU_cjs=require('./chunk-FHJJKFAU.cjs'),chunkG7SSHELM_cjs=require('./chunk-G7SSHELM.cjs'),zod=require('zod'),graphqlYoga=require('graphql-yoga'),module$1=require('module'),crypto=require('crypto');var _documentCurrentScript=typeof document!=='undefined'?document.currentScript:null;function L(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(L(s.fields,e))return true}if("fields"in t&&t.fields&&L(t.fields,e))return true}return false}var z=class extends Error{errors;constructor(e){super(`Configuration validation failed:
1
+ 'use strict';var chunk65G73T7Z_cjs=require('./chunk-65G73T7Z.cjs'),chunkKD7LUCFY_cjs=require('./chunk-KD7LUCFY.cjs'),chunkZUVP4UK7_cjs=require('./chunk-ZUVP4UK7.cjs'),chunkHS2KNFAB_cjs=require('./chunk-HS2KNFAB.cjs'),chunkZLGWJ4TK_cjs=require('./chunk-ZLGWJ4TK.cjs'),chunkILEZ3NYX_cjs=require('./chunk-ILEZ3NYX.cjs'),chunkNY47CFVP_cjs=require('./chunk-NY47CFVP.cjs'),chunkG3J2EU5D_cjs=require('./chunk-G3J2EU5D.cjs'),chunkWG3UQEV7_cjs=require('./chunk-WG3UQEV7.cjs'),chunkMIOMMB23_cjs=require('./chunk-MIOMMB23.cjs'),chunkFHJJKFAU_cjs=require('./chunk-FHJJKFAU.cjs'),chunkG7SSHELM_cjs=require('./chunk-G7SSHELM.cjs'),zod=require('zod'),graphqlYoga=require('graphql-yoga'),module$1=require('module'),crypto=require('crypto');var _documentCurrentScript=typeof document!=='undefined'?document.currentScript:null;function L(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(L(s.fields,e))return true}if("fields"in t&&t.fields&&L(t.fields,e))return true}return false}var z=class extends Error{errors;constructor(e){super(`Configuration validation failed:
2
2
  ${e.join(`
3
- `)}`),this.name="ConfigValidationError",this.errors=e;}};function X(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=R(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&&(L(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)L(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(i=>i.name==="email"),s=n.fields.some(i=>i.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 J(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=R(n.fields,`global:${n.slug}`);e.push(...t);}return e}function R(n,e){let t=[],s=new Set;for(let i=0;i<n.length;i++){let a=n[i];if(a.type==="row"||a.type==="collapsible"||a.type==="tabs"){if("fields"in a&&a.fields){let r=R(a.fields,e);t.push(...r);}else if("tabs"in a)for(let r of a.tabs){let c=R(r.fields,e);t.push(...c);}continue}let o=a.name;if(!o){t.push(`${e}: Field at index ${i} is missing a "name" property`);continue}if(s.has(o)&&t.push(`${e}: Duplicate field name "${o}"`),s.add(o),/^[a-zA-Z][a-zA-Z0-9_]*$/.test(o)||t.push(`${e}: Field name "${o}" must be alphanumeric with underscores`),!a.type){t.push(`${e}: Field "${o}" is missing a "type" property`);continue}switch(a.type){case "relationship":a.relationTo||t.push(`${e}: Relationship field "${o}" is missing "relationTo"`);break;case "array":if(!a.fields||a.fields.length===0)t.push(`${e}: Array field "${o}" has no fields defined`);else {let r=R(a.fields,`${e}.${o}`);t.push(...r);}break;case "group":if(!a.fields||a.fields.length===0)t.push(`${e}: Group field "${o}" has no fields defined`);else {let r=R(a.fields,`${e}.${o}`);t.push(...r);}break;case "blocks":if(!a.blocks||a.blocks.length===0)t.push(`${e}: Blocks field "${o}" has no blocks defined`);else {let r=Ke(a.blocks,`${e}.${o}`);t.push(...r);}break;case "select":case "radio":if(typeof a.options=="function")break;if((!a.options||a.options.length===0)&&!a.dynamicOptions)t.push(`${e}: ${a.type} field "${o}" has no options defined`);else if(Array.isArray(a.options)){let r=a.options.map(d=>d.value),c=new Set(r);r.length!==c.size&&t.push(`${e}: ${a.type} field "${o}" has duplicate option values`);}break;case "upload":a.relationTo||t.push(`${e}: Upload field "${o}" is missing "relationTo"`);break}"min"in a&&"max"in a&&a.min>a.max&&t.push(`${e}: Field "${o}" has min greater than max`),"minLength"in a&&"maxLength"in a&&a.minLength>a.maxLength&&t.push(`${e}: Field "${o}" has minLength greater than maxLength`),"minRows"in a&&"maxRows"in a&&a.minRows>a.maxRows&&t.push(`${e}: Field "${o}" has minRows greater than maxRows`);}return t}function Ke(n,e){let t=[],s=new Set;for(let i of n){if(!i.slug){t.push(`${e}: Block is missing a "slug" property`);continue}if(s.has(i.slug)&&t.push(`${e}: Duplicate block slug "${i.slug}"`),s.add(i.slug),i.label||t.push(`${e}: Block "${i.slug}" is missing a "label" property`),!i.fields||i.fields.length===0)t.push(`${e}: Block "${i.slug}" has no fields defined`);else {let a=R(i.fields,`${e}.${i.slug}`);t.push(...a);}}return t}function we(n,e=[]){let t=[],s=new Set;for(let i of n)s.has(i.slug)&&t.push(`Duplicate collection slug "${i.slug}"`),s.add(i.slug);for(let i of e)s.has(i.slug)&&t.push(`Duplicate global slug "${i.slug}"`),s.add(i.slug);for(let i of n){let a=X(i);t.push(...a);}for(let i of e){let a=J(i);t.push(...a);}for(let i of n){let a=_(i.fields,n);t.push(...a);}if(t.length>0)throw new z(t)}function _(n,e){let t=[],s=new Set(e.map(i=>i.slug));for(let i of n){if(i.type==="relationship"){let a=Array.isArray(i.relationTo)?i.relationTo:[i.relationTo];for(let o of a)o!=="*"&&!s.has(o)&&console.warn(`[Kyro Config Warning]: Relationship field "${i.name}" references unknown collection "${o}". Select options will not be available until this collection is registered.`);}if(i.type==="upload"){let a=Array.isArray(i.relationTo)?i.relationTo:[i.relationTo];for(let o of a)s.has(o)||t.push(`Upload field "${i.name}" references unknown collection "${o}"`);}if("fields"in i&&i.fields){let a=_(i.fields,e);t.push(...a);}if("tabs"in i)for(let a of i.tabs){let o=_(a.fields,e);t.push(...o);}if("blocks"in i)for(let a of i.blocks){let o=_(a.fields,e);t.push(...o);}}return t}function A(n){switch(n.type){case "text":return Me(n);case "number":return Ve(n);case "checkbox":return Be(n);case "date":return He(n);case "email":return We(n);case "password":return ze(n);case "textarea":return Xe(n);case "select":return Je(n);case "radio":return Ye(n);case "color":return Qe(n);case "richtext":return et(n);case "json":return tt(n);case "code":return st(n);case "upload":return Re(n);case "image":return Re(n);case "markdown":return nt(n);case "relationship":return Ne(n);case "relationship-block":return Ne(n);case "array":return it(n);case "list":return at(n);case "group":return ot(n);case "blocks":return rt(n);case "row":return lt(n);case "collapsible":return ct(n);case "tabs":return dt(n);default:return zod.z.any()}}function Me(n){let e=zod.z.string();return n.minLength&&(e=e.min(n.minLength)),n.maxLength&&(e=e.max(n.maxLength)),n.pattern&&(e=e.regex(new RegExp(n.pattern))),n.variant==="email"&&(e=e.email()),n.variant==="url"&&(e=e.url()),n.hasMany&&(e=zod.z.array(e)),n.required||(e=e.optional().nullable()),n.validate&&(e=T(e,n.validate)),e}function Ve(n){let e=n.integer?zod.z.coerce.number().int():zod.z.coerce.number();return n.min!==void 0&&(e=e.min(n.min)),n.max!==void 0&&(e=e.max(n.max)),n.step&&(e=e.refine(t=>Number.isInteger(t/n.step),`Value must be divisible by ${n.step}`)),n.hasMany&&(e=zod.z.array(e)),n.required||(e=e.optional().nullable()),n.validate&&(e=T(e,n.validate)),e}function Be(n){let e=zod.z.boolean();return n.required||(e=e.optional().nullable()),n.validate&&(e=T(e,n.validate)),e}function He(n){let e=zod.z.string().refine(t=>!isNaN(Date.parse(t)),"Invalid date format");return n.minDate&&(e=e.refine(t=>new Date(t)>=new Date(n.minDate),`Date must be after ${n.minDate}`)),n.maxDate&&(e=e.refine(t=>new Date(t)<=new Date(n.maxDate),`Date must be before ${n.maxDate}`)),n.required||(e=e.optional().nullable()),n.validate&&(e=T(e,n.validate)),e}function We(n){let e=zod.z.string().email("Invalid email");return n.required||(e=e.optional().nullable()),n.validate&&(e=T(e,n.validate)),e}function ze(n){let e=zod.z.string().min(6,"Password must be at least 6 characters");return n.required||(e=e.optional().nullable()),n.validate&&(e=T(e,n.validate)),e}function Xe(n){let e=zod.z.string();return n.minLength&&(e=e.min(n.minLength)),n.maxLength&&(e=e.max(n.maxLength)),n.required||(e=e.optional().nullable()),n.validate&&(e=T(e,n.validate)),e}function Je(n){let e;if(Array.isArray(n.options)&&n.options.length>0){let t=n.options.map(s=>s.value);n.hasMany?e=zod.z.array(zod.z.enum(t)):e=zod.z.enum(t);}else e=n.hasMany?zod.z.array(zod.z.string()):zod.z.string();return n.required||(e=e.optional().nullable()),n.validate&&(e=T(e,n.validate)),e}function Ye(n){let e;if(Array.isArray(n.options)&&n.options.length>0){let t=n.options.map(s=>s.value);e=zod.z.enum(t);}else e=zod.z.string();return n.required||(e=e.optional().nullable()),n.validate&&(e=T(e,n.validate)),e}function Qe(n){let e=zod.z.string();return n.format==="hex"&&(e=e.regex(/^#[0-9A-Fa-f]{6}$/)),n.format==="rgb"&&(e=e.regex(/^rgb\(\s*\d{1,3}\s*,\s*\d{1,3}\s*,\s*\d{1,3}\s*\)$/)),n.format==="hsl"&&(e=e.regex(/^hsl\(\s*\d{1,3}\s*,\s*\d{1,3}%\s*,\s*\d{1,3}%\s*\)$/)),n.required||(e=e.optional().nullable()),n.validate&&(e=T(e,n.validate)),e}function et(n){let e=zod.z.array(zod.z.record(zod.z.any()));return n.required||(e=e.optional().nullable()),n.validate&&(e=T(e,n.validate)),e}function tt(n){let e=zod.z.union([zod.z.record(zod.z.any()),zod.z.array(zod.z.any())]);return n.required||(e=e.optional().nullable()),n.validate&&(e=T(e,n.validate)),e}function st(n){let e=zod.z.string();return n.required||(e=e.optional().nullable()),n.validate&&(e=T(e,n.validate)),e}function Re(n){let e;if(n.relationTo){let t=zod.z.object({id:zod.z.string(),url:zod.z.string().optional(),filename:zod.z.string().optional(),mimeType:zod.z.string().optional()});e=zod.z.union([zod.z.string(),t]);}else e=zod.z.string();return n.hasMany&&(e=zod.z.array(e)),n.required||(e=e.optional().nullable()),n.validate&&(e=T(e,n.validate)),e}function nt(n){let e=zod.z.string();return n.required||(e=e.optional().nullable()),n.validate&&(e=T(e,n.validate)),e}function Ne(n){let e;return Array.isArray(n.relationTo)?e=zod.z.object({relationTo:zod.z.enum(n.relationTo),value:zod.z.string()}):e=zod.z.union([zod.z.string(),zod.z.object({relationTo:zod.z.string(),value:zod.z.string()})]),n.hasMany&&(e=zod.z.array(e)),n.required||(e=e.optional().nullable()),n.validate&&(e=T(e,n.validate)),e}function it(n){let e=zod.z.object(Object.fromEntries(n.fields.filter(s=>s.name).map(s=>[s.name,A(s)]))).passthrough(),t=zod.z.array(e);return n.minRows&&(t=t.min(n.minRows)),n.maxRows&&(t=t.max(n.maxRows)),n.required||(t=t.optional().nullable()),n.validate&&(t=T(t,n.validate)),t}function at(n){let e=zod.z.array(zod.z.string());return n.required||(e=e.optional().nullable()),e}function ot(n){let e=zod.z.object(Object.fromEntries(n.fields.filter(t=>t.name).map(t=>[t.name,A(t)])));return n.required?e:e.optional().nullable()}function rt(n){let e=n.blocks||[];e.map(a=>zod.z.object({blockType:zod.z.literal(a.slug),...Object.fromEntries(a.fields.filter(o=>o.name).map(o=>[o.name,A(o)]))}));let s=e.map(a=>a.slug),i;if(s.length>0){let a=zod.z.object({blockType:zod.z.enum(s)}).catchall(zod.z.any()),o=zod.z.object({blockType:zod.z.string()}).catchall(zod.z.any());i=zod.z.array(zod.z.union([a,o,zod.z.record(zod.z.any())]));}else i=zod.z.array(zod.z.union([zod.z.object({blockType:zod.z.string()}).catchall(zod.z.any()),zod.z.record(zod.z.any())]));return n.minRows&&(i=i.min(n.minRows)),n.maxRows&&(i=i.max(n.maxRows)),n.required||(i=i.optional().nullable()),n.validate&&(i=T(i,n.validate)),i}function lt(n){return zod.z.object(Object.fromEntries(n.fields.filter(t=>t.name).map(t=>[t.name,A(t)])))}function ct(n){return zod.z.object(Object.fromEntries(n.fields.filter(t=>t.name).map(t=>[t.name,A(t)])))}function dt(n){let e={};for(let t of n.tabs)for(let s of t.fields)s.name&&(e[s.name]=A(s));return zod.z.object(e).passthrough().optional()}function T(n,e){return n.refine(async t=>await e(t,{required:false})===true,{message:"Custom validation failed"})}function F(n){let e={};for(let t of n)if(t.type==="tabs"&&"tabs"in t){let s={};for(let i of t.tabs){let a=F(i.fields);Object.assign(s,a);}t.name?e[t.name]=zod.z.object(s).passthrough().optional():Object.assign(e,s);}else if(t.type==="row"&&"fields"in t){let s=F(t.fields);t.name?e[t.name]=zod.z.object(s).passthrough().optional():Object.assign(e,s);}else if(t.type==="collapsible"&&"fields"in t){let s=F(t.fields);t.name?e[t.name]=zod.z.object(s).passthrough().optional():Object.assign(e,s);}else {if(!t.name)continue;e[t.name]=A(t);}return e}function v(n){let e={};for(let t of n)if(t.type==="tabs"&&"tabs"in t){let s={};for(let i of t.tabs){let a=v(i.fields);Object.assign(s,a);}t.name?e[t.name]=zod.z.object(s).passthrough().optional().nullable():Object.assign(e,s);}else if(t.type==="row"&&"fields"in t){let s=v(t.fields);t.name?e[t.name]=zod.z.object(s).passthrough().optional().nullable():Object.assign(e,s);}else if(t.type==="collapsible"&&"fields"in t){let s=v(t.fields);t.name?e[t.name]=zod.z.object(s).passthrough().optional().nullable():Object.assign(e,s);}else if(t.type==="group"&&"fields"in t)t.name?e[t.name]=zod.z.object(v(t.fields)).passthrough().optional().nullable():Object.assign(e,v(t.fields));else {if(!t.name)continue;e[t.name]=A(t).optional().nullable();}return e}function De(n){let e=F(n.fields);return n.timestamps&&(e.createdAt=zod.z.string().optional(),e.updatedAt=zod.z.string().optional()),n.tenantScoped&&(e.tenantId=zod.z.string().optional()),e.id=zod.z.string().optional(),zod.z.object(e).passthrough()}function Fe(n){let e=F(n.fields);return zod.z.object(e).passthrough()}function ke(n){let e={};for(let t of n.fields)if(t.name)if(t.type==="tabs"&&"tabs"in t){let s={};for(let i of t.tabs)for(let a of i.fields)a.name&&(s[a.name]=A(a).optional().nullable());e[t.name]=zod.z.object(s).optional().nullable();}else if(t.type==="row"&&"fields"in t){let s={};for(let i of t.fields)i.name&&(s[i.name]=A(i).optional().nullable());Object.assign(e,s);}else t.type==="collapsible"&&"fields"in t?e[t.name]=zod.z.object(v(t.fields)).optional().nullable():t.type==="group"&&"fields"in t?e[t.name]=zod.z.object(v(t.fields)).optional().nullable():e[t.name]=A(t).optional().nullable();return zod.z.object(e).passthrough()}function Ie(n){let e={};for(let t of n.fields)t.name&&(e[t.name]=zod.z.object({equals:zod.z.any().optional(),not_equals:zod.z.any().optional(),in:zod.z.array(zod.z.any()).optional(),not_in:zod.z.array(zod.z.any()).optional(),greater_than:zod.z.number().optional(),greater_than_equal:zod.z.number().optional(),less_than:zod.z.number().optional(),less_than_equal:zod.z.number().optional(),like:zod.z.string().optional(),not_like:zod.z.string().optional(),contains:zod.z.string().optional(),exists:zod.z.boolean().optional()}).optional());return e.AND=zod.z.array(zod.z.lazy(()=>zod.z.object(e))).optional(),e.OR=zod.z.array(zod.z.lazy(()=>zod.z.object(e))).optional(),zod.z.object(e).optional()}function Pe(n){let e=F(n.fields);return e.id=zod.z.string().optional(),zod.z.object(e).passthrough()}function Oe(n){let e={};for(let t of n.fields)if(t.name)if(t.type==="tabs"&&"tabs"in t){let s={};for(let i of t.tabs)for(let a of i.fields)a.name&&(s[a.name]=A(a).optional().nullable());e[t.name]=zod.z.object(s).optional().nullable();}else t.type==="collapsible"&&"fields"in t?e[t.name]=zod.z.object(v(t.fields)).optional().nullable():t.type==="group"&&"fields"in t?e[t.name]=zod.z.object(v(t.fields)).optional().nullable():e[t.name]=A(t).optional().nullable();return zod.z.object(e).passthrough()}var I=class{storageProviders=chunkXTRY75KC_cjs.f();collections=new Map;globals=new Map;plugins=[];schemaCache=new Map;initialized=false;addCollection(e){if(this.initialized)throw new Error("Cannot add collections after Registry has been initialized");if(this.collections.has(e.slug)){console.warn(`[Registry] Duplicate collection slug "${e.slug}" \u2014 skipping`);return}let t={...e,fields:[...e.fields]};for(let i of this.plugins){let a=i.extensions?.collections?.find(o=>o.slug===t.slug);a&&(t={...t,...a.config,fields:[...t.fields,...a.config.fields||[]]});}if(t.seo){let i=chunkKD7LUCFY_cjs.a(),a=t.fields.findIndex(o=>o.type==="tabs");if(a!==-1){let o=t.fields[a];t.fields[a]={...o,tabs:[...o.tabs,{label:"SEO Settings",fields:i.fields}]};}else t.fields.push(i);}t.fields=this.applyFieldDefaults(t);let s=X(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=J(e);if(t.length>0)throw new Error(`Invalid global config: ${t.join(", ")}`);let s={...e};for(let i of this.plugins){let a=i.extensions?.globals?.find(o=>o.slug===s.slug);a&&(s={...s,...a.config,fields:[...s.fields||[],...a.config.fields||[]]});}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 a=De(s);return this.schemaCache.set(e,a),a}let i=this.globals.get(e);if(i){let a=Pe(i);return this.schemaCache.set(`global:${e}`,a),a}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 i=this.collections.get(e);if(i){let a=Fe(i);return this.schemaCache.set(t,a),a}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 i=this.collections.get(e);if(i){let o=ke(i);return this.schemaCache.set(t,o),o}let a=this.globals.get(e);if(a){let o=Oe(a);return this.schemaCache.set(`global:${e}:update`,o),o}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 i=this.collections.get(e);if(i){let a=Ie(i);return this.schemaCache.set(t,a),a}throw new Error(`No collection found with slug "${e}"`)}getFieldZodSchema(e){return A(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,i=a=>{for(let o of a){if(o.name&&s.set(o.name,o),"fields"in o&&o.fields&&i(o.fields),"tabs"in o)for(let r of o.tabs)i(r.fields);if("blocks"in o)for(let r of o.blocks)i(r.fields);}};return i(t),s}getVisibleFields(e){return this.getFields(e).filter(s=>!s.admin?.hidden)}validate(){let e=this.getCollections(),t=this.getGlobals();we(e,t);}async init(e){this.validate();for(let t of this.plugins){t.init&&await t.init(e||this);let s=t.collections||[];for(let a of s)a.slug&&!this.hasCollection(a.slug)&&this.addCollection(a);let i=t.globals||[];for(let a of i)a.slug&&!this.hasGlobal(a.slug)&&this.addGlobal(a);}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(i=>i.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()}}},k=null;function ut(){return k||(k=new I),k}function pt(){k=null;}function Y(){return k=new I,k}var x=class{name;displayName;adminEntry;version;description;hooks={};collections=[];globals=[];fields=[];extensions={collections:[],globals:[]};adminComponents={};adminStyles=[];serverMiddleware;clientMiddleware;constructor(e){this.name=e;}async init(e){}async beforeInit(e){}async afterInit(e){}getCollections(){return this.collections}getGlobals(){return this.globals}getHooks(){return this.hooks}},j=class{plugins=new Map;hooks=new Map;register(e){if(this.plugins.has(e.name))throw new Error(`Plugin "${e.name}" is already registered`);this.plugins.set(e.name,e);let t=e.getHooks?.()||{};for(let[s,i]of Object.entries(t))if(Array.isArray(i))for(let a of i)this.registerHook(s,a);}unregister(e){let t=this.plugins.get(e);if(!t)return;let s=t.getHooks?.()||{};for(let[i,a]of Object.entries(s))if(Array.isArray(a))for(let o of a)this.unregisterHook(i,o);this.plugins.delete(e);}get(e){return this.plugins.get(e)}getAll(){return Array.from(this.plugins.values())}has(e){return this.plugins.has(e)}registerHook(e,t){this.hooks.has(e)||this.hooks.set(e,[]),this.hooks.get(e).push(t);}unregisterHook(e,t){let s=this.hooks.get(e);if(s){let i=s.indexOf(t);i>-1&&s.splice(i,1);}}async executeHook(e,t){let s=this.hooks.get(e)||[],i=t;for(let a of s)try{let o=await a({...t,data:i});o!==void 0&&(i=o);}catch(o){console.error(`[PluginManager] Error in hook "${e}":`,o);}return i}getAllCollections(){let e=[];for(let t of this.plugins.values()){let s=t.getCollections?.()||[];e.push(...s);}return e}getAllGlobals(){let e=[];for(let t of this.plugins.values()){let s=t.getGlobals?.()||[];e.push(...s);}return e}getAllFields(){let e=[];for(let t of this.plugins.values())e.push(...t.fields);return e}getAdminComponents(){let e={};for(let t of this.plugins.values())Object.assign(e,t.adminComponents);return e}getAdminStyles(){let e=[];for(let t of this.plugins.values())e.push(...t.adminStyles);return e}},Q=class extends x{constructor(){super("seo"),this.displayName="Core SEO",this.description="Advanced SEO features including sitemaps, robots.txt, and structured data",this.adminEntry="@kyro-cms/admin/plugins/seo-admin",this.collections.push({slug:"seo-settings",label:"SEO Settings",fields:[{name:"sitemap",type:"checkbox",label:"Enable Sitemap",defaultValue:true},{name:"robotsTxt",type:"richtext",label:"robots.txt Content"},{name:"canonicalUrl",type:"text",variant:"url",label:"Canonical URL"},{name:"ogImage",type:"text",label:"Default OG Image URL"}]});}},ee=class extends x{constructor(){super("analytics"),this.displayName="Core Analytics",this.description="Built-in privacy-friendly analytics and dashboards",this.collections.push({slug:"analytics-events",label:"Analytics Events",fields:[{name:"name",type:"text",required:true},{name:"properties",type:"json",label:"Event Properties"},{name:"timestamp",type:"date",required:true},{name:"userId",type:"text",label:"User ID"},{name:"sessionId",type:"text",label:"Session ID"}]}),this.adminComponents.AnalyticsDashboard={};}},te=class extends x{constructor(){super("comments"),this.description="Commenting system for products and posts",this.collections.push({slug:"comments",label:"Comments",fields:[{name:"content",type:"richtext",required:true},{name:"author",type:"text",required:true},{name:"email",type:"email"},{name:"approved",type:"checkbox",defaultValue:false},{name:"parent",type:"text",label:"Parent Comment ID"},{name:"resourceType",type:"text",required:true},{name:"resourceId",type:"text",required:true}]}),this.adminComponents.CommentModeration={};}},se=class extends x{constructor(){super("reviews"),this.description="Product reviews and ratings",this.collections.push({slug:"reviews",label:"Reviews",fields:[{name:"rating",type:"number",required:true,min:1,max:5},{name:"title",type:"text"},{name:"content",type:"richtext",required:true},{name:"author",type:"relationship",relationTo:"customers"},{name:"product",type:"relationship",relationTo:"products",required:true},{name:"approved",type:"checkbox",defaultValue:false},{name:"verified",type:"checkbox",label:"Verified Purchase"},{name:"helpful",type:"number",label:"Helpful Count",defaultValue:0}]}),this.adminComponents.ReviewModeration={};}},ne=class extends x{constructor(){super("wishlist"),this.description="Customer wishlists",this.collections.push({slug:"wishlists",label:"Wishlists",fields:[{name:"customer",type:"relationship",relationTo:"customers",required:true},{name:"name",type:"text",label:"Wishlist Name",defaultValue:"My Wishlist"},{name:"items",type:"blocks",label:"Items",blocks:[{slug:"wishlist-item",label:"Item",fields:[{name:"product",type:"relationship",relationTo:"products"},{name:"quantity",type:"number",defaultValue:1},{name:"addedAt",type:"date"},{name:"priority",type:"select",options:[{label:"Low",value:"low"},{label:"Medium",value:"medium"},{label:"High",value:"high"}]}]}]}]});}},_t={SEO:Q,Analytics:ee,Comments:te,Reviews:se,Wishlist:ne};var ft={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 yt(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 $e(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:yt(n,e),cdnUrl:e?.cdnUrl,prefix:e?.prefix,accountId:e?.accountId,publicDevUrl:e?.publicDevUrl}}function gt(n,e,t){let s=t[e.configKey]||{};return $e(n,s)}function ht(n,e,t){let s=t?.[e.configKey]||t;return $e(n,s)}var ie=class extends x{constructor(){super("@kyro-cms/storage-s3"),this.version="1.0.0",this.description="S3-compatible storage (AWS R2 GCS DigitalOcean Backblaze Wasabi)";}async init(e){let t=e.registry?.storageProviders;if(!t)return;let s=this.name;for(let i of Object.values(ft))t.register({type:i.type,displayName:i.displayName,pluginName:s,configKey:i.configKey,configFields:i.configFields,extractConfig:a=>gt(i.type,i,a),extractRawConfig:a=>ht(i.type,i,a),factory:a=>chunkXTRY75KC_cjs.a(a)});}},_e=new ie;var ae=class extends x{constructor(){super("@kyro-cms/storage-cloudinary"),this.version="1.0.0",this.description="Cloudinary image and video storage";}async init(e){let t=e.registry?.storageProviders;t&&t.register({type:"cloudinary",displayName:"Cloudinary",pluginName:this.name,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:s=>({cloudName:s.cloudinary?.cloudName||"",apiKey:s.cloudinary?.apiKey||"",apiSecret:s.cloudinary?.apiSecret||"",folder:s.cloudinary?.folder,uploadPreset:s.cloudinary?.uploadPreset}),extractRawConfig:s=>{let i=s?.cloudinary||s;return {cloudName:i?.cloudName||"",apiKey:i?.apiKey||"",apiSecret:i?.apiSecret||"",folder:i?.folder,uploadPreset:i?.uploadPreset}},factory:s=>chunkXTRY75KC_cjs.b(s)});}},Le=new ae;var oe=class extends x{constructor(){super("@kyro-cms/storage-ftp"),this.version="1.0.0",this.description="FTP/SFTP storage provider";}async init(e){let t=e.registry?.storageProviders;t&&t.register({type:"ftp",displayName:"FTP",pluginName:this.name,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:s=>({host:s.ftp?.host||"",port:s.ftp?.port||21,user:s.ftp?.user||"",password:s.ftp?.password||"",secure:s.ftp?.secure||false,baseUrl:s.ftp?.baseUrl||"",prefix:s.ftp?.prefix,type:"ftp"}),extractRawConfig:s=>{let i=s?.ftp||s;return {host:i?.host||"",port:i?.port||21,user:i?.user||"",password:i?.password||"",secure:i?.secure||false,baseUrl:i?.baseUrl||"",prefix:i?.prefix,type:"ftp"}},factory:s=>chunkXTRY75KC_cjs.c(s)});}},je=new oe;var bt=[_e,Le,je];function N(n,e,t){let s=e.split(".");if(s.length===0)return false;let i=s[0],a=s.slice(1).join(".");for(let o of n)if(o.name===i)if(a){if(o.fields&&Array.isArray(o.fields))return N(o.fields,a,t);if(o.type==="tabs"&&o.tabs&&Array.isArray(o.tabs)){for(let r of o.tabs)if(r.fields&&Array.isArray(r.fields)&&N(r.fields,a,t))return true;return false}if(o.type==="blocks"&&o.blocks&&Array.isArray(o.blocks)){let r=a.split(".")[0],c=a.split(".").slice(1).join(".");if(!c)return false;for(let d of o.blocks)if(d.slug===r&&d.fields&&Array.isArray(d.fields))return N(d.fields,c,t);return false}return o.type==="array"&&o.fields&&Array.isArray(o.fields)?N(o.fields,a,t):false}else return Object.assign(o,t),true;for(let o of n)if(!o.name||o.type==="tabs"||o.type==="row"||o.type==="collapsible"){if(o.fields&&Array.isArray(o.fields)&&N(o.fields,e,t))return true;if(o.type==="tabs"&&o.tabs&&Array.isArray(o.tabs)){for(let c of o.tabs)if(c.fields&&Array.isArray(c.fields)&&N(c.fields,e,t))return true}}return a?false:(n.push({name:i,...t}),true)}function Tt(n,e){if(e)for(let t of n){let s=e[t.slug];if(s){let{fields:i,...a}=s;if(t.admin={...t.admin,...a},i&&t.fields&&Array.isArray(t.fields))for(let[o,r]of Object.entries(i))N(t.fields,o,r);}}}var re=class{registry;db;pubsub;webhookService;settings;pluginManager;wsServer;config;constructor(e){this.config=e,this.registry=Y(),this.db=e.adapter,this.pubsub=new chunkG3J2EU5D_cjs.b(this.registry),this.webhookService=chunkILEZ3NYX_cjs.o(this.db),this.pluginManager=new j;for(let t of bt)this.pluginManager.register(t),this.registry.addPlugin(t);if(e.plugins)for(let t of e.plugins)this.pluginManager.register(t),this.registry.addPlugin(t);e.collections&&e.admin?.collectionOverrides&&Tt(e.collections,e.admin.collectionOverrides),e.collections&&this.registry.addCollections(e.collections),e.globals&&this.registry.addGlobals(e.globals);}async init(){await this.pluginManager.executeHook("beforeInit",{kyro:this}),await this.registry.init(this),await this.pluginManager.executeHook("afterInit",{kyro:this}),this.registry.addGlobalPostInit(chunk65G73T7Z_cjs.a);let e={slug:"plugin-settings",admin:{hidden:true},fields:[{name:"states",type:"json"}]};if(this.registry.addGlobalPostInit(e),!this.db)throw new Error("Database adapter is null \u2014 failed to load at startup. Check the server console for the exact error.");let t={slug:chunkNY47CFVP_cjs.d,fields:[{name:"userId",type:"text",required:true},{name:"name",type:"text",required:true},{name:"key",type:"text",required:true},{name:"keyPrefix",type:"text",required:true},{name:"permissions",type:"json"},{name:"lastUsedAt",type:"date"},{name:"expiresAt",type:"date"}]},s={slug:chunkILEZ3NYX_cjs.f,fields:[{name:"name",type:"text",required:true},{name:"url",type:"text",required:true},{name:"events",type:"json",required:true},{name:"collections",type:"json"},{name:"status",type:"text",required:true},{name:"secret",type:"text"},{name:"headers",type:"json"},{name:"action",type:"text"},{name:"config",type:"json"},{name:"lastTriggered",type:"date"},{name:"lastError",type:"text"}]},i={slug:chunkILEZ3NYX_cjs.g,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"}]},a=this.registry.getGlobals();if(this.db instanceof chunkWG3UQEV7_cjs.c&&this.db.dialect==="postgres"){let o=this.db,r=chunkNY47CFVP_cjs.d.replace(/-/g,"_");o.schema[r]||(o.schema[r]=chunkMIOMMB23_cjs.g);}await this.db.init([...this.registry.getCollections(),t,s,i],a),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 i=await this.db.findOne({collection:"_globals_plugin-settings",where:{},draft:!0});i&&i.states&&(s=i.states);}catch{}for(let i of t)s[i]!==void 0&&e.setPluginEnabled(i,s[i]);}getREST(e){let t=typeof this.config.auth=="object"?this.config.auth:null,s=t?.secret,i=t?.checkSession!==false;return chunkXTRY75KC_cjs.t({registry:this.registry,db:this.db,authSecret:s,authAdapter:this.config.authAdapter,checkSession:i,...e,cors:this.config.cors,webhookService:this.webhookService,settings:this.settings})}getGraphQL(e){let t=chunkHS2KNFAB_cjs.c({registry:this.registry,db:this.db,settings:this.settings});return {fetch:graphqlYoga.createYoga({schema:t,context:async({request:i})=>{let a=chunkNY47CFVP_cjs.f(i),o,r;if(a&&this.db){let d=await chunkNY47CFVP_cjs.e(a,this.db);d.user&&(o=d.user,r=chunkNY47CFVP_cjs.g(d));}let c=e?.tenantId;return {db:this.db,registry:this.registry,user:o,req:i,tenantId:c,apiKey:r,relationLoader:new chunkHS2KNFAB_cjs.a({db:this.db,tenantId:c,user:o})}},graphiql:this.config.graphQL?.disablePlayground!==true,plugins:[]}).fetch,schema:t}}getTRPC(e){return {fetch:async(t,s)=>{let a=new URL(t.url).pathname.replace(/^\/api\/trpc\//,""),[o,...r]=a.split("."),c=r.join(".");if(c=c.replace(/\.(query|mutate|subscribe)$/,""),!o||!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 chunkZUVP4UK7_cjs.a({db:this.db,registry:this.registry,req:t,user:e?.user,tenantId:e?.tenantId,settings:this.settings}),p=chunkZUVP4UK7_cjs.i(d)[o];if(!p)return new Response(JSON.stringify({error:{message:`Collection '${o}' not found`,code:-32601,data:{code:"NOT_FOUND",httpStatus:404}}}),{status:404,headers:{"Content-Type":"application/json"}});let m=p[c];if(typeof m!="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 y={};if(t.method==="POST"||t.method==="PATCH")y=await t.json().catch(()=>({}));else {let C=new URL(t.url).searchParams.get("input");if(C)try{y=JSON.parse(decodeURIComponent(C));}catch{}}let g=y?.["0"]??y,f=await m({...g,collection:o});return new Response(JSON.stringify({result:{data:f}}),{status:200,headers:{"Content-Type":"application/json"}})}catch(y){let g=y.message||"Internal error",f=g.includes("not found")?404:g.includes("denied")||g.includes("authentication required")?403:g.includes("conflict")?409:500,C=f===404?-32601:f===403?-32001:f===409?-32002:-32603;return new Response(JSON.stringify({error:{message:g,code:C,data:{code:"INTERNAL_SERVER_ERROR",httpStatus:f}}}),{status:f,headers:{"Content-Type":"application/json"}})}},router:null}}getWS(){return this.wsServer}async startWebSocket(e){let t=this.settings?.access?.apiAccess;if(t?.wsEnabled===false)return null;let s=async a=>{let o=await chunkNY47CFVP_cjs.e(a,this.db);if(!o.valid)throw new Error(o.error||"Invalid API key");if(!o.user)throw new Error("API key has no associated user");return o.user},i=e?.port||8080;if(globalThis.__KYRO_WS_SERVER__)try{await globalThis.__KYRO_WS_SERVER__.close();}catch{}return this.wsServer=chunkG3J2EU5D_cjs.d({pubsub:this.pubsub,port:i,requireAuth:e?.requireAuth??t?.requireAuth,verifyToken:e?.verifyToken||s}),globalThis.__KYRO_WS_SERVER__=this.wsServer,this.wsServer}async shutdown(){await this.pluginManager.executeHook("beforeServerStop",{kyro:this}),this.wsServer&&await this.wsServer.close(),await this.db.disconnect(),await this.pluginManager.executeHook("afterServerStop",{kyro:this});}};function gs(n){return new re(n)}var At=module$1.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('chunk-O3OYZQN7.cjs', document.baseURI).href))),St="node:sqlite",{DatabaseSync:xt}=At(St);function E(n){let e=[];for(let t of n)if(t.type==="tabs"&&"tabs"in t)for(let s of t.tabs)e.push(...E(s.fields));else t.type==="row"&&"fields"in t?e.push(...E(t.fields)):t.type==="collapsible"&&"fields"in t?e.push(...E(t.fields)):e.push(t);return e}function Et(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 i=new Date(s);isNaN(i.getTime())?s=null:s=i.toISOString();}catch{s=null;}if((t.type==="upload"||t.type==="image")&&s)try{let i=JSON.parse(s);Array.isArray(i)?s=i.map(a=>typeof a=="object"&&a!==null?a:{id:a}):s=typeof i=="object"?i:{id:i};}catch{s={id:s};}if(t.type==="relationship"&&s)try{let i=JSON.parse(s);Array.isArray(i),s=i;}catch{s={relationTo:Array.isArray(t.relationTo)?t.relationTo[0]:t.relationTo,value:s};}if(t.type==="list"&&s)try{let i=JSON.parse(s);s=Array.isArray(i)?i:[];}catch{s=[];}if(t.type==="relationship-block"&&s)try{let i=JSON.parse(s);s=Array.isArray(i)?i:[];}catch{s=[];}return s}function qe(n,e){return Array.isArray(n)?n.map(t=>{if(!t||typeof t!="object")return t;let s=t.data?{...t.data}:void 0;if(!s)return t;let i=e.find(a=>a.slug===t.type||a.slug===t.slug);if(!i||!Array.isArray(i.fields))return t;for(let a of i.fields){if(a.name&&(a.type==="upload"||a.type==="image")&&s[a.name]){let o=s[a.name];Array.isArray(o)?s[a.name]=o.map(r=>typeof r=="string"?{id:r}:r):typeof o=="string"&&(s[a.name]={id:o});}if(a.type==="blocks"&&a.name&&s[a.name]){let o=a.blocks||[];s[a.name]=qe(s[a.name],o);}}return {...t,data:s}}):n}function q(n,e){try{return n.prepare(`PRAGMA table_info(${e})`).all().map(s=>s.name)}catch{return []}}var le=class extends chunkFHJJKFAU_cjs.a{db;path;migrations=new Map;versionsTableName="kyro_versions";constructor(e){super(),this.path=e.path,e.db?this.db=e.db:this.db=null;}async connect(){if(this.db||(this.db=new xt(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 i=e(s),a=o=>typeof o=="boolean"?o?1:0:o===void 0?null:o;return new Proxy(i,{get(o,r,c){if(r==="all")return (...u)=>o.all(...u.map(a));if(r==="get")return (...u)=>o.get(...u.map(a));if(r==="run")return (...u)=>o.run(...u.map(a));let d=Reflect.get(o,r,c);return typeof d=="function"?d.bind(o):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),i=["id TEXT PRIMARY KEY"];for(let r of E(e.fields)){if(!r.name||r.name==="id")continue;let c=this.fieldToSQL(r);c&&i.push(c);}let a=E(e.fields);a.some(r=>r.name==="createdAt")||i.push(`${this.col("createdAt")} TEXT DEFAULT (datetime('now'))`),a.some(r=>r.name==="updatedAt")||i.push(`${this.col("updatedAt")} TEXT DEFAULT (datetime('now'))`),a.some(r=>r.name==="status")||i.push("status TEXT DEFAULT 'draft'"),a.some(r=>r.name==="hasDraft")||i.push("hasDraft INTEGER DEFAULT 0"),e.tenantScoped&&i.push("tenant_id TEXT NOT NULL");let o=q(this.db,s);if(o.length===0){let r=`CREATE TABLE IF NOT EXISTS ${s} (${i.join(", ")})`;this.db.exec(r),this.db.exec(`CREATE INDEX IF NOT EXISTS idx_${s}_status ON ${s}(status)`);for(let c of E(e.fields))c.name&&c.indexed&&this.db.exec(`CREATE INDEX IF NOT EXISTS idx_${s}_${c.name} ON ${s}(${this.col(c.name)})`),c.name&&c.unique&&this.db.exec(`CREATE UNIQUE INDEX IF NOT EXISTS idx_${s}_${c.name}_unique ON ${s}(${this.col(c.name)})`);}else {let r=new Set(o);for(let c of i){let d=c.split(" ")[0].replace(/^"/,"").replace(/"$/,"");if(!r.has(d)&&d!=="id")try{d==="status"?this.db.exec(`ALTER TABLE ${s} ADD COLUMN ${this.col(d)} TEXT DEFAULT 'published'`):d==="hasDraft"?this.db.exec(`ALTER TABLE ${s} ADD COLUMN ${this.col(d)} INTEGER DEFAULT 0`):this.db.exec(`ALTER TABLE ${s} ADD COLUMN ${this.col(d)} TEXT`);}catch{}}}this.migrations.set(s,true);}ensureVersionsTable(){this.db.exec(`
3
+ `)}`),this.name="ConfigValidationError",this.errors=e;}};function X(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=R(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&&(L(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)L(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(i=>i.name==="email"),s=n.fields.some(i=>i.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 J(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=R(n.fields,`global:${n.slug}`);e.push(...t);}return e}function R(n,e){let t=[],s=new Set;for(let i=0;i<n.length;i++){let a=n[i];if(a.type==="row"||a.type==="collapsible"||a.type==="tabs"){if("fields"in a&&a.fields){let r=R(a.fields,e);t.push(...r);}else if("tabs"in a)for(let r of a.tabs){let c=R(r.fields,e);t.push(...c);}continue}let o=a.name;if(!o){t.push(`${e}: Field at index ${i} is missing a "name" property`);continue}if(s.has(o)&&t.push(`${e}: Duplicate field name "${o}"`),s.add(o),/^[a-zA-Z][a-zA-Z0-9_]*$/.test(o)||t.push(`${e}: Field name "${o}" must be alphanumeric with underscores`),!a.type){t.push(`${e}: Field "${o}" is missing a "type" property`);continue}switch(a.type){case "relationship":a.relationTo||t.push(`${e}: Relationship field "${o}" is missing "relationTo"`);break;case "array":if(!a.fields||a.fields.length===0)t.push(`${e}: Array field "${o}" has no fields defined`);else {let r=R(a.fields,`${e}.${o}`);t.push(...r);}break;case "group":if(!a.fields||a.fields.length===0)t.push(`${e}: Group field "${o}" has no fields defined`);else {let r=R(a.fields,`${e}.${o}`);t.push(...r);}break;case "blocks":if(!a.blocks||a.blocks.length===0)t.push(`${e}: Blocks field "${o}" has no blocks defined`);else {let r=Ke(a.blocks,`${e}.${o}`);t.push(...r);}break;case "select":case "radio":if(typeof a.options=="function")break;if((!a.options||a.options.length===0)&&!a.dynamicOptions)t.push(`${e}: ${a.type} field "${o}" has no options defined`);else if(Array.isArray(a.options)){let r=a.options.map(d=>d.value),c=new Set(r);r.length!==c.size&&t.push(`${e}: ${a.type} field "${o}" has duplicate option values`);}break;case "upload":a.relationTo||t.push(`${e}: Upload field "${o}" is missing "relationTo"`);break}"min"in a&&"max"in a&&a.min>a.max&&t.push(`${e}: Field "${o}" has min greater than max`),"minLength"in a&&"maxLength"in a&&a.minLength>a.maxLength&&t.push(`${e}: Field "${o}" has minLength greater than maxLength`),"minRows"in a&&"maxRows"in a&&a.minRows>a.maxRows&&t.push(`${e}: Field "${o}" has minRows greater than maxRows`);}return t}function Ke(n,e){let t=[],s=new Set;for(let i of n){if(!i.slug){t.push(`${e}: Block is missing a "slug" property`);continue}if(s.has(i.slug)&&t.push(`${e}: Duplicate block slug "${i.slug}"`),s.add(i.slug),i.label||t.push(`${e}: Block "${i.slug}" is missing a "label" property`),!i.fields||i.fields.length===0)t.push(`${e}: Block "${i.slug}" has no fields defined`);else {let a=R(i.fields,`${e}.${i.slug}`);t.push(...a);}}return t}function we(n,e=[]){let t=[],s=new Set;for(let i of n)s.has(i.slug)&&t.push(`Duplicate collection slug "${i.slug}"`),s.add(i.slug);for(let i of e)s.has(i.slug)&&t.push(`Duplicate global slug "${i.slug}"`),s.add(i.slug);for(let i of n){let a=X(i);t.push(...a);}for(let i of e){let a=J(i);t.push(...a);}for(let i of n){let a=_(i.fields,n);t.push(...a);}if(t.length>0)throw new z(t)}function _(n,e){let t=[],s=new Set(e.map(i=>i.slug));for(let i of n){if(i.type==="relationship"){let a=Array.isArray(i.relationTo)?i.relationTo:[i.relationTo];for(let o of a)o!=="*"&&!s.has(o)&&console.warn(`[Kyro Config Warning]: Relationship field "${i.name}" references unknown collection "${o}". Select options will not be available until this collection is registered.`);}if(i.type==="upload"){let a=Array.isArray(i.relationTo)?i.relationTo:[i.relationTo];for(let o of a)s.has(o)||t.push(`Upload field "${i.name}" references unknown collection "${o}"`);}if("fields"in i&&i.fields){let a=_(i.fields,e);t.push(...a);}if("tabs"in i)for(let a of i.tabs){let o=_(a.fields,e);t.push(...o);}if("blocks"in i)for(let a of i.blocks){let o=_(a.fields,e);t.push(...o);}}return t}function A(n){switch(n.type){case "text":return Me(n);case "number":return Ve(n);case "checkbox":return Be(n);case "date":return He(n);case "email":return We(n);case "password":return ze(n);case "textarea":return Xe(n);case "select":return Je(n);case "radio":return Ye(n);case "color":return Qe(n);case "richtext":return et(n);case "json":return tt(n);case "code":return st(n);case "upload":return Re(n);case "image":return Re(n);case "markdown":return nt(n);case "relationship":return Ne(n);case "relationship-block":return Ne(n);case "array":return it(n);case "list":return at(n);case "group":return ot(n);case "blocks":return rt(n);case "row":return lt(n);case "collapsible":return ct(n);case "tabs":return dt(n);default:return zod.z.any()}}function Me(n){let e=zod.z.string();return n.minLength&&(e=e.min(n.minLength)),n.maxLength&&(e=e.max(n.maxLength)),n.pattern&&(e=e.regex(new RegExp(n.pattern))),n.variant==="email"&&(e=e.email()),n.variant==="url"&&(e=e.url()),n.hasMany&&(e=zod.z.array(e)),n.required||(e=e.optional().nullable()),n.validate&&(e=T(e,n.validate)),e}function Ve(n){let e=n.integer?zod.z.coerce.number().int():zod.z.coerce.number();return n.min!==void 0&&(e=e.min(n.min)),n.max!==void 0&&(e=e.max(n.max)),n.step&&(e=e.refine(t=>Number.isInteger(t/n.step),`Value must be divisible by ${n.step}`)),n.hasMany&&(e=zod.z.array(e)),n.required||(e=e.optional().nullable()),n.validate&&(e=T(e,n.validate)),e}function Be(n){let e=zod.z.boolean();return n.required||(e=e.optional().nullable()),n.validate&&(e=T(e,n.validate)),e}function He(n){let e=zod.z.string().refine(t=>!isNaN(Date.parse(t)),"Invalid date format");return n.minDate&&(e=e.refine(t=>new Date(t)>=new Date(n.minDate),`Date must be after ${n.minDate}`)),n.maxDate&&(e=e.refine(t=>new Date(t)<=new Date(n.maxDate),`Date must be before ${n.maxDate}`)),n.required||(e=e.optional().nullable()),n.validate&&(e=T(e,n.validate)),e}function We(n){let e=zod.z.string().email("Invalid email");return n.required||(e=e.optional().nullable()),n.validate&&(e=T(e,n.validate)),e}function ze(n){let e=zod.z.string().min(6,"Password must be at least 6 characters");return n.required||(e=e.optional().nullable()),n.validate&&(e=T(e,n.validate)),e}function Xe(n){let e=zod.z.string();return n.minLength&&(e=e.min(n.minLength)),n.maxLength&&(e=e.max(n.maxLength)),n.required||(e=e.optional().nullable()),n.validate&&(e=T(e,n.validate)),e}function Je(n){let e;if(Array.isArray(n.options)&&n.options.length>0){let t=n.options.map(s=>s.value);n.hasMany?e=zod.z.array(zod.z.enum(t)):e=zod.z.enum(t);}else e=n.hasMany?zod.z.array(zod.z.string()):zod.z.string();return n.required||(e=e.optional().nullable()),n.validate&&(e=T(e,n.validate)),e}function Ye(n){let e;if(Array.isArray(n.options)&&n.options.length>0){let t=n.options.map(s=>s.value);e=zod.z.enum(t);}else e=zod.z.string();return n.required||(e=e.optional().nullable()),n.validate&&(e=T(e,n.validate)),e}function Qe(n){let e=zod.z.string();return n.format==="hex"&&(e=e.regex(/^#[0-9A-Fa-f]{6}$/)),n.format==="rgb"&&(e=e.regex(/^rgb\(\s*\d{1,3}\s*,\s*\d{1,3}\s*,\s*\d{1,3}\s*\)$/)),n.format==="hsl"&&(e=e.regex(/^hsl\(\s*\d{1,3}\s*,\s*\d{1,3}%\s*,\s*\d{1,3}%\s*\)$/)),n.required||(e=e.optional().nullable()),n.validate&&(e=T(e,n.validate)),e}function et(n){let e=zod.z.array(zod.z.record(zod.z.any()));return n.required||(e=e.optional().nullable()),n.validate&&(e=T(e,n.validate)),e}function tt(n){let e=zod.z.union([zod.z.record(zod.z.any()),zod.z.array(zod.z.any())]);return n.required||(e=e.optional().nullable()),n.validate&&(e=T(e,n.validate)),e}function st(n){let e=zod.z.string();return n.required||(e=e.optional().nullable()),n.validate&&(e=T(e,n.validate)),e}function Re(n){let e;if(n.relationTo){let t=zod.z.object({id:zod.z.string(),url:zod.z.string().optional(),filename:zod.z.string().optional(),mimeType:zod.z.string().optional()});e=zod.z.union([zod.z.string(),t]);}else e=zod.z.string();return n.hasMany&&(e=zod.z.array(e)),n.required||(e=e.optional().nullable()),n.validate&&(e=T(e,n.validate)),e}function nt(n){let e=zod.z.string();return n.required||(e=e.optional().nullable()),n.validate&&(e=T(e,n.validate)),e}function Ne(n){let e;return Array.isArray(n.relationTo)?e=zod.z.object({relationTo:zod.z.enum(n.relationTo),value:zod.z.string()}):e=zod.z.union([zod.z.string(),zod.z.object({relationTo:zod.z.string(),value:zod.z.string()})]),n.hasMany&&(e=zod.z.array(e)),n.required||(e=e.optional().nullable()),n.validate&&(e=T(e,n.validate)),e}function it(n){let e=zod.z.object(Object.fromEntries(n.fields.filter(s=>s.name).map(s=>[s.name,A(s)]))).passthrough(),t=zod.z.array(e);return n.minRows&&(t=t.min(n.minRows)),n.maxRows&&(t=t.max(n.maxRows)),n.required||(t=t.optional().nullable()),n.validate&&(t=T(t,n.validate)),t}function at(n){let e=zod.z.array(zod.z.string());return n.required||(e=e.optional().nullable()),e}function ot(n){let e=zod.z.object(Object.fromEntries(n.fields.filter(t=>t.name).map(t=>[t.name,A(t)])));return n.required?e:e.optional().nullable()}function rt(n){let e=n.blocks||[];e.map(a=>zod.z.object({blockType:zod.z.literal(a.slug),...Object.fromEntries(a.fields.filter(o=>o.name).map(o=>[o.name,A(o)]))}));let s=e.map(a=>a.slug),i;if(s.length>0){let a=zod.z.object({blockType:zod.z.enum(s)}).catchall(zod.z.any()),o=zod.z.object({blockType:zod.z.string()}).catchall(zod.z.any());i=zod.z.array(zod.z.union([a,o,zod.z.record(zod.z.any())]));}else i=zod.z.array(zod.z.union([zod.z.object({blockType:zod.z.string()}).catchall(zod.z.any()),zod.z.record(zod.z.any())]));return n.minRows&&(i=i.min(n.minRows)),n.maxRows&&(i=i.max(n.maxRows)),n.required||(i=i.optional().nullable()),n.validate&&(i=T(i,n.validate)),i}function lt(n){return zod.z.object(Object.fromEntries(n.fields.filter(t=>t.name).map(t=>[t.name,A(t)])))}function ct(n){return zod.z.object(Object.fromEntries(n.fields.filter(t=>t.name).map(t=>[t.name,A(t)])))}function dt(n){let e={};for(let t of n.tabs)for(let s of t.fields)s.name&&(e[s.name]=A(s));return zod.z.object(e).passthrough().optional()}function T(n,e){return n.refine(async t=>await e(t,{required:false})===true,{message:"Custom validation failed"})}function F(n){let e={};for(let t of n)if(t.type==="tabs"&&"tabs"in t){let s={};for(let i of t.tabs){let a=F(i.fields);Object.assign(s,a);}t.name?e[t.name]=zod.z.object(s).passthrough().optional():Object.assign(e,s);}else if(t.type==="row"&&"fields"in t){let s=F(t.fields);t.name?e[t.name]=zod.z.object(s).passthrough().optional():Object.assign(e,s);}else if(t.type==="collapsible"&&"fields"in t){let s=F(t.fields);t.name?e[t.name]=zod.z.object(s).passthrough().optional():Object.assign(e,s);}else {if(!t.name)continue;e[t.name]=A(t);}return e}function v(n){let e={};for(let t of n)if(t.type==="tabs"&&"tabs"in t){let s={};for(let i of t.tabs){let a=v(i.fields);Object.assign(s,a);}t.name?e[t.name]=zod.z.object(s).passthrough().optional().nullable():Object.assign(e,s);}else if(t.type==="row"&&"fields"in t){let s=v(t.fields);t.name?e[t.name]=zod.z.object(s).passthrough().optional().nullable():Object.assign(e,s);}else if(t.type==="collapsible"&&"fields"in t){let s=v(t.fields);t.name?e[t.name]=zod.z.object(s).passthrough().optional().nullable():Object.assign(e,s);}else if(t.type==="group"&&"fields"in t)t.name?e[t.name]=zod.z.object(v(t.fields)).passthrough().optional().nullable():Object.assign(e,v(t.fields));else {if(!t.name)continue;e[t.name]=A(t).optional().nullable();}return e}function De(n){let e=F(n.fields);return n.timestamps&&(e.createdAt=zod.z.string().optional(),e.updatedAt=zod.z.string().optional()),n.tenantScoped&&(e.tenantId=zod.z.string().optional()),e.id=zod.z.string().optional(),zod.z.object(e).passthrough()}function Fe(n){let e=F(n.fields);return zod.z.object(e).passthrough()}function ke(n){let e={};for(let t of n.fields)if(t.name)if(t.type==="tabs"&&"tabs"in t){let s={};for(let i of t.tabs)for(let a of i.fields)a.name&&(s[a.name]=A(a).optional().nullable());e[t.name]=zod.z.object(s).optional().nullable();}else if(t.type==="row"&&"fields"in t){let s={};for(let i of t.fields)i.name&&(s[i.name]=A(i).optional().nullable());Object.assign(e,s);}else t.type==="collapsible"&&"fields"in t?e[t.name]=zod.z.object(v(t.fields)).optional().nullable():t.type==="group"&&"fields"in t?e[t.name]=zod.z.object(v(t.fields)).optional().nullable():e[t.name]=A(t).optional().nullable();return zod.z.object(e).passthrough()}function Ie(n){let e={};for(let t of n.fields)t.name&&(e[t.name]=zod.z.object({equals:zod.z.any().optional(),not_equals:zod.z.any().optional(),in:zod.z.array(zod.z.any()).optional(),not_in:zod.z.array(zod.z.any()).optional(),greater_than:zod.z.number().optional(),greater_than_equal:zod.z.number().optional(),less_than:zod.z.number().optional(),less_than_equal:zod.z.number().optional(),like:zod.z.string().optional(),not_like:zod.z.string().optional(),contains:zod.z.string().optional(),exists:zod.z.boolean().optional()}).optional());return e.AND=zod.z.array(zod.z.lazy(()=>zod.z.object(e))).optional(),e.OR=zod.z.array(zod.z.lazy(()=>zod.z.object(e))).optional(),zod.z.object(e).optional()}function Pe(n){let e=F(n.fields);return e.id=zod.z.string().optional(),zod.z.object(e).passthrough()}function Oe(n){let e={};for(let t of n.fields)if(t.name)if(t.type==="tabs"&&"tabs"in t){let s={};for(let i of t.tabs)for(let a of i.fields)a.name&&(s[a.name]=A(a).optional().nullable());e[t.name]=zod.z.object(s).optional().nullable();}else t.type==="collapsible"&&"fields"in t?e[t.name]=zod.z.object(v(t.fields)).optional().nullable():t.type==="group"&&"fields"in t?e[t.name]=zod.z.object(v(t.fields)).optional().nullable():e[t.name]=A(t).optional().nullable();return zod.z.object(e).passthrough()}var I=class{storageProviders=chunkZLGWJ4TK_cjs.f();collections=new Map;globals=new Map;plugins=[];schemaCache=new Map;initialized=false;addCollection(e){if(this.initialized)throw new Error("Cannot add collections after Registry has been initialized");if(this.collections.has(e.slug)){console.warn(`[Registry] Duplicate collection slug "${e.slug}" \u2014 skipping`);return}let t={...e,fields:[...e.fields]};for(let i of this.plugins){let a=i.extensions?.collections?.find(o=>o.slug===t.slug);a&&(t={...t,...a.config,fields:[...t.fields,...a.config.fields||[]]});}if(t.seo){let i=chunkKD7LUCFY_cjs.a(),a=t.fields.findIndex(o=>o.type==="tabs");if(a!==-1){let o=t.fields[a];t.fields[a]={...o,tabs:[...o.tabs,{label:"SEO Settings",fields:i.fields}]};}else t.fields.push(i);}t.fields=this.applyFieldDefaults(t);let s=X(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=J(e);if(t.length>0)throw new Error(`Invalid global config: ${t.join(", ")}`);let s={...e};for(let i of this.plugins){let a=i.extensions?.globals?.find(o=>o.slug===s.slug);a&&(s={...s,...a.config,fields:[...s.fields||[],...a.config.fields||[]]});}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 a=De(s);return this.schemaCache.set(e,a),a}let i=this.globals.get(e);if(i){let a=Pe(i);return this.schemaCache.set(`global:${e}`,a),a}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 i=this.collections.get(e);if(i){let a=Fe(i);return this.schemaCache.set(t,a),a}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 i=this.collections.get(e);if(i){let o=ke(i);return this.schemaCache.set(t,o),o}let a=this.globals.get(e);if(a){let o=Oe(a);return this.schemaCache.set(`global:${e}:update`,o),o}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 i=this.collections.get(e);if(i){let a=Ie(i);return this.schemaCache.set(t,a),a}throw new Error(`No collection found with slug "${e}"`)}getFieldZodSchema(e){return A(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,i=a=>{for(let o of a){if(o.name&&s.set(o.name,o),"fields"in o&&o.fields&&i(o.fields),"tabs"in o)for(let r of o.tabs)i(r.fields);if("blocks"in o)for(let r of o.blocks)i(r.fields);}};return i(t),s}getVisibleFields(e){return this.getFields(e).filter(s=>!s.admin?.hidden)}validate(){let e=this.getCollections(),t=this.getGlobals();we(e,t);}async init(e){this.validate();for(let t of this.plugins){t.init&&await t.init(e||this);let s=t.collections||[];for(let a of s)a.slug&&!this.hasCollection(a.slug)&&this.addCollection(a);let i=t.globals||[];for(let a of i)a.slug&&!this.hasGlobal(a.slug)&&this.addGlobal(a);}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(i=>i.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()}}},k=null;function ut(){return k||(k=new I),k}function pt(){k=null;}function Y(){return k=new I,k}var x=class{name;displayName;adminEntry;version;description;hooks={};collections=[];globals=[];fields=[];extensions={collections:[],globals:[]};adminComponents={};adminStyles=[];serverMiddleware;clientMiddleware;constructor(e){this.name=e;}async init(e){}async beforeInit(e){}async afterInit(e){}getCollections(){return this.collections}getGlobals(){return this.globals}getHooks(){return this.hooks}},j=class{plugins=new Map;hooks=new Map;register(e){if(this.plugins.has(e.name))throw new Error(`Plugin "${e.name}" is already registered`);this.plugins.set(e.name,e);let t=e.getHooks?.()||{};for(let[s,i]of Object.entries(t))if(Array.isArray(i))for(let a of i)this.registerHook(s,a);}unregister(e){let t=this.plugins.get(e);if(!t)return;let s=t.getHooks?.()||{};for(let[i,a]of Object.entries(s))if(Array.isArray(a))for(let o of a)this.unregisterHook(i,o);this.plugins.delete(e);}get(e){return this.plugins.get(e)}getAll(){return Array.from(this.plugins.values())}has(e){return this.plugins.has(e)}registerHook(e,t){this.hooks.has(e)||this.hooks.set(e,[]),this.hooks.get(e).push(t);}unregisterHook(e,t){let s=this.hooks.get(e);if(s){let i=s.indexOf(t);i>-1&&s.splice(i,1);}}async executeHook(e,t){let s=this.hooks.get(e)||[],i=t;for(let a of s)try{let o=await a({...t,data:i});o!==void 0&&(i=o);}catch(o){console.error(`[PluginManager] Error in hook "${e}":`,o);}return i}getAllCollections(){let e=[];for(let t of this.plugins.values()){let s=t.getCollections?.()||[];e.push(...s);}return e}getAllGlobals(){let e=[];for(let t of this.plugins.values()){let s=t.getGlobals?.()||[];e.push(...s);}return e}getAllFields(){let e=[];for(let t of this.plugins.values())e.push(...t.fields);return e}getAdminComponents(){let e={};for(let t of this.plugins.values())Object.assign(e,t.adminComponents);return e}getAdminStyles(){let e=[];for(let t of this.plugins.values())e.push(...t.adminStyles);return e}},Q=class extends x{constructor(){super("seo"),this.displayName="Core SEO",this.description="Advanced SEO features including sitemaps, robots.txt, and structured data",this.adminEntry="@kyro-cms/admin/plugins/seo-admin",this.collections.push({slug:"seo-settings",label:"SEO Settings",fields:[{name:"sitemap",type:"checkbox",label:"Enable Sitemap",defaultValue:true},{name:"robotsTxt",type:"richtext",label:"robots.txt Content"},{name:"canonicalUrl",type:"text",variant:"url",label:"Canonical URL"},{name:"ogImage",type:"text",label:"Default OG Image URL"}]});}},ee=class extends x{constructor(){super("analytics"),this.displayName="Core Analytics",this.description="Built-in privacy-friendly analytics and dashboards",this.collections.push({slug:"analytics-events",label:"Analytics Events",fields:[{name:"name",type:"text",required:true},{name:"properties",type:"json",label:"Event Properties"},{name:"timestamp",type:"date",required:true},{name:"userId",type:"text",label:"User ID"},{name:"sessionId",type:"text",label:"Session ID"}]}),this.adminComponents.AnalyticsDashboard={};}},te=class extends x{constructor(){super("comments"),this.description="Commenting system for products and posts",this.collections.push({slug:"comments",label:"Comments",fields:[{name:"content",type:"richtext",required:true},{name:"author",type:"text",required:true},{name:"email",type:"email"},{name:"approved",type:"checkbox",defaultValue:false},{name:"parent",type:"text",label:"Parent Comment ID"},{name:"resourceType",type:"text",required:true},{name:"resourceId",type:"text",required:true}]}),this.adminComponents.CommentModeration={};}},se=class extends x{constructor(){super("reviews"),this.description="Product reviews and ratings",this.collections.push({slug:"reviews",label:"Reviews",fields:[{name:"rating",type:"number",required:true,min:1,max:5},{name:"title",type:"text"},{name:"content",type:"richtext",required:true},{name:"author",type:"relationship",relationTo:"customers"},{name:"product",type:"relationship",relationTo:"products",required:true},{name:"approved",type:"checkbox",defaultValue:false},{name:"verified",type:"checkbox",label:"Verified Purchase"},{name:"helpful",type:"number",label:"Helpful Count",defaultValue:0}]}),this.adminComponents.ReviewModeration={};}},ne=class extends x{constructor(){super("wishlist"),this.description="Customer wishlists",this.collections.push({slug:"wishlists",label:"Wishlists",fields:[{name:"customer",type:"relationship",relationTo:"customers",required:true},{name:"name",type:"text",label:"Wishlist Name",defaultValue:"My Wishlist"},{name:"items",type:"blocks",label:"Items",blocks:[{slug:"wishlist-item",label:"Item",fields:[{name:"product",type:"relationship",relationTo:"products"},{name:"quantity",type:"number",defaultValue:1},{name:"addedAt",type:"date"},{name:"priority",type:"select",options:[{label:"Low",value:"low"},{label:"Medium",value:"medium"},{label:"High",value:"high"}]}]}]}]});}},_t={SEO:Q,Analytics:ee,Comments:te,Reviews:se,Wishlist:ne};var ft={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 yt(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 $e(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:yt(n,e),cdnUrl:e?.cdnUrl,prefix:e?.prefix,accountId:e?.accountId,publicDevUrl:e?.publicDevUrl}}function gt(n,e,t){let s=t[e.configKey]||{};return $e(n,s)}function ht(n,e,t){let s=t?.[e.configKey]||t;return $e(n,s)}var ie=class extends x{constructor(){super("@kyro-cms/storage-s3"),this.version="1.0.0",this.description="S3-compatible storage (AWS R2 GCS DigitalOcean Backblaze Wasabi)";}async init(e){let t=e.registry?.storageProviders;if(!t)return;let s=this.name;for(let i of Object.values(ft))t.register({type:i.type,displayName:i.displayName,pluginName:s,configKey:i.configKey,configFields:i.configFields,extractConfig:a=>gt(i.type,i,a),extractRawConfig:a=>ht(i.type,i,a),factory:a=>chunkZLGWJ4TK_cjs.a(a)});}},_e=new ie;var ae=class extends x{constructor(){super("@kyro-cms/storage-cloudinary"),this.version="1.0.0",this.description="Cloudinary image and video storage";}async init(e){let t=e.registry?.storageProviders;t&&t.register({type:"cloudinary",displayName:"Cloudinary",pluginName:this.name,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:s=>({cloudName:s.cloudinary?.cloudName||"",apiKey:s.cloudinary?.apiKey||"",apiSecret:s.cloudinary?.apiSecret||"",folder:s.cloudinary?.folder,uploadPreset:s.cloudinary?.uploadPreset}),extractRawConfig:s=>{let i=s?.cloudinary||s;return {cloudName:i?.cloudName||"",apiKey:i?.apiKey||"",apiSecret:i?.apiSecret||"",folder:i?.folder,uploadPreset:i?.uploadPreset}},factory:s=>chunkZLGWJ4TK_cjs.b(s)});}},Le=new ae;var oe=class extends x{constructor(){super("@kyro-cms/storage-ftp"),this.version="1.0.0",this.description="FTP/SFTP storage provider";}async init(e){let t=e.registry?.storageProviders;t&&t.register({type:"ftp",displayName:"FTP",pluginName:this.name,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:s=>({host:s.ftp?.host||"",port:s.ftp?.port||21,user:s.ftp?.user||"",password:s.ftp?.password||"",secure:s.ftp?.secure||false,baseUrl:s.ftp?.baseUrl||"",prefix:s.ftp?.prefix,type:"ftp"}),extractRawConfig:s=>{let i=s?.ftp||s;return {host:i?.host||"",port:i?.port||21,user:i?.user||"",password:i?.password||"",secure:i?.secure||false,baseUrl:i?.baseUrl||"",prefix:i?.prefix,type:"ftp"}},factory:s=>chunkZLGWJ4TK_cjs.c(s)});}},je=new oe;var bt=[_e,Le,je];function N(n,e,t){let s=e.split(".");if(s.length===0)return false;let i=s[0],a=s.slice(1).join(".");for(let o of n)if(o.name===i)if(a){if(o.fields&&Array.isArray(o.fields))return N(o.fields,a,t);if(o.type==="tabs"&&o.tabs&&Array.isArray(o.tabs)){for(let r of o.tabs)if(r.fields&&Array.isArray(r.fields)&&N(r.fields,a,t))return true;return false}if(o.type==="blocks"&&o.blocks&&Array.isArray(o.blocks)){let r=a.split(".")[0],c=a.split(".").slice(1).join(".");if(!c)return false;for(let d of o.blocks)if(d.slug===r&&d.fields&&Array.isArray(d.fields))return N(d.fields,c,t);return false}return o.type==="array"&&o.fields&&Array.isArray(o.fields)?N(o.fields,a,t):false}else return Object.assign(o,t),true;for(let o of n)if(!o.name||o.type==="tabs"||o.type==="row"||o.type==="collapsible"){if(o.fields&&Array.isArray(o.fields)&&N(o.fields,e,t))return true;if(o.type==="tabs"&&o.tabs&&Array.isArray(o.tabs)){for(let c of o.tabs)if(c.fields&&Array.isArray(c.fields)&&N(c.fields,e,t))return true}}return a?false:(n.push({name:i,...t}),true)}function Tt(n,e){if(e)for(let t of n){let s=e[t.slug];if(s){let{fields:i,...a}=s;if(t.admin={...t.admin,...a},i&&t.fields&&Array.isArray(t.fields))for(let[o,r]of Object.entries(i))N(t.fields,o,r);}}}var re=class{registry;db;pubsub;webhookService;settings;pluginManager;wsServer;config;constructor(e){this.config=e,this.registry=Y(),this.db=e.adapter,this.pubsub=new chunkG3J2EU5D_cjs.b(this.registry),this.webhookService=chunkILEZ3NYX_cjs.o(this.db),this.pluginManager=new j;for(let t of bt)this.pluginManager.register(t),this.registry.addPlugin(t);if(e.plugins)for(let t of e.plugins)this.pluginManager.register(t),this.registry.addPlugin(t);e.collections&&e.admin?.collectionOverrides&&Tt(e.collections,e.admin.collectionOverrides),e.collections&&this.registry.addCollections(e.collections),e.globals&&this.registry.addGlobals(e.globals);}async init(){await this.pluginManager.executeHook("beforeInit",{kyro:this}),await this.registry.init(this),await this.pluginManager.executeHook("afterInit",{kyro:this}),this.registry.addGlobalPostInit(chunk65G73T7Z_cjs.a);let e={slug:"plugin-settings",admin:{hidden:true},fields:[{name:"states",type:"json"}]};if(this.registry.addGlobalPostInit(e),!this.db)throw new Error("Database adapter is null \u2014 failed to load at startup. Check the server console for the exact error.");let t={slug:chunkNY47CFVP_cjs.d,fields:[{name:"userId",type:"text",required:true},{name:"name",type:"text",required:true},{name:"key",type:"text",required:true},{name:"keyPrefix",type:"text",required:true},{name:"permissions",type:"json"},{name:"lastUsedAt",type:"date"},{name:"expiresAt",type:"date"}]},s={slug:chunkILEZ3NYX_cjs.f,fields:[{name:"name",type:"text",required:true},{name:"url",type:"text",required:true},{name:"events",type:"json",required:true},{name:"collections",type:"json"},{name:"status",type:"text",required:true},{name:"secret",type:"text"},{name:"headers",type:"json"},{name:"action",type:"text"},{name:"config",type:"json"},{name:"lastTriggered",type:"date"},{name:"lastError",type:"text"}]},i={slug:chunkILEZ3NYX_cjs.g,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"}]},a=this.registry.getGlobals();if(this.db instanceof chunkWG3UQEV7_cjs.c&&this.db.dialect==="postgres"){let o=this.db,r=chunkNY47CFVP_cjs.d.replace(/-/g,"_");o.schema[r]||(o.schema[r]=chunkMIOMMB23_cjs.g);}await this.db.init([...this.registry.getCollections(),t,s,i],a),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 i=await this.db.findOne({collection:"_globals_plugin-settings",where:{},draft:!0});i&&i.states&&(s=i.states);}catch{}for(let i of t)s[i]!==void 0&&e.setPluginEnabled(i,s[i]);}getREST(e){let t=typeof this.config.auth=="object"?this.config.auth:null,s=t?.secret,i=t?.checkSession!==false;return chunkZLGWJ4TK_cjs.t({registry:this.registry,db:this.db,authSecret:s,authAdapter:this.config.authAdapter,checkSession:i,...e,cors:this.config.cors,webhookService:this.webhookService,settings:this.settings})}getGraphQL(e){let t=chunkHS2KNFAB_cjs.c({registry:this.registry,db:this.db,settings:this.settings});return {fetch:graphqlYoga.createYoga({schema:t,context:async({request:i})=>{let a=chunkNY47CFVP_cjs.f(i),o,r;if(a&&this.db){let d=await chunkNY47CFVP_cjs.e(a,this.db);d.user&&(o=d.user,r=chunkNY47CFVP_cjs.g(d));}let c=e?.tenantId;return {db:this.db,registry:this.registry,user:o,req:i,tenantId:c,apiKey:r,relationLoader:new chunkHS2KNFAB_cjs.a({db:this.db,tenantId:c,user:o})}},graphiql:this.config.graphQL?.disablePlayground!==true,plugins:[]}).fetch,schema:t}}getTRPC(e){return {fetch:async(t,s)=>{let a=new URL(t.url).pathname.replace(/^\/api\/trpc\//,""),[o,...r]=a.split("."),c=r.join(".");if(c=c.replace(/\.(query|mutate|subscribe)$/,""),!o||!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 chunkZUVP4UK7_cjs.a({db:this.db,registry:this.registry,req:t,user:e?.user,tenantId:e?.tenantId,settings:this.settings}),p=chunkZUVP4UK7_cjs.i(d)[o];if(!p)return new Response(JSON.stringify({error:{message:`Collection '${o}' not found`,code:-32601,data:{code:"NOT_FOUND",httpStatus:404}}}),{status:404,headers:{"Content-Type":"application/json"}});let m=p[c];if(typeof m!="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 y={};if(t.method==="POST"||t.method==="PATCH")y=await t.json().catch(()=>({}));else {let C=new URL(t.url).searchParams.get("input");if(C)try{y=JSON.parse(decodeURIComponent(C));}catch{}}let g=y?.["0"]??y,f=await m({...g,collection:o});return new Response(JSON.stringify({result:{data:f}}),{status:200,headers:{"Content-Type":"application/json"}})}catch(y){let g=y.message||"Internal error",f=g.includes("not found")?404:g.includes("denied")||g.includes("authentication required")?403:g.includes("conflict")?409:500,C=f===404?-32601:f===403?-32001:f===409?-32002:-32603;return new Response(JSON.stringify({error:{message:g,code:C,data:{code:"INTERNAL_SERVER_ERROR",httpStatus:f}}}),{status:f,headers:{"Content-Type":"application/json"}})}},router:null}}getWS(){return this.wsServer}async startWebSocket(e){let t=this.settings?.access?.apiAccess;if(t?.wsEnabled===false)return null;let s=async a=>{let o=await chunkNY47CFVP_cjs.e(a,this.db);if(!o.valid)throw new Error(o.error||"Invalid API key");if(!o.user)throw new Error("API key has no associated user");return o.user},i=e?.port||8080;if(globalThis.__KYRO_WS_SERVER__)try{await globalThis.__KYRO_WS_SERVER__.close();}catch{}return this.wsServer=chunkG3J2EU5D_cjs.d({pubsub:this.pubsub,port:i,requireAuth:e?.requireAuth??t?.requireAuth,verifyToken:e?.verifyToken||s}),globalThis.__KYRO_WS_SERVER__=this.wsServer,this.wsServer}async shutdown(){await this.pluginManager.executeHook("beforeServerStop",{kyro:this}),this.wsServer&&await this.wsServer.close(),await this.db.disconnect(),await this.pluginManager.executeHook("afterServerStop",{kyro:this});}};function gs(n){return new re(n)}var At=module$1.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('chunk-MR5BDZKI.cjs', document.baseURI).href))),St="node:sqlite",{DatabaseSync:xt}=At(St);function E(n){let e=[];for(let t of n)if(t.type==="tabs"&&"tabs"in t)for(let s of t.tabs)e.push(...E(s.fields));else t.type==="row"&&"fields"in t?e.push(...E(t.fields)):t.type==="collapsible"&&"fields"in t?e.push(...E(t.fields)):e.push(t);return e}function Et(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 i=new Date(s);isNaN(i.getTime())?s=null:s=i.toISOString();}catch{s=null;}if((t.type==="upload"||t.type==="image")&&s)try{let i=JSON.parse(s);Array.isArray(i)?s=i.map(a=>typeof a=="object"&&a!==null?a:{id:a}):s=typeof i=="object"?i:{id:i};}catch{s={id:s};}if(t.type==="relationship"&&s)try{let i=JSON.parse(s);Array.isArray(i),s=i;}catch{s={relationTo:Array.isArray(t.relationTo)?t.relationTo[0]:t.relationTo,value:s};}if(t.type==="list"&&s)try{let i=JSON.parse(s);s=Array.isArray(i)?i:[];}catch{s=[];}if(t.type==="relationship-block"&&s)try{let i=JSON.parse(s);s=Array.isArray(i)?i:[];}catch{s=[];}return s}function qe(n,e){return Array.isArray(n)?n.map(t=>{if(!t||typeof t!="object")return t;let s=t.data?{...t.data}:void 0;if(!s)return t;let i=e.find(a=>a.slug===t.type||a.slug===t.slug);if(!i||!Array.isArray(i.fields))return t;for(let a of i.fields){if(a.name&&(a.type==="upload"||a.type==="image")&&s[a.name]){let o=s[a.name];Array.isArray(o)?s[a.name]=o.map(r=>typeof r=="string"?{id:r}:r):typeof o=="string"&&(s[a.name]={id:o});}if(a.type==="blocks"&&a.name&&s[a.name]){let o=a.blocks||[];s[a.name]=qe(s[a.name],o);}}return {...t,data:s}}):n}function q(n,e){try{return n.prepare(`PRAGMA table_info(${e})`).all().map(s=>s.name)}catch{return []}}var le=class extends chunkFHJJKFAU_cjs.a{db;path;migrations=new Map;versionsTableName="kyro_versions";constructor(e){super(),this.path=e.path,e.db?this.db=e.db:this.db=null;}async connect(){if(this.db||(this.db=new xt(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 i=e(s),a=o=>typeof o=="boolean"?o?1:0:o===void 0?null:o;return new Proxy(i,{get(o,r,c){if(r==="all")return (...u)=>o.all(...u.map(a));if(r==="get")return (...u)=>o.get(...u.map(a));if(r==="run")return (...u)=>o.run(...u.map(a));let d=Reflect.get(o,r,c);return typeof d=="function"?d.bind(o):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),i=["id TEXT PRIMARY KEY"];for(let r of E(e.fields)){if(!r.name||r.name==="id")continue;let c=this.fieldToSQL(r);c&&i.push(c);}let a=E(e.fields);a.some(r=>r.name==="createdAt")||i.push(`${this.col("createdAt")} TEXT DEFAULT (datetime('now'))`),a.some(r=>r.name==="updatedAt")||i.push(`${this.col("updatedAt")} TEXT DEFAULT (datetime('now'))`),a.some(r=>r.name==="status")||i.push("status TEXT DEFAULT 'draft'"),a.some(r=>r.name==="hasDraft")||i.push("hasDraft INTEGER DEFAULT 0"),e.tenantScoped&&i.push("tenant_id TEXT NOT NULL");let o=q(this.db,s);if(o.length===0){let r=`CREATE TABLE IF NOT EXISTS ${s} (${i.join(", ")})`;this.db.exec(r),this.db.exec(`CREATE INDEX IF NOT EXISTS idx_${s}_status ON ${s}(status)`);for(let c of E(e.fields))c.name&&c.indexed&&this.db.exec(`CREATE INDEX IF NOT EXISTS idx_${s}_${c.name} ON ${s}(${this.col(c.name)})`),c.name&&c.unique&&this.db.exec(`CREATE UNIQUE INDEX IF NOT EXISTS idx_${s}_${c.name}_unique ON ${s}(${this.col(c.name)})`);}else {let r=new Set(o);for(let c of i){let d=c.split(" ")[0].replace(/^"/,"").replace(/"$/,"");if(!r.has(d)&&d!=="id")try{d==="status"?this.db.exec(`ALTER TABLE ${s} ADD COLUMN ${this.col(d)} TEXT DEFAULT 'published'`):d==="hasDraft"?this.db.exec(`ALTER TABLE ${s} ADD COLUMN ${this.col(d)} INTEGER DEFAULT 0`):this.db.exec(`ALTER TABLE ${s} ADD COLUMN ${this.col(d)} TEXT`);}catch{}}}this.migrations.set(s,true);}ensureVersionsTable(){this.db.exec(`
4
4
  CREATE TABLE IF NOT EXISTS ${this.versionsTableName} (
5
5
  id TEXT PRIMARY KEY,
6
6
  collection_slug TEXT NOT NULL,