@kyro-cms/core 0.12.30 → 0.12.31

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.
@@ -1 +1 @@
1
- 'use strict';var chunkRHAP6SPA_cjs=require('./chunk-RHAP6SPA.cjs');require('./chunk-GZWRTHHL.cjs'),require('./chunk-4XZABBHF.cjs'),require('./chunk-65G73T7Z.cjs'),require('./chunk-KD7LUCFY.cjs'),require('./chunk-ZUVP4UK7.cjs'),require('./chunk-HS2KNFAB.cjs'),require('./chunk-UVM7P4SE.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-FUWPXR6W.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 chunkRHAP6SPA_cjs.a.db.findOne({collection:"_globals_access-settings",where:{},draft:!0}))?.apiAccess?.graphqlEnabled??p.graphqlEnabled}catch{return true}}var l=async e=>{if(await chunkRHAP6SPA_cjs.b(),!await o())return r();let t=await chunkRHAP6SPA_cjs.a.getGraphQL().fetch(e.request,e.locals);return n(t)},u=async e=>{if(await chunkRHAP6SPA_cjs.b(),!await o())return r();let t=await chunkRHAP6SPA_cjs.a.getGraphQL().fetch(e.request,e.locals);return n(t)};exports.GET=u;exports.POST=l;
1
+ 'use strict';var chunkTMKROUQA_cjs=require('./chunk-TMKROUQA.cjs');require('./chunk-4KFXG5ZB.cjs'),require('./chunk-4XZABBHF.cjs'),require('./chunk-65G73T7Z.cjs'),require('./chunk-KD7LUCFY.cjs'),require('./chunk-ZUVP4UK7.cjs'),require('./chunk-HS2KNFAB.cjs'),require('./chunk-2YRM7CZZ.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-FUWPXR6W.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 chunkTMKROUQA_cjs.a.db.findOne({collection:"_globals_access-settings",where:{},draft:!0}))?.apiAccess?.graphqlEnabled??p.graphqlEnabled}catch{return true}}var l=async e=>{if(await chunkTMKROUQA_cjs.b(),!await o())return r();let t=await chunkTMKROUQA_cjs.a.getGraphQL().fetch(e.request,e.locals);return n(t)},u=async e=>{if(await chunkTMKROUQA_cjs.b(),!await o())return r();let t=await chunkTMKROUQA_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-2XTLTOS4.js';import'./chunk-LZI5BSC3.js';import'./chunk-6MSPBK3W.js';import'./chunk-NZ35PV5R.js';import'./chunk-5SEHX7ON.js';import'./chunk-LHW4R367.js';import'./chunk-PP7W5UKL.js';import'./chunk-4CJ5RLWO.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-5KSRMBEO.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
+ import {b,a}from'./chunk-7R5IPQ5F.js';import'./chunk-DZMIMB5W.js';import'./chunk-6MSPBK3W.js';import'./chunk-NZ35PV5R.js';import'./chunk-5SEHX7ON.js';import'./chunk-LHW4R367.js';import'./chunk-PP7W5UKL.js';import'./chunk-4DJYAD4L.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-5KSRMBEO.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 chunkRHAP6SPA_cjs=require('./chunk-RHAP6SPA.cjs');require('./chunk-GZWRTHHL.cjs'),require('./chunk-4XZABBHF.cjs'),require('./chunk-65G73T7Z.cjs'),require('./chunk-KD7LUCFY.cjs'),require('./chunk-ZUVP4UK7.cjs'),require('./chunk-HS2KNFAB.cjs'),require('./chunk-UVM7P4SE.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-FUWPXR6W.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 chunkRHAP6SPA_cjs.a.db.findOne({collection:"_globals_access-settings",where:{},draft:!0}))?.apiAccess?.trpcEnabled??r.trpcEnabled}catch{return true}}var i=async e=>(await chunkRHAP6SPA_cjs.b(),await s()?chunkRHAP6SPA_cjs.a.getTRPC().fetch(e.request,e.locals):n());exports.ALL=i;
1
+ 'use strict';var chunkTMKROUQA_cjs=require('./chunk-TMKROUQA.cjs');require('./chunk-4KFXG5ZB.cjs'),require('./chunk-4XZABBHF.cjs'),require('./chunk-65G73T7Z.cjs'),require('./chunk-KD7LUCFY.cjs'),require('./chunk-ZUVP4UK7.cjs'),require('./chunk-HS2KNFAB.cjs'),require('./chunk-2YRM7CZZ.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-FUWPXR6W.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 chunkTMKROUQA_cjs.a.db.findOne({collection:"_globals_access-settings",where:{},draft:!0}))?.apiAccess?.trpcEnabled??r.trpcEnabled}catch{return true}}var i=async e=>(await chunkTMKROUQA_cjs.b(),await s()?chunkTMKROUQA_cjs.a.getTRPC().fetch(e.request,e.locals):n());exports.ALL=i;
@@ -1 +1 @@
1
- import {b,a}from'./chunk-2XTLTOS4.js';import'./chunk-LZI5BSC3.js';import'./chunk-6MSPBK3W.js';import'./chunk-NZ35PV5R.js';import'./chunk-5SEHX7ON.js';import'./chunk-LHW4R367.js';import'./chunk-PP7W5UKL.js';import'./chunk-4CJ5RLWO.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-5KSRMBEO.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
+ import {b,a}from'./chunk-7R5IPQ5F.js';import'./chunk-DZMIMB5W.js';import'./chunk-6MSPBK3W.js';import'./chunk-NZ35PV5R.js';import'./chunk-5SEHX7ON.js';import'./chunk-LHW4R367.js';import'./chunk-PP7W5UKL.js';import'./chunk-4DJYAD4L.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-5KSRMBEO.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 chunkRHAP6SPA_cjs=require('./chunk-RHAP6SPA.cjs');require('./chunk-GZWRTHHL.cjs'),require('./chunk-4XZABBHF.cjs'),require('./chunk-65G73T7Z.cjs'),require('./chunk-KD7LUCFY.cjs'),require('./chunk-ZUVP4UK7.cjs'),require('./chunk-HS2KNFAB.cjs'),require('./chunk-UVM7P4SE.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-FUWPXR6W.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 chunkRHAP6SPA_cjs.c}});Object.defineProperty(exports,"kyroInstance",{enumerable:true,get:function(){return chunkRHAP6SPA_cjs.a}});Object.defineProperty(exports,"warmKyroInstance",{enumerable:true,get:function(){return chunkRHAP6SPA_cjs.b}});
1
+ 'use strict';var chunkTMKROUQA_cjs=require('./chunk-TMKROUQA.cjs');require('./chunk-4KFXG5ZB.cjs'),require('./chunk-4XZABBHF.cjs'),require('./chunk-65G73T7Z.cjs'),require('./chunk-KD7LUCFY.cjs'),require('./chunk-ZUVP4UK7.cjs'),require('./chunk-HS2KNFAB.cjs'),require('./chunk-2YRM7CZZ.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-FUWPXR6W.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 chunkTMKROUQA_cjs.c}});Object.defineProperty(exports,"kyroInstance",{enumerable:true,get:function(){return chunkTMKROUQA_cjs.a}});Object.defineProperty(exports,"warmKyroInstance",{enumerable:true,get:function(){return chunkTMKROUQA_cjs.b}});
@@ -1 +1 @@
1
- export{c as ALL,a as kyroInstance,b as warmKyroInstance}from'./chunk-2XTLTOS4.js';import'./chunk-LZI5BSC3.js';import'./chunk-6MSPBK3W.js';import'./chunk-NZ35PV5R.js';import'./chunk-5SEHX7ON.js';import'./chunk-LHW4R367.js';import'./chunk-PP7W5UKL.js';import'./chunk-4CJ5RLWO.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-5KSRMBEO.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
+ export{c as ALL,a as kyroInstance,b as warmKyroInstance}from'./chunk-7R5IPQ5F.js';import'./chunk-DZMIMB5W.js';import'./chunk-6MSPBK3W.js';import'./chunk-NZ35PV5R.js';import'./chunk-5SEHX7ON.js';import'./chunk-LHW4R367.js';import'./chunk-PP7W5UKL.js';import'./chunk-4DJYAD4L.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-5KSRMBEO.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';
@@ -102,7 +102,7 @@
102
102
  `),await this.db.execute(e`CREATE INDEX IF NOT EXISTS "idx_media_folders_path" ON "media_folders" ("path")`),It=true;}}now(){return new Date().toISOString()}buildFindConditions(e){let t=[],s=[],a=e.sortBy==="name"?"title":e.sortBy==="createdAt"?"created_at":e.sortBy==="updatedAt"?"updated_at":e.sortBy||"created_at",d=e.sortDir==="asc"?"ASC":"DESC";if(e.search){t.push("(title LIKE ? OR filename LIKE ? OR original_name LIKE ? OR alt LIKE ?)");let u=`%${e.search}%`;s.push(u,u,u,u);}return e.type&&e.type!=="all"&&(t.push("mime_type LIKE ?"),s.push(`${e.type}/%`)),e.folder&&(t.push("(folder = ? OR folder LIKE ?)"),s.push(e.folder,`${e.folder}/%`)),{where:t.length>0?`WHERE ${t.join(" AND ")}`:"",params:s,orderBy:d,sortCol:a}}rowToMedia(e,t){return {id:e.id,filename:e.filename,title:e.title??null,originalName:e.original_name??e.originalName,mimeType:e.mime_type??e.mimeType,fileSize:e.file_size??e.fileSize,width:e.width??null,height:e.height??null,url:c.resolveMediaUrl(e.url,t),thumbnailUrl:c.resolveMediaUrl(e.thumbnail_url??e.thumbnailUrl??null,t),folder:e.folder??null,provider:e.provider,alt:e.alt??null,caption:e.caption??null,metadata:typeof e.metadata=="string"?JSON.parse(e.metadata):e.metadata??null,createdAt:e.created_at??e.createdAt,updatedAt:e.updated_at??e.updatedAt}}static resolveMediaUrl(e,t){return e?e.startsWith("http://")||e.startsWith("https://")||e.startsWith("blob:")||e.startsWith("data:")?e:`${(process.env.KYRO_BASE_URL||t||"http://localhost:4321").replace(/\/+$/,"")}${e.startsWith("/")?"":"/"}${e}`:null}async sqliteRun(e,t=[]){let s=this.db.prepare(e),a=e.trim().toLowerCase();return a.startsWith("insert")||a.startsWith("update")||a.startsWith("delete")?s.run(...t):s.all(...t)}sqliteGet(e,t=[]){return this.db.prepare(e).get(...t)}async upload(e,t="",s){let a=e.type.startsWith("image/"),d,l=e,u=e.name,f=null,y=null;if(a&&!e.type.includes("svg")){let R=Buffer.from(await e.arrayBuffer());d=await or(R),u=`${e.name.replace(/\.[^/.]+$/,"").toLowerCase().replace(/[^a-z0-9]/g,"-").replace(/-+/g,"-").substring(0,50)}.webp`,f=d.width??null,y=d.height??null,l=new File([d.buffer],u,{type:"image/webp"});}let I=await this.storage.upload(l,{folder:t,filename:u}),h=await this.storage.generateThumbnail({...I,id:"",provider:this.storage.name,createdAt:this.now()},{width:400,height:400}),k=this.genId(),C=this.now();if(this.dialect==="mongodb"){let R=I.mimeType,q=R.startsWith("image/")?"image":R.startsWith("video/")?"video":R.startsWith("audio/")?"audio":R.startsWith("application/pdf")?"document":["application/zip","application/x-zip","application/x-tar","application/gzip","application/x-7z"].includes(R)?"archive":"other";return await this.db.db.collection(this.mediaTable).insertOne({_id:k,id:k,filename:I.filename,title:e.name.replace(/\.[^/.]+$/,""),originalName:e.name,mimeType:R,fileSize:I.size,width:f,height:y,url:I.url,thumbnailUrl:h,folder:t||"",provider:this.storage.name,type:q,status:"active",alt:null,caption:null,createdAt:new Date,updatedAt:new Date}),this.rowToMedia({id:k,filename:I.filename,title:e.name.replace(/\.[^/.]+$/,""),originalName:e.name,mimeType:R,fileSize:I.size,width:f,height:y,url:I.url,thumbnailUrl:h,folder:t||"",provider:this.storage.name,type:q,status:"active",alt:null,caption:null,createdAt:new Date,updatedAt:new Date},s)}if(this.dialect==="sqlite")await this.sqliteRun(`INSERT INTO ${this.mediaTable}
103
103
  (id, filename, title, original_name, mime_type, file_size, width, height, url, thumbnail_url, folder, provider, alt, caption, metadata, created_at, updated_at)
104
104
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[k,I.filename,e.name.replace(/\.[^/.]+$/,""),e.name,I.mimeType,I.size,f,y,I.url,h,t||null,this.storage.name,null,null,null,C,C]);else {let{media:R}=await import('./media-OUBQTIQP.cjs'),q=I.mimeType,z=q.startsWith("image/")?"image":q.startsWith("video/")?"video":q.startsWith("audio/")?"audio":q.startsWith("application/pdf")?"document":["application/zip","application/x-zip","application/x-tar","application/gzip","application/x-7z"].includes(q)?"archive":"other",V=await this.db.insert(R).values({id:k,filename:I.filename,title:e.name.replace(/\.[^/.]+$/,""),originalName:e.name,mimeType:q,fileSize:I.size,width:f,height:y,url:I.url,thumbnailUrl:h,folder:t||"",provider:this.storage.name,type:z,status:"active",alt:null,caption:null,createdAt:new Date,updatedAt:new Date}).returning();V&&V[0]&&(k=V[0].id);}return {id:k,filename:I.filename,title:e.name.replace(/\.[^/.]+$/,""),originalName:e.name,mimeType:I.mimeType,fileSize:I.size,width:f,height:y,url:I.url,thumbnailUrl:h,folder:t||null,provider:this.storage.name,alt:null,caption:null,metadata:null,createdAt:C,updatedAt:C}}async uploadFromUrl(e,t="",s){let a=await fetch(e);if(!a.ok)throw new Error(`Failed to fetch URL: ${a.status}`);let d=await a.blob(),l=e.split("/").pop()||"url-image",u=a.headers.get("content-type")||d.type||"application/octet-stream",f=new File([d],l,{type:u});return this.upload(f,t,s)}async delete(e,t){this.dialect==="postgres"&&(e=Pe(e));let s=await this.findById(e,t);if(s){if(await this.deleteFile(s.url),s.thumbnailUrl&&s.thumbnailUrl!==s.url&&s.thumbnailUrl!==s.url+"?thumb")try{await this.deleteFile(s.thumbnailUrl);}catch{}if(this.dialect==="mongodb"){await this.db.db.collection(this.mediaTable).deleteOne({id:e});return}if(this.dialect==="sqlite")await this.sqliteRun(`DELETE FROM ${this.mediaTable} WHERE id = ?`,[e]);else {let{media:a}=await import('./media-OUBQTIQP.cjs'),{eq:d}=await import('drizzle-orm');await this.db.delete(a).where(d(a.id,e));}}}async deleteFile(e){await this.storage.delete(e);}async rename(e,t,s){this.dialect==="postgres"&&(e=Pe(e));let a=await this.findById(e,s);if(!a)return null;let d=await this.storage.rename(a.url,t),l;if(a.thumbnailUrl||this.storage.name==="cloudinary"){let I=d.match(/\/upload\/(v\d+)\//),h=I?I[1]+"/":"",k=d.match(/(.+?)\/upload\//);l=`${k?k[1]:"https://res.cloudinary.com/"+this.storage.config?.cloudName||"unknown"}/upload/w_200,h_200,c_fill/${h}${t}`;}let u=a.filename.split(".").pop(),f=t.includes(".")?t:`${t}.${u}`,y={url:d,filename:f,thumbnailUrl:l};if(this.dialect==="mongodb")return await this.db.db.collection(this.mediaTable).updateOne({id:e},{$set:{url:d,thumbnailUrl:l||null,updatedAt:new Date}}),this.findById(e,s);if(this.dialect==="sqlite"){let I={...y};"thumbnailUrl"in I&&(I.thumbnail_url=I.thumbnailUrl,delete I.thumbnailUrl);let h=Object.keys(I).map(C=>`${C} = ?`).join(", "),k=Object.values(I);await this.sqliteRun(`UPDATE ${this.mediaTable} SET ${h}, updated_at = ? WHERE id = ?`,[...k,this.now(),e]);}else {let{media:I}=await import('./media-OUBQTIQP.cjs'),{eq:h}=await import('drizzle-orm');await this.db.update(I).set({...y,updatedAt:this.now()}).where(h(I.id,e));}return {...a,...y,updatedAt:this.now(),thumbnailUrl:y.thumbnailUrl??null}}async findById(e,t){if(this.dialect==="postgres"&&(e=Pe(e)),this.dialect==="mongodb"){let l=await this.db.db.collection(this.mediaTable).findOne({id:e});return l?this.rowToMedia(l,t):null}if(this.dialect==="sqlite"){let l=this.sqliteGet(`SELECT * FROM ${this.mediaTable} WHERE id = ?`,[e]);return l?this.rowToMedia(l,t):null}let{media:s}=await import('./media-OUBQTIQP.cjs'),{eq:a}=await import('drizzle-orm'),[d]=await this.db.select().from(s).where(a(s.id,e));return d?this.rowToMedia(d,t):null}async find(e={},t){let{page:s=1,limit:a=30,search:d="",type:l="",folder:u="",sortBy:f="createdAt",sortDir:y="desc"}=e,{where:I,params:h,orderBy:k,sortCol:C}=this.buildFindConditions({page:s,limit:a,search:d,type:l,folder:u,sortBy:f,sortDir:y}),R=(s-1)*a;if(this.dialect==="mongodb"){let X={},{search:G,type:ae,folder:K,sortBy:Re="createdAt",sortDir:Ee="desc"}=e;G&&(X.$or=[{title:{$regex:G,$options:"i"}},{filename:{$regex:G,$options:"i"}},{originalName:{$regex:G,$options:"i"}},{alt:{$regex:G,$options:"i"}}]),ae&&ae!=="all"&&(X.mimeType={$regex:`^${ae}/`}),K&&(X.$or=[{folder:K},{folder:{$regex:`^${K}/`}}]);let Rt={[Re==="name"?"title":Re]:Ee==="asc"?1:-1},r=await this.db.db.collection(this.mediaTable).countDocuments(X);return {docs:(await this.db.db.collection(this.mediaTable).find(X).sort(Rt).skip(R).limit(a).toArray()).map(m=>this.rowToMedia(m,t)),totalDocs:r,page:s,limit:a,totalPages:Math.ceil(r/a)}}if(this.dialect==="sqlite"){let G=this.sqliteGet(`SELECT COUNT(*) as cnt FROM ${this.mediaTable} ${I}`,h)?.cnt??0;return {docs:(await this.sqliteRun(`SELECT * FROM ${this.mediaTable} ${I} ORDER BY ${C} ${k} LIMIT ? OFFSET ?`,[...h,a,R])).map(K=>this.rowToMedia(K,t)),totalDocs:G,page:s,limit:a,totalPages:Math.ceil(G/a)}}let{media:q}=await import('./media-OUBQTIQP.cjs'),{like:z,or:V,and:ne,asc:L,desc:pe,eq:Z,sql:E}=await import('drizzle-orm'),Q=[];d&&Q.push(V(z(q.title,`%${d}%`),z(q.filename,`%${d}%`),z(q.originalName,`%${d}%`),z(q.alt,`%${d}%`))),l&&l!=="all"&&Q.push(z(q.mimeType,`${l}/%`)),u&&Q.push(V(Z(q.folder,u),z(q.folder,`${u}/%`)));let qe=Q.length>0?ne(...Q):void 0,me=q[{created_at:"createdAt",updated_at:"updatedAt",title:"title",filename:"filename",file_size:"fileSize",mime_type:"mimeType",original_name:"originalName"}[C]||"createdAt"],xt=y==="asc"?L(me):pe(me),ve=await this.db.select().from(q).where(qe).orderBy(xt).limit(a).offset(R),[{count:be}]=await this.db.select({count:E`count(*)`}).from(q).where(qe),O=Number(be);return {docs:ve.map(X=>this.rowToMedia(X,t)),totalDocs:O,page:s,limit:a,totalPages:Math.ceil(O/a)}}async update(e,t,s){this.dialect==="postgres"&&(e=Pe(e));let a=this.now();if(this.dialect==="mongodb")return await this.db.db.collection(this.mediaTable).updateOne({id:e},{$set:{...t,updatedAt:new Date}}),this.findById(e,s);if(this.dialect==="sqlite"){let f=["updated_at = ?"],y=[a];t.title!==void 0&&(f.push("title = ?"),y.push(t.title)),t.alt!==void 0&&(f.push("alt = ?"),y.push(t.alt)),t.caption!==void 0&&(f.push("caption = ?"),y.push(t.caption)),t.folder!==void 0&&(f.push("folder = ?"),y.push(t.folder)),t.metadata!==void 0&&(f.push("metadata = ?"),y.push(t.metadata===null?null:JSON.stringify(t.metadata))),t.originalName!==void 0&&(f.push("original_name = ?"),y.push(t.originalName)),y.push(e),await this.sqliteRun(`UPDATE ${this.mediaTable} SET ${f.join(", ")} WHERE id = ?`,y);let I=this.sqliteGet(`SELECT * FROM ${this.mediaTable} WHERE id = ?`,[e]);return I?this.rowToMedia(I,s):null}let{media:d}=await import('./media-OUBQTIQP.cjs'),{eq:l}=await import('drizzle-orm'),[u]=await this.db.update(d).set({...t,updatedAt:new Date}).where(l(d.id,e)).returning();return u?this.rowToMedia(u,s):null}async updateMany(e,t){this.dialect==="postgres"&&(e=e.map(Pe));let s=this.now();if(this.dialect==="mongodb"){for(let a of e)await this.db.db.collection(this.mediaTable).updateOne({id:a},{$set:{...t,updatedAt:new Date}});return}if(this.dialect==="sqlite")for(let a of e){let d=["updated_at = ?"],l=[s];t.folder!==void 0&&(d.push("folder = ?"),l.push(t.folder||null)),l.push(a),await this.sqliteRun(`UPDATE ${this.mediaTable} SET ${d.join(", ")} WHERE id = ?`,l);}else {let{media:a}=await import('./media-OUBQTIQP.cjs'),{eq:d}=await import('drizzle-orm');for(let l of e)await this.db.update(a).set({...t,updatedAt:new Date}).where(d(a.id,l));}}async listFolders(){if(this.dialect==="mongodb"){let f=await this.db.db.collection(this.foldersTable).find({},{projection:{path:1}}).toArray(),y=await this.db.db.collection(this.mediaTable).distinct("folder"),I=new Set([...f.map(h=>h.path),...y]);return Array.from(I).filter(h=>h&&h!=="").sort()}if(this.dialect==="sqlite")return (await this.sqliteRun(`SELECT path FROM ${this.foldersTable} UNION
105
- SELECT folder as path FROM ${this.mediaTable} WHERE folder IS NOT NULL AND folder != ''`)).map(y=>y.path).filter(y=>y&&y!=="").sort();let{media:e,mediaFolders:t}=await import('./media-OUBQTIQP.cjs'),{eq:s,sql:a}=await import('drizzle-orm'),d=await this.db.select({folder:e.folder}).from(e).groupBy(e.folder),l=await this.db.select({path:t.path}).from(t),u=new Set([...d.map(f=>f.folder),...l.map(f=>f.path)]);return Array.from(u).filter(f=>f&&f!=="").sort()}async createFolder(e,t=""){let s=t?`${t}/${e}`:e;await this.storage.createFolder?.(s);let a=this.now();if(this.dialect==="mongodb"){await this.db.db.collection(this.foldersTable).findOne({path:s})||await this.db.db.collection(this.foldersTable).insertOne({_id:this.genId(),name:e,path:s,parentPath:t||null,createdAt:new Date});return}if(this.dialect==="sqlite")await this.sqliteRun(`INSERT OR IGNORE INTO ${this.foldersTable} (path, name, parent_path, created_at) VALUES (?, ?, ?, ?)`,[s,e,t||null,a]);else {let{mediaFolders:d}=await import('./media-OUBQTIQP.cjs');await this.db.insert(d).values({path:s,name:e,parentPath:t||null,createdAt:new Date}).onConflictDoNothing();}}async deleteFolder(e){let t=await this.find({folder:e,limit:1e4});for(let s of t.docs)await this.delete(s.id);if(await this.storage.deleteFolder?.(e),this.dialect==="mongodb"){await this.db.db.collection(this.foldersTable).deleteMany({$or:[{path:e},{path:{$regex:`^${e}/`}}]});return}if(this.dialect==="sqlite")await this.sqliteRun(`DELETE FROM ${this.foldersTable} WHERE path = ? OR path LIKE ?`,[e,`${e}/%`]);else {let{mediaFolders:s}=await import('./media-OUBQTIQP.cjs'),{like:a,or:d,eq:l}=await import('drizzle-orm');await this.db.delete(s).where(d(l(s.path,e),a(s.path,`${e}/%`)));}}};function Xe(c){return c.map(e=>`${e.path.join(".")}: ${e.message}`).join(", ")}function ye(c,e){if(!(!c||typeof c!="object"))for(let t of e){if(t.type==="tabs"&&Array.isArray(t.tabs)){let a=t.name?c[t.name]:c;if(a&&typeof a=="object")for(let d of t.tabs)Array.isArray(d.fields)&&ye(a,d.fields);continue}if(!t.name||!(t.name in c))continue;if(c[t.name]===""&&(t.type==="text"||t.type==="textarea"||t.type==="code"||t.type==="markdown"||(c[t.name]=null)),(t.type==="group"||t.type==="collapsible")&&t.name&&Array.isArray(t.fields)&&c[t.name]&&typeof c[t.name]=="object")ye(c[t.name],t.fields);else if(t.type==="array"&&t.name&&Array.isArray(t.fields)&&Array.isArray(c[t.name]))for(let a of c[t.name])a&&typeof a=="object"&&ye(a,t.fields);else if(t.type==="blocks"&&t.name&&Array.isArray(t.blocks)&&Array.isArray(c[t.name]))for(let a of c[t.name]){if(!a||typeof a!="object")continue;let d=a.type||a.blockType;if(!d)continue;let l=t.blocks.find(f=>f.slug===d);if(!l||!Array.isArray(l.fields))continue;let u=a.data&&typeof a.data=="object"?a.data:a;ye(u,l.fields);}}}function we(c,e){if(!(!e||typeof e!="object"))for(let t of c){if(t.type==="tabs"&&Array.isArray(t.tabs)){let s=t.name?e[t.name]:e;if(s&&typeof s=="object")for(let a of t.tabs)Array.isArray(a.fields)&&we(a.fields,s);}if(t.type==="richtext"&&t.name){let s=e[t.name];typeof s=="string"?e[t.name]=[{type:"paragraph",children:[{text:s}]}]:s&&typeof s=="object"&&!Array.isArray(s)&&s.type==="doc"&&Array.isArray(s.content)&&(e[t.name]=s.content);}if((t.type==="group"||t.type==="collapsible")&&t.name&&Array.isArray(t.fields)&&e[t.name]&&typeof e[t.name]=="object")we(t.fields,e[t.name]);else if(t.type==="array"&&t.name&&Array.isArray(t.fields)&&Array.isArray(e[t.name]))for(let s of e[t.name])s&&typeof s=="object"&&we(t.fields,s);else if(t.type==="blocks"&&t.name&&Array.isArray(t.blocks)&&Array.isArray(e[t.name]))for(let s of e[t.name]){if(!s||typeof s!="object")continue;let a=s.type||s.blockType;if(!a)continue;let d=t.blocks.find(u=>u.slug===a);if(!d||!Array.isArray(d.fields))continue;let l=s.data&&typeof s.data=="object"?s.data:s;we(d.fields,l);}}}function De(c,e){if(!(!e||typeof e!="object")){for(let t of c)if(!(!t.name||!(t.name in e))){if(t.unique&&(t.type==="text"||t.type==="email"?e[t.name]=`${e[t.name]||t.name}-copy-${Date.now().toString(36)}`:delete e[t.name]),t.type==="tabs"&&t.name&&Array.isArray(t.tabs)&&e[t.name]&&typeof e[t.name]=="object")for(let s of t.tabs)Array.isArray(s.fields)&&De(s.fields,e[t.name]);else if((t.type==="group"||t.type==="collapsible")&&t.name&&Array.isArray(t.fields)&&e[t.name]&&typeof e[t.name]=="object")De(t.fields,e[t.name]);else if(t.type==="array"&&t.name&&Array.isArray(t.fields)&&Array.isArray(e[t.name]))for(let s of e[t.name])s&&typeof s=="object"&&(delete s.id,De(t.fields,s));else if(t.type==="blocks"&&t.name&&Array.isArray(t.blocks)&&Array.isArray(e[t.name]))for(let s of e[t.name]){if(!s||typeof s!="object")continue;delete s.id;let a=s.type||s.blockType;if(!a)continue;let d=t.blocks.find(u=>u.slug===a);if(!d||!Array.isArray(d.fields))continue;let l=s.data&&typeof s.data=="object"?s.data:s;De(d.fields,l);}}}}var Jr={_media:{create:chunkILEZ3NYX_cjs.d.MEDIA_UPLOAD,update:chunkILEZ3NYX_cjs.d.MEDIA_UPLOAD,delete:chunkILEZ3NYX_cjs.d.MEDIA_DELETE}};function ke(c,e){let t=Jr[c];return t?t[e]:`collection.${e}`}function Zr(c){let e=c.headers.get("x-forwarded-for");return e?e.split(",")[0].trim():c.headers.get("x-real-ip")||"unknown"}function Ge(c,e,t,s,a){e?.apiKeyId&&c&&c.createAuditLog({action:"api_request",userId:e.userId||"",resource:"api_key",resourceId:e.apiKeyId,success:true,metadata:{endpoint:t,method:s,ip:Zr(a)}});}function Ye(c){return c.baseUpdatedAt??c._baseUpdatedAt}function St(c){let{baseUpdatedAt:e,_baseUpdatedAt:t,...s}=c;return s}function Tt(c,e){return {error:"Document has changed since you started editing",code:"REVISION_CONFLICT",conflict:{expectedUpdatedAt:c??null,actualUpdatedAt:e.updatedAt??null,current:e}}}async function N(c,e,t,s,a,d,l=true,u="none"){return await chunkILEZ3NYX_cjs.b(c,e,{user:s,req:t,tenantId:a,apiKey:d},{enablePublicAccess:l,defaultAccess:u})}async function J(c,e,t,s,a,d=true){return await chunkILEZ3NYX_cjs.c(c,e,{user:s,req:t,tenantId:a},{enablePublicAccess:d})}async function P(c,e,t,s){if(t)return {user:t,tenantId:s,apiKeyContext:void 0,authType:"static"};if(e){let a=await e(c);if(a.status===200&&a.user)return {user:a.user,tenantId:a.tenantContext?.tenantId,apiKeyContext:a.apiKeyContext,authType:a.authType}}return {user:void 0,tenantId:void 0,apiKeyContext:void 0,authType:void 0}}function Qr(c,e){if("dialect"in c&&c.dialect==="postgres"&&c instanceof chunkFUWPXR6W_cjs.c)return new chunkGYQMNXXW_cjs.a({db:c.client});if("dialect"in c&&c.dialect==="sqlite"&&c instanceof chunkFUWPXR6W_cjs.c)return new Be({db:c.client});if("dialect"in c&&c.dialect==="mongodb"){let s=c;return new chunkQCA3AP3M_cjs.a({db:()=>s.db})}let t=ze.resolve(e,"data","kyro.db");return new chunkHOP4D5XZ_cjs.a({path:process.env.KYRO_AUTH_DB_PATH||t})}function pr(c){let{registry:e,db:t,authSecret:s,authAdapter:a,checkSession:d,user:l,tenantId:u,cors:f,webhookService:y,settings:I}=c,h=new hono.Hono;function k(r){if(Array.isArray(r))return r.map(k);if(r!==null&&typeof r=="object"){let o={};for(let m in r)m!=="attrs"&&(o[m]=k(r[m]));return o}return r}h.use("*",async(r,o)=>{await o();let m=r.req.header("referer")||"";if(!(r.req.header("x-kyro-admin")==="true"||m.includes("/admin"))){let n=r.res.headers.get("Content-Type");if(n&&n.includes("application/json"))try{let p=await r.res.clone().json(),A=k(p);r.res=r.json(A,r.res.status);}catch{}}});for(let r of e.getPlugins())typeof r.serverMiddleware=="function"&&r.serverMiddleware(h);let C=I?.access?.apiAccess,R=I?.access?.enablePublicAccess??false,q=I?.access?.defaultCollectionAccess??"none";C?.requireAuth;let V=process.cwd(),ne=V.endsWith("admin")?ze.resolve(V,".."):V,L=a||Qr(t,ne),E=Vt({db:t,userLookup:async r=>await L.findUserById(r)||null}),Q=C?.cors?.allowedOrigins,qe=f?.origins,Je=Array.isArray(Q)?Q:typeof Q=="string"&&Q?Q.split(`
105
+ SELECT folder as path FROM ${this.mediaTable} WHERE folder IS NOT NULL AND folder != ''`)).map(y=>y.path).filter(y=>y&&y!=="").sort();let{media:e,mediaFolders:t}=await import('./media-OUBQTIQP.cjs'),{eq:s,sql:a}=await import('drizzle-orm'),d=await this.db.select({folder:e.folder}).from(e).groupBy(e.folder),l=await this.db.select({path:t.path}).from(t),u=new Set([...d.map(f=>f.folder),...l.map(f=>f.path)]);return Array.from(u).filter(f=>f&&f!=="").sort()}async createFolder(e,t=""){let s=t?`${t}/${e}`:e;await this.storage.createFolder?.(s);let a=this.now();if(this.dialect==="mongodb"){await this.db.db.collection(this.foldersTable).findOne({path:s})||await this.db.db.collection(this.foldersTable).insertOne({_id:this.genId(),name:e,path:s,parentPath:t||null,createdAt:new Date});return}if(this.dialect==="sqlite")await this.sqliteRun(`INSERT OR IGNORE INTO ${this.foldersTable} (path, name, parent_path, created_at) VALUES (?, ?, ?, ?)`,[s,e,t||null,a]);else {let{mediaFolders:d}=await import('./media-OUBQTIQP.cjs');await this.db.insert(d).values({path:s,name:e,parentPath:t||null,createdAt:new Date}).onConflictDoNothing();}}async deleteFolder(e){let t=await this.find({folder:e,limit:1e4});for(let s of t.docs)await this.delete(s.id);if(await this.storage.deleteFolder?.(e),this.dialect==="mongodb"){await this.db.db.collection(this.foldersTable).deleteMany({$or:[{path:e},{path:{$regex:`^${e}/`}}]});return}if(this.dialect==="sqlite")await this.sqliteRun(`DELETE FROM ${this.foldersTable} WHERE path = ? OR path LIKE ?`,[e,`${e}/%`]);else {let{mediaFolders:s}=await import('./media-OUBQTIQP.cjs'),{like:a,or:d,eq:l}=await import('drizzle-orm');await this.db.delete(s).where(d(l(s.path,e),a(s.path,`${e}/%`)));}}};function Xe(c){return c.map(e=>`${e.path.join(".")}: ${e.message}`).join(", ")}function ye(c,e){if(!(!c||typeof c!="object"))for(let t of e){if(t.type==="tabs"&&Array.isArray(t.tabs)){let a=t.name?c[t.name]:c;if(a&&typeof a=="object")for(let d of t.tabs)Array.isArray(d.fields)&&ye(a,d.fields);continue}if(!t.name||!(t.name in c))continue;if(c[t.name]===""&&(t.type==="text"||t.type==="textarea"||t.type==="code"||t.type==="markdown"||(c[t.name]=null)),(t.type==="group"||t.type==="collapsible")&&t.name&&Array.isArray(t.fields)&&c[t.name]&&typeof c[t.name]=="object")ye(c[t.name],t.fields);else if(t.type==="array"&&t.name&&Array.isArray(t.fields)&&Array.isArray(c[t.name]))for(let a of c[t.name])a&&typeof a=="object"&&ye(a,t.fields);else if(t.type==="blocks"&&t.name&&Array.isArray(t.blocks)&&Array.isArray(c[t.name]))for(let a of c[t.name]){if(!a||typeof a!="object")continue;let d=a.type||a.blockType;if(!d)continue;let l=t.blocks.find(f=>f.slug===d);if(!l||!Array.isArray(l.fields))continue;let u=a.data&&typeof a.data=="object"?a.data:a;ye(u,l.fields);}}}function we(c,e){if(!(!e||typeof e!="object"))for(let t of c){if(t.type==="tabs"&&Array.isArray(t.tabs)){let s=t.name?e[t.name]:e;if(s&&typeof s=="object")for(let a of t.tabs)Array.isArray(a.fields)&&we(a.fields,s);}if(t.type==="richtext"&&t.name){let s=e[t.name];typeof s=="string"?e[t.name]=[{type:"paragraph",children:[{text:s}]}]:s&&typeof s=="object"&&!Array.isArray(s)&&s.type==="doc"&&Array.isArray(s.content)&&(e[t.name]=s.content);}if((t.type==="group"||t.type==="collapsible")&&t.name&&Array.isArray(t.fields)&&e[t.name]&&typeof e[t.name]=="object")we(t.fields,e[t.name]);else if(t.type==="array"&&t.name&&Array.isArray(t.fields)&&Array.isArray(e[t.name]))for(let s of e[t.name])s&&typeof s=="object"&&we(t.fields,s);else if(t.type==="blocks"&&t.name&&Array.isArray(t.blocks)&&Array.isArray(e[t.name]))for(let s of e[t.name]){if(!s||typeof s!="object")continue;let a=s.type||s.blockType;if(!a)continue;let d=t.blocks.find(u=>u.slug===a);if(!d||!Array.isArray(d.fields))continue;let l=s.data&&typeof s.data=="object"?s.data:s;we(d.fields,l);}}}function De(c,e){if(!(!e||typeof e!="object")){for(let t of c)if(!(!t.name||!(t.name in e))){if(t.unique&&(t.type==="text"||t.type==="email"?e[t.name]=`${e[t.name]||t.name}-copy-${Date.now().toString(36)}`:delete e[t.name]),t.type==="tabs"&&t.name&&Array.isArray(t.tabs)&&e[t.name]&&typeof e[t.name]=="object")for(let s of t.tabs)Array.isArray(s.fields)&&De(s.fields,e[t.name]);else if((t.type==="group"||t.type==="collapsible")&&t.name&&Array.isArray(t.fields)&&e[t.name]&&typeof e[t.name]=="object")De(t.fields,e[t.name]);else if(t.type==="array"&&t.name&&Array.isArray(t.fields)&&Array.isArray(e[t.name]))for(let s of e[t.name])s&&typeof s=="object"&&(delete s.id,De(t.fields,s));else if(t.type==="blocks"&&t.name&&Array.isArray(t.blocks)&&Array.isArray(e[t.name]))for(let s of e[t.name]){if(!s||typeof s!="object")continue;delete s.id;let a=s.type||s.blockType;if(!a)continue;let d=t.blocks.find(u=>u.slug===a);if(!d||!Array.isArray(d.fields))continue;let l=s.data&&typeof s.data=="object"?s.data:s;De(d.fields,l);}}}}var Jr={_media:{create:chunkILEZ3NYX_cjs.d.MEDIA_UPLOAD,update:chunkILEZ3NYX_cjs.d.MEDIA_UPLOAD,delete:chunkILEZ3NYX_cjs.d.MEDIA_DELETE}};function ke(c,e){let t=Jr[c];return t?t[e]:`collection.${e}`}function Zr(c){let e=c.headers.get("x-forwarded-for");return e?e.split(",")[0].trim():c.headers.get("x-real-ip")||"unknown"}function Ge(c,e,t,s,a){e?.apiKeyId&&c&&c.createAuditLog({action:"api_request",userId:e.userId||"",resource:"api_key",resourceId:e.apiKeyId,success:true,metadata:{endpoint:t,method:s,ip:Zr(a)}});}function Ye(c){return c.baseUpdatedAt??c._baseUpdatedAt}function St(c){let{baseUpdatedAt:e,_baseUpdatedAt:t,...s}=c;return s}function Tt(c,e){return {error:"Document has changed since you started editing",code:"REVISION_CONFLICT",conflict:{expectedUpdatedAt:c??null,actualUpdatedAt:e.updatedAt??null,current:e}}}async function N(c,e,t,s,a,d,l=true,u="none"){return await chunkILEZ3NYX_cjs.b(c,e,{user:s,req:t,tenantId:a,apiKey:d},{enablePublicAccess:l,defaultAccess:u})}async function J(c,e,t,s,a,d=true){return await chunkILEZ3NYX_cjs.c(c,e,{user:s,req:t,tenantId:a},{enablePublicAccess:d})}async function P(c,e,t,s){if(t)return {user:t,tenantId:s,apiKeyContext:void 0,authType:"static"};if(e){let a=await e(c);if(a.status===200&&a.user)return {user:a.user,tenantId:a.tenantContext?.tenantId,apiKeyContext:a.apiKeyContext,authType:a.authType}}return {user:void 0,tenantId:void 0,apiKeyContext:void 0,authType:void 0}}function Qr(c,e){if("dialect"in c&&c.dialect==="postgres"&&c instanceof chunkFUWPXR6W_cjs.c)return new chunkGYQMNXXW_cjs.a({db:c.client});if("dialect"in c&&c.dialect==="sqlite"&&c instanceof chunkFUWPXR6W_cjs.c)return new Be({db:c.client});if("dialect"in c&&c.dialect==="mongodb"){let s=c;return new chunkQCA3AP3M_cjs.a({db:()=>s.db})}let t=ze.resolve(e,"data","auth.db");return new chunkHOP4D5XZ_cjs.a({path:process.env.KYRO_AUTH_DB_PATH||t})}function pr(c){let{registry:e,db:t,authSecret:s,authAdapter:a,checkSession:d,user:l,tenantId:u,cors:f,webhookService:y,settings:I}=c,h=new hono.Hono;function k(r){if(Array.isArray(r))return r.map(k);if(r!==null&&typeof r=="object"){let o={};for(let m in r)m!=="attrs"&&(o[m]=k(r[m]));return o}return r}h.use("*",async(r,o)=>{await o();let m=r.req.header("referer")||"";if(!(r.req.header("x-kyro-admin")==="true"||m.includes("/admin"))){let n=r.res.headers.get("Content-Type");if(n&&n.includes("application/json"))try{let p=await r.res.clone().json(),A=k(p);r.res=r.json(A,r.res.status);}catch{}}});for(let r of e.getPlugins())typeof r.serverMiddleware=="function"&&r.serverMiddleware(h);let C=I?.access?.apiAccess,R=I?.access?.enablePublicAccess??false,q=I?.access?.defaultCollectionAccess??"none";C?.requireAuth;let V=process.cwd(),ne=V.endsWith("admin")?ze.resolve(V,".."):V,L=a||Qr(t,ne),E=Vt({db:t,userLookup:async r=>await L.findUserById(r)||null}),Q=C?.cors?.allowedOrigins,qe=f?.origins,Je=Array.isArray(Q)?Q:typeof Q=="string"&&Q?Q.split(`
106
106
  `).map(r=>r.trim()).filter(Boolean):[],me=Je.length>0?Je:qe||[];(me.length>0||f)&&h.use("*",async(r,o)=>{let m=r.req.header("Origin")||"*";if(me.length>0&&!me.includes(m))return r.json({error:"Origin not allowed"},403);let b=me.length>0?m:"*";if(r.header("Access-Control-Allow-Origin",b),r.header("Access-Control-Allow-Methods","GET, POST, PATCH, DELETE, OPTIONS"),r.header("Access-Control-Allow-Headers","Content-Type, Authorization, X-API-Key"),f?.credentials&&r.header("Access-Control-Allow-Credentials","true"),r.req.method==="OPTIONS")return r.text("");await o();});let ve=I?.access?.rateLimiting,be;if(ve?.enabled){let r=ve.maxRequests||100,o=ve.windowMs||6e4;be=new Oe({"api:general":{window:o,max:r}}),h.use("/api/*",async(m,b)=>{if(!be)return b();let n=m.req.header("CF-Connecting-IP")||m.req.header("X-Forwarded-For")?.split(",")[0]?.trim()||m.req.header("X-Real-IP")||"unknown",i=await be.check("api:general",n);if(m.header("X-RateLimit-Limit",String(r)),m.header("X-RateLimit-Remaining",String(i.remaining)),m.header("X-RateLimit-Reset",String(i.resetAt)),!i.allowed)return m.json({error:"Too many requests",retryAfter:i.retryAfter},429);await b();});}let O=new Me({redis:L,jwtSecret:s||"change-me",baseUrl:process.env.KYRO_BASE_URL||"http://localhost:4321",rateLimiter:be});chunk5K4YG5DA_cjs.k.fromConfig(t).then(r=>{r&&(O.email=r);}).catch(r=>{console.error("[Email] Failed to initialize transport from config:",r);}),h.post("/api/auth/login",async r=>O.login(r.req.raw)),h.post("/api/auth/register",async r=>{try{let o=await t.findOne({collection:"_globals_system",where:{}});if(o&&o.enableRegistration===!1)return r.json({error:"User registration is currently disabled by administrator."},403);if(o?.defaultRegistrationRole){let m=r.req.raw;if((m.headers.get("content-type")||"").includes("application/json")){let n=await r.req.json();n.role||(n.role=o.defaultRegistrationRole);let i=new Request(m.url,{method:m.method,headers:m.headers,body:JSON.stringify(n)});return O.register(i)}}}catch{}return O.register(r.req.raw)}),h.post("/api/auth/logout",async r=>O.logout(r.req.raw)),h.post("/api/auth/refresh",async r=>O.refresh(r.req.raw)),h.get("/api/auth/me",async r=>O.me(r.req.raw)),h.post("/api/auth/forgot-password",async r=>O.forgotPassword(r.req.raw)),h.post("/api/auth/reset-password",async r=>O.resetPassword(r.req.raw)),h.post("/api/auth/change-password",async r=>O.changePassword(r.req.raw)),h.get("/api/auth/verify-email",async r=>O.verifyEmail(r.req.raw)),h.post("/api/auth/verify-email",async r=>O.verifyEmail(r.req.raw)),h.get("/api/auth/verify",async r=>O.verifyEmail(r.req.raw)),h.post("/api/auth/verify",async r=>O.verifyEmail(r.req.raw)),h.get("/api/auth/sessions",async r=>O.listSessions(r.req.raw)),h.post("/api/auth/sessions/refresh",async r=>O.refreshSession(r.req.raw)),h.delete("/api/auth/sessions",async r=>O.revokeOtherSessions(r.req.raw)),h.delete("/api/auth/sessions/:id",async r=>O.revokeSession(r.req.raw,r.req.param("id"))),h.put("/api/auth/sessions/:id/name",async r=>O.renameSession(r.req.raw,r.req.param("id"))),h.get("/api/auth/access",async r=>{try{let{user:o,tenantId:m}=await P(r.req.raw,E,l,u);if(!o)return r.json({error:"Not authenticated"},401);let b={},n={};for(let i of e.getCollections()){let p={read:(await N(i,"read",r.req.raw,o,m,void 0,R,q)).allowed,create:(await N(i,"create",r.req.raw,o,m,void 0,R,q)).allowed,update:(await N(i,"update",r.req.raw,o,m,void 0,R,q)).allowed,delete:(await N(i,"delete",r.req.raw,o,m,void 0,R,q)).allowed};b[i.slug]=p;}for(let i of e.getGlobals()){let p={read:(await J(i,"read",r.req.raw,o,m,R)).allowed,update:(await J(i,"update",r.req.raw,o,m,R)).allowed};n[i.slug]=p;}return r.json({collections:b,globals:n})}catch(o){return r.json({error:o.message},500)}});let X=typeof e.hasCollection=="function"&&e.hasCollection("users")?e.getCollection("users"):(()=>{try{return e.getCollection("users")}catch{return chunkGO34AOBZ_cjs.a}})();h.get("/api/users",async r=>{try{let{user:o,tenantId:m}=await P(r.req.raw,E,l,u),b=await N(X,"read",r.req.raw,o,m,void 0,R,q);if(!b.allowed)return r.json({error:b.error},b.status||403);let n=parseInt(r.req.query("page")||"1"),i=Math.min(parseInt(r.req.query("limit")||"10"),100),p=r.req.query("search")||void 0,A=[],g=0;if(typeof L.findUsers=="function"){let w=await L.findUsers({page:n,limit:i,search:p});A=w.users||[],g=w.total||0;}else {let w=await t.find({collection:"users",page:n,limit:i,where:p?{email:{contains:p}}:{},tenantId:m});A=w.docs||[],g=w.totalDocs||0;}return r.json({docs:A,totalDocs:g,limit:i,totalPages:Math.ceil(g/i)||1,page:n,pagingCounter:(n-1)*i+1,hasPrevPage:n>1,hasNextPage:n<Math.ceil(g/i),prevPage:n>1?n-1:null,nextPage:n<Math.ceil(g/i)?n+1:null})}catch(o){return console.error("[API] Error listing users:",o),r.json({error:o.message},500)}}),h.get("/api/users/:id",async r=>{try{let{user:o,tenantId:m}=await P(r.req.raw,E,l,u),b=r.req.param("id"),n=await L.findUserById(b);return n?r.json({data:n}):r.json({error:"User not found"},404)}catch(o){return r.json({error:o.message},500)}}),h.post("/api/users",async r=>{try{let{user:o,tenantId:m}=await P(r.req.raw,E,l,u),b=await N(X,"create",r.req.raw,o,m,void 0,R,q);if(!b.allowed)return r.json({error:b.error},b.status||403);let n=await r.req.json();if(!n.email||!n.password)return r.json({error:"Email and password are required"},400);if(await L.findUserByEmail(n.email))return r.json({error:"Email already in use"},400);let p=n.role||"customer";if(p!=="customer"&&o?.role!=="super_admin")return r.json({error:"Forbidden: Only super_admin can assign administrative roles"},403);let A=await L.createUser({email:n.email,password:n.password,name:n.name,role:p,avatar:n.avatar,tenantId:n.tenantId});return o&&L?.createAuditLog({action:"user_create",userId:o.id,resource:"users",resourceId:A.id,success:!0}),r.json({data:A,message:"User created successfully"},201)}catch(o){return r.json({error:o.message},500)}}),h.patch("/api/users/:id",async r=>{try{let{user:o,tenantId:m}=await P(r.req.raw,E,l,u),b=await N(X,"update",r.req.raw,o,m,void 0,R,q);if(!b.allowed)return r.json({error:b.error},b.status||403);let n=r.req.param("id"),i=await r.req.json(),p=await L.findUserById(n);if(!p)return r.json({error:"User not found"},404);let A={};if(i.name!==void 0&&(A.name=i.name),i.email!==void 0&&(A.email=i.email),i.role!==void 0&&i.role!==p.role){if(o?.role!=="super_admin")return r.json({error:"Forbidden: Only super_admin can modify user roles"},403);A.role=i.role;}i.avatar!==void 0&&(A.avatar=typeof i.avatar=="object"&&i.avatar!==null?i.avatar.id||String(i.avatar):i.avatar),i.tenantId!==void 0&&(A.tenantId=i.tenantId),i.emailVerified!==void 0&&(A.emailVerified=i.emailVerified),i.locked!==void 0&&(A.locked=i.locked),i.failedLoginAttempts!==void 0&&(A.failedLoginAttempts=i.failedLoginAttempts),i.lastLogin!==void 0&&(A.lastLogin=i.lastLogin);let g=await L.updateUser(n,A);return g?(o&&(L?.createAuditLog({action:"user_update",userId:o.id,resource:"users",resourceId:n,success:!0}),i.role&&p.role!==i.role&&L?.createAuditLog({action:"role_change",userId:o.id,resource:"users",resourceId:n,success:!0,metadata:{oldRole:p.role,newRole:i.role}})),r.json({data:g,message:"User updated successfully"})):r.json({error:"User update failed"},500)}catch(o){return r.json({error:o.message},500)}}),h.delete("/api/users/:id",async r=>{try{let{user:o,tenantId:m}=await P(r.req.raw,E,l,u),b=await N(X,"delete",r.req.raw,o,m,void 0,R,q);if(!b.allowed)return r.json({error:b.error},b.status||403);let n=r.req.param("id");if(o&&o.id===n)return r.json({error:"You cannot delete your own account"},403);let i=await L.findUserById(n);return i?await L.deleteUser(n)?(o&&L?.createAuditLog({action:"user_delete",userId:o.id,resource:"users",resourceId:n,success:!0}),r.json({data:i,message:"User deleted successfully"})):r.json({error:"User deletion failed"},500):r.json({error:"User not found"},404)}catch(o){return r.json({error:o.message},500)}}),h.get("/api/auth/audit-logs",async r=>{try{let{user:o,tenantId:m}=await P(r.req.raw,E,l,u),b=e.getCollection("audit_logs");if(b){let T=await N(b,"read",r.req.raw,o,m,void 0,R,q);if(!T.allowed)return r.json({error:T.error},T.status||403)}else if(!o)return r.json({error:"Authentication required"},401);let n=parseInt(r.req.query("page")||"1"),i=Math.min(parseInt(r.req.query("limit")||"50"),100),p=r.req.query("action")||void 0,A=r.req.query("userId")||void 0,g=r.req.query("resource")||void 0,w=await L.findAuditLogs({action:p,userId:A,resource:g,limit:i,offset:(n-1)*i});return r.json({docs:w.logs,totalDocs:w.total,limit:i,totalPages:Math.ceil(w.total/i),page:n,pagingCounter:(n-1)*i+1,hasPrevPage:n>1,hasNextPage:n<Math.ceil(w.total/i),prevPage:n>1?n-1:null,nextPage:n<Math.ceil(w.total/i)?n+1:null})}catch(o){return console.error("[API] Error listing audit logs:",o),r.json({error:o.message},500)}});let G=null,ae=null,K=async()=>{if(ae)throw ae;if(!G)try{let r="sqlite";"dialect"in t&&t.dialect==="postgres"&&t instanceof chunkFUWPXR6W_cjs.c?r=t.dialect:"dialect"in t&&t.dialect==="mongodb"&&(r="mongodb");let o=r==="postgres"&&t instanceof chunkFUWPXR6W_cjs.c?t.client:t;G=await He.init(o,{dialect:r});}catch(r){throw console.error("[getMedia] Init error:",r),ae=r,r}return G};h.get("/api/media",async r=>{try{let{user:o}=await P(r.req.raw,E,l,u);if(!o)return r.json({error:"Authentication required"},401);let m=await K(),b=new URL(r.req.url).origin,n=parseInt(r.req.query("page")||"1"),i=parseInt(r.req.query("limit")||"30"),p=r.req.query("search")||"",A=r.req.query("type")||"",g=r.req.query("folder")||"",w=await m.find({page:n,limit:i,search:p,type:A,folder:g},b);return r.json(w)}catch(o){return console.error("[Media] find error:",o),r.json({error:o.message},500)}}),h.post("/api/media/upload",async r=>{try{let{user:o}=await P(r.req.raw,E,l,u);if(!o)return r.json({error:"Authentication required"},401);let m=await K(),b=r.req.header("content-type")||"",n=new URL(r.req.url).origin;if(b.includes("multipart/form-data")){let w=await r.req.formData(),T=w.get("file"),S=w.get("folder")||"";if(!T)return r.json({error:"No file uploaded"},400);let v=await m.upload(T,S,n);return r.json(v)}let i=await r.req.json(),{url:p}=i,A=i.folder||"";if(!p)return r.json({error:"No URL provided"},400);let g=await m.uploadFromUrl(p,A,n);return r.json(g)}catch(o){return console.error("[Media] upload error:",o),r.json({error:o.message},500)}}),h.get("/api/media/folders",async r=>{try{let{user:o}=await P(r.req.raw,E,l,u);if(!o)return r.json({error:"Authentication required"},401);let b=await(await K()).listFolders();return r.json(b)}catch(o){return console.error("[Media] folders error:",o),r.json({error:o.message},500)}}),h.post("/api/media/folders",async r=>{try{let{user:o}=await P(r.req.raw,E,l,u);if(!o)return r.json({error:"Authentication required"},401);let m=await K(),b=await r.req.json(),{name:n,parentPath:i}=b;return n?(await m.createFolder(n,i||""),r.json({message:"Folder created",path:i?`${i}/${n}`:n})):r.json({error:"Folder name is required"},400)}catch(o){return console.error("[Media] create folder error:",o),r.json({error:o.message},500)}}),h.delete("/api/media/folders",async r=>{try{let{user:o}=await P(r.req.raw,E,l,u);if(!o)return r.json({error:"Authentication required"},401);let m=await K(),b=r.req.query("path");return b?(await m.deleteFolder(b),r.json({message:"Folder deleted"})):r.json({error:"Path is required"},400)}catch(o){return console.error("[Media] delete folder error:",o),r.json({error:o.message},500)}}),h.delete("/api/media/:id",async r=>{try{let{user:o}=await P(r.req.raw,E,l,u);if(!o)return r.json({error:"Authentication required"},401);let m=await K(),b=r.req.param("id"),n=new URL(r.req.url).origin;return await m.delete(b,n),r.json({success:!0})}catch(o){return console.error("[Media] delete error:",o),r.json({error:o.message},500)}}),h.get("/api/media/resize",async r=>{try{let{user:o}=await P(r.req.raw,E,l,u);if(!o)return r.json({error:"Authentication required"},401);let m=r.req.query("url"),b=parseInt(r.req.query("w")||"0"),n=parseInt(r.req.query("h")||"0"),i=r.req.query("fit")||"cover",p=parseFloat(r.req.query("cx")||"0"),A=parseFloat(r.req.query("cy")||"0"),g=parseFloat(r.req.query("cw")||"0"),w=parseFloat(r.req.query("ch")||"0");if(!m)return r.json({error:"URL is required"},400);let S=(await K()).storage;if(S.name!=="local")return r.redirect(m);let v=S.config?.uploadDir||ze.join(process.cwd(),"public","uploads"),x=S.config?.baseUrl||"/uploads";if(!m.startsWith(x))return r.redirect(m);let U=m.replace(x,""),j=ze.join(v,U);if(!fs.existsSync(j))return r.json({error:"File not found"},404);let $=fs.readFileSync(j),{default:D}=await import('sharp'),_=D($);if(g>0&&w>0){let M=await D($).metadata(),oe=M.width||0,W=M.height||0;if(oe>0&&W>0){let H=Math.max(0,Math.min(Math.round(p/100*oe),oe-1)),Ae=Math.max(0,Math.min(Math.round(A/100*W),W-1)),mr=Math.max(1,Math.min(Math.round(g/100*oe),oe-H)),gr=Math.max(1,Math.min(Math.round(w/100*W),W-Ae));_=_.extract({left:H,top:Ae,width:mr,height:gr});}}(b>0||n>0)&&(_=_.resize({width:b>0?b:void 0,height:n>0?n:void 0,fit:i}));let F=await _.toBuffer(),Y=await D($).metadata();return r.header("Content-Type",`image/${Y.format||"webp"}`),r.header("Cache-Control","public, max-age=31536000, immutable"),r.body(F)}catch(o){return console.error("[Media] resize error:",o),r.json({error:o.message},500)}}),h.get("/api/media/:id",async r=>{try{let{user:o}=await P(r.req.raw,E,l,u);if(!o)return r.json({error:"Authentication required"},401);let m=await K(),b=r.req.param("id"),n=new URL(r.req.url).origin,i=await m.findById(b,n);return i?r.json(i):r.json({error:"Media not found"},404)}catch(o){return console.error("[Media] get error:",o),r.json({error:o.message},500)}}),h.patch("/api/media/:id",async r=>{try{let{user:o}=await P(r.req.raw,E,l,u);if(!o)return r.json({error:"Authentication required"},401);let m=await K(),b=r.req.param("id"),n=await r.req.json(),i=new URL(r.req.url).origin,p=["folder","metadata","title","alt","caption","originalName"],A={};for(let g of p)n[g]!==void 0&&(A[g]=n[g]);if(Object.keys(A).length>0){let g=await m.update(b,A,i);return r.json({doc:g})}return r.json({error:"No valid fields to update"},400)}catch(o){return console.error("[Media] update error:",o),r.json({error:o.message},500)}}),h.get("/api/media/test",async r=>{try{let{user:o}=await P(r.req.raw,E,l,u);if(!o)return r.json({error:"Authentication required"},401);let m=await K();return r.json({status:m?"initialized":"failed",serviceType:m?.constructor?.name})}catch(o){return console.error("[test] Error:",o),r.json({error:o.message,type:o.constructor?.name,stack:o.stack},500)}}),h.get("/api/storage-status",async r=>{try{let{user:o}=await P(r.req.raw,E,l,u);if(!o)return r.json({error:"Authentication required"},401);let m=!1,b="local";if(t)try{let n=t.prepare('SELECT provider FROM "_globals_storage-settings" LIMIT 1').get();n&&n.provider&&(m=!0,b=n.provider==="aws"?"s3":n.provider);}catch{try{let n=await t.findOne({collection:"_globals_storage-settings",where:{},draft:!0});n&&n.provider&&(m=!0,b=n.provider==="aws"?"s3":n.provider);}catch{}}return r.json({provider:b,configured:m,usage:0,limit:"unlimited"})}catch(o){return console.error("[Storage] status error:",o),r.json({error:o.message},500)}}),h.get("/api/plugins",async r=>{try{let{user:o}=await P(r.req.raw,E,l,u);if(!o)return r.json({error:"Authentication required"},401);let m=e.getPlugins(),b=e.storageProviders,n=await Promise.all(m.map(async i=>{let p=!0,A=i.name,g={};try{let S=await t.findOne({collection:"_globals_plugin-settings",where:{},draft:!0});S&&S.states&&(g=S.states);}catch{}g[A]!==void 0&&(p=g[A]),b.setPluginEnabled(A,p);let w=A.replace(/^@[^/]+\//,"");w=w.replace(/^(plugin|kyro)-/,"");let T={ai:"AI",seo:"SEO",s3:"S3",aws:"AWS",api:"API",ui:"UI",ftp:"FTP"};if(w=w.split("-").map(S=>{let v=S.toLowerCase();return T[v]?T[v]:S.charAt(0).toUpperCase()+S.slice(1)}).join(" "),w.toLowerCase().startsWith("storage ")){let S=w.split(" ");S.length===2&&(w=`${S[1]} Storage`);}return {id:A,name:i.displayName||w,version:i.version||"1.0.0",description:i.description||"",enabled:p,status:p?"active":"disabled"}}));return r.json(n)}catch(o){return console.error("[Plugins] list error:",o),r.json({error:o.message},500)}}),h.put("/api/plugins/:name/toggle",async r=>{try{let{user:o}=await P(r.req.raw,E,l,u);if(!o)return r.json({error:"Authentication required"},401);let m=r.req.param("name"),b=e.storageProviders,i=!b.isPluginEnabled(m),p=[];if(!i)for(let g of b.getAll())g.pluginName===m&&p.push(g.type);if(!(r.req.query("force")==="1")&&!i&&p.length>0){let g="local";try{let w=t?.prepare?.('SELECT provider FROM "_globals_storage-settings" LIMIT 1')?.get();w?.provider&&(g=w.provider);}catch{try{let w=await t?.findOne?.({collection:"_globals_storage-settings",where:{},draft:!0});w?.provider&&(g=w.provider);}catch{}}if(p.includes(g))return r.json({error:`Cannot disable "${m}" \u2014 storage provider "${g}" is currently active. Switch to Local storage first.`,requiresAction:!0,activeProvider:g},409)}try{let g={},w="global",T=await t.findOne({collection:"_globals_plugin-settings",where:{},draft:!0});T&&(g=T.states||{},w=T.id),g[m]=i,T?await t.update({collection:"_globals_plugin-settings",id:w,data:{states:g}}):await t.create({collection:"_globals_plugin-settings",data:{states:g,id:"global"}});}catch(g){console.warn(`[Plugins] Could not persist state for "${m}":`,g);}return b.setPluginEnabled(m,i),r.json({name:m,enabled:i})}catch(o){return console.error("[Plugins] toggle error:",o),r.json({error:o.message},500)}}),h.get("/api/health",r=>r.json({status:"ok",version:"0.11.0",collections:e.getCollectionSlugs(),timestamp:new Date().toISOString()})),h.get("/api/metrics",async r=>{try{let{user:o,tenantId:m}=await P(r.req.raw,E,l,u);if(!o)return r.json({error:"Authentication required"},401);let b=o.role==="admin"||o.role==="super_admin",i=e.getCollectionSlugs().filter(x=>!["users","audit_logs","media","_globals_access-settings","_globals_brand-settings"].includes(x)&&!x.startsWith("_globals_")).filter(x=>b||chunkQ3Q7BJVQ_cjs.a(o,`${x}:read`)),p=0,A={};await Promise.all(i.map(async x=>{try{let j=(await t.find({collection:x,where:{},limit:1,page:1,tenantId:m})).totalDocs??0;p+=j,A[x]=j;}catch{}}));let g=0;try{g=(await t.find({collection:"media",where:{},limit:1,page:1,tenantId:m})).totalDocs??0;}catch{}let w=0;try{w=(await t.find({collection:"users",where:{},limit:1,page:1,tenantId:m})).totalDocs??0;}catch{}let T=0;try{if(y){let x=await y.getWebhooks();T=Array.isArray(x)?x.length:0;}}catch{}let S=0;try{S=(await t.find({collection:chunkNY47CFVP_cjs.d,where:{},limit:1,page:1,tenantId:m})).totalDocs??0;}catch{}let v=p+g+w;return r.json({totalDocuments:p,totalMedia:b||chunkQ3Q7BJVQ_cjs.a(o,"media:read")?g:void 0,totalUsers:b||chunkQ3Q7BJVQ_cjs.a(o,"users:read")?w:void 0,totalWebhooks:b?T:void 0,totalApiKeys:b?S:void 0,totalStoredRecords:v,collectionCounts:A,collections:i.length,timestamp:new Date().toISOString()})}catch(o){return console.error("[API] Metrics error:",o),r.json({error:o.message},500)}}),h.get("/api/analytics",async r=>{try{let{user:o,tenantId:m}=await P(r.req.raw,E,l,u);if(!o)return r.json({error:"Authentication required"},401);if(!(o.role==="admin"||o.role==="super_admin"))return r.json({error:"Unauthorized"},403);let i=(await t.find({collection:"orders",where:{},limit:1e3,page:1,tenantId:m})).docs||[],p=await t.findOne({collection:"_globals_store-settings",where:{},tenantId:m}),A=p?.currency?.code||p?.currency||"USD",g={},w={},T={};i.forEach(x=>{let U=x.createdAt||x.updatedAt,j=U?new Date(U).toISOString().split("T")[0]:new Date().toISOString().split("T")[0];g[j]||(g[j]=0),w[j]||(w[j]=0);let $=typeof x.total=="number"?x.total:parseFloat(String(x.total||0));g[j]+=isNaN($)?0:$,w[j]+=1;let D=x.orderStatus||x.status||"pending";T[D]=(T[D]||0)+1;});let S=Object.keys(g).sort().map(x=>({date:x,revenue:Math.round(g[x]*100)/100,orders:w[x]})),v=Math.round(S.reduce((x,U)=>x+U.revenue,0)*100)/100;return r.json({chartData:S,totalRevenue:v,totalOrders:i.length,ordersByStatus:T,currencyCode:typeof A=="string"?A:"USD"})}catch(o){return r.json({error:o.message},500)}}),h.get("/api/kyro/schema",async r=>{let{user:o}=await P(r.req.raw,E,l,u);if(!o)return r.json({error:"Authentication required"},401);let m=n=>n.map(i=>{let p={name:i.name,type:i.type,label:i.label,required:i.required??false,unique:i.unique??false,indexed:i.indexed??false,defaultValue:i.defaultValue,admin:i.admin?{...i.admin}:void 0};return i.minLength!==void 0&&(p.minLength=i.minLength),i.maxLength!==void 0&&(p.maxLength=i.maxLength),i.pattern!==void 0&&(p.pattern=i.pattern),i.variant!==void 0&&(p.variant=i.variant),i.hasMany!==void 0&&(p.hasMany=i.hasMany),i.min!==void 0&&(p.min=i.min),i.max!==void 0&&(p.max=i.max),i.step!==void 0&&(p.step=i.step),i.integer!==void 0&&(p.integer=i.integer),i.options&&(p.options=i.options),i.relationTo&&(p.relationTo=i.relationTo),i.maxDepth!==void 0&&(p.maxDepth=i.maxDepth),i.minRows!==void 0&&(p.minRows=i.minRows),i.maxRows!==void 0&&(p.maxRows=i.maxRows),i.localized!==void 0&&(p.localized=i.localized),i.language&&(p.language=i.language),i.format&&(p.format=i.format),i.allowedTypes&&(p.allowedTypes=i.allowedTypes),i.maxSize&&(p.maxSize=i.maxSize),(i.type==="group"||i.type==="row"||i.type==="collapsible"&&i.fields)&&(p.fields=m(i.fields)),i.type==="array"&&i.fields&&(p.fields=m(i.fields)),i.type==="blocks"&&i.blocks&&(p.blocks=i.blocks.map(A=>({slug:A.slug,label:A.label,fields:m(A.fields)}))),i.type==="tabs"&&i.tabs&&(p.tabs=i.tabs.map(A=>({label:A.label,name:A.name,fields:m(A.fields)}))),p}),b={collections:{},globals:{}};for(let n of e.getCollections()){let i=n.slug;try{b.collections[i]={slug:i,label:n.label||i,fields:m(n.fields),jsonSchema:zodToJsonSchema.zodToJsonSchema(e.getZodSchema(i),{target:"openApi3"}),createSchema:zodToJsonSchema.zodToJsonSchema(e.getCreateZodSchema(i),{target:"openApi3"}),updateSchema:zodToJsonSchema.zodToJsonSchema(e.getUpdateZodSchema(i),{target:"openApi3"}),procedures:{find:{collection:i,where:"Record<string,any>",sort:"string",limit:"number",page:"number",depth:"number",select:"string[]",draft:"boolean"},findByID:{collection:i,id:"string",depth:"number",select:"string[]",draft:"boolean"},create:{collection:i,data:"Record<string,any>",depth:"number",select:"string[]"},update:{collection:i,id:"string",data:"Record<string,any>",depth:"number",select:"string[]",baseUpdatedAt:"string"},delete:{collection:i,id:"string"},count:{collection:i,where:"Record<string,any>"}}};}catch{}}for(let n of e.getGlobals()){let i=n.slug,p=n.fields;if(i==="storage-settings"){let A=e.storageProviders,g=A.getAll(),w=new Set(A.getAllAvailable(S=>A.isPluginEnabled(S)).map(S=>S.type));w.add("local");let T=new Set(g.map(S=>S.type));p=p.filter(S=>S.type==="group"&&S.name&&T.has(S.name)?w.has(S.name):true).map(S=>S.name==="provider"&&S.type==="select"?{...S,options:S.options.filter(v=>w.has(v.value))}:S);}try{b.globals[i]={slug:i,label:n.label||i,fields:m(p),jsonSchema:zodToJsonSchema.zodToJsonSchema(e.getZodSchema(i),{target:"openApi3"}),procedures:{get:{},update:{data:"Record<string,any>"}}};}catch{}}return r.json(b)}),h.get("/api/collections",async r=>{let{user:o}=await P(r.req.raw,E,l,u);if(!o)return r.json({error:"Authentication required"},401);let m=e.getCollections().map(b=>({slug:b.slug,label:b.label||b.slug,fields:b.fields.filter(n=>n.name).map(n=>({name:n.name,type:n.type,required:n.required,label:n.label}))}));return r.json(m)});function Re(r,o,m){if(m in o)return o[m];for(let b of r)if(b.name){if(b.type==="tabs"&&b.tabs){let n=o[b.name];if(n&&typeof n=="object"&&m in n)return n[m]}if((b.type==="group"||b.type==="collapsible")&&b.fields){let n=o[b.name];if(n&&typeof n=="object"){if(m in n)return n[m];let i=Re(b.fields,n,m);if(i!==void 0)return i}}}}h.get("/api/search",async r=>{try{let o=r.req.query("q")||"",m=r.req.query("collections")||"",b=Math.min(parseInt(r.req.query("limit")||"10"),50);if(!o||o.length<2)return r.json({results:[],message:"Query too short"});let{user:n,tenantId:i}=await P(r.req.raw,E,l,u),p=m?m.split(",").filter(Boolean):e.getCollectionSlugs(),A=[],g=new RegExp(o.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"i");for(let w of e.getCollections()){if(!p.includes(w.slug)||!(await N(w,"read",r.req.raw,n,i,void 0,R,q)).allowed)continue;let S=w.fields.filter(v=>v.name&&v.name!=="id"&&(v.type==="text"||v.type==="email"||v.type==="textarea"||v.type==="richtext"||v.indexed)&&!v.admin?.hidden).map(v=>v.name);if(S.length!==0)try{let v=S.map(U=>{let j={};return j[U]={like:`%${o}%`},j}),x=await t.find({collection:w.slug,where:{OR:v},limit:b,tenantId:i});await chunkILEZ3NYX_cjs.a(x.docs,w.fields,t,e,1,0);for(let U of x.docs){let j=w.admin?.useAsTitle||S.find(D=>D==="title"||D==="name"||D==="heading"||D==="slug"),$=j?Re(w.fields,U,j)??U.id:U.id;A.push({collection:w.slug,label:w.label||w.slug,id:U.id,title:String($||"Untitled"),doc:U});}}catch(v){console.error(`Search error for ${w.slug}:`,v);}}return A.sort((w,T)=>w.label.localeCompare(T.label)),r.json({results:A})}catch(o){return r.json({error:o.message,results:[]},500)}}),h.get("/api/keys",async r=>{try{let{user:o,tenantId:m}=await P(r.req.raw,E,l,u);if(!o||!chunkQ3Q7BJVQ_cjs.a(o,"users:read"))return r.json({error:"Forbidden"},403);let b=parseInt(r.req.query("page")||"1"),n=Math.min(parseInt(r.req.query("limit")||"50"),100),i=await t.find({collection:chunkNY47CFVP_cjs.d,where:{},page:b,limit:n,tenantId:m}),p=(i.docs||[]).map(A=>({id:A.id,name:A.name,keyPrefix:A.keyPrefix,permissions:A.permissions||[],lastUsed:A.lastUsedAt,createdAt:A.createdAt}));return r.json({docs:p,totalDocs:i.totalDocs||p.length,totalPages:i.totalPages||1})}catch(o){return console.error("[ApiKeys] GET error:",o),r.json({error:o.message},500)}}),h.post("/api/keys",async r=>{try{let{user:o}=await P(r.req.raw,E,l,u);if(!o||!chunkQ3Q7BJVQ_cjs.a(o,"users:admin"))return r.json({error:"Forbidden"},403);let m=await r.req.json();if(!m.name||typeof m.name!="string")return r.json({error:"name is required"},400);let b=chunkNY47CFVP_cjs.i(),n=await t.create({collection:chunkNY47CFVP_cjs.d,data:{userId:o.id,name:m.name,key:b,keyPrefix:chunkNY47CFVP_cjs.j(b),permissions:Array.isArray(m.permissions)?m.permissions:["*"],expiresAt:m.expiresAt||null,createdAt:new Date().toISOString()}});return await L?.createAuditLog({action:"api_key_create",userId:o.id,resource:"api_key",resourceId:n.id,success:!0,metadata:{keyName:m.name}}),r.json({...n,key:b,permissions:Array.isArray(m.permissions)?m.permissions:["*"]},201)}catch(o){return console.error("[ApiKeys] POST error:",o),r.json({error:o.message},500)}}),h.delete("/api/keys/:id",async r=>{try{let{user:o}=await P(r.req.raw,E,l,u);if(!o||!chunkQ3Q7BJVQ_cjs.a(o,"users:admin"))return r.json({error:"Forbidden"},403);let m=r.req.param("id"),b=await t.findByID({collection:chunkNY47CFVP_cjs.d,id:m});return b?(await t.delete({collection:chunkNY47CFVP_cjs.d,id:m}),await L?.createAuditLog({action:"api_key_delete",userId:o.id,resource:"api_key",resourceId:m,success:!0,metadata:{keyName:b.name}}),r.json({message:"API key deleted"})):r.json({error:"API key not found"},404)}catch(o){return console.error("[ApiKeys] DELETE error:",o),r.json({error:o.message},500)}}),h.patch("/api/keys/:id",async r=>{try{let{user:o}=await P(r.req.raw,E,l,u);if(!o||!chunkQ3Q7BJVQ_cjs.a(o,"users:admin"))return r.json({error:"Forbidden"},403);let m=r.req.param("id"),b=await r.req.json(),n=await t.findByID({collection:chunkNY47CFVP_cjs.d,id:m});if(!n)return r.json({error:"API key not found"},404);let i={};if(typeof b.name=="string"&&b.name.trim()&&(i.name=b.name.trim()),Array.isArray(b.permissions)&&(i.permissions=b.permissions),b.expiresAt!==void 0&&(i.expiresAt=b.expiresAt||null),Object.keys(i).length===0)return r.json({error:"Nothing to update"},400);let p=await t.update({collection:chunkNY47CFVP_cjs.d,id:m,data:i});return r.json({...p,keyPrefix:n.keyPrefix})}catch(o){return console.error("[ApiKeys] PATCH error:",o),r.json({error:o.message},500)}}),h.post("/api/keys/:id/rotate",async r=>{try{let{user:o}=await P(r.req.raw,E,l,u);if(!o||!chunkQ3Q7BJVQ_cjs.a(o,"users:admin"))return r.json({error:"Forbidden"},403);let m=r.req.param("id"),b=await t.findByID({collection:chunkNY47CFVP_cjs.d,id:m});if(!b)return r.json({error:"API key not found"},404);let n=chunkNY47CFVP_cjs.i(),i=await t.update({collection:chunkNY47CFVP_cjs.d,id:m,data:{key:n,keyPrefix:chunkNY47CFVP_cjs.j(n),lastUsedAt:null}});return await L?.createAuditLog({action:"api_key_rotate",userId:o.id,resource:"api_key",resourceId:m,success:!0,metadata:{keyName:b.name}}),r.json({...i,key:n,permissions:b.permissions,expiresAt:b.expiresAt})}catch(o){return console.error("[ApiKeys] rotate error:",o),r.json({error:o.message},500)}}),h.get("/api/webhooks/actions",async r=>{try{let{user:o}=await P(r.req.raw,E,l,u);if(!o||!chunkQ3Q7BJVQ_cjs.a(o,"users:read"))return r.json({error:"Forbidden"},403);let m={generic:{label:"Custom URL",description:"POST to any endpoint with Kyro payload",configFields:[],envVars:[]},"github-push":{label:"GitHub Push",description:"Push an empty commit to simulate a push event",configFields:[{name:"githubOwner",label:"Owner",required:!0,placeholder:"e.g., kyro-dev"},{name:"githubRepo",label:"Repository",required:!0,placeholder:"e.g., my-website"},{name:"githubBranch",label:"Branch",required:!1,placeholder:"main"}],envVars:["GITHUB_TOKEN"]}};return r.json({actions:m})}catch(o){return console.error("[Webhooks] actions error:",o),r.json({error:o.message},500)}}),h.get("/api/webhooks",async r=>{try{let{user:o}=await P(r.req.raw,E,l,u);if(!o||!chunkQ3Q7BJVQ_cjs.a(o,"users:read"))return r.json({error:"Forbidden"},403);if(!y)return r.json({error:"Webhook service not available"},503);let m=await y.getWebhooks();return r.json({docs:m})}catch(o){return console.error("[Webhooks] GET error:",o),r.json({error:o.message},500)}}),h.post("/api/webhooks",async r=>{try{let{user:o}=await P(r.req.raw,E,l,u);if(!o||!chunkQ3Q7BJVQ_cjs.a(o,"users:admin"))return r.json({error:"Forbidden"},403);if(!y)return r.json({error:"Webhook service not available"},503);let m=await r.req.json(),b=await y.createWebhook(m);return await L?.createAuditLog({action:"webhook_create",userId:o.id,resource:"webhook",resourceId:b.id,success:!0,metadata:{name:b.name,url:b.url}}),r.json(b,201)}catch(o){return console.error("[Webhooks] POST error:",o),r.json({error:o.message},500)}}),h.get("/api/webhooks/:id",async r=>{try{let{user:o}=await P(r.req.raw,E,l,u);if(!o||!chunkQ3Q7BJVQ_cjs.a(o,"users:read"))return r.json({error:"Forbidden"},403);if(!y)return r.json({error:"Webhook service not available"},503);let m=r.req.param("id"),b=await y.getWebhookById(m);return b?r.json(b):r.json({error:"Webhook not found"},404)}catch(o){return console.error("[Webhooks] GET :id error:",o),r.json({error:o.message},500)}}),h.patch("/api/webhooks/:id",async r=>{try{let{user:o}=await P(r.req.raw,E,l,u);if(!o||!chunkQ3Q7BJVQ_cjs.a(o,"users:admin"))return r.json({error:"Forbidden"},403);if(!y)return r.json({error:"Webhook service not available"},503);let m=r.req.param("id"),b=await r.req.json(),n=await y.updateWebhook(m,b);return n?(await L?.createAuditLog({action:"webhook_update",userId:o.id,resource:"webhook",resourceId:m,success:!0,metadata:{name:n.name}}),r.json(n)):r.json({error:"Webhook not found"},404)}catch(o){return console.error("[Webhooks] PATCH error:",o),r.json({error:o.message},500)}}),h.delete("/api/webhooks/:id",async r=>{try{let{user:o}=await P(r.req.raw,E,l,u);if(!o||!chunkQ3Q7BJVQ_cjs.a(o,"users:admin"))return r.json({error:"Forbidden"},403);if(!y)return r.json({error:"Webhook service not available"},503);let m=r.req.param("id"),b=await y.getWebhookById(m);return b?(await y.deleteWebhook(m),await L?.createAuditLog({action:"webhook_delete",userId:o.id,resource:"webhook",resourceId:m,success:!0,metadata:{name:b.name}}),r.json({message:"Webhook deleted"})):r.json({error:"Webhook not found"},404)}catch(o){return console.error("[Webhooks] DELETE error:",o),r.json({error:o.message},500)}}),h.post("/api/webhooks/:id/test",async r=>{try{let{user:o}=await P(r.req.raw,E,l,u);if(!o||!chunkQ3Q7BJVQ_cjs.a(o,"users:admin"))return r.json({error:"Forbidden"},403);if(!y)return r.json({error:"Webhook service not available"},503);let m=r.req.param("id"),b=await y.testWebhook(m);return b?r.json(b):r.json({error:"Webhook not found"},404)}catch(o){return console.error("[Webhooks] test error:",o),r.json({error:o.message},500)}}),h.get("/api/webhooks/:id/history",async r=>{try{let{user:o}=await P(r.req.raw,E,l,u);if(!o||!chunkQ3Q7BJVQ_cjs.a(o,"users:read"))return r.json({error:"Forbidden"},403);if(!y)return r.json({error:"Webhook service not available"},503);let m=r.req.param("id"),b=Math.min(parseInt(r.req.query("limit")||"50"),100),n=await y.getDeliveryHistory(m,b);return r.json({docs:n})}catch(o){return console.error("[Webhooks] history error:",o),r.json({error:o.message},500)}});function Ee(r){let o={},m=["name","type","required","hasMany","relationTo","options","min","max","minLength","maxLength","defaultValue","label","localized","admin","unique","index","hidden","readOnly","deprecated"];for(let b of m)b in r&&(o[b]=r[b]);return r.fields&&(o.fields=r.fields.map(Ee)),r.tabs&&(o.tabs=r.tabs.map(b=>({label:b.label,name:b.name,fields:b.fields.map(Ee)}))),o}h.get("/api/__schema",async r=>{try{let{user:o,apiKeyContext:m}=await P(r.req.raw,E,l,u);if(!o&&!m)return r.json({error:"Unauthorized"},401);let n=e.getCollections().filter(i=>i.slug!=="users"&&i.slug!=="audit_logs").map(i=>({slug:i.slug,label:i.label,labelPlural:i.labelPlural,singularLabel:i.singularLabel,timestamps:i.timestamps,auth:!!i.auth,tenantScoped:!!i.tenantScoped,upload:i.upload?{staticDir:i.upload.staticDir,imageSizes:i.upload.imageSizes,mimeTypes:i.upload.mimeTypes}:void 0,fields:i.fields.map(Ee)}));return r.json(n)}catch(o){return console.error("[Schema] error:",o),r.json({error:o.message},500)}});let vt=e.getCollections();for(let r of vt){let b=function(n,i){let p=[],A=new Set([...Object.keys(n),...Object.keys(i)]);for(let g of A)g==="id"||g==="createdAt"||g==="updatedAt"||JSON.stringify(n[g])!==JSON.stringify(i[g])&&p.push({field:g,oldValue:g in n?n[g]:void 0,newValue:g in i?i[g]:void 0});return p};let o=r.slug;if(o==="users"||o==="audit_logs")continue;let m=`/api/${o}`;h.post(`${m}/dynamic-options/:fieldName`,async n=>{try{let{user:i,tenantId:p,apiKeyContext:A}=await P(n.req.raw,E,l,u),g=await N(r,"read",n.req.raw,i,p,A,R,q);if(!g.allowed)return n.json({error:g.error},g.status||403);let w=n.req.param("fieldName"),T=await n.req.json(),{data:S,siblingData:v}=T,x=ge(r.fields,w);if(!x)return n.json({error:"Field not found"},404);if(x.type!=="select")return n.json({error:"Field is not a select field"},400);let U=[];return typeof x.options=="function"?U=await x.options({data:S||{},siblingData:v||{}}):Array.isArray(x.options)&&(U=x.options),n.json({options:U})}catch(i){return n.json({error:i.message},500)}}),h.get(m,async n=>{try{let{user:i,tenantId:p,apiKeyContext:A}=await P(n.req.raw,E,l,u),g=await N(r,"read",n.req.raw,i,p,A,R,q);if(!g.allowed)return n.json({error:g.error},g.status||403);p&&t.setTenantContext({tenantId:p,userId:i?.id??"",role:i?.role,isSuperAdmin:i?.role==="super_admin"});let w=new URL(n.req.url),T=parseInt(w.searchParams.get("page")||"1"),S=Math.min(parseInt(w.searchParams.get("limit")||"10"),100),v=w.searchParams.get("sort")||void 0,x=parseInt(w.searchParams.get("depth")||"0"),U=w.searchParams.get("select")?.split(",")||void 0,j=w.searchParams.get("draft"),$=j==="true"?!0:j==="false"?!1:!!i,D={},_=w.searchParams.get("where");if(_)try{D=JSON.parse(_);}catch{return n.json({error:"Invalid JSON in where parameter"},400)}let F=await t.find({collection:o,where:D,sort:v,limit:S,page:T,depth:x,tenantId:p,select:U,draft:$});return await chunkILEZ3NYX_cjs.a(F.docs,r.fields,t,e,1,x),n.json(chunkG7SSHELM_cjs.a(F))}catch(i){return console.error("[API] list error:",i),n.json({error:i.message},500)}}),h.get(`${m}/:id/versions`,async n=>{try{let{user:i,tenantId:p,apiKeyContext:A}=await P(n.req.raw,E,l,u),g=await N(r,"read",n.req.raw,i,p,A,R,q);if(!g.allowed)return n.json({error:g.error},g.status||403);let w=n.req.param("id");if(!w)return n.json({error:"Missing document ID"},400);let T=new URL(n.req.url),S=T.searchParams.get("compareA"),v=T.searchParams.get("compareB");if(Ge(L,A,`${m}/${w}/versions`,"GET",n.req.raw),S&&v){let[$,D]=await Promise.all([t.findVersionByID({collection:o,versionId:S,tenantId:p}),t.findVersionByID({collection:o,versionId:v,tenantId:p})]);if(!$||!D)return n.json({error:"Version not found"},404);let _=b($.data,D.data);return n.json({diffs:_})}let x=parseInt(T.searchParams.get("page")||"1"),U=Math.min(parseInt(T.searchParams.get("limit")||"10"),100),j=await t.findVersions({collection:o,documentId:w,page:x,limit:U,tenantId:p});return n.json(j)}catch(i){return console.error("[API] versions error:",i),n.json({error:i.message},500)}}),h.put(`${m}/:id/draft`,async n=>{try{let{user:i,tenantId:p,apiKeyContext:A}=await P(n.req.raw,E,l,u),g=await N(r,"update",n.req.raw,i,p,A,R,q);if(!g.allowed)return n.json({error:g.error},g.status||403);let w=n.req.param("id"),T=await n.req.json(),S=Ye(T),v=await t.findByID({collection:o,id:w,tenantId:p,draft:!0});if(!v)return n.json({error:"Document not found"},404);let x;T.delta?x={...v,...T.delta}:x=T.data??St(T);let U=await t.updateLatestVersion({collection:o,documentId:w,data:x,status:"draft",tenantId:p});return i&&L?.createAuditLog({action:"document_update",userId:i.id,resource:o,resourceId:w,success:!0,metadata:{type:"draft_save"}}),n.json({data:U,message:"Draft saved successfully"})}catch(i){return n.json({error:i.message},500)}}),h.delete(`${m}/:id/draft`,async n=>{try{let{user:i,tenantId:p,apiKeyContext:A}=await P(n.req.raw,E,l,u),g=await N(r,"update",n.req.raw,i,p,A,R,q);return g.allowed?(i&&L?.createAuditLog({action:"document_update",userId:i.id,resource:o,resourceId:n.req.param("id"),success:!0,metadata:{type:"draft_discard"}}),n.json({message:"Draft discarded successfully"})):n.json({error:g.error},g.status||403)}catch(i){return n.json({error:i.message},500)}}),h.get(`${m}/:id`,async n=>{try{let{user:i,tenantId:p,apiKeyContext:A}=await P(n.req.raw,E,l,u),g=new URL(n.req.url),w=g.searchParams.get("draft"),T=g.searchParams.get("kyroToken"),S=!1;if(w==="true"&&T&&s)try{let D=await jwt.verify(T,s,"HS256");D&&D.type==="preview"&&D.collection===r.slug&&(S=!0);}catch(D){console.warn("Invalid preview token",D);}if(!S){let D=await N(r,"read",n.req.raw,i,p,A,R,q);if(!D.allowed)return n.json({error:D.error},D.status||403)}let v=n.req.param("id"),x=parseInt(g.searchParams.get("depth")||"0"),U=g.searchParams.get("select")?.split(",")||void 0,j=w==="true"?!0:w==="false"?!1:!!i,$=await t.findByID({collection:o,id:v,depth:x,tenantId:p,select:U,draft:j});return !$&&r.fields.some(D=>D.name==="slug")&&($=await t.findOne({collection:o,where:{slug:v},tenantId:p,draft:j})),$?(await chunkILEZ3NYX_cjs.a([$],r.fields,t,e,1,x),n.json({data:chunkG7SSHELM_cjs.a($)})):n.json({error:"Document not found"},404)}catch(i){return n.json({error:i.message},500)}}),h.post(`${m}/preview-url`,async n=>{try{let{user:i,tenantId:p}=await P(n.req.raw,E,l,u),A=await N(r,"read",n.req.raw,i,p);if(!A.allowed)return n.json({error:A.error||"Forbidden"},A.status||403);let g=await n.req.json().catch(()=>({})),w="";s&&(w=await jwt.sign({type:"preview",collection:r.slug,id:g.id,exp:Math.floor(Date.now()/1e3)+3600},s,"HS256"));let T="";if(r.admin?.preview){T=await r.admin.preview(g,{req:n.req.raw,token:w});try{let S=new URL(T,"http://localhost");S.searchParams.has("preview")||S.searchParams.set("preview","true"),!S.searchParams.has("kyroToken")&&w&&S.searchParams.set("kyroToken",w),T=T.startsWith("http")?S.toString():`${S.pathname}${S.search}`;}catch{}}else {let S="";try{let x=await t.findOne({collection:"_globals_site-settings",where:{}});x?.siteUrl&&(S=x.siteUrl);}catch{}if(!S)return n.json({error:"No site URL configured in settings, and no custom preview function defined for this collection."},400);S=S.replace(/\/$/,"");let v=g.slug||g.id||"";T=`${S}/${r.slug}/${v}?preview=true&kyroToken=${w}`;}return n.json({url:T})}catch(i){return n.json({error:i.message},500)}}),h.post(m,async n=>{try{let{user:i,tenantId:p,apiKeyContext:A}=await P(n.req.raw,E,l,u),g=await N(r,"create",n.req.raw,i,p,A,R,q);if(!g.allowed)return n.json({error:g.error},g.status||403);p&&t.setTenantContext({tenantId:p,userId:i?.id??"",role:i?.role,isSuperAdmin:i?.role==="super_admin"}),Ge(L,A,m,"POST",n.req.raw);let T=await n.req.json();ye(T,r.fields),we(r.fields,T);let S=n.req.raw;if(r.hooks?.beforeValidate)for(let D of r.hooks.beforeValidate){let _=await D({collection:o,data:T,req:S,user:i,tenantId:p,operation:"create"});_&&typeof _=="object"&&!Array.isArray(_)&&Object.assign(T,_);}let v=e.getCreateZodSchema(o);try{T=v.parse(T);}catch(D){return n.json({error:`Validation failed: ${Xe(D.errors)}`,details:D.errors},400)}r.tenantScoped&&p&&(T.tenantId=p);let x=r.versions?.drafts===!0,U=r.fields.find(D=>D.name==="status"),j=U?.type==="select"&&Array.isArray(U.options)&&U.options.some(D=>D.value==="published");if(x?T.status="draft":j&&!T.status&&(T.status="published"),r.hooks?.beforeChange)for(let D of r.hooks.beforeChange){let _=await D({collection:o,data:T,req:S,user:i,tenantId:p,operation:"create"});_&&typeof _=="object"&&!Array.isArray(_)&&Object.assign(T,_);}let $=await t.create({collection:o,data:T,tenantId:p});if(x&&await t.createVersion({collection:o,documentId:$.id,data:T,status:"draft",createdBy:i?.id,changeDescription:"Created",tenantId:p}),r.hooks?.afterChange)for(let D of r.hooks.afterChange)await D({collection:o,doc:$,data:T,req:S,user:i,tenantId:p,operation:"create"});return y&&y.trigger(ke(o,"create"),{collection:o,operation:"create",data:$,user:i?{id:i.id,email:i.email,role:i.role}:void 0,tenantId:p}).catch(D=>console.error("[Webhook] Failed to trigger:",D)),i&&L?.createAuditLog({action:"document_create",userId:i.id,resource:o,resourceId:$.id,success:!0}),n.json({data:$,message:"Created successfully"},201)}catch(i){return i.name==="ZodError"?n.json({error:`Validation failed: ${Xe(i.errors)}`,details:i.errors},400):n.json({error:i.message},500)}}),h.patch(`${m}/:id`,async n=>{try{let{user:i,tenantId:p,apiKeyContext:A}=await P(n.req.raw,E,l,u),g=await N(r,"update",n.req.raw,i,p,A,R,q);if(!g.allowed)return n.json({error:g.error},g.status||403);let w=n.req.param("id"),T=await n.req.json(),S=Ye(T),v=await t.findByID({collection:o,id:w,tenantId:p,draft:!0});if(!v)return n.json({error:"Document not found"},404);if(S&&v.updatedAt&&S!==v.updatedAt)return n.json(Tt(S,v),409);let x=Object.fromEntries(Object.entries(St(T)).filter(([Y,M])=>M!=="null"&&M!==void 0));ye(x,r.fields),we(r.fields,x);let U=n.req.raw;if(r.hooks?.beforeValidate)for(let Y of r.hooks.beforeValidate){let M=await Y({collection:o,data:x,originalDoc:v,req:U,user:i,tenantId:p,operation:"update"});M&&typeof M=="object"&&!Array.isArray(M)&&Object.assign(x,M);}if(x=e.getUpdateZodSchema(o).parse(x),r.hooks?.beforeChange)for(let Y of r.hooks.beforeChange){let M=await Y({collection:o,data:x,originalDoc:v,req:U,user:i,tenantId:p,operation:"update"});M&&typeof M=="object"&&!Array.isArray(M)&&Object.assign(x,M);}let $=n.req.header("X-Draft")==="true",D=r.versions?.drafts===!0,_=n.req.query("autosave")==="true",F;if(D&&$?await t.createVersion({collection:o,documentId:w,data:x,status:"draft",autosave:_,createdBy:i?.id,changeDescription:_?"Autosave":"Draft saved",tenantId:p}):D?(await t.update({collection:o,id:w,data:{...x,status:"published"},tenantId:p}),await t.createVersion({collection:o,documentId:w,data:x,status:"published",createdBy:i?.id,changeDescription:"Published",tenantId:p})):await t.update({collection:o,id:w,data:x,tenantId:p}),F=await t.findByID({collection:o,id:w,tenantId:p,draft:!0}),r.hooks?.afterChange)for(let Y of r.hooks.afterChange)await Y({collection:o,doc:F,data:x,originalDoc:v,req:U,user:i,tenantId:p,operation:"update"});return y&&!_&&y.trigger(ke(o,"update"),{collection:o,operation:"update",data:F,previousData:v,user:i?{id:i.id,email:i.email,role:i.role}:void 0,tenantId:p}).catch(Y=>console.error("[Webhook] Failed to trigger:",Y)),Ge(L,A,`${m}/${w}`,"PATCH",n.req.raw),i&&L?.createAuditLog({action:"document_update",userId:i.id,resource:o,resourceId:w,success:!0}),n.json({data:F,message:D?"Draft saved":"Updated successfully"})}catch(i){return i.name==="ZodError"?(console.error(`[PATCH ${m}/:id] Validation failed:`,i.errors),n.json({error:`Validation failed: ${Xe(i.errors)}`,details:i.errors},400)):(console.error(`[PATCH ${m}/:id] ERROR:`,i.message,"CAUSE:",i.cause?.message||i.cause,"QUERY:",i.query),n.json({error:i.message},500))}}),h.delete(`${m}/:id`,async n=>{try{let{user:i,tenantId:p,apiKeyContext:A}=await P(n.req.raw,E,l,u),g=await N(r,"delete",n.req.raw,i,p,A,R,q);if(!g.allowed)return n.json({error:g.error},g.status||403);p&&t.setTenantContext({tenantId:p,userId:i?.id??"",role:i?.role,isSuperAdmin:i?.role==="super_admin"});let w=n.req.param("id"),T=n.req.raw,S=await t.findByID({collection:o,id:w,tenantId:p,draft:!0});if(!S)return n.json({error:"Document not found"},404);if(r.hooks?.beforeDelete)for(let x of r.hooks.beforeDelete)await x({collection:o,doc:S,req:T,user:i,tenantId:p,operation:"delete"});let v=await t.delete({collection:o,id:w,tenantId:p});if(r.hooks?.afterDelete)for(let x of r.hooks.afterDelete)await x({collection:o,doc:v,originalDoc:S,req:T,user:i,tenantId:p,operation:"delete"});return y&&y.trigger(ke(o,"delete"),{collection:o,operation:"delete",data:v,previousData:S,user:i?{id:i.id,email:i.email,role:i.role}:void 0,tenantId:p}).catch(x=>console.error("[Webhook] Failed to trigger:",x)),Ge(L,A,`${m}/${w}`,"DELETE",n.req.raw),i&&L?.createAuditLog({action:"document_delete",userId:i.id,resource:o,resourceId:w,success:!0}),n.json({data:v,message:"Deleted successfully"})}catch(i){return console.error(`[DELETE] Error deleting ${o}:`,i),n.json({error:i.message||String(i)},500)}}),h.post(`${m}/:id/duplicate`,async n=>{try{let{user:i,tenantId:p,apiKeyContext:A}=await P(n.req.raw,E,l,u),g=await N(r,"create",n.req.raw,i,p,A,R,q);if(!g.allowed)return n.json({error:g.error},g.status||403);let w=n.req.param("id"),T=await t.findByID({collection:o,id:w,tenantId:p,draft:!0});if(!T)return n.json({error:"Document not found"},404);let{id:S,createdAt:v,updatedAt:x,...U}=T;De(r.fields,U);let j=Date.now().toString(36);"slug"in U&&typeof U.slug=="string"&&(U.slug=`${U.slug||"document"}-copy-${j}`),"title"in U&&typeof U.title=="string"?U.title=`${U.title||"Copy"} (Copy)`:"name"in U&&typeof U.name=="string"&&(U.name=`${U.name||"Copy"} (Copy)`);let $=await t.create({collection:o,data:{...U,status:"draft"},tenantId:p});return n.json({data:$,message:"Document duplicated successfully"})}catch(i){return console.error("[Duplicate] Error:",i),n.json({error:i.message||String(i)},500)}}),h.post(`${m}/:id/versions/:versionId/restore`,async n=>{try{let{user:i,tenantId:p,apiKeyContext:A}=await P(n.req.raw,E,l,u),g=await N(r,"update",n.req.raw,i,p,A,R,q);if(!g.allowed)return n.json({error:g.error},g.status||403);let w=n.req.param("id"),T=n.req.param("versionId"),S=await t.findVersionByID({collection:o,versionId:T,tenantId:p});if(!S)return n.json({error:"Version not found"},404);let v=await t.update({collection:o,id:w,data:{...S.data,status:"draft"},tenantId:p});return n.json({data:v,message:"Version restored successfully"})}catch(i){return n.json({error:i.message},500)}}),h.post(`${m}/:id/versions`,async n=>{try{let{user:i,tenantId:p,apiKeyContext:A}=await P(n.req.raw,E,l,u),g=await N(r,"update",n.req.raw,i,p,A,R,q);if(!g.allowed)return n.json({error:g.error},g.status||403);let w=await n.req.json(),{versionId:T,action:S}=w;if(S==="restore"&&T){let v=await t.findVersionByID({collection:o,versionId:T,tenantId:p});if(!v)return n.json({error:"Version not found"},404);let x=await t.update({collection:o,id:n.req.param("id"),data:{...v.data,status:"draft"},tenantId:p});return n.json({data:x,message:"Version restored successfully"})}return n.json({error:"Invalid action"},400)}catch(i){return n.json({error:i.message},500)}}),h.post(`${m}/:id/publish`,async n=>{try{let{user:i,tenantId:p,apiKeyContext:A}=await P(n.req.raw,E,l,u),g=await N(r,"update",n.req.raw,i,p,A,R,q);if(!g.allowed)return n.json({error:g.error},g.status||403);p&&t.setTenantContext({tenantId:p,userId:i?.id??"",role:i?.role,isSuperAdmin:i?.role==="super_admin"});let w=n.req.param("id"),T=await n.req.json().catch(()=>({})),S=Ye(T),v=await t.findByID({collection:o,id:w,tenantId:p,draft:!0});if(!v)return n.json({error:"Document not found"},404);if(S&&v.updatedAt&&S!==v.updatedAt)return n.json(Tt(S,v),409);let x={status:"published"},U=v;if(r.versions?.drafts){let $=await t.findVersions({collection:o,documentId:w,limit:1,sort:"-createdAt",tenantId:p});if($.docs.length>0){let D=$.docs[0];U={...v,...D.data},x={...D.data,...x};}}let j=await t.update({collection:o,id:w,data:x,tenantId:p});return r.versions?.drafts&&await t.createVersion({collection:o,documentId:w,data:{...U,status:"published"},status:"published",createdBy:i?.id,changeDescription:"Published",tenantId:p}),y&&y.trigger(ke(o,"update"),{collection:o,operation:"update",data:j,user:i?{id:i.id,email:i.email,role:i.role}:void 0,tenantId:p}).catch($=>console.error("[Webhook] Failed to trigger:",$)),n.json({data:j,message:"Published successfully"})}catch(i){return n.json({error:i.message},500)}}),h.post(`${m}/:id/unpublish`,async n=>{try{let{user:i,tenantId:p,apiKeyContext:A}=await P(n.req.raw,E,l,u),g=await N(r,"update",n.req.raw,i,p,A,R,q);if(!g.allowed)return n.json({error:g.error},g.status||403);let w=n.req.param("id");if(!await t.findByID({collection:o,id:w,tenantId:p,draft:!0}))return n.json({error:"Document not found"},404);let S=await t.update({collection:o,id:w,data:{status:"draft"},tenantId:p});return y&&y.trigger(ke(o,"update"),{collection:o,operation:"update",data:S,user:i?{id:i.id,email:i.email,role:i.role}:void 0,tenantId:p}).catch(v=>console.error("[Webhook] Failed to trigger:",v)),n.json({data:S,message:"Unpublished successfully"})}catch(i){return n.json({error:i.message},500)}});}for(let r of e.getGlobals()){let o=r.slug,m=`/api/globals/${o}`;h.post(`${m}/dynamic-options/:fieldName`,async n=>{try{let{user:i,tenantId:p}=await P(n.req.raw,E,l,u),A=await J(r,"read",n.req.raw,i,p,R);if(!A.allowed)return n.json({error:A.error},A.status||403);let g=n.req.param("fieldName"),w=await n.req.json(),{data:T,siblingData:S}=w,v=ge(r.fields,g);if(!v)return n.json({error:"Field not found"},404);if(v.type!=="select")return n.json({error:"Field is not a select field"},400);let x=[];return typeof v.options=="function"?x=await v.options({data:T||{},siblingData:S||{}}):Array.isArray(v.options)&&(x=v.options),n.json({options:x})}catch(i){return n.json({error:i.message},500)}}),h.get(m,async n=>{try{let{user:i,tenantId:p}=await P(n.req.raw,E,l,u),A=new URL(n.req.url),g=A.searchParams.get("kyroToken"),w=A.searchParams.get("draft"),T=!1;if(w==="true"&&g&&s)try{let j=await jwt.verify(g,s,"HS256");j&&j.type==="preview"&&j.collection===`_globals_${r.slug}`&&(T=!0);}catch(j){console.warn("Invalid preview token",j);}if(!T){let j=await J(r,"read",n.req.raw,i,p,R);if(!j.allowed)return n.json({error:j.error},j.status||403)}let S=w==="true"?!0:w==="false"?!1:!!i,v=parseInt(A.searchParams.get("depth")||"0"),U=(await t.find({collection:`_globals_${o}`,where:{},tenantId:p,draft:S,depth:v,limit:1})).docs[0];if(U&&v>0&&await chunkILEZ3NYX_cjs.a([U],r.fields,t,e,1,v),o==="system"){let j=yr__default.default.randomBytes(32).toString("hex");U?U.appSecret||(await t.update({collection:`_globals_${o}`,id:o,data:{appSecret:j},tenantId:p}),U.appSecret=j):U=await t.create({collection:`_globals_${o}`,data:{id:o,appSecret:j},tenantId:p});}return n.json({data:U||{}})}catch(i){return n.json({error:i.message},500)}});let b=async n=>{try{let{user:i,tenantId:p}=await P(n.req.raw,E,l,u),A=await J(r,"update",n.req.raw,i,p,R);if(!A.allowed)return n.json({error:A.error},A.status||403);let g=new URL(n.req.url),w=parseInt(g.searchParams.get("depth")||"0"),T=await n.req.json(),S=Ye(T),v=St(T),x=Object.fromEntries(Object.entries(v).filter(([H,Ae])=>Ae!==null&&Ae!=="null"&&Ae!==void 0));ye(x,r.fields),we(r.fields,x);let U=e.getUpdateZodSchema(o),j;try{j=U.parse(x);}catch(H){return n.json({error:`Validation failed: ${Xe(H.errors)}`,details:H.errors},400)}let $=new Set(["id","createdAt","updatedAt","status","baseUpdatedAt","_baseUpdatedAt"]),D=Object.fromEntries(Object.entries(j).filter(([H])=>!$.has(H))),_=`_globals_${o}`,F=await t.findOne({collection:_,where:{},tenantId:p,draft:!0});if(F&&S&&F.updatedAt&&S!==F.updatedAt)return n.json(Tt(S,F),409);let Y=n.req.header("X-Draft")==="true",M=r.versions?.drafts===!0,oe=n.req.query("autosave")==="true",W;if(M&&Y)await t.createVersion({collection:_,documentId:o,data:D,status:"draft",autosave:oe,createdBy:i?.id,changeDescription:oe?"Autosave":"Manual save",tenantId:p}),F?W=F:W=await t.create({collection:_,data:{...D,id:o,status:"draft"},tenantId:p});else if(M&&!Y){let H="published";F?W=await t.update({collection:_,id:o,data:{...D,status:H},tenantId:p}):W=await t.create({collection:_,data:{...D,id:o,status:H},tenantId:p}),await t.createVersion({collection:_,documentId:o,data:D,status:H,autosave:!1,createdBy:i?.id,changeDescription:"Published",tenantId:p});}else F?W=await t.update({collection:_,id:o,data:D,tenantId:p}):W=await t.create({collection:_,data:{...D,id:o},tenantId:p});if(o==="storage-settings"&&(G=null,ae=null),o==="email-settings"){let H=await chunk5K4YG5DA_cjs.k.fromConfig(t);O.email=H||void 0;}return o==="system"&&await Ft(),i&&L?.createAuditLog({action:"settings_change",userId:i.id,resource:`global:${o}`,resourceId:o,success:!0}),W&&w>0&&await chunkILEZ3NYX_cjs.a([W],r.fields,t,e,1,w),n.json({data:W,message:"Updated successfully"})}catch(i){return console.error(`[API] Save global "${o}" failed:`,i),n.json({error:i.message||"Save failed",stack:process.env.NODE_ENV==="development"?i.stack:void 0},500)}};h.post(m,b),h.patch(m,b),h.post(`${m}/preview-url`,async n=>{try{let{user:i,tenantId:p}=await P(n.req.raw,E,l,u),A=await J(r,"read",n.req.raw,i,p);if(!A.allowed)return n.json({error:A.error||"Forbidden"},A.status||403);let g=await n.req.json().catch(()=>({})),w="";s&&(w=await jwt.sign({type:"preview",collection:`_globals_${r.slug}`,exp:Math.floor(Date.now()/1e3)+3600},s,"HS256"));let T="";if(r.admin?.preview)T=await r.admin.preview(g,{req:n.req.raw,token:w});else {let S="";try{let v=await t.findOne({collection:"_globals_site-settings",where:{}});v?.siteUrl&&(S=v.siteUrl);}catch{}if(!S)return n.json({error:"No site URL configured in settings, and no custom preview function defined."},400);S=S.replace(/\/$/,""),T=`${S}/?preview=true&kyroToken=${w}`;}return n.json({url:T})}catch(i){return n.json({error:i.message},500)}}),h.post(`${m}/publish`,async n=>{try{let{user:i,tenantId:p}=await P(n.req.raw,E,l,u),A=await J(r,"update",n.req.raw,i,p,R);if(!A.allowed)return n.json({error:A.error},403);let g=`_globals_${o}`,w=await t.findOne({collection:g,where:{},tenantId:p,draft:!0});if(!w)return n.json({error:"Global not found"},404);let T={status:"published"},S=w;if(r.versions?.drafts){let x=await t.findVersions({collection:g,documentId:o,limit:1,sort:"-createdAt",tenantId:p});x.docs.length>0&&(S={...w,...x.docs[0].data},T={...x.docs[0].data,...T});}let v=await t.update({collection:g,id:o,data:T,tenantId:p});return r.versions?.drafts&&await t.createVersion({collection:g,documentId:o,data:{...S,status:"published"},status:"published",createdBy:i?.id,changeDescription:"Published",tenantId:p}),n.json({data:v,message:"Published successfully"})}catch(i){return n.json({error:i.message},500)}}),h.post(`${m}/unpublish`,async n=>{try{let{user:i,tenantId:p}=await P(n.req.raw,E,l,u),A=await J(r,"update",n.req.raw,i,p,R);if(!A.allowed)return n.json({error:A.error},403);let g=await t.update({collection:`_globals_${o}`,id:o,data:{status:"draft"},tenantId:p});return n.json({data:g,message:"Unpublished successfully"})}catch(i){return n.json({error:i.message},500)}}),h.get(`${m}/versions`,async n=>{try{let{user:i,tenantId:p}=await P(n.req.raw,E,l,u),A=await J(r,"read",n.req.raw,i,p,R);if(!A.allowed)return n.json({error:A.error},403);let g=parseInt(n.req.query("limit")||"10"),w=parseInt(n.req.query("page")||"1"),T=await t.findVersions({collection:`_globals_${o}`,documentId:o,limit:g,page:w,tenantId:p});return n.json(T)}catch(i){return n.json({error:i.message},500)}}),h.get(`${m}/versions/:versionId`,async n=>{try{let i=n.req.param("versionId"),{user:p,tenantId:A}=await P(n.req.raw,E,l,u),g=await J(r,"read",n.req.raw,p,A,R);if(!g.allowed)return n.json({error:g.error},403);let w=await t.findVersionByID({collection:`_globals_${o}`,versionId:i,tenantId:A});return w?n.json({data:w}):n.json({error:"Version not found"},404)}catch(i){return n.json({error:i.message},500)}}),h.post(`${m}/versions/:versionId/restore`,async n=>{try{let i=n.req.param("versionId"),{user:p,tenantId:A}=await P(n.req.raw,E,l,u),g=await J(r,"update",n.req.raw,p,A,R);if(!g.allowed)return n.json({error:g.error},403);let w=`_globals_${o}`,T=await t.findVersionByID({collection:w,versionId:i,tenantId:A});if(!T)return n.json({error:"Version not found"},404);let S=await t.update({collection:w,id:o,data:{...T.data,status:"draft"},tenantId:A});return n.json({data:S,message:"Version restored successfully"})}catch(i){return n.json({error:i.message},500)}}),o==="email-settings"&&h.post(`${m}/test`,async n=>{try{let{user:i,tenantId:p}=await P(n.req.raw,E,l,u),A=await J(r,"update",n.req.raw,i,p,R);if(!A.allowed)return n.json({error:A.error},A.status||403);let g=await n.req.json(),w={provider:g.provider,from:g.fromEmail||g.from,fromName:g.fromName,replyTo:g.replyTo,smtp:g.smtp?{host:g.smtp.host,port:g.smtp.port,secure:g.smtp.secure,auth:{user:g.smtp.username||g.smtp.user,pass:g.smtp.password||g.smtp.pass}}:void 0,resend:g.resend,sendgrid:g.sendgrid,mailgun:g.mailgun,ses:g.ses},T=new chunk5K4YG5DA_cjs.k(w),S=g.email||g.testEmail||g.testEmailSection&&g.testEmailSection.testEmail;if(!S)return n.json({error:"No test recipient email provided"},400);let v=g.provider?g.provider.charAt(0).toUpperCase()+g.provider.slice(1):"SMTP",x=g.fromName?`${g.fromName} <${g.fromEmail||g.from||"default"}>`:g.fromEmail||g.from||"Configured Sender",U=new Date().toUTCString();return await T.send({to:S,subject:"Kyro CMS \u2014 Email Connection Test",html:`<!DOCTYPE html>
107
107
  <html lang="en">
108
108
  <head>
@@ -102,7 +102,7 @@ import {l,j,k}from'./chunk-6J27P5D6.js';import {a as a$2}from'./chunk-IETGL7WJ.j
102
102
  `),await this.db.execute(e`CREATE INDEX IF NOT EXISTS "idx_media_folders_path" ON "media_folders" ("path")`),It=true;}}now(){return new Date().toISOString()}buildFindConditions(e){let t=[],s=[],a=e.sortBy==="name"?"title":e.sortBy==="createdAt"?"created_at":e.sortBy==="updatedAt"?"updated_at":e.sortBy||"created_at",d=e.sortDir==="asc"?"ASC":"DESC";if(e.search){t.push("(title LIKE ? OR filename LIKE ? OR original_name LIKE ? OR alt LIKE ?)");let u=`%${e.search}%`;s.push(u,u,u,u);}return e.type&&e.type!=="all"&&(t.push("mime_type LIKE ?"),s.push(`${e.type}/%`)),e.folder&&(t.push("(folder = ? OR folder LIKE ?)"),s.push(e.folder,`${e.folder}/%`)),{where:t.length>0?`WHERE ${t.join(" AND ")}`:"",params:s,orderBy:d,sortCol:a}}rowToMedia(e,t){return {id:e.id,filename:e.filename,title:e.title??null,originalName:e.original_name??e.originalName,mimeType:e.mime_type??e.mimeType,fileSize:e.file_size??e.fileSize,width:e.width??null,height:e.height??null,url:c.resolveMediaUrl(e.url,t),thumbnailUrl:c.resolveMediaUrl(e.thumbnail_url??e.thumbnailUrl??null,t),folder:e.folder??null,provider:e.provider,alt:e.alt??null,caption:e.caption??null,metadata:typeof e.metadata=="string"?JSON.parse(e.metadata):e.metadata??null,createdAt:e.created_at??e.createdAt,updatedAt:e.updated_at??e.updatedAt}}static resolveMediaUrl(e,t){return e?e.startsWith("http://")||e.startsWith("https://")||e.startsWith("blob:")||e.startsWith("data:")?e:`${(process.env.KYRO_BASE_URL||t||"http://localhost:4321").replace(/\/+$/,"")}${e.startsWith("/")?"":"/"}${e}`:null}async sqliteRun(e,t=[]){let s=this.db.prepare(e),a=e.trim().toLowerCase();return a.startsWith("insert")||a.startsWith("update")||a.startsWith("delete")?s.run(...t):s.all(...t)}sqliteGet(e,t=[]){return this.db.prepare(e).get(...t)}async upload(e,t="",s){let a=e.type.startsWith("image/"),d,l=e,u=e.name,f=null,y=null;if(a&&!e.type.includes("svg")){let R=Buffer.from(await e.arrayBuffer());d=await or(R),u=`${e.name.replace(/\.[^/.]+$/,"").toLowerCase().replace(/[^a-z0-9]/g,"-").replace(/-+/g,"-").substring(0,50)}.webp`,f=d.width??null,y=d.height??null,l=new File([d.buffer],u,{type:"image/webp"});}let I=await this.storage.upload(l,{folder:t,filename:u}),h=await this.storage.generateThumbnail({...I,id:"",provider:this.storage.name,createdAt:this.now()},{width:400,height:400}),k=this.genId(),C=this.now();if(this.dialect==="mongodb"){let R=I.mimeType,q=R.startsWith("image/")?"image":R.startsWith("video/")?"video":R.startsWith("audio/")?"audio":R.startsWith("application/pdf")?"document":["application/zip","application/x-zip","application/x-tar","application/gzip","application/x-7z"].includes(R)?"archive":"other";return await this.db.db.collection(this.mediaTable).insertOne({_id:k,id:k,filename:I.filename,title:e.name.replace(/\.[^/.]+$/,""),originalName:e.name,mimeType:R,fileSize:I.size,width:f,height:y,url:I.url,thumbnailUrl:h,folder:t||"",provider:this.storage.name,type:q,status:"active",alt:null,caption:null,createdAt:new Date,updatedAt:new Date}),this.rowToMedia({id:k,filename:I.filename,title:e.name.replace(/\.[^/.]+$/,""),originalName:e.name,mimeType:R,fileSize:I.size,width:f,height:y,url:I.url,thumbnailUrl:h,folder:t||"",provider:this.storage.name,type:q,status:"active",alt:null,caption:null,createdAt:new Date,updatedAt:new Date},s)}if(this.dialect==="sqlite")await this.sqliteRun(`INSERT INTO ${this.mediaTable}
103
103
  (id, filename, title, original_name, mime_type, file_size, width, height, url, thumbnail_url, folder, provider, alt, caption, metadata, created_at, updated_at)
104
104
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[k,I.filename,e.name.replace(/\.[^/.]+$/,""),e.name,I.mimeType,I.size,f,y,I.url,h,t||null,this.storage.name,null,null,null,C,C]);else {let{media:R}=await import('./media-L5XDD47D.js'),q=I.mimeType,z=q.startsWith("image/")?"image":q.startsWith("video/")?"video":q.startsWith("audio/")?"audio":q.startsWith("application/pdf")?"document":["application/zip","application/x-zip","application/x-tar","application/gzip","application/x-7z"].includes(q)?"archive":"other",V=await this.db.insert(R).values({id:k,filename:I.filename,title:e.name.replace(/\.[^/.]+$/,""),originalName:e.name,mimeType:q,fileSize:I.size,width:f,height:y,url:I.url,thumbnailUrl:h,folder:t||"",provider:this.storage.name,type:z,status:"active",alt:null,caption:null,createdAt:new Date,updatedAt:new Date}).returning();V&&V[0]&&(k=V[0].id);}return {id:k,filename:I.filename,title:e.name.replace(/\.[^/.]+$/,""),originalName:e.name,mimeType:I.mimeType,fileSize:I.size,width:f,height:y,url:I.url,thumbnailUrl:h,folder:t||null,provider:this.storage.name,alt:null,caption:null,metadata:null,createdAt:C,updatedAt:C}}async uploadFromUrl(e,t="",s){let a=await fetch(e);if(!a.ok)throw new Error(`Failed to fetch URL: ${a.status}`);let d=await a.blob(),l=e.split("/").pop()||"url-image",u=a.headers.get("content-type")||d.type||"application/octet-stream",f=new File([d],l,{type:u});return this.upload(f,t,s)}async delete(e,t){this.dialect==="postgres"&&(e=Pe(e));let s=await this.findById(e,t);if(s){if(await this.deleteFile(s.url),s.thumbnailUrl&&s.thumbnailUrl!==s.url&&s.thumbnailUrl!==s.url+"?thumb")try{await this.deleteFile(s.thumbnailUrl);}catch{}if(this.dialect==="mongodb"){await this.db.db.collection(this.mediaTable).deleteOne({id:e});return}if(this.dialect==="sqlite")await this.sqliteRun(`DELETE FROM ${this.mediaTable} WHERE id = ?`,[e]);else {let{media:a}=await import('./media-L5XDD47D.js'),{eq:d}=await import('drizzle-orm');await this.db.delete(a).where(d(a.id,e));}}}async deleteFile(e){await this.storage.delete(e);}async rename(e,t,s){this.dialect==="postgres"&&(e=Pe(e));let a=await this.findById(e,s);if(!a)return null;let d=await this.storage.rename(a.url,t),l;if(a.thumbnailUrl||this.storage.name==="cloudinary"){let I=d.match(/\/upload\/(v\d+)\//),h=I?I[1]+"/":"",k=d.match(/(.+?)\/upload\//);l=`${k?k[1]:"https://res.cloudinary.com/"+this.storage.config?.cloudName||"unknown"}/upload/w_200,h_200,c_fill/${h}${t}`;}let u=a.filename.split(".").pop(),f=t.includes(".")?t:`${t}.${u}`,y={url:d,filename:f,thumbnailUrl:l};if(this.dialect==="mongodb")return await this.db.db.collection(this.mediaTable).updateOne({id:e},{$set:{url:d,thumbnailUrl:l||null,updatedAt:new Date}}),this.findById(e,s);if(this.dialect==="sqlite"){let I={...y};"thumbnailUrl"in I&&(I.thumbnail_url=I.thumbnailUrl,delete I.thumbnailUrl);let h=Object.keys(I).map(C=>`${C} = ?`).join(", "),k=Object.values(I);await this.sqliteRun(`UPDATE ${this.mediaTable} SET ${h}, updated_at = ? WHERE id = ?`,[...k,this.now(),e]);}else {let{media:I}=await import('./media-L5XDD47D.js'),{eq:h}=await import('drizzle-orm');await this.db.update(I).set({...y,updatedAt:this.now()}).where(h(I.id,e));}return {...a,...y,updatedAt:this.now(),thumbnailUrl:y.thumbnailUrl??null}}async findById(e,t){if(this.dialect==="postgres"&&(e=Pe(e)),this.dialect==="mongodb"){let l=await this.db.db.collection(this.mediaTable).findOne({id:e});return l?this.rowToMedia(l,t):null}if(this.dialect==="sqlite"){let l=this.sqliteGet(`SELECT * FROM ${this.mediaTable} WHERE id = ?`,[e]);return l?this.rowToMedia(l,t):null}let{media:s}=await import('./media-L5XDD47D.js'),{eq:a}=await import('drizzle-orm'),[d]=await this.db.select().from(s).where(a(s.id,e));return d?this.rowToMedia(d,t):null}async find(e={},t){let{page:s=1,limit:a=30,search:d="",type:l="",folder:u="",sortBy:f="createdAt",sortDir:y="desc"}=e,{where:I,params:h,orderBy:k,sortCol:C}=this.buildFindConditions({page:s,limit:a,search:d,type:l,folder:u,sortBy:f,sortDir:y}),R=(s-1)*a;if(this.dialect==="mongodb"){let X={},{search:G,type:ae,folder:K,sortBy:Re="createdAt",sortDir:Ee="desc"}=e;G&&(X.$or=[{title:{$regex:G,$options:"i"}},{filename:{$regex:G,$options:"i"}},{originalName:{$regex:G,$options:"i"}},{alt:{$regex:G,$options:"i"}}]),ae&&ae!=="all"&&(X.mimeType={$regex:`^${ae}/`}),K&&(X.$or=[{folder:K},{folder:{$regex:`^${K}/`}}]);let Rt={[Re==="name"?"title":Re]:Ee==="asc"?1:-1},r=await this.db.db.collection(this.mediaTable).countDocuments(X);return {docs:(await this.db.db.collection(this.mediaTable).find(X).sort(Rt).skip(R).limit(a).toArray()).map(m=>this.rowToMedia(m,t)),totalDocs:r,page:s,limit:a,totalPages:Math.ceil(r/a)}}if(this.dialect==="sqlite"){let G=this.sqliteGet(`SELECT COUNT(*) as cnt FROM ${this.mediaTable} ${I}`,h)?.cnt??0;return {docs:(await this.sqliteRun(`SELECT * FROM ${this.mediaTable} ${I} ORDER BY ${C} ${k} LIMIT ? OFFSET ?`,[...h,a,R])).map(K=>this.rowToMedia(K,t)),totalDocs:G,page:s,limit:a,totalPages:Math.ceil(G/a)}}let{media:q}=await import('./media-L5XDD47D.js'),{like:z,or:V,and:ne,asc:L,desc:pe,eq:Z,sql:E}=await import('drizzle-orm'),Q=[];d&&Q.push(V(z(q.title,`%${d}%`),z(q.filename,`%${d}%`),z(q.originalName,`%${d}%`),z(q.alt,`%${d}%`))),l&&l!=="all"&&Q.push(z(q.mimeType,`${l}/%`)),u&&Q.push(V(Z(q.folder,u),z(q.folder,`${u}/%`)));let qe=Q.length>0?ne(...Q):void 0,me=q[{created_at:"createdAt",updated_at:"updatedAt",title:"title",filename:"filename",file_size:"fileSize",mime_type:"mimeType",original_name:"originalName"}[C]||"createdAt"],xt=y==="asc"?L(me):pe(me),ve=await this.db.select().from(q).where(qe).orderBy(xt).limit(a).offset(R),[{count:be}]=await this.db.select({count:E`count(*)`}).from(q).where(qe),O=Number(be);return {docs:ve.map(X=>this.rowToMedia(X,t)),totalDocs:O,page:s,limit:a,totalPages:Math.ceil(O/a)}}async update(e,t,s){this.dialect==="postgres"&&(e=Pe(e));let a=this.now();if(this.dialect==="mongodb")return await this.db.db.collection(this.mediaTable).updateOne({id:e},{$set:{...t,updatedAt:new Date}}),this.findById(e,s);if(this.dialect==="sqlite"){let f=["updated_at = ?"],y=[a];t.title!==void 0&&(f.push("title = ?"),y.push(t.title)),t.alt!==void 0&&(f.push("alt = ?"),y.push(t.alt)),t.caption!==void 0&&(f.push("caption = ?"),y.push(t.caption)),t.folder!==void 0&&(f.push("folder = ?"),y.push(t.folder)),t.metadata!==void 0&&(f.push("metadata = ?"),y.push(t.metadata===null?null:JSON.stringify(t.metadata))),t.originalName!==void 0&&(f.push("original_name = ?"),y.push(t.originalName)),y.push(e),await this.sqliteRun(`UPDATE ${this.mediaTable} SET ${f.join(", ")} WHERE id = ?`,y);let I=this.sqliteGet(`SELECT * FROM ${this.mediaTable} WHERE id = ?`,[e]);return I?this.rowToMedia(I,s):null}let{media:d}=await import('./media-L5XDD47D.js'),{eq:l}=await import('drizzle-orm'),[u]=await this.db.update(d).set({...t,updatedAt:new Date}).where(l(d.id,e)).returning();return u?this.rowToMedia(u,s):null}async updateMany(e,t){this.dialect==="postgres"&&(e=e.map(Pe));let s=this.now();if(this.dialect==="mongodb"){for(let a of e)await this.db.db.collection(this.mediaTable).updateOne({id:a},{$set:{...t,updatedAt:new Date}});return}if(this.dialect==="sqlite")for(let a of e){let d=["updated_at = ?"],l=[s];t.folder!==void 0&&(d.push("folder = ?"),l.push(t.folder||null)),l.push(a),await this.sqliteRun(`UPDATE ${this.mediaTable} SET ${d.join(", ")} WHERE id = ?`,l);}else {let{media:a}=await import('./media-L5XDD47D.js'),{eq:d}=await import('drizzle-orm');for(let l of e)await this.db.update(a).set({...t,updatedAt:new Date}).where(d(a.id,l));}}async listFolders(){if(this.dialect==="mongodb"){let f=await this.db.db.collection(this.foldersTable).find({},{projection:{path:1}}).toArray(),y=await this.db.db.collection(this.mediaTable).distinct("folder"),I=new Set([...f.map(h=>h.path),...y]);return Array.from(I).filter(h=>h&&h!=="").sort()}if(this.dialect==="sqlite")return (await this.sqliteRun(`SELECT path FROM ${this.foldersTable} UNION
105
- SELECT folder as path FROM ${this.mediaTable} WHERE folder IS NOT NULL AND folder != ''`)).map(y=>y.path).filter(y=>y&&y!=="").sort();let{media:e,mediaFolders:t}=await import('./media-L5XDD47D.js'),{eq:s,sql:a}=await import('drizzle-orm'),d=await this.db.select({folder:e.folder}).from(e).groupBy(e.folder),l=await this.db.select({path:t.path}).from(t),u=new Set([...d.map(f=>f.folder),...l.map(f=>f.path)]);return Array.from(u).filter(f=>f&&f!=="").sort()}async createFolder(e,t=""){let s=t?`${t}/${e}`:e;await this.storage.createFolder?.(s);let a=this.now();if(this.dialect==="mongodb"){await this.db.db.collection(this.foldersTable).findOne({path:s})||await this.db.db.collection(this.foldersTable).insertOne({_id:this.genId(),name:e,path:s,parentPath:t||null,createdAt:new Date});return}if(this.dialect==="sqlite")await this.sqliteRun(`INSERT OR IGNORE INTO ${this.foldersTable} (path, name, parent_path, created_at) VALUES (?, ?, ?, ?)`,[s,e,t||null,a]);else {let{mediaFolders:d}=await import('./media-L5XDD47D.js');await this.db.insert(d).values({path:s,name:e,parentPath:t||null,createdAt:new Date}).onConflictDoNothing();}}async deleteFolder(e){let t=await this.find({folder:e,limit:1e4});for(let s of t.docs)await this.delete(s.id);if(await this.storage.deleteFolder?.(e),this.dialect==="mongodb"){await this.db.db.collection(this.foldersTable).deleteMany({$or:[{path:e},{path:{$regex:`^${e}/`}}]});return}if(this.dialect==="sqlite")await this.sqliteRun(`DELETE FROM ${this.foldersTable} WHERE path = ? OR path LIKE ?`,[e,`${e}/%`]);else {let{mediaFolders:s}=await import('./media-L5XDD47D.js'),{like:a,or:d,eq:l}=await import('drizzle-orm');await this.db.delete(s).where(d(l(s.path,e),a(s.path,`${e}/%`)));}}};function Xe(c){return c.map(e=>`${e.path.join(".")}: ${e.message}`).join(", ")}function ye(c,e){if(!(!c||typeof c!="object"))for(let t of e){if(t.type==="tabs"&&Array.isArray(t.tabs)){let a=t.name?c[t.name]:c;if(a&&typeof a=="object")for(let d of t.tabs)Array.isArray(d.fields)&&ye(a,d.fields);continue}if(!t.name||!(t.name in c))continue;if(c[t.name]===""&&(t.type==="text"||t.type==="textarea"||t.type==="code"||t.type==="markdown"||(c[t.name]=null)),(t.type==="group"||t.type==="collapsible")&&t.name&&Array.isArray(t.fields)&&c[t.name]&&typeof c[t.name]=="object")ye(c[t.name],t.fields);else if(t.type==="array"&&t.name&&Array.isArray(t.fields)&&Array.isArray(c[t.name]))for(let a of c[t.name])a&&typeof a=="object"&&ye(a,t.fields);else if(t.type==="blocks"&&t.name&&Array.isArray(t.blocks)&&Array.isArray(c[t.name]))for(let a of c[t.name]){if(!a||typeof a!="object")continue;let d=a.type||a.blockType;if(!d)continue;let l=t.blocks.find(f=>f.slug===d);if(!l||!Array.isArray(l.fields))continue;let u=a.data&&typeof a.data=="object"?a.data:a;ye(u,l.fields);}}}function we(c,e){if(!(!e||typeof e!="object"))for(let t of c){if(t.type==="tabs"&&Array.isArray(t.tabs)){let s=t.name?e[t.name]:e;if(s&&typeof s=="object")for(let a of t.tabs)Array.isArray(a.fields)&&we(a.fields,s);}if(t.type==="richtext"&&t.name){let s=e[t.name];typeof s=="string"?e[t.name]=[{type:"paragraph",children:[{text:s}]}]:s&&typeof s=="object"&&!Array.isArray(s)&&s.type==="doc"&&Array.isArray(s.content)&&(e[t.name]=s.content);}if((t.type==="group"||t.type==="collapsible")&&t.name&&Array.isArray(t.fields)&&e[t.name]&&typeof e[t.name]=="object")we(t.fields,e[t.name]);else if(t.type==="array"&&t.name&&Array.isArray(t.fields)&&Array.isArray(e[t.name]))for(let s of e[t.name])s&&typeof s=="object"&&we(t.fields,s);else if(t.type==="blocks"&&t.name&&Array.isArray(t.blocks)&&Array.isArray(e[t.name]))for(let s of e[t.name]){if(!s||typeof s!="object")continue;let a=s.type||s.blockType;if(!a)continue;let d=t.blocks.find(u=>u.slug===a);if(!d||!Array.isArray(d.fields))continue;let l=s.data&&typeof s.data=="object"?s.data:s;we(d.fields,l);}}}function De(c,e){if(!(!e||typeof e!="object")){for(let t of c)if(!(!t.name||!(t.name in e))){if(t.unique&&(t.type==="text"||t.type==="email"?e[t.name]=`${e[t.name]||t.name}-copy-${Date.now().toString(36)}`:delete e[t.name]),t.type==="tabs"&&t.name&&Array.isArray(t.tabs)&&e[t.name]&&typeof e[t.name]=="object")for(let s of t.tabs)Array.isArray(s.fields)&&De(s.fields,e[t.name]);else if((t.type==="group"||t.type==="collapsible")&&t.name&&Array.isArray(t.fields)&&e[t.name]&&typeof e[t.name]=="object")De(t.fields,e[t.name]);else if(t.type==="array"&&t.name&&Array.isArray(t.fields)&&Array.isArray(e[t.name]))for(let s of e[t.name])s&&typeof s=="object"&&(delete s.id,De(t.fields,s));else if(t.type==="blocks"&&t.name&&Array.isArray(t.blocks)&&Array.isArray(e[t.name]))for(let s of e[t.name]){if(!s||typeof s!="object")continue;delete s.id;let a=s.type||s.blockType;if(!a)continue;let d=t.blocks.find(u=>u.slug===a);if(!d||!Array.isArray(d.fields))continue;let l=s.data&&typeof s.data=="object"?s.data:s;De(d.fields,l);}}}}var Jr={_media:{create:d.MEDIA_UPLOAD,update:d.MEDIA_UPLOAD,delete:d.MEDIA_DELETE}};function ke(c,e){let t=Jr[c];return t?t[e]:`collection.${e}`}function Zr(c){let e=c.headers.get("x-forwarded-for");return e?e.split(",")[0].trim():c.headers.get("x-real-ip")||"unknown"}function Ge(c,e,t,s,a){e?.apiKeyId&&c&&c.createAuditLog({action:"api_request",userId:e.userId||"",resource:"api_key",resourceId:e.apiKeyId,success:true,metadata:{endpoint:t,method:s,ip:Zr(a)}});}function Ye(c){return c.baseUpdatedAt??c._baseUpdatedAt}function St(c){let{baseUpdatedAt:e,_baseUpdatedAt:t,...s}=c;return s}function Tt(c,e){return {error:"Document has changed since you started editing",code:"REVISION_CONFLICT",conflict:{expectedUpdatedAt:c??null,actualUpdatedAt:e.updatedAt??null,current:e}}}async function N(c,e,t,s,a,d,l=true,u="none"){return await b$1(c,e,{user:s,req:t,tenantId:a,apiKey:d},{enablePublicAccess:l,defaultAccess:u})}async function J(c,e,t,s,a,d=true){return await c$2(c,e,{user:s,req:t,tenantId:a},{enablePublicAccess:d})}async function P(c,e,t,s){if(t)return {user:t,tenantId:s,apiKeyContext:void 0,authType:"static"};if(e){let a=await e(c);if(a.status===200&&a.user)return {user:a.user,tenantId:a.tenantContext?.tenantId,apiKeyContext:a.apiKeyContext,authType:a.authType}}return {user:void 0,tenantId:void 0,apiKeyContext:void 0,authType:void 0}}function Qr(c,e){if("dialect"in c&&c.dialect==="postgres"&&c instanceof c$1)return new a$6({db:c.client});if("dialect"in c&&c.dialect==="sqlite"&&c instanceof c$1)return new Be({db:c.client});if("dialect"in c&&c.dialect==="mongodb"){let s=c;return new a$7({db:()=>s.db})}let t=resolve(e,"data","kyro.db");return new a$8({path:process.env.KYRO_AUTH_DB_PATH||t})}function pr(c){let{registry:e,db:t,authSecret:s,authAdapter:a,checkSession:d,user:l,tenantId:u,cors:f,webhookService:y,settings:I}=c,h=new Hono;function k$1(r){if(Array.isArray(r))return r.map(k$1);if(r!==null&&typeof r=="object"){let o={};for(let m in r)m!=="attrs"&&(o[m]=k$1(r[m]));return o}return r}h.use("*",async(r,o)=>{await o();let m=r.req.header("referer")||"";if(!(r.req.header("x-kyro-admin")==="true"||m.includes("/admin"))){let n=r.res.headers.get("Content-Type");if(n&&n.includes("application/json"))try{let p=await r.res.clone().json(),A=k$1(p);r.res=r.json(A,r.res.status);}catch{}}});for(let r of e.getPlugins())typeof r.serverMiddleware=="function"&&r.serverMiddleware(h);let C=I?.access?.apiAccess,R=I?.access?.enablePublicAccess??false,q=I?.access?.defaultCollectionAccess??"none";C?.requireAuth;let V=process.cwd(),ne=V.endsWith("admin")?resolve(V,".."):V,L=a||Qr(t,ne),E=Vt({db:t,userLookup:async r=>await L.findUserById(r)||null}),Q=C?.cors?.allowedOrigins,qe=f?.origins,Je=Array.isArray(Q)?Q:typeof Q=="string"&&Q?Q.split(`
105
+ SELECT folder as path FROM ${this.mediaTable} WHERE folder IS NOT NULL AND folder != ''`)).map(y=>y.path).filter(y=>y&&y!=="").sort();let{media:e,mediaFolders:t}=await import('./media-L5XDD47D.js'),{eq:s,sql:a}=await import('drizzle-orm'),d=await this.db.select({folder:e.folder}).from(e).groupBy(e.folder),l=await this.db.select({path:t.path}).from(t),u=new Set([...d.map(f=>f.folder),...l.map(f=>f.path)]);return Array.from(u).filter(f=>f&&f!=="").sort()}async createFolder(e,t=""){let s=t?`${t}/${e}`:e;await this.storage.createFolder?.(s);let a=this.now();if(this.dialect==="mongodb"){await this.db.db.collection(this.foldersTable).findOne({path:s})||await this.db.db.collection(this.foldersTable).insertOne({_id:this.genId(),name:e,path:s,parentPath:t||null,createdAt:new Date});return}if(this.dialect==="sqlite")await this.sqliteRun(`INSERT OR IGNORE INTO ${this.foldersTable} (path, name, parent_path, created_at) VALUES (?, ?, ?, ?)`,[s,e,t||null,a]);else {let{mediaFolders:d}=await import('./media-L5XDD47D.js');await this.db.insert(d).values({path:s,name:e,parentPath:t||null,createdAt:new Date}).onConflictDoNothing();}}async deleteFolder(e){let t=await this.find({folder:e,limit:1e4});for(let s of t.docs)await this.delete(s.id);if(await this.storage.deleteFolder?.(e),this.dialect==="mongodb"){await this.db.db.collection(this.foldersTable).deleteMany({$or:[{path:e},{path:{$regex:`^${e}/`}}]});return}if(this.dialect==="sqlite")await this.sqliteRun(`DELETE FROM ${this.foldersTable} WHERE path = ? OR path LIKE ?`,[e,`${e}/%`]);else {let{mediaFolders:s}=await import('./media-L5XDD47D.js'),{like:a,or:d,eq:l}=await import('drizzle-orm');await this.db.delete(s).where(d(l(s.path,e),a(s.path,`${e}/%`)));}}};function Xe(c){return c.map(e=>`${e.path.join(".")}: ${e.message}`).join(", ")}function ye(c,e){if(!(!c||typeof c!="object"))for(let t of e){if(t.type==="tabs"&&Array.isArray(t.tabs)){let a=t.name?c[t.name]:c;if(a&&typeof a=="object")for(let d of t.tabs)Array.isArray(d.fields)&&ye(a,d.fields);continue}if(!t.name||!(t.name in c))continue;if(c[t.name]===""&&(t.type==="text"||t.type==="textarea"||t.type==="code"||t.type==="markdown"||(c[t.name]=null)),(t.type==="group"||t.type==="collapsible")&&t.name&&Array.isArray(t.fields)&&c[t.name]&&typeof c[t.name]=="object")ye(c[t.name],t.fields);else if(t.type==="array"&&t.name&&Array.isArray(t.fields)&&Array.isArray(c[t.name]))for(let a of c[t.name])a&&typeof a=="object"&&ye(a,t.fields);else if(t.type==="blocks"&&t.name&&Array.isArray(t.blocks)&&Array.isArray(c[t.name]))for(let a of c[t.name]){if(!a||typeof a!="object")continue;let d=a.type||a.blockType;if(!d)continue;let l=t.blocks.find(f=>f.slug===d);if(!l||!Array.isArray(l.fields))continue;let u=a.data&&typeof a.data=="object"?a.data:a;ye(u,l.fields);}}}function we(c,e){if(!(!e||typeof e!="object"))for(let t of c){if(t.type==="tabs"&&Array.isArray(t.tabs)){let s=t.name?e[t.name]:e;if(s&&typeof s=="object")for(let a of t.tabs)Array.isArray(a.fields)&&we(a.fields,s);}if(t.type==="richtext"&&t.name){let s=e[t.name];typeof s=="string"?e[t.name]=[{type:"paragraph",children:[{text:s}]}]:s&&typeof s=="object"&&!Array.isArray(s)&&s.type==="doc"&&Array.isArray(s.content)&&(e[t.name]=s.content);}if((t.type==="group"||t.type==="collapsible")&&t.name&&Array.isArray(t.fields)&&e[t.name]&&typeof e[t.name]=="object")we(t.fields,e[t.name]);else if(t.type==="array"&&t.name&&Array.isArray(t.fields)&&Array.isArray(e[t.name]))for(let s of e[t.name])s&&typeof s=="object"&&we(t.fields,s);else if(t.type==="blocks"&&t.name&&Array.isArray(t.blocks)&&Array.isArray(e[t.name]))for(let s of e[t.name]){if(!s||typeof s!="object")continue;let a=s.type||s.blockType;if(!a)continue;let d=t.blocks.find(u=>u.slug===a);if(!d||!Array.isArray(d.fields))continue;let l=s.data&&typeof s.data=="object"?s.data:s;we(d.fields,l);}}}function De(c,e){if(!(!e||typeof e!="object")){for(let t of c)if(!(!t.name||!(t.name in e))){if(t.unique&&(t.type==="text"||t.type==="email"?e[t.name]=`${e[t.name]||t.name}-copy-${Date.now().toString(36)}`:delete e[t.name]),t.type==="tabs"&&t.name&&Array.isArray(t.tabs)&&e[t.name]&&typeof e[t.name]=="object")for(let s of t.tabs)Array.isArray(s.fields)&&De(s.fields,e[t.name]);else if((t.type==="group"||t.type==="collapsible")&&t.name&&Array.isArray(t.fields)&&e[t.name]&&typeof e[t.name]=="object")De(t.fields,e[t.name]);else if(t.type==="array"&&t.name&&Array.isArray(t.fields)&&Array.isArray(e[t.name]))for(let s of e[t.name])s&&typeof s=="object"&&(delete s.id,De(t.fields,s));else if(t.type==="blocks"&&t.name&&Array.isArray(t.blocks)&&Array.isArray(e[t.name]))for(let s of e[t.name]){if(!s||typeof s!="object")continue;delete s.id;let a=s.type||s.blockType;if(!a)continue;let d=t.blocks.find(u=>u.slug===a);if(!d||!Array.isArray(d.fields))continue;let l=s.data&&typeof s.data=="object"?s.data:s;De(d.fields,l);}}}}var Jr={_media:{create:d.MEDIA_UPLOAD,update:d.MEDIA_UPLOAD,delete:d.MEDIA_DELETE}};function ke(c,e){let t=Jr[c];return t?t[e]:`collection.${e}`}function Zr(c){let e=c.headers.get("x-forwarded-for");return e?e.split(",")[0].trim():c.headers.get("x-real-ip")||"unknown"}function Ge(c,e,t,s,a){e?.apiKeyId&&c&&c.createAuditLog({action:"api_request",userId:e.userId||"",resource:"api_key",resourceId:e.apiKeyId,success:true,metadata:{endpoint:t,method:s,ip:Zr(a)}});}function Ye(c){return c.baseUpdatedAt??c._baseUpdatedAt}function St(c){let{baseUpdatedAt:e,_baseUpdatedAt:t,...s}=c;return s}function Tt(c,e){return {error:"Document has changed since you started editing",code:"REVISION_CONFLICT",conflict:{expectedUpdatedAt:c??null,actualUpdatedAt:e.updatedAt??null,current:e}}}async function N(c,e,t,s,a,d,l=true,u="none"){return await b$1(c,e,{user:s,req:t,tenantId:a,apiKey:d},{enablePublicAccess:l,defaultAccess:u})}async function J(c,e,t,s,a,d=true){return await c$2(c,e,{user:s,req:t,tenantId:a},{enablePublicAccess:d})}async function P(c,e,t,s){if(t)return {user:t,tenantId:s,apiKeyContext:void 0,authType:"static"};if(e){let a=await e(c);if(a.status===200&&a.user)return {user:a.user,tenantId:a.tenantContext?.tenantId,apiKeyContext:a.apiKeyContext,authType:a.authType}}return {user:void 0,tenantId:void 0,apiKeyContext:void 0,authType:void 0}}function Qr(c,e){if("dialect"in c&&c.dialect==="postgres"&&c instanceof c$1)return new a$6({db:c.client});if("dialect"in c&&c.dialect==="sqlite"&&c instanceof c$1)return new Be({db:c.client});if("dialect"in c&&c.dialect==="mongodb"){let s=c;return new a$7({db:()=>s.db})}let t=resolve(e,"data","auth.db");return new a$8({path:process.env.KYRO_AUTH_DB_PATH||t})}function pr(c){let{registry:e,db:t,authSecret:s,authAdapter:a,checkSession:d,user:l,tenantId:u,cors:f,webhookService:y,settings:I}=c,h=new Hono;function k$1(r){if(Array.isArray(r))return r.map(k$1);if(r!==null&&typeof r=="object"){let o={};for(let m in r)m!=="attrs"&&(o[m]=k$1(r[m]));return o}return r}h.use("*",async(r,o)=>{await o();let m=r.req.header("referer")||"";if(!(r.req.header("x-kyro-admin")==="true"||m.includes("/admin"))){let n=r.res.headers.get("Content-Type");if(n&&n.includes("application/json"))try{let p=await r.res.clone().json(),A=k$1(p);r.res=r.json(A,r.res.status);}catch{}}});for(let r of e.getPlugins())typeof r.serverMiddleware=="function"&&r.serverMiddleware(h);let C=I?.access?.apiAccess,R=I?.access?.enablePublicAccess??false,q=I?.access?.defaultCollectionAccess??"none";C?.requireAuth;let V=process.cwd(),ne=V.endsWith("admin")?resolve(V,".."):V,L=a||Qr(t,ne),E=Vt({db:t,userLookup:async r=>await L.findUserById(r)||null}),Q=C?.cors?.allowedOrigins,qe=f?.origins,Je=Array.isArray(Q)?Q:typeof Q=="string"&&Q?Q.split(`
106
106
  `).map(r=>r.trim()).filter(Boolean):[],me=Je.length>0?Je:qe||[];(me.length>0||f)&&h.use("*",async(r,o)=>{let m=r.req.header("Origin")||"*";if(me.length>0&&!me.includes(m))return r.json({error:"Origin not allowed"},403);let b=me.length>0?m:"*";if(r.header("Access-Control-Allow-Origin",b),r.header("Access-Control-Allow-Methods","GET, POST, PATCH, DELETE, OPTIONS"),r.header("Access-Control-Allow-Headers","Content-Type, Authorization, X-API-Key"),f?.credentials&&r.header("Access-Control-Allow-Credentials","true"),r.req.method==="OPTIONS")return r.text("");await o();});let ve=I?.access?.rateLimiting,be;if(ve?.enabled){let r=ve.maxRequests||100,o=ve.windowMs||6e4;be=new Oe({"api:general":{window:o,max:r}}),h.use("/api/*",async(m,b)=>{if(!be)return b();let n=m.req.header("CF-Connecting-IP")||m.req.header("X-Forwarded-For")?.split(",")[0]?.trim()||m.req.header("X-Real-IP")||"unknown",i=await be.check("api:general",n);if(m.header("X-RateLimit-Limit",String(r)),m.header("X-RateLimit-Remaining",String(i.remaining)),m.header("X-RateLimit-Reset",String(i.resetAt)),!i.allowed)return m.json({error:"Too many requests",retryAfter:i.retryAfter},429);await b();});}let O=new Me({redis:L,jwtSecret:s||"change-me",baseUrl:process.env.KYRO_BASE_URL||"http://localhost:4321",rateLimiter:be});k.fromConfig(t).then(r=>{r&&(O.email=r);}).catch(r=>{console.error("[Email] Failed to initialize transport from config:",r);}),h.post("/api/auth/login",async r=>O.login(r.req.raw)),h.post("/api/auth/register",async r=>{try{let o=await t.findOne({collection:"_globals_system",where:{}});if(o&&o.enableRegistration===!1)return r.json({error:"User registration is currently disabled by administrator."},403);if(o?.defaultRegistrationRole){let m=r.req.raw;if((m.headers.get("content-type")||"").includes("application/json")){let n=await r.req.json();n.role||(n.role=o.defaultRegistrationRole);let i=new Request(m.url,{method:m.method,headers:m.headers,body:JSON.stringify(n)});return O.register(i)}}}catch{}return O.register(r.req.raw)}),h.post("/api/auth/logout",async r=>O.logout(r.req.raw)),h.post("/api/auth/refresh",async r=>O.refresh(r.req.raw)),h.get("/api/auth/me",async r=>O.me(r.req.raw)),h.post("/api/auth/forgot-password",async r=>O.forgotPassword(r.req.raw)),h.post("/api/auth/reset-password",async r=>O.resetPassword(r.req.raw)),h.post("/api/auth/change-password",async r=>O.changePassword(r.req.raw)),h.get("/api/auth/verify-email",async r=>O.verifyEmail(r.req.raw)),h.post("/api/auth/verify-email",async r=>O.verifyEmail(r.req.raw)),h.get("/api/auth/verify",async r=>O.verifyEmail(r.req.raw)),h.post("/api/auth/verify",async r=>O.verifyEmail(r.req.raw)),h.get("/api/auth/sessions",async r=>O.listSessions(r.req.raw)),h.post("/api/auth/sessions/refresh",async r=>O.refreshSession(r.req.raw)),h.delete("/api/auth/sessions",async r=>O.revokeOtherSessions(r.req.raw)),h.delete("/api/auth/sessions/:id",async r=>O.revokeSession(r.req.raw,r.req.param("id"))),h.put("/api/auth/sessions/:id/name",async r=>O.renameSession(r.req.raw,r.req.param("id"))),h.get("/api/auth/access",async r=>{try{let{user:o,tenantId:m}=await P(r.req.raw,E,l,u);if(!o)return r.json({error:"Not authenticated"},401);let b={},n={};for(let i of e.getCollections()){let p={read:(await N(i,"read",r.req.raw,o,m,void 0,R,q)).allowed,create:(await N(i,"create",r.req.raw,o,m,void 0,R,q)).allowed,update:(await N(i,"update",r.req.raw,o,m,void 0,R,q)).allowed,delete:(await N(i,"delete",r.req.raw,o,m,void 0,R,q)).allowed};b[i.slug]=p;}for(let i of e.getGlobals()){let p={read:(await J(i,"read",r.req.raw,o,m,R)).allowed,update:(await J(i,"update",r.req.raw,o,m,R)).allowed};n[i.slug]=p;}return r.json({collections:b,globals:n})}catch(o){return r.json({error:o.message},500)}});let X=typeof e.hasCollection=="function"&&e.hasCollection("users")?e.getCollection("users"):(()=>{try{return e.getCollection("users")}catch{return a$2}})();h.get("/api/users",async r=>{try{let{user:o,tenantId:m}=await P(r.req.raw,E,l,u),b=await N(X,"read",r.req.raw,o,m,void 0,R,q);if(!b.allowed)return r.json({error:b.error},b.status||403);let n=parseInt(r.req.query("page")||"1"),i=Math.min(parseInt(r.req.query("limit")||"10"),100),p=r.req.query("search")||void 0,A=[],g=0;if(typeof L.findUsers=="function"){let w=await L.findUsers({page:n,limit:i,search:p});A=w.users||[],g=w.total||0;}else {let w=await t.find({collection:"users",page:n,limit:i,where:p?{email:{contains:p}}:{},tenantId:m});A=w.docs||[],g=w.totalDocs||0;}return r.json({docs:A,totalDocs:g,limit:i,totalPages:Math.ceil(g/i)||1,page:n,pagingCounter:(n-1)*i+1,hasPrevPage:n>1,hasNextPage:n<Math.ceil(g/i),prevPage:n>1?n-1:null,nextPage:n<Math.ceil(g/i)?n+1:null})}catch(o){return console.error("[API] Error listing users:",o),r.json({error:o.message},500)}}),h.get("/api/users/:id",async r=>{try{let{user:o,tenantId:m}=await P(r.req.raw,E,l,u),b=r.req.param("id"),n=await L.findUserById(b);return n?r.json({data:n}):r.json({error:"User not found"},404)}catch(o){return r.json({error:o.message},500)}}),h.post("/api/users",async r=>{try{let{user:o,tenantId:m}=await P(r.req.raw,E,l,u),b=await N(X,"create",r.req.raw,o,m,void 0,R,q);if(!b.allowed)return r.json({error:b.error},b.status||403);let n=await r.req.json();if(!n.email||!n.password)return r.json({error:"Email and password are required"},400);if(await L.findUserByEmail(n.email))return r.json({error:"Email already in use"},400);let p=n.role||"customer";if(p!=="customer"&&o?.role!=="super_admin")return r.json({error:"Forbidden: Only super_admin can assign administrative roles"},403);let A=await L.createUser({email:n.email,password:n.password,name:n.name,role:p,avatar:n.avatar,tenantId:n.tenantId});return o&&L?.createAuditLog({action:"user_create",userId:o.id,resource:"users",resourceId:A.id,success:!0}),r.json({data:A,message:"User created successfully"},201)}catch(o){return r.json({error:o.message},500)}}),h.patch("/api/users/:id",async r=>{try{let{user:o,tenantId:m}=await P(r.req.raw,E,l,u),b=await N(X,"update",r.req.raw,o,m,void 0,R,q);if(!b.allowed)return r.json({error:b.error},b.status||403);let n=r.req.param("id"),i=await r.req.json(),p=await L.findUserById(n);if(!p)return r.json({error:"User not found"},404);let A={};if(i.name!==void 0&&(A.name=i.name),i.email!==void 0&&(A.email=i.email),i.role!==void 0&&i.role!==p.role){if(o?.role!=="super_admin")return r.json({error:"Forbidden: Only super_admin can modify user roles"},403);A.role=i.role;}i.avatar!==void 0&&(A.avatar=typeof i.avatar=="object"&&i.avatar!==null?i.avatar.id||String(i.avatar):i.avatar),i.tenantId!==void 0&&(A.tenantId=i.tenantId),i.emailVerified!==void 0&&(A.emailVerified=i.emailVerified),i.locked!==void 0&&(A.locked=i.locked),i.failedLoginAttempts!==void 0&&(A.failedLoginAttempts=i.failedLoginAttempts),i.lastLogin!==void 0&&(A.lastLogin=i.lastLogin);let g=await L.updateUser(n,A);return g?(o&&(L?.createAuditLog({action:"user_update",userId:o.id,resource:"users",resourceId:n,success:!0}),i.role&&p.role!==i.role&&L?.createAuditLog({action:"role_change",userId:o.id,resource:"users",resourceId:n,success:!0,metadata:{oldRole:p.role,newRole:i.role}})),r.json({data:g,message:"User updated successfully"})):r.json({error:"User update failed"},500)}catch(o){return r.json({error:o.message},500)}}),h.delete("/api/users/:id",async r=>{try{let{user:o,tenantId:m}=await P(r.req.raw,E,l,u),b=await N(X,"delete",r.req.raw,o,m,void 0,R,q);if(!b.allowed)return r.json({error:b.error},b.status||403);let n=r.req.param("id");if(o&&o.id===n)return r.json({error:"You cannot delete your own account"},403);let i=await L.findUserById(n);return i?await L.deleteUser(n)?(o&&L?.createAuditLog({action:"user_delete",userId:o.id,resource:"users",resourceId:n,success:!0}),r.json({data:i,message:"User deleted successfully"})):r.json({error:"User deletion failed"},500):r.json({error:"User not found"},404)}catch(o){return r.json({error:o.message},500)}}),h.get("/api/auth/audit-logs",async r=>{try{let{user:o,tenantId:m}=await P(r.req.raw,E,l,u),b=e.getCollection("audit_logs");if(b){let T=await N(b,"read",r.req.raw,o,m,void 0,R,q);if(!T.allowed)return r.json({error:T.error},T.status||403)}else if(!o)return r.json({error:"Authentication required"},401);let n=parseInt(r.req.query("page")||"1"),i=Math.min(parseInt(r.req.query("limit")||"50"),100),p=r.req.query("action")||void 0,A=r.req.query("userId")||void 0,g=r.req.query("resource")||void 0,w=await L.findAuditLogs({action:p,userId:A,resource:g,limit:i,offset:(n-1)*i});return r.json({docs:w.logs,totalDocs:w.total,limit:i,totalPages:Math.ceil(w.total/i),page:n,pagingCounter:(n-1)*i+1,hasPrevPage:n>1,hasNextPage:n<Math.ceil(w.total/i),prevPage:n>1?n-1:null,nextPage:n<Math.ceil(w.total/i)?n+1:null})}catch(o){return console.error("[API] Error listing audit logs:",o),r.json({error:o.message},500)}});let G=null,ae=null,K=async()=>{if(ae)throw ae;if(!G)try{let r="sqlite";"dialect"in t&&t.dialect==="postgres"&&t instanceof c$1?r=t.dialect:"dialect"in t&&t.dialect==="mongodb"&&(r="mongodb");let o=r==="postgres"&&t instanceof c$1?t.client:t;G=await He.init(o,{dialect:r});}catch(r){throw console.error("[getMedia] Init error:",r),ae=r,r}return G};h.get("/api/media",async r=>{try{let{user:o}=await P(r.req.raw,E,l,u);if(!o)return r.json({error:"Authentication required"},401);let m=await K(),b=new URL(r.req.url).origin,n=parseInt(r.req.query("page")||"1"),i=parseInt(r.req.query("limit")||"30"),p=r.req.query("search")||"",A=r.req.query("type")||"",g=r.req.query("folder")||"",w=await m.find({page:n,limit:i,search:p,type:A,folder:g},b);return r.json(w)}catch(o){return console.error("[Media] find error:",o),r.json({error:o.message},500)}}),h.post("/api/media/upload",async r=>{try{let{user:o}=await P(r.req.raw,E,l,u);if(!o)return r.json({error:"Authentication required"},401);let m=await K(),b=r.req.header("content-type")||"",n=new URL(r.req.url).origin;if(b.includes("multipart/form-data")){let w=await r.req.formData(),T=w.get("file"),S=w.get("folder")||"";if(!T)return r.json({error:"No file uploaded"},400);let v=await m.upload(T,S,n);return r.json(v)}let i=await r.req.json(),{url:p}=i,A=i.folder||"";if(!p)return r.json({error:"No URL provided"},400);let g=await m.uploadFromUrl(p,A,n);return r.json(g)}catch(o){return console.error("[Media] upload error:",o),r.json({error:o.message},500)}}),h.get("/api/media/folders",async r=>{try{let{user:o}=await P(r.req.raw,E,l,u);if(!o)return r.json({error:"Authentication required"},401);let b=await(await K()).listFolders();return r.json(b)}catch(o){return console.error("[Media] folders error:",o),r.json({error:o.message},500)}}),h.post("/api/media/folders",async r=>{try{let{user:o}=await P(r.req.raw,E,l,u);if(!o)return r.json({error:"Authentication required"},401);let m=await K(),b=await r.req.json(),{name:n,parentPath:i}=b;return n?(await m.createFolder(n,i||""),r.json({message:"Folder created",path:i?`${i}/${n}`:n})):r.json({error:"Folder name is required"},400)}catch(o){return console.error("[Media] create folder error:",o),r.json({error:o.message},500)}}),h.delete("/api/media/folders",async r=>{try{let{user:o}=await P(r.req.raw,E,l,u);if(!o)return r.json({error:"Authentication required"},401);let m=await K(),b=r.req.query("path");return b?(await m.deleteFolder(b),r.json({message:"Folder deleted"})):r.json({error:"Path is required"},400)}catch(o){return console.error("[Media] delete folder error:",o),r.json({error:o.message},500)}}),h.delete("/api/media/:id",async r=>{try{let{user:o}=await P(r.req.raw,E,l,u);if(!o)return r.json({error:"Authentication required"},401);let m=await K(),b=r.req.param("id"),n=new URL(r.req.url).origin;return await m.delete(b,n),r.json({success:!0})}catch(o){return console.error("[Media] delete error:",o),r.json({error:o.message},500)}}),h.get("/api/media/resize",async r=>{try{let{user:o}=await P(r.req.raw,E,l,u);if(!o)return r.json({error:"Authentication required"},401);let m=r.req.query("url"),b=parseInt(r.req.query("w")||"0"),n=parseInt(r.req.query("h")||"0"),i=r.req.query("fit")||"cover",p=parseFloat(r.req.query("cx")||"0"),A=parseFloat(r.req.query("cy")||"0"),g=parseFloat(r.req.query("cw")||"0"),w=parseFloat(r.req.query("ch")||"0");if(!m)return r.json({error:"URL is required"},400);let S=(await K()).storage;if(S.name!=="local")return r.redirect(m);let v=S.config?.uploadDir||join(process.cwd(),"public","uploads"),x=S.config?.baseUrl||"/uploads";if(!m.startsWith(x))return r.redirect(m);let U=m.replace(x,""),j=join(v,U);if(!existsSync(j))return r.json({error:"File not found"},404);let $=readFileSync(j),{default:D}=await import('sharp'),_=D($);if(g>0&&w>0){let M=await D($).metadata(),oe=M.width||0,W=M.height||0;if(oe>0&&W>0){let H=Math.max(0,Math.min(Math.round(p/100*oe),oe-1)),Ae=Math.max(0,Math.min(Math.round(A/100*W),W-1)),mr=Math.max(1,Math.min(Math.round(g/100*oe),oe-H)),gr=Math.max(1,Math.min(Math.round(w/100*W),W-Ae));_=_.extract({left:H,top:Ae,width:mr,height:gr});}}(b>0||n>0)&&(_=_.resize({width:b>0?b:void 0,height:n>0?n:void 0,fit:i}));let F=await _.toBuffer(),Y=await D($).metadata();return r.header("Content-Type",`image/${Y.format||"webp"}`),r.header("Cache-Control","public, max-age=31536000, immutable"),r.body(F)}catch(o){return console.error("[Media] resize error:",o),r.json({error:o.message},500)}}),h.get("/api/media/:id",async r=>{try{let{user:o}=await P(r.req.raw,E,l,u);if(!o)return r.json({error:"Authentication required"},401);let m=await K(),b=r.req.param("id"),n=new URL(r.req.url).origin,i=await m.findById(b,n);return i?r.json(i):r.json({error:"Media not found"},404)}catch(o){return console.error("[Media] get error:",o),r.json({error:o.message},500)}}),h.patch("/api/media/:id",async r=>{try{let{user:o}=await P(r.req.raw,E,l,u);if(!o)return r.json({error:"Authentication required"},401);let m=await K(),b=r.req.param("id"),n=await r.req.json(),i=new URL(r.req.url).origin,p=["folder","metadata","title","alt","caption","originalName"],A={};for(let g of p)n[g]!==void 0&&(A[g]=n[g]);if(Object.keys(A).length>0){let g=await m.update(b,A,i);return r.json({doc:g})}return r.json({error:"No valid fields to update"},400)}catch(o){return console.error("[Media] update error:",o),r.json({error:o.message},500)}}),h.get("/api/media/test",async r=>{try{let{user:o}=await P(r.req.raw,E,l,u);if(!o)return r.json({error:"Authentication required"},401);let m=await K();return r.json({status:m?"initialized":"failed",serviceType:m?.constructor?.name})}catch(o){return console.error("[test] Error:",o),r.json({error:o.message,type:o.constructor?.name,stack:o.stack},500)}}),h.get("/api/storage-status",async r=>{try{let{user:o}=await P(r.req.raw,E,l,u);if(!o)return r.json({error:"Authentication required"},401);let m=!1,b="local";if(t)try{let n=t.prepare('SELECT provider FROM "_globals_storage-settings" LIMIT 1').get();n&&n.provider&&(m=!0,b=n.provider==="aws"?"s3":n.provider);}catch{try{let n=await t.findOne({collection:"_globals_storage-settings",where:{},draft:!0});n&&n.provider&&(m=!0,b=n.provider==="aws"?"s3":n.provider);}catch{}}return r.json({provider:b,configured:m,usage:0,limit:"unlimited"})}catch(o){return console.error("[Storage] status error:",o),r.json({error:o.message},500)}}),h.get("/api/plugins",async r=>{try{let{user:o}=await P(r.req.raw,E,l,u);if(!o)return r.json({error:"Authentication required"},401);let m=e.getPlugins(),b=e.storageProviders,n=await Promise.all(m.map(async i=>{let p=!0,A=i.name,g={};try{let S=await t.findOne({collection:"_globals_plugin-settings",where:{},draft:!0});S&&S.states&&(g=S.states);}catch{}g[A]!==void 0&&(p=g[A]),b.setPluginEnabled(A,p);let w=A.replace(/^@[^/]+\//,"");w=w.replace(/^(plugin|kyro)-/,"");let T={ai:"AI",seo:"SEO",s3:"S3",aws:"AWS",api:"API",ui:"UI",ftp:"FTP"};if(w=w.split("-").map(S=>{let v=S.toLowerCase();return T[v]?T[v]:S.charAt(0).toUpperCase()+S.slice(1)}).join(" "),w.toLowerCase().startsWith("storage ")){let S=w.split(" ");S.length===2&&(w=`${S[1]} Storage`);}return {id:A,name:i.displayName||w,version:i.version||"1.0.0",description:i.description||"",enabled:p,status:p?"active":"disabled"}}));return r.json(n)}catch(o){return console.error("[Plugins] list error:",o),r.json({error:o.message},500)}}),h.put("/api/plugins/:name/toggle",async r=>{try{let{user:o}=await P(r.req.raw,E,l,u);if(!o)return r.json({error:"Authentication required"},401);let m=r.req.param("name"),b=e.storageProviders,i=!b.isPluginEnabled(m),p=[];if(!i)for(let g of b.getAll())g.pluginName===m&&p.push(g.type);if(!(r.req.query("force")==="1")&&!i&&p.length>0){let g="local";try{let w=t?.prepare?.('SELECT provider FROM "_globals_storage-settings" LIMIT 1')?.get();w?.provider&&(g=w.provider);}catch{try{let w=await t?.findOne?.({collection:"_globals_storage-settings",where:{},draft:!0});w?.provider&&(g=w.provider);}catch{}}if(p.includes(g))return r.json({error:`Cannot disable "${m}" \u2014 storage provider "${g}" is currently active. Switch to Local storage first.`,requiresAction:!0,activeProvider:g},409)}try{let g={},w="global",T=await t.findOne({collection:"_globals_plugin-settings",where:{},draft:!0});T&&(g=T.states||{},w=T.id),g[m]=i,T?await t.update({collection:"_globals_plugin-settings",id:w,data:{states:g}}):await t.create({collection:"_globals_plugin-settings",data:{states:g,id:"global"}});}catch(g){console.warn(`[Plugins] Could not persist state for "${m}":`,g);}return b.setPluginEnabled(m,i),r.json({name:m,enabled:i})}catch(o){return console.error("[Plugins] toggle error:",o),r.json({error:o.message},500)}}),h.get("/api/health",r=>r.json({status:"ok",version:"0.11.0",collections:e.getCollectionSlugs(),timestamp:new Date().toISOString()})),h.get("/api/metrics",async r=>{try{let{user:o,tenantId:m}=await P(r.req.raw,E,l,u);if(!o)return r.json({error:"Authentication required"},401);let b=o.role==="admin"||o.role==="super_admin",i=e.getCollectionSlugs().filter(x=>!["users","audit_logs","media","_globals_access-settings","_globals_brand-settings"].includes(x)&&!x.startsWith("_globals_")).filter(x=>b||a$3(o,`${x}:read`)),p=0,A={};await Promise.all(i.map(async x=>{try{let j=(await t.find({collection:x,where:{},limit:1,page:1,tenantId:m})).totalDocs??0;p+=j,A[x]=j;}catch{}}));let g=0;try{g=(await t.find({collection:"media",where:{},limit:1,page:1,tenantId:m})).totalDocs??0;}catch{}let w=0;try{w=(await t.find({collection:"users",where:{},limit:1,page:1,tenantId:m})).totalDocs??0;}catch{}let T=0;try{if(y){let x=await y.getWebhooks();T=Array.isArray(x)?x.length:0;}}catch{}let S=0;try{S=(await t.find({collection:d$1,where:{},limit:1,page:1,tenantId:m})).totalDocs??0;}catch{}let v=p+g+w;return r.json({totalDocuments:p,totalMedia:b||a$3(o,"media:read")?g:void 0,totalUsers:b||a$3(o,"users:read")?w:void 0,totalWebhooks:b?T:void 0,totalApiKeys:b?S:void 0,totalStoredRecords:v,collectionCounts:A,collections:i.length,timestamp:new Date().toISOString()})}catch(o){return console.error("[API] Metrics error:",o),r.json({error:o.message},500)}}),h.get("/api/analytics",async r=>{try{let{user:o,tenantId:m}=await P(r.req.raw,E,l,u);if(!o)return r.json({error:"Authentication required"},401);if(!(o.role==="admin"||o.role==="super_admin"))return r.json({error:"Unauthorized"},403);let i=(await t.find({collection:"orders",where:{},limit:1e3,page:1,tenantId:m})).docs||[],p=await t.findOne({collection:"_globals_store-settings",where:{},tenantId:m}),A=p?.currency?.code||p?.currency||"USD",g={},w={},T={};i.forEach(x=>{let U=x.createdAt||x.updatedAt,j=U?new Date(U).toISOString().split("T")[0]:new Date().toISOString().split("T")[0];g[j]||(g[j]=0),w[j]||(w[j]=0);let $=typeof x.total=="number"?x.total:parseFloat(String(x.total||0));g[j]+=isNaN($)?0:$,w[j]+=1;let D=x.orderStatus||x.status||"pending";T[D]=(T[D]||0)+1;});let S=Object.keys(g).sort().map(x=>({date:x,revenue:Math.round(g[x]*100)/100,orders:w[x]})),v=Math.round(S.reduce((x,U)=>x+U.revenue,0)*100)/100;return r.json({chartData:S,totalRevenue:v,totalOrders:i.length,ordersByStatus:T,currencyCode:typeof A=="string"?A:"USD"})}catch(o){return r.json({error:o.message},500)}}),h.get("/api/kyro/schema",async r=>{let{user:o}=await P(r.req.raw,E,l,u);if(!o)return r.json({error:"Authentication required"},401);let m=n=>n.map(i=>{let p={name:i.name,type:i.type,label:i.label,required:i.required??false,unique:i.unique??false,indexed:i.indexed??false,defaultValue:i.defaultValue,admin:i.admin?{...i.admin}:void 0};return i.minLength!==void 0&&(p.minLength=i.minLength),i.maxLength!==void 0&&(p.maxLength=i.maxLength),i.pattern!==void 0&&(p.pattern=i.pattern),i.variant!==void 0&&(p.variant=i.variant),i.hasMany!==void 0&&(p.hasMany=i.hasMany),i.min!==void 0&&(p.min=i.min),i.max!==void 0&&(p.max=i.max),i.step!==void 0&&(p.step=i.step),i.integer!==void 0&&(p.integer=i.integer),i.options&&(p.options=i.options),i.relationTo&&(p.relationTo=i.relationTo),i.maxDepth!==void 0&&(p.maxDepth=i.maxDepth),i.minRows!==void 0&&(p.minRows=i.minRows),i.maxRows!==void 0&&(p.maxRows=i.maxRows),i.localized!==void 0&&(p.localized=i.localized),i.language&&(p.language=i.language),i.format&&(p.format=i.format),i.allowedTypes&&(p.allowedTypes=i.allowedTypes),i.maxSize&&(p.maxSize=i.maxSize),(i.type==="group"||i.type==="row"||i.type==="collapsible"&&i.fields)&&(p.fields=m(i.fields)),i.type==="array"&&i.fields&&(p.fields=m(i.fields)),i.type==="blocks"&&i.blocks&&(p.blocks=i.blocks.map(A=>({slug:A.slug,label:A.label,fields:m(A.fields)}))),i.type==="tabs"&&i.tabs&&(p.tabs=i.tabs.map(A=>({label:A.label,name:A.name,fields:m(A.fields)}))),p}),b={collections:{},globals:{}};for(let n of e.getCollections()){let i=n.slug;try{b.collections[i]={slug:i,label:n.label||i,fields:m(n.fields),jsonSchema:zodToJsonSchema(e.getZodSchema(i),{target:"openApi3"}),createSchema:zodToJsonSchema(e.getCreateZodSchema(i),{target:"openApi3"}),updateSchema:zodToJsonSchema(e.getUpdateZodSchema(i),{target:"openApi3"}),procedures:{find:{collection:i,where:"Record<string,any>",sort:"string",limit:"number",page:"number",depth:"number",select:"string[]",draft:"boolean"},findByID:{collection:i,id:"string",depth:"number",select:"string[]",draft:"boolean"},create:{collection:i,data:"Record<string,any>",depth:"number",select:"string[]"},update:{collection:i,id:"string",data:"Record<string,any>",depth:"number",select:"string[]",baseUpdatedAt:"string"},delete:{collection:i,id:"string"},count:{collection:i,where:"Record<string,any>"}}};}catch{}}for(let n of e.getGlobals()){let i=n.slug,p=n.fields;if(i==="storage-settings"){let A=e.storageProviders,g=A.getAll(),w=new Set(A.getAllAvailable(S=>A.isPluginEnabled(S)).map(S=>S.type));w.add("local");let T=new Set(g.map(S=>S.type));p=p.filter(S=>S.type==="group"&&S.name&&T.has(S.name)?w.has(S.name):true).map(S=>S.name==="provider"&&S.type==="select"?{...S,options:S.options.filter(v=>w.has(v.value))}:S);}try{b.globals[i]={slug:i,label:n.label||i,fields:m(p),jsonSchema:zodToJsonSchema(e.getZodSchema(i),{target:"openApi3"}),procedures:{get:{},update:{data:"Record<string,any>"}}};}catch{}}return r.json(b)}),h.get("/api/collections",async r=>{let{user:o}=await P(r.req.raw,E,l,u);if(!o)return r.json({error:"Authentication required"},401);let m=e.getCollections().map(b=>({slug:b.slug,label:b.label||b.slug,fields:b.fields.filter(n=>n.name).map(n=>({name:n.name,type:n.type,required:n.required,label:n.label}))}));return r.json(m)});function Re(r,o,m){if(m in o)return o[m];for(let b of r)if(b.name){if(b.type==="tabs"&&b.tabs){let n=o[b.name];if(n&&typeof n=="object"&&m in n)return n[m]}if((b.type==="group"||b.type==="collapsible")&&b.fields){let n=o[b.name];if(n&&typeof n=="object"){if(m in n)return n[m];let i=Re(b.fields,n,m);if(i!==void 0)return i}}}}h.get("/api/search",async r=>{try{let o=r.req.query("q")||"",m=r.req.query("collections")||"",b=Math.min(parseInt(r.req.query("limit")||"10"),50);if(!o||o.length<2)return r.json({results:[],message:"Query too short"});let{user:n,tenantId:i}=await P(r.req.raw,E,l,u),p=m?m.split(",").filter(Boolean):e.getCollectionSlugs(),A=[],g=new RegExp(o.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"i");for(let w of e.getCollections()){if(!p.includes(w.slug)||!(await N(w,"read",r.req.raw,n,i,void 0,R,q)).allowed)continue;let S=w.fields.filter(v=>v.name&&v.name!=="id"&&(v.type==="text"||v.type==="email"||v.type==="textarea"||v.type==="richtext"||v.indexed)&&!v.admin?.hidden).map(v=>v.name);if(S.length!==0)try{let v=S.map(U=>{let j={};return j[U]={like:`%${o}%`},j}),x=await t.find({collection:w.slug,where:{OR:v},limit:b,tenantId:i});await a$4(x.docs,w.fields,t,e,1,0);for(let U of x.docs){let j=w.admin?.useAsTitle||S.find(D=>D==="title"||D==="name"||D==="heading"||D==="slug"),$=j?Re(w.fields,U,j)??U.id:U.id;A.push({collection:w.slug,label:w.label||w.slug,id:U.id,title:String($||"Untitled"),doc:U});}}catch(v){console.error(`Search error for ${w.slug}:`,v);}}return A.sort((w,T)=>w.label.localeCompare(T.label)),r.json({results:A})}catch(o){return r.json({error:o.message,results:[]},500)}}),h.get("/api/keys",async r=>{try{let{user:o,tenantId:m}=await P(r.req.raw,E,l,u);if(!o||!a$3(o,"users:read"))return r.json({error:"Forbidden"},403);let b=parseInt(r.req.query("page")||"1"),n=Math.min(parseInt(r.req.query("limit")||"50"),100),i=await t.find({collection:d$1,where:{},page:b,limit:n,tenantId:m}),p=(i.docs||[]).map(A=>({id:A.id,name:A.name,keyPrefix:A.keyPrefix,permissions:A.permissions||[],lastUsed:A.lastUsedAt,createdAt:A.createdAt}));return r.json({docs:p,totalDocs:i.totalDocs||p.length,totalPages:i.totalPages||1})}catch(o){return console.error("[ApiKeys] GET error:",o),r.json({error:o.message},500)}}),h.post("/api/keys",async r=>{try{let{user:o}=await P(r.req.raw,E,l,u);if(!o||!a$3(o,"users:admin"))return r.json({error:"Forbidden"},403);let m=await r.req.json();if(!m.name||typeof m.name!="string")return r.json({error:"name is required"},400);let b=i(),n=await t.create({collection:d$1,data:{userId:o.id,name:m.name,key:b,keyPrefix:j$1(b),permissions:Array.isArray(m.permissions)?m.permissions:["*"],expiresAt:m.expiresAt||null,createdAt:new Date().toISOString()}});return await L?.createAuditLog({action:"api_key_create",userId:o.id,resource:"api_key",resourceId:n.id,success:!0,metadata:{keyName:m.name}}),r.json({...n,key:b,permissions:Array.isArray(m.permissions)?m.permissions:["*"]},201)}catch(o){return console.error("[ApiKeys] POST error:",o),r.json({error:o.message},500)}}),h.delete("/api/keys/:id",async r=>{try{let{user:o}=await P(r.req.raw,E,l,u);if(!o||!a$3(o,"users:admin"))return r.json({error:"Forbidden"},403);let m=r.req.param("id"),b=await t.findByID({collection:d$1,id:m});return b?(await t.delete({collection:d$1,id:m}),await L?.createAuditLog({action:"api_key_delete",userId:o.id,resource:"api_key",resourceId:m,success:!0,metadata:{keyName:b.name}}),r.json({message:"API key deleted"})):r.json({error:"API key not found"},404)}catch(o){return console.error("[ApiKeys] DELETE error:",o),r.json({error:o.message},500)}}),h.patch("/api/keys/:id",async r=>{try{let{user:o}=await P(r.req.raw,E,l,u);if(!o||!a$3(o,"users:admin"))return r.json({error:"Forbidden"},403);let m=r.req.param("id"),b=await r.req.json(),n=await t.findByID({collection:d$1,id:m});if(!n)return r.json({error:"API key not found"},404);let i={};if(typeof b.name=="string"&&b.name.trim()&&(i.name=b.name.trim()),Array.isArray(b.permissions)&&(i.permissions=b.permissions),b.expiresAt!==void 0&&(i.expiresAt=b.expiresAt||null),Object.keys(i).length===0)return r.json({error:"Nothing to update"},400);let p=await t.update({collection:d$1,id:m,data:i});return r.json({...p,keyPrefix:n.keyPrefix})}catch(o){return console.error("[ApiKeys] PATCH error:",o),r.json({error:o.message},500)}}),h.post("/api/keys/:id/rotate",async r=>{try{let{user:o}=await P(r.req.raw,E,l,u);if(!o||!a$3(o,"users:admin"))return r.json({error:"Forbidden"},403);let m=r.req.param("id"),b=await t.findByID({collection:d$1,id:m});if(!b)return r.json({error:"API key not found"},404);let n=i(),i$1=await t.update({collection:d$1,id:m,data:{key:n,keyPrefix:j$1(n),lastUsedAt:null}});return await L?.createAuditLog({action:"api_key_rotate",userId:o.id,resource:"api_key",resourceId:m,success:!0,metadata:{keyName:b.name}}),r.json({...i$1,key:n,permissions:b.permissions,expiresAt:b.expiresAt})}catch(o){return console.error("[ApiKeys] rotate error:",o),r.json({error:o.message},500)}}),h.get("/api/webhooks/actions",async r=>{try{let{user:o}=await P(r.req.raw,E,l,u);if(!o||!a$3(o,"users:read"))return r.json({error:"Forbidden"},403);let m={generic:{label:"Custom URL",description:"POST to any endpoint with Kyro payload",configFields:[],envVars:[]},"github-push":{label:"GitHub Push",description:"Push an empty commit to simulate a push event",configFields:[{name:"githubOwner",label:"Owner",required:!0,placeholder:"e.g., kyro-dev"},{name:"githubRepo",label:"Repository",required:!0,placeholder:"e.g., my-website"},{name:"githubBranch",label:"Branch",required:!1,placeholder:"main"}],envVars:["GITHUB_TOKEN"]}};return r.json({actions:m})}catch(o){return console.error("[Webhooks] actions error:",o),r.json({error:o.message},500)}}),h.get("/api/webhooks",async r=>{try{let{user:o}=await P(r.req.raw,E,l,u);if(!o||!a$3(o,"users:read"))return r.json({error:"Forbidden"},403);if(!y)return r.json({error:"Webhook service not available"},503);let m=await y.getWebhooks();return r.json({docs:m})}catch(o){return console.error("[Webhooks] GET error:",o),r.json({error:o.message},500)}}),h.post("/api/webhooks",async r=>{try{let{user:o}=await P(r.req.raw,E,l,u);if(!o||!a$3(o,"users:admin"))return r.json({error:"Forbidden"},403);if(!y)return r.json({error:"Webhook service not available"},503);let m=await r.req.json(),b=await y.createWebhook(m);return await L?.createAuditLog({action:"webhook_create",userId:o.id,resource:"webhook",resourceId:b.id,success:!0,metadata:{name:b.name,url:b.url}}),r.json(b,201)}catch(o){return console.error("[Webhooks] POST error:",o),r.json({error:o.message},500)}}),h.get("/api/webhooks/:id",async r=>{try{let{user:o}=await P(r.req.raw,E,l,u);if(!o||!a$3(o,"users:read"))return r.json({error:"Forbidden"},403);if(!y)return r.json({error:"Webhook service not available"},503);let m=r.req.param("id"),b=await y.getWebhookById(m);return b?r.json(b):r.json({error:"Webhook not found"},404)}catch(o){return console.error("[Webhooks] GET :id error:",o),r.json({error:o.message},500)}}),h.patch("/api/webhooks/:id",async r=>{try{let{user:o}=await P(r.req.raw,E,l,u);if(!o||!a$3(o,"users:admin"))return r.json({error:"Forbidden"},403);if(!y)return r.json({error:"Webhook service not available"},503);let m=r.req.param("id"),b=await r.req.json(),n=await y.updateWebhook(m,b);return n?(await L?.createAuditLog({action:"webhook_update",userId:o.id,resource:"webhook",resourceId:m,success:!0,metadata:{name:n.name}}),r.json(n)):r.json({error:"Webhook not found"},404)}catch(o){return console.error("[Webhooks] PATCH error:",o),r.json({error:o.message},500)}}),h.delete("/api/webhooks/:id",async r=>{try{let{user:o}=await P(r.req.raw,E,l,u);if(!o||!a$3(o,"users:admin"))return r.json({error:"Forbidden"},403);if(!y)return r.json({error:"Webhook service not available"},503);let m=r.req.param("id"),b=await y.getWebhookById(m);return b?(await y.deleteWebhook(m),await L?.createAuditLog({action:"webhook_delete",userId:o.id,resource:"webhook",resourceId:m,success:!0,metadata:{name:b.name}}),r.json({message:"Webhook deleted"})):r.json({error:"Webhook not found"},404)}catch(o){return console.error("[Webhooks] DELETE error:",o),r.json({error:o.message},500)}}),h.post("/api/webhooks/:id/test",async r=>{try{let{user:o}=await P(r.req.raw,E,l,u);if(!o||!a$3(o,"users:admin"))return r.json({error:"Forbidden"},403);if(!y)return r.json({error:"Webhook service not available"},503);let m=r.req.param("id"),b=await y.testWebhook(m);return b?r.json(b):r.json({error:"Webhook not found"},404)}catch(o){return console.error("[Webhooks] test error:",o),r.json({error:o.message},500)}}),h.get("/api/webhooks/:id/history",async r=>{try{let{user:o}=await P(r.req.raw,E,l,u);if(!o||!a$3(o,"users:read"))return r.json({error:"Forbidden"},403);if(!y)return r.json({error:"Webhook service not available"},503);let m=r.req.param("id"),b=Math.min(parseInt(r.req.query("limit")||"50"),100),n=await y.getDeliveryHistory(m,b);return r.json({docs:n})}catch(o){return console.error("[Webhooks] history error:",o),r.json({error:o.message},500)}});function Ee(r){let o={},m=["name","type","required","hasMany","relationTo","options","min","max","minLength","maxLength","defaultValue","label","localized","admin","unique","index","hidden","readOnly","deprecated"];for(let b of m)b in r&&(o[b]=r[b]);return r.fields&&(o.fields=r.fields.map(Ee)),r.tabs&&(o.tabs=r.tabs.map(b=>({label:b.label,name:b.name,fields:b.fields.map(Ee)}))),o}h.get("/api/__schema",async r=>{try{let{user:o,apiKeyContext:m}=await P(r.req.raw,E,l,u);if(!o&&!m)return r.json({error:"Unauthorized"},401);let n=e.getCollections().filter(i=>i.slug!=="users"&&i.slug!=="audit_logs").map(i=>({slug:i.slug,label:i.label,labelPlural:i.labelPlural,singularLabel:i.singularLabel,timestamps:i.timestamps,auth:!!i.auth,tenantScoped:!!i.tenantScoped,upload:i.upload?{staticDir:i.upload.staticDir,imageSizes:i.upload.imageSizes,mimeTypes:i.upload.mimeTypes}:void 0,fields:i.fields.map(Ee)}));return r.json(n)}catch(o){return console.error("[Schema] error:",o),r.json({error:o.message},500)}});let vt=e.getCollections();for(let r of vt){let b=function(n,i){let p=[],A=new Set([...Object.keys(n),...Object.keys(i)]);for(let g of A)g==="id"||g==="createdAt"||g==="updatedAt"||JSON.stringify(n[g])!==JSON.stringify(i[g])&&p.push({field:g,oldValue:g in n?n[g]:void 0,newValue:g in i?i[g]:void 0});return p};let o=r.slug;if(o==="users"||o==="audit_logs")continue;let m=`/api/${o}`;h.post(`${m}/dynamic-options/:fieldName`,async n=>{try{let{user:i,tenantId:p,apiKeyContext:A}=await P(n.req.raw,E,l,u),g=await N(r,"read",n.req.raw,i,p,A,R,q);if(!g.allowed)return n.json({error:g.error},g.status||403);let w=n.req.param("fieldName"),T=await n.req.json(),{data:S,siblingData:v}=T,x=ge(r.fields,w);if(!x)return n.json({error:"Field not found"},404);if(x.type!=="select")return n.json({error:"Field is not a select field"},400);let U=[];return typeof x.options=="function"?U=await x.options({data:S||{},siblingData:v||{}}):Array.isArray(x.options)&&(U=x.options),n.json({options:U})}catch(i){return n.json({error:i.message},500)}}),h.get(m,async n=>{try{let{user:i,tenantId:p,apiKeyContext:A}=await P(n.req.raw,E,l,u),g=await N(r,"read",n.req.raw,i,p,A,R,q);if(!g.allowed)return n.json({error:g.error},g.status||403);p&&t.setTenantContext({tenantId:p,userId:i?.id??"",role:i?.role,isSuperAdmin:i?.role==="super_admin"});let w=new URL(n.req.url),T=parseInt(w.searchParams.get("page")||"1"),S=Math.min(parseInt(w.searchParams.get("limit")||"10"),100),v=w.searchParams.get("sort")||void 0,x=parseInt(w.searchParams.get("depth")||"0"),U=w.searchParams.get("select")?.split(",")||void 0,j=w.searchParams.get("draft"),$=j==="true"?!0:j==="false"?!1:!!i,D={},_=w.searchParams.get("where");if(_)try{D=JSON.parse(_);}catch{return n.json({error:"Invalid JSON in where parameter"},400)}let F=await t.find({collection:o,where:D,sort:v,limit:S,page:T,depth:x,tenantId:p,select:U,draft:$});return await a$4(F.docs,r.fields,t,e,1,x),n.json(a$5(F))}catch(i){return console.error("[API] list error:",i),n.json({error:i.message},500)}}),h.get(`${m}/:id/versions`,async n=>{try{let{user:i,tenantId:p,apiKeyContext:A}=await P(n.req.raw,E,l,u),g=await N(r,"read",n.req.raw,i,p,A,R,q);if(!g.allowed)return n.json({error:g.error},g.status||403);let w=n.req.param("id");if(!w)return n.json({error:"Missing document ID"},400);let T=new URL(n.req.url),S=T.searchParams.get("compareA"),v=T.searchParams.get("compareB");if(Ge(L,A,`${m}/${w}/versions`,"GET",n.req.raw),S&&v){let[$,D]=await Promise.all([t.findVersionByID({collection:o,versionId:S,tenantId:p}),t.findVersionByID({collection:o,versionId:v,tenantId:p})]);if(!$||!D)return n.json({error:"Version not found"},404);let _=b($.data,D.data);return n.json({diffs:_})}let x=parseInt(T.searchParams.get("page")||"1"),U=Math.min(parseInt(T.searchParams.get("limit")||"10"),100),j=await t.findVersions({collection:o,documentId:w,page:x,limit:U,tenantId:p});return n.json(j)}catch(i){return console.error("[API] versions error:",i),n.json({error:i.message},500)}}),h.put(`${m}/:id/draft`,async n=>{try{let{user:i,tenantId:p,apiKeyContext:A}=await P(n.req.raw,E,l,u),g=await N(r,"update",n.req.raw,i,p,A,R,q);if(!g.allowed)return n.json({error:g.error},g.status||403);let w=n.req.param("id"),T=await n.req.json(),S=Ye(T),v=await t.findByID({collection:o,id:w,tenantId:p,draft:!0});if(!v)return n.json({error:"Document not found"},404);let x;T.delta?x={...v,...T.delta}:x=T.data??St(T);let U=await t.updateLatestVersion({collection:o,documentId:w,data:x,status:"draft",tenantId:p});return i&&L?.createAuditLog({action:"document_update",userId:i.id,resource:o,resourceId:w,success:!0,metadata:{type:"draft_save"}}),n.json({data:U,message:"Draft saved successfully"})}catch(i){return n.json({error:i.message},500)}}),h.delete(`${m}/:id/draft`,async n=>{try{let{user:i,tenantId:p,apiKeyContext:A}=await P(n.req.raw,E,l,u),g=await N(r,"update",n.req.raw,i,p,A,R,q);return g.allowed?(i&&L?.createAuditLog({action:"document_update",userId:i.id,resource:o,resourceId:n.req.param("id"),success:!0,metadata:{type:"draft_discard"}}),n.json({message:"Draft discarded successfully"})):n.json({error:g.error},g.status||403)}catch(i){return n.json({error:i.message},500)}}),h.get(`${m}/:id`,async n=>{try{let{user:i,tenantId:p,apiKeyContext:A}=await P(n.req.raw,E,l,u),g=new URL(n.req.url),w=g.searchParams.get("draft"),T=g.searchParams.get("kyroToken"),S=!1;if(w==="true"&&T&&s)try{let D=await verify(T,s,"HS256");D&&D.type==="preview"&&D.collection===r.slug&&(S=!0);}catch(D){console.warn("Invalid preview token",D);}if(!S){let D=await N(r,"read",n.req.raw,i,p,A,R,q);if(!D.allowed)return n.json({error:D.error},D.status||403)}let v=n.req.param("id"),x=parseInt(g.searchParams.get("depth")||"0"),U=g.searchParams.get("select")?.split(",")||void 0,j=w==="true"?!0:w==="false"?!1:!!i,$=await t.findByID({collection:o,id:v,depth:x,tenantId:p,select:U,draft:j});return !$&&r.fields.some(D=>D.name==="slug")&&($=await t.findOne({collection:o,where:{slug:v},tenantId:p,draft:j})),$?(await a$4([$],r.fields,t,e,1,x),n.json({data:a$5($)})):n.json({error:"Document not found"},404)}catch(i){return n.json({error:i.message},500)}}),h.post(`${m}/preview-url`,async n=>{try{let{user:i,tenantId:p}=await P(n.req.raw,E,l,u),A=await N(r,"read",n.req.raw,i,p);if(!A.allowed)return n.json({error:A.error||"Forbidden"},A.status||403);let g=await n.req.json().catch(()=>({})),w="";s&&(w=await sign({type:"preview",collection:r.slug,id:g.id,exp:Math.floor(Date.now()/1e3)+3600},s,"HS256"));let T="";if(r.admin?.preview){T=await r.admin.preview(g,{req:n.req.raw,token:w});try{let S=new URL(T,"http://localhost");S.searchParams.has("preview")||S.searchParams.set("preview","true"),!S.searchParams.has("kyroToken")&&w&&S.searchParams.set("kyroToken",w),T=T.startsWith("http")?S.toString():`${S.pathname}${S.search}`;}catch{}}else {let S="";try{let x=await t.findOne({collection:"_globals_site-settings",where:{}});x?.siteUrl&&(S=x.siteUrl);}catch{}if(!S)return n.json({error:"No site URL configured in settings, and no custom preview function defined for this collection."},400);S=S.replace(/\/$/,"");let v=g.slug||g.id||"";T=`${S}/${r.slug}/${v}?preview=true&kyroToken=${w}`;}return n.json({url:T})}catch(i){return n.json({error:i.message},500)}}),h.post(m,async n=>{try{let{user:i,tenantId:p,apiKeyContext:A}=await P(n.req.raw,E,l,u),g=await N(r,"create",n.req.raw,i,p,A,R,q);if(!g.allowed)return n.json({error:g.error},g.status||403);p&&t.setTenantContext({tenantId:p,userId:i?.id??"",role:i?.role,isSuperAdmin:i?.role==="super_admin"}),Ge(L,A,m,"POST",n.req.raw);let T=await n.req.json();ye(T,r.fields),we(r.fields,T);let S=n.req.raw;if(r.hooks?.beforeValidate)for(let D of r.hooks.beforeValidate){let _=await D({collection:o,data:T,req:S,user:i,tenantId:p,operation:"create"});_&&typeof _=="object"&&!Array.isArray(_)&&Object.assign(T,_);}let v=e.getCreateZodSchema(o);try{T=v.parse(T);}catch(D){return n.json({error:`Validation failed: ${Xe(D.errors)}`,details:D.errors},400)}r.tenantScoped&&p&&(T.tenantId=p);let x=r.versions?.drafts===!0,U=r.fields.find(D=>D.name==="status"),j=U?.type==="select"&&Array.isArray(U.options)&&U.options.some(D=>D.value==="published");if(x?T.status="draft":j&&!T.status&&(T.status="published"),r.hooks?.beforeChange)for(let D of r.hooks.beforeChange){let _=await D({collection:o,data:T,req:S,user:i,tenantId:p,operation:"create"});_&&typeof _=="object"&&!Array.isArray(_)&&Object.assign(T,_);}let $=await t.create({collection:o,data:T,tenantId:p});if(x&&await t.createVersion({collection:o,documentId:$.id,data:T,status:"draft",createdBy:i?.id,changeDescription:"Created",tenantId:p}),r.hooks?.afterChange)for(let D of r.hooks.afterChange)await D({collection:o,doc:$,data:T,req:S,user:i,tenantId:p,operation:"create"});return y&&y.trigger(ke(o,"create"),{collection:o,operation:"create",data:$,user:i?{id:i.id,email:i.email,role:i.role}:void 0,tenantId:p}).catch(D=>console.error("[Webhook] Failed to trigger:",D)),i&&L?.createAuditLog({action:"document_create",userId:i.id,resource:o,resourceId:$.id,success:!0}),n.json({data:$,message:"Created successfully"},201)}catch(i){return i.name==="ZodError"?n.json({error:`Validation failed: ${Xe(i.errors)}`,details:i.errors},400):n.json({error:i.message},500)}}),h.patch(`${m}/:id`,async n=>{try{let{user:i,tenantId:p,apiKeyContext:A}=await P(n.req.raw,E,l,u),g=await N(r,"update",n.req.raw,i,p,A,R,q);if(!g.allowed)return n.json({error:g.error},g.status||403);let w=n.req.param("id"),T=await n.req.json(),S=Ye(T),v=await t.findByID({collection:o,id:w,tenantId:p,draft:!0});if(!v)return n.json({error:"Document not found"},404);if(S&&v.updatedAt&&S!==v.updatedAt)return n.json(Tt(S,v),409);let x=Object.fromEntries(Object.entries(St(T)).filter(([Y,M])=>M!=="null"&&M!==void 0));ye(x,r.fields),we(r.fields,x);let U=n.req.raw;if(r.hooks?.beforeValidate)for(let Y of r.hooks.beforeValidate){let M=await Y({collection:o,data:x,originalDoc:v,req:U,user:i,tenantId:p,operation:"update"});M&&typeof M=="object"&&!Array.isArray(M)&&Object.assign(x,M);}if(x=e.getUpdateZodSchema(o).parse(x),r.hooks?.beforeChange)for(let Y of r.hooks.beforeChange){let M=await Y({collection:o,data:x,originalDoc:v,req:U,user:i,tenantId:p,operation:"update"});M&&typeof M=="object"&&!Array.isArray(M)&&Object.assign(x,M);}let $=n.req.header("X-Draft")==="true",D=r.versions?.drafts===!0,_=n.req.query("autosave")==="true",F;if(D&&$?await t.createVersion({collection:o,documentId:w,data:x,status:"draft",autosave:_,createdBy:i?.id,changeDescription:_?"Autosave":"Draft saved",tenantId:p}):D?(await t.update({collection:o,id:w,data:{...x,status:"published"},tenantId:p}),await t.createVersion({collection:o,documentId:w,data:x,status:"published",createdBy:i?.id,changeDescription:"Published",tenantId:p})):await t.update({collection:o,id:w,data:x,tenantId:p}),F=await t.findByID({collection:o,id:w,tenantId:p,draft:!0}),r.hooks?.afterChange)for(let Y of r.hooks.afterChange)await Y({collection:o,doc:F,data:x,originalDoc:v,req:U,user:i,tenantId:p,operation:"update"});return y&&!_&&y.trigger(ke(o,"update"),{collection:o,operation:"update",data:F,previousData:v,user:i?{id:i.id,email:i.email,role:i.role}:void 0,tenantId:p}).catch(Y=>console.error("[Webhook] Failed to trigger:",Y)),Ge(L,A,`${m}/${w}`,"PATCH",n.req.raw),i&&L?.createAuditLog({action:"document_update",userId:i.id,resource:o,resourceId:w,success:!0}),n.json({data:F,message:D?"Draft saved":"Updated successfully"})}catch(i){return i.name==="ZodError"?(console.error(`[PATCH ${m}/:id] Validation failed:`,i.errors),n.json({error:`Validation failed: ${Xe(i.errors)}`,details:i.errors},400)):(console.error(`[PATCH ${m}/:id] ERROR:`,i.message,"CAUSE:",i.cause?.message||i.cause,"QUERY:",i.query),n.json({error:i.message},500))}}),h.delete(`${m}/:id`,async n=>{try{let{user:i,tenantId:p,apiKeyContext:A}=await P(n.req.raw,E,l,u),g=await N(r,"delete",n.req.raw,i,p,A,R,q);if(!g.allowed)return n.json({error:g.error},g.status||403);p&&t.setTenantContext({tenantId:p,userId:i?.id??"",role:i?.role,isSuperAdmin:i?.role==="super_admin"});let w=n.req.param("id"),T=n.req.raw,S=await t.findByID({collection:o,id:w,tenantId:p,draft:!0});if(!S)return n.json({error:"Document not found"},404);if(r.hooks?.beforeDelete)for(let x of r.hooks.beforeDelete)await x({collection:o,doc:S,req:T,user:i,tenantId:p,operation:"delete"});let v=await t.delete({collection:o,id:w,tenantId:p});if(r.hooks?.afterDelete)for(let x of r.hooks.afterDelete)await x({collection:o,doc:v,originalDoc:S,req:T,user:i,tenantId:p,operation:"delete"});return y&&y.trigger(ke(o,"delete"),{collection:o,operation:"delete",data:v,previousData:S,user:i?{id:i.id,email:i.email,role:i.role}:void 0,tenantId:p}).catch(x=>console.error("[Webhook] Failed to trigger:",x)),Ge(L,A,`${m}/${w}`,"DELETE",n.req.raw),i&&L?.createAuditLog({action:"document_delete",userId:i.id,resource:o,resourceId:w,success:!0}),n.json({data:v,message:"Deleted successfully"})}catch(i){return console.error(`[DELETE] Error deleting ${o}:`,i),n.json({error:i.message||String(i)},500)}}),h.post(`${m}/:id/duplicate`,async n=>{try{let{user:i,tenantId:p,apiKeyContext:A}=await P(n.req.raw,E,l,u),g=await N(r,"create",n.req.raw,i,p,A,R,q);if(!g.allowed)return n.json({error:g.error},g.status||403);let w=n.req.param("id"),T=await t.findByID({collection:o,id:w,tenantId:p,draft:!0});if(!T)return n.json({error:"Document not found"},404);let{id:S,createdAt:v,updatedAt:x,...U}=T;De(r.fields,U);let j=Date.now().toString(36);"slug"in U&&typeof U.slug=="string"&&(U.slug=`${U.slug||"document"}-copy-${j}`),"title"in U&&typeof U.title=="string"?U.title=`${U.title||"Copy"} (Copy)`:"name"in U&&typeof U.name=="string"&&(U.name=`${U.name||"Copy"} (Copy)`);let $=await t.create({collection:o,data:{...U,status:"draft"},tenantId:p});return n.json({data:$,message:"Document duplicated successfully"})}catch(i){return console.error("[Duplicate] Error:",i),n.json({error:i.message||String(i)},500)}}),h.post(`${m}/:id/versions/:versionId/restore`,async n=>{try{let{user:i,tenantId:p,apiKeyContext:A}=await P(n.req.raw,E,l,u),g=await N(r,"update",n.req.raw,i,p,A,R,q);if(!g.allowed)return n.json({error:g.error},g.status||403);let w=n.req.param("id"),T=n.req.param("versionId"),S=await t.findVersionByID({collection:o,versionId:T,tenantId:p});if(!S)return n.json({error:"Version not found"},404);let v=await t.update({collection:o,id:w,data:{...S.data,status:"draft"},tenantId:p});return n.json({data:v,message:"Version restored successfully"})}catch(i){return n.json({error:i.message},500)}}),h.post(`${m}/:id/versions`,async n=>{try{let{user:i,tenantId:p,apiKeyContext:A}=await P(n.req.raw,E,l,u),g=await N(r,"update",n.req.raw,i,p,A,R,q);if(!g.allowed)return n.json({error:g.error},g.status||403);let w=await n.req.json(),{versionId:T,action:S}=w;if(S==="restore"&&T){let v=await t.findVersionByID({collection:o,versionId:T,tenantId:p});if(!v)return n.json({error:"Version not found"},404);let x=await t.update({collection:o,id:n.req.param("id"),data:{...v.data,status:"draft"},tenantId:p});return n.json({data:x,message:"Version restored successfully"})}return n.json({error:"Invalid action"},400)}catch(i){return n.json({error:i.message},500)}}),h.post(`${m}/:id/publish`,async n=>{try{let{user:i,tenantId:p,apiKeyContext:A}=await P(n.req.raw,E,l,u),g=await N(r,"update",n.req.raw,i,p,A,R,q);if(!g.allowed)return n.json({error:g.error},g.status||403);p&&t.setTenantContext({tenantId:p,userId:i?.id??"",role:i?.role,isSuperAdmin:i?.role==="super_admin"});let w=n.req.param("id"),T=await n.req.json().catch(()=>({})),S=Ye(T),v=await t.findByID({collection:o,id:w,tenantId:p,draft:!0});if(!v)return n.json({error:"Document not found"},404);if(S&&v.updatedAt&&S!==v.updatedAt)return n.json(Tt(S,v),409);let x={status:"published"},U=v;if(r.versions?.drafts){let $=await t.findVersions({collection:o,documentId:w,limit:1,sort:"-createdAt",tenantId:p});if($.docs.length>0){let D=$.docs[0];U={...v,...D.data},x={...D.data,...x};}}let j=await t.update({collection:o,id:w,data:x,tenantId:p});return r.versions?.drafts&&await t.createVersion({collection:o,documentId:w,data:{...U,status:"published"},status:"published",createdBy:i?.id,changeDescription:"Published",tenantId:p}),y&&y.trigger(ke(o,"update"),{collection:o,operation:"update",data:j,user:i?{id:i.id,email:i.email,role:i.role}:void 0,tenantId:p}).catch($=>console.error("[Webhook] Failed to trigger:",$)),n.json({data:j,message:"Published successfully"})}catch(i){return n.json({error:i.message},500)}}),h.post(`${m}/:id/unpublish`,async n=>{try{let{user:i,tenantId:p,apiKeyContext:A}=await P(n.req.raw,E,l,u),g=await N(r,"update",n.req.raw,i,p,A,R,q);if(!g.allowed)return n.json({error:g.error},g.status||403);let w=n.req.param("id");if(!await t.findByID({collection:o,id:w,tenantId:p,draft:!0}))return n.json({error:"Document not found"},404);let S=await t.update({collection:o,id:w,data:{status:"draft"},tenantId:p});return y&&y.trigger(ke(o,"update"),{collection:o,operation:"update",data:S,user:i?{id:i.id,email:i.email,role:i.role}:void 0,tenantId:p}).catch(v=>console.error("[Webhook] Failed to trigger:",v)),n.json({data:S,message:"Unpublished successfully"})}catch(i){return n.json({error:i.message},500)}});}for(let r of e.getGlobals()){let o=r.slug,m=`/api/globals/${o}`;h.post(`${m}/dynamic-options/:fieldName`,async n=>{try{let{user:i,tenantId:p}=await P(n.req.raw,E,l,u),A=await J(r,"read",n.req.raw,i,p,R);if(!A.allowed)return n.json({error:A.error},A.status||403);let g=n.req.param("fieldName"),w=await n.req.json(),{data:T,siblingData:S}=w,v=ge(r.fields,g);if(!v)return n.json({error:"Field not found"},404);if(v.type!=="select")return n.json({error:"Field is not a select field"},400);let x=[];return typeof v.options=="function"?x=await v.options({data:T||{},siblingData:S||{}}):Array.isArray(v.options)&&(x=v.options),n.json({options:x})}catch(i){return n.json({error:i.message},500)}}),h.get(m,async n=>{try{let{user:i,tenantId:p}=await P(n.req.raw,E,l,u),A=new URL(n.req.url),g=A.searchParams.get("kyroToken"),w=A.searchParams.get("draft"),T=!1;if(w==="true"&&g&&s)try{let j=await verify(g,s,"HS256");j&&j.type==="preview"&&j.collection===`_globals_${r.slug}`&&(T=!0);}catch(j){console.warn("Invalid preview token",j);}if(!T){let j=await J(r,"read",n.req.raw,i,p,R);if(!j.allowed)return n.json({error:j.error},j.status||403)}let S=w==="true"?!0:w==="false"?!1:!!i,v=parseInt(A.searchParams.get("depth")||"0"),U=(await t.find({collection:`_globals_${o}`,where:{},tenantId:p,draft:S,depth:v,limit:1})).docs[0];if(U&&v>0&&await a$4([U],r.fields,t,e,1,v),o==="system"){let j=yr.randomBytes(32).toString("hex");U?U.appSecret||(await t.update({collection:`_globals_${o}`,id:o,data:{appSecret:j},tenantId:p}),U.appSecret=j):U=await t.create({collection:`_globals_${o}`,data:{id:o,appSecret:j},tenantId:p});}return n.json({data:U||{}})}catch(i){return n.json({error:i.message},500)}});let b=async n=>{try{let{user:i,tenantId:p}=await P(n.req.raw,E,l,u),A=await J(r,"update",n.req.raw,i,p,R);if(!A.allowed)return n.json({error:A.error},A.status||403);let g=new URL(n.req.url),w=parseInt(g.searchParams.get("depth")||"0"),T=await n.req.json(),S=Ye(T),v=St(T),x=Object.fromEntries(Object.entries(v).filter(([H,Ae])=>Ae!==null&&Ae!=="null"&&Ae!==void 0));ye(x,r.fields),we(r.fields,x);let U=e.getUpdateZodSchema(o),j;try{j=U.parse(x);}catch(H){return n.json({error:`Validation failed: ${Xe(H.errors)}`,details:H.errors},400)}let $=new Set(["id","createdAt","updatedAt","status","baseUpdatedAt","_baseUpdatedAt"]),D=Object.fromEntries(Object.entries(j).filter(([H])=>!$.has(H))),_=`_globals_${o}`,F=await t.findOne({collection:_,where:{},tenantId:p,draft:!0});if(F&&S&&F.updatedAt&&S!==F.updatedAt)return n.json(Tt(S,F),409);let Y=n.req.header("X-Draft")==="true",M=r.versions?.drafts===!0,oe=n.req.query("autosave")==="true",W;if(M&&Y)await t.createVersion({collection:_,documentId:o,data:D,status:"draft",autosave:oe,createdBy:i?.id,changeDescription:oe?"Autosave":"Manual save",tenantId:p}),F?W=F:W=await t.create({collection:_,data:{...D,id:o,status:"draft"},tenantId:p});else if(M&&!Y){let H="published";F?W=await t.update({collection:_,id:o,data:{...D,status:H},tenantId:p}):W=await t.create({collection:_,data:{...D,id:o,status:H},tenantId:p}),await t.createVersion({collection:_,documentId:o,data:D,status:H,autosave:!1,createdBy:i?.id,changeDescription:"Published",tenantId:p});}else F?W=await t.update({collection:_,id:o,data:D,tenantId:p}):W=await t.create({collection:_,data:{...D,id:o},tenantId:p});if(o==="storage-settings"&&(G=null,ae=null),o==="email-settings"){let H=await k.fromConfig(t);O.email=H||void 0;}return o==="system"&&await Ft(),i&&L?.createAuditLog({action:"settings_change",userId:i.id,resource:`global:${o}`,resourceId:o,success:!0}),W&&w>0&&await a$4([W],r.fields,t,e,1,w),n.json({data:W,message:"Updated successfully"})}catch(i){return console.error(`[API] Save global "${o}" failed:`,i),n.json({error:i.message||"Save failed",stack:process.env.NODE_ENV==="development"?i.stack:void 0},500)}};h.post(m,b),h.patch(m,b),h.post(`${m}/preview-url`,async n=>{try{let{user:i,tenantId:p}=await P(n.req.raw,E,l,u),A=await J(r,"read",n.req.raw,i,p);if(!A.allowed)return n.json({error:A.error||"Forbidden"},A.status||403);let g=await n.req.json().catch(()=>({})),w="";s&&(w=await sign({type:"preview",collection:`_globals_${r.slug}`,exp:Math.floor(Date.now()/1e3)+3600},s,"HS256"));let T="";if(r.admin?.preview)T=await r.admin.preview(g,{req:n.req.raw,token:w});else {let S="";try{let v=await t.findOne({collection:"_globals_site-settings",where:{}});v?.siteUrl&&(S=v.siteUrl);}catch{}if(!S)return n.json({error:"No site URL configured in settings, and no custom preview function defined."},400);S=S.replace(/\/$/,""),T=`${S}/?preview=true&kyroToken=${w}`;}return n.json({url:T})}catch(i){return n.json({error:i.message},500)}}),h.post(`${m}/publish`,async n=>{try{let{user:i,tenantId:p}=await P(n.req.raw,E,l,u),A=await J(r,"update",n.req.raw,i,p,R);if(!A.allowed)return n.json({error:A.error},403);let g=`_globals_${o}`,w=await t.findOne({collection:g,where:{},tenantId:p,draft:!0});if(!w)return n.json({error:"Global not found"},404);let T={status:"published"},S=w;if(r.versions?.drafts){let x=await t.findVersions({collection:g,documentId:o,limit:1,sort:"-createdAt",tenantId:p});x.docs.length>0&&(S={...w,...x.docs[0].data},T={...x.docs[0].data,...T});}let v=await t.update({collection:g,id:o,data:T,tenantId:p});return r.versions?.drafts&&await t.createVersion({collection:g,documentId:o,data:{...S,status:"published"},status:"published",createdBy:i?.id,changeDescription:"Published",tenantId:p}),n.json({data:v,message:"Published successfully"})}catch(i){return n.json({error:i.message},500)}}),h.post(`${m}/unpublish`,async n=>{try{let{user:i,tenantId:p}=await P(n.req.raw,E,l,u),A=await J(r,"update",n.req.raw,i,p,R);if(!A.allowed)return n.json({error:A.error},403);let g=await t.update({collection:`_globals_${o}`,id:o,data:{status:"draft"},tenantId:p});return n.json({data:g,message:"Unpublished successfully"})}catch(i){return n.json({error:i.message},500)}}),h.get(`${m}/versions`,async n=>{try{let{user:i,tenantId:p}=await P(n.req.raw,E,l,u),A=await J(r,"read",n.req.raw,i,p,R);if(!A.allowed)return n.json({error:A.error},403);let g=parseInt(n.req.query("limit")||"10"),w=parseInt(n.req.query("page")||"1"),T=await t.findVersions({collection:`_globals_${o}`,documentId:o,limit:g,page:w,tenantId:p});return n.json(T)}catch(i){return n.json({error:i.message},500)}}),h.get(`${m}/versions/:versionId`,async n=>{try{let i=n.req.param("versionId"),{user:p,tenantId:A}=await P(n.req.raw,E,l,u),g=await J(r,"read",n.req.raw,p,A,R);if(!g.allowed)return n.json({error:g.error},403);let w=await t.findVersionByID({collection:`_globals_${o}`,versionId:i,tenantId:A});return w?n.json({data:w}):n.json({error:"Version not found"},404)}catch(i){return n.json({error:i.message},500)}}),h.post(`${m}/versions/:versionId/restore`,async n=>{try{let i=n.req.param("versionId"),{user:p,tenantId:A}=await P(n.req.raw,E,l,u),g=await J(r,"update",n.req.raw,p,A,R);if(!g.allowed)return n.json({error:g.error},403);let w=`_globals_${o}`,T=await t.findVersionByID({collection:w,versionId:i,tenantId:A});if(!T)return n.json({error:"Version not found"},404);let S=await t.update({collection:w,id:o,data:{...T.data,status:"draft"},tenantId:A});return n.json({data:S,message:"Version restored successfully"})}catch(i){return n.json({error:i.message},500)}}),o==="email-settings"&&h.post(`${m}/test`,async n=>{try{let{user:i,tenantId:p}=await P(n.req.raw,E,l,u),A=await J(r,"update",n.req.raw,i,p,R);if(!A.allowed)return n.json({error:A.error},A.status||403);let g=await n.req.json(),w={provider:g.provider,from:g.fromEmail||g.from,fromName:g.fromName,replyTo:g.replyTo,smtp:g.smtp?{host:g.smtp.host,port:g.smtp.port,secure:g.smtp.secure,auth:{user:g.smtp.username||g.smtp.user,pass:g.smtp.password||g.smtp.pass}}:void 0,resend:g.resend,sendgrid:g.sendgrid,mailgun:g.mailgun,ses:g.ses},T=new k(w),S=g.email||g.testEmail||g.testEmailSection&&g.testEmailSection.testEmail;if(!S)return n.json({error:"No test recipient email provided"},400);let v=g.provider?g.provider.charAt(0).toUpperCase()+g.provider.slice(1):"SMTP",x=g.fromName?`${g.fromName} <${g.fromEmail||g.from||"default"}>`:g.fromEmail||g.from||"Configured Sender",U=new Date().toUTCString();return await T.send({to:S,subject:"Kyro CMS \u2014 Email Connection Test",html:`<!DOCTYPE html>
107
107
  <html lang="en">
108
108
  <head>