@kyro-cms/core 0.12.60 → 0.12.62

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (77) hide show
  1. package/dist/api-handler-graphql.cjs +1 -1
  2. package/dist/api-handler-graphql.js +1 -1
  3. package/dist/api-handler-trpc.cjs +1 -1
  4. package/dist/api-handler-trpc.js +1 -1
  5. package/dist/api-handler.cjs +1 -1
  6. package/dist/api-handler.js +1 -1
  7. package/dist/{bootstrap-VUWX45QN.js → bootstrap-WB6FDH2T.js} +1 -1
  8. package/dist/bootstrap-XDT4MRML.cjs +1 -0
  9. package/dist/{chunk-33E4YN62.js → chunk-26MOA3HJ.js} +10 -10
  10. package/dist/{chunk-M56F4LQ5.cjs → chunk-3XLXKGEU.cjs} +1 -1
  11. package/dist/{chunk-WQCLLM4S.cjs → chunk-4FHWIGHO.cjs} +10 -10
  12. package/dist/chunk-4ZWLNGLS.js +2 -0
  13. package/dist/{chunk-VOQUO2EZ.cjs → chunk-5DWQGEM2.cjs} +22 -22
  14. package/dist/{chunk-OXGJOYEO.js → chunk-637PTUHF.js} +1 -1
  15. package/dist/chunk-6QWX3DEB.cjs +120 -0
  16. package/dist/{chunk-ZMG7Z3KF.js → chunk-75BFTYBS.js} +23 -23
  17. package/dist/{chunk-YZEMLLD2.js → chunk-AWQGDMOE.js} +3 -3
  18. package/dist/chunk-D6SDGHY6.js +2 -0
  19. package/dist/{chunk-MP5VC5ER.cjs → chunk-FP5UK272.cjs} +1 -1
  20. package/dist/{chunk-AK754S3T.cjs → chunk-FSL3NLRT.cjs} +2 -2
  21. package/dist/{chunk-RTHJ6SS5.js → chunk-GQGFNTDZ.js} +1 -1
  22. package/dist/chunk-HKYBQYAJ.cjs +19 -0
  23. package/dist/{chunk-TDGSIF5H.cjs → chunk-JU3UAZRY.cjs} +10 -11
  24. package/dist/chunk-KMFLHGD5.cjs +1 -0
  25. package/dist/{chunk-NTKIONEC.cjs → chunk-LOP464VR.cjs} +1 -1
  26. package/dist/{chunk-R25WLKX4.js → chunk-N6MNQIQU.js} +101 -101
  27. package/dist/{chunk-BHR7OAU4.cjs → chunk-OPTVCCQQ.cjs} +101 -101
  28. package/dist/chunk-RDFGJHEG.js +2 -0
  29. package/dist/chunk-RILJCH6H.js +121 -0
  30. package/dist/{chunk-KCHPADCH.cjs → chunk-SOCBJPYB.cjs} +1 -1
  31. package/dist/chunk-T4JJVUGT.js +20 -0
  32. package/dist/{chunk-7N6TW4JB.js → chunk-TBTQXIHP.js} +1 -1
  33. package/dist/{chunk-KNOFTUQV.js → chunk-VJODUKKM.js} +11 -12
  34. package/dist/{chunk-DUO523BH.cjs → chunk-ZHA446FA.cjs} +1 -1
  35. package/dist/cli/index.cjs +1 -1
  36. package/dist/cli/index.js +1 -1
  37. package/dist/client.cjs +1 -1
  38. package/dist/client.js +1 -1
  39. package/dist/drizzle/index.cjs +1 -1
  40. package/dist/drizzle/index.d.cts +2 -1
  41. package/dist/drizzle/index.d.ts +2 -1
  42. package/dist/drizzle/index.js +1 -1
  43. package/dist/fields/index.cjs +1 -1
  44. package/dist/fields/index.js +1 -1
  45. package/dist/graphql/index.cjs +1 -1
  46. package/dist/graphql/index.d.cts +2 -0
  47. package/dist/graphql/index.d.ts +2 -0
  48. package/dist/graphql/index.js +1 -1
  49. package/dist/index.cjs +3 -3
  50. package/dist/index.d.cts +1 -1
  51. package/dist/index.d.ts +1 -1
  52. package/dist/index.js +5 -5
  53. package/dist/{local-2IFOTHAA.js → local-4MZ7KOL3.js} +1 -1
  54. package/dist/{local-UESCNPQP.cjs → local-NDTKWJQ6.cjs} +1 -1
  55. package/dist/postgres-auth-adapter-SK3N3OSS.js +1 -1
  56. package/dist/postgres-auth-adapter-ZO6HK5AK.cjs +1 -1
  57. package/dist/postgres-js-GXZX3AGZ.cjs +1 -0
  58. package/dist/{postgres-js-4CI7FMYS.js → postgres-js-WE3NBRFO.js} +1 -1
  59. package/dist/rest/index.cjs +1 -1
  60. package/dist/rest/index.d.cts +3 -3
  61. package/dist/rest/index.d.ts +3 -3
  62. package/dist/rest/index.js +1 -1
  63. package/dist/{sqlite-adapter-4TPNROJK.js → sqlite-adapter-52PL52VU.js} +1 -1
  64. package/dist/{sqlite-adapter-ZTABLT2X.cjs → sqlite-adapter-MNNZZXGX.cjs} +1 -1
  65. package/dist/trpc/index.cjs +1 -1
  66. package/dist/trpc/index.js +1 -1
  67. package/package.json +2 -2
  68. package/dist/bootstrap-JF6Q4L6P.cjs +0 -1
  69. package/dist/chunk-5LPNEYK5.cjs +0 -1
  70. package/dist/chunk-72VOOMJI.js +0 -20
  71. package/dist/chunk-AO2IXWV4.js +0 -2
  72. package/dist/chunk-OUMUIICN.cjs +0 -264
  73. package/dist/chunk-PA4ZZREG.js +0 -2
  74. package/dist/chunk-PCVQNVSU.cjs +0 -19
  75. package/dist/chunk-SQBTIMWF.js +0 -2
  76. package/dist/chunk-T4TSELDS.js +0 -265
  77. package/dist/postgres-js-3Y54EXVQ.cjs +0 -1
@@ -1,3 +1,3 @@
1
- import {a as a$1,h}from'./chunk-RTHJ6SS5.js';import {a}from'./chunk-VVVCCB6R.js';import {a as a$2}from'./chunk-TBHNE4VV.js';import {g}from'./chunk-Y2YAKDEQ.js';import {createHmac,randomBytes,randomUUID}from'crypto';if (typeof window === "undefined") { const { createRequire } = await import(/* @vite-ignore */ 'module'); createRequire(import.meta.url); }
2
- g();var _={COLLECTION_CREATE:"collection.create",COLLECTION_UPDATE:"collection.update",COLLECTION_DELETE:"collection.delete",MEDIA_UPLOAD:"media.upload",MEDIA_DELETE:"media.delete",AUTH_LOGIN:"auth.login",AUTH_REGISTER:"auth.register",AUTH_LOGOUT:"auth.logout",ORDER_CREATED:"order.created",ORDER_PAID:"order.paid",ORDER_SHIPPED:"order.shipped",ORDER_DELIVERED:"order.delivered"},G=Object.values(_);var k="_webhooks",w="_webhook_deliveries";g();g();g();g();async function L(o,t,s,e={}){let r=e.timeout||3e4,i=Date.now(),u=new AbortController,c=setTimeout(()=>u.abort(),r);try{let a=await fetch(o,{method:"POST",headers:t,body:s,signal:u.signal});clearTimeout(c);let n=Date.now()-i,l;try{l=(await a.text()).slice(0,1e3);}catch{}let d={success:a.ok,status:a.status,statusText:a.statusText,body:l,duration:n};return d.success&&e.onSuccess?e.onSuccess(d):!d.success&&e.onFailure&&e.onFailure(`HTTP ${a.status}: ${a.statusText}`),d}catch(a){clearTimeout(c);let n=Date.now()-i,l=a.name==="AbortError"?`Request timed out after ${r}ms`:a.message||"Unknown error";return e.onFailure&&e.onFailure(l),{success:false,status:0,duration:n,error:l}}}async function $(o,t,s={}){let e=JSON.stringify(t),r={"Content-Type":"application/json","User-Agent":"Kyro-CMS-Webhook/1.0","X-Webhook-Event":t.event,"X-Webhook-Delivery":t.id,"X-Webhook-Timestamp":t.timestamp,...o.headers||{}};return o.secret&&(r["X-Webhook-Signature"]=P(e,o.secret)),L(o.url,r,e,s)}g();async function j(o,t,s={}){let e=o.config||{},r=process.env.GITHUB_TOKEN;if(!r)return {success:false,status:0,duration:0,error:"GITHUB_TOKEN environment variable is not set"};if(!e.githubOwner||!e.githubRepo)return {success:false,status:0,duration:0,error:"GitHub owner and repo are required"};let i=e.githubBranch||"main",u=Date.now(),c=async(a,n,l)=>{let d=await fetch(a,{method:n,headers:{"Content-Type":"application/json",Accept:"application/vnd.github+json",Authorization:`Bearer ${r}`,"X-GitHub-Api-Version":"2022-11-28","User-Agent":"Kyro-CMS-Webhook/1.0"},body:l?JSON.stringify(l):void 0});if(!d.ok){let y=await d.text();throw new Error(`GitHub API HTTP ${d.status}: ${y}`)}return d.json()};try{let a=`https://api.github.com/repos/${e.githubOwner}/${e.githubRepo}/git/refs/heads/${i}`,l=(await c(a,"GET")).object.sha,d=`https://api.github.com/repos/${e.githubOwner}/${e.githubRepo}/git/commits/${l}`,f=(await c(d,"GET")).tree.sha,p=`https://api.github.com/repos/${e.githubOwner}/${e.githubRepo}/git/commits`,b=(await c(p,"POST",{message:`Content updated via Kyro CMS (${t.event})`,tree:f,parents:[l]})).sha;return await c(a,"PATCH",{sha:b,force:!1}),{success:!0,status:201,duration:Date.now()-u,body:`Successfully pushed empty commit ${b} to branch ${i}`}}catch(a){return {success:false,status:0,duration:Date.now()-u,error:a.message||"Failed to push empty commit to GitHub"}}}var K={generic:$,"github-push":j};function S(o){return K[o||"generic"]||K.generic}function P(o,t){return `sha256=${createHmac("sha256",t).update(o).digest("hex")}`}function x(){return randomBytes(32).toString("hex")}async function U(o,t,s={}){return S(o.action)(o,t,s)}async function I(o,t,s,e={}){let r=e.maxRetries??5,i=e.retryDelay??1e3,u=null;for(let c=0;c<=r;c++){if(c>0){let a=Math.min(i*Math.pow(2,c-1),3e4);e.onRetry&&e.onRetry(c,`Retrying in ${a}ms...`),await F(a);}if(e.onRetry&&c>0&&e.onRetry(c,`Attempt ${c+1}/${r+1}`),u=await U(o,t,{...e,onRetry:void 0,onSuccess:void 0,onFailure:void 0}),u.success)return u;if(!(u.error?.includes("timed out")&&c<r)&&u.status>=400&&u.status<500)return u}return u||{success:false,status:0,duration:0,error:"All delivery attempts failed"}}function H(o,t,s,e,r,i){return {id:o,webhookId:t,event:s,payload:e,attempt:r,status:i.success?"success":"failed",responseStatus:i.status||void 0,responseBody:i.body,duration:i.duration,error:i.error,createdAt:new Date().toISOString(),deliveredAt:i.success?new Date().toISOString():void 0}}function F(o){return new Promise(t=>setTimeout(t,o))}function z(){return {id:`test_${Date.now()}`,event:"collection.create",timestamp:new Date().toISOString(),collection:"test",operation:"create",data:{message:"This is a test webhook delivery"},user:{id:"system",email:"system@kyro.dev",role:"super_admin"}}}g();function N(o){let t=new Set,s=[];for(let e of o){let r=e==="create"||e==="update"||e==="delete"?`collection.${e}`:e;t.has(r)||(t.add(r),s.push(r));}return s}var O=class{db;constructor(t){this.db=t;}async getWebhooks(t){let e=(await this.db.find({collection:k,where:t?.status?{status:{equals:t.status}}:{},limit:100,page:1,draft:true})).docs;return t?.event?e.filter(r=>r.events.includes(t.event)):e}async getWebhookById(t){return this.db.findByID({collection:k,id:t,draft:true})}async createWebhook(t){let s=new Date().toISOString(),e=t.secret||x(),r={id:randomUUID(),name:t.name,url:t.url,events:N(t.events),collections:t.collections||[],status:t.status||"active",secret:e,headers:t.headers||{},action:t.action||"generic",config:t.config||{},createdAt:s,updatedAt:s};return await this.db.create({collection:k,data:r}),r}async updateWebhook(t,s){let e=await this.getWebhookById(t);if(!e)return null;let r={...e,...s,events:s.events?N(s.events):e.events,collections:s.collections!==void 0?s.collections:e.collections,action:s.action!==void 0?s.action:e.action,config:s.config!==void 0?{...e.config,...s.config}:e.config,updatedAt:new Date().toISOString()};return s.secret===""&&"secret"in s&&delete r.secret,await this.db.update({collection:k,id:t,data:r}),r}async deleteWebhook(t){await this.db.delete({collection:k,id:t});}async trigger(t,s){let e=await this.getWebhooks({status:"active",event:t}),r=s.collection,i=e.filter(a=>!a.collections||a.collections.length===0||!r?true:a.collections.includes(r));if(i.length===0)return [];let u={id:randomUUID(),event:t,timestamp:new Date().toISOString(),...s},c=[];for(let a of i){let n=await this.triggerWebhook(a,u);c.push(n);}return c}async triggerWebhook(t,s){let e=randomUUID();try{let r=await I(t,s,e,{maxRetries:5,retryDelay:1e3}),i=H(e,t.id,t.events[0],s,1,r);try{await this.db.create({collection:w,data:i});}catch{console.warn("[WebhookService] Failed to save delivery record:",e);}return r.success?await this.updateWebhook(t.id,{lastTriggered:new Date().toISOString(),lastError:null}).catch(()=>{}):await this.updateWebhook(t.id,{lastError:r.error||`HTTP ${r.status}`}).catch(()=>{}),{deliveryId:e,webhookId:t.id,event:t.events[0],status:r.success?"success":"failed",responseStatus:r.status,duration:r.duration,error:r.error}}catch(r){return {deliveryId:e,webhookId:t.id,event:t.events[0],status:"failed",error:r.message}}}async testWebhook(t){let s=await this.getWebhookById(t);if(!s)return null;let e={id:randomUUID(),event:s.events[0]||"collection.create",timestamp:new Date().toISOString(),collection:"test",operation:"create",data:{message:"This is a test webhook delivery from Kyro CMS"},user:{id:"system",email:"system@kyro.dev",role:"super_admin"}};return this.triggerWebhook(s,e)}async getDeliveryHistory(t,s=50){return (await this.db.find({collection:w,where:{webhookId:{equals:t}},sort:"-createdAt",limit:s,page:1})).docs}async retryDelivery(t){let s=await this.db.findByID({collection:w,id:t});if(!s)return null;let e=await this.getWebhookById(s.webhookId);return e?this.triggerWebhook(e,s.payload):null}};function X(o){return new O(o)}g();g();function Y(o){if(!o)return [];if(typeof o=="string")return [{id:o}];if(Array.isArray(o))return o.map(t=>typeof t=="object"?{id:t.value??t.id??t,relationTo:t.relationTo}:{id:t});if(typeof o=="object"){let t=o.value??o.id??o;if(typeof t=="string")return [{id:t,relationTo:o.relationTo}];if(Array.isArray(t))return t.map(s=>({id:s,relationTo:o.relationTo}))}return []}function W(o,t,s){if(!(!o||typeof o!="object")){for(let e of t)if(!(!e.name&&e.type!=="row"&&e.type!=="collapsible"&&e.type!=="tabs")){if(e.type==="relationship"||e.type==="upload")s(e,o);else if(e.type==="group"||e.type==="collapsible"||e.type==="row"){let r=e.name?o[e.name]:o;W(r,e.fields||[],s);}else if(e.type==="tabs"&&e.tabs){let r=e.name?o[e.name]:o;for(let i of e.tabs)W(r,i.fields||[],s);}else if(e.type==="array"&&e.name&&Array.isArray(o[e.name]))for(let r of o[e.name])W(r,e.fields||[],s);else if(e.type==="blocks"&&e.name&&Array.isArray(o[e.name]))for(let r of o[e.name]){if(!r||typeof r!="object")continue;let i=r.type||r.blockType;if(!i)continue;let u=e.blocks?.find(c=>c.slug===i);if(u&&Array.isArray(u.fields)){let c=r.data&&typeof r.data=="object"?r.data:r;W(c,u.fields,s);}}}}}function J(o,t,s){W(o,t,(e,r)=>{let i=r[e.name];if(!i)return;let u=Array.isArray(e.relationTo)?e.relationTo:[e.relationTo],c=Y(i);for(let a of c){if(!a.id)continue;let n=a.relationTo?[a.relationTo]:u;for(let l of n)l!=="*"&&(s.has(l)||s.set(l,new Set),s.get(l).add(a.id));}});}function Q(o,t,s){W(o,t,(e,r)=>{let i=r[e.name];if(!i)return;let u=Array.isArray(e.relationTo)?e.relationTo:[e.relationTo],c=n=>{r[e.name]=n;},a=(n,l)=>{let d=l?[l]:u;for(let y of d){let f=s.get(y);if(f&&f.has(n))return f.get(n)}return null};if(typeof i=="string"){let n=a(i);c(n||{id:i});}else if(Array.isArray(i))c(i.map(n=>{let l=typeof n=="object"?n.value??n.id:n,d=typeof n=="object"?n.relationTo:void 0,y=a(l,d);return y||{id:l}}));else if(typeof i=="object"){let n=i.value??i.id,l=i.relationTo,d=a(n,l);c(d||{id:n});}});}async function Z(o,t,s,e,r=1,i=0){if(!o||o.length===0||r>i)return;let u=new Map;for(let n of o)J(n,t,u);if(u.size===0)return;let c=new Map,a$1=new Map;for(let[n,l]of u.entries()){if(l.size===0||!e.getCollection(n))continue;let y=new Map,f=Array.from(l),p=[];for(let E of f){try{let v=(await s.find({collection:n,where:{id:{in:f}},limit:f.length,draft:!0}))?.docs||[];for(let A of v)A&&A.id&&(y.set(String(A.id),A),p.push(A));}catch{for(let b of f)try{let v=await s.findByID({collection:n,id:b,draft:!0});v&&(y.set(b,v),p.push(v));}catch{}}break}c.set(n,y),p.length>0&&a$1.set(n,p);}if(r<i)for(let[n,l]of a$1.entries()){let d=e.getCollection(n);d&&await Z(l,d.fields,s,e,r+1,i);}for(let n=0;n<o.length;n++)Q(o[n],t,c),o[n]=a(o[n]);}g();function M(o){return o==="read"?"read":o==="create"?"create":o==="update"?"update":"delete"}function ee(o,t){return {none:false,read:o==="read",create:o==="read"||o==="create",update:o==="read"||o==="create"||o==="update",delete:o==="read"||o==="create"||o==="update"||o==="delete",admin:true}[t]||false}async function Le(o,t,s,e={}){let{user:r,req:i,tenantId:u,apiKey:c}=s,{enablePublicAccess:a=true,defaultAccess:n="none"}=e,l=o.access?.[t];if(l){let y=await a$1(l,{req:i,user:r,tenantId:u});return y===false?{allowed:false,error:"Access denied",status:403}:typeof y=="object"?{allowed:true,extraWhere:y}:{allowed:true}}if(c?.permissions?.length>0){let y=o.slug,f=M(t),p=`${y}:${f}`;return !h(c.permissions,p)&&!h(c.permissions,`${y}:admin`)?{allowed:false,error:"Access denied: insufficient permissions",status:403}:{allowed:true}}if(r){let y=o.slug,f=M(t),p=`${y}:${f}`,E=a$2({id:r.id,email:r.email,role:r.role},p),b=a$2({id:r.id,email:r.email,role:r.role},`${y}:admin`);return E||b?{allowed:true}:{allowed:false,error:"Access denied: missing RBAC permission",status:403}}let d=ee(t,n);return a&&d?{allowed:true}:{allowed:false,error:"Authentication required",status:401}}async function $e(o,t,s,e={}){let{user:r,req:i,tenantId:u}=s,{enablePublicAccess:c=true}=e,a=o.access?.[t];if(a)return await a$1(a,{req:i,user:r,tenantId:u})===false?{allowed:false,error:"Access denied",status:403}:{allowed:true};if(r){let n=`globals:${t}`,l=a$2({id:r.id,email:r.email,role:r.role},n),d=a$2({id:r.id,email:r.email,role:r.role},"globals:admin");return l||d?{allowed:true}:{allowed:false,error:"Access denied: missing RBAC permission",status:403}}return c?{allowed:true}:{allowed:false,error:"Authentication required",status:401}}
3
- export{Z as a,Le as b,$e as c,_ as d,G as e,k as f,w as g,P as h,x as i,U as j,I as k,H as l,z as m,O as n,X as o};
1
+ import {h,e}from'./chunk-GQGFNTDZ.js';import {a as a$1}from'./chunk-VVVCCB6R.js';import {a}from'./chunk-TBHNE4VV.js';import {g}from'./chunk-Y2YAKDEQ.js';import {createHmac,randomBytes,randomUUID}from'crypto';if (typeof window === "undefined") { const { createRequire } = await import(/* @vite-ignore */ 'module'); createRequire(import.meta.url); }
2
+ g();var _={COLLECTION_CREATE:"collection.create",COLLECTION_UPDATE:"collection.update",COLLECTION_DELETE:"collection.delete",MEDIA_UPLOAD:"media.upload",MEDIA_DELETE:"media.delete",AUTH_LOGIN:"auth.login",AUTH_REGISTER:"auth.register",AUTH_LOGOUT:"auth.logout",ORDER_CREATED:"order.created",ORDER_PAID:"order.paid",ORDER_SHIPPED:"order.shipped",ORDER_DELIVERED:"order.delivered"},G=Object.values(_);var k="_webhooks",w="_webhook_deliveries";g();g();g();g();async function L(o,t,s,e={}){let r=e.timeout||3e4,i=Date.now(),u=new AbortController,c=setTimeout(()=>u.abort(),r);try{let a=await fetch(o,{method:"POST",headers:t,body:s,signal:u.signal});clearTimeout(c);let n=Date.now()-i,l;try{l=(await a.text()).slice(0,1e3);}catch{}let d={success:a.ok,status:a.status,statusText:a.statusText,body:l,duration:n};return d.success&&e.onSuccess?e.onSuccess(d):!d.success&&e.onFailure&&e.onFailure(`HTTP ${a.status}: ${a.statusText}`),d}catch(a){clearTimeout(c);let n=Date.now()-i,l=a.name==="AbortError"?`Request timed out after ${r}ms`:a.message||"Unknown error";return e.onFailure&&e.onFailure(l),{success:false,status:0,duration:n,error:l}}}async function $(o,t,s={}){let e=JSON.stringify(t),r={"Content-Type":"application/json","User-Agent":"Kyro-CMS-Webhook/1.0","X-Webhook-Event":t.event,"X-Webhook-Delivery":t.id,"X-Webhook-Timestamp":t.timestamp,...o.headers||{}};return o.secret&&(r["X-Webhook-Signature"]=P(e,o.secret)),L(o.url,r,e,s)}g();async function j(o,t,s={}){let e=o.config||{},r=process.env.GITHUB_TOKEN;if(!r)return {success:false,status:0,duration:0,error:"GITHUB_TOKEN environment variable is not set"};if(!e.githubOwner||!e.githubRepo)return {success:false,status:0,duration:0,error:"GitHub owner and repo are required"};let i=e.githubBranch||"main",u=Date.now(),c=async(a,n,l)=>{let d=await fetch(a,{method:n,headers:{"Content-Type":"application/json",Accept:"application/vnd.github+json",Authorization:`Bearer ${r}`,"X-GitHub-Api-Version":"2022-11-28","User-Agent":"Kyro-CMS-Webhook/1.0"},body:l?JSON.stringify(l):void 0});if(!d.ok){let y=await d.text();throw new Error(`GitHub API HTTP ${d.status}: ${y}`)}return d.json()};try{let a=`https://api.github.com/repos/${e.githubOwner}/${e.githubRepo}/git/refs/heads/${i}`,l=(await c(a,"GET")).object.sha,d=`https://api.github.com/repos/${e.githubOwner}/${e.githubRepo}/git/commits/${l}`,f=(await c(d,"GET")).tree.sha,p=`https://api.github.com/repos/${e.githubOwner}/${e.githubRepo}/git/commits`,b=(await c(p,"POST",{message:`Content updated via Kyro CMS (${t.event})`,tree:f,parents:[l]})).sha;return await c(a,"PATCH",{sha:b,force:!1}),{success:!0,status:201,duration:Date.now()-u,body:`Successfully pushed empty commit ${b} to branch ${i}`}}catch(a){return {success:false,status:0,duration:Date.now()-u,error:a.message||"Failed to push empty commit to GitHub"}}}var K={generic:$,"github-push":j};function S(o){return K[o||"generic"]||K.generic}function P(o,t){return `sha256=${createHmac("sha256",t).update(o).digest("hex")}`}function x(){return randomBytes(32).toString("hex")}async function U(o,t,s={}){return S(o.action)(o,t,s)}async function I(o,t,s,e={}){let r=e.maxRetries??5,i=e.retryDelay??1e3,u=null;for(let c=0;c<=r;c++){if(c>0){let a=Math.min(i*Math.pow(2,c-1),3e4);e.onRetry&&e.onRetry(c,`Retrying in ${a}ms...`),await F(a);}if(e.onRetry&&c>0&&e.onRetry(c,`Attempt ${c+1}/${r+1}`),u=await U(o,t,{...e,onRetry:void 0,onSuccess:void 0,onFailure:void 0}),u.success)return u;if(!(u.error?.includes("timed out")&&c<r)&&u.status>=400&&u.status<500)return u}return u||{success:false,status:0,duration:0,error:"All delivery attempts failed"}}function H(o,t,s,e,r,i){return {id:o,webhookId:t,event:s,payload:e,attempt:r,status:i.success?"success":"failed",responseStatus:i.status||void 0,responseBody:i.body,duration:i.duration,error:i.error,createdAt:new Date().toISOString(),deliveredAt:i.success?new Date().toISOString():void 0}}function F(o){return new Promise(t=>setTimeout(t,o))}function z(){return {id:`test_${Date.now()}`,event:"collection.create",timestamp:new Date().toISOString(),collection:"test",operation:"create",data:{message:"This is a test webhook delivery"},user:{id:"system",email:"system@kyro.dev",role:"super_admin"}}}g();function N(o){let t=new Set,s=[];for(let e of o){let r=e==="create"||e==="update"||e==="delete"?`collection.${e}`:e;t.has(r)||(t.add(r),s.push(r));}return s}var O=class{db;constructor(t){this.db=t;}async getWebhooks(t){let e=(await this.db.find({collection:k,where:t?.status?{status:{equals:t.status}}:{},limit:100,page:1,draft:true})).docs;return t?.event?e.filter(r=>r.events.includes(t.event)):e}async getWebhookById(t){return this.db.findByID({collection:k,id:t,draft:true})}async createWebhook(t){let s=new Date().toISOString(),e=t.secret||x(),r={id:randomUUID(),name:t.name,url:t.url,events:N(t.events),collections:t.collections||[],status:t.status||"active",secret:e,headers:t.headers||{},action:t.action||"generic",config:t.config||{},createdAt:s,updatedAt:s};return await this.db.create({collection:k,data:r}),r}async updateWebhook(t,s){let e=await this.getWebhookById(t);if(!e)return null;let r={...e,...s,events:s.events?N(s.events):e.events,collections:s.collections!==void 0?s.collections:e.collections,action:s.action!==void 0?s.action:e.action,config:s.config!==void 0?{...e.config,...s.config}:e.config,updatedAt:new Date().toISOString()};return s.secret===""&&"secret"in s&&delete r.secret,await this.db.update({collection:k,id:t,data:r}),r}async deleteWebhook(t){await this.db.delete({collection:k,id:t});}async trigger(t,s){let e=await this.getWebhooks({status:"active",event:t}),r=s.collection,i=e.filter(a=>!a.collections||a.collections.length===0||!r?true:a.collections.includes(r));if(i.length===0)return [];let u={id:randomUUID(),event:t,timestamp:new Date().toISOString(),...s},c=[];for(let a of i){let n=await this.triggerWebhook(a,u);c.push(n);}return c}async triggerWebhook(t,s){let e=randomUUID();try{let r=await I(t,s,e,{maxRetries:5,retryDelay:1e3}),i=H(e,t.id,t.events[0],s,1,r);try{await this.db.create({collection:w,data:i});}catch{console.warn("[WebhookService] Failed to save delivery record:",e);}return r.success?await this.updateWebhook(t.id,{lastTriggered:new Date().toISOString(),lastError:null}).catch(()=>{}):await this.updateWebhook(t.id,{lastError:r.error||`HTTP ${r.status}`}).catch(()=>{}),{deliveryId:e,webhookId:t.id,event:t.events[0],status:r.success?"success":"failed",responseStatus:r.status,duration:r.duration,error:r.error}}catch(r){return {deliveryId:e,webhookId:t.id,event:t.events[0],status:"failed",error:r.message}}}async testWebhook(t){let s=await this.getWebhookById(t);if(!s)return null;let e={id:randomUUID(),event:s.events[0]||"collection.create",timestamp:new Date().toISOString(),collection:"test",operation:"create",data:{message:"This is a test webhook delivery from Kyro CMS"},user:{id:"system",email:"system@kyro.dev",role:"super_admin"}};return this.triggerWebhook(s,e)}async getDeliveryHistory(t,s=50){return (await this.db.find({collection:w,where:{webhookId:{equals:t}},sort:"-createdAt",limit:s,page:1})).docs}async retryDelivery(t){let s=await this.db.findByID({collection:w,id:t});if(!s)return null;let e=await this.getWebhookById(s.webhookId);return e?this.triggerWebhook(e,s.payload):null}};function X(o){return new O(o)}g();g();function M(o){return o==="read"?"read":o==="create"?"create":o==="update"?"update":"delete"}function Y(o,t){return {none:false,read:o==="read",create:o==="read"||o==="create",update:o==="read"||o==="create"||o==="update",delete:o==="read"||o==="create"||o==="update"||o==="delete",admin:true}[t]||false}async function He(o,t,s,e$1={}){let{user:r,req:i,tenantId:u,apiKey:c}=s,{enablePublicAccess:a$1=true,defaultAccess:n="none"}=e$1,l=o.access?.[t];if(l){let y=await h(l,{req:i,user:r,tenantId:u});return y===false?{allowed:false,error:"Access denied",status:403}:typeof y=="object"?{allowed:true,extraWhere:y}:{allowed:true}}if(c?.permissions?.length>0){let y=o.slug,f=M(t),p=`${y}:${f}`;return !e(c.permissions,p)&&!e(c.permissions,`${y}:admin`)?{allowed:false,error:"Access denied: insufficient permissions",status:403}:{allowed:true}}if(r){let y=o.slug,f=M(t),p=`${y}:${f}`,E=a({id:r.id,email:r.email,role:r.role},p),b=a({id:r.id,email:r.email,role:r.role},`${y}:admin`);return E||b?{allowed:true}:{allowed:false,error:"Access denied: missing RBAC permission",status:403}}let d=Y(t,n);return a$1&&d?{allowed:true}:{allowed:false,error:"Authentication required",status:401}}async function Be(o,t,s,e={}){let{user:r,req:i,tenantId:u}=s,{enablePublicAccess:c=true}=e,a$1=o.access?.[t];if(a$1)return await h(a$1,{req:i,user:r,tenantId:u})===false?{allowed:false,error:"Access denied",status:403}:{allowed:true};if(r){let n=`globals:${t}`,l=a({id:r.id,email:r.email,role:r.role},n),d=a({id:r.id,email:r.email,role:r.role},"globals:admin");return l||d?{allowed:true}:{allowed:false,error:"Access denied: missing RBAC permission",status:403}}return c?{allowed:true}:{allowed:false,error:"Authentication required",status:401}}g();function J(o){if(!o)return [];if(typeof o=="string")return [{id:o}];if(Array.isArray(o))return o.map(t=>typeof t=="object"?{id:t.value??t.id??t,relationTo:t.relationTo}:{id:t});if(typeof o=="object"){let t=o.value??o.id??o;if(typeof t=="string")return [{id:t,relationTo:o.relationTo}];if(Array.isArray(t))return t.map(s=>({id:s,relationTo:o.relationTo}))}return []}function W(o,t,s){if(!(!o||typeof o!="object")){for(let e of t)if(!(!e.name&&e.type!=="row"&&e.type!=="collapsible"&&e.type!=="tabs")){if(e.type==="relationship"||e.type==="upload")s(e,o);else if(e.type==="group"||e.type==="collapsible"||e.type==="row"){let r=e.name?o[e.name]:o;W(r,e.fields||[],s);}else if(e.type==="tabs"&&e.tabs){let r=e.name?o[e.name]:o;for(let i of e.tabs)W(r,i.fields||[],s);}else if(e.type==="array"&&e.name&&Array.isArray(o[e.name]))for(let r of o[e.name])W(r,e.fields||[],s);else if(e.type==="blocks"&&e.name&&Array.isArray(o[e.name]))for(let r of o[e.name]){if(!r||typeof r!="object")continue;let i=r.type||r.blockType;if(!i)continue;let u=e.blocks?.find(c=>c.slug===i);if(u&&Array.isArray(u.fields)){let c=r.data&&typeof r.data=="object"?r.data:r;W(c,u.fields,s);}}}}}function Q(o,t,s){W(o,t,(e,r)=>{let i=r[e.name];if(!i)return;let u=Array.isArray(e.relationTo)?e.relationTo:[e.relationTo],c=J(i);for(let a of c){if(!a.id)continue;let n=a.relationTo?[a.relationTo]:u;for(let l of n)l!=="*"&&(s.has(l)||s.set(l,new Set),s.get(l).add(a.id));}});}function Z(o,t,s){W(o,t,(e,r)=>{let i=r[e.name];if(!i)return;let u=Array.isArray(e.relationTo)?e.relationTo:[e.relationTo],c=n=>{r[e.name]=n;},a=(n,l)=>{let d=l?[l]:u;for(let y of d){let f=s.get(y);if(f&&f.has(n))return f.get(n)}return null};if(typeof i=="string"){let n=a(i);c(n||{id:i});}else if(Array.isArray(i))c(i.map(n=>{let l=typeof n=="object"?n.value??n.id:n,d=typeof n=="object"?n.relationTo:void 0,y=a(l,d);return y||{id:l}}));else if(typeof i=="object"){let n=i.value??i.id,l=i.relationTo,d=a(n,l);c(d||{id:n});}});}async function ee(o,t,s,e,r=1,i=0){if(!o||o.length===0||r>i)return;let u=new Map;for(let n of o)Q(n,t,u);if(u.size===0)return;let c=new Map,a=new Map;for(let[n,l]of u.entries()){if(l.size===0||!e.getCollection(n))continue;let y=new Map,f=Array.from(l),p=[];for(let E of f){try{let v=(await s.find({collection:n,where:{id:{in:f}},limit:f.length,draft:!0}))?.docs||[];for(let A of v)A&&A.id&&(y.set(String(A.id),A),p.push(A));}catch{for(let b of f)try{let v=await s.findByID({collection:n,id:b,draft:!0});v&&(y.set(b,v),p.push(v));}catch{}}break}c.set(n,y),p.length>0&&a.set(n,p);}if(r<i)for(let[n,l]of a.entries()){let d=e.getCollection(n);d&&await ee(l,d.fields,s,e,r+1,i);}for(let n=0;n<o.length;n++)Z(o[n],t,c),o[n]=a$1(o[n]);}
3
+ export{He as a,Be as b,_ as c,G as d,k as e,w as f,P as g,x as h,U as i,I as j,H as k,z as l,O as m,X as n,ee as o};
@@ -0,0 +1,2 @@
1
+ import {g}from'./chunk-Y2YAKDEQ.js';if (typeof window === "undefined") { const { createRequire } = await import(/* @vite-ignore */ 'module'); createRequire(import.meta.url); }
2
+ g();function i(){return {name:"seo",type:"group",label:"SEO Settings",fields:[{name:"metaTitle",type:"text",label:"Meta Title",admin:{description:"The title used for search engines (recommended < 60 chars). Leave empty for AI auto-generation."}},{name:"metaDescription",type:"textarea",label:"Meta Description",admin:{description:"A brief summary for search engines (recommended < 160 chars). Leave empty for AI auto-generation."}},{name:"keywords",type:"text",label:"Keywords",admin:{description:"Comma-separated list of keywords for this page."}},{name:"ogImage",type:"upload",label:"OpenGraph Image",relationTo:"media",admin:{description:"The image shown when the post is shared on social media (Facebook, LinkedIn)."}},{name:"twitter",type:"group",label:"Twitter Card",fields:[{name:"title",type:"text",label:"Twitter Title"},{name:"description",type:"textarea",label:"Twitter Description"},{name:"image",type:"upload",label:"Twitter Image",relationTo:"media"}]},{name:"advanced",type:"group",label:"Advanced Search Settings",fields:[{name:"noindex",type:"checkbox",label:"Hide from search engines (noindex)",defaultValue:false},{name:"nofollow",type:"checkbox",label:"Do not follow links (nofollow)",defaultValue:false},{name:"canonicalUrl",type:"text",label:"Canonical URL Override",admin:{description:"Leave empty to use the default canonical URL."}},{name:"structuredData",type:"code",label:"JSON-LD Structured Data",admin:{description:"Custom JSON-LD schema for this specific page."}}]}]}}export{i as a};
@@ -1 +1 @@
1
- 'use strict';var chunkAK754S3T_cjs=require('./chunk-AK754S3T.cjs'),chunkDUO523BH_cjs=require('./chunk-DUO523BH.cjs'),chunkZOVH6QT5_cjs=require('./chunk-ZOVH6QT5.cjs'),chunkBUNLC3II_cjs=require('./chunk-BUNLC3II.cjs');chunkBUNLC3II_cjs.h();chunkBUNLC3II_cjs.h();async function V(e){let a=chunkAK754S3T_cjs.o(e.db),t={db:e.db,registry:e.registry,req:e.req,user:e.user,tenantId:e.tenantId,webhookService:a,settings:e.settings},n=chunkDUO523BH_cjs.f(e.req);if(n){let r=await chunkDUO523BH_cjs.e(n,e.db,async o=>{try{return await e.db.findByID({collection:"users",id:o})||null}catch{return null}});r.valid&&(t.user=r.user||e.user,t.tenantId=r.tenantId||e.tenantId,t.apiKey=chunkDUO523BH_cjs.g(r));}return t}chunkBUNLC3II_cjs.h();var G={_media:{create:chunkAK754S3T_cjs.d.MEDIA_UPLOAD,update:chunkAK754S3T_cjs.d.MEDIA_UPLOAD,delete:chunkAK754S3T_cjs.d.MEDIA_DELETE}};function R(e,a){let t=G[e];return t?t[a]:`collection.${a}`}async function q(e,a,t){if(e.webhookService)try{await e.webhookService.trigger(a,{collection:t.collection,operation:t.operation,data:t.data,previousData:t.previousData,user:e.user?{id:e.user.id,email:e.user.email,role:e.user.role}:void 0,tenantId:e.tenantId});}catch(n){console.error(`[Webhook] Failed to trigger ${a}:`,n);}}function I(e,a){if(!(!e||typeof e!="object"))for(let t of a){if(t.type==="tabs"&&Array.isArray(t.tabs)){let r=t.name?e[t.name]:e;if(r&&typeof r=="object")for(let o of t.tabs)Array.isArray(o.fields)&&I(r,o.fields);continue}if(!t.name||!(t.name in e))continue;if(e[t.name]===""&&(t.type==="text"||t.type==="textarea"||t.type==="code"||t.type==="markdown"||t.type==="email"||t.type==="password"||t.type==="color"||(e[t.name]=null)),(t.type==="group"||t.type==="collapsible")&&t.name&&Array.isArray(t.fields)&&e[t.name]&&typeof e[t.name]=="object")I(e[t.name],t.fields);else if(t.type==="array"&&t.name&&Array.isArray(t.fields)&&Array.isArray(e[t.name]))for(let r of e[t.name])r&&typeof r=="object"&&I(r,t.fields);else if(t.type==="blocks"&&t.name&&Array.isArray(t.blocks)&&Array.isArray(e[t.name]))for(let r of e[t.name]){if(!r||typeof r!="object")continue;let o=r.type||r.blockType;if(!o)continue;let s=t.blocks.find(i=>i.slug===o);if(!s||!Array.isArray(s.fields))continue;let u=r.data&&typeof r.data=="object"?r.data:r;I(u,s.fields);}}}async function b(e,a,t){let n=await chunkAK754S3T_cjs.b(e,a,{user:t.user,req:t.req,tenantId:t.tenantId,apiKey:t.apiKey});if(!n.allowed)throw new Error(n.error||"Access denied");t.tenantId&&t.db.setTenantContext({tenantId:t.tenantId,userId:t.user?.id??"",role:t.user?.role,isSuperAdmin:t.user?.role==="super_admin"});}function P(e){return async a=>{let{collection:t,where:n,sort:r,limit:o,page:s,depth:u,select:i,draft:d}=a,l=e.registry.getCollection(t);if(await b(l,"read",e),l.hooks?.beforeRead)for(let p of l.hooks.beforeRead)await p({collection:t,req:e.req,user:e.user,tenantId:e.tenantId,operation:"read",where:n});let c=d??!!e.user,h=await e.db.find({collection:t,where:n||{},sort:r,limit:o||10,page:s||1,depth:u||0,tenantId:e.tenantId,select:i,draft:c});if(l.hooks?.afterRead)for(let p of h.docs)for(let k of l.hooks.afterRead)await k({collection:t,doc:p,req:e.req,user:e.user,tenantId:e.tenantId,operation:"read"});return await chunkAK754S3T_cjs.a(h.docs,l.fields,e.db,e.registry,1,u||0),chunkZOVH6QT5_cjs.a(h)}}function v(e){return async a=>{let{collection:t,id:n,depth:r,select:o,draft:s}=a,u=e.registry.getCollection(t);await b(u,"read",e);let i=s??!!e.user,d=await e.db.findByID({collection:t,id:n,depth:r||0,tenantId:e.tenantId,select:o,draft:i});if(!d)throw new Error(`Document not found: ${t}/${n}`);if(u.hooks?.afterRead)for(let l of u.hooks.afterRead)await l({collection:t,doc:d,req:e.req,user:e.user,tenantId:e.tenantId,operation:"read",id:n});return await chunkAK754S3T_cjs.a([d],u.fields,e.db,e.registry,1,r||0),chunkZOVH6QT5_cjs.a(d)}}function K(e){return async a=>{let{collection:t,data:n,depth:r,select:o}=a,s=e.registry.getCollection(t);await b(s,"create",e);let i=e.registry.getCreateZodSchema(t).parse(n);if(s.tenantScoped&&e.tenantId&&(i.tenantId=e.tenantId),s.hooks?.beforeValidate)for(let l of s.hooks.beforeValidate){let c=await l({collection:t,data:i,req:e.req,user:e.user,tenantId:e.tenantId,operation:"create"});c&&typeof c=="object"&&!Array.isArray(c)&&Object.assign(i,c);}if(s.hooks?.beforeChange)for(let l of s.hooks.beforeChange){let c=await l({collection:t,data:i,req:e.req,user:e.user,tenantId:e.tenantId,operation:"create"});c&&typeof c=="object"&&!Array.isArray(c)&&Object.assign(i,c);}let d=await e.db.create({collection:t,data:i,depth:r||0,tenantId:e.tenantId,select:o});if(s.hooks?.afterChange)for(let l of s.hooks.afterChange)await l({collection:t,doc:d,data:i,req:e.req,user:e.user,tenantId:e.tenantId,operation:"create"});return await q(e,R(t,"create"),{collection:t,data:d,operation:"create"}),{doc:d}}}function E(e){return async a=>{let{collection:t,id:n,data:r,depth:o,select:s,baseUpdatedAt:u}=a,i=e.registry.getCollection(t);await b(i,"update",e);let d=await e.db.findByID({collection:t,id:n,tenantId:e.tenantId,draft:true});if(!d)throw new Error(`Document not found: ${t}/${n}`);if(u&&d.updatedAt&&u!==d.updatedAt)throw new Error(`Revision conflict: document has changed since ${u}. Current updatedAt: ${d.updatedAt}`);I(r,i.fields);let c=e.registry.getUpdateZodSchema(t).parse(r);if(i.tenantScoped&&e.tenantId&&(c.tenantId=e.tenantId),i.hooks?.beforeValidate)for(let m of i.hooks.beforeValidate){let f=await m({collection:t,data:c,originalDoc:d,req:e.req,user:e.user,tenantId:e.tenantId,operation:"update",id:n});f&&typeof f=="object"&&!Array.isArray(f)&&Object.assign(c,f);}if(i.hooks?.beforeChange)for(let m of i.hooks.beforeChange){let f=await m({collection:t,data:c,originalDoc:d,req:e.req,user:e.user,tenantId:e.tenantId,operation:"update",id:n});f&&typeof f=="object"&&!Array.isArray(f)&&Object.assign(c,f);}let h=e.req&&typeof e.req.headers?.get=="function"&&e.req.headers.get("x-draft")==="true"||a.draft===true,p=i.versions?.drafts===true,k=e.req?.query?.autosave==="true"||e.req?.url?.includes("autosave=true")||a.autosave===true,g;if(p&&h?(await e.db.createVersion({collection:t,documentId:n,data:c,status:"draft",autosave:k,createdBy:e.user?.id,tenantId:e.tenantId}),g=await e.db.findByID({collection:t,id:n,tenantId:e.tenantId,draft:true})):p?(g=await e.db.update({collection:t,id:n,data:{...c,status:"published"},depth:o||0,tenantId:e.tenantId,select:s}),await e.db.createVersion({collection:t,documentId:n,data:c,status:"published",createdBy:e.user?.id,tenantId:e.tenantId})):g=await e.db.update({collection:t,id:n,data:c,depth:o||0,tenantId:e.tenantId,select:s}),i.hooks?.afterChange)for(let m of i.hooks.afterChange)await m({collection:t,doc:g,data:c,originalDoc:d,req:e.req,user:e.user,tenantId:e.tenantId,operation:"update",id:n});return await q(e,R(t,"update"),{collection:t,data:g,previousData:d,operation:"update"}),{doc:g}}}function j(e){return async a=>{let{collection:t,id:n}=a,r=e.registry.getCollection(t);await b(r,"delete",e);let o=await e.db.findByID({collection:t,id:n,tenantId:e.tenantId,draft:true});if(!o)throw new Error(`Document not found: ${t}/${n}`);if(r.hooks?.beforeDelete)for(let u of r.hooks.beforeDelete)await u({collection:t,doc:o,req:e.req,user:e.user,tenantId:e.tenantId,operation:"delete",id:n});let s=await e.db.delete({collection:t,id:n,tenantId:e.tenantId});if(r.hooks?.afterDelete)for(let u of r.hooks.afterDelete)await u({collection:t,doc:s,req:e.req,user:e.user,tenantId:e.tenantId,operation:"delete",id:n});return await q(e,R(t,"delete"),{collection:t,data:s,previousData:o,operation:"delete"}),{doc:s,message:"Deleted successfully"}}}function S(e){return async a=>{let{collection:t,where:n}=a,r=e.registry.getCollection(t);return await b(r,"read",e),{totalDocs:await e.db.count({collection:t,where:n||{},tenantId:e.tenantId})}}}chunkBUNLC3II_cjs.h();async function W(e,a,t){let n=await chunkAK754S3T_cjs.c(e,a,{user:t.user,req:t.req,tenantId:t.tenantId});if(!n.allowed)throw new Error(n.error||"Access denied");t.tenantId&&t.db.setTenantContext({tenantId:t.tenantId,userId:t.user?.id??"",role:t.user?.role,isSuperAdmin:t.user?.role==="super_admin"});}function O(e){let a={},t=e.registry.getCollections();for(let r of t){let o=r.slug;a[o]={find:P(e),findByID:v(e),create:K(e),update:E(e),delete:j(e),count:S(e)};}let n=e.registry.getGlobals();for(let r of n){let o=r.slug;a[`_globals_${o}`]={get:async s=>(await W(r,"read",e),await e.db.findOne({collection:`_globals_${o}`,where:{},tenantId:e.tenantId,depth:s?.depth,draft:s?.draft,select:s?.select})),update:async s=>{await W(r,"update",e);let i=e.registry.getZodSchema(o).parse(s.data),d=await e.db.findOne({collection:`_globals_${o}`,where:{},tenantId:e.tenantId,draft:true}),l;return d?l=await e.db.update({collection:`_globals_${o}`,id:d.id,data:i,tenantId:e.tenantId}):l=await e.db.create({collection:`_globals_${o}`,data:{...i,id:o},tenantId:e.tenantId}),l}};}return a}function L(e){if(e.settings?.access?.apiAccess?.trpcEnabled===false)throw new Error("tRPC API is disabled");return O(e)}exports.a=V;exports.b=P;exports.c=v;exports.d=K;exports.e=E;exports.f=j;exports.g=S;exports.h=O;exports.i=L;
1
+ 'use strict';var chunkFSL3NLRT_cjs=require('./chunk-FSL3NLRT.cjs'),chunkZHA446FA_cjs=require('./chunk-ZHA446FA.cjs'),chunkZOVH6QT5_cjs=require('./chunk-ZOVH6QT5.cjs'),chunkBUNLC3II_cjs=require('./chunk-BUNLC3II.cjs');chunkBUNLC3II_cjs.h();chunkBUNLC3II_cjs.h();async function V(e){let a=chunkFSL3NLRT_cjs.n(e.db),t={db:e.db,registry:e.registry,req:e.req,user:e.user,tenantId:e.tenantId,webhookService:a,settings:e.settings},n=chunkZHA446FA_cjs.c(e.req);if(n){let r=await chunkZHA446FA_cjs.b(n,e.db,async o=>{try{return await e.db.findByID({collection:"users",id:o})||null}catch{return null}});r.valid&&(t.user=r.user||e.user,t.tenantId=r.tenantId||e.tenantId,t.apiKey=chunkZHA446FA_cjs.d(r));}return t}chunkBUNLC3II_cjs.h();var G={_media:{create:chunkFSL3NLRT_cjs.c.MEDIA_UPLOAD,update:chunkFSL3NLRT_cjs.c.MEDIA_UPLOAD,delete:chunkFSL3NLRT_cjs.c.MEDIA_DELETE}};function R(e,a){let t=G[e];return t?t[a]:`collection.${a}`}async function q(e,a,t){if(e.webhookService)try{await e.webhookService.trigger(a,{collection:t.collection,operation:t.operation,data:t.data,previousData:t.previousData,user:e.user?{id:e.user.id,email:e.user.email,role:e.user.role}:void 0,tenantId:e.tenantId});}catch(n){console.error(`[Webhook] Failed to trigger ${a}:`,n);}}function I(e,a){if(!(!e||typeof e!="object"))for(let t of a){if(t.type==="tabs"&&Array.isArray(t.tabs)){let r=t.name?e[t.name]:e;if(r&&typeof r=="object")for(let o of t.tabs)Array.isArray(o.fields)&&I(r,o.fields);continue}if(!t.name||!(t.name in e))continue;if(e[t.name]===""&&(t.type==="text"||t.type==="textarea"||t.type==="code"||t.type==="markdown"||t.type==="email"||t.type==="password"||t.type==="color"||(e[t.name]=null)),(t.type==="group"||t.type==="collapsible")&&t.name&&Array.isArray(t.fields)&&e[t.name]&&typeof e[t.name]=="object")I(e[t.name],t.fields);else if(t.type==="array"&&t.name&&Array.isArray(t.fields)&&Array.isArray(e[t.name]))for(let r of e[t.name])r&&typeof r=="object"&&I(r,t.fields);else if(t.type==="blocks"&&t.name&&Array.isArray(t.blocks)&&Array.isArray(e[t.name]))for(let r of e[t.name]){if(!r||typeof r!="object")continue;let o=r.type||r.blockType;if(!o)continue;let s=t.blocks.find(i=>i.slug===o);if(!s||!Array.isArray(s.fields))continue;let u=r.data&&typeof r.data=="object"?r.data:r;I(u,s.fields);}}}async function b(e,a,t){let n=await chunkFSL3NLRT_cjs.a(e,a,{user:t.user,req:t.req,tenantId:t.tenantId,apiKey:t.apiKey});if(!n.allowed)throw new Error(n.error||"Access denied");t.tenantId&&t.db.setTenantContext({tenantId:t.tenantId,userId:t.user?.id??"",role:t.user?.role,isSuperAdmin:t.user?.role==="super_admin"});}function P(e){return async a=>{let{collection:t,where:n,sort:r,limit:o,page:s,depth:u,select:i,draft:d}=a,l=e.registry.getCollection(t);if(await b(l,"read",e),l.hooks?.beforeRead)for(let p of l.hooks.beforeRead)await p({collection:t,req:e.req,user:e.user,tenantId:e.tenantId,operation:"read",where:n});let c=d??!!e.user,h=await e.db.find({collection:t,where:n||{},sort:r,limit:o||10,page:s||1,depth:u||0,tenantId:e.tenantId,select:i,draft:c});if(l.hooks?.afterRead)for(let p of h.docs)for(let k of l.hooks.afterRead)await k({collection:t,doc:p,req:e.req,user:e.user,tenantId:e.tenantId,operation:"read"});return await chunkFSL3NLRT_cjs.o(h.docs,l.fields,e.db,e.registry,1,u||0),chunkZOVH6QT5_cjs.a(h)}}function v(e){return async a=>{let{collection:t,id:n,depth:r,select:o,draft:s}=a,u=e.registry.getCollection(t);await b(u,"read",e);let i=s??!!e.user,d=await e.db.findByID({collection:t,id:n,depth:r||0,tenantId:e.tenantId,select:o,draft:i});if(!d)throw new Error(`Document not found: ${t}/${n}`);if(u.hooks?.afterRead)for(let l of u.hooks.afterRead)await l({collection:t,doc:d,req:e.req,user:e.user,tenantId:e.tenantId,operation:"read",id:n});return await chunkFSL3NLRT_cjs.o([d],u.fields,e.db,e.registry,1,r||0),chunkZOVH6QT5_cjs.a(d)}}function K(e){return async a=>{let{collection:t,data:n,depth:r,select:o}=a,s=e.registry.getCollection(t);await b(s,"create",e);let i=e.registry.getCreateZodSchema(t).parse(n);if(s.tenantScoped&&e.tenantId&&(i.tenantId=e.tenantId),s.hooks?.beforeValidate)for(let l of s.hooks.beforeValidate){let c=await l({collection:t,data:i,req:e.req,user:e.user,tenantId:e.tenantId,operation:"create"});c&&typeof c=="object"&&!Array.isArray(c)&&Object.assign(i,c);}if(s.hooks?.beforeChange)for(let l of s.hooks.beforeChange){let c=await l({collection:t,data:i,req:e.req,user:e.user,tenantId:e.tenantId,operation:"create"});c&&typeof c=="object"&&!Array.isArray(c)&&Object.assign(i,c);}let d=await e.db.create({collection:t,data:i,depth:r||0,tenantId:e.tenantId,select:o});if(s.hooks?.afterChange)for(let l of s.hooks.afterChange)await l({collection:t,doc:d,data:i,req:e.req,user:e.user,tenantId:e.tenantId,operation:"create"});return await q(e,R(t,"create"),{collection:t,data:d,operation:"create"}),{doc:d}}}function E(e){return async a=>{let{collection:t,id:n,data:r,depth:o,select:s,baseUpdatedAt:u}=a,i=e.registry.getCollection(t);await b(i,"update",e);let d=await e.db.findByID({collection:t,id:n,tenantId:e.tenantId,draft:true});if(!d)throw new Error(`Document not found: ${t}/${n}`);if(u&&d.updatedAt&&u!==d.updatedAt)throw new Error(`Revision conflict: document has changed since ${u}. Current updatedAt: ${d.updatedAt}`);I(r,i.fields);let c=e.registry.getUpdateZodSchema(t).parse(r);if(i.tenantScoped&&e.tenantId&&(c.tenantId=e.tenantId),i.hooks?.beforeValidate)for(let m of i.hooks.beforeValidate){let f=await m({collection:t,data:c,originalDoc:d,req:e.req,user:e.user,tenantId:e.tenantId,operation:"update",id:n});f&&typeof f=="object"&&!Array.isArray(f)&&Object.assign(c,f);}if(i.hooks?.beforeChange)for(let m of i.hooks.beforeChange){let f=await m({collection:t,data:c,originalDoc:d,req:e.req,user:e.user,tenantId:e.tenantId,operation:"update",id:n});f&&typeof f=="object"&&!Array.isArray(f)&&Object.assign(c,f);}let h=e.req&&typeof e.req.headers?.get=="function"&&e.req.headers.get("x-draft")==="true"||a.draft===true,p=i.versions?.drafts===true,k=e.req?.query?.autosave==="true"||e.req?.url?.includes("autosave=true")||a.autosave===true,g;if(p&&h?(await e.db.createVersion({collection:t,documentId:n,data:c,status:"draft",autosave:k,createdBy:e.user?.id,tenantId:e.tenantId}),g=await e.db.findByID({collection:t,id:n,tenantId:e.tenantId,draft:true})):p?(g=await e.db.update({collection:t,id:n,data:{...c,status:"published"},depth:o||0,tenantId:e.tenantId,select:s}),await e.db.createVersion({collection:t,documentId:n,data:c,status:"published",createdBy:e.user?.id,tenantId:e.tenantId})):g=await e.db.update({collection:t,id:n,data:c,depth:o||0,tenantId:e.tenantId,select:s}),i.hooks?.afterChange)for(let m of i.hooks.afterChange)await m({collection:t,doc:g,data:c,originalDoc:d,req:e.req,user:e.user,tenantId:e.tenantId,operation:"update",id:n});return await q(e,R(t,"update"),{collection:t,data:g,previousData:d,operation:"update"}),{doc:g}}}function j(e){return async a=>{let{collection:t,id:n}=a,r=e.registry.getCollection(t);await b(r,"delete",e);let o=await e.db.findByID({collection:t,id:n,tenantId:e.tenantId,draft:true});if(!o)throw new Error(`Document not found: ${t}/${n}`);if(r.hooks?.beforeDelete)for(let u of r.hooks.beforeDelete)await u({collection:t,doc:o,req:e.req,user:e.user,tenantId:e.tenantId,operation:"delete",id:n});let s=await e.db.delete({collection:t,id:n,tenantId:e.tenantId});if(r.hooks?.afterDelete)for(let u of r.hooks.afterDelete)await u({collection:t,doc:s,req:e.req,user:e.user,tenantId:e.tenantId,operation:"delete",id:n});return await q(e,R(t,"delete"),{collection:t,data:s,previousData:o,operation:"delete"}),{doc:s,message:"Deleted successfully"}}}function S(e){return async a=>{let{collection:t,where:n}=a,r=e.registry.getCollection(t);return await b(r,"read",e),{totalDocs:await e.db.count({collection:t,where:n||{},tenantId:e.tenantId})}}}chunkBUNLC3II_cjs.h();async function W(e,a,t){let n=await chunkFSL3NLRT_cjs.b(e,a,{user:t.user,req:t.req,tenantId:t.tenantId});if(!n.allowed)throw new Error(n.error||"Access denied");t.tenantId&&t.db.setTenantContext({tenantId:t.tenantId,userId:t.user?.id??"",role:t.user?.role,isSuperAdmin:t.user?.role==="super_admin"});}function O(e){let a={},t=e.registry.getCollections();for(let r of t){let o=r.slug;a[o]={find:P(e),findByID:v(e),create:K(e),update:E(e),delete:j(e),count:S(e)};}let n=e.registry.getGlobals();for(let r of n){let o=r.slug;a[`_globals_${o}`]={get:async s=>(await W(r,"read",e),await e.db.findOne({collection:`_globals_${o}`,where:{},tenantId:e.tenantId,depth:s?.depth,draft:s?.draft,select:s?.select})),update:async s=>{await W(r,"update",e);let i=e.registry.getZodSchema(o).parse(s.data),d=await e.db.findOne({collection:`_globals_${o}`,where:{},tenantId:e.tenantId,draft:true}),l;return d?l=await e.db.update({collection:`_globals_${o}`,id:d.id,data:i,tenantId:e.tenantId}):l=await e.db.create({collection:`_globals_${o}`,data:{...i,id:o},tenantId:e.tenantId}),l}};}return a}function L(e){if(e.settings?.access?.apiAccess?.trpcEnabled===false)throw new Error("tRPC API is disabled");return O(e)}exports.a=V;exports.b=P;exports.c=v;exports.d=K;exports.e=E;exports.f=j;exports.g=S;exports.h=O;exports.i=L;
@@ -1,2 +1,2 @@
1
- 'use strict';var chunkDUO523BH_cjs=require('./chunk-DUO523BH.cjs'),chunkZOVH6QT5_cjs=require('./chunk-ZOVH6QT5.cjs'),chunk7WMMKGEO_cjs=require('./chunk-7WMMKGEO.cjs'),chunkBUNLC3II_cjs=require('./chunk-BUNLC3II.cjs'),crypto=require('crypto');chunkBUNLC3II_cjs.h();var B={COLLECTION_CREATE:"collection.create",COLLECTION_UPDATE:"collection.update",COLLECTION_DELETE:"collection.delete",MEDIA_UPLOAD:"media.upload",MEDIA_DELETE:"media.delete",AUTH_LOGIN:"auth.login",AUTH_REGISTER:"auth.register",AUTH_LOGOUT:"auth.logout",ORDER_CREATED:"order.created",ORDER_PAID:"order.paid",ORDER_SHIPPED:"order.shipped",ORDER_DELIVERED:"order.delivered"},M=Object.values(B);var b="_webhooks",D="_webhook_deliveries";chunkBUNLC3II_cjs.h();chunkBUNLC3II_cjs.h();chunkBUNLC3II_cjs.h();chunkBUNLC3II_cjs.h();async function _(o,t,s,e={}){let r=e.timeout||3e4,i=Date.now(),u=new AbortController,c=setTimeout(()=>u.abort(),r);try{let a=await fetch(o,{method:"POST",headers:t,body:s,signal:u.signal});clearTimeout(c);let n=Date.now()-i,l;try{l=(await a.text()).slice(0,1e3);}catch{}let d={success:a.ok,status:a.status,statusText:a.statusText,body:l,duration:n};return d.success&&e.onSuccess?e.onSuccess(d):!d.success&&e.onFailure&&e.onFailure(`HTTP ${a.status}: ${a.statusText}`),d}catch(a){clearTimeout(c);let n=Date.now()-i,l=a.name==="AbortError"?`Request timed out after ${r}ms`:a.message||"Unknown error";return e.onFailure&&e.onFailure(l),{success:false,status:0,duration:n,error:l}}}async function L(o,t,s={}){let e=JSON.stringify(t),r={"Content-Type":"application/json","User-Agent":"Kyro-CMS-Webhook/1.0","X-Webhook-Event":t.event,"X-Webhook-Delivery":t.id,"X-Webhook-Timestamp":t.timestamp,...o.headers||{}};return o.secret&&(r["X-Webhook-Signature"]=C(e,o.secret)),_(o.url,r,e,s)}chunkBUNLC3II_cjs.h();async function $(o,t,s={}){let e=o.config||{},r=process.env.GITHUB_TOKEN;if(!r)return {success:false,status:0,duration:0,error:"GITHUB_TOKEN environment variable is not set"};if(!e.githubOwner||!e.githubRepo)return {success:false,status:0,duration:0,error:"GitHub owner and repo are required"};let i=e.githubBranch||"main",u=Date.now(),c=async(a,n,l)=>{let d=await fetch(a,{method:n,headers:{"Content-Type":"application/json",Accept:"application/vnd.github+json",Authorization:`Bearer ${r}`,"X-GitHub-Api-Version":"2022-11-28","User-Agent":"Kyro-CMS-Webhook/1.0"},body:l?JSON.stringify(l):void 0});if(!d.ok){let y=await d.text();throw new Error(`GitHub API HTTP ${d.status}: ${y}`)}return d.json()};try{let a=`https://api.github.com/repos/${e.githubOwner}/${e.githubRepo}/git/refs/heads/${i}`,l=(await c(a,"GET")).object.sha,d=`https://api.github.com/repos/${e.githubOwner}/${e.githubRepo}/git/commits/${l}`,f=(await c(d,"GET")).tree.sha,p=`https://api.github.com/repos/${e.githubOwner}/${e.githubRepo}/git/commits`,m=(await c(p,"POST",{message:`Content updated via Kyro CMS (${t.event})`,tree:f,parents:[l]})).sha;return await c(a,"PATCH",{sha:m,force:!1}),{success:!0,status:201,duration:Date.now()-u,body:`Successfully pushed empty commit ${m} to branch ${i}`}}catch(a){return {success:false,status:0,duration:Date.now()-u,error:a.message||"Failed to push empty commit to GitHub"}}}var j={generic:L,"github-push":$};function P(o){return j[o||"generic"]||j.generic}function C(o,t){return `sha256=${crypto.createHmac("sha256",t).update(o).digest("hex")}`}function S(){return crypto.randomBytes(32).toString("hex")}async function K(o,t,s={}){return P(o.action)(o,t,s)}async function x(o,t,s,e={}){let r=e.maxRetries??5,i=e.retryDelay??1e3,u=null;for(let c=0;c<=r;c++){if(c>0){let a=Math.min(i*Math.pow(2,c-1),3e4);e.onRetry&&e.onRetry(c,`Retrying in ${a}ms...`),await V(a);}if(e.onRetry&&c>0&&e.onRetry(c,`Attempt ${c+1}/${r+1}`),u=await K(o,t,{...e,onRetry:void 0,onSuccess:void 0,onFailure:void 0}),u.success)return u;if(!(u.error?.includes("timed out")&&c<r)&&u.status>=400&&u.status<500)return u}return u||{success:false,status:0,duration:0,error:"All delivery attempts failed"}}function I(o,t,s,e,r,i){return {id:o,webhookId:t,event:s,payload:e,attempt:r,status:i.success?"success":"failed",responseStatus:i.status||void 0,responseBody:i.body,duration:i.duration,error:i.error,createdAt:new Date().toISOString(),deliveredAt:i.success?new Date().toISOString():void 0}}function V(o){return new Promise(t=>setTimeout(t,o))}function F(){return {id:`test_${Date.now()}`,event:"collection.create",timestamp:new Date().toISOString(),collection:"test",operation:"create",data:{message:"This is a test webhook delivery"},user:{id:"system",email:"system@kyro.dev",role:"super_admin"}}}chunkBUNLC3II_cjs.h();function U(o){let t=new Set,s=[];for(let e of o){let r=e==="create"||e==="update"||e==="delete"?`collection.${e}`:e;t.has(r)||(t.add(r),s.push(r));}return s}var T=class{db;constructor(t){this.db=t;}async getWebhooks(t){let e=(await this.db.find({collection:b,where:t?.status?{status:{equals:t.status}}:{},limit:100,page:1,draft:true})).docs;return t?.event?e.filter(r=>r.events.includes(t.event)):e}async getWebhookById(t){return this.db.findByID({collection:b,id:t,draft:true})}async createWebhook(t){let s=new Date().toISOString(),e=t.secret||S(),r={id:crypto.randomUUID(),name:t.name,url:t.url,events:U(t.events),collections:t.collections||[],status:t.status||"active",secret:e,headers:t.headers||{},action:t.action||"generic",config:t.config||{},createdAt:s,updatedAt:s};return await this.db.create({collection:b,data:r}),r}async updateWebhook(t,s){let e=await this.getWebhookById(t);if(!e)return null;let r={...e,...s,events:s.events?U(s.events):e.events,collections:s.collections!==void 0?s.collections:e.collections,action:s.action!==void 0?s.action:e.action,config:s.config!==void 0?{...e.config,...s.config}:e.config,updatedAt:new Date().toISOString()};return s.secret===""&&"secret"in s&&delete r.secret,await this.db.update({collection:b,id:t,data:r}),r}async deleteWebhook(t){await this.db.delete({collection:b,id:t});}async trigger(t,s){let e=await this.getWebhooks({status:"active",event:t}),r=s.collection,i=e.filter(a=>!a.collections||a.collections.length===0||!r?true:a.collections.includes(r));if(i.length===0)return [];let u={id:crypto.randomUUID(),event:t,timestamp:new Date().toISOString(),...s},c=[];for(let a of i){let n=await this.triggerWebhook(a,u);c.push(n);}return c}async triggerWebhook(t,s){let e=crypto.randomUUID();try{let r=await x(t,s,e,{maxRetries:5,retryDelay:1e3}),i=I(e,t.id,t.events[0],s,1,r);try{await this.db.create({collection:D,data:i});}catch{console.warn("[WebhookService] Failed to save delivery record:",e);}return r.success?await this.updateWebhook(t.id,{lastTriggered:new Date().toISOString(),lastError:null}).catch(()=>{}):await this.updateWebhook(t.id,{lastError:r.error||`HTTP ${r.status}`}).catch(()=>{}),{deliveryId:e,webhookId:t.id,event:t.events[0],status:r.success?"success":"failed",responseStatus:r.status,duration:r.duration,error:r.error}}catch(r){return {deliveryId:e,webhookId:t.id,event:t.events[0],status:"failed",error:r.message}}}async testWebhook(t){let s=await this.getWebhookById(t);if(!s)return null;let e={id:crypto.randomUUID(),event:s.events[0]||"collection.create",timestamp:new Date().toISOString(),collection:"test",operation:"create",data:{message:"This is a test webhook delivery from Kyro CMS"},user:{id:"system",email:"system@kyro.dev",role:"super_admin"}};return this.triggerWebhook(s,e)}async getDeliveryHistory(t,s=50){return (await this.db.find({collection:D,where:{webhookId:{equals:t}},sort:"-createdAt",limit:s,page:1})).docs}async retryDelivery(t){let s=await this.db.findByID({collection:D,id:t});if(!s)return null;let e=await this.getWebhookById(s.webhookId);return e?this.triggerWebhook(e,s.payload):null}};function z(o){return new T(o)}chunkBUNLC3II_cjs.h();chunkBUNLC3II_cjs.h();function X(o){if(!o)return [];if(typeof o=="string")return [{id:o}];if(Array.isArray(o))return o.map(t=>typeof t=="object"?{id:t.value??t.id??t,relationTo:t.relationTo}:{id:t});if(typeof o=="object"){let t=o.value??o.id??o;if(typeof t=="string")return [{id:t,relationTo:o.relationTo}];if(Array.isArray(t))return t.map(s=>({id:s,relationTo:o.relationTo}))}return []}function k(o,t,s){if(!(!o||typeof o!="object")){for(let e of t)if(!(!e.name&&e.type!=="row"&&e.type!=="collapsible"&&e.type!=="tabs")){if(e.type==="relationship"||e.type==="upload")s(e,o);else if(e.type==="group"||e.type==="collapsible"||e.type==="row"){let r=e.name?o[e.name]:o;k(r,e.fields||[],s);}else if(e.type==="tabs"&&e.tabs){let r=e.name?o[e.name]:o;for(let i of e.tabs)k(r,i.fields||[],s);}else if(e.type==="array"&&e.name&&Array.isArray(o[e.name]))for(let r of o[e.name])k(r,e.fields||[],s);else if(e.type==="blocks"&&e.name&&Array.isArray(o[e.name]))for(let r of o[e.name]){if(!r||typeof r!="object")continue;let i=r.type||r.blockType;if(!i)continue;let u=e.blocks?.find(c=>c.slug===i);if(u&&Array.isArray(u.fields)){let c=r.data&&typeof r.data=="object"?r.data:r;k(c,u.fields,s);}}}}}function Y(o,t,s){k(o,t,(e,r)=>{let i=r[e.name];if(!i)return;let u=Array.isArray(e.relationTo)?e.relationTo:[e.relationTo],c=X(i);for(let a of c){if(!a.id)continue;let n=a.relationTo?[a.relationTo]:u;for(let l of n)l!=="*"&&(s.has(l)||s.set(l,new Set),s.get(l).add(a.id));}});}function J(o,t,s){k(o,t,(e,r)=>{let i=r[e.name];if(!i)return;let u=Array.isArray(e.relationTo)?e.relationTo:[e.relationTo],c=n=>{r[e.name]=n;},a=(n,l)=>{let d=l?[l]:u;for(let y of d){let f=s.get(y);if(f&&f.has(n))return f.get(n)}return null};if(typeof i=="string"){let n=a(i);c(n||{id:i});}else if(Array.isArray(i))c(i.map(n=>{let l=typeof n=="object"?n.value??n.id:n,d=typeof n=="object"?n.relationTo:void 0,y=a(l,d);return y||{id:l}}));else if(typeof i=="object"){let n=i.value??i.id,l=i.relationTo,d=a(n,l);c(d||{id:n});}});}async function Q(o,t,s,e,r=1,i=0){if(!o||o.length===0||r>i)return;let u=new Map;for(let n of o)Y(n,t,u);if(u.size===0)return;let c=new Map,a=new Map;for(let[n,l]of u.entries()){if(l.size===0||!e.getCollection(n))continue;let y=new Map,f=Array.from(l),p=[];for(let O of f){try{let W=(await s.find({collection:n,where:{id:{in:f}},limit:f.length,draft:!0}))?.docs||[];for(let v of W)v&&v.id&&(y.set(String(v.id),v),p.push(v));}catch{for(let m of f)try{let W=await s.findByID({collection:n,id:m,draft:!0});W&&(y.set(m,W),p.push(W));}catch{}}break}c.set(n,y),p.length>0&&a.set(n,p);}if(r<i)for(let[n,l]of a.entries()){let d=e.getCollection(n);d&&await Q(l,d.fields,s,e,r+1,i);}for(let n=0;n<o.length;n++)J(o[n],t,c),o[n]=chunkZOVH6QT5_cjs.a(o[n]);}chunkBUNLC3II_cjs.h();function N(o){return o==="read"?"read":o==="create"?"create":o==="update"?"update":"delete"}function Z(o,t){return {none:false,read:o==="read",create:o==="read"||o==="create",update:o==="read"||o==="create"||o==="update",delete:o==="read"||o==="create"||o==="update"||o==="delete",admin:true}[t]||false}async function _e(o,t,s,e={}){let{user:r,req:i,tenantId:u,apiKey:c}=s,{enablePublicAccess:a=true,defaultAccess:n="none"}=e,l=o.access?.[t];if(l){let y=await chunkDUO523BH_cjs.a(l,{req:i,user:r,tenantId:u});return y===false?{allowed:false,error:"Access denied",status:403}:typeof y=="object"?{allowed:true,extraWhere:y}:{allowed:true}}if(c?.permissions?.length>0){let y=o.slug,f=N(t),p=`${y}:${f}`;return !chunkDUO523BH_cjs.h(c.permissions,p)&&!chunkDUO523BH_cjs.h(c.permissions,`${y}:admin`)?{allowed:false,error:"Access denied: insufficient permissions",status:403}:{allowed:true}}if(r){let y=o.slug,f=N(t),p=`${y}:${f}`,O=chunk7WMMKGEO_cjs.a({id:r.id,email:r.email,role:r.role},p),m=chunk7WMMKGEO_cjs.a({id:r.id,email:r.email,role:r.role},`${y}:admin`);return O||m?{allowed:true}:{allowed:false,error:"Access denied: missing RBAC permission",status:403}}let d=Z(t,n);return a&&d?{allowed:true}:{allowed:false,error:"Authentication required",status:401}}async function Le(o,t,s,e={}){let{user:r,req:i,tenantId:u}=s,{enablePublicAccess:c=true}=e,a=o.access?.[t];if(a)return await chunkDUO523BH_cjs.a(a,{req:i,user:r,tenantId:u})===false?{allowed:false,error:"Access denied",status:403}:{allowed:true};if(r){let n=`globals:${t}`,l=chunk7WMMKGEO_cjs.a({id:r.id,email:r.email,role:r.role},n),d=chunk7WMMKGEO_cjs.a({id:r.id,email:r.email,role:r.role},"globals:admin");return l||d?{allowed:true}:{allowed:false,error:"Access denied: missing RBAC permission",status:403}}return c?{allowed:true}:{allowed:false,error:"Authentication required",status:401}}
2
- exports.a=Q;exports.b=_e;exports.c=Le;exports.d=B;exports.e=M;exports.f=b;exports.g=D;exports.h=C;exports.i=S;exports.j=K;exports.k=x;exports.l=I;exports.m=F;exports.n=T;exports.o=z;
1
+ 'use strict';var chunkZHA446FA_cjs=require('./chunk-ZHA446FA.cjs'),chunkZOVH6QT5_cjs=require('./chunk-ZOVH6QT5.cjs'),chunk7WMMKGEO_cjs=require('./chunk-7WMMKGEO.cjs'),chunkBUNLC3II_cjs=require('./chunk-BUNLC3II.cjs'),crypto=require('crypto');chunkBUNLC3II_cjs.h();var B={COLLECTION_CREATE:"collection.create",COLLECTION_UPDATE:"collection.update",COLLECTION_DELETE:"collection.delete",MEDIA_UPLOAD:"media.upload",MEDIA_DELETE:"media.delete",AUTH_LOGIN:"auth.login",AUTH_REGISTER:"auth.register",AUTH_LOGOUT:"auth.logout",ORDER_CREATED:"order.created",ORDER_PAID:"order.paid",ORDER_SHIPPED:"order.shipped",ORDER_DELIVERED:"order.delivered"},M=Object.values(B);var b="_webhooks",D="_webhook_deliveries";chunkBUNLC3II_cjs.h();chunkBUNLC3II_cjs.h();chunkBUNLC3II_cjs.h();chunkBUNLC3II_cjs.h();async function _(o,t,s,e={}){let r=e.timeout||3e4,i=Date.now(),u=new AbortController,c=setTimeout(()=>u.abort(),r);try{let a=await fetch(o,{method:"POST",headers:t,body:s,signal:u.signal});clearTimeout(c);let n=Date.now()-i,l;try{l=(await a.text()).slice(0,1e3);}catch{}let d={success:a.ok,status:a.status,statusText:a.statusText,body:l,duration:n};return d.success&&e.onSuccess?e.onSuccess(d):!d.success&&e.onFailure&&e.onFailure(`HTTP ${a.status}: ${a.statusText}`),d}catch(a){clearTimeout(c);let n=Date.now()-i,l=a.name==="AbortError"?`Request timed out after ${r}ms`:a.message||"Unknown error";return e.onFailure&&e.onFailure(l),{success:false,status:0,duration:n,error:l}}}async function L(o,t,s={}){let e=JSON.stringify(t),r={"Content-Type":"application/json","User-Agent":"Kyro-CMS-Webhook/1.0","X-Webhook-Event":t.event,"X-Webhook-Delivery":t.id,"X-Webhook-Timestamp":t.timestamp,...o.headers||{}};return o.secret&&(r["X-Webhook-Signature"]=C(e,o.secret)),_(o.url,r,e,s)}chunkBUNLC3II_cjs.h();async function $(o,t,s={}){let e=o.config||{},r=process.env.GITHUB_TOKEN;if(!r)return {success:false,status:0,duration:0,error:"GITHUB_TOKEN environment variable is not set"};if(!e.githubOwner||!e.githubRepo)return {success:false,status:0,duration:0,error:"GitHub owner and repo are required"};let i=e.githubBranch||"main",u=Date.now(),c=async(a,n,l)=>{let d=await fetch(a,{method:n,headers:{"Content-Type":"application/json",Accept:"application/vnd.github+json",Authorization:`Bearer ${r}`,"X-GitHub-Api-Version":"2022-11-28","User-Agent":"Kyro-CMS-Webhook/1.0"},body:l?JSON.stringify(l):void 0});if(!d.ok){let y=await d.text();throw new Error(`GitHub API HTTP ${d.status}: ${y}`)}return d.json()};try{let a=`https://api.github.com/repos/${e.githubOwner}/${e.githubRepo}/git/refs/heads/${i}`,l=(await c(a,"GET")).object.sha,d=`https://api.github.com/repos/${e.githubOwner}/${e.githubRepo}/git/commits/${l}`,f=(await c(d,"GET")).tree.sha,p=`https://api.github.com/repos/${e.githubOwner}/${e.githubRepo}/git/commits`,m=(await c(p,"POST",{message:`Content updated via Kyro CMS (${t.event})`,tree:f,parents:[l]})).sha;return await c(a,"PATCH",{sha:m,force:!1}),{success:!0,status:201,duration:Date.now()-u,body:`Successfully pushed empty commit ${m} to branch ${i}`}}catch(a){return {success:false,status:0,duration:Date.now()-u,error:a.message||"Failed to push empty commit to GitHub"}}}var j={generic:L,"github-push":$};function P(o){return j[o||"generic"]||j.generic}function C(o,t){return `sha256=${crypto.createHmac("sha256",t).update(o).digest("hex")}`}function S(){return crypto.randomBytes(32).toString("hex")}async function K(o,t,s={}){return P(o.action)(o,t,s)}async function x(o,t,s,e={}){let r=e.maxRetries??5,i=e.retryDelay??1e3,u=null;for(let c=0;c<=r;c++){if(c>0){let a=Math.min(i*Math.pow(2,c-1),3e4);e.onRetry&&e.onRetry(c,`Retrying in ${a}ms...`),await V(a);}if(e.onRetry&&c>0&&e.onRetry(c,`Attempt ${c+1}/${r+1}`),u=await K(o,t,{...e,onRetry:void 0,onSuccess:void 0,onFailure:void 0}),u.success)return u;if(!(u.error?.includes("timed out")&&c<r)&&u.status>=400&&u.status<500)return u}return u||{success:false,status:0,duration:0,error:"All delivery attempts failed"}}function I(o,t,s,e,r,i){return {id:o,webhookId:t,event:s,payload:e,attempt:r,status:i.success?"success":"failed",responseStatus:i.status||void 0,responseBody:i.body,duration:i.duration,error:i.error,createdAt:new Date().toISOString(),deliveredAt:i.success?new Date().toISOString():void 0}}function V(o){return new Promise(t=>setTimeout(t,o))}function F(){return {id:`test_${Date.now()}`,event:"collection.create",timestamp:new Date().toISOString(),collection:"test",operation:"create",data:{message:"This is a test webhook delivery"},user:{id:"system",email:"system@kyro.dev",role:"super_admin"}}}chunkBUNLC3II_cjs.h();function U(o){let t=new Set,s=[];for(let e of o){let r=e==="create"||e==="update"||e==="delete"?`collection.${e}`:e;t.has(r)||(t.add(r),s.push(r));}return s}var T=class{db;constructor(t){this.db=t;}async getWebhooks(t){let e=(await this.db.find({collection:b,where:t?.status?{status:{equals:t.status}}:{},limit:100,page:1,draft:true})).docs;return t?.event?e.filter(r=>r.events.includes(t.event)):e}async getWebhookById(t){return this.db.findByID({collection:b,id:t,draft:true})}async createWebhook(t){let s=new Date().toISOString(),e=t.secret||S(),r={id:crypto.randomUUID(),name:t.name,url:t.url,events:U(t.events),collections:t.collections||[],status:t.status||"active",secret:e,headers:t.headers||{},action:t.action||"generic",config:t.config||{},createdAt:s,updatedAt:s};return await this.db.create({collection:b,data:r}),r}async updateWebhook(t,s){let e=await this.getWebhookById(t);if(!e)return null;let r={...e,...s,events:s.events?U(s.events):e.events,collections:s.collections!==void 0?s.collections:e.collections,action:s.action!==void 0?s.action:e.action,config:s.config!==void 0?{...e.config,...s.config}:e.config,updatedAt:new Date().toISOString()};return s.secret===""&&"secret"in s&&delete r.secret,await this.db.update({collection:b,id:t,data:r}),r}async deleteWebhook(t){await this.db.delete({collection:b,id:t});}async trigger(t,s){let e=await this.getWebhooks({status:"active",event:t}),r=s.collection,i=e.filter(a=>!a.collections||a.collections.length===0||!r?true:a.collections.includes(r));if(i.length===0)return [];let u={id:crypto.randomUUID(),event:t,timestamp:new Date().toISOString(),...s},c=[];for(let a of i){let n=await this.triggerWebhook(a,u);c.push(n);}return c}async triggerWebhook(t,s){let e=crypto.randomUUID();try{let r=await x(t,s,e,{maxRetries:5,retryDelay:1e3}),i=I(e,t.id,t.events[0],s,1,r);try{await this.db.create({collection:D,data:i});}catch{console.warn("[WebhookService] Failed to save delivery record:",e);}return r.success?await this.updateWebhook(t.id,{lastTriggered:new Date().toISOString(),lastError:null}).catch(()=>{}):await this.updateWebhook(t.id,{lastError:r.error||`HTTP ${r.status}`}).catch(()=>{}),{deliveryId:e,webhookId:t.id,event:t.events[0],status:r.success?"success":"failed",responseStatus:r.status,duration:r.duration,error:r.error}}catch(r){return {deliveryId:e,webhookId:t.id,event:t.events[0],status:"failed",error:r.message}}}async testWebhook(t){let s=await this.getWebhookById(t);if(!s)return null;let e={id:crypto.randomUUID(),event:s.events[0]||"collection.create",timestamp:new Date().toISOString(),collection:"test",operation:"create",data:{message:"This is a test webhook delivery from Kyro CMS"},user:{id:"system",email:"system@kyro.dev",role:"super_admin"}};return this.triggerWebhook(s,e)}async getDeliveryHistory(t,s=50){return (await this.db.find({collection:D,where:{webhookId:{equals:t}},sort:"-createdAt",limit:s,page:1})).docs}async retryDelivery(t){let s=await this.db.findByID({collection:D,id:t});if(!s)return null;let e=await this.getWebhookById(s.webhookId);return e?this.triggerWebhook(e,s.payload):null}};function z(o){return new T(o)}chunkBUNLC3II_cjs.h();chunkBUNLC3II_cjs.h();function N(o){return o==="read"?"read":o==="create"?"create":o==="update"?"update":"delete"}function X(o,t){return {none:false,read:o==="read",create:o==="read"||o==="create",update:o==="read"||o==="create"||o==="update",delete:o==="read"||o==="create"||o==="update"||o==="delete",admin:true}[t]||false}async function Ie(o,t,s,e={}){let{user:r,req:i,tenantId:u,apiKey:c}=s,{enablePublicAccess:a=true,defaultAccess:n="none"}=e,l=o.access?.[t];if(l){let y=await chunkZHA446FA_cjs.h(l,{req:i,user:r,tenantId:u});return y===false?{allowed:false,error:"Access denied",status:403}:typeof y=="object"?{allowed:true,extraWhere:y}:{allowed:true}}if(c?.permissions?.length>0){let y=o.slug,f=N(t),p=`${y}:${f}`;return !chunkZHA446FA_cjs.e(c.permissions,p)&&!chunkZHA446FA_cjs.e(c.permissions,`${y}:admin`)?{allowed:false,error:"Access denied: insufficient permissions",status:403}:{allowed:true}}if(r){let y=o.slug,f=N(t),p=`${y}:${f}`,O=chunk7WMMKGEO_cjs.a({id:r.id,email:r.email,role:r.role},p),m=chunk7WMMKGEO_cjs.a({id:r.id,email:r.email,role:r.role},`${y}:admin`);return O||m?{allowed:true}:{allowed:false,error:"Access denied: missing RBAC permission",status:403}}let d=X(t,n);return a&&d?{allowed:true}:{allowed:false,error:"Authentication required",status:401}}async function He(o,t,s,e={}){let{user:r,req:i,tenantId:u}=s,{enablePublicAccess:c=true}=e,a=o.access?.[t];if(a)return await chunkZHA446FA_cjs.h(a,{req:i,user:r,tenantId:u})===false?{allowed:false,error:"Access denied",status:403}:{allowed:true};if(r){let n=`globals:${t}`,l=chunk7WMMKGEO_cjs.a({id:r.id,email:r.email,role:r.role},n),d=chunk7WMMKGEO_cjs.a({id:r.id,email:r.email,role:r.role},"globals:admin");return l||d?{allowed:true}:{allowed:false,error:"Access denied: missing RBAC permission",status:403}}return c?{allowed:true}:{allowed:false,error:"Authentication required",status:401}}chunkBUNLC3II_cjs.h();function Y(o){if(!o)return [];if(typeof o=="string")return [{id:o}];if(Array.isArray(o))return o.map(t=>typeof t=="object"?{id:t.value??t.id??t,relationTo:t.relationTo}:{id:t});if(typeof o=="object"){let t=o.value??o.id??o;if(typeof t=="string")return [{id:t,relationTo:o.relationTo}];if(Array.isArray(t))return t.map(s=>({id:s,relationTo:o.relationTo}))}return []}function k(o,t,s){if(!(!o||typeof o!="object")){for(let e of t)if(!(!e.name&&e.type!=="row"&&e.type!=="collapsible"&&e.type!=="tabs")){if(e.type==="relationship"||e.type==="upload")s(e,o);else if(e.type==="group"||e.type==="collapsible"||e.type==="row"){let r=e.name?o[e.name]:o;k(r,e.fields||[],s);}else if(e.type==="tabs"&&e.tabs){let r=e.name?o[e.name]:o;for(let i of e.tabs)k(r,i.fields||[],s);}else if(e.type==="array"&&e.name&&Array.isArray(o[e.name]))for(let r of o[e.name])k(r,e.fields||[],s);else if(e.type==="blocks"&&e.name&&Array.isArray(o[e.name]))for(let r of o[e.name]){if(!r||typeof r!="object")continue;let i=r.type||r.blockType;if(!i)continue;let u=e.blocks?.find(c=>c.slug===i);if(u&&Array.isArray(u.fields)){let c=r.data&&typeof r.data=="object"?r.data:r;k(c,u.fields,s);}}}}}function J(o,t,s){k(o,t,(e,r)=>{let i=r[e.name];if(!i)return;let u=Array.isArray(e.relationTo)?e.relationTo:[e.relationTo],c=Y(i);for(let a of c){if(!a.id)continue;let n=a.relationTo?[a.relationTo]:u;for(let l of n)l!=="*"&&(s.has(l)||s.set(l,new Set),s.get(l).add(a.id));}});}function Q(o,t,s){k(o,t,(e,r)=>{let i=r[e.name];if(!i)return;let u=Array.isArray(e.relationTo)?e.relationTo:[e.relationTo],c=n=>{r[e.name]=n;},a=(n,l)=>{let d=l?[l]:u;for(let y of d){let f=s.get(y);if(f&&f.has(n))return f.get(n)}return null};if(typeof i=="string"){let n=a(i);c(n||{id:i});}else if(Array.isArray(i))c(i.map(n=>{let l=typeof n=="object"?n.value??n.id:n,d=typeof n=="object"?n.relationTo:void 0,y=a(l,d);return y||{id:l}}));else if(typeof i=="object"){let n=i.value??i.id,l=i.relationTo,d=a(n,l);c(d||{id:n});}});}async function Z(o,t,s,e,r=1,i=0){if(!o||o.length===0||r>i)return;let u=new Map;for(let n of o)J(n,t,u);if(u.size===0)return;let c=new Map,a=new Map;for(let[n,l]of u.entries()){if(l.size===0||!e.getCollection(n))continue;let y=new Map,f=Array.from(l),p=[];for(let O of f){try{let W=(await s.find({collection:n,where:{id:{in:f}},limit:f.length,draft:!0}))?.docs||[];for(let v of W)v&&v.id&&(y.set(String(v.id),v),p.push(v));}catch{for(let m of f)try{let W=await s.findByID({collection:n,id:m,draft:!0});W&&(y.set(m,W),p.push(W));}catch{}}break}c.set(n,y),p.length>0&&a.set(n,p);}if(r<i)for(let[n,l]of a.entries()){let d=e.getCollection(n);d&&await Z(l,d.fields,s,e,r+1,i);}for(let n=0;n<o.length;n++)Q(o[n],t,c),o[n]=chunkZOVH6QT5_cjs.a(o[n]);}
2
+ exports.a=Ie;exports.b=He;exports.c=B;exports.d=M;exports.e=b;exports.f=D;exports.g=C;exports.h=S;exports.i=K;exports.j=x;exports.k=I;exports.l=F;exports.m=T;exports.n=z;exports.o=Z;
@@ -1,2 +1,2 @@
1
1
  import {g as g$1}from'./chunk-Y2YAKDEQ.js';import {timingSafeEqual}from'crypto';if (typeof window === "undefined") { const { createRequire } = await import(/* @vite-ignore */ 'module'); createRequire(import.meta.url); }
2
- g$1();async function p(e,r){return typeof e=="boolean"?e:typeof e=="function"?await e(r):true}function h(...e){let r={};for(let t of e)t&&typeof t=="object"&&Object.assign(r,t);return r}function x(e,r){return p(e,r).then(t=>{if(t!==true)return t===false?{_id:{$eq:null}}:t})}g$1();var u="api_keys";function g(e){return e.substring(0,8)}function y(e,r){if(e.length!==r.length)return false;try{return timingSafeEqual(Buffer.from(e),Buffer.from(r))}catch{return false}}async function P(e,r,t){if(!e||typeof e!="string")return {valid:false,error:"No API key provided"};if(!e.startsWith("kyro_"))return {valid:false,error:"Invalid API key format"};let l=g(e);try{let s=await r.find({collection:u,where:{keyPrefix:{equals:l}},limit:100,page:1});if(!s.docs||s.docs.length===0)return {valid:!1,error:"Invalid API key"};let n=null;for(let i of s.docs){let c=i;if(y(c.key,e)){n=c;break}}if(!n)return {valid:!1,error:"Invalid API key"};if(n.expiresAt&&new Date(n.expiresAt)<new Date)return {valid:!1,error:"API key has expired"};try{await r.update({collection:u,id:n.id,data:{lastUsedAt:new Date().toISOString()}});}catch{}let o={id:n.userId,role:n.role||"author",tenantId:n.tenantId};if(t){let i=await t(n.userId);i&&Object.assign(o,i);}return {valid:!0,userId:n.userId,user:o,permissions:n.permissions||[],apiKeyId:n.id,tenantId:o.tenantId,role:o.role}}catch(s){return console.error("[ApiKey] Validation error:",s),{valid:false,error:"Failed to validate API key"}}}function K(e){let r=e.headers.get("Authorization");if(r){if(r.startsWith("ApiKey "))return r.slice(7).trim();if(r.startsWith("Bearer "))return null}let t=e.headers.get("X-API-Key");return t?t.trim():null}function k(e){return !e.valid||!e.userId?null:{userId:e.userId,user:e.user||{},permissions:e.permissions||[],apiKeyId:e.apiKeyId||"",tenantId:e.tenantId,role:e.role}}function v(e,r){if(e.length===0)return false;if(e.includes("*")||e.includes(r))return true;let[t,l]=r.split(":");return !!e.includes(`${t}:*`)}function b(){let e="abcdefghijklmnopqrstuvwxyz0123456789",r="";for(let t=0;t<32;t++)r+=e[Math.floor(Math.random()*e.length)];return `kyro_${r}`}function R(e){return e.substring(0,8)}export{p as a,h as b,x as c,u as d,P as e,K as f,k as g,v as h,b as i,R as j};
2
+ g$1();async function p(e,r){return typeof e=="boolean"?e:typeof e=="function"?await e(r):true}function h(...e){let r={};for(let t of e)t&&typeof t=="object"&&Object.assign(r,t);return r}function x(e,r){return p(e,r).then(t=>{if(t!==true)return t===false?{_id:{$eq:null}}:t})}g$1();var u="api_keys";function g(e){return e.substring(0,8)}function y(e,r){if(e.length!==r.length)return false;try{return timingSafeEqual(Buffer.from(e),Buffer.from(r))}catch{return false}}async function P(e,r,t){if(!e||typeof e!="string")return {valid:false,error:"No API key provided"};if(!e.startsWith("kyro_"))return {valid:false,error:"Invalid API key format"};let l=g(e);try{let s=await r.find({collection:u,where:{keyPrefix:{equals:l}},limit:100,page:1});if(!s.docs||s.docs.length===0)return {valid:!1,error:"Invalid API key"};let n=null;for(let i of s.docs){let c=i;if(y(c.key,e)){n=c;break}}if(!n)return {valid:!1,error:"Invalid API key"};if(n.expiresAt&&new Date(n.expiresAt)<new Date)return {valid:!1,error:"API key has expired"};try{await r.update({collection:u,id:n.id,data:{lastUsedAt:new Date().toISOString()}});}catch{}let o={id:n.userId,role:n.role||"author",tenantId:n.tenantId};if(t){let i=await t(n.userId);i&&Object.assign(o,i);}return {valid:!0,userId:n.userId,user:o,permissions:n.permissions||[],apiKeyId:n.id,tenantId:o.tenantId,role:o.role}}catch(s){return console.error("[ApiKey] Validation error:",s),{valid:false,error:"Failed to validate API key"}}}function K(e){let r=e.headers.get("Authorization");if(r){if(r.startsWith("ApiKey "))return r.slice(7).trim();if(r.startsWith("Bearer "))return null}let t=e.headers.get("X-API-Key");return t?t.trim():null}function k(e){return !e.valid||!e.userId?null:{userId:e.userId,user:e.user||{},permissions:e.permissions||[],apiKeyId:e.apiKeyId||"",tenantId:e.tenantId,role:e.role}}function v(e,r){if(e.length===0)return false;if(e.includes("*")||e.includes(r))return true;let[t,l]=r.split(":");return !!e.includes(`${t}:*`)}function b(){let e="abcdefghijklmnopqrstuvwxyz0123456789",r="";for(let t=0;t<32;t++)r+=e[Math.floor(Math.random()*e.length)];return `kyro_${r}`}function R(e){return e.substring(0,8)}export{u as a,P as b,K as c,k as d,v as e,b as f,R as g,p as h,h as i,x as j};
@@ -0,0 +1,19 @@
1
+ 'use strict';var chunkVQ53TFYA_cjs=require('./chunk-VQ53TFYA.cjs'),chunkZOVH6QT5_cjs=require('./chunk-ZOVH6QT5.cjs'),chunkBUNLC3II_cjs=require('./chunk-BUNLC3II.cjs'),module$1=require('module'),crypto=require('crypto');chunkBUNLC3II_cjs.h();chunkBUNLC3II_cjs.h();chunkBUNLC3II_cjs.h();function N(T){let e=[];for(let n of T)if(n.type==="tabs"&&"tabs"in n)for(let a of n.tabs)e.push(...N(a.fields));else n.type==="row"&&"fields"in n?e.push(...N(n.fields)):n.type==="collapsible"&&"fields"in n?e.push(...N(n.fields)):e.push(n);return e}function P(T,e){let n=e,a=T[n.name];if(n.type==="json"||n.type==="richtext"||n.type==="array"||n.type==="group"||n.type==="blocks"||n.type==="list"||n.type==="relationship-block")try{a=a?JSON.parse(a):null;}catch{a=null;}if(n.type==="checkbox"&&(a=!!a),n.type==="date"&&a)try{let o=new Date(a);isNaN(o.getTime())?a=null:a=o.toISOString();}catch{a=null;}if((n.type==="upload"||n.type==="image")&&a)try{let o=JSON.parse(a);Array.isArray(o)?a=o.map(i=>typeof i=="object"&&i!==null?i:{id:i}):a=typeof o=="object"?o:{id:o};}catch{a=typeof a=="string"?{id:a}:a;}return a}var R;function U(){return R||(R=module$1.createRequire("file:///")("node:sqlite").DatabaseSync,R)}function w(T,e){return Array.isArray(T)?T.map(n=>{if(!n||typeof n!="object")return n;let a=n.data?{...n.data}:void 0;if(!a)return n;let o=e.find(i=>i.slug===n.type||i.slug===n.slug);if(!o||!Array.isArray(o.fields))return n;for(let i of o.fields){if(i.name&&(i.type==="upload"||i.type==="image")&&a[i.name]){let t=a[i.name];Array.isArray(t)?a[i.name]=t.map(s=>typeof s=="string"?{id:s}:s):typeof t=="string"&&(a[i.name]={id:t});}if(i.type==="blocks"&&i.name&&a[i.name]){let t=i.blocks||[];a[i.name]=w(a[i.name],t);}}return {...n,data:a}}):T}function L(T,e){try{return T.prepare(`PRAGMA table_info(${e})`).all().map(a=>a.name)}catch{return []}}var O=class extends chunkVQ53TFYA_cjs.a{db;path;migrations=new Map;versionsTableName="kyro_versions";constructor(e){super(),this.path=e.path,e.db?this.db=e.db:this.db=null;}async connect(){if(!this.db)this.db=new(U())(this.path||":memory:");else try{this.db.exec("SELECT 1");}catch{this.db=new(U())(this.path||":memory:");}if(this.db&&typeof this.db.prepare=="function"&&!this.db.prepare.__wrapped){let e=this.db.prepare.bind(this.db),n=a=>{let o=e(a),i=t=>typeof t=="boolean"?t?1:0:t===void 0?null:t;return new Proxy(o,{get(t,s,r){if(s==="all")return (...c)=>t.all(...c.map(i));if(s==="get")return (...c)=>t.get(...c.map(i));if(s==="run")return (...c)=>t.run(...c.map(i));let l=Reflect.get(t,s,r);return typeof l=="function"?l.bind(t):l}})};n.__wrapped=true,this.db.prepare=n;}this.db.exec("PRAGMA journal_mode = WAL"),this.db.exec("PRAGMA foreign_keys = ON"),this.connected=true;}async disconnect(){if(this.db){try{this.db.close();}catch{}this.db=null;}this.connected=false;}ensureTable(e,n){let a=n||this.getTableNameFor(e.slug),o=["id TEXT PRIMARY KEY"];for(let s of N(e.fields)){if(!s.name||s.name==="id")continue;let r=this.fieldToSQL(s);r&&o.push(r);}let i=N(e.fields);i.some(s=>s.name==="createdAt")||o.push(`${this.col("createdAt")} TEXT DEFAULT (datetime('now'))`),i.some(s=>s.name==="updatedAt")||o.push(`${this.col("updatedAt")} TEXT DEFAULT (datetime('now'))`),i.some(s=>s.name==="status")||o.push("status TEXT DEFAULT 'draft'"),i.some(s=>s.name==="hasDraft")||o.push("hasDraft INTEGER DEFAULT 0"),e.tenantScoped&&o.push("tenant_id TEXT NOT NULL");let t=L(this.db,a);if(t.length===0){let s=`CREATE TABLE IF NOT EXISTS ${a} (${o.join(", ")})`;this.db.exec(s),this.db.exec(`CREATE INDEX IF NOT EXISTS idx_${a}_status ON ${a}(status)`);for(let r of N(e.fields))r.name&&r.indexed&&this.db.exec(`CREATE INDEX IF NOT EXISTS idx_${a}_${r.name} ON ${a}(${this.col(r.name)})`),r.name&&r.unique&&this.db.exec(`CREATE UNIQUE INDEX IF NOT EXISTS idx_${a}_${r.name}_unique ON ${a}(${this.col(r.name)})`);}else {let s=new Set(t);for(let r of o){let l=r.split(" ")[0].replace(/^"/,"").replace(/"$/,"");if(!s.has(l)&&l!=="id")try{l==="status"?this.db.exec(`ALTER TABLE ${a} ADD COLUMN ${this.col(l)} TEXT DEFAULT 'published'`):l==="hasDraft"?this.db.exec(`ALTER TABLE ${a} ADD COLUMN ${this.col(l)} INTEGER DEFAULT 0`):this.db.exec(`ALTER TABLE ${a} ADD COLUMN ${this.col(l)} TEXT`);}catch{}}}this.migrations.set(a,true);}ensureVersionsTable(){this.db.exec(`
2
+ CREATE TABLE IF NOT EXISTS ${this.versionsTableName} (
3
+ id TEXT PRIMARY KEY,
4
+ collection_slug TEXT NOT NULL,
5
+ document_id TEXT NOT NULL,
6
+ tenant_id TEXT,
7
+ version INTEGER NOT NULL,
8
+ status TEXT NOT NULL DEFAULT 'draft',
9
+ autosave INTEGER NOT NULL DEFAULT 0,
10
+ data TEXT NOT NULL,
11
+ created_by TEXT,
12
+ change_description TEXT,
13
+ published_at TEXT,
14
+ created_at TEXT DEFAULT (datetime('now')),
15
+ updated_at TEXT DEFAULT (datetime('now'))
16
+ )
17
+ `);try{this.db.exec(`ALTER TABLE ${this.versionsTableName} ADD COLUMN autosave INTEGER NOT NULL DEFAULT 0`);}catch{}this.db.exec(`CREATE INDEX IF NOT EXISTS idx_${this.versionsTableName}_doc ON ${this.versionsTableName}(collection_slug, document_id)`),this.db.exec(`CREATE INDEX IF NOT EXISTS idx_${this.versionsTableName}_status ON ${this.versionsTableName}(status)`),this.db.exec(`CREATE INDEX IF NOT EXISTS idx_${this.versionsTableName}_autosave ON ${this.versionsTableName}(autosave)`);}resolveCol(e,n){let a=n.replace(/^-/,""),o=L(this.db,e);if(!o.includes(a)){if(a==="created_at"&&o.includes("createdAt"))return '"createdAt"';if(a==="createdAt"&&o.includes("created_at"))return '"created_at"';if(a==="updated_at"&&o.includes("updatedAt"))return '"updatedAt"';if(a==="updatedAt"&&o.includes("updated_at"))return '"updated_at"'}return this.col(a)}col(e){return `"${e}"`}fieldToSQL(e){switch(e.type){case "text":case "email":case "password":case "textarea":case "color":case "icon":case "code":case "markdown":case "url":return this.col(e.name)+" TEXT";case "number":return this.col(e.name)+" REAL";case "checkbox":return this.col(e.name)+" INTEGER DEFAULT 0";case "date":return this.col(e.name)+" TEXT";case "select":case "radio":return this.col(e.name)+" TEXT";case "relationship":case "upload":return this.col(e.name)+" TEXT";case "json":case "richtext":case "array":case "group":case "blocks":return this.col(e.name)+" TEXT";default:return null}}parseGlobalsSlug(e){if(e.startsWith("_globals_")){let n=e.replace("_globals_","");return {isGlobal:true,globalSlug:n,tableName:`global_${n.replace(/-/g,"_")}`}}return {isGlobal:false,globalSlug:"",tableName:this.getTableNameFor(e)}}async find(e){let{collection:n,where:a={},sort:o,limit:i=10,page:t=1,tenantId:s,draft:r=false}=e,l=this.parseGlobalsSlug(n),c=l.isGlobal?this.globals.get(l.globalSlug):this.getCollection(n);this.ensureTable(c,l.tableName);let d=l.tableName,b=`SELECT * FROM ${d}`,u=[],f=[],p={...a};this.tenantContext&&c.tenantScoped&&(p=chunkVQ53TFYA_cjs.c({where:p},n,this.tenantContext,chunkVQ53TFYA_cjs.b).where||{});let E=c.fields.find(h=>h.name==="status"),m=E?.type==="select"&&Array.isArray(E.options)&&E.options.some(h=>h.value==="published");!r&&m&&(f.push("status = ?"),u.push("published")),s&&c.tenantScoped&&(f.push("tenant_id = ?"),u.push(s));for(let[h,y]of Object.entries(p)){if(h==="AND"||h==="OR")continue;let S=this.resolveCol(d,h);typeof y=="object"&&y!==null?(y.equals!==void 0&&(f.push(`${S} = ?`),u.push(y.equals)),y.in!==void 0&&(f.push(`${S} IN (${y.in.map(()=>"?").join(", ")})`),u.push(...y.in)),y.not_equals!==void 0&&(f.push(`${S} != ?`),u.push(y.not_equals))):(f.push(`${S} = ?`),u.push(y));}f.length>0&&(b+=` WHERE ${f.join(" AND ")}`);let g=o||"-createdAt",M=this.resolveCol(d,g),j=g.startsWith("-")?"DESC":"ASC";b+=` ORDER BY ${M} ${j}`;let V=b.replace("SELECT *","SELECT COUNT(*) as count"),C=this.db.prepare(V).get(...u)?.count||0;b+=" LIMIT ? OFFSET ?",u.push(i,(t-1)*i);let A=this.db.prepare(b).all(...u).map(h=>this.rowToDoc(h,c));return this.tenantContext&&!this.tenantContext.isSuperAdmin&&(A=A.filter(h=>chunkVQ53TFYA_cjs.d(h,n,this.tenantContext,chunkVQ53TFYA_cjs.b))),r&&(A=await Promise.all(A.map(async h=>{let y=this.db.prepare(`SELECT * FROM ${this.versionsTableName} WHERE collection_slug = ? AND document_id = ? AND tenant_id IS NULL ORDER BY version DESC LIMIT 1`).get(n,h.id);if(y){let S=y.data?JSON.parse(y.data):{};return chunkZOVH6QT5_cjs.a({...h,...S,status:h.status,_hasUnpublishedChanges:y.status==="draft"})}return h}))),A=A.map(h=>chunkZOVH6QT5_cjs.a(h)),{docs:A,totalDocs:C,limit:i,totalPages:Math.ceil(C/i),page:t,pagingCounter:(t-1)*i+1,hasPrevPage:t>1,hasNextPage:t<Math.ceil(C/i),prevPage:t>1?t-1:null,nextPage:t<Math.ceil(C/i)?t+1:null}}async findByID(e){let{collection:n,id:a,tenantId:o,draft:i=false}=e,t=this.parseGlobalsSlug(n),s=t.isGlobal?this.globals.get(t.globalSlug):this.getCollection(n);this.ensureTable(s,t.tableName);let l=`SELECT * FROM ${t.tableName} WHERE id = ?`,c=[a];if(this.tenantContext&&s.tenantScoped){let p={id:a,tenant_id:this.tenantContext.tenantId};if(!chunkVQ53TFYA_cjs.d(p,n,this.tenantContext,chunkVQ53TFYA_cjs.b))return null}let d=s.fields.find(p=>p.name==="status"),b=d?.type==="select"&&Array.isArray(d.options)&&d.options.some(p=>p.value==="published");!i&&b&&(l+=" AND status = ?",c.push("published")),o&&s.tenantScoped&&(l+=" AND tenant_id = ?",c.push(o));let u=this.db.prepare(l).get(...c);if(!u)return null;let f=this.rowToDoc(u,s);if(i){let p=this.db.prepare(`SELECT * FROM ${this.versionsTableName} WHERE collection_slug = ? AND document_id = ? AND tenant_id IS NULL ORDER BY version DESC LIMIT 1`).get(n,f.id);if(p){let E=p.data?JSON.parse(p.data):{};f={...f,...E,status:f.status,_hasUnpublishedChanges:p.status==="draft"};}}return chunkZOVH6QT5_cjs.a(f)}async create(e){let{collection:n,data:a,tenantId:o}=e,i=this.parseGlobalsSlug(n),t=i.isGlobal?this.globals.get(i.globalSlug):this.getCollection(n);this.ensureTable(t,i.tableName);let s=i.tableName,r=i.isGlobal?i.globalSlug:a.id||this.generateId(),l=this.prepareData(a,t);l.id=r;let c=new Date().toISOString();l.created_at=c,l.updated_at=c,o&&t.tenantScoped&&(l.tenant_id=o);let d=Object.keys(l),b=L(this.db,s),u={};for(let g of d)b.includes(g)&&(u[g]=l[g]);let f=Object.keys(u),p=f.map(g=>this.col(g)),E=f.map(()=>"?").join(", "),m=Object.values(u).map(g=>g!==null&&typeof g=="object"?JSON.stringify(g):g);return this.db.prepare(`INSERT OR REPLACE INTO ${s} (${p.join(", ")}) VALUES (${E})`).run(...m),this.ensureVersionsTable(),this.findByID({collection:n,id:r,tenantId:o,draft:true})}async update(e){let{collection:n,id:a,data:o,tenantId:i}=e,t=this.parseGlobalsSlug(n),s=t.isGlobal?this.globals.get(t.globalSlug):this.getCollection(n);this.ensureTable(s,t.tableName);let r=t.tableName,l=this.prepareData(o,s);l.updated_at=new Date().toISOString();let c=L(this.db,r),d={};for(let m of Object.keys(l))c.includes(m)&&(d[m]=l[m]);let u=Object.keys(d).map(m=>`${this.col(m)} = ?`).join(", "),f=Object.values(d).map(m=>m!==null&&typeof m=="object"?JSON.stringify(m):m),p=`UPDATE ${r} SET ${u} WHERE id = ?`,E=[...f,a];return i&&s.tenantScoped&&(p+=" AND tenant_id = ?",E.push(i)),this.db.prepare(p).run(...E),this.ensureVersionsTable(),this.findByID({collection:n,id:a,tenantId:i,draft:true})}async delete(e){let{collection:n,id:a,tenantId:o}=e,i=this.parseGlobalsSlug(n),t=i.isGlobal?this.globals.get(i.globalSlug):this.getCollection(n);this.ensureTable(t,i.tableName),this.ensureVersionsTable();let s=await this.findByID({collection:n,id:a,tenantId:o,draft:true});if(!s)throw new Error(`Document not found: ${n}/${a}`);let l=`DELETE FROM ${i.tableName} WHERE id = ?`,c=[a];return o&&t.tenantScoped&&(l+=" AND tenant_id = ?",c.push(o)),this.db.prepare(l).run(...c),s}async count(e){let{collection:n,tenantId:a}=e,o=this.parseGlobalsSlug(n),i=o.isGlobal?this.globals.get(o.globalSlug):this.getCollection(n);this.ensureTable(i,o.tableName);let s=`SELECT COUNT(*) as count FROM ${o.tableName}`,r=[];return a&&i.tenantScoped&&(s+=" WHERE tenant_id = ?",r.push(a)),this.db.prepare(s).get(...r)?.count||0}async findOne(e){let n=this.parseGlobalsSlug(e.collection);if(n.isGlobal){let o=this.globals.get(n.globalSlug);if(!o)throw new Error(`Global "${n.globalSlug}" not found in adapter`);this.ensureTable(o,n.tableName);let i=`SELECT * FROM ${n.tableName}`,t=[],s=[],r=o.fields.find(d=>d.name==="status"),l=r?.type==="select"&&Array.isArray(r.options)&&r.options.some(d=>d.value==="published");!e.draft&&o.versions&&l&&t.push("status = 'published'"),t.length>0&&(i+=` WHERE ${t.join(" AND ")}`),i+=" LIMIT 1";let c=this.db.prepare(i).get(...s);if(c){let d=this.rowToDoc(c,o);if(e.draft){let b=this.db.prepare(`SELECT * FROM ${this.versionsTableName} WHERE collection_slug = ? AND document_id = ? AND tenant_id IS NULL ORDER BY version DESC LIMIT 1`).get(e.collection,n.globalSlug);if(b){let u=b.data?JSON.parse(b.data):{};d={...d,...u,status:d.status,_hasUnpublishedChanges:b.status==="draft"};}}return d}return null}return (await this.find({...e,limit:1})).docs[0]||null}async findVersions(e){this.ensureVersionsTable();let{collection:n,documentId:a,tenantId:o,limit:i=20,page:t=1}=e,s=["collection_slug = ?","document_id = ?","autosave = 0"],r=[n,a];o?(s.push("tenant_id = ?"),r.push(o)):s.push("tenant_id IS NULL");let l=`WHERE ${s.join(" AND ")}`,d=this.db.prepare(`SELECT COUNT(*) as count FROM ${this.versionsTableName} ${l}`).get(...r)?.count||0,b=(t-1)*i;return {docs:this.db.prepare(`SELECT * FROM ${this.versionsTableName} ${l} ORDER BY version DESC LIMIT ? OFFSET ?`).all(...r,i,b).map(p=>this.rowToVersion(p)),totalDocs:d,limit:i,totalPages:Math.ceil(d/i),page:t,pagingCounter:(t-1)*i+1,hasPrevPage:t>1,hasNextPage:t<Math.ceil(d/i),prevPage:t>1?t-1:null,nextPage:t<Math.ceil(d/i)?t+1:null}}async findVersionByID(e){this.ensureVersionsTable();let n=this.db.prepare(`SELECT * FROM ${this.versionsTableName} WHERE id = ? AND collection_slug = ? LIMIT 1`).get(e.versionId,e.collection);return n?this.rowToVersion(n):null}async createVersion(e){this.ensureVersionsTable();let n=new Date().toISOString();if(e.autosave){let s=`SELECT * FROM ${this.versionsTableName} WHERE collection_slug = ? AND document_id = ? AND autosave = 1`,r=[e.collection,e.documentId];e.tenantId?(s+=" AND tenant_id = ?",r.push(e.tenantId)):s+=" AND tenant_id IS NULL",s+=" LIMIT 1";let l=this.db.prepare(s).get(...r);if(l){this.db.prepare(`UPDATE ${this.versionsTableName} SET data = ?, status = ?, updated_at = ? WHERE id = ?`).run(JSON.stringify(e.data),e.status,n,l.id);let c=await this.findVersionByID({collection:e.collection,versionId:l.id});if(c)return c}}let a=this.generateId(),i=(this.db.prepare(`SELECT version FROM ${this.versionsTableName} WHERE collection_slug = ? AND document_id = ? AND autosave = 0 ORDER BY version DESC LIMIT 1`).get(e.collection,e.documentId)?.version??0)+1;if(this.db.prepare(`INSERT INTO ${this.versionsTableName} (
18
+ id, collection_slug, document_id, tenant_id, version, status, autosave, data, created_by, change_description, published_at, created_at, updated_at
19
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(a,e.collection,e.documentId,e.tenantId??null,i,e.status,e.autosave?1:0,JSON.stringify(e.data),e.createdBy??null,e.changeDescription??null,e.status==="published"?n:null,n,n),!e.autosave){let r=this.collections.get(e.collection)?.versions?.maxPerDoc;r&&r>0&&await this.deleteVersions({collection:e.collection,documentId:e.documentId,keepLatest:r,tenantId:e.tenantId});}return await this.findVersionByID({collection:e.collection,versionId:a})}async updateLatestVersion(e){return this.createVersion({...e,autosave:true})}async deleteVersions(e){this.ensureVersionsTable();let{collection:n,documentId:a,keepLatest:o,tenantId:i}=e;if(o&&o>0){let t=this.db.prepare(`SELECT id, status, autosave FROM ${this.versionsTableName} WHERE collection_slug = ? AND document_id = ? ORDER BY version DESC`).all(n,a),s=0,r=[];for(let l of t)l.status==="published"||l.autosave===1||(s++,s>o&&r.push(l.id));for(let l of r)this.db.prepare(`DELETE FROM ${this.versionsTableName} WHERE id = ?`).run(l);}else {let t=`DELETE FROM ${this.versionsTableName} WHERE collection_slug = ? AND document_id = ?`,s=[n,a];i&&(t+=" AND tenant_id = ?",s.push(i)),this.db.prepare(t).run(...s);}}rowToVersion(e){return {id:String(e.id),collection:e.collection_slug,documentId:e.document_id,version:e.version,status:e.status,data:e.data?JSON.parse(e.data):{},createdBy:e.created_by??void 0,changeDescription:e.change_description??void 0,publishedAt:e.published_at??null,createdAt:e.created_at,updatedAt:e.updated_at}}prepareData(e,n){let a={},o=N(n.fields),i=(t,s)=>{let r=t;if(r.type==="json"||r.type==="richtext"||r.type==="array"||r.type==="group"||r.type==="blocks"||r.type==="list"||r.type==="relationship-block")return s!=null?JSON.stringify(s):null;if(r.type==="checkbox")return s?1:0;if(r.type==="number")return s!==null&&s!==""?Number(s):null;if(r.type==="upload"||r.type==="image"){if(s==null)return null;if(Array.isArray(s)){let l=s.map(c=>typeof c=="string"?c:typeof c=="object"?c.id||c._id||c:String(c));return JSON.stringify(l)}return typeof s=="string"?s:typeof s=="object"?JSON.stringify(s):String(s)}else if(t.type==="relationship"){if(s==null)return null;if(Array.isArray(s)){let l=s.map(c=>typeof c=="string"?c:typeof c=="object"?JSON.stringify({relationTo:t.relationTo,value:c.id||c}):String(c));return JSON.stringify(l)}return typeof s=="string"?s:typeof s=="object"?JSON.stringify({relationTo:t.relationTo,value:s.id||s}):String(s)}return s};for(let t of o){if(!t.name||t.name==="id"||n.fields.some(l=>l.type==="tabs"&&l.name&&"tabs"in l&&l.tabs.some(c=>c.fields.some(d=>d.name===t.name))))continue;let r=e[t.name];r!==void 0&&(a[t.name]=i(t,r));}for(let t of n.fields)if(t.type==="tabs"&&"tabs"in t&&t.name){let s=e[t.name];if(s&&typeof s=="object"){for(let r of t.tabs)for(let l of r.fields)if(l.name&&l.name!=="id"){let c=s[l.name];c!==void 0&&(a[l.name]=i(l,c));}}}return a}rowToDoc(e,n){let a={id:e.id};for(let o of N(n.fields)){if(!o.name||o.name==="id")continue;let i=o,t=e[i.name];if(i.type==="json"||i.type==="richtext"||i.type==="array"||i.type==="group"||i.type==="blocks"||i.type==="list"||i.type==="relationship-block")try{t=t?JSON.parse(t):null;}catch{t=null;}if(i.type==="blocks"&&t&&Array.isArray(t)){let s=i.blocks||[];t=w(t,s);}if(o.type==="checkbox"&&(t=!!t),o.type==="date"&&t)try{let s=new Date(t);isNaN(s.getTime())?(console.warn(`[LocalAdapter] Invalid date value for field "${o.name}":`,t),t=null):t=s.toISOString();}catch{t=null;}if((o.type==="upload"||o.type==="image")&&t)try{let s=JSON.parse(t);Array.isArray(s)?t=s.map(r=>typeof r=="object"&&r!==null?r:{id:r}):t=typeof s=="object"?s:{id:s};}catch{t={id:t};}if(o.type==="relationship"&&t)try{let s=JSON.parse(t);Array.isArray(s),t=s;}catch{t={relationTo:Array.isArray(o.relationTo)?o.relationTo[0]:o.relationTo,value:t};}a[o.name]=t;}for(let o of n.fields)if(!(!o.name||o.name==="id"||o.name==="row"||o.name==="collapsible")&&o.type==="tabs"&&"tabs"in o){let i={};for(let t of o.tabs)for(let s of t.fields)s.name&&s.name!=="id"&&(i[s.name]=P(e,s));a[o.name]=i;}if(n.timestamps){let o=e.createdAt||e.created_at,i=e.updatedAt||e.updated_at;if(o)try{let t=new Date(o);isNaN(t.getTime())||(a.createdAt=t.toISOString());}catch{}if(i)try{let t=new Date(i);isNaN(t.getTime())||(a.updatedAt=t.toISOString());}catch{}}n.tenantScoped&&(a.tenantId=e.tenant_id),a.status=e.status??"published",a.hasDraft=e.hasDraft?!!e.hasDraft:false;for(let o of Object.keys(a))/^\d+$/.test(o)&&delete a[o];return a}generateId(){let e=Date.now().toString(16).padStart(12,"0"),n=crypto.randomBytes(6).toString("hex");return e+n}getMediaById(e){try{let n=this.getTableNameFor("media"),a=this.db.prepare(`SELECT id, url, thumbnail_url FROM ${n} WHERE id = ?`).get(e);if(a)return {id:a.id,url:a.url,thumbnailUrl:a.thumbnail_url||a.url}}catch{}return null}getTableNameFor(e){return e.replace(/-/g,"_")}async migrate(){for(let e of this.collections.values())this.ensureTable(e);}async rollback(){}async transaction(e){return new Promise((n,a)=>{let o=this.db.transaction(async()=>e({db:this.db}));try{let i=o();n(i);}catch(i){a(i);}})}getDatabase(){return this.db}exec(e){this.db.exec(e);}prepare(e){return this.db.prepare(e)}};function B(T){return new O(T||{})}exports.a=O;exports.b=B;
@@ -1,5 +1,5 @@
1
- 'use strict';var chunkKCHPADCH_cjs=require('./chunk-KCHPADCH.cjs'),chunkLY7N3UHH_cjs=require('./chunk-LY7N3UHH.cjs'),chunk7ACHOBWY_cjs=require('./chunk-7ACHOBWY.cjs'),chunkBCEE4NBZ_cjs=require('./chunk-BCEE4NBZ.cjs'),chunkVRZC4TTF_cjs=require('./chunk-VRZC4TTF.cjs'),chunkVQ53TFYA_cjs=require('./chunk-VQ53TFYA.cjs'),chunkF4ITQ6XQ_cjs=require('./chunk-F4ITQ6XQ.cjs'),chunkZOVH6QT5_cjs=require('./chunk-ZOVH6QT5.cjs'),chunkBUNLC3II_cjs=require('./chunk-BUNLC3II.cjs'),crypto=require('crypto'),promises=require('fs/promises'),path=require('path'),module$1=require('module');chunkBUNLC3II_cjs.h();function D(f){if(typeof f!="string")return f;let t=f.replace(/-/g,"").toLowerCase();return t.length===32?`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`:f}function L(f,t="postgres"){switch(f.type){case "text":case "email":case "password":case "color":case "icon":return t==="sqlite"?"text":"varchar";case "textarea":case "code":case "markdown":case "secret":return "text";case "number":return f.integer?"integer":"decimal";case "checkbox":return "boolean";case "date":return "timestamp";case "select":case "radio":return t==="sqlite"?"text":"varchar";case "richtext":case "json":case "array":case "group":case "blocks":case "row":case "collapsible":case "tabs":return "jsonb";case "relationship":return t==="sqlite"?"text":"varchar";case "upload":return "jsonb";default:return "jsonb"}}function Se(f,t="postgres"){let i=f.slug.replace(/-/g,"_"),e=[];e.push(`export const ${i} = pgTable('${i}', {`),e.push(" id: uuid('id').primaryKey().defaultRandom(),");for(let s of f.fields){if(s.name==="id"||s.type==="password")continue;let n=L(s,t),r=s.required,a=` ${s.name}: pg.${n}('${s.name}')`;s.unique&&(a+=".unique()"),r||(a+=".nullable()"),s.defaultValue!==void 0&&(typeof s.defaultValue=="string"?a+=`.default('${s.defaultValue}')`:typeof s.defaultValue=="boolean"?a+=`.default(${s.defaultValue})`:a+=`.default(sql\`${JSON.stringify(s.defaultValue)}\`)`),a+=",",e.push(a);}return f.timestamps&&(e.push(" createdAt: pg.timestamp('created_at').defaultNow(),"),e.push(" updatedAt: pg.timestamp('updated_at').defaultNow(),")),e.push(` status: ${t==="sqlite"?"sqlite":"pg"}.varchar('status').default('draft'),`),e.push(` hasDraft: ${t==="sqlite"?"sqlite":"pg"}.boolean('hasDraft').default(false),`),e.push("});"),e.join(`
2
- `)}function le(f,t){return Array.isArray(f)?f.map(i=>{if(!i||typeof i!="object")return i;let e=i.data?{...i.data}:void 0;if(!e)return i;let s=t.find(n=>n.slug===i.type||n.slug===i.slug);if(!s||!Array.isArray(s.fields))return i;for(let n of s.fields){if(n.name&&(n.type==="upload"||n.type==="image")&&e[n.name]){let r=e[n.name];Array.isArray(r)?e[n.name]=r.map(a=>typeof a=="string"?{id:a}:a):typeof r=="string"&&(e[n.name]={id:r});}if(n.type==="blocks"&&n.name&&e[n.name]){let r=n.blocks||[];e[n.name]=le(e[n.name],r);}}return {...i,data:e}}):f}var M=class extends chunkVQ53TFYA_cjs.a{client;schema;_schemaEnsured=false;dialect;connectionString;versionsTableReady=false;rawClient;constructor(t){if(super(),this.schema=t.schema||{},t.connectionString){this.connectionString=t.connectionString;let i=t.connectionString.toLowerCase();i.startsWith("postgres://")||i.startsWith("postgresql://")?this.dialect="postgres":i.includes(".db")||i.includes("sqlite")||i.includes("file:")?this.dialect="sqlite":this.dialect=t.type||"postgres";}else this.rawClient=t.client,this.client=t.client,this.dialect=t.type||"sqlite";}prepareData(t,i){let e=super.prepareData(t,i);e.createdAt&&typeof e.createdAt=="string"&&(e.createdAt=new Date(e.createdAt)),e.updatedAt&&typeof e.updatedAt=="string"&&(e.updatedAt=new Date(e.updatedAt));for(let s of i.fields)if(s.type==="date"&&s.name){let n=e[s.name];n&&typeof n=="string"&&(e[s.name]=new Date(n));}for(let s of i.fields){let r=L(s,this.dialect)==="jsonb";if(s.type==="tabs"&&"tabs"in s&&s.name){let a=t[s.name];if(a&&typeof a=="object"){let o={};for(let[c,d]of Object.entries(a)){let u=s.tabs.flatMap(g=>g.fields).find(g=>g.name===c);(u?.type==="upload"||u?.type==="image"||u?.type==="list"||u?.type==="relationship-block")&&d?o[c]=Array.isArray(d)||typeof d=="object"?JSON.stringify(d):d:o[c]=d;}e[s.name]=this.dialect==="sqlite"||!r?JSON.stringify(o):o;}}else if(r&&s.name&&t[s.name]!==void 0&&t[s.name]!==null)e[s.name]=this.dialect==="sqlite"?JSON.stringify(t[s.name]):t[s.name];else if((s.type==="upload"||s.type==="image"||s.type==="list"||s.type==="relationship-block")&&s.name){let a=t[s.name];a!=null&&(e[s.name]=this.dialect==="sqlite"||!r?typeof a=="string"?a:JSON.stringify(a):a);}}for(let s of i.fields)if(s.name&&e[s.name]===""){let n=L(s,this.dialect);(n==="timestamp"||n==="jsonb"||n==="decimal"||n==="integer"||n==="numeric"||n==="boolean")&&(e[s.name]=null);}return e}async connect(){if(this.connectionString&&!this.client){if(this.dialect==="postgres"){let t,i;try{t=(await import('./src-6LAUXXDM.cjs')).default,i=(await import('./postgres-js-3Y54EXVQ.cjs')).drizzle;}catch{chunkF4ITQ6XQ_cjs.a(["postgres","drizzle-orm"]),t=(await import('./src-6LAUXXDM.cjs')).default,i=(await import('./postgres-js-3Y54EXVQ.cjs')).drizzle;}let e=t(this.connectionString,{onnotice:()=>{}});this.client=i(e,{schema:this.schema});}else if(this.dialect==="sqlite"){let t,i;try{t=(await import('better-sqlite3')).default,i=(await import('./better-sqlite3-5IISPX34.cjs')).drizzle;}catch{chunkF4ITQ6XQ_cjs.a(["better-sqlite3","drizzle-orm"]),t=(await import('better-sqlite3')).default,i=(await import('./better-sqlite3-5IISPX34.cjs')).drizzle;}let e=new t(this.connectionString.replace("file:",""));this.client=i(e,{schema:this.schema});}}if(this.rawClient&&typeof this.rawClient.prepare=="function"&&typeof this.client?.select!="function"){let{drizzle:t}=await import('./d1-5ZQJOFDX.cjs');this.client=t(this.rawClient,{schema:this.schema});}this.connected=true;}async init(t,i=[]){if(await super.init(t,i),(this.connectionString&&!this.client||this.rawClient&&typeof this.client?.select!="function")&&await this.connect(),this.client&&!this._schemaEnsured){for(let s of t){let n=this.getTableName(s.slug);this.schema[n]||(this.schema[n]=this.createTableFromConfig(s));}await this.ensureCollectionTables(t);let e=i.map(s=>({slug:`_globals_${s.slug}`,fields:s.fields,label:s.label}));for(let s of e){let n=this.getTableName(s.slug);this.schema[n]||(this.schema[n]=this.createTableFromConfig(s,true)),this.collections.has(s.slug)||this.collections.set(s.slug,s);}await this.ensureCollectionTables(e),this._schemaEnsured=true;}}createTableFromConfig(t,i=false){let e=this.getTableName(t.slug),s={id:i?chunkVRZC4TTF_cjs.ia("id").primaryKey():chunkVRZC4TTF_cjs.oa("id").primaryKey().defaultRandom()};for(let n of t.fields){if(!n.name||n.name==="id"||n.type==="password")continue;let r=L(n,this.dialect),a=n.name.replace(/-/g,"_"),o=a.replace(/([A-Z])/g,"_$1").toLowerCase(),c;if(this.dialect==="sqlite")switch(r){case "varchar":case "text":c=chunk7ACHOBWY_cjs.c(o);break;case "integer":c=chunk7ACHOBWY_cjs.a(o);break;case "decimal":case "numeric":c=chunk7ACHOBWY_cjs.b(o);break;case "boolean":c=chunk7ACHOBWY_cjs.a(o,{mode:"boolean"});break;case "timestamp":c=chunk7ACHOBWY_cjs.c(o);break;case "jsonb":c=chunk7ACHOBWY_cjs.c(o);break;default:c=chunk7ACHOBWY_cjs.c(o);}else switch(r){case "varchar":c=chunkVRZC4TTF_cjs.pa(o,{length:255});break;case "integer":c=chunkVRZC4TTF_cjs.ca(o);break;case "decimal":c=chunkVRZC4TTF_cjs.ha(o);break;case "boolean":c=chunkVRZC4TTF_cjs.$(o);break;case "timestamp":c=chunkVRZC4TTF_cjs.ma(o);break;case "jsonb":c=chunkVRZC4TTF_cjs.fa(o);break;default:c=chunkVRZC4TTF_cjs.ia(o);}n.required||(c=c.default(null)),s[a]=c;}return s.createdAt||(s.createdAt=this.dialect==="sqlite"?chunk7ACHOBWY_cjs.c("created_at").default(new Date().toISOString()):chunkVRZC4TTF_cjs.ma("created_at").defaultNow()),s.updatedAt||(s.updatedAt=this.dialect==="sqlite"?chunk7ACHOBWY_cjs.c("updated_at").default(new Date().toISOString()):chunkVRZC4TTF_cjs.ma("updated_at").defaultNow()),e!=="users"&&e!=="audit_logs"&&(s.status||(s.status=this.dialect==="sqlite"?chunk7ACHOBWY_cjs.c("status").default("draft"):chunkVRZC4TTF_cjs.pa("status",{length:20}).default("draft")),s.hasDraft||(s.hasDraft=this.dialect==="sqlite"?chunk7ACHOBWY_cjs.a("hasDraft",{mode:"boolean"}).default(false):chunkVRZC4TTF_cjs.$("hasDraft").default(false))),this.dialect==="sqlite"?chunk7ACHOBWY_cjs.e(e,s):chunkVRZC4TTF_cjs.ra(e,s)}async ensureCollectionTables(t){let i=[];for(let e of t){let s=e.slug.startsWith("_globals_"),n=this.getTableName(e.slug),r=this.generateCreateColumns(e),a=e.fields.some(u=>u.name==="createdAt"),o=e.fields.some(u=>u.name==="updatedAt"),c=e.fields.some(u=>u.name==="status"),d=e.fields.some(u=>u.name==="hasDraft");if(this.dialect==="postgres"){let u=s?'"id" TEXT PRIMARY KEY':'"id" UUID PRIMARY KEY DEFAULT gen_random_uuid()';i.push(`
1
+ 'use strict';var chunk7ACHOBWY_cjs=require('./chunk-7ACHOBWY.cjs'),chunkSOCBJPYB_cjs=require('./chunk-SOCBJPYB.cjs'),chunkBCEE4NBZ_cjs=require('./chunk-BCEE4NBZ.cjs'),chunkLY7N3UHH_cjs=require('./chunk-LY7N3UHH.cjs'),chunkVRZC4TTF_cjs=require('./chunk-VRZC4TTF.cjs'),chunkVQ53TFYA_cjs=require('./chunk-VQ53TFYA.cjs'),chunkF4ITQ6XQ_cjs=require('./chunk-F4ITQ6XQ.cjs'),chunkZOVH6QT5_cjs=require('./chunk-ZOVH6QT5.cjs'),chunkBUNLC3II_cjs=require('./chunk-BUNLC3II.cjs'),crypto=require('crypto'),promises=require('fs/promises'),path=require('path'),module$1=require('module');chunkBUNLC3II_cjs.h();var x;function Ae(){return x||(x=module$1.createRequire("file:///")("node:sqlite").DatabaseSync,x)}function Ee(){return process.env.DB_TYPE==="postgres"?"postgres":"sqlite"}function de(){return crypto.randomBytes(16).toString("hex")}async function Se(){let f=Ee();if(f==="sqlite"){let r=path.resolve(process.cwd(),"data","kyro.db");await promises.mkdir(path.dirname(r),{recursive:true});let a=new(Ae())(r);return a.exec("PRAGMA journal_mode = WAL"),{db:a,dialect:f,genId:de}}let t=process.env.DATABASE_URL||"postgresql://postgres:postgres@localhost:5432/kyro_cms",i=parseInt(process.env.DB_POOL_MAX||"10",10),e=process.env.DB_SSL==="true",s=chunkLY7N3UHH_cjs.a(t,{max:i,ssl:e?"require":false,onnotice:()=>{}});return {db:chunkSOCBJPYB_cjs.f(s),dialect:f,genId:de}}async function Ie(f,t){}async function $e(f){let{roles:t}=await import('./schema-RT6WSUYC.cjs');await f.insert(t).values({name:"super_admin",level:100,inherits:[],description:"Full system access across all tenants",isSystem:true}).onConflictDoNothing();}chunkBUNLC3II_cjs.h();function w(f,t="postgres"){switch(f.type){case "text":case "email":case "password":case "color":case "icon":return t==="sqlite"?"text":"varchar";case "textarea":case "code":case "markdown":case "secret":return "text";case "number":return f.integer?"integer":"decimal";case "checkbox":return "boolean";case "date":return "timestamp";case "select":case "radio":return t==="sqlite"?"text":"varchar";case "richtext":case "json":case "array":case "group":case "blocks":case "row":case "collapsible":case "tabs":return "jsonb";case "relationship":return t==="sqlite"?"text":"varchar";case "upload":return "jsonb";default:return "jsonb"}}function we(f,t="postgres"){let i=f.slug.replace(/-/g,"_"),e=[];e.push(`export const ${i} = pgTable('${i}', {`),e.push(" id: uuid('id').primaryKey().defaultRandom(),");for(let s of f.fields){if(s.name==="id"||s.type==="password")continue;let n=w(s,t),r=s.required,a=` ${s.name}: pg.${n}('${s.name}')`;s.unique&&(a+=".unique()"),r||(a+=".nullable()"),s.defaultValue!==void 0&&(typeof s.defaultValue=="string"?a+=`.default('${s.defaultValue}')`:typeof s.defaultValue=="boolean"?a+=`.default(${s.defaultValue})`:a+=`.default(sql\`${JSON.stringify(s.defaultValue)}\`)`),a+=",",e.push(a);}return f.timestamps&&(e.push(" createdAt: pg.timestamp('created_at').defaultNow(),"),e.push(" updatedAt: pg.timestamp('updated_at').defaultNow(),")),e.push(` status: ${t==="sqlite"?"sqlite":"pg"}.varchar('status').default('draft'),`),e.push(` hasDraft: ${t==="sqlite"?"sqlite":"pg"}.boolean('hasDraft').default(false),`),e.push("});"),e.join(`
2
+ `)}function M(f,t){return Array.isArray(f)?f.map(i=>{if(!i||typeof i!="object")return i;let e=i.data?{...i.data}:void 0;if(!e)return i;let s=t.find(n=>n.slug===i.type||n.slug===i.slug);if(!s||!Array.isArray(s.fields))return i;for(let n of s.fields){if(n.name&&(n.type==="upload"||n.type==="image")&&e[n.name]){let r=e[n.name];Array.isArray(r)?e[n.name]=r.map(a=>typeof a=="string"?{id:a}:a):typeof r=="string"&&(e[n.name]={id:r});}if(n.type==="blocks"&&n.name&&e[n.name]){let r=n.blocks||[];e[n.name]=M(e[n.name],r);}}return {...i,data:e}}):f}chunkBUNLC3II_cjs.h();function _(f){if(typeof f!="string")return f;let t=f.replace(/-/g,"").toLowerCase();return t.length===32?`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`:f}var P=class extends chunkVQ53TFYA_cjs.a{client;schema;_schemaEnsured=false;dialect;connectionString;versionsTableReady=false;rawClient;constructor(t){if(super(),this.schema=t.schema||{},t.connectionString){this.connectionString=t.connectionString;let i=t.connectionString.toLowerCase();i.startsWith("postgres://")||i.startsWith("postgresql://")?this.dialect="postgres":i.includes(".db")||i.includes("sqlite")||i.includes("file:")?this.dialect="sqlite":this.dialect=t.type||"postgres";}else this.rawClient=t.client,this.client=t.client,this.dialect=t.type||"sqlite";}prepareData(t,i){let e=super.prepareData(t,i);e.createdAt&&typeof e.createdAt=="string"&&(e.createdAt=new Date(e.createdAt)),e.updatedAt&&typeof e.updatedAt=="string"&&(e.updatedAt=new Date(e.updatedAt));for(let s of i.fields)if(s.type==="date"&&s.name){let n=e[s.name];n&&typeof n=="string"&&(e[s.name]=new Date(n));}for(let s of i.fields){let r=w(s,this.dialect)==="jsonb";if(s.type==="tabs"&&"tabs"in s&&s.name){let a=t[s.name];if(a&&typeof a=="object"){let o={};for(let[c,d]of Object.entries(a)){let u=s.tabs.flatMap(g=>g.fields).find(g=>g.name===c);(u?.type==="upload"||u?.type==="image"||u?.type==="list"||u?.type==="relationship-block")&&d?o[c]=Array.isArray(d)||typeof d=="object"?JSON.stringify(d):d:o[c]=d;}e[s.name]=this.dialect==="sqlite"||!r?JSON.stringify(o):o;}}else if(r&&s.name&&t[s.name]!==void 0&&t[s.name]!==null)e[s.name]=this.dialect==="sqlite"?JSON.stringify(t[s.name]):t[s.name];else if((s.type==="upload"||s.type==="image"||s.type==="list"||s.type==="relationship-block")&&s.name){let a=t[s.name];a!=null&&(e[s.name]=this.dialect==="sqlite"||!r?typeof a=="string"?a:JSON.stringify(a):a);}}for(let s of i.fields)if(s.name&&e[s.name]===""){let n=w(s,this.dialect);(n==="timestamp"||n==="jsonb"||n==="decimal"||n==="integer"||n==="numeric"||n==="boolean")&&(e[s.name]=null);}return e}async connect(){if(this.connectionString&&!this.client){if(this.dialect==="postgres"){let t,i;try{t=(await import('./src-6LAUXXDM.cjs')).default,i=(await import('./postgres-js-GXZX3AGZ.cjs')).drizzle;}catch{chunkF4ITQ6XQ_cjs.a(["postgres","drizzle-orm"]),t=(await import('./src-6LAUXXDM.cjs')).default,i=(await import('./postgres-js-GXZX3AGZ.cjs')).drizzle;}let e=t(this.connectionString,{onnotice:()=>{}});this.client=i(e,{schema:this.schema});}else if(this.dialect==="sqlite"){let t,i;try{t=(await import('better-sqlite3')).default,i=(await import('./better-sqlite3-5IISPX34.cjs')).drizzle;}catch{chunkF4ITQ6XQ_cjs.a(["better-sqlite3","drizzle-orm"]),t=(await import('better-sqlite3')).default,i=(await import('./better-sqlite3-5IISPX34.cjs')).drizzle;}let e=new t(this.connectionString.replace("file:",""));this.client=i(e,{schema:this.schema});}}if(this.rawClient&&typeof this.rawClient.prepare=="function"&&typeof this.client?.select!="function"){let{drizzle:t}=await import('./d1-5ZQJOFDX.cjs');this.client=t(this.rawClient,{schema:this.schema});}this.connected=true;}async init(t,i=[]){if(await super.init(t,i),(this.connectionString&&!this.client||this.rawClient&&typeof this.client?.select!="function")&&await this.connect(),this.client&&!this._schemaEnsured){for(let s of t){let n=this.getTableName(s.slug);this.schema[n]||(this.schema[n]=this.createTableFromConfig(s));}await this.ensureCollectionTables(t);let e=i.map(s=>({slug:`_globals_${s.slug}`,fields:s.fields,label:s.label}));for(let s of e){let n=this.getTableName(s.slug);this.schema[n]||(this.schema[n]=this.createTableFromConfig(s,true)),this.collections.has(s.slug)||this.collections.set(s.slug,s);}await this.ensureCollectionTables(e),this._schemaEnsured=true;}}createTableFromConfig(t,i=false){let e=this.getTableName(t.slug),s={id:i?chunkVRZC4TTF_cjs.ia("id").primaryKey():chunkVRZC4TTF_cjs.oa("id").primaryKey().defaultRandom()};for(let n of t.fields){if(!n.name||n.name==="id"||n.type==="password")continue;let r=w(n,this.dialect),a=n.name.replace(/-/g,"_"),o=a.replace(/([A-Z])/g,"_$1").toLowerCase(),c;if(this.dialect==="sqlite")switch(r){case "varchar":case "text":c=chunk7ACHOBWY_cjs.c(o);break;case "integer":c=chunk7ACHOBWY_cjs.a(o);break;case "decimal":case "numeric":c=chunk7ACHOBWY_cjs.b(o);break;case "boolean":c=chunk7ACHOBWY_cjs.a(o,{mode:"boolean"});break;case "timestamp":c=chunk7ACHOBWY_cjs.c(o);break;case "jsonb":c=chunk7ACHOBWY_cjs.c(o);break;default:c=chunk7ACHOBWY_cjs.c(o);}else switch(r){case "varchar":c=chunkVRZC4TTF_cjs.pa(o,{length:255});break;case "integer":c=chunkVRZC4TTF_cjs.ca(o);break;case "decimal":c=chunkVRZC4TTF_cjs.ha(o);break;case "boolean":c=chunkVRZC4TTF_cjs.$(o);break;case "timestamp":c=chunkVRZC4TTF_cjs.ma(o);break;case "jsonb":c=chunkVRZC4TTF_cjs.fa(o);break;default:c=chunkVRZC4TTF_cjs.ia(o);}n.required||(c=c.default(null)),s[a]=c;}return s.createdAt||(s.createdAt=this.dialect==="sqlite"?chunk7ACHOBWY_cjs.c("created_at").default(new Date().toISOString()):chunkVRZC4TTF_cjs.ma("created_at").defaultNow()),s.updatedAt||(s.updatedAt=this.dialect==="sqlite"?chunk7ACHOBWY_cjs.c("updated_at").default(new Date().toISOString()):chunkVRZC4TTF_cjs.ma("updated_at").defaultNow()),e!=="users"&&e!=="audit_logs"&&(s.status||(s.status=this.dialect==="sqlite"?chunk7ACHOBWY_cjs.c("status").default("draft"):chunkVRZC4TTF_cjs.pa("status",{length:20}).default("draft")),s.hasDraft||(s.hasDraft=this.dialect==="sqlite"?chunk7ACHOBWY_cjs.a("hasDraft",{mode:"boolean"}).default(false):chunkVRZC4TTF_cjs.$("hasDraft").default(false))),this.dialect==="sqlite"?chunk7ACHOBWY_cjs.e(e,s):chunkVRZC4TTF_cjs.ra(e,s)}async ensureCollectionTables(t){let i=[];for(let e of t){let s=e.slug.startsWith("_globals_"),n=this.getTableName(e.slug),r=this.generateCreateColumns(e),a=e.fields.some(u=>u.name==="createdAt"),o=e.fields.some(u=>u.name==="updatedAt"),c=e.fields.some(u=>u.name==="status"),d=e.fields.some(u=>u.name==="hasDraft");if(this.dialect==="postgres"){let u=s?'"id" TEXT PRIMARY KEY':'"id" UUID PRIMARY KEY DEFAULT gen_random_uuid()';i.push(`
3
3
  CREATE TABLE IF NOT EXISTS "${n}" (
4
4
  ${u},
5
5
  ${r}
@@ -18,27 +18,27 @@
18
18
  ${d?"":'"hasDraft" INTEGER DEFAULT 0'}
19
19
  )
20
20
  `);}if(i.length>0)if(this.dialect==="postgres")await this.executeRaw(chunkVRZC4TTF_cjs.J.raw(i.join(`;
21
- `)));else for(let e of i)await this.executeRaw(chunkVRZC4TTF_cjs.J.raw(e));for(let e of t){let s=this.getTableName(e.slug);s==="users"||s==="audit_logs"||await this.syncTableColumns(e,s);}}getColumnSqlDefinition(t,i){let e=L(t,i),s=t.name.replace(/-/g,"_").replace(/([A-Z])/g,"_$1").toLowerCase(),n=this.columnSqlType(e,i);return `"${s}" ${n} DEFAULT NULL`}columnSqlType(t,i){if(i==="sqlite")switch(t){case "varchar":return "TEXT";case "text":return "TEXT";case "integer":return "INTEGER";case "decimal":case "numeric":return "NUMERIC";case "boolean":return "INTEGER";case "timestamp":return "TEXT";case "jsonb":return "TEXT";default:return "TEXT"}switch(t){case "varchar":return "VARCHAR(255)";case "text":return "TEXT";case "integer":return "INTEGER";case "decimal":case "numeric":return "DECIMAL";case "boolean":return "BOOLEAN";case "timestamp":return "TIMESTAMP";case "jsonb":return "JSONB";default:return "TEXT"}}getExpectedColumnDefs(t,i){let e={},s=t.slug.startsWith("_globals_"),n=t.fields.some(c=>c.name==="createdAt"),r=t.fields.some(c=>c.name==="updatedAt"),a=t.fields.some(c=>c.name==="status"),o=t.fields.some(c=>c.name==="hasDraft");this.dialect==="postgres"?(e.id=s?'"id" TEXT PRIMARY KEY':'"id" UUID PRIMARY KEY DEFAULT gen_random_uuid()',n||(e.created_at='"created_at" TIMESTAMP DEFAULT NULL'),r||(e.updated_at='"updated_at" TIMESTAMP DEFAULT NULL'),a||(e.status='"status" VARCHAR(20) DEFAULT NULL'),o||(e.hasDraft='"hasDraft" BOOLEAN DEFAULT NULL')):(e.id='"id" TEXT PRIMARY KEY',n||(e.created_at='"created_at" TEXT DEFAULT NULL'),r||(e.updated_at='"updated_at" TEXT DEFAULT NULL'),a||(e.status='"status" TEXT DEFAULT NULL'),o||(e.hasDraft='"hasDraft" INTEGER DEFAULT NULL'));for(let c of t.fields){if(!c.name||c.name==="id")continue;let d=this.getColumnSqlDefinition(c,this.dialect),u=c.name.replace(/-/g,"_").replace(/([A-Z])/g,"_$1").toLowerCase();e[u]=d;}return e}async syncTableColumns(t,i){let e;try{if(this.dialect==="postgres"){let r=await this.executeRaw(chunkVRZC4TTF_cjs.J`SELECT column_name, data_type, character_maximum_length FROM information_schema.columns WHERE table_name = ${i}`);e=new Map(r.map(a=>[a.column_name,{type:a.data_type,maxLen:a.character_maximum_length}]));}else {let r=await this.executeRaw(chunkVRZC4TTF_cjs.J`PRAGMA table_info("${chunkVRZC4TTF_cjs.J.raw(i)}")`);e=new Map(r.map(a=>[a.name,{type:a.type,maxLen:null}]));}}catch{return}let s=this.getExpectedColumnDefs(t,i),n=Object.keys(s).filter(r=>!e.has(r));if(n.length>0){let r=n.map(a=>`ALTER TABLE "${i}" ADD COLUMN ${s[a]}`);await this.executeRaw(chunkVRZC4TTF_cjs.J.raw(r.join(`;
22
- `)));}if(this.dialect==="postgres")for(let r of t.fields){if(!r.name||r.name==="id")continue;let a=L(r,this.dialect),o=r.name.replace(/-/g,"_").replace(/([A-Z])/g,"_$1").toLowerCase(),c=e.get(o);!c||c.type!=="character varying"||(a==="text"?await this.executeRaw(chunkVRZC4TTF_cjs.J.raw(`ALTER TABLE "${i}" ALTER COLUMN "${o}" TYPE TEXT`)):a==="jsonb"&&(await this.executeRaw(chunkVRZC4TTF_cjs.J.raw(`ALTER TABLE "${i}" ALTER COLUMN "${o}" DROP DEFAULT`)),await this.executeRaw(chunkVRZC4TTF_cjs.J.raw(`ALTER TABLE "${i}" ALTER COLUMN "${o}" TYPE JSONB USING (CASE WHEN "${o}" IS NULL THEN NULL WHEN "${o}"::text ~ '^\\s*\\{' THEN "${o}"::jsonb ELSE jsonb_build_object('id', "${o}"::text) END)`))));}}generateCreateColumns(t){let i=[];for(let e of t.fields){if(!e.name||e.name==="id")continue;let s=L(e,this.dialect),n=e.name.replace(/-/g,"_").replace(/([A-Z])/g,"_$1").toLowerCase(),r=e.required?"NOT NULL":"DEFAULT NULL",a;if(this.dialect==="sqlite")switch(s){case "varchar":case "text":a=`TEXT ${r}`;break;case "integer":a=`INTEGER ${r}`;break;case "decimal":case "numeric":a=`NUMERIC ${r}`;break;case "boolean":a=`INTEGER ${r}`;break;case "timestamp":a=`TEXT ${r}`;break;case "jsonb":a=`TEXT ${r}`;break;default:a=`TEXT ${r}`;}else switch(s){case "varchar":a=`VARCHAR(255) ${r}`;break;case "integer":a=`INTEGER ${r}`;break;case "decimal":a=`DECIMAL ${r}`;break;case "boolean":a=`BOOLEAN ${r}`;break;case "timestamp":a=`TIMESTAMP ${r}`;break;case "jsonb":a=`JSONB ${r}`;break;default:a=`TEXT ${r}`;}i.push(`"${n}" ${a}`);}return i.join(`,
23
- `)+(i.length>0?",":"")}async disconnect(){this.connected=false;}async find(t){let{collection:i,where:e={},sort:s,limit:n=10,page:r=1,tenantId:a,select:o,draft:c}=t,d=this.getCollection(i),u=this.getTable(i),m={...e};this.tenantContext&&d.tenantScoped&&(m=chunkVQ53TFYA_cjs.c({where:m},i,this.tenantContext,chunkVQ53TFYA_cjs.b).where||{});let g=this.buildWhereClause(m,d,u,a),y=d.fields.find(h=>h.name==="status"),p=y?.type==="select"&&Array.isArray(y.options)&&y.options.some(h=>h.value==="published");!c&&u.status&&p&&g.push(chunkBCEE4NBZ_cjs.n(u.status,"published"));let b=this.parseSort(s),_=!c&&u.status&&p?{...m,status:"published"}:m,ue=await this.count({collection:i,where:_,tenantId:a}),fe=(r-1)*n,P=[];try{let h=u[b.field]||u.createdAt||u.id,R=b.direction==="asc"?h:chunkBCEE4NBZ_cjs.M(h),A=this.client.select().from(u);g.length>0&&(A=A.where(chunkBCEE4NBZ_cjs.p(...g))),P=await A.orderBy(R).limit(n).offset(fe);}catch(h){console.error("[DrizzleAdapter] Query error:",h);}let N=P.map(h=>this.processResult(h,d));return this.tenantContext&&!this.tenantContext.isSuperAdmin&&(N=N.filter(h=>chunkVQ53TFYA_cjs.d(h,i,this.tenantContext,chunkVQ53TFYA_cjs.b))),c&&(N=await Promise.all(N.map(async h=>{let R=await this.executeRaw(chunkVRZC4TTF_cjs.J`
21
+ `)));else for(let e of i)await this.executeRaw(chunkVRZC4TTF_cjs.J.raw(e));for(let e of t){let s=this.getTableName(e.slug);s==="users"||s==="audit_logs"||await this.syncTableColumns(e,s);}}getColumnSqlDefinition(t,i){let e=w(t,i),s=t.name.replace(/-/g,"_").replace(/([A-Z])/g,"_$1").toLowerCase(),n=this.columnSqlType(e,i);return `"${s}" ${n} DEFAULT NULL`}columnSqlType(t,i){if(i==="sqlite")switch(t){case "varchar":return "TEXT";case "text":return "TEXT";case "integer":return "INTEGER";case "decimal":case "numeric":return "NUMERIC";case "boolean":return "INTEGER";case "timestamp":return "TEXT";case "jsonb":return "TEXT";default:return "TEXT"}switch(t){case "varchar":return "VARCHAR(255)";case "text":return "TEXT";case "integer":return "INTEGER";case "decimal":case "numeric":return "DECIMAL";case "boolean":return "BOOLEAN";case "timestamp":return "TIMESTAMP";case "jsonb":return "JSONB";default:return "TEXT"}}getExpectedColumnDefs(t,i){let e={},s=t.slug.startsWith("_globals_"),n=t.fields.some(c=>c.name==="createdAt"),r=t.fields.some(c=>c.name==="updatedAt"),a=t.fields.some(c=>c.name==="status"),o=t.fields.some(c=>c.name==="hasDraft");this.dialect==="postgres"?(e.id=s?'"id" TEXT PRIMARY KEY':'"id" UUID PRIMARY KEY DEFAULT gen_random_uuid()',n||(e.created_at='"created_at" TIMESTAMP DEFAULT NULL'),r||(e.updated_at='"updated_at" TIMESTAMP DEFAULT NULL'),a||(e.status='"status" VARCHAR(20) DEFAULT NULL'),o||(e.hasDraft='"hasDraft" BOOLEAN DEFAULT NULL')):(e.id='"id" TEXT PRIMARY KEY',n||(e.created_at='"created_at" TEXT DEFAULT NULL'),r||(e.updated_at='"updated_at" TEXT DEFAULT NULL'),a||(e.status='"status" TEXT DEFAULT NULL'),o||(e.hasDraft='"hasDraft" INTEGER DEFAULT NULL'));for(let c of t.fields){if(!c.name||c.name==="id")continue;let d=this.getColumnSqlDefinition(c,this.dialect),u=c.name.replace(/-/g,"_").replace(/([A-Z])/g,"_$1").toLowerCase();e[u]=d;}return e}async syncTableColumns(t,i){let e;try{if(this.dialect==="postgres"){let r=await this.executeRaw(chunkVRZC4TTF_cjs.J`SELECT column_name, data_type, character_maximum_length FROM information_schema.columns WHERE table_name = ${i}`);e=new Map(r.map(a=>[a.column_name,{type:a.data_type,maxLen:a.character_maximum_length}]));}else {let r=await this.executeRaw(chunkVRZC4TTF_cjs.J`PRAGMA table_info("${chunkVRZC4TTF_cjs.J.raw(i)}")`);e=new Map(r.map(a=>[a.name,{type:a.type,maxLen:null}]));}}catch{return}let s=this.getExpectedColumnDefs(t,i),n=Object.keys(s).filter(r=>!e.has(r));if(n.length>0){let r=n.map(a=>`ALTER TABLE "${i}" ADD COLUMN ${s[a]}`);await this.executeRaw(chunkVRZC4TTF_cjs.J.raw(r.join(`;
22
+ `)));}if(this.dialect==="postgres")for(let r of t.fields){if(!r.name||r.name==="id")continue;let a=w(r,this.dialect),o=r.name.replace(/-/g,"_").replace(/([A-Z])/g,"_$1").toLowerCase(),c=e.get(o);!c||c.type!=="character varying"||(a==="text"?await this.executeRaw(chunkVRZC4TTF_cjs.J.raw(`ALTER TABLE "${i}" ALTER COLUMN "${o}" TYPE TEXT`)):a==="jsonb"&&(await this.executeRaw(chunkVRZC4TTF_cjs.J.raw(`ALTER TABLE "${i}" ALTER COLUMN "${o}" DROP DEFAULT`)),await this.executeRaw(chunkVRZC4TTF_cjs.J.raw(`ALTER TABLE "${i}" ALTER COLUMN "${o}" TYPE JSONB USING (CASE WHEN "${o}" IS NULL THEN NULL WHEN "${o}"::text ~ '^\\s*\\{' THEN "${o}"::jsonb ELSE jsonb_build_object('id', "${o}"::text) END)`))));}}generateCreateColumns(t){let i=[];for(let e of t.fields){if(!e.name||e.name==="id")continue;let s=w(e,this.dialect),n=e.name.replace(/-/g,"_").replace(/([A-Z])/g,"_$1").toLowerCase(),r=e.required?"NOT NULL":"DEFAULT NULL",a;if(this.dialect==="sqlite")switch(s){case "varchar":case "text":a=`TEXT ${r}`;break;case "integer":a=`INTEGER ${r}`;break;case "decimal":case "numeric":a=`NUMERIC ${r}`;break;case "boolean":a=`INTEGER ${r}`;break;case "timestamp":a=`TEXT ${r}`;break;case "jsonb":a=`TEXT ${r}`;break;default:a=`TEXT ${r}`;}else switch(s){case "varchar":a=`VARCHAR(255) ${r}`;break;case "integer":a=`INTEGER ${r}`;break;case "decimal":a=`DECIMAL ${r}`;break;case "boolean":a=`BOOLEAN ${r}`;break;case "timestamp":a=`TIMESTAMP ${r}`;break;case "jsonb":a=`JSONB ${r}`;break;default:a=`TEXT ${r}`;}i.push(`"${n}" ${a}`);}return i.join(`,
23
+ `)+(i.length>0?",":"")}async disconnect(){this.connected=false;}async find(t){let{collection:i,where:e={},sort:s,limit:n=10,page:r=1,tenantId:a,select:o,draft:c}=t,d=this.getCollection(i),u=this.getTable(i),m={...e};this.tenantContext&&d.tenantScoped&&(m=chunkVQ53TFYA_cjs.c({where:m},i,this.tenantContext,chunkVQ53TFYA_cjs.b).where||{});let g=this.buildWhereClause(m,d,u,a),y=d.fields.find(h=>h.name==="status"),p=y?.type==="select"&&Array.isArray(y.options)&&y.options.some(h=>h.value==="published");!c&&u.status&&p&&g.push(chunkBCEE4NBZ_cjs.n(u.status,"published"));let b=this.parseSort(s),N=!c&&u.status&&p?{...m,status:"published"}:m,fe=await this.count({collection:i,where:N,tenantId:a}),pe=(r-1)*n,j=[];try{let h=u[b.field]||u.createdAt||u.id,C=b.direction==="asc"?h:chunkBCEE4NBZ_cjs.M(h),A=this.client.select().from(u);g.length>0&&(A=A.where(chunkBCEE4NBZ_cjs.p(...g))),j=await A.orderBy(C).limit(n).offset(pe);}catch(h){console.error("[DrizzleAdapter] Query error:",h);}let R=j.map(h=>this.processResult(h,d));return this.tenantContext&&!this.tenantContext.isSuperAdmin&&(R=R.filter(h=>chunkVQ53TFYA_cjs.d(h,i,this.tenantContext,chunkVQ53TFYA_cjs.b))),c&&(R=await Promise.all(R.map(async h=>{let C=await this.executeRaw(chunkVRZC4TTF_cjs.J`
24
24
  SELECT * FROM kyro_versions
25
25
  WHERE collection_slug = ${i}
26
26
  AND document_id = ${h.id}
27
27
  ORDER BY created_at DESC
28
28
  LIMIT 1
29
- `);if(R.length>0){let A=R[0],pe=typeof A.data=="string"?JSON.parse(A.data):A.data;return {...h,...pe,status:h.status,_hasUnpublishedChanges:A.status==="draft"}}return h}))),{docs:N,...this.calculatePagination(r,n,ue)}}async findByID(t){let{collection:i,id:e,tenantId:s,draft:n}=t,r=this.getCollection(i),a=this.getTable(i),o=this.dialect==="postgres"&&typeof e=="string"?D(e):e;if(this.tenantContext&&r.tenantScoped){let p={id:o,tenantId:this.tenantContext.tenantId};if(!chunkVQ53TFYA_cjs.d(p,i,this.tenantContext,chunkVQ53TFYA_cjs.b))return null}let c=[chunkBCEE4NBZ_cjs.n(a.id,o)];s&&a.tenantId&&c.push(chunkBCEE4NBZ_cjs.n(a.tenantId,s));let d=r.fields.find(p=>p.name==="status"),u=d?.type==="select"&&Array.isArray(d.options)&&d.options.some(p=>p.value==="published");!n&&a.status&&u&&c.push(chunkBCEE4NBZ_cjs.n(a.status,"published"));let m=c.length>1?chunkBCEE4NBZ_cjs.p(...c):c[0],g=await this.client.select().from(a).where(m);if(g.length===0)return null;let y=this.processResult(g[0],r);if(n){let p=await this.executeRaw(chunkVRZC4TTF_cjs.J`
29
+ `);if(C.length>0){let A=C[0],he=typeof A.data=="string"?JSON.parse(A.data):A.data;return {...h,...he,status:h.status,_hasUnpublishedChanges:A.status==="draft"}}return h}))),{docs:R,...this.calculatePagination(r,n,fe)}}async findByID(t){let{collection:i,id:e,tenantId:s,draft:n}=t,r=this.getCollection(i),a=this.getTable(i),o=this.dialect==="postgres"&&typeof e=="string"?_(e):e;if(this.tenantContext&&r.tenantScoped){let p={id:o,tenantId:this.tenantContext.tenantId};if(!chunkVQ53TFYA_cjs.d(p,i,this.tenantContext,chunkVQ53TFYA_cjs.b))return null}let c=[chunkBCEE4NBZ_cjs.n(a.id,o)];s&&a.tenantId&&c.push(chunkBCEE4NBZ_cjs.n(a.tenantId,s));let d=r.fields.find(p=>p.name==="status"),u=d?.type==="select"&&Array.isArray(d.options)&&d.options.some(p=>p.value==="published");!n&&a.status&&u&&c.push(chunkBCEE4NBZ_cjs.n(a.status,"published"));let m=c.length>1?chunkBCEE4NBZ_cjs.p(...c):c[0],g=await this.client.select().from(a).where(m);if(g.length===0)return null;let y=this.processResult(g[0],r);if(n){let p=await this.executeRaw(chunkVRZC4TTF_cjs.J`
30
30
  SELECT * FROM kyro_versions
31
31
  WHERE collection_slug = ${i}
32
32
  AND document_id = ${y.id}
33
33
  ORDER BY created_at DESC
34
34
  LIMIT 1
35
- `);if(p.length>0){let b=p[0],_=typeof b.data=="string"?JSON.parse(b.data):b.data;y={...y,..._,status:y.status,_hasUnpublishedChanges:b.status==="draft"};}}return y}async create(t){let{collection:i,data:e,tenantId:s}=t,n=this.getCollection(i),r=this.getTable(i),a=this.prepareData(e,n);s&&n.tenantScoped&&(a.tenantId=s);let o=await this.client.insert(r).values(a).returning();return this.processResult(o[0],n)}async update(t){let{collection:i,id:e,data:s,tenantId:n}=t,r=this.getCollection(i),a=this.getTable(i),o=this.prepareData(s,r),c=this.dialect==="postgres"&&typeof e=="string"?D(e):e,d=[chunkBCEE4NBZ_cjs.n(a.id,c)];n&&a.tenantId&&d.push(chunkBCEE4NBZ_cjs.n(a.tenantId,n));let u=await this.client.update(a).set(o).where(chunkBCEE4NBZ_cjs.p(...d)).returning();if(u.length===0)throw new Error(`Document not found: ${i}/${e}`);return this.processResult(u[0],r)}async delete(t){let{collection:i,id:e,tenantId:s}=t,n=this.getCollection(i),r=this.getTable(i),a=this.dialect==="postgres"&&typeof e=="string"?D(e):e,o=[chunkBCEE4NBZ_cjs.n(r.id,a)];s&&r.tenantId&&o.push(chunkBCEE4NBZ_cjs.n(r.tenantId,s));let c=await this.client.delete(r).where(chunkBCEE4NBZ_cjs.p(...o)).returning();if(c.length===0)throw new Error(`Document not found: ${i}/${e}`);return this.processResult(c[0],n)}async count(t){let{collection:i,where:e={},tenantId:s}=t,n=this.getCollection(i),r=this.getTable(i),a=this.buildWhereClause(e,n,r,s);try{let o=this.client.select({count:chunkVRZC4TTF_cjs.J`count(*)`}).from(r);a.length>0&&(o=o.where(chunkBCEE4NBZ_cjs.p(...a)));let c=await o;return Number(c[0]?.count||0)}catch{return 0}}async findOne(t){let{collection:i,where:e={},tenantId:s,draft:n}=t;if(i.startsWith("_globals_")){let a=i.replace("_globals_",""),o=this.globals.get(a);if(!o)throw new Error(`Global "${a}" not found`);let c=this.getTable(i),d=this.client.select().from(c),u=o.fields.find(p=>p.name==="status"),m=u?.type==="select"&&Array.isArray(u.options)&&u.options.some(p=>p.value==="published");!n&&c.status&&m&&(d=d.where(chunkBCEE4NBZ_cjs.n(c.status,"published")));let g=await d.limit(1);if(g.length===0)return null;let y=this.processResult(g[0],o);if(n){let p=await this.executeRaw(chunkVRZC4TTF_cjs.J`
35
+ `);if(p.length>0){let b=p[0],N=typeof b.data=="string"?JSON.parse(b.data):b.data;y={...y,...N,status:y.status,_hasUnpublishedChanges:b.status==="draft"};}}return y}async create(t){let{collection:i,data:e,tenantId:s}=t,n=this.getCollection(i),r=this.getTable(i),a=this.prepareData(e,n);s&&n.tenantScoped&&(a.tenantId=s);let o=await this.client.insert(r).values(a).returning();return this.processResult(o[0],n)}async update(t){let{collection:i,id:e,data:s,tenantId:n}=t,r=this.getCollection(i),a=this.getTable(i),o=this.prepareData(s,r),c=this.dialect==="postgres"&&typeof e=="string"?_(e):e,d=[chunkBCEE4NBZ_cjs.n(a.id,c)];n&&a.tenantId&&d.push(chunkBCEE4NBZ_cjs.n(a.tenantId,n));let u=await this.client.update(a).set(o).where(chunkBCEE4NBZ_cjs.p(...d)).returning();if(u.length===0)throw new Error(`Document not found: ${i}/${e}`);return this.processResult(u[0],r)}async delete(t){let{collection:i,id:e,tenantId:s}=t,n=this.getCollection(i),r=this.getTable(i),a=this.dialect==="postgres"&&typeof e=="string"?_(e):e,o=[chunkBCEE4NBZ_cjs.n(r.id,a)];s&&r.tenantId&&o.push(chunkBCEE4NBZ_cjs.n(r.tenantId,s));let c=await this.client.delete(r).where(chunkBCEE4NBZ_cjs.p(...o)).returning();if(c.length===0)throw new Error(`Document not found: ${i}/${e}`);return this.processResult(c[0],n)}async count(t){let{collection:i,where:e={},tenantId:s}=t,n=this.getCollection(i),r=this.getTable(i),a=this.buildWhereClause(e,n,r,s);try{let o=this.client.select({count:chunkVRZC4TTF_cjs.J`count(*)`}).from(r);a.length>0&&(o=o.where(chunkBCEE4NBZ_cjs.p(...a)));let c=await o;return Number(c[0]?.count||0)}catch{return 0}}async findOne(t){let{collection:i,where:e={},tenantId:s,draft:n}=t;if(i.startsWith("_globals_")){let a=i.replace("_globals_",""),o=this.globals.get(a);if(!o)throw new Error(`Global "${a}" not found`);let c=this.getTable(i),d=this.client.select().from(c),u=o.fields.find(p=>p.name==="status"),m=u?.type==="select"&&Array.isArray(u.options)&&u.options.some(p=>p.value==="published");!n&&c.status&&m&&(d=d.where(chunkBCEE4NBZ_cjs.n(c.status,"published")));let g=await d.limit(1);if(g.length===0)return null;let y=this.processResult(g[0],o);if(n){let p=await this.executeRaw(chunkVRZC4TTF_cjs.J`
36
36
  SELECT * FROM kyro_versions
37
37
  WHERE collection_slug = ${i}
38
38
  AND document_id = ${a}
39
39
  ORDER BY created_at DESC
40
40
  LIMIT 1
41
- `);if(p.length>0){let b=p[0],_=typeof b.data=="string"?JSON.parse(b.data):b.data;y={...y,..._,status:y.status,_hasUnpublishedChanges:b.status==="draft"};}}return y}return (await this.find({...t,limit:1})).docs[0]||null}async findVersions(t){await this.ensureVersionsTable();let{collection:i,documentId:e,limit:s=10,page:n=1,tenantId:r}=t,a=(n-1)*s,o=this.getCollection(i),c=await this.executeRaw(chunkVRZC4TTF_cjs.J`
41
+ `);if(p.length>0){let b=p[0],N=typeof b.data=="string"?JSON.parse(b.data):b.data;y={...y,...N,status:y.status,_hasUnpublishedChanges:b.status==="draft"};}}return y}return (await this.find({...t,limit:1})).docs[0]||null}async findVersions(t){await this.ensureVersionsTable();let{collection:i,documentId:e,limit:s=10,page:n=1,tenantId:r}=t,a=(n-1)*s,o=this.getCollection(i),c=await this.executeRaw(chunkVRZC4TTF_cjs.J`
42
42
  SELECT count(*) as count
43
43
  FROM kyro_versions
44
44
  WHERE collection_slug = ${i}
@@ -101,7 +101,7 @@
101
101
  WHERE collection_slug = ${t.collection}
102
102
  AND document_id = ${t.documentId}
103
103
  ${t.tenantId&&i.tenantScoped?chunkVRZC4TTF_cjs.J`AND tenant_id = ${t.tenantId}`:chunkVRZC4TTF_cjs.J``}
104
- `);}getTable(t){let i=this.getTableName(t),e=this.schema[i];if(!e)throw new Error(`Table "${i}" not found in schema`);return e}buildWhereClause(t,i,e,s){let n=[];s&&i.tenantScoped&&e.tenantId&&n.push(chunkBCEE4NBZ_cjs.n(e.tenantId,s));for(let[r,a]of Object.entries(t))if(r==="id"&&this.dialect==="postgres"&&(typeof a=="string"?a=D(a):a&&typeof a=="object"&&(a.equals!==void 0&&typeof a.equals=="string"&&(a={...a,equals:D(a.equals)}),a.in&&Array.isArray(a.in)&&(a={...a,in:a.in.map(o=>typeof o=="string"?D(o):o)}))),r==="AND"&&Array.isArray(a)){let o=a.map(c=>this.buildWhereClause(c,i,e)).flat().filter(Boolean);o.length>0&&n.push(chunkBCEE4NBZ_cjs.p(...o));}else if(r==="OR"&&Array.isArray(a)){let o=a.map(c=>this.buildWhereClause(c,i,e)).flat().filter(Boolean);o.length>0&&n.push(chunkBCEE4NBZ_cjs.q(...o));}else if(typeof a=="object"&&a!==null&&!Array.isArray(a)){let o=e[r];if(!o)continue;a.equals!==void 0&&n.push(chunkBCEE4NBZ_cjs.n(o,a.equals)),a.not_equals!==void 0&&n.push(chunkBCEE4NBZ_cjs.o(o,a.not_equals)),a.in&&Array.isArray(a.in)&&n.push(chunkBCEE4NBZ_cjs.w(o,a.in)),a.like!==void 0&&n.push(chunkBCEE4NBZ_cjs.E(o,a.like)),a.contains!==void 0&&n.push(chunkBCEE4NBZ_cjs.E(o,`%${a.contains}%`)),a.greater_than!==void 0&&n.push(chunkBCEE4NBZ_cjs.s(o,a.greater_than)),a.greater_than_equal!==void 0&&n.push(chunkBCEE4NBZ_cjs.t(o,a.greater_than_equal)),a.less_than!==void 0&&n.push(chunkBCEE4NBZ_cjs.u(o,a.less_than)),a.less_than_equal!==void 0&&n.push(chunkBCEE4NBZ_cjs.v(o,a.less_than_equal));}else {let o=e[r];o&&n.push(chunkBCEE4NBZ_cjs.n(o,a));}return n}processResult(t,i){if(!t)return null;let e={...t};for(let s of Object.keys(e))/^\d+$/.test(s)&&delete e[s];t.id&&(e.id=String(t.id));for(let s of i.fields){if(!s.name)continue;let n=s.name.replace(/-/g,"_").replace(/([A-Z])/g,"_$1").toLowerCase();n!==s.name&&e[n]!==void 0&&e[s.name]===void 0&&(e[s.name]=e[n],delete e[n]);}for(let s of i.fields){if(["json","richtext","array","group","blocks","upload","image","list","relationship-block"].includes(s.type)){let n=s;if(e[n.name]&&typeof e[n.name]=="string")try{let r=JSON.parse(e[n.name]);e[n.name]=r;}catch{}if(s.type==="blocks"&&e[n.name]&&Array.isArray(e[n.name])){let r=n.blocks||[];e[n.name]=le(e[n.name],r);}}if(s.type==="tabs"&&"tabs"in s&&s.name){if(typeof e[s.name]=="object"&&e[s.name]!==null&&!Array.isArray(e[s.name])){for(let r of s.tabs)for(let a of r.fields)if((a.type==="upload"||a.type==="image")&&a.name){let o=e[s.name][a.name];if(typeof o=="string")try{let c=JSON.parse(o);e[s.name][a.name]=Array.isArray(c)?c.map(d=>d&&typeof d=="object"&&typeof d.id=="string"?d.id:String(d||"")):typeof c.id=="string"?c.id:String(c.id||"");}catch{}else o&&typeof o=="object"&&(e[s.name][a.name]=Array.isArray(o)?o.map(c=>c&&typeof c=="object"&&typeof c.id=="string"?c.id:String(c||"")):typeof o.id=="string"?o.id:String(o.id||""));}continue}if(typeof e[s.name]=="string")try{let r=JSON.parse(e[s.name]);if(typeof r=="object"&&r!==null){e[s.name]=r;continue}}catch{}let n={};for(let r of s.tabs)for(let a of r.fields)if(a.name&&e[a.name]!==void 0){let o=e[a.name];if(["json","richtext","array","group","blocks","upload","image","list","relationship-block"].includes(a.type)){if(o&&typeof o=="string")try{o=JSON.parse(o);}catch{}(a.type==="upload"||a.type==="image")&&o&&typeof o=="object"&&(o=Array.isArray(o)?o.map(c=>c&&typeof c=="object"&&typeof c.id=="string"?c.id:String(c||"")):typeof o.id=="string"?o.id:String(o.id||""));}n[a.name]=o,delete e[a.name];}e[s.name]=n;}}return e.createdAt&&(e.createdAt=new Date(e.createdAt).toISOString()),e.updatedAt&&(e.updatedAt=new Date(e.updatedAt).toISOString()),chunkZOVH6QT5_cjs.a(e)}async ensureVersionsTable(){if(this.versionsTableReady)return;let t;this.dialect==="sqlite"?t=`
104
+ `);}getTable(t){let i=this.getTableName(t),e=this.schema[i];if(!e)throw new Error(`Table "${i}" not found in schema`);return e}buildWhereClause(t,i,e,s){let n=[];s&&i.tenantScoped&&e.tenantId&&n.push(chunkBCEE4NBZ_cjs.n(e.tenantId,s));for(let[r,a]of Object.entries(t))if(r==="id"&&this.dialect==="postgres"&&(typeof a=="string"?a=_(a):a&&typeof a=="object"&&(a.equals!==void 0&&typeof a.equals=="string"&&(a={...a,equals:_(a.equals)}),a.in&&Array.isArray(a.in)&&(a={...a,in:a.in.map(o=>typeof o=="string"?_(o):o)}))),r==="AND"&&Array.isArray(a)){let o=a.map(c=>this.buildWhereClause(c,i,e)).flat().filter(Boolean);o.length>0&&n.push(chunkBCEE4NBZ_cjs.p(...o));}else if(r==="OR"&&Array.isArray(a)){let o=a.map(c=>this.buildWhereClause(c,i,e)).flat().filter(Boolean);o.length>0&&n.push(chunkBCEE4NBZ_cjs.q(...o));}else if(typeof a=="object"&&a!==null&&!Array.isArray(a)){let o=e[r];if(!o)continue;a.equals!==void 0&&n.push(chunkBCEE4NBZ_cjs.n(o,a.equals)),a.not_equals!==void 0&&n.push(chunkBCEE4NBZ_cjs.o(o,a.not_equals)),a.in&&Array.isArray(a.in)&&n.push(chunkBCEE4NBZ_cjs.w(o,a.in)),a.like!==void 0&&n.push(chunkBCEE4NBZ_cjs.E(o,a.like)),a.contains!==void 0&&n.push(chunkBCEE4NBZ_cjs.E(o,`%${a.contains}%`)),a.greater_than!==void 0&&n.push(chunkBCEE4NBZ_cjs.s(o,a.greater_than)),a.greater_than_equal!==void 0&&n.push(chunkBCEE4NBZ_cjs.t(o,a.greater_than_equal)),a.less_than!==void 0&&n.push(chunkBCEE4NBZ_cjs.u(o,a.less_than)),a.less_than_equal!==void 0&&n.push(chunkBCEE4NBZ_cjs.v(o,a.less_than_equal));}else {let o=e[r];o&&n.push(chunkBCEE4NBZ_cjs.n(o,a));}return n}processResult(t,i){if(!t)return null;let e={...t};for(let s of Object.keys(e))/^\d+$/.test(s)&&delete e[s];t.id&&(e.id=String(t.id));for(let s of i.fields){if(!s.name)continue;let n=s.name.replace(/-/g,"_").replace(/([A-Z])/g,"_$1").toLowerCase();n!==s.name&&e[n]!==void 0&&e[s.name]===void 0&&(e[s.name]=e[n],delete e[n]);}for(let s of i.fields){if(["json","richtext","array","group","blocks","upload","image","list","relationship-block"].includes(s.type)){let n=s;if(e[n.name]&&typeof e[n.name]=="string")try{let r=JSON.parse(e[n.name]);e[n.name]=r;}catch{}if(s.type==="blocks"&&e[n.name]&&Array.isArray(e[n.name])){let r=n.blocks||[];e[n.name]=M(e[n.name],r);}}if(s.type==="tabs"&&"tabs"in s&&s.name){if(typeof e[s.name]=="object"&&e[s.name]!==null&&!Array.isArray(e[s.name])){for(let r of s.tabs)for(let a of r.fields)if((a.type==="upload"||a.type==="image")&&a.name){let o=e[s.name][a.name];if(typeof o=="string")try{let c=JSON.parse(o);e[s.name][a.name]=Array.isArray(c)?c.map(d=>d&&typeof d=="object"&&typeof d.id=="string"?d.id:String(d||"")):typeof c.id=="string"?c.id:String(c.id||"");}catch{}else o&&typeof o=="object"&&(e[s.name][a.name]=Array.isArray(o)?o.map(c=>c&&typeof c=="object"&&typeof c.id=="string"?c.id:String(c||"")):typeof o.id=="string"?o.id:String(o.id||""));}continue}if(typeof e[s.name]=="string")try{let r=JSON.parse(e[s.name]);if(typeof r=="object"&&r!==null){e[s.name]=r;continue}}catch{}let n={};for(let r of s.tabs)for(let a of r.fields)if(a.name&&e[a.name]!==void 0){let o=e[a.name];if(["json","richtext","array","group","blocks","upload","image","list","relationship-block"].includes(a.type)){if(o&&typeof o=="string")try{o=JSON.parse(o);}catch{}(a.type==="upload"||a.type==="image")&&o&&typeof o=="object"&&(o=Array.isArray(o)?o.map(c=>c&&typeof c=="object"&&typeof c.id=="string"?c.id:String(c||"")):typeof o.id=="string"?o.id:String(o.id||""));}n[a.name]=o,delete e[a.name];}e[s.name]=n;}}return e.createdAt&&(e.createdAt=new Date(e.createdAt).toISOString()),e.updatedAt&&(e.updatedAt=new Date(e.updatedAt).toISOString()),chunkZOVH6QT5_cjs.a(e)}async ensureVersionsTable(){if(this.versionsTableReady)return;let t;this.dialect==="sqlite"?t=`
105
105
  CREATE TABLE IF NOT EXISTS kyro_versions (
106
106
  id text PRIMARY KEY,
107
107
  collection_slug text NOT NULL,
@@ -129,5 +129,4 @@
129
129
  created_at text NOT NULL,
130
130
  updated_at text NOT NULL
131
131
  )
132
- `,await this.executeRaw(chunkVRZC4TTF_cjs.J.raw(t));try{this.dialect==="postgres"?await this.executeRaw(chunkVRZC4TTF_cjs.J.raw("ALTER TABLE kyro_versions ADD COLUMN IF NOT EXISTS autosave integer NOT NULL DEFAULT 0")):await this.executeRaw(chunkVRZC4TTF_cjs.J.raw("ALTER TABLE kyro_versions ADD COLUMN autosave integer NOT NULL DEFAULT 0"));}catch{}this.versionsTableReady=true;}async execute(t){return this.executeRaw(t)}async executeRaw(t){let i="",e=[];if(typeof t=="string")i=t;else if(t&&(t.queryChunks||t.decoder))if(this.dialect==="postgres"){let n=new chunkKCHPADCH_cjs.a().sqlToQuery(t);i=n.sql,e=n.params;}else {let n=new chunk7ACHOBWY_cjs.h().sqlToQuery(t);i=n.sql,e=n.params;}else if(t&&typeof t.toSQL=="function"){let n=t.toSQL();i=n.sql,e=n.params||[];}else i=String(t);let s=this.rawClient||this.client;if(s?.prepare&&typeof s.prepare=="function"){let n=s.prepare(i);return (e.length>0?await n.bind(...e).all():await n.all()).results||[]}if(typeof this.client?.execute=="function"){let n=await this.client.execute(t);return Array.isArray(n)?n:Array.isArray(n?.rows)?n.rows:Array.isArray(n?.[0])?n[0]:[]}return []}};function Ie(f){return new M(f)}chunkBUNLC3II_cjs.h();var x;function Ae(){return x||(x=module$1.createRequire("file:///")("node:sqlite").DatabaseSync,x)}function Ee(){return process.env.DB_TYPE==="postgres"?"postgres":"sqlite"}function de(){return crypto.randomBytes(16).toString("hex")}async function Me(){let f=Ee();if(f==="sqlite"){let r=path.resolve(process.cwd(),"data","kyro.db");await promises.mkdir(path.dirname(r),{recursive:true});let a=new(Ae())(r);return a.exec("PRAGMA journal_mode = WAL"),{db:a,dialect:f,genId:de}}let t=process.env.DATABASE_URL||"postgresql://postgres:postgres@localhost:5432/kyro_cms",i=parseInt(process.env.DB_POOL_MAX||"10",10),e=process.env.DB_SSL==="true",s=chunkLY7N3UHH_cjs.a(t,{max:i,ssl:e?"require":false,onnotice:()=>{}});return {db:chunkKCHPADCH_cjs.f(s),dialect:f,genId:de}}async function Pe(f,t){}async function je(f){let{roles:t}=await import('./schema-RT6WSUYC.cjs');await f.insert(t).values({name:"super_admin",level:100,inherits:[],description:"Full system access across all tenants",isSystem:true}).onConflictDoNothing();}
133
- exports.a=L;exports.b=Se;exports.c=M;exports.d=Ie;exports.e=de;exports.f=Me;exports.g=Pe;exports.h=je;
132
+ `,await this.executeRaw(chunkVRZC4TTF_cjs.J.raw(t));try{this.dialect==="postgres"?await this.executeRaw(chunkVRZC4TTF_cjs.J.raw("ALTER TABLE kyro_versions ADD COLUMN IF NOT EXISTS autosave integer NOT NULL DEFAULT 0")):await this.executeRaw(chunkVRZC4TTF_cjs.J.raw("ALTER TABLE kyro_versions ADD COLUMN autosave integer NOT NULL DEFAULT 0"));}catch{}this.versionsTableReady=true;}async execute(t){return this.executeRaw(t)}async executeRaw(t){let i="",e=[];if(typeof t=="string")i=t;else if(t&&(t.queryChunks||t.decoder))if(this.dialect==="postgres"){let n=new chunkSOCBJPYB_cjs.a().sqlToQuery(t);i=n.sql,e=n.params;}else {let n=new chunk7ACHOBWY_cjs.h().sqlToQuery(t);i=n.sql,e=n.params;}else if(t&&typeof t.toSQL=="function"){let n=t.toSQL();i=n.sql,e=n.params||[];}else i=String(t);let s=this.rawClient||this.client;if(s?.prepare&&typeof s.prepare=="function"){let n=s.prepare(i);return (e.length>0?await n.bind(...e).all():await n.all()).results||[]}if(typeof this.client?.execute=="function"){let n=await this.client.execute(t);return Array.isArray(n)?n:Array.isArray(n?.rows)?n.rows:Array.isArray(n?.[0])?n[0]:[]}return []}};function Xe(f){return new P(f)}exports.a=de;exports.b=Se;exports.c=Ie;exports.d=$e;exports.e=w;exports.f=we;exports.g=P;exports.h=Xe;
@@ -0,0 +1 @@
1
+ 'use strict';var chunkBUNLC3II_cjs=require('./chunk-BUNLC3II.cjs');chunkBUNLC3II_cjs.h();function t(){return {name:"seo",type:"group",label:"SEO Settings",fields:[{name:"metaTitle",type:"text",label:"Meta Title",admin:{description:"The title used for search engines (recommended < 60 chars). Leave empty for AI auto-generation."}},{name:"metaDescription",type:"textarea",label:"Meta Description",admin:{description:"A brief summary for search engines (recommended < 160 chars). Leave empty for AI auto-generation."}},{name:"keywords",type:"text",label:"Keywords",admin:{description:"Comma-separated list of keywords for this page."}},{name:"ogImage",type:"upload",label:"OpenGraph Image",relationTo:"media",admin:{description:"The image shown when the post is shared on social media (Facebook, LinkedIn)."}},{name:"twitter",type:"group",label:"Twitter Card",fields:[{name:"title",type:"text",label:"Twitter Title"},{name:"description",type:"textarea",label:"Twitter Description"},{name:"image",type:"upload",label:"Twitter Image",relationTo:"media"}]},{name:"advanced",type:"group",label:"Advanced Search Settings",fields:[{name:"noindex",type:"checkbox",label:"Hide from search engines (noindex)",defaultValue:false},{name:"nofollow",type:"checkbox",label:"Do not follow links (nofollow)",defaultValue:false},{name:"canonicalUrl",type:"text",label:"Canonical URL Override",admin:{description:"Leave empty to use the default canonical URL."}},{name:"structuredData",type:"code",label:"JSON-LD Structured Data",admin:{description:"Custom JSON-LD schema for this specific page."}}]}]}}exports.a=t;
@@ -1 +1 @@
1
- 'use strict';var chunkWQCLLM4S_cjs=require('./chunk-WQCLLM4S.cjs'),chunkM56F4LQ5_cjs=require('./chunk-M56F4LQ5.cjs'),chunkOUMUIICN_cjs=require('./chunk-OUMUIICN.cjs'),chunkBHR7OAU4_cjs=require('./chunk-BHR7OAU4.cjs'),chunkTDGSIF5H_cjs=require('./chunk-TDGSIF5H.cjs'),chunkXBQ6HV3T_cjs=require('./chunk-XBQ6HV3T.cjs'),chunk7DUKWHRN_cjs=require('./chunk-7DUKWHRN.cjs'),chunkBUNLC3II_cjs=require('./chunk-BUNLC3II.cjs'),w=require('kyro:config');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var w__default=/*#__PURE__*/_interopDefault(w);chunkBUNLC3II_cjs.h();exports.a=null;var l=null;async function b(){if(!exports.a){if(globalThis.__KYRO_INSTANCE__)try{await globalThis.__KYRO_INSTANCE__.shutdown();}catch{}try{let e=w__default.default.default||w__default.default,t=e.adapter,o=t&&!t.dialect&&typeof t.connect=="function";if(globalThis.DB&&(!t||o)){let s=globalThis.DB;e.adapter=new chunkTDGSIF5H_cjs.c({type:"sqlite",client:s}),chunkWQCLLM4S_cjs.D.info("Hot-swapped to D1 DrizzleAdapter");}exports.a=chunkWQCLLM4S_cjs.A(e),await exports.a.init();let a=e.adapter,p=a&&a.dialect&&(a.dialect==="postgres"||a.dialect==="sqlite"),c=a&&a.dialect==="mongodb",n;if(p)a.dialect==="postgres"?n=new chunkXBQ6HV3T_cjs.a({db:a.client}):a.dialect==="sqlite"&&(n=new chunkOUMUIICN_cjs.fb({db:a.rawClient||a.client}));else if(o&&!globalThis.DB){let s=process.env.KYRO_AUTH_DB_PATH||"./data/auth.db";n=new chunkBHR7OAU4_cjs.a({path:s});}else c&&(n=new chunk7DUKWHRN_cjs.a({adapter:a}));if(n?.connect)try{await n.connect();}catch(s){chunkWQCLLM4S_cjs.D.warn("Auth connect warning:",s);}try{await exports.a.loadSettings();}catch(s){chunkWQCLLM4S_cjs.D.warn("loadSettings warning:",s);}try{await chunkM56F4LQ5_cjs.e(n);}catch(s){chunkWQCLLM4S_cjs.D.warn("autoBootstrap warning:",s);}globalThis.__KYRO_INSTANCE__=exports.a;}catch(e){throw exports.a=null,l=null,chunkWQCLLM4S_cjs.D.error("Init failed, will retry:",e),e}}}async function E(e){let t=globalThis.DB?globalThis:null;try{let{env:o}=await import('cloudflare:workers');o&&(t=o);}catch{}if(e)try{t=e.locals?.cfContext?.env||e?.env||t;}catch{}if(!t)try{t=process.env;}catch{}t?.DB&&(globalThis.DB=t.DB),t?.STORAGE_BUCKET&&(globalThis.STORAGE_BUCKET=t.STORAGE_BUCKET),l||(l=b()),await l;}var _={graphqlEnabled:false,trpcEnabled:false,wsEnabled:false,requireAuth:false};function T(e){return exports.a?exports.a.settings?.access?.apiAccess?.[e]??_[e]??true:_[e]??true}var R=async e=>{if(!exports.a)try{await Promise.race([E(e),new Promise((t,o)=>setTimeout(()=>o(new Error("Initialization timeout")),3e4))]);}catch(t){return console.error("[Kyro API] Warm error:",t?.stack||t?.message||t),new Response(JSON.stringify({error:"Service Unavailable",message:"Kyro CMS is still starting up. Please try again in a moment."}),{status:503,headers:{"Content-Type":"application/json","Retry-After":"5"}})}try{let o=new URL(e.request.url).pathname,a=__KYRO_API_PATH__;if(o===`${a}/graphql`&&typeof exports.a.getGraphQL=="function"){if(!T("graphqlEnabled"))return new Response(JSON.stringify({error:"GraphQL is disabled"}),{status:503,headers:{"Content-Type":"application/json"}});let n=await exports.a.getGraphQL().fetch(e.request,e.locals);return new Response(n.body,n)}if(o.startsWith(`${a}/trpc/`)&&typeof exports.a.getTRPC=="function"){if(!T("trpcEnabled"))return new Response(JSON.stringify({error:"tRPC is disabled"}),{status:503,headers:{"Content-Type":"application/json"}});let n=await exports.a.getTRPC().fetch(e.request,e.locals);return new Response(n.body,n)}return await(await exports.a.getREST()).fetch(e.request,e.locals)}catch(t){return console.error("[Kyro API Execution Error]:",t?.stack||t?.message||t),new Response(JSON.stringify({error:"Internal Server Error",message:t?.message||String(t),stack:t?.stack}),{status:500,headers:{"Content-Type":"application/json"}})}},L=R;exports.b=E;exports.c=R;exports.d=L;
1
+ 'use strict';var chunk4FHWIGHO_cjs=require('./chunk-4FHWIGHO.cjs'),chunk3XLXKGEU_cjs=require('./chunk-3XLXKGEU.cjs'),chunk6QWX3DEB_cjs=require('./chunk-6QWX3DEB.cjs'),chunkOPTVCCQQ_cjs=require('./chunk-OPTVCCQQ.cjs'),chunkJU3UAZRY_cjs=require('./chunk-JU3UAZRY.cjs'),chunkXBQ6HV3T_cjs=require('./chunk-XBQ6HV3T.cjs'),chunk7DUKWHRN_cjs=require('./chunk-7DUKWHRN.cjs'),chunkBUNLC3II_cjs=require('./chunk-BUNLC3II.cjs'),w=require('kyro:config');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var w__default=/*#__PURE__*/_interopDefault(w);chunkBUNLC3II_cjs.h();exports.a=null;var l=null;async function b(){if(!exports.a){if(globalThis.__KYRO_INSTANCE__)try{await globalThis.__KYRO_INSTANCE__.shutdown();}catch{}try{let e=w__default.default.default||w__default.default,t=e.adapter,o=t&&!t.dialect&&typeof t.connect=="function";if(globalThis.DB&&(!t||o)){let s=globalThis.DB;e.adapter=new chunkJU3UAZRY_cjs.g({type:"sqlite",client:s}),chunk4FHWIGHO_cjs.D.info("Hot-swapped to D1 DrizzleAdapter");}exports.a=chunk4FHWIGHO_cjs.A(e),await exports.a.init();let a=e.adapter,p=a&&a.dialect&&(a.dialect==="postgres"||a.dialect==="sqlite"),c=a&&a.dialect==="mongodb",n;if(p)a.dialect==="postgres"?n=new chunkXBQ6HV3T_cjs.a({db:a.client}):a.dialect==="sqlite"&&(n=new chunk6QWX3DEB_cjs.hb({db:a.rawClient||a.client}));else if(o&&!globalThis.DB){let s=process.env.KYRO_AUTH_DB_PATH||"./data/auth.db";n=new chunkOPTVCCQQ_cjs.a({path:s});}else c&&(n=new chunk7DUKWHRN_cjs.a({adapter:a}));if(n?.connect)try{await n.connect();}catch(s){chunk4FHWIGHO_cjs.D.warn("Auth connect warning:",s);}try{await exports.a.loadSettings();}catch(s){chunk4FHWIGHO_cjs.D.warn("loadSettings warning:",s);}try{await chunk3XLXKGEU_cjs.e(n);}catch(s){chunk4FHWIGHO_cjs.D.warn("autoBootstrap warning:",s);}globalThis.__KYRO_INSTANCE__=exports.a;}catch(e){throw exports.a=null,l=null,chunk4FHWIGHO_cjs.D.error("Init failed, will retry:",e),e}}}async function E(e){let t=globalThis.DB?globalThis:null;try{let{env:o}=await import('cloudflare:workers');o&&(t=o);}catch{}if(e)try{t=e.locals?.cfContext?.env||e?.env||t;}catch{}if(!t)try{t=process.env;}catch{}t?.DB&&(globalThis.DB=t.DB),t?.STORAGE_BUCKET&&(globalThis.STORAGE_BUCKET=t.STORAGE_BUCKET),l||(l=b()),await l;}var _={graphqlEnabled:false,trpcEnabled:false,wsEnabled:false,requireAuth:false};function T(e){return exports.a?exports.a.settings?.access?.apiAccess?.[e]??_[e]??true:_[e]??true}var R=async e=>{if(!exports.a)try{await Promise.race([E(e),new Promise((t,o)=>setTimeout(()=>o(new Error("Initialization timeout")),3e4))]);}catch(t){return console.error("[Kyro API] Warm error:",t?.stack||t?.message||t),new Response(JSON.stringify({error:"Service Unavailable",message:"Kyro CMS is still starting up. Please try again in a moment."}),{status:503,headers:{"Content-Type":"application/json","Retry-After":"5"}})}try{let o=new URL(e.request.url).pathname,a=__KYRO_API_PATH__;if(o===`${a}/graphql`&&typeof exports.a.getGraphQL=="function"){if(!T("graphqlEnabled"))return new Response(JSON.stringify({error:"GraphQL is disabled"}),{status:503,headers:{"Content-Type":"application/json"}});let n=await exports.a.getGraphQL().fetch(e.request,e.locals);return new Response(n.body,n)}if(o.startsWith(`${a}/trpc/`)&&typeof exports.a.getTRPC=="function"){if(!T("trpcEnabled"))return new Response(JSON.stringify({error:"tRPC is disabled"}),{status:503,headers:{"Content-Type":"application/json"}});let n=await exports.a.getTRPC().fetch(e.request,e.locals);return new Response(n.body,n)}return await(await exports.a.getREST()).fetch(e.request,e.locals)}catch(t){return console.error("[Kyro API Execution Error]:",t?.stack||t?.message||t),new Response(JSON.stringify({error:"Internal Server Error",message:t?.message||String(t),stack:t?.stack}),{status:500,headers:{"Content-Type":"application/json"}})}},L=R;exports.b=E;exports.c=R;exports.d=L;