@kyro-cms/core 0.10.17 → 0.10.18
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.
- package/dist/api-handler-graphql.cjs +1 -1
- package/dist/api-handler-graphql.js +1 -1
- package/dist/api-handler-trpc.cjs +1 -1
- package/dist/api-handler-trpc.js +1 -1
- package/dist/api-handler.cjs +1 -1
- package/dist/api-handler.js +1 -1
- package/dist/chunk-4YYBWCDJ.js +1 -0
- package/dist/chunk-5H7LD62N.js +21 -0
- package/dist/{chunk-44TYUUC6.cjs → chunk-BL34J64W.cjs} +1 -1
- package/dist/{chunk-N3PMDG7U.js → chunk-CFMATLA3.js} +1 -1
- package/dist/chunk-GPKEOELO.js +2 -0
- package/dist/{chunk-VKXQUYYV.js → chunk-MBUUNROA.js} +14 -14
- package/dist/chunk-QIRWEE7V.cjs +3 -0
- package/dist/{chunk-IGLFKSXH.cjs → chunk-RBZNQINT.cjs} +4 -4
- package/dist/{chunk-PDSHJVCT.cjs → chunk-RXOAX7GO.cjs} +6 -6
- package/dist/chunk-TRFBYBYC.js +86 -0
- package/dist/chunk-TYOVXKQP.js +2 -0
- package/dist/chunk-W4ZDETHA.cjs +1 -0
- package/dist/chunk-WMY7BDPK.cjs +2 -0
- package/dist/{chunk-6CLRVJPP.cjs → chunk-X3RRRWIN.cjs} +14 -14
- package/dist/chunk-YJRLS2Z3.js +3 -0
- package/dist/chunk-ZPUIRXKS.cjs +2 -0
- package/dist/drizzle/index.cjs +1 -1
- package/dist/drizzle/index.js +1 -1
- package/dist/graphql/index.cjs +1 -1
- package/dist/graphql/index.js +1 -1
- package/dist/index.cjs +2 -2
- package/dist/index.js +1 -1
- package/dist/mongodb/index.cjs +1 -1
- package/dist/mongodb/index.js +1 -1
- package/dist/rest/index.cjs +1 -1
- package/dist/rest/index.js +1 -1
- package/dist/templates/index.cjs +1 -1
- package/dist/templates/index.js +1 -1
- package/package.json +1 -1
- package/dist/chunk-3RUOCZ4Y.cjs +0 -3
- package/dist/chunk-CIE3XMLH.cjs +0 -2
- package/dist/chunk-DV4LFLPL.cjs +0 -1
- package/dist/chunk-G3DZDZIP.js +0 -86
- package/dist/chunk-G6A7OSIG.js +0 -2
- package/dist/chunk-R6UUTH3T.js +0 -2
- package/dist/chunk-S5SJ2ARG.js +0 -3
- package/dist/chunk-SB33D472.js +0 -21
- package/dist/chunk-UDSJGML2.cjs +0 -2
- package/dist/chunk-ZAQOSRP6.js +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
'use strict';var
|
|
1
|
+
'use strict';var chunkBL34J64W_cjs=require('./chunk-BL34J64W.cjs');require('./chunk-RBZNQINT.cjs'),require('./chunk-UJNSOOYZ.cjs'),require('./chunk-65G73T7Z.cjs'),require('./chunk-CVVW4LXZ.cjs'),require('./chunk-ZPUIRXKS.cjs'),require('./chunk-RXOAX7GO.cjs'),require('./chunk-AJAZ7D3W.cjs'),require('./chunk-WIZ6C5QZ.cjs'),require('./chunk-GFU7AOI3.cjs'),require('./chunk-ET6NN2V2.cjs'),require('./chunk-HVXO3OFB.cjs'),require('./chunk-ISWMETHJ.cjs'),require('./chunk-NY47CFVP.cjs'),require('./chunk-F7SR5IDT.cjs'),require('./chunk-4ORJMSJU.cjs'),require('./chunk-X3RRRWIN.cjs'),require('./chunk-GYQMNXXW.cjs'),require('./chunk-MIOMMB23.cjs'),require('./chunk-UBHFUFD4.cjs'),require('./chunk-WMY7BDPK.cjs'),require('./chunk-ATLSIYRH.cjs'),require('./chunk-W4ZDETHA.cjs'),require('./chunk-Q3Q7BJVQ.cjs'),require('./chunk-AHSFSERC.cjs');function n(e){return new Response(e.body,e)}var p={graphqlEnabled:false,trpcEnabled:false,wsEnabled:false,requireAuth:false};function r(){return new Response(JSON.stringify({error:"GraphQL is disabled"}),{status:503,headers:{"Content-Type":"application/json"}})}async function o(){try{return (await chunkBL34J64W_cjs.a.db.findOne({collection:"_globals_access-settings",where:{},draft:!0}))?.apiAccess?.graphqlEnabled??p.graphqlEnabled}catch{return true}}var l=async e=>{if(await chunkBL34J64W_cjs.b(),!await o())return r();let t=await chunkBL34J64W_cjs.a.getGraphQL().fetch(e.request,e.locals);return n(t)},u=async e=>{if(await chunkBL34J64W_cjs.b(),!await o())return r();let t=await chunkBL34J64W_cjs.a.getGraphQL().fetch(e.request,e.locals);return n(t)};exports.GET=u;exports.POST=l;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import {b,a}from'./chunk-
|
|
1
|
+
import {b,a}from'./chunk-CFMATLA3.js';import'./chunk-5H7LD62N.js';import'./chunk-FO3HLBC7.js';import'./chunk-NZ35PV5R.js';import'./chunk-7N6NKCRT.js';import'./chunk-GPKEOELO.js';import'./chunk-TRFBYBYC.js';import'./chunk-7WOX27LK.js';import'./chunk-K6WUOU6P.js';import'./chunk-AE6GXUT7.js';import'./chunk-2W4FK6CJ.js';import'./chunk-NRLIGDYF.js';import'./chunk-UVTS2IWM.js';import'./chunk-HLSB2MCK.js';import'./chunk-SL3LZQCF.js';import'./chunk-PP5S2UBV.js';import'./chunk-MBUUNROA.js';import'./chunk-RHCWCG3O.js';import'./chunk-OG7CNQGU.js';import'./chunk-QRXDCV6K.js';import'./chunk-TYOVXKQP.js';import'./chunk-P7CESLDJ.js';import'./chunk-4YYBWCDJ.js';import'./chunk-KDNYHLD2.js';import'./chunk-5J6HXUF6.js';function n(e){return new Response(e.body,e)}var p={graphqlEnabled:false,trpcEnabled:false,wsEnabled:false,requireAuth:false};function r(){return new Response(JSON.stringify({error:"GraphQL is disabled"}),{status:503,headers:{"Content-Type":"application/json"}})}async function o(){try{return (await a.db.findOne({collection:"_globals_access-settings",where:{},draft:!0}))?.apiAccess?.graphqlEnabled??p.graphqlEnabled}catch{return true}}var l=async e=>{if(await b(),!await o())return r();let t=await a.getGraphQL().fetch(e.request,e.locals);return n(t)},u=async e=>{if(await b(),!await o())return r();let t=await a.getGraphQL().fetch(e.request,e.locals);return n(t)};export{u as GET,l as POST};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
'use strict';var
|
|
1
|
+
'use strict';var chunkBL34J64W_cjs=require('./chunk-BL34J64W.cjs');require('./chunk-RBZNQINT.cjs'),require('./chunk-UJNSOOYZ.cjs'),require('./chunk-65G73T7Z.cjs'),require('./chunk-CVVW4LXZ.cjs'),require('./chunk-ZPUIRXKS.cjs'),require('./chunk-RXOAX7GO.cjs'),require('./chunk-AJAZ7D3W.cjs'),require('./chunk-WIZ6C5QZ.cjs'),require('./chunk-GFU7AOI3.cjs'),require('./chunk-ET6NN2V2.cjs'),require('./chunk-HVXO3OFB.cjs'),require('./chunk-ISWMETHJ.cjs'),require('./chunk-NY47CFVP.cjs'),require('./chunk-F7SR5IDT.cjs'),require('./chunk-4ORJMSJU.cjs'),require('./chunk-X3RRRWIN.cjs'),require('./chunk-GYQMNXXW.cjs'),require('./chunk-MIOMMB23.cjs'),require('./chunk-UBHFUFD4.cjs'),require('./chunk-WMY7BDPK.cjs'),require('./chunk-ATLSIYRH.cjs'),require('./chunk-W4ZDETHA.cjs'),require('./chunk-Q3Q7BJVQ.cjs'),require('./chunk-AHSFSERC.cjs');function n(){return new Response(JSON.stringify({error:"tRPC is disabled"}),{status:503,headers:{"Content-Type":"application/json"}})}var r={graphqlEnabled:false,trpcEnabled:false,wsEnabled:false,requireAuth:false};async function s(){try{return (await chunkBL34J64W_cjs.a.db.findOne({collection:"_globals_access-settings",where:{},draft:!0}))?.apiAccess?.trpcEnabled??r.trpcEnabled}catch{return true}}var i=async e=>(await chunkBL34J64W_cjs.b(),await s()?chunkBL34J64W_cjs.a.getTRPC().fetch(e.request,e.locals):n());exports.ALL=i;
|
package/dist/api-handler-trpc.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import {b,a}from'./chunk-
|
|
1
|
+
import {b,a}from'./chunk-CFMATLA3.js';import'./chunk-5H7LD62N.js';import'./chunk-FO3HLBC7.js';import'./chunk-NZ35PV5R.js';import'./chunk-7N6NKCRT.js';import'./chunk-GPKEOELO.js';import'./chunk-TRFBYBYC.js';import'./chunk-7WOX27LK.js';import'./chunk-K6WUOU6P.js';import'./chunk-AE6GXUT7.js';import'./chunk-2W4FK6CJ.js';import'./chunk-NRLIGDYF.js';import'./chunk-UVTS2IWM.js';import'./chunk-HLSB2MCK.js';import'./chunk-SL3LZQCF.js';import'./chunk-PP5S2UBV.js';import'./chunk-MBUUNROA.js';import'./chunk-RHCWCG3O.js';import'./chunk-OG7CNQGU.js';import'./chunk-QRXDCV6K.js';import'./chunk-TYOVXKQP.js';import'./chunk-P7CESLDJ.js';import'./chunk-4YYBWCDJ.js';import'./chunk-KDNYHLD2.js';import'./chunk-5J6HXUF6.js';function n(){return new Response(JSON.stringify({error:"tRPC is disabled"}),{status:503,headers:{"Content-Type":"application/json"}})}var r={graphqlEnabled:false,trpcEnabled:false,wsEnabled:false,requireAuth:false};async function s(){try{return (await a.db.findOne({collection:"_globals_access-settings",where:{},draft:!0}))?.apiAccess?.trpcEnabled??r.trpcEnabled}catch{return true}}var i=async e=>(await b(),await s()?a.getTRPC().fetch(e.request,e.locals):n());export{i as ALL};
|
package/dist/api-handler.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
'use strict';var
|
|
1
|
+
'use strict';var chunkBL34J64W_cjs=require('./chunk-BL34J64W.cjs');require('./chunk-RBZNQINT.cjs'),require('./chunk-UJNSOOYZ.cjs'),require('./chunk-65G73T7Z.cjs'),require('./chunk-CVVW4LXZ.cjs'),require('./chunk-ZPUIRXKS.cjs'),require('./chunk-RXOAX7GO.cjs'),require('./chunk-AJAZ7D3W.cjs'),require('./chunk-WIZ6C5QZ.cjs'),require('./chunk-GFU7AOI3.cjs'),require('./chunk-ET6NN2V2.cjs'),require('./chunk-HVXO3OFB.cjs'),require('./chunk-ISWMETHJ.cjs'),require('./chunk-NY47CFVP.cjs'),require('./chunk-F7SR5IDT.cjs'),require('./chunk-4ORJMSJU.cjs'),require('./chunk-X3RRRWIN.cjs'),require('./chunk-GYQMNXXW.cjs'),require('./chunk-MIOMMB23.cjs'),require('./chunk-UBHFUFD4.cjs'),require('./chunk-WMY7BDPK.cjs'),require('./chunk-ATLSIYRH.cjs'),require('./chunk-W4ZDETHA.cjs'),require('./chunk-Q3Q7BJVQ.cjs'),require('./chunk-AHSFSERC.cjs');Object.defineProperty(exports,"ALL",{enumerable:true,get:function(){return chunkBL34J64W_cjs.c}});Object.defineProperty(exports,"kyroInstance",{enumerable:true,get:function(){return chunkBL34J64W_cjs.a}});Object.defineProperty(exports,"warmKyroInstance",{enumerable:true,get:function(){return chunkBL34J64W_cjs.b}});
|
package/dist/api-handler.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export{c as ALL,a as kyroInstance,b as warmKyroInstance}from'./chunk-
|
|
1
|
+
export{c as ALL,a as kyroInstance,b as warmKyroInstance}from'./chunk-CFMATLA3.js';import'./chunk-5H7LD62N.js';import'./chunk-FO3HLBC7.js';import'./chunk-NZ35PV5R.js';import'./chunk-7N6NKCRT.js';import'./chunk-GPKEOELO.js';import'./chunk-TRFBYBYC.js';import'./chunk-7WOX27LK.js';import'./chunk-K6WUOU6P.js';import'./chunk-AE6GXUT7.js';import'./chunk-2W4FK6CJ.js';import'./chunk-NRLIGDYF.js';import'./chunk-UVTS2IWM.js';import'./chunk-HLSB2MCK.js';import'./chunk-SL3LZQCF.js';import'./chunk-PP5S2UBV.js';import'./chunk-MBUUNROA.js';import'./chunk-RHCWCG3O.js';import'./chunk-OG7CNQGU.js';import'./chunk-QRXDCV6K.js';import'./chunk-TYOVXKQP.js';import'./chunk-P7CESLDJ.js';import'./chunk-4YYBWCDJ.js';import'./chunk-KDNYHLD2.js';import'./chunk-5J6HXUF6.js';
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import {b}from'./chunk-KDNYHLD2.js';var a=class{collections=new Map;globals=new Map;connected=false;tenantContext;setTenantContext(e){this.tenantContext=e;}getTenantContext(){return this.tenantContext}async init(e,n=[]){for(let t of e)this.collections.set(t.slug,t);for(let t of n)this.globals.set(t.slug,t);await this.connect();}getCollection(e){let n=this.collections.get(e);if(!n)throw console.error(`[Adapter] Missing collection "${e}". Available collections:`,Array.from(this.collections.keys())),new Error(`Collection "${e}" not found in adapter`);return n}applyTenantFilter(e={},n){return n?{...e,tenantID:{equals:n}}:e}getTableName(e){return e.replace(/-/g,"_")}prepareData(e,n){let t={...e};return n.timestamps&&(t.updatedAt=new Date().toISOString(),t.createdAt||(t.createdAt=new Date().toISOString())),n.auth&&t.password,t}processRelationships(e,n,t){return e}parseSort(e){return e?e.startsWith("-")?{field:e.slice(1),direction:"desc"}:{field:e,direction:"asc"}:{field:"createdAt",direction:"desc"}}calculatePagination(e,n,t){let r=Math.ceil(t/n);return {totalDocs:t,limit:n,totalPages:r,page:e,pagingCounter:(e-1)*n+1,hasPrevPage:e>1,hasNextPage:e<r,prevPage:e>1?e-1:null,nextPage:e<r?e+1:null}}selectFields(e,n){if(!n||n.length===0)return e;let t={};for(let r of n)r in e&&(t[r]=e[r]);return t.id=e.id,t}isRelationshipField(e){return e.type==="relationship"}isUploadField(e){return e.type==="upload"}getRelationshipFields(e){let n=[];for(let t of e)t.type==="relationship"?n.push(t):"fields"in t&&t.fields&&n.push(...this.getRelationshipFields(t.fields));return n}getUploadFields(e){let n=[];for(let t of e)t.type==="upload"?n.push(t):"fields"in t&&t.fields&&n.push(...this.getUploadFields(t.fields));return n}};var s={tenantEnabled:true,tenantField:"tenantId",ownershipRules:{posts:{ownerField:"authorId",bypassRoles:["super_admin","admin","editor"]},pages:{ownerField:"authorId",bypassRoles:["super_admin","admin","editor"]},media:{ownerField:"uploadedBy",bypassRoles:["super_admin","admin","editor"]},orders:{ownerField:"customerId",bypassRoles:["super_admin","admin","editor"]},customers:{ownerField:"id",bypassRoles:["super_admin","admin"]},navigation:{ownerField:"id",bypassRoles:["super_admin","admin"]}}};function d(i,e,n=s){return !n.tenantEnabled||e.isSuperAdmin?i:{...i,where:{...i.where,[n.tenantField]:e.tenantId}}}function l(i,e,n,t=s){let r=t.ownershipRules[e];return !r||r.bypassRoles&&b({role:n.role},r.bypassRoles)?i:r.ownerField==="id"&&n.userId?{...i,where:{...i.where,id:n.userId}}:r.ownerField&&n.userId?{...i,where:{...i.where,[r.ownerField]:n.userId}}:i}function u(i,e,n,t=s){let r=i;return r=d(r,n,t),r=l(r,e,n,t),r}function p(i,e,n,t=s){if(n.isSuperAdmin)return true;if(t.tenantEnabled&&i[t.tenantField]!==n.tenantId)return false;let r=t.ownershipRules[e];return !r||r.bypassRoles&&b({role:n.role},r.bypassRoles)?true:r.ownerField==="id"?i.id===n.userId:r.ownerField?i[r.ownerField]===n.userId:true}export{a,s as b,u as c,p as d};
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import {a}from'./chunk-NZ35PV5R.js';import {a as a$2,i}from'./chunk-7N6NKCRT.js';import {c as c$1,a as a$1}from'./chunk-GPKEOELO.js';import {f,s,a as a$4,b as b$2,c as c$3}from'./chunk-TRFBYBYC.js';import {n,e,f as f$1}from'./chunk-UVTS2IWM.js';import {d,f as f$2,e as e$1,g as g$1}from'./chunk-HLSB2MCK.js';import {b,d as d$1}from'./chunk-SL3LZQCF.js';import {c}from'./chunk-MBUUNROA.js';import {g}from'./chunk-OG7CNQGU.js';import {a as a$3,c as c$2,b as b$1,d as d$2}from'./chunk-4YYBWCDJ.js';import {z as z$1}from'zod';import {createYoga}from'graphql-yoga';import {createRequire}from'module';import {randomBytes}from'crypto';function O(s,e){for(let t of s){if(t.name===e)return true;if("tabs"in t&&t.tabs){for(let n of t.tabs)if(O(n.fields,e))return true}if("fields"in t&&t.fields&&O(t.fields,e))return true}return false}var K=class extends Error{errors;constructor(e){super(`Configuration validation failed:
|
|
2
|
+
${e.join(`
|
|
3
|
+
`)}`),this.name="ConfigValidationError",this.errors=e;}};function V(s){let e=[];if(s.slug?/^[a-z][a-z0-9_-]*$/.test(s.slug)||e.push(`Collection slug "${s.slug}" must be lowercase alphanumeric with dashes`):e.push('Collection is missing a "slug" property'),!s.fields||s.fields.length===0)e.push(`Collection "${s.slug}" has no fields defined`);else {let t=x(s.fields,s.slug);e.push(...t);}if(s.access)for(let[t,n]of Object.entries(s.access))typeof n!="boolean"&&typeof n!="function"&&e.push(`Collection "${s.slug}" has invalid access.${t} (must be boolean or function)`);if(s.admin?.useAsTitle&&(O(s.fields,s.admin.useAsTitle)||e.push(`Collection "${s.slug}" admin.useAsTitle references unknown field "${s.admin.useAsTitle}"`)),s.admin?.defaultColumns)for(let t of s.admin.defaultColumns)O(s.fields,t)||e.push(`Collection "${s.slug}" admin.defaultColumns references unknown field "${t}"`);if(s.upload&&s.upload.fileSize&&s.upload.fileSize<=0&&e.push(`Collection "${s.slug}" upload.fileSize must be positive`),s.versions&&s.versions.maxPerDoc&&s.versions.maxPerDoc<=0&&e.push(`Collection "${s.slug}" versions.maxPerDoc must be positive`),s.auth){let t=s.fields.some(a=>a.name==="email"),n=s.fields.some(a=>a.name==="password");t||e.push(`Collection "${s.slug}" with auth enabled requires an "email" field`),n||e.push(`Collection "${s.slug}" with auth enabled requires a "password" field`);}return e}function B(s){let e=[];if(s.slug?/^[a-z][a-z0-9_-]*$/.test(s.slug)||e.push(`Global slug "${s.slug}" must be lowercase alphanumeric with dashes`):e.push('Global is missing a "slug" property'),!s.fields||s.fields.length===0)e.push(`Global "${s.slug}" has no fields defined`);else {let t=x(s.fields,`global:${s.slug}`);e.push(...t);}return e}function x(s,e){let t=[],n=new Set;for(let a=0;a<s.length;a++){let o=s[a];if(o.type==="row"||o.type==="collapsible"||o.type==="tabs"){if("fields"in o&&o.fields){let r=x(o.fields,e);t.push(...r);}else if("tabs"in o)for(let r of o.tabs){let c=x(r.fields,e);t.push(...c);}continue}let i=o.name;if(!i){t.push(`${e}: Field at index ${a} is missing a "name" property`);continue}if(n.has(i)&&t.push(`${e}: Duplicate field name "${i}"`),n.add(i),/^[a-zA-Z][a-zA-Z0-9_]*$/.test(i)||t.push(`${e}: Field name "${i}" must be alphanumeric with underscores`),!o.type){t.push(`${e}: Field "${i}" is missing a "type" property`);continue}switch(o.type){case "relationship":o.relationTo||t.push(`${e}: Relationship field "${i}" is missing "relationTo"`);break;case "array":if(!o.fields||o.fields.length===0)t.push(`${e}: Array field "${i}" has no fields defined`);else {let r=x(o.fields,`${e}.${i}`);t.push(...r);}break;case "group":if(!o.fields||o.fields.length===0)t.push(`${e}: Group field "${i}" has no fields defined`);else {let r=x(o.fields,`${e}.${i}`);t.push(...r);}break;case "blocks":if(!o.blocks||o.blocks.length===0)t.push(`${e}: Blocks field "${i}" has no blocks defined`);else {let r=we(o.blocks,`${e}.${i}`);t.push(...r);}break;case "select":case "radio":if((!o.options||o.options.length===0)&&!o.dynamicOptions)t.push(`${e}: ${o.type} field "${i}" has no options defined`);else if(o.options){let r=o.options.map(d=>d.value),c=new Set(r);r.length!==c.size&&t.push(`${e}: ${o.type} field "${i}" has duplicate option values`);}break;case "upload":o.relationTo||t.push(`${e}: Upload field "${i}" is missing "relationTo"`);break}"min"in o&&"max"in o&&o.min>o.max&&t.push(`${e}: Field "${i}" has min greater than max`),"minLength"in o&&"maxLength"in o&&o.minLength>o.maxLength&&t.push(`${e}: Field "${i}" has minLength greater than maxLength`),"minRows"in o&&"maxRows"in o&&o.minRows>o.maxRows&&t.push(`${e}: Field "${i}" has minRows greater than maxRows`);}return t}function we(s,e){let t=[],n=new Set;for(let a of s){if(!a.slug){t.push(`${e}: Block is missing a "slug" property`);continue}if(n.has(a.slug)&&t.push(`${e}: Duplicate block slug "${a.slug}"`),n.add(a.slug),a.label||t.push(`${e}: Block "${a.slug}" is missing a "label" property`),!a.fields||a.fields.length===0)t.push(`${e}: Block "${a.slug}" has no fields defined`);else {let o=x(a.fields,`${e}.${a.slug}`);t.push(...o);}}return t}function pe(s,e=[]){let t=[],n=new Set;for(let a of s)n.has(a.slug)&&t.push(`Duplicate collection slug "${a.slug}"`),n.add(a.slug);for(let a of e)n.has(a.slug)&&t.push(`Duplicate global slug "${a.slug}"`),n.add(a.slug);for(let a of s){let o=V(a);t.push(...o);}for(let a of e){let o=B(a);t.push(...o);}for(let a of s){let o=$(a.fields,s);t.push(...o);}if(t.length>0)throw new K(t)}function $(s,e){let t=[],n=new Set(e.map(a=>a.slug));for(let a of s){if(a.type==="relationship"){let o=Array.isArray(a.relationTo)?a.relationTo:[a.relationTo];for(let i of o)n.has(i)||console.warn(`[Kyro Config Warning]: Relationship field "${a.name}" references unknown collection "${i}". Select options will not be available until this collection is registered.`);}if(a.type==="upload"){let o=Array.isArray(a.relationTo)?a.relationTo:[a.relationTo];for(let i of o)n.has(i)||t.push(`Upload field "${a.name}" references unknown collection "${i}"`);}if("fields"in a&&a.fields){let o=$(a.fields,e);t.push(...o);}if("tabs"in a)for(let o of a.tabs){let i=$(o.fields,e);t.push(...i);}if("blocks"in a)for(let o of a.blocks){let i=$(o.fields,e);t.push(...i);}}return t}function C(s){switch(s.type){case "text":return Fe(s);case "number":return Ie(s);case "checkbox":return $e(s);case "date":return Oe(s);case "email":return Pe(s);case "password":return Le(s);case "textarea":return ke(s);case "select":return _e(s);case "radio":return je(s);case "color":return Ze(s);case "richtext":return qe(s);case "json":return Ue(s);case "code":return Ge(s);case "upload":return fe(s);case "image":return fe(s);case "markdown":return Ke(s);case "relationship":return ye(s);case "relationship-block":return ye(s);case "array":return Ve(s);case "list":return Be(s);case "group":return Me(s);case "blocks":return ze(s);case "row":return We(s);case "collapsible":return Xe(s);case "tabs":return Je(s);default:return z$1.any()}}function Fe(s){let e=z$1.string();return s.minLength&&(e=e.min(s.minLength)),s.maxLength&&(e=e.max(s.maxLength)),s.pattern&&(e=e.regex(new RegExp(s.pattern))),s.variant==="email"&&(e=e.email()),s.variant==="url"&&(e=e.url()),s.hasMany&&(e=z$1.array(e)),s.required||(e=e.optional().nullable()),s.validate&&(e=T(e,s.validate)),e}function Ie(s){let e=s.integer?z$1.coerce.number().int():z$1.coerce.number();return s.min!==void 0&&(e=e.min(s.min)),s.max!==void 0&&(e=e.max(s.max)),s.step&&(e=e.refine(t=>Number.isInteger(t/s.step),`Value must be divisible by ${s.step}`)),s.hasMany&&(e=z$1.array(e)),s.required||(e=e.optional().nullable()),s.validate&&(e=T(e,s.validate)),e}function $e(s){let e=z$1.boolean();return s.required||(e=e.optional().nullable()),s.validate&&(e=T(e,s.validate)),e}function Oe(s){let e=z$1.string().refine(t=>!isNaN(Date.parse(t)),"Invalid date format");return s.minDate&&(e=e.refine(t=>new Date(t)>=new Date(s.minDate),`Date must be after ${s.minDate}`)),s.maxDate&&(e=e.refine(t=>new Date(t)<=new Date(s.maxDate),`Date must be before ${s.maxDate}`)),s.required||(e=e.optional().nullable()),s.validate&&(e=T(e,s.validate)),e}function Pe(s){let e=z$1.string().email("Invalid email");return s.required||(e=e.optional().nullable()),s.validate&&(e=T(e,s.validate)),e}function Le(s){let e=z$1.string().min(6,"Password must be at least 6 characters");return s.required||(e=e.optional().nullable()),s.validate&&(e=T(e,s.validate)),e}function ke(s){let e=z$1.string();return s.minLength&&(e=e.min(s.minLength)),s.maxLength&&(e=e.max(s.maxLength)),s.required||(e=e.optional().nullable()),s.validate&&(e=T(e,s.validate)),e}function _e(s){let e;if(s.options&&s.options.length>0){let t=s.options.map(n=>n.value);s.hasMany?e=z$1.array(z$1.enum(t)):e=z$1.enum(t);}else e=s.hasMany?z$1.array(z$1.string()):z$1.string();return s.required||(e=e.optional().nullable()),s.validate&&(e=T(e,s.validate)),e}function je(s){let e=s.options.map(n=>n.value),t=z$1.enum(e);return s.required||(t=t.optional().nullable()),s.validate&&(t=T(t,s.validate)),t}function Ze(s){let e=z$1.string();return s.format==="hex"&&(e=e.regex(/^#[0-9A-Fa-f]{6}$/)),s.format==="rgb"&&(e=e.regex(/^rgb\(\s*\d{1,3}\s*,\s*\d{1,3}\s*,\s*\d{1,3}\s*\)$/)),s.format==="hsl"&&(e=e.regex(/^hsl\(\s*\d{1,3}\s*,\s*\d{1,3}%\s*,\s*\d{1,3}%\s*\)$/)),s.required||(e=e.optional().nullable()),s.validate&&(e=T(e,s.validate)),e}function qe(s){let e=z$1.array(z$1.record(z$1.any()));return s.required||(e=e.optional().nullable()),s.validate&&(e=T(e,s.validate)),e}function Ue(s){let e=z$1.union([z$1.record(z$1.any()),z$1.array(z$1.any())]);return s.required||(e=e.optional().nullable()),s.validate&&(e=T(e,s.validate)),e}function Ge(s){let e=z$1.string();return s.required||(e=e.optional().nullable()),s.validate&&(e=T(e,s.validate)),e}function fe(s){let e;if(s.relationTo){let t=z$1.object({id:z$1.string(),url:z$1.string().optional(),filename:z$1.string().optional(),mimeType:z$1.string().optional()});e=z$1.union([z$1.string(),t]);}else e=z$1.string();return s.hasMany&&(e=z$1.array(e)),s.required||(e=e.optional().nullable()),s.validate&&(e=T(e,s.validate)),e}function Ke(s){let e=z$1.string();return s.required||(e=e.optional().nullable()),s.validate&&(e=T(e,s.validate)),e}function ye(s){let e;return Array.isArray(s.relationTo)?e=z$1.object({relationTo:z$1.enum(s.relationTo),value:z$1.string()}):e=z$1.union([z$1.string(),z$1.object({relationTo:z$1.string(),value:z$1.string()})]),s.hasMany&&(e=z$1.array(e)),s.required||(e=e.optional().nullable()),s.validate&&(e=T(e,s.validate)),e}function Ve(s){let e=z$1.object(Object.fromEntries(s.fields.filter(n=>n.name).map(n=>[n.name,C(n)]))),t=z$1.array(e);return s.minRows&&(t=t.min(s.minRows)),s.maxRows&&(t=t.max(s.maxRows)),s.required||(t=t.optional().nullable()),s.validate&&(t=T(t,s.validate)),t}function Be(s){let e=z$1.array(z$1.string());return s.required||(e=e.optional().nullable()),e}function Me(s){let e=z$1.object(Object.fromEntries(s.fields.filter(t=>t.name).map(t=>[t.name,C(t)])));return s.required?e:e.optional().nullable()}function ze(s){let e=s.blocks||[];e.map(o=>z$1.object({blockType:z$1.literal(o.slug),...Object.fromEntries(o.fields.filter(i=>i.name).map(i=>[i.name,C(i)]))}));let n=e.map(o=>o.slug),a;if(n.length>0){let o=z$1.object({blockType:z$1.enum(n)}).catchall(z$1.any()),i=z$1.object({blockType:z$1.string()}).catchall(z$1.any());a=z$1.array(z$1.union([o,i,z$1.record(z$1.any())]));}else a=z$1.array(z$1.union([z$1.object({blockType:z$1.string()}).catchall(z$1.any()),z$1.record(z$1.any())]));return s.minRows&&(a=a.min(s.minRows)),s.maxRows&&(a=a.max(s.maxRows)),s.required||(a=a.optional().nullable()),s.validate&&(a=T(a,s.validate)),a}function We(s){return z$1.object(Object.fromEntries(s.fields.filter(t=>t.name).map(t=>[t.name,C(t)])))}function Xe(s){return z$1.object(Object.fromEntries(s.fields.filter(t=>t.name).map(t=>[t.name,C(t)])))}function Je(s){let e={};for(let t of s.tabs)for(let n of t.fields)n.name&&(e[n.name]=C(n));return z$1.object(e).passthrough().optional()}function T(s,e){return s.refine(async t=>await e(t,{required:false})===true,{message:"Custom validation failed"})}function R(s){let e={};for(let t of s)if(t.name)if(t.type==="tabs"&&"tabs"in t){let n={};for(let a of t.tabs){let o=R(a.fields);Object.assign(n,o);}e[t.name]=z$1.object(n).passthrough().optional();}else if(t.type==="row"&&"fields"in t){let n=R(t.fields);Object.assign(e,n);}else t.type==="collapsible"&&"fields"in t?e[t.name]=z$1.object(R(t.fields)).passthrough().optional():e[t.name]=C(t);return e}function E(s){let e={};for(let t of s)if(t.name)if(t.type==="tabs"&&"tabs"in t){let n={};for(let a of t.tabs){let o=E(a.fields);Object.assign(n,o);}e[t.name]=z$1.object(n).passthrough().optional().nullable();}else if(t.type==="row"&&"fields"in t){let n=E(t.fields);Object.assign(e,n);}else t.type==="collapsible"&&"fields"in t?e[t.name]=z$1.object(E(t.fields)).passthrough().optional().nullable():t.type==="group"&&"fields"in t?e[t.name]=z$1.object(E(t.fields)).passthrough().optional().nullable():e[t.name]=C(t).optional().nullable();return e}function he(s){let e=R(s.fields);return s.timestamps&&(e.createdAt=z$1.string().optional(),e.updatedAt=z$1.string().optional()),s.tenantScoped&&(e.tenantID=z$1.string().optional()),e.id=z$1.string().optional(),z$1.object(e).passthrough()}function ge(s){let e=R(s.fields);return z$1.object(e).passthrough()}function me(s){let e={};for(let t of s.fields)if(t.name)if(t.type==="tabs"&&"tabs"in t){let n={};for(let a of t.tabs)for(let o of a.fields)o.name&&(n[o.name]=C(o).optional().nullable());e[t.name]=z$1.object(n).optional().nullable();}else if(t.type==="row"&&"fields"in t){let n={};for(let a of t.fields)a.name&&(n[a.name]=C(a).optional().nullable());Object.assign(e,n);}else t.type==="collapsible"&&"fields"in t?e[t.name]=z$1.object(E(t.fields)).optional().nullable():t.type==="group"&&"fields"in t?e[t.name]=z$1.object(E(t.fields)).optional().nullable():e[t.name]=C(t).optional().nullable();return z$1.object(e).passthrough()}function be(s){let e={};for(let t of s.fields)t.name&&(e[t.name]=z$1.object({equals:z$1.any().optional(),not_equals:z$1.any().optional(),in:z$1.array(z$1.any()).optional(),not_in:z$1.array(z$1.any()).optional(),greater_than:z$1.number().optional(),greater_than_equal:z$1.number().optional(),less_than:z$1.number().optional(),less_than_equal:z$1.number().optional(),like:z$1.string().optional(),not_like:z$1.string().optional(),contains:z$1.string().optional(),exists:z$1.boolean().optional()}).optional());return e.AND=z$1.array(z$1.lazy(()=>z$1.object(e))).optional(),e.OR=z$1.array(z$1.lazy(()=>z$1.object(e))).optional(),z$1.object(e).optional()}function Te(s){let e=R(s.fields);return e.id=z$1.string().optional(),z$1.object(e).passthrough()}function Ce(s){let e={};for(let t of s.fields)if(t.name)if(t.type==="tabs"&&"tabs"in t){let n={};for(let a of t.tabs)for(let o of a.fields)o.name&&(n[o.name]=C(o).optional().nullable());e[t.name]=z$1.object(n).optional().nullable();}else t.type==="collapsible"&&"fields"in t?e[t.name]=z$1.object(E(t.fields)).optional().nullable():t.type==="group"&&"fields"in t?e[t.name]=z$1.object(E(t.fields)).optional().nullable():e[t.name]=C(t).optional().nullable();return z$1.object(e).passthrough()}var w=class{storageProviders=f();collections=new Map;globals=new Map;plugins=[];schemaCache=new Map;initialized=false;addCollection(e){if(this.initialized)throw new Error("Cannot add collections after Registry has been initialized");if(this.collections.has(e.slug)){console.warn(`[Registry] Duplicate collection slug "${e.slug}" \u2014 skipping`);return}let t={...e};for(let a of this.plugins)a.extendCollection&&(t=a.extendCollection(t.slug,t));t.fields=this.applyFieldDefaults(t);let n=V(t);if(n.length>0)throw new Error(`Invalid collection config: ${n.join(", ")}`);this.collections.set(t.slug,t),this.clearSchemaCache(t.slug);}addCollections(e){for(let t of e)this.addCollection(t);}getCollection(e){return this.collections.get(e)}getCollections(){return Array.from(this.collections.values())}getCollectionSlugs(){return Array.from(this.collections.keys())}hasCollection(e){return this.collections.has(e)}removeCollection(e){if(this.initialized)throw new Error("Cannot remove collections after Registry has been initialized");return this.clearSchemaCache(e),this.collections.delete(e)}addGlobal(e){if(this.initialized)throw new Error("Cannot add globals after Registry has been initialized");this._addGlobalUnsafe(e);}addGlobalPostInit(e){this.globals.has(e.slug)&&this.globals.delete(e.slug),this._addGlobalUnsafe(e);}_addGlobalUnsafe(e){if(this.globals.has(e.slug)){console.warn(`[Registry] Duplicate global slug "${e.slug}" \u2014 skipping`);return}let t=B(e);if(t.length>0)throw new Error(`Invalid global config: ${t.join(", ")}`);let n={...e};for(let a of this.plugins)a.extendGlobal&&(n=a.extendGlobal(n.slug,n));this.globals.set(n.slug,n),this.clearSchemaCache(`global:${n.slug}`);}addGlobals(e){for(let t of e)this.addGlobal(t);}getGlobal(e){return this.globals.get(e)}getGlobals(){return Array.from(this.globals.values())}getGlobalSlugs(){return Array.from(this.globals.keys())}hasGlobal(e){return this.globals.has(e)}removeGlobal(e){if(this.initialized)throw new Error("Cannot remove globals after Registry has been initialized");return this.clearSchemaCache(`global:${e}`),this.globals.delete(e)}addPlugin(e){if(this.initialized)throw new Error("Cannot add plugins after Registry has been initialized");this.plugins.push(e);}getPlugins(){return [...this.plugins]}getZodSchema(e){let t=this.schemaCache.get(e);if(t)return t;let n=this.collections.get(e);if(n){let o=he(n);return this.schemaCache.set(e,o),o}let a=this.globals.get(e);if(a){let o=Te(a);return this.schemaCache.set(`global:${e}`,o),o}throw new Error(`No collection or global found with slug "${e}"`)}getCreateZodSchema(e){let t=`${e}:create`,n=this.schemaCache.get(t);if(n)return n;let a=this.collections.get(e);if(a){let o=ge(a);return this.schemaCache.set(t,o),o}throw new Error(`No collection found with slug "${e}"`)}getUpdateZodSchema(e){let t=`${e}:update`,n=this.schemaCache.get(t);if(n)return n;let a=this.collections.get(e);if(a){let i=me(a);return this.schemaCache.set(t,i),i}let o=this.globals.get(e);if(o){let i=Ce(o);return this.schemaCache.set(`global:${e}:update`,i),i}throw new Error(`No collection or global found with slug "${e}"`)}getWhereZodSchema(e){let t=`${e}:where`,n=this.schemaCache.get(t);if(n)return n;let a=this.collections.get(e);if(a){let o=be(a);return this.schemaCache.set(t,o),o}throw new Error(`No collection found with slug "${e}"`)}getFieldZodSchema(e){return C(e)}clearSchemaCache(e){this.schemaCache.delete(e),this.schemaCache.delete(`${e}:create`),this.schemaCache.delete(`${e}:update`),this.schemaCache.delete(`${e}:where`);}applyFieldDefaults(e){let t=[...e.fields];return t.some(n=>n.name==="id")||t.unshift({name:"id",type:"text",admin:{readOnly:true,hidden:true}}),e.tenantScoped&&!t.some(n=>n.name==="tenantID")&&t.push({name:"tenantID",type:"text",required:true,admin:{readOnly:true,hidden:true}}),e.timestamps&&!t.some(n=>n.name==="createdAt")&&(t.push({name:"createdAt",type:"date",admin:{readOnly:true,hidden:true}}),t.push({name:"updatedAt",type:"date",admin:{readOnly:true,hidden:true}})),e.versions?.drafts&&!t.some(n=>n.name==="status")&&t.push({name:"status",type:"select",options:[{value:"draft",label:"Draft"},{value:"published",label:"Published"}],admin:{readOnly:true,hidden:true}}),e.auth&&!t.some(n=>n.name==="password")&&t.push({name:"password",type:"password",required:true,admin:{hidden:true}}),t}getFields(e){let t=this.collections.get(e);if(t)return t.fields;let n=this.globals.get(e);if(n)return n.fields;throw new Error(`No collection or global found with slug "${e}"`)}getFieldMap(e){let t=this.getFields(e),n=new Map,a=o=>{for(let i of o){if(i.name&&n.set(i.name,i),"fields"in i&&i.fields&&a(i.fields),"tabs"in i)for(let r of i.tabs)a(r.fields);if("blocks"in i)for(let r of i.blocks)a(r.fields);}};return a(t),n}getVisibleFields(e){return this.getFields(e).filter(n=>!n.admin?.hidden)}validate(){let e=this.getCollections(),t=this.getGlobals();pe(e,t);}async init(e){this.validate();for(let t of this.plugins)t.init&&await t.init(e||this);this.initialized=true;}isInitialized(){return this.initialized}getPaginationDefaults(e){let t=this.collections.get(e);return {defaultLimit:t?.admin?.pagination?.defaultLimit||10,limits:t?.admin?.pagination?.limits||[10,25,50,100]}}getDefaultSort(e){let n=this.collections.get(e)?.admin?.useAsTitle;return n||"createdAt"}getDefaultColumns(e){let t=this.collections.get(e);return t?.admin?.defaultColumns?t.admin.defaultColumns:this.getVisibleFields(e).slice(0,4).map(a=>a.name)}getAdminTitle(e){let t=this.collections.get(e);return t?.label||t?.admin?.description||e}getAdminLabel(e){let t=this.collections.get(e);return t?.singularLabel||t?.label||e}getAdminGroup(e){return this.collections.get(e)?.admin?.group}getStats(){let e=0;for(let t of this.collections.values())e+=t.fields.length;for(let t of this.globals.values())e+=t.fields.length;return {collections:this.collections.size,globals:this.globals.size,plugins:this.plugins.length,fields:e}}toJSON(){return {collections:this.getCollections(),globals:this.getGlobals()}}},v=null;function He(){return v||(v=new w),v}function Ye(){v=null;}function M(){return v=new w,v}var Qe={aws:{type:"aws",configKey:"s3",displayName:"S3 Compatible (AWS, Backblaze, Wasabi, etc.)",configFields:[{name:"bucket",type:"text",label:"Bucket Name",required:true},{name:"region",type:"text",label:"Region",defaultValue:"us-east-1",admin:{placeholder:"us-east-1"}},{name:"accessKeyId",type:"text",label:"Access Key ID",required:true},{name:"secretAccessKey",type:"password",label:"Secret Access Key",required:true},{name:"endpoint",type:"text",label:"Endpoint URL",admin:{placeholder:"https://s3.custom.com"}},{name:"cdnUrl",type:"text",label:"CDN URL",admin:{placeholder:"https://cdn.example.com"}},{name:"prefix",type:"text",label:"Path Prefix",admin:{placeholder:"uploads"}}]},r2:{type:"r2",configKey:"r2",displayName:"Cloudflare R2",configFields:[{name:"accountId",type:"text",label:"Account ID",required:true,admin:{placeholder:"Your Cloudflare Account ID"}},{name:"accessKeyId",type:"text",label:"Access Key ID",required:true},{name:"secretAccessKey",type:"password",label:"Secret Access Key",required:true},{name:"bucket",type:"text",label:"Bucket Name",required:true},{name:"publicDevUrl",type:"text",label:"Public Dev URL ID",admin:{placeholder:"pub-xxxxxxxxxxxxxxxx",description:"Enter ONLY the ID (e.g., pub-b8d8c4cc8bcf4d868ddd95efc1b305aa). Do NOT include https:// or the full URL. Found in R2 Dashboard \u2192 Public Dev URL."}},{name:"cdnUrl",type:"text",label:"Custom CDN URL",admin:{placeholder:"https://assets.example.com (optional)"}},{name:"prefix",type:"text",label:"Path Prefix",admin:{placeholder:"uploads (optional)",description:"Optional prefix for all object keys. Do not use '/' as prefix."}}]},gcs:{type:"gcs",configKey:"gcs",displayName:"Google Cloud Storage",configFields:[{name:"bucket",type:"text",label:"Bucket Name",required:true},{name:"projectId",type:"text",label:"Project ID"},{name:"clientEmail",type:"text",label:"Client Email"},{name:"privateKey",type:"password",label:"Private Key"},{name:"cdnUrl",type:"text",label:"CDN URL"},{name:"prefix",type:"text",label:"Path Prefix"}]},digitalocean:{type:"digitalocean",configKey:"digitalocean",displayName:"DigitalOcean Spaces",configFields:[{name:"bucket",type:"text",label:"Bucket Name",required:true},{name:"region",type:"text",label:"Region",defaultValue:"nyc3"},{name:"accessKeyId",type:"text",label:"Access Key ID",required:true},{name:"secretAccessKey",type:"password",label:"Secret Access Key",required:true},{name:"cdnUrl",type:"text",label:"CDN URL"},{name:"prefix",type:"text",label:"Path Prefix"}]},backblaze:{type:"backblaze",configKey:"backblaze",displayName:"Backblaze B2",configFields:[{name:"bucket",type:"text",label:"Bucket Name",required:true},{name:"accountId",type:"text",label:"Account ID"},{name:"applicationKeyId",type:"text",label:"Application Key ID",required:true},{name:"applicationKey",type:"password",label:"Application Key",required:true},{name:"cdnUrl",type:"text",label:"CDN URL"},{name:"prefix",type:"text",label:"Path Prefix"}]},wasabi:{type:"wasabi",configKey:"wasabi",displayName:"Wasabi",configFields:[{name:"bucket",type:"text",label:"Bucket Name",required:true},{name:"region",type:"text",label:"Region",defaultValue:"us-east-1"},{name:"accessKeyId",type:"text",label:"Access Key ID",required:true},{name:"secretAccessKey",type:"password",label:"Secret Access Key",required:true},{name:"cdnUrl",type:"text",label:"CDN URL"},{name:"prefix",type:"text",label:"Path Prefix"}]}};function et(s,e){switch(s){case "r2":return e?.endpoint||`https://${e?.accountId||""}.r2.cloudflarestorage.com`;case "digitalocean":return e?.endpoint||`https://${e?.region||"nyc3"}.digitaloceanspaces.com`;case "backblaze":return e?.endpoint||"https://s3.backblazeb2.com";case "wasabi":return e?.endpoint||`https://s3.${e?.region||"us-east-1"}.wasabisys.com`;default:return e?.endpoint}}function Ae(s,e){return {provider:s,bucket:e?.bucket||"",region:e?.region||"us-east-1",accessKeyId:e?.accessKeyId||e?.clientEmail||e?.applicationKeyId||"",secretAccessKey:e?.secretAccessKey||e?.privateKey||e?.applicationKey||"",endpoint:et(s,e),cdnUrl:e?.cdnUrl,prefix:e?.prefix,accountId:e?.accountId,publicDevUrl:e?.publicDevUrl}}function tt(s,e,t){let n=t[e.configKey]||{};return Ae(s,n)}function st(s,e,t){let n=t?.[e.configKey]||t;return Ae(s,n)}var Se={name:"@kyro-cms/storage-s3",version:"1.0.0",description:"S3-compatible storage (AWS R2 GCS DigitalOcean Backblaze Wasabi)",init:s=>{let e=s.registry?.storageProviders;if(!e)return;let t="@kyro-cms/storage-s3";for(let n of Object.values(Qe))e.register({type:n.type,displayName:n.displayName,pluginName:t,configKey:n.configKey,configFields:n.configFields,extractConfig:a=>tt(n.type,n,a),extractRawConfig:a=>st(n.type,n,a),factory:a=>a$4(a)});}};var Ee={name:"@kyro-cms/storage-cloudinary",version:"1.0.0",description:"Cloudinary image and video storage",init:s=>{let e=s.registry?.storageProviders;e&&e.register({type:"cloudinary",displayName:"Cloudinary",pluginName:"@kyro-cms/storage-cloudinary",configKey:"cloudinary",configFields:[{name:"cloudName",type:"text",label:"Cloud Name",required:true},{name:"apiKey",type:"text",label:"API Key",required:true},{name:"apiSecret",type:"password",label:"API Secret",required:true},{name:"folder",type:"text",label:"Folder",admin:{placeholder:"Optional folder path"}},{name:"uploadPreset",type:"text",label:"Upload Preset (optional)",admin:{placeholder:"Leave empty for signed uploads",description:"If not set, uploads will be signed with API Secret"}}],extractConfig:t=>({cloudName:t.cloudinary?.cloudName||"",apiKey:t.cloudinary?.apiKey||"",apiSecret:t.cloudinary?.apiSecret||"",folder:t.cloudinary?.folder,uploadPreset:t.cloudinary?.uploadPreset}),extractRawConfig:t=>{let n=t?.cloudinary||t;return {cloudName:n?.cloudName||"",apiKey:n?.apiKey||"",apiSecret:n?.apiSecret||"",folder:n?.folder,uploadPreset:n?.uploadPreset}},factory:t=>b$2(t)});}};var xe={name:"@kyro-cms/storage-ftp",version:"1.0.0",description:"FTP/SFTP storage provider",init:s=>{let e=s.registry?.storageProviders;e&&e.register({type:"ftp",displayName:"FTP",pluginName:"@kyro-cms/storage-ftp",configKey:"ftp",configFields:[{name:"host",type:"text",label:"Host",required:true,admin:{placeholder:"ftp.example.com"}},{name:"port",type:"number",label:"Port",defaultValue:21,admin:{placeholder:"21 for FTP"}},{name:"user",type:"text",label:"Username",required:true},{name:"password",type:"password",label:"Password",required:true},{name:"secure",type:"checkbox",label:"Use TLS/SSL",defaultValue:false,admin:{description:"Enable TLS/SSL for secure connections (FTP only)"}},{name:"baseUrl",type:"text",label:"Base URL",required:true,admin:{placeholder:"https://files.example.com"}},{name:"prefix",type:"text",label:"Path Prefix",admin:{placeholder:"uploads"}}],extractConfig:t=>({host:t.ftp?.host||"",port:t.ftp?.port||21,user:t.ftp?.user||"",password:t.ftp?.password||"",secure:t.ftp?.secure||false,baseUrl:t.ftp?.baseUrl||"",prefix:t.ftp?.prefix,type:"ftp"}),extractRawConfig:t=>{let n=t?.ftp||t;return {host:n?.host||"",port:n?.port||21,user:n?.user||"",password:n?.password||"",secure:n?.secure||false,baseUrl:n?.baseUrl||"",prefix:n?.prefix,type:"ftp"}},factory:t=>c$3(t)});}};var at=[Se,Ee,xe];function z(s,e,t){let n=e.split(".");if(n.length===0)return false;let a=n[0],o=n.slice(1).join(".");for(let i of s)if(i.name===a)return o?i.fields&&Array.isArray(i.fields)||i.type==="array"&&i.fields&&Array.isArray(i.fields)?z(i.fields,o,t):false:(Object.assign(i,t),true);return false}function it(s,e){if(e)for(let t of s){let n=e[t.slug];if(n){let{fields:a,...o}=n;if(t.admin={...t.admin,...o},a&&t.fields&&Array.isArray(t.fields))for(let[i,r]of Object.entries(a))z(t.fields,i,r);}}}var W=class{registry;db;pubsub;webhookService;settings;wsServer;config;constructor(e){this.config=e,this.registry=M(),this.db=e.adapter,this.pubsub=new b(this.registry),this.webhookService=n(this.db);for(let t of at)this.registry.addPlugin(t);if(e.plugins)for(let t of e.plugins)this.registry.addPlugin(t);e.collections&&e.admin?.collectionOverrides&&it(e.collections,e.admin.collectionOverrides),e.collections&&this.registry.addCollections(e.collections),e.globals&&this.registry.addGlobals(e.globals);}async init(){await this.registry.init(this),this.registry.addGlobalPostInit(a);let e$1={slug:"plugin-settings",admin:{hidden:true},fields:[{name:"states",type:"json"}]};if(this.registry.addGlobalPostInit(e$1),!this.db)throw new Error("Database adapter is null \u2014 failed to load at startup. Check the server console for the exact error.");let t={slug:d,fields:[{name:"userId",type:"text",required:true},{name:"name",type:"text",required:true},{name:"key",type:"text",required:true},{name:"keyPrefix",type:"text",required:true},{name:"permissions",type:"json"},{name:"lastUsedAt",type:"date"},{name:"expiresAt",type:"date"}]},n={slug:e,fields:[{name:"name",type:"text",required:true},{name:"url",type:"text",required:true},{name:"events",type:"json",required:true},{name:"status",type:"text",required:true},{name:"secret",type:"text"},{name:"headers",type:"json"},{name:"lastTriggered",type:"date"},{name:"lastError",type:"text"}]},a$1={slug:f$1,fields:[{name:"webhookId",type:"text",required:true},{name:"event",type:"text",required:true},{name:"payload",type:"json",required:true},{name:"attempt",type:"number",required:true},{name:"status",type:"text",required:true},{name:"responseStatus",type:"number"},{name:"responseBody",type:"text"},{name:"error",type:"text"},{name:"duration",type:"number"},{name:"deliveredAt",type:"date"},{name:"nextRetryAt",type:"date"}]},o=this.registry.getGlobals();if(this.db instanceof c&&this.db.dialect==="postgres"){let i=this.db,r=d.replace(/-/g,"_");i.schema[r]||(i.schema[r]=g);}await this.db.init([...this.registry.getCollections(),t,n,a$1],o),await this.loadPluginState(),this.pubsub.autoRegisterHooks();}async loadSettings(){if(this.settings)return this.settings;try{let e=await this.db.findOne({collection:"_globals_access-settings",where:{},draft:!0});e&&(this.settings={access:e});}catch{}return this.settings||{}}async loadPluginState(){let e=this.registry.storageProviders,t=e.getAllPluginNames(),n={};try{let a=await this.db.findOne({collection:"_globals_plugin-settings",where:{},draft:!0});a&&a.states&&(n=a.states);}catch{}for(let a of t)n[a]!==void 0&&e.setPluginEnabled(a,n[a]);}getREST(e){let t=typeof this.config.auth=="object"?this.config.auth:null,n=t?.secret,a=t?.checkSession!==false;return s({registry:this.registry,db:this.db,authSecret:n,authAdapter:this.config.authAdapter,checkSession:a,...e,cors:this.config.cors,webhookService:this.webhookService,settings:this.settings})}getGraphQL(e){let t=c$1({registry:this.registry,db:this.db,settings:this.settings});return {fetch:createYoga({schema:t,context:async({request:a})=>{let o=f$2(a),i,r;if(o&&this.db){let d=await e$1(o,this.db);d.user&&(i=d.user,r=g$1(d));}let c=e?.tenantID;return {db:this.db,registry:this.registry,user:i,req:a,tenantID:c,apiKey:r,relationLoader:new a$1({db:this.db,tenantID:c,user:i})}},graphiql:this.config.graphQL?.disablePlayground!==true,plugins:[]}).fetch,schema:t}}getTRPC(e){return {fetch:async(t,n)=>{let o=new URL(t.url).pathname.replace(/^\/api\/trpc\//,""),[i$1,...r]=o.split("."),c=r.join(".");if(c=c.replace(/\.(query|mutate|subscribe)$/,""),!i$1||!c)return new Response(JSON.stringify({error:{message:"Invalid tRPC path",code:-32600,data:{code:"BAD_REQUEST",httpStatus:400}}}),{status:400,headers:{"Content-Type":"application/json"}});let d=await a$2({db:this.db,registry:this.registry,req:t,user:e?.user,tenantID:e?.tenantID,settings:this.settings}),p=i(d)[i$1];if(!p)return new Response(JSON.stringify({error:{message:`Collection '${i$1}' not found`,code:-32601,data:{code:"NOT_FOUND",httpStatus:404}}}),{status:404,headers:{"Content-Type":"application/json"}});let m=p[c];if(typeof m!="function")return new Response(JSON.stringify({error:{message:`Procedure '${c}' not found`,code:-32601,data:{code:"NOT_FOUND",httpStatus:404}}}),{status:404,headers:{"Content-Type":"application/json"}});try{let y={};if(t.method==="POST"||t.method==="PATCH")y=await t.json().catch(()=>({}));else {let A=new URL(t.url).searchParams.get("input");if(A)try{y=JSON.parse(decodeURIComponent(A));}catch{}}let h=y?.["0"]??y,f=await m({...h,collection:i$1});return new Response(JSON.stringify({result:{data:f}}),{status:200,headers:{"Content-Type":"application/json"}})}catch(y){let h=y.message||"Internal error",f=h.includes("not found")?404:h.includes("denied")||h.includes("authentication required")?403:h.includes("conflict")?409:500,A=f===404?-32601:f===403?-32001:f===409?-32002:-32603;return new Response(JSON.stringify({error:{message:h,code:A,data:{code:"INTERNAL_SERVER_ERROR",httpStatus:f}}}),{status:f,headers:{"Content-Type":"application/json"}})}},router:null}}getWS(){return this.wsServer}async startWebSocket(e){let t=this.settings?.access?.apiAccess;if(t?.wsEnabled===false)return null;let n=async a=>{let o=await e$1(a,this.db);if(!o.valid)throw new Error(o.error||"Invalid API key");if(!o.user)throw new Error("API key has no associated user");return o.user};return this.wsServer=d$1({pubsub:this.pubsub,port:e?.port||8080,requireAuth:e?.requireAuth??t?.requireAuth,verifyToken:e?.verifyToken||n}),this.wsServer}async shutdown(){this.wsServer&&await this.wsServer.close(),await this.db.disconnect();}};function Wt(s){return new W(s)}var rt=createRequire(import.meta.url),lt="node:sqlite",{DatabaseSync:ct}=rt(lt);function N(s){let e=[];for(let t of s)if(t.type==="tabs"&&"tabs"in t)for(let n of t.tabs)e.push(...N(n.fields));else t.type==="row"&&"fields"in t?e.push(...N(t.fields)):t.type==="collapsible"&&"fields"in t?e.push(...N(t.fields)):e.push(t);return e}function ut(s,e){let t=e,n=s[t.name];if(t.type==="json"||t.type==="richtext"||t.type==="array"||t.type==="group"||t.type==="blocks"||t.type==="list"||t.type==="relationship-block")try{n=n?JSON.parse(n):null;}catch{n=null;}if(t.type==="checkbox"&&(n=!!n),t.type==="date"&&n)try{let a=new Date(n);isNaN(a.getTime())?n=null:n=a.toISOString();}catch{n=null;}if((t.type==="upload"||t.type==="image")&&n)try{let a=JSON.parse(n);Array.isArray(a)?n=a.map(o=>typeof o=="object"&&o!==null?o:{id:o}):n=typeof a=="object"?a:{id:a};}catch{n={id:n};}if(t.type==="relationship"&&n)try{let a=JSON.parse(n);Array.isArray(a),n=a;}catch{n={relationTo:Array.isArray(t.relationTo)?t.relationTo[0]:t.relationTo,value:n};}if(t.type==="list"&&n)try{let a=JSON.parse(n);n=Array.isArray(a)?a:[];}catch{n=[];}if(t.type==="relationship-block"&&n)try{let a=JSON.parse(n);n=Array.isArray(a)?a:[];}catch{n=[];}return n}function X(s,e){try{return s.prepare(`PRAGMA table_info(${e})`).all().map(n=>n.name)}catch{return []}}var J=class extends a$3{db;path;migrations=new Map;versionsTableName="kyro_versions";constructor(e){super(),this.path=e.path,e.db?this.db=e.db:this.db=null;}async connect(){if(this.db||(this.db=new ct(this.path||":memory:")),this.db&&typeof this.db.prepare=="function"&&!this.db.prepare.__wrapped){let e=this.db.prepare.bind(this.db),t=n=>{let a=e(n),o=i=>typeof i=="boolean"?i?1:0:i===void 0?null:i;return new Proxy(a,{get(i,r,c){if(r==="all")return (...u)=>i.all(...u.map(o));if(r==="get")return (...u)=>i.get(...u.map(o));if(r==="run")return (...u)=>i.run(...u.map(o));let d=Reflect.get(i,r,c);return typeof d=="function"?d.bind(i):d}})};t.__wrapped=true,this.db.prepare=t;}this.db.exec("PRAGMA journal_mode = WAL"),this.db.exec("PRAGMA foreign_keys = ON"),this.connected=true;}async disconnect(){this.db&&this.db.close(),this.connected=false;}ensureTable(e,t){let n=t||this.getTableNameFor(e.slug),a=["id TEXT PRIMARY KEY"];for(let i of N(e.fields)){if(!i.name||i.name==="id")continue;let r=this.fieldToSQL(i);r&&a.push(r);}a.push(`${this.col("createdAt")} TEXT DEFAULT (datetime('now'))`),a.push(`${this.col("updatedAt")} TEXT DEFAULT (datetime('now'))`),a.push("status TEXT DEFAULT 'draft'"),a.push("hasDraft INTEGER DEFAULT 0"),e.tenantScoped&&a.push("tenant_id TEXT NOT NULL");let o=X(this.db,n);if(o.length===0){let i=`CREATE TABLE IF NOT EXISTS ${n} (${a.join(", ")})`;this.db.exec(i),this.db.exec(`CREATE INDEX IF NOT EXISTS idx_${n}_status ON ${n}(status)`);for(let r of N(e.fields))r.name&&r.indexed&&this.db.exec(`CREATE INDEX IF NOT EXISTS idx_${n}_${r.name} ON ${n}(${this.col(r.name)})`),r.name&&r.unique&&this.db.exec(`CREATE UNIQUE INDEX IF NOT EXISTS idx_${n}_${r.name}_unique ON ${n}(${this.col(r.name)})`);}else {let i=new Set(o);for(let r of a){let c=r.split(" ")[0].replace(/^"/,"").replace(/"$/,"");if(!i.has(c)&&c!=="id")try{c==="status"?this.db.exec(`ALTER TABLE ${n} ADD COLUMN ${this.col(c)} TEXT DEFAULT 'published'`):c==="hasDraft"?this.db.exec(`ALTER TABLE ${n} ADD COLUMN ${this.col(c)} INTEGER DEFAULT 0`):this.db.exec(`ALTER TABLE ${n} ADD COLUMN ${this.col(c)} TEXT`);}catch{}}}this.migrations.set(n,true);}ensureVersionsTable(){this.db.exec(`
|
|
4
|
+
CREATE TABLE IF NOT EXISTS ${this.versionsTableName} (
|
|
5
|
+
id TEXT PRIMARY KEY,
|
|
6
|
+
collection_slug TEXT NOT NULL,
|
|
7
|
+
document_id TEXT NOT NULL,
|
|
8
|
+
tenant_id TEXT,
|
|
9
|
+
version INTEGER NOT NULL,
|
|
10
|
+
status TEXT NOT NULL DEFAULT 'draft',
|
|
11
|
+
autosave INTEGER NOT NULL DEFAULT 0,
|
|
12
|
+
data TEXT NOT NULL,
|
|
13
|
+
created_by TEXT,
|
|
14
|
+
change_description TEXT,
|
|
15
|
+
published_at TEXT,
|
|
16
|
+
created_at TEXT DEFAULT (datetime('now')),
|
|
17
|
+
updated_at TEXT DEFAULT (datetime('now'))
|
|
18
|
+
)
|
|
19
|
+
`);try{this.db.exec(`ALTER TABLE ${this.versionsTableName} ADD COLUMN autosave INTEGER NOT NULL DEFAULT 0`);}catch{}this.db.exec(`CREATE INDEX IF NOT EXISTS idx_${this.versionsTableName}_doc ON ${this.versionsTableName}(collection_slug, document_id)`),this.db.exec(`CREATE INDEX IF NOT EXISTS idx_${this.versionsTableName}_status ON ${this.versionsTableName}(status)`),this.db.exec(`CREATE INDEX IF NOT EXISTS idx_${this.versionsTableName}_autosave ON ${this.versionsTableName}(autosave)`);}col(e){return `"${e}"`}fieldToSQL(e){switch(e.type){case "text":case "email":case "password":case "textarea":case "color":case "code":case "markdown":case "url":return this.col(e.name)+" TEXT";case "number":return this.col(e.name)+" REAL";case "checkbox":return this.col(e.name)+" INTEGER DEFAULT 0";case "date":return this.col(e.name)+" TEXT";case "select":case "radio":return this.col(e.name)+" TEXT";case "relationship":case "upload":return this.col(e.name)+" TEXT";case "json":case "richtext":case "array":case "group":case "blocks":return this.col(e.name)+" TEXT";default:return null}}parseGlobalsSlug(e){if(e.startsWith("_globals_")){let t=e.replace("_globals_","");return {isGlobal:true,globalSlug:t,tableName:`global_${t.replace(/-/g,"_")}`}}return {isGlobal:false,globalSlug:"",tableName:this.getTableNameFor(e)}}async find(e){let{collection:t,where:n={},sort:a,limit:o=10,page:i=1,tenantID:r,draft:c=false}=e,d=this.parseGlobalsSlug(t),u=d.isGlobal?this.globals.get(d.globalSlug):this.getCollection(t);this.ensureTable(u,d.tableName);let m=`SELECT * FROM ${d.tableName}`,y=[],h=[],f={...n};this.tenantContext&&u.tenantScoped&&(f=c$2({where:f},t,this.tenantContext,b$1).where||{});let A=u.fields.find(b=>b.name==="status"),g=A?.type==="select"&&A.options?.some(b=>b.value==="published");!c&&g&&(h.push("status = ?"),y.push("published")),r&&u.tenantScoped&&(h.push("tenant_id = ?"),y.push(r));for(let[b,S]of Object.entries(f))b==="AND"||b==="OR"||(typeof S=="object"&&S!==null?(S.equals!==void 0&&(h.push(`${this.col(b)} = ?`),y.push(S.equals)),S.in!==void 0&&(h.push(`${this.col(b)} IN (${S.in.map(()=>"?").join(", ")})`),y.push(...S.in)),S.not_equals!==void 0&&(h.push(`${this.col(b)} != ?`),y.push(S.not_equals))):(h.push(`${this.col(b)} = ?`),y.push(S)));h.length>0&&(m+=` WHERE ${h.join(" AND ")}`);let Ne=this.col(a?.replace("-","")||"createdAt"),Re=a?.startsWith("-")?"DESC":"ASC";m+=` ORDER BY ${Ne} ${Re}`;let ve=m.replace("SELECT *","SELECT COUNT(*) as count"),F=this.db.prepare(ve).get(...y)?.count||0;m+=" LIMIT ? OFFSET ?",y.push(o,(i-1)*o);let D=this.db.prepare(m).all(...y).map(b=>this.rowToDoc(b,u));return this.tenantContext&&!this.tenantContext.isSuperAdmin&&(D=D.filter(b=>d$2(b,t,this.tenantContext,b$1))),c&&(D=await Promise.all(D.map(async b=>{let S=this.db.prepare(`SELECT * FROM ${this.versionsTableName} WHERE collection_slug = ? AND document_id = ? AND tenant_id IS NULL ORDER BY version DESC LIMIT 1`).get(t,b.id);if(S){let De=S.data?JSON.parse(S.data):{};return {...b,...De,status:b.status}}return b}))),{docs:D,totalDocs:F,limit:o,totalPages:Math.ceil(F/o),page:i,pagingCounter:(i-1)*o+1,hasPrevPage:i>1,hasNextPage:i<Math.ceil(F/o),prevPage:i>1?i-1:null,nextPage:i<Math.ceil(F/o)?i+1:null}}async findByID(e){let{collection:t,id:n,tenantID:a,draft:o=false}=e,i=this.parseGlobalsSlug(t),r=i.isGlobal?this.globals.get(i.globalSlug):this.getCollection(t);this.ensureTable(r,i.tableName);let d=`SELECT * FROM ${i.tableName} WHERE id = ?`,u=[n];if(this.tenantContext&&r.tenantScoped){let f={id:n,tenant_id:this.tenantContext.tenantId};if(!d$2(f,t,this.tenantContext,b$1))return null}let p=r.fields.find(f=>f.name==="status"),m=p?.type==="select"&&p.options?.some(f=>f.value==="published");!o&&m&&(d+=" AND status = ?",u.push("published")),a&&r.tenantScoped&&(d+=" AND tenant_id = ?",u.push(a));let y=this.db.prepare(d).get(...u);if(!y)return null;let h=this.rowToDoc(y,r);if(o){let f=this.db.prepare(`SELECT * FROM ${this.versionsTableName} WHERE collection_slug = ? AND document_id = ? AND tenant_id IS NULL ORDER BY version DESC LIMIT 1`).get(t,h.id);if(f){let A=f.data?JSON.parse(f.data):{};h={...h,...A,status:h.status};}}return h}async create(e){let{collection:t,data:n,tenantID:a}=e,o=this.parseGlobalsSlug(t),i=o.isGlobal?this.globals.get(o.globalSlug):this.getCollection(t);this.ensureTable(i,o.tableName);let r=o.tableName,c=o.isGlobal?o.globalSlug:n.id||this.generateId(),d=this.prepareData(n,i);d.id=c,d.created_at=new Date().toISOString(),d.updated_at=new Date().toISOString(),a&&i.tenantScoped&&(d.tenant_id=a);let u=Object.keys(d),p=X(this.db,r),m={};for(let g of u)p.includes(g)&&(m[g]=d[g]);let y=Object.keys(m),h=y.map(g=>this.col(g)),f=y.map(()=>"?").join(", "),A=Object.values(m).map(g=>g!==null&&typeof g=="object"?JSON.stringify(g):g);return this.db.prepare(`INSERT OR REPLACE INTO ${r} (${h.join(", ")}) VALUES (${f})`).run(...A),this.ensureVersionsTable(),this.findByID({collection:t,id:c,tenantID:a,draft:true})}async update(e){let{collection:t,id:n,data:a,tenantID:o}=e,i=this.parseGlobalsSlug(t),r=i.isGlobal?this.globals.get(i.globalSlug):this.getCollection(t);this.ensureTable(r,i.tableName);let c=i.tableName,d=this.prepareData(a,r);d.updated_at=new Date().toISOString();let u=X(this.db,c),p={};for(let g of Object.keys(d))u.includes(g)&&(p[g]=d[g]);let y=Object.keys(p).map(g=>`${this.col(g)} = ?`).join(", "),h=Object.values(p).map(g=>g!==null&&typeof g=="object"?JSON.stringify(g):g),f=`UPDATE ${c} SET ${y} WHERE id = ?`,A=[...h,n];return o&&r.tenantScoped&&(f+=" AND tenant_id = ?",A.push(o)),this.db.prepare(f).run(...A),this.ensureVersionsTable(),this.findByID({collection:t,id:n,tenantID:o,draft:true})}async delete(e){let{collection:t,id:n,tenantID:a}=e,o=this.parseGlobalsSlug(t),i=o.isGlobal?this.globals.get(o.globalSlug):this.getCollection(t);this.ensureTable(i,o.tableName),this.ensureVersionsTable();let r=await this.findByID({collection:t,id:n,tenantID:a,draft:true});if(!r)throw new Error(`Document not found: ${t}/${n}`);let d=`DELETE FROM ${o.tableName} WHERE id = ?`,u=[n];return a&&i.tenantScoped&&(d+=" AND tenant_id = ?",u.push(a)),this.db.prepare(d).run(...u),r}async count(e){let{collection:t,tenantID:n}=e,a=this.parseGlobalsSlug(t),o=a.isGlobal?this.globals.get(a.globalSlug):this.getCollection(t);this.ensureTable(o,a.tableName);let r=`SELECT COUNT(*) as count FROM ${a.tableName}`,c=[];return n&&o.tenantScoped&&(r+=" WHERE tenant_id = ?",c.push(n)),this.db.prepare(r).get(...c)?.count||0}async findOne(e){let t=this.parseGlobalsSlug(e.collection);if(t.isGlobal){let a=this.globals.get(t.globalSlug);if(!a)throw new Error(`Global "${t.globalSlug}" not found in adapter`);this.ensureTable(a,t.tableName);let o=`SELECT * FROM ${t.tableName}`,i=[],r=[],c=a.fields.find(p=>p.name==="status"),d=c?.type==="select"&&c.options?.some(p=>p.value==="published");!e.draft&&a.versions&&d&&i.push("status = 'published'"),i.length>0&&(o+=` WHERE ${i.join(" AND ")}`),o+=" LIMIT 1";let u=this.db.prepare(o).get(...r);if(u){let p=this.rowToDoc(u,a);if(e.draft){let m=this.db.prepare(`SELECT * FROM ${this.versionsTableName} WHERE collection_slug = ? AND document_id = ? AND tenant_id IS NULL ORDER BY version DESC LIMIT 1`).get(e.collection,t.globalSlug);if(m){let y=m.data?JSON.parse(m.data):{};p={...p,...y,status:p.status};}}return p}return null}return (await this.find({...e,limit:1})).docs[0]||null}async findVersions(e){this.ensureVersionsTable();let{collection:t,documentId:n,tenantID:a,limit:o=20,page:i=1}=e,r=["collection_slug = ?","document_id = ?","autosave = 0"],c=[t,n];a?(r.push("tenant_id = ?"),c.push(a)):r.push("tenant_id IS NULL");let d=`WHERE ${r.join(" AND ")}`,p=this.db.prepare(`SELECT COUNT(*) as count FROM ${this.versionsTableName} ${d}`).get(...c)?.count||0,m=(i-1)*o;return {docs:this.db.prepare(`SELECT * FROM ${this.versionsTableName} ${d} ORDER BY version DESC LIMIT ? OFFSET ?`).all(...c,o,m).map(f=>this.rowToVersion(f)),totalDocs:p,limit:o,totalPages:Math.ceil(p/o),page:i,pagingCounter:(i-1)*o+1,hasPrevPage:i>1,hasNextPage:i<Math.ceil(p/o),prevPage:i>1?i-1:null,nextPage:i<Math.ceil(p/o)?i+1:null}}async findVersionByID(e){this.ensureVersionsTable();let t=this.db.prepare(`SELECT * FROM ${this.versionsTableName} WHERE id = ? AND collection_slug = ? LIMIT 1`).get(e.versionId,e.collection);return t?this.rowToVersion(t):null}async createVersion(e){this.ensureVersionsTable();let t=new Date().toISOString();if(e.autosave){let r=`SELECT * FROM ${this.versionsTableName} WHERE collection_slug = ? AND document_id = ? AND autosave = 1`,c=[e.collection,e.documentId];e.tenantID?(r+=" AND tenant_id = ?",c.push(e.tenantID)):r+=" AND tenant_id IS NULL",r+=" LIMIT 1";let d=this.db.prepare(r).get(...c);if(d){this.db.prepare(`UPDATE ${this.versionsTableName} SET data = ?, status = ?, updated_at = ? WHERE id = ?`).run(JSON.stringify(e.data),e.status,t,d.id);let u=await this.findVersionByID({collection:e.collection,versionId:d.id});if(u)return u}}let n=this.generateId(),o=(this.db.prepare(`SELECT version FROM ${this.versionsTableName} WHERE collection_slug = ? AND document_id = ? AND autosave = 0 ORDER BY version DESC LIMIT 1`).get(e.collection,e.documentId)?.version??0)+1;if(this.db.prepare(`INSERT INTO ${this.versionsTableName} (
|
|
20
|
+
id, collection_slug, document_id, tenant_id, version, status, autosave, data, created_by, change_description, published_at, created_at, updated_at
|
|
21
|
+
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(n,e.collection,e.documentId,e.tenantID??null,o,e.status,e.autosave?1:0,JSON.stringify(e.data),e.createdBy??null,e.changeDescription??null,e.status==="published"?t:null,t,t),!e.autosave){let c=this.collections.get(e.collection)?.versions?.maxPerDoc;c&&c>0&&await this.deleteVersions({collection:e.collection,documentId:e.documentId,keepLatest:c,tenantID:e.tenantID});}return await this.findVersionByID({collection:e.collection,versionId:n})}async updateLatestVersion(e){return this.createVersion({...e,autosave:true})}async deleteVersions(e){this.ensureVersionsTable();let{collection:t,documentId:n,keepLatest:a,tenantID:o}=e;if(a&&a>0){let i=this.db.prepare(`SELECT id, status, autosave FROM ${this.versionsTableName} WHERE collection_slug = ? AND document_id = ? ORDER BY version DESC`).all(t,n),r=0,c=[];for(let d of i)d.status==="published"||d.autosave===1||(r++,r>a&&c.push(d.id));for(let d of c)this.db.prepare(`DELETE FROM ${this.versionsTableName} WHERE id = ?`).run(d);}else {let i=`DELETE FROM ${this.versionsTableName} WHERE collection_slug = ? AND document_id = ?`,r=[t,n];o&&(i+=" AND tenant_id = ?",r.push(o)),this.db.prepare(i).run(...r);}}rowToVersion(e){return {id:String(e.id),collection:e.collection_slug,documentId:e.document_id,version:e.version,status:e.status,data:e.data?JSON.parse(e.data):{},createdBy:e.created_by??void 0,changeDescription:e.change_description??void 0,publishedAt:e.published_at??null,createdAt:e.created_at,updatedAt:e.updated_at}}prepareData(e,t){let n={},a=N(t.fields),o=(i,r)=>{let c=i;if(c.type==="json"||c.type==="richtext"||c.type==="array"||c.type==="group"||c.type==="blocks"||c.type==="list"||c.type==="relationship-block")return r!=null?JSON.stringify(r):null;if(c.type==="checkbox")return r?1:0;if(c.type==="number")return r!==null&&r!==""?Number(r):null;if(c.type==="upload"||c.type==="image"){if(r==null)return null;if(Array.isArray(r)){let d=r.map(u=>typeof u=="string"?u:typeof u=="object"?u.id||u._id||u:String(u));return JSON.stringify(d)}return typeof r=="string"?r:typeof r=="object"?JSON.stringify(r):String(r)}else if(i.type==="relationship"){if(r==null)return null;if(Array.isArray(r)){let d=r.map(u=>typeof u=="string"?u:typeof u=="object"?JSON.stringify({relationTo:i.relationTo,value:u.id||u}):String(u));return JSON.stringify(d)}return typeof r=="string"?r:typeof r=="object"?JSON.stringify({relationTo:i.relationTo,value:r.id||r}):String(r)}return r};for(let i of a){if(!i.name||i.name==="id"||t.fields.some(d=>d.type==="tabs"&&"tabs"in d&&d.tabs.some(u=>u.fields.some(p=>p.name===i.name))))continue;let c=e[i.name];c!==void 0&&(n[i.name]=o(i,c));}for(let i of t.fields)if(i.type==="tabs"&&"tabs"in i&&i.name){let r=e[i.name];if(r&&typeof r=="object"){for(let c of i.tabs)for(let d of c.fields)if(d.name&&d.name!=="id"){let u=r[d.name];u!==void 0&&(n[d.name]=o(d,u));}}}return n}rowToDoc(e,t){let n={id:e.id};for(let a of N(t.fields)){if(!a.name||a.name==="id")continue;let o=a,i=e[o.name];if(o.type==="json"||o.type==="richtext"||o.type==="array"||o.type==="group"||o.type==="blocks"||o.type==="list"||o.type==="relationship-block")try{i=i?JSON.parse(i):null;}catch{i=null;}if(a.type==="checkbox"&&(i=!!i),a.type==="date"&&i)try{let r=new Date(i);isNaN(r.getTime())?(console.warn(`[LocalAdapter] Invalid date value for field "${a.name}":`,i),i=null):i=r.toISOString();}catch{i=null;}if((a.type==="upload"||a.type==="image")&&i)try{let r=JSON.parse(i);Array.isArray(r)?i=r.map(c=>typeof c=="object"&&c!==null?c:{id:c}):i=typeof r=="object"?r:{id:r};}catch{i={id:i};}if(a.type==="relationship"&&i)try{let r=JSON.parse(i);Array.isArray(r),i=r;}catch{i={relationTo:Array.isArray(a.relationTo)?a.relationTo[0]:a.relationTo,value:i};}n[a.name]=i;}for(let a of t.fields)if(!(!a.name||a.name==="id"||a.name==="row"||a.name==="collapsible")&&a.type==="tabs"&&"tabs"in a){let o={};for(let i of a.tabs)for(let r of i.fields)r.name&&r.name!=="id"&&(o[r.name]=ut(e,r));n[a.name]=o;}if(t.timestamps){let a=e.createdAt||e.created_at,o=e.updatedAt||e.updated_at;if(a)try{let i=new Date(a);isNaN(i.getTime())||(n.createdAt=i.toISOString());}catch{}if(o)try{let i=new Date(o);isNaN(i.getTime())||(n.updatedAt=i.toISOString());}catch{}}return t.tenantScoped&&(n.tenantID=e.tenant_id),n.status=e.status??"published",n.hasDraft=e.hasDraft?!!e.hasDraft:false,n}generateId(){let e=Date.now().toString(16).padStart(12,"0"),t=randomBytes(6).toString("hex");return e+t}getMediaById(e){try{let t=this.getTableNameFor("media"),n=this.db.prepare(`SELECT id, url, thumbnail_url FROM ${t} WHERE id = ?`).get(e);if(n)return {id:n.id,url:n.url,thumbnailUrl:n.thumbnail_url||n.url}}catch{}return null}getTableNameFor(e){return e.replace(/-/g,"_")}async migrate(){for(let e of this.collections.values())this.ensureTable(e);}async rollback(){}async transaction(e){return new Promise((t,n)=>{let a=this.db.transaction(async()=>e({db:this.db}));try{let o=a();t(o);}catch(o){n(o);}})}getDatabase(){return this.db}exec(e){this.db.exec(e);}prepare(e){return this.db.prepare(e)}};function cs(s){return new J(s||{})}export{K as a,V as b,B as c,x as d,pe as e,C as f,he as g,ge as h,me as i,be as j,Te as k,w as l,He as m,Ye as n,M as o,W as p,Wt as q,J as r,cs as s};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
'use strict';var
|
|
1
|
+
'use strict';var chunkRBZNQINT_cjs=require('./chunk-RBZNQINT.cjs'),chunkUJNSOOYZ_cjs=require('./chunk-UJNSOOYZ.cjs'),chunkET6NN2V2_cjs=require('./chunk-ET6NN2V2.cjs'),chunkX3RRRWIN_cjs=require('./chunk-X3RRRWIN.cjs'),chunkGYQMNXXW_cjs=require('./chunk-GYQMNXXW.cjs'),chunkWMY7BDPK_cjs=require('./chunk-WMY7BDPK.cjs'),chunkATLSIYRH_cjs=require('./chunk-ATLSIYRH.cjs'),A=require('kyro:config');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var A__default=/*#__PURE__*/_interopDefault(A);exports.a=null;var n=null;async function g(){if(!exports.a)try{let e=A__default.default.default||A__default.default;exports.a=chunkRBZNQINT_cjs.q(e),await exports.a.init(),await exports.a.loadSettings();let a=exports.a.db,r;if(a instanceof chunkX3RRRWIN_cjs.c){if(a.dialect==="postgres")r=new chunkGYQMNXXW_cjs.a({db:a.client});else if(a.dialect==="sqlite"){let s=process.env.KYRO_AUTH_DB_PATH||"./data/auth.db";r=new chunkET6NN2V2_cjs.a({path:s});}}else if(a instanceof chunkRBZNQINT_cjs.r){let s=process.env.KYRO_AUTH_DB_PATH||"./data/auth.db";r=new chunkET6NN2V2_cjs.a({path:s});}else a instanceof chunkWMY7BDPK_cjs.a&&(r=new chunkATLSIYRH_cjs.a({db:a.db}));r?.connect&&await r.connect(),(await chunkUJNSOOYZ_cjs.d(r))?.success,typeof exports.a.startWebSocket=="function"&&exports.a.startWebSocket().catch(s=>{console.error("[Kyro] WebSocket auto-start failed:",s);}),globalThis.__KYRO_INSTANCE__=exports.a;}catch(e){throw exports.a=null,n=null,console.error("[Kyro API] Init failed, will retry:",e),e}}async function q(){n||(n=g()),await n;}var w={graphqlEnabled:false,trpcEnabled:false,wsEnabled:false,requireAuth:false};async function b(e){try{return (await exports.a.db.findOne({collection:"_globals_access-settings",where:{},draft:!0}))?.apiAccess?.[e]??w[e]??!0}catch{return true}}var v=async e=>{if(!exports.a){n||(n=g());try{await Promise.race([n,new Promise((l,o)=>setTimeout(()=>o(new Error("Initialization timeout")),3e4))]);}catch{return new Response(JSON.stringify({error:"Service Unavailable",message:"Kyro CMS is still starting up. Please try again in a moment."}),{status:503,headers:{"Content-Type":"application/json","Retry-After":"5"}})}}let r=new URL(e.request.url).pathname,i=__KYRO_API_PATH__;if(r===`${i}/graphql`&&typeof exports.a.getGraphQL=="function"){if(!await b("graphqlEnabled"))return new Response(JSON.stringify({error:"GraphQL is disabled"}),{status:503,headers:{"Content-Type":"application/json"}});let o=await exports.a.getGraphQL().fetch(e.request,e.locals);return new Response(o.body,o)}if(r.startsWith(`${i}/trpc/`)&&typeof exports.a.getTRPC=="function"){if(!await b("trpcEnabled"))return new Response(JSON.stringify({error:"tRPC is disabled"}),{status:503,headers:{"Content-Type":"application/json"}});let o=await exports.a.getTRPC().fetch(e.request,e.locals);return new Response(o.body,o)}return exports.a.getREST().fetch(e.request,e.locals)};exports.b=q;exports.c=v;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import {q as q$1,r}from'./chunk-
|
|
1
|
+
import {q as q$1,r}from'./chunk-5H7LD62N.js';import {d}from'./chunk-FO3HLBC7.js';import {a as a$1}from'./chunk-2W4FK6CJ.js';import {c}from'./chunk-MBUUNROA.js';import {a}from'./chunk-RHCWCG3O.js';import {a as a$2}from'./chunk-TYOVXKQP.js';import {a as a$3}from'./chunk-P7CESLDJ.js';import A from'kyro:config';var t=null,n=null;async function g(){if(!t)try{let e=A.default||A;t=q$1(e),await t.init(),await t.loadSettings();let a$4=t.db,r$1;if(a$4 instanceof c){if(a$4.dialect==="postgres")r$1=new a({db:a$4.client});else if(a$4.dialect==="sqlite"){let s=process.env.KYRO_AUTH_DB_PATH||"./data/auth.db";r$1=new a$1({path:s});}}else if(a$4 instanceof r){let s=process.env.KYRO_AUTH_DB_PATH||"./data/auth.db";r$1=new a$1({path:s});}else a$4 instanceof a$2&&(r$1=new a$3({db:a$4.db}));r$1?.connect&&await r$1.connect(),(await d(r$1))?.success,typeof t.startWebSocket=="function"&&t.startWebSocket().catch(s=>{console.error("[Kyro] WebSocket auto-start failed:",s);}),globalThis.__KYRO_INSTANCE__=t;}catch(e){throw t=null,n=null,console.error("[Kyro API] Init failed, will retry:",e),e}}async function q(){n||(n=g()),await n;}var w={graphqlEnabled:false,trpcEnabled:false,wsEnabled:false,requireAuth:false};async function b(e){try{return (await t.db.findOne({collection:"_globals_access-settings",where:{},draft:!0}))?.apiAccess?.[e]??w[e]??!0}catch{return true}}var v=async e=>{if(!t){n||(n=g());try{await Promise.race([n,new Promise((l,o)=>setTimeout(()=>o(new Error("Initialization timeout")),3e4))]);}catch{return new Response(JSON.stringify({error:"Service Unavailable",message:"Kyro CMS is still starting up. Please try again in a moment."}),{status:503,headers:{"Content-Type":"application/json","Retry-After":"5"}})}}let r=new URL(e.request.url).pathname,i=__KYRO_API_PATH__;if(r===`${i}/graphql`&&typeof t.getGraphQL=="function"){if(!await b("graphqlEnabled"))return new Response(JSON.stringify({error:"GraphQL is disabled"}),{status:503,headers:{"Content-Type":"application/json"}});let o=await t.getGraphQL().fetch(e.request,e.locals);return new Response(o.body,o)}if(r.startsWith(`${i}/trpc/`)&&typeof t.getTRPC=="function"){if(!await b("trpcEnabled"))return new Response(JSON.stringify({error:"tRPC is disabled"}),{status:503,headers:{"Content-Type":"application/json"}});let o=await t.getTRPC().fetch(e.request,e.locals);return new Response(o.body,o)}return t.getREST().fetch(e.request,e.locals)};export{t as a,q as b,v as c};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import {h,a}from'./chunk-HLSB2MCK.js';import {a as a$1}from'./chunk-KDNYHLD2.js';import {GraphQLScalarType,Kind,GraphQLObjectType,GraphQLString,GraphQLInputObjectType,GraphQLBoolean,GraphQLInt,GraphQLList,GraphQLNonNull,GraphQLSchema,GraphQLUnionType,GraphQLFloat}from'graphql';export{printSchema as e}from'graphql';var H=class{db;tenantID;user;caches=new Map;pending=new Map;waiting=new Map;flushScheduled=false;constructor(n){this.db=n.db,this.tenantID=n.tenantID,this.user=n.user;}getCacheKey(n){return n}async load(n,a){let l=this.getCacheKey(n),p=this.caches.get(l);if(p||(p=new Map,this.caches.set(l,p)),p.has(a))return p.get(a);let s=this.pending.get(l);return s||(s=new Set,this.pending.set(l,s)),s.add(a),p.set(a,void 0),this.flushScheduled||(this.flushScheduled=true,queueMicrotask(()=>{this.flushScheduled=false,this.flushAll();})),new Promise(o=>{let i=this.waiting.get(`${l}:${a}`);i||(i=[],this.waiting.set(`${l}:${a}`,i)),i.push(o);})}async flushAll(){for(let[n,a]of this.pending){if(a.size===0)continue;let l=this.caches.get(n),p=await this.db.find({collection:n,where:{id:{in:Array.from(a)}},limit:a.size,tenantID:this.tenantID,draft:!!this.user});for(let s of p.docs||[])if(s&&s.id){l.set(s.id,s);let o=this.waiting.get(`${n}:${s.id}`);o&&(o.forEach(i=>i(s)),this.waiting.delete(`${n}:${s.id}`));}}for(let[n,a]of this.waiting)a.forEach(l=>l(void 0));this.waiting.clear(),this.pending.clear();}resolveOne(n,a){return this.caches.get(this.getCacheKey(n))?.get(a)}},R=new GraphQLScalarType({name:"JSON",description:"Arbitrary JSON value",serialize(e){return e},parseValue(e){return e},parseLiteral(e){switch(e.kind){case Kind.STRING:return e.value;case Kind.INT:case Kind.FLOAT:return parseFloat(e.value);case Kind.BOOLEAN:return e.value;case Kind.OBJECT:{let n={};for(let a of e.fields)n[a.name.value]=R.parseLiteral(a.value);return n}case Kind.LIST:return e.values.map(n=>R.parseLiteral(n));case Kind.NULL:return null;default:return null}}});function se(e){return n=>{let a=0;return {Field(){a++,a>e&&n.reportError(new Error(`Query exceeds max depth of ${e}`));},leaveField(){a--;}}}}function D(e){return e.split(/[-_]/).map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join("")}function z(e){let n=D(e);return n.charAt(0).toLowerCase()+n.slice(1)}function v(e){return e.endsWith("s")&&e.length>1?e.slice(0,-1):e}async function j(e,n,a$2){let l=e.access?.[n];if(a$2.apiKey){if(a$2.apiKey.permissions?.length>0){let s=e.slug,i=`${s}:${n==="read"?"read":n==="create"?"create":"update"}`;return !h(a$2.apiKey.permissions,i)&&!h(a$2.apiKey.permissions,`${s}:admin`)?{allowed:false}:{allowed:true}}if(l){let s=await a(l,{req:a$2.req,user:a$2.user,tenantID:a$2.tenantID});return typeof s=="boolean"?{allowed:s}:{allowed:true,extraWhere:s}}return {allowed:true}}if(a$2.user){let s=e.slug,i=`${s}:${n==="read"?"read":n==="create"?"create":n==="update"?"update":"delete"}`;if(!a$1({id:a$2.user.id,email:a$2.user.email,role:a$2.user.role},i)&&!a$1({id:a$2.user.id,email:a$2.user.email,role:a$2.user.role},`${s}:admin`)&&!l)return {allowed:false}}if(!l)return a$2.user?{allowed:true}:{allowed:false};let p=await a(l,{req:a$2.req,user:a$2.user,tenantID:a$2.tenantID});return typeof p=="boolean"?{allowed:p}:{allowed:true,extraWhere:p}}async function Y(e,n,a$1){let l=e.access?.[n];if(a$1.apiKey){if(a$1.apiKey.permissions?.length>0){let s=e.slug,o=`${s}:${n}`;return !h(a$1.apiKey.permissions,o)&&!h(a$1.apiKey.permissions,`${s}:admin`)&&!h(a$1.apiKey.permissions,`${s}:*`)?{allowed:false}:{allowed:true}}if(l){let s=await a(l,{req:a$1.req,user:a$1.user,tenantID:a$1.tenantID});return {allowed:typeof s=="boolean"?s:true}}return {allowed:true}}if(!l){if(!a$1.user)return {allowed:false};let s=a$1.user.role;return s==="super_admin"||s==="admin"?{allowed:true}:{allowed:false}}let p=await a(l,{req:a$1.req,user:a$1.user,tenantID:a$1.tenantID});return typeof p=="boolean"?{allowed:p}:{allowed:true}}function X(e,n){return e?e.startsWith("http://")||e.startsWith("https://")||e.startsWith("blob:")||e.startsWith("data:")?e:`${(process.env.KYRO_BASE_URL||n||"http://localhost:4321").replace(/\/+$/,"")}${e.startsWith("/")?"":"/"}${e}`:null}function K(e,n){return e&&(e.url&&(e.url=X(e.url,n)),e.thumbnailUrl&&(e.thumbnailUrl=X(e.thumbnailUrl,n)),e)}function k(e,n,a,l=false,p="Root",s=new Map){switch(e.type){case "text":case "email":case "password":case "textarea":case "color":case "code":case "markdown":case "date":case "select":case "radio":return GraphQLString;case "upload":{let o=e;if(l)return o.hasMany?new GraphQLList(GraphQLString):GraphQLString;if(o.relationTo&&a?.[o.relationTo]){let i=a[o.relationTo];return o.hasMany?new GraphQLList(i):i}return R}case "image":{if(l)return GraphQLString;let o=e;return o.relationTo&&a?.[o.relationTo]?a[o.relationTo]:R}case "number":return e.integer?GraphQLInt:GraphQLFloat;case "checkbox":return GraphQLBoolean;case "json":case "richtext":return R;case "blocks":{if(l)return R;let o=e,i=(o.blocks||[]).map(I=>{let b=`Block_${D(I.slug)}`,w=s.get(b);return w||(w=new GraphQLObjectType({name:b,fields:()=>{let f=M(I.fields||[],n,a,b,s);return f.blockType={type:GraphQLString},f.name={type:GraphQLString},f}}),s.set(b,w)),w});if(i.length===0)return R;let d=`${p}_${D(o.name)}_Blocks`,T=s.get(d);return T||(T=new GraphQLUnionType({name:d,types:i,resolveType:I=>`Block_${D(I.blockType||I.type)}`}),s.set(d,T)),new GraphQLList(T)}case "tabs":{if(l)return R;let o=e,i=`${p}_${D(o.name)}_Tabs`,d=s.get(i);return d||(d=new GraphQLObjectType({name:i,fields:()=>M(o.tabs?.flatMap(T=>T.fields||[])||[],n,a,i,s)}),s.set(i,d)),d}case "relationship":if(typeof e.relationTo=="string"){if(l)return e.hasMany?new GraphQLList(GraphQLString):GraphQLString;if(a?.[e.relationTo])return e.hasMany?new GraphQLList(a[e.relationTo]):a[e.relationTo];let o=n.getCollection(e.relationTo);if(o)return new GraphQLObjectType({name:`${D(e.relationTo)}Ref`,fields:()=>({id:{type:GraphQLString},...Z(o,n,a,s)})})}return R;case "array":{if(l)return new GraphQLList(R);let o=e,i=`${p}_${D(o.name)}_ArrayItem`,d=s.get(i);return d||(d=new GraphQLObjectType({name:i,fields:()=>{let T=M(o.fields||[],n,a,i,s);return T.id={type:GraphQLString},T}}),s.set(i,d)),new GraphQLList(d)}case "group":{if(l)return R;let o=e,i=`${p}_${D(o.name)}_Group`,d=s.get(i);return d||(d=new GraphQLObjectType({name:i,fields:()=>M(o.fields||[],n,a,i,s)}),s.set(i,d)),d}default:return GraphQLString}}function M(e,n,a,l,p=new Map){let s={};for(let o of e){if(o.type==="tabs"&&!o.name){for(let i of o.tabs||[]){let d=M(i.fields||[],n,a,l,p);Object.assign(s,d);}continue}if(o.type==="row"||o.type==="collapsible"){let i=M(o.fields||[],n,a,l,p);Object.assign(s,i);continue}if(o.name&&o.admin?.hidden!==true){let i=ie(o,n,a,l,p);i&&(s[o.name]=i);}}return s}function Z(e,n,a,l=new Map){return M(e.fields,n,a,D(v(e.slug)),l)}function ie(e,n,a,l,p=new Map){if(!e.name)return null;let s=e.deprecated||void 0;if(e.type==="upload"){let i=k(e,n,a,false,l,p),d=e;return {type:e.required?new GraphQLNonNull(i):i,description:e.admin?.description||e.label,deprecationReason:s,resolve:async(T,I,b)=>{let w=b?.relationLoader,f=T?.[d.name],c=b?.req?.url?new URL(b.req.url).origin:void 0;if(!f)return null;if(d.hasMany){let g=Array.isArray(f)?f:[];return Promise.all(g.map(async h=>{let G=typeof h=="string"?h:h?.id;if(!G||typeof h=="object"&&h?.url)return K(h,c);if(w){let S=w.resolveOne(d.relationTo,G);if(S)return K(S,c);let r=await w.load(d.relationTo,G);if(r)return K(r,c)}return {id:G}}))}let m=typeof f=="string"?f:f?.id;if(!m||typeof f=="object"&&f?.url)return K(f,c);if(w){let g=w.resolveOne(d.relationTo,m);if(g)return K(g,c);let h=await w.load(d.relationTo,m);if(h)return K(h,c)}return {id:m}}}}if(e.type==="relationship"&&!e.hasMany){let i=k(e,n,a,false,l,p);return {type:e.required?new GraphQLNonNull(i):i,description:e.admin?.description||e.label,deprecationReason:s,resolve:async(d,T,I)=>{let b=I?.relationLoader,w=e,f=d?.[w.name];if(!f)return null;let c=Array.isArray(w.relationTo),m=c?f?.relationTo:w.relationTo,g=c?f?.value:f;if(c&&typeof f=="string"&&(m=w.relationTo[0],g=f),b&&typeof g=="string"&&typeof m=="string"){let h=b.resolveOne(m,g);if(h)return c?{relationTo:m,value:h}:h;let G=await b.load(m,g);if(G)return c?{relationTo:m,value:G}:G}return c?{relationTo:m,value:{id:g}}:{id:g}}}}if(e.type==="relationship"&&e.hasMany)return {type:k(e,n,a,false,l,p),description:e.admin?.description||e.label,deprecationReason:s,resolve:async(d,T,I)=>{let b=I?.relationLoader,w=e,f=d?.[w.name]||[];if(!f.length)return [];let c=Array.isArray(w.relationTo);if(b){let m=[];for(let g of f){let h=c?g?.relationTo:w.relationTo,G=c?g?.value:g;if(c&&typeof g=="string"&&(h=w.relationTo[0],G=g),typeof G!="string"||typeof h!="string"){m.push(g);continue}let S=b.resolveOne(h,G);if(S)m.push(c?{relationTo:h,value:S}:S);else {let r=await b.load(h,G);m.push(c?{relationTo:h,value:r||{id:G}}:r||{id:G});}}return m}return f.map(m=>{let g=c?m?.relationTo:w.relationTo,h=c?m?.value:m;return c&&typeof m=="string"&&(g=w.relationTo[0],h=m),c?{relationTo:g,value:{id:h}}:{id:h}})}};if(e.type==="blocks"){let i=k(e,n,a,false,l,p);return {type:e.required?new GraphQLNonNull(i):i,description:e.admin?.description||e.label,deprecationReason:s,resolve:d=>{let T=d?.[e.name];return Array.isArray(T)?T.map(I=>I&&I.data&&I.type?{...I.data,id:I.id,type:I.type,blockType:I.type,name:I.name}:I):T}}}let o=k(e,n,a,false,l,p);return {type:e.required?new GraphQLNonNull(o):o,description:e.admin?.description||e.label,deprecationReason:s}}function x(e){let{registry:n,db:a,user:l,req:p,tenantID:s,apiKey:o,settings:i}=e;if(i?.access?.apiAccess?.graphqlEnabled===false)throw new Error("GraphQL API is disabled");let T=n.getCollections(),I=n.getGlobals(),b={},w={},f=new Map;for(let r of T){b[r.slug]=new GraphQLObjectType({name:D(v(r.slug)),fields:()=>({id:{type:GraphQLString},...Z(r,n,b,f),...r.timestamps?{createdAt:{type:GraphQLString},updatedAt:{type:GraphQLString}}:{},...r.tenantScoped?{tenantID:{type:GraphQLString}}:{}})});let Q={};for(let q of r.fields)q.name&&q.name!=="id"&&(Q[q.name]={type:k(q,n,b,true)});w[r.slug]=new GraphQLInputObjectType({name:`${D(v(r.slug))}Input`,fields:()=>Q});}let c={},m={};for(let r of I)c[r.slug]=new GraphQLObjectType({name:`${D(r.slug)}Global`,fields:()=>({id:{type:GraphQLString},...Z({slug:r.slug,fields:r.fields},n,b)})}),m[r.slug]=new GraphQLInputObjectType({name:`${D(r.slug)}GlobalInput`,fields:()=>{let Q={};for(let q of r.fields)q.name&&q.name!=="id"&&(Q[q.name]={type:k(q,n,b,true)});return Q}});let g={};for(let r of T){let Q=b[r.slug];Q&&(g[z(r.slug)]={type:new GraphQLObjectType({name:`${D(v(r.slug))}FindResult`,fields:{docs:{type:new GraphQLList(Q)},totalDocs:{type:GraphQLInt},page:{type:GraphQLInt},totalPages:{type:GraphQLInt},hasNextPage:{type:GraphQLBoolean},hasPrevPage:{type:GraphQLBoolean}}}),args:{where:{type:GraphQLString},sort:{type:GraphQLString},limit:{type:GraphQLInt},page:{type:GraphQLInt},draft:{type:GraphQLBoolean}},resolve:async(q,L,t)=>{let u=await j(r,"read",{user:t.user,req:t.req,tenantID:t.tenantID,apiKey:t.apiKey});if(!u.allowed)throw new Error("Access denied");t.tenantID&&a.setTenantContext({tenantId:t.tenantID,userId:t.user?.id??"",role:t.user?.role,isSuperAdmin:t.user?.role==="super_admin"});let A={};if(L.where)try{A=JSON.parse(L.where);}catch{}u.extraWhere&&(A={...A,...u.extraWhere});let F=L.draft??!!t.user;return a.find({collection:r.slug,where:A,sort:L.sort,limit:L.limit||10,page:L.page||1,tenantID:t.tenantID,draft:F})}},g[z(v(r.slug))]={type:Q,args:{id:{type:GraphQLString},slug:{type:GraphQLString},draft:{type:GraphQLBoolean}},resolve:async(q,L,t)=>{if(!L.id&&!L.slug)throw new Error("Either id or slug is required");if(!(await j(r,"read",{user:t.user,req:t.req,tenantID:t.tenantID,apiKey:t.apiKey})).allowed)throw new Error("Access denied");t.tenantID&&a.setTenantContext({tenantId:t.tenantID,userId:t.user?.id??"",role:t.user?.role,isSuperAdmin:t.user?.role==="super_admin"});let A=L.draft??!!t.user;return L.id?a.findByID({collection:r.slug,id:L.id,tenantID:t.tenantID,draft:A}):(await a.find({collection:r.slug,where:{slug:{equals:L.slug}},limit:1,page:1,tenantID:t.tenantID,draft:A})).docs?.[0]||null}},g[`count${D(r.slug)}`]={type:new GraphQLObjectType({name:`${D(v(r.slug))}Count`,fields:{totalDocs:{type:GraphQLInt}}}),args:{where:{type:GraphQLString}},resolve:async(q,L,t)=>{if(!(await j(r,"read",{user:t.user,req:t.req,tenantID:t.tenantID,apiKey:t.apiKey})).allowed)return {totalDocs:0};let A={};if(L.where)try{A=JSON.parse(L.where);}catch{}return {totalDocs:await a.count({collection:r.slug,where:A,tenantID:t.tenantID})}}});}for(let r of I){let Q=c[r.slug];Q&&(g[z(v(r.slug))]={type:Q,resolve:async(q,L,t)=>{if(!(await Y(r,"read",{user:t.user,req:t.req,tenantID:t.tenantID,apiKey:t.apiKey})).allowed)throw new Error("Access denied: cannot read global");return t.tenantID&&a.setTenantContext({tenantId:t.tenantID,userId:t.user?.id??"",role:t.user?.role,isSuperAdmin:t.user?.role==="super_admin"}),a.findOne({collection:`_globals_${r.slug}`,where:{},tenantID:t.tenantID})}});}let h=new GraphQLObjectType({name:"Query",fields:g}),G={};for(let r of T){let Q=b[r.slug],q=w[r.slug];!Q||!q||(G[`create${D(v(r.slug))}`]={type:new GraphQLObjectType({name:`${D(v(r.slug))}CreateResult`,fields:{doc:{type:Q},message:{type:GraphQLString}}}),args:{data:{type:new GraphQLNonNull(q)}},resolve:async(L,t,u)=>{if(!(await j(r,"create",{user:u.user,req:u.req,tenantID:u.tenantID,apiKey:u.apiKey})).allowed)throw new Error("Access denied: cannot create");u.tenantID&&a.setTenantContext({tenantId:u.tenantID,userId:u.user?.id??"",role:u.user?.role,isSuperAdmin:u.user?.role==="super_admin"});let N=n.getCreateZodSchema(r.slug).parse(t.data);return {doc:await a.create({collection:r.slug,data:N,tenantID:u.tenantID}),message:"Created successfully"}}},G[`update${D(v(r.slug))}`]={type:new GraphQLObjectType({name:`${D(v(r.slug))}UpdateResult`,fields:{doc:{type:Q},message:{type:GraphQLString}}}),args:{id:{type:new GraphQLNonNull(GraphQLString)},data:{type:new GraphQLNonNull(q)},baseUpdatedAt:{type:GraphQLString}},resolve:async(L,t,u)=>{if(!(await j(r,"update",{user:u.user,req:u.req,tenantID:u.tenantID,apiKey:u.apiKey})).allowed)throw new Error("Access denied: cannot update");if(u.tenantID&&a.setTenantContext({tenantId:u.tenantID,userId:u.user?.id??"",role:u.user?.role,isSuperAdmin:u.user?.role==="super_admin"}),t.baseUpdatedAt){let W=await a.findByID({collection:r.slug,id:t.id,tenantID:u.tenantID,draft:true});if(W&&W.updatedAt&&t.baseUpdatedAt!==W.updatedAt)throw new Error(`Revision conflict: document has changed since ${t.baseUpdatedAt}. Current updatedAt: ${W.updatedAt}`)}let N=n.getUpdateZodSchema(r.slug).parse(t.data);return {doc:await a.update({collection:r.slug,id:t.id,data:N,tenantID:u.tenantID}),message:"Updated successfully"}}},G[`delete${D(v(r.slug))}`]={type:new GraphQLObjectType({name:`${D(v(r.slug))}DeleteResult`,fields:{doc:{type:Q},message:{type:GraphQLString}}}),args:{id:{type:new GraphQLNonNull(GraphQLString)}},resolve:async(L,t,u)=>{if(!(await j(r,"delete",{user:u.user,req:u.req,tenantID:u.tenantID,apiKey:u.apiKey})).allowed)throw new Error("Access denied: cannot delete");return u.tenantID&&a.setTenantContext({tenantId:u.tenantID,userId:u.user?.id??"",role:u.user?.role,isSuperAdmin:u.user?.role==="super_admin"}),{doc:await a.delete({collection:r.slug,id:t.id,tenantID:u.tenantID}),message:"Deleted successfully"}}});}for(let r of I){let Q=m[r.slug];Q&&(G[`update${D(r.slug)}`]={type:new GraphQLObjectType({name:`${D(r.slug)}UpdateResult`,fields:{doc:{type:c[r.slug]||GraphQLString},message:{type:GraphQLString}}}),args:{data:{type:new GraphQLNonNull(Q)}},resolve:async(q,L,t)=>{if(!(await Y(r,"update",{user:t.user,req:t.req,tenantID:t.tenantID,apiKey:t.apiKey})).allowed)throw new Error("Access denied: cannot update global");t.tenantID&&a.setTenantContext({tenantId:t.tenantID,userId:t.user?.id??"",role:t.user?.role,isSuperAdmin:t.user?.role==="super_admin"});let A=await a.findOne({collection:`_globals_${r.slug}`,where:{},tenantID:t.tenantID}),F;return A?F=await a.update({collection:`_globals_${r.slug}`,id:A.id,data:L.data,tenantID:t.tenantID}):F=await a.create({collection:`_globals_${r.slug}`,data:L.data,tenantID:t.tenantID}),{doc:F,message:"Updated successfully"}}});}let S=new GraphQLObjectType({name:"Mutation",fields:G});return new GraphQLSchema({query:h,mutation:S})}function oe(e,n,a){return x({registry:e,db:n,user:a?.user,req:a?.req,tenantID:a?.tenantID,apiKey:a?.apiKey})}
|
|
2
|
+
export{H as a,se as b,x as c,oe as d};
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import {a,c,b
|
|
2
|
-
`)}var
|
|
1
|
+
import {a,c,b,d}from'./chunk-4YYBWCDJ.js';import {sql,eq,desc,and,or,ne,inArray,like,gt,gte,lt,lte}from'drizzle-orm';import {text,uuid,jsonb,timestamp,boolean,decimal,integer as integer$1,varchar,pgTable}from'drizzle-orm/pg-core';import {text as text$1,integer,numeric,sqliteTable}from'drizzle-orm/sqlite-core';import {drizzle}from'drizzle-orm/postgres-js';import oe from'postgres';import {randomBytes}from'crypto';import {mkdir}from'fs/promises';import {resolve,dirname}from'path';import {createRequire}from'module';var M=false;function D(p,s="postgres"){switch(p.type){case "text":case "email":case "password":case "color":return s==="sqlite"?"text":"varchar";case "textarea":case "code":case "markdown":case "secret":return "text";case "number":return p.integer?"integer":"decimal";case "checkbox":return "boolean";case "date":return "timestamp";case "select":case "radio":return s==="sqlite"?"text":"varchar";case "richtext":case "json":case "array":case "group":case "blocks":case "row":case "collapsible":case "tabs":return "jsonb";case "relationship":return s==="sqlite"?"text":"varchar";case "upload":return "jsonb";default:return "jsonb"}}function Ae(p,s="postgres"){let n=p.slug.replace(/-/g,"_"),e=[];e.push(`export const ${n} = pgTable('${n}', {`),e.push(" id: uuid('id').primaryKey().defaultRandom(),");for(let t of p.fields){if(t.name==="id")continue;let o=D(t,s),r=t.required,a=` ${t.name}: pg.${o}('${t.name}')`;t.unique&&(a+=".unique()"),r||(a+=".nullable()"),t.defaultValue!==void 0&&(typeof t.defaultValue=="string"?a+=`.default('${t.defaultValue}')`:typeof t.defaultValue=="boolean"?a+=`.default(${t.defaultValue})`:a+=`.default(sql\`${JSON.stringify(t.defaultValue)}\`)`),a+=",",e.push(a);}return p.timestamps&&(e.push(" createdAt: pg.timestamp('created_at').defaultNow(),"),e.push(" updatedAt: pg.timestamp('updated_at').defaultNow(),")),e.push(` status: ${s==="sqlite"?"sqlite":"pg"}.varchar('status').default('draft'),`),e.push(` hasDraft: ${s==="sqlite"?"sqlite":"pg"}.boolean('hasDraft').default(false),`),e.push("});"),e.join(`
|
|
2
|
+
`)}var S=class extends a{client;schema;dialect;connectionString;versionsTableReady=false;constructor(s){if(super(),this.schema=s.schema||{},s.connectionString){this.connectionString=s.connectionString;let n=s.connectionString.toLowerCase();n.startsWith("postgres://")||n.startsWith("postgresql://")?this.dialect="postgres":n.includes(".db")||n.includes("sqlite")||n.includes("file:")?this.dialect="sqlite":this.dialect=s.type||"postgres";}else this.client=s.client,this.dialect=s.type||"sqlite";}prepareData(s,n){let e=super.prepareData(s,n);e.createdAt&&typeof e.createdAt=="string"&&(e.createdAt=new Date(e.createdAt)),e.updatedAt&&typeof e.updatedAt=="string"&&(e.updatedAt=new Date(e.updatedAt));for(let t of n.fields)if(t.type==="date"&&t.name){let o=e[t.name];o&&typeof o=="string"&&(e[t.name]=new Date(o));}for(let t of n.fields){let r=D(t,this.dialect)==="jsonb";if(t.type==="tabs"&&"tabs"in t&&t.name){let a=s[t.name];if(a&&typeof a=="object"){let i={};for(let[c,u]of Object.entries(a)){let d=t.tabs.flatMap(h=>h.fields).find(h=>h.name===c);(d?.type==="upload"||d?.type==="image"||d?.type==="list"||d?.type==="relationship-block")&&u?i[c]=Array.isArray(u)||typeof u=="object"?JSON.stringify(u):u:i[c]=u;}e[t.name]=r?i:JSON.stringify(i);}}if((t.type==="upload"||t.type==="image"||t.type==="list"||t.type==="relationship-block")&&t.name){let a=s[t.name];a&&(e[t.name]=r?a:Array.isArray(a)||typeof a=="object"?JSON.stringify(a):a);}}for(let t of n.fields)if(t.name&&e[t.name]===""){let o=D(t,this.dialect);(o==="timestamp"||o==="jsonb"||o==="decimal"||o==="integer"||o==="numeric"||o==="boolean")&&(e[t.name]=null);}return e}async connect(){if(this.connectionString&&!this.client){if(this.dialect==="postgres"){let{default:s}=await import('postgres'),{drizzle:n}=await import('drizzle-orm/postgres-js'),e=s(this.connectionString,{onnotice:()=>{}});this.client=n(e,{schema:this.schema});}else if(this.dialect==="sqlite"){let{default:s}=await import('better-sqlite3'),{drizzle:n}=await import('drizzle-orm/better-sqlite3'),e=new s(this.connectionString.replace("file:",""));this.client=n(e,{schema:this.schema});}}this.connected=true;}async init(s,n=[]){if(await super.init(s,n),this.connectionString&&!this.client&&await this.connect(),this.client&&!M){for(let t of s){let o=this.getTableName(t.slug);this.schema[o]||(this.schema[o]=this.createTableFromConfig(t));}await this.ensureCollectionTables(s);let e=n.map(t=>({slug:`_globals_${t.slug}`,fields:t.fields,label:t.label}));for(let t of e){let o=this.getTableName(t.slug);this.schema[o]||(this.schema[o]=this.createTableFromConfig(t,true)),this.collections.has(t.slug)||this.collections.set(t.slug,t);}await this.ensureCollectionTables(e),M=true;}}createTableFromConfig(s,n=false){let e=this.getTableName(s.slug),t={id:n?text("id").primaryKey():uuid("id").primaryKey().defaultRandom()};for(let o of s.fields){if(!o.name||o.name==="id")continue;let r=D(o,this.dialect),a=o.name.replace(/-/g,"_"),i=a.replace(/([A-Z])/g,"_$1").toLowerCase(),c;if(this.dialect==="sqlite")switch(r){case "varchar":case "text":c=text$1(i);break;case "integer":c=integer(i);break;case "decimal":case "numeric":c=numeric(i);break;case "boolean":c=integer(i,{mode:"boolean"});break;case "timestamp":c=text$1(i);break;case "jsonb":c=text$1(i);break;default:c=text$1(i);}else switch(r){case "varchar":c=varchar(i,{length:255});break;case "integer":c=integer$1(i);break;case "decimal":c=decimal(i);break;case "boolean":c=boolean(i);break;case "timestamp":c=timestamp(i);break;case "jsonb":c=jsonb(i);break;default:c=text(i);}o.required||(c=c.default(null)),t[a]=c;}return t.createdAt||(t.createdAt=this.dialect==="sqlite"?text$1("created_at").default(new Date().toISOString()):timestamp("created_at").defaultNow()),t.updatedAt||(t.updatedAt=this.dialect==="sqlite"?text$1("updated_at").default(new Date().toISOString()):timestamp("updated_at").defaultNow()),t.status=this.dialect==="sqlite"?text$1("status").default("draft"):varchar("status",{length:20}).default("draft"),t.hasDraft=this.dialect==="sqlite"?integer("hasDraft",{mode:"boolean"}).default(false):boolean("hasDraft").default(false),this.dialect==="sqlite"?sqliteTable(e,t):pgTable(e,t)}async ensureCollectionTables(s){let n=[];for(let e of s){let t=e.slug.startsWith("_globals_"),o=this.getTableName(e.slug),r=this.generateCreateColumns(e),a=e.fields.some(d=>d.name==="createdAt"),i=e.fields.some(d=>d.name==="updatedAt"),c=e.fields.some(d=>d.name==="status"),u=e.fields.some(d=>d.name==="hasDraft");if(this.dialect==="postgres"){let d=t?'"id" TEXT PRIMARY KEY':'"id" UUID PRIMARY KEY DEFAULT gen_random_uuid()';n.push(`
|
|
3
3
|
CREATE TABLE IF NOT EXISTS "${o}" (
|
|
4
|
-
${
|
|
4
|
+
${d},
|
|
5
5
|
${r}
|
|
6
6
|
${a?"":'"created_at" TIMESTAMP NOT NULL DEFAULT NOW(),'}
|
|
7
7
|
${i?"":'"updated_at" TIMESTAMP NOT NULL DEFAULT NOW(),'}
|
|
@@ -18,27 +18,27 @@ import {a,c,b as b$1,d}from'./chunk-ZAQOSRP6.js';import {sql,eq,desc,and,or,ne,i
|
|
|
18
18
|
${u?"":'"hasDraft" INTEGER DEFAULT 0'}
|
|
19
19
|
)
|
|
20
20
|
`);}if(n.length>0)if(this.dialect==="postgres")await this.client.execute(sql.raw(n.join(`;
|
|
21
|
-
`)));else for(let e of n)await this.client.execute(sql.raw(e));for(let e of s){let t=this.getTableName(e.slug);t==="users"||t==="audit_logs"||await this.syncTableColumns(e,t);}}getColumnSqlDefinition(s,n){let e=
|
|
22
|
-
`)));}if(this.dialect==="postgres")for(let r of s.fields){if(!r.name||r.name==="id")continue;let a=
|
|
23
|
-
`)+(n.length>0?",":"")}async disconnect(){this.connected=false;}async find(s){let{collection:n,where:e={},sort:t,limit:o=10,page:r=1,tenantID:a,select:i,draft:c$1}=s,u=this.getCollection(n),
|
|
21
|
+
`)));else for(let e of n)await this.client.execute(sql.raw(e));for(let e of s){let t=this.getTableName(e.slug);t==="users"||t==="audit_logs"||await this.syncTableColumns(e,t);}}getColumnSqlDefinition(s,n){let e=D(s,n),t=s.name.replace(/-/g,"_").replace(/([A-Z])/g,"_$1").toLowerCase(),o=this.columnSqlType(e,n);return `"${t}" ${o} DEFAULT NULL`}columnSqlType(s,n){if(n==="sqlite")switch(s){case "varchar":return "TEXT";case "text":return "TEXT";case "integer":return "INTEGER";case "decimal":case "numeric":return "NUMERIC";case "boolean":return "INTEGER";case "timestamp":return "TEXT";case "jsonb":return "TEXT";default:return "TEXT"}switch(s){case "varchar":return "VARCHAR(255)";case "text":return "TEXT";case "integer":return "INTEGER";case "decimal":case "numeric":return "DECIMAL";case "boolean":return "BOOLEAN";case "timestamp":return "TIMESTAMP";case "jsonb":return "JSONB";default:return "TEXT"}}getExpectedColumnDefs(s,n){let e={},t=s.slug.startsWith("_globals_"),o=s.fields.some(c=>c.name==="createdAt"),r=s.fields.some(c=>c.name==="updatedAt"),a=s.fields.some(c=>c.name==="status"),i=s.fields.some(c=>c.name==="hasDraft");this.dialect==="postgres"?(e.id=t?'"id" TEXT PRIMARY KEY':'"id" UUID PRIMARY KEY DEFAULT gen_random_uuid()',o||(e.created_at='"created_at" TIMESTAMP DEFAULT NULL'),r||(e.updated_at='"updated_at" TIMESTAMP DEFAULT NULL'),a||(e.status='"status" VARCHAR(20) DEFAULT NULL'),i||(e.hasDraft='"hasDraft" BOOLEAN DEFAULT NULL')):(e.id='"id" TEXT PRIMARY KEY',o||(e.created_at='"created_at" TEXT DEFAULT NULL'),r||(e.updated_at='"updated_at" TEXT DEFAULT NULL'),a||(e.status='"status" TEXT DEFAULT NULL'),i||(e.hasDraft='"hasDraft" INTEGER DEFAULT NULL'));for(let c of s.fields){if(!c.name||c.name==="id")continue;let u=this.getColumnSqlDefinition(c,this.dialect),d=c.name.replace(/-/g,"_").replace(/([A-Z])/g,"_$1").toLowerCase();e[d]=u;}return e}async syncTableColumns(s,n){let e;try{if(this.dialect==="postgres"){let r=await this.client.execute(sql`SELECT column_name, data_type, character_maximum_length FROM information_schema.columns WHERE table_name = ${n}`);e=new Map(r.map(a=>[a.column_name,{type:a.data_type,maxLen:a.character_maximum_length}]));}else {let r=await this.client.execute(sql`PRAGMA table_info("${sql.raw(n)}")`);e=new Map(r.map(a=>[a.name,{type:a.type,maxLen:null}]));}}catch{return}let t=this.getExpectedColumnDefs(s,n),o=Object.keys(t).filter(r=>!e.has(r));if(o.length>0){let r=o.map(a=>`ALTER TABLE "${n}" ADD COLUMN ${t[a]}`);await this.executeRaw(sql.raw(r.join(`;
|
|
22
|
+
`)));}if(this.dialect==="postgres")for(let r of s.fields){if(!r.name||r.name==="id")continue;let a=D(r,this.dialect),i=r.name.replace(/-/g,"_").replace(/([A-Z])/g,"_$1").toLowerCase(),c=e.get(i);!c||c.type!=="character varying"||(a==="text"?await this.executeRaw(sql.raw(`ALTER TABLE "${n}" ALTER COLUMN "${i}" TYPE TEXT`)):a==="jsonb"&&(await this.executeRaw(sql.raw(`ALTER TABLE "${n}" ALTER COLUMN "${i}" DROP DEFAULT`)),await this.executeRaw(sql.raw(`ALTER TABLE "${n}" ALTER COLUMN "${i}" TYPE JSONB USING (CASE WHEN "${i}" IS NULL THEN NULL WHEN "${i}"::text ~ '^\\s*\\{' THEN "${i}"::jsonb ELSE jsonb_build_object('id', "${i}"::text) END)`))));}}generateCreateColumns(s){let n=[];for(let e of s.fields){if(!e.name||e.name==="id")continue;let t=D(e,this.dialect),o=e.name.replace(/-/g,"_").replace(/([A-Z])/g,"_$1").toLowerCase(),r=e.required?"NOT NULL":"DEFAULT NULL",a;if(this.dialect==="sqlite")switch(t){case "varchar":case "text":a=`TEXT ${r}`;break;case "integer":a=`INTEGER ${r}`;break;case "decimal":case "numeric":a=`NUMERIC ${r}`;break;case "boolean":a=`INTEGER ${r}`;break;case "timestamp":a=`TEXT ${r}`;break;case "jsonb":a=`TEXT ${r}`;break;default:a=`TEXT ${r}`;}else switch(t){case "varchar":a=`VARCHAR(255) ${r}`;break;case "integer":a=`INTEGER ${r}`;break;case "decimal":a=`DECIMAL ${r}`;break;case "boolean":a=`BOOLEAN ${r}`;break;case "timestamp":a=`TIMESTAMP ${r}`;break;case "jsonb":a=`JSONB ${r}`;break;default:a=`TEXT ${r}`;}n.push(`"${o}" ${a}`);}return n.join(`,
|
|
23
|
+
`)+(n.length>0?",":"")}async disconnect(){this.connected=false;}async find(s){let{collection:n,where:e={},sort:t,limit:o=10,page:r=1,tenantID:a,select:i,draft:c$1}=s,u=this.getCollection(n),d$1=this.getTable(n),T={...e};this.tenantContext&&u.tenantScoped&&(T=c({where:T},n,this.tenantContext,b).where||{});let h=this.buildWhereClause(T,u,d$1,a),m=u.fields.find(f=>f.name==="status"),g=m?.type==="select"&&m.options?.some(f=>f.value==="published");!c$1&&d$1.status&&g&&h.push(eq(d$1.status,"published"));let E=this.parseSort(t),R=!c$1&&d$1.status&&g?{...T,status:"published"}:T,j=await this.count({collection:n,where:R,tenantID:a}),B=(r-1)*o,v=[];try{let f=d$1[E.field]||d$1.createdAt||d$1.id,N=E.direction==="asc"?f:desc(f),b=this.client.select().from(d$1);h.length>0&&(b=b.where(and(...h))),v=await b.orderBy(N).limit(o).offset(B);}catch(f){console.error("[DrizzleAdapter] Query error:",f);}let _=v.map(f=>this.processResult(f,u));return this.tenantContext&&!this.tenantContext.isSuperAdmin&&(_=_.filter(f=>d(f,n,this.tenantContext,b))),c$1&&(_=await Promise.all(_.map(async f=>{let N=await this.executeRaw(sql`
|
|
24
24
|
SELECT * FROM kyro_versions
|
|
25
25
|
WHERE collection_slug = ${n}
|
|
26
|
-
AND document_id = ${
|
|
26
|
+
AND document_id = ${f.id}
|
|
27
27
|
ORDER BY created_at DESC
|
|
28
28
|
LIMIT 1
|
|
29
|
-
`);if(
|
|
29
|
+
`);if(N.length>0){let b=N[0],X=typeof b.data=="string"?JSON.parse(b.data):b.data;return {...f,...X,status:f.status}}return f}))),{docs:_,...this.calculatePagination(r,o,j)}}async findByID(s){let{collection:n,id:e,tenantID:t,draft:o}=s,r=this.getCollection(n),a=this.getTable(n);if(this.tenantContext&&r.tenantScoped){let m={id:e,tenantId:this.tenantContext.tenantId};if(!d(m,n,this.tenantContext,b))return null}let i=[eq(a.id,e)];t&&a.tenantId&&i.push(eq(a.tenantId,t));let c=r.fields.find(m=>m.name==="status"),u=c?.type==="select"&&c.options?.some(m=>m.value==="published");!o&&a.status&&u&&i.push(eq(a.status,"published"));let d$1=i.length>1?and(...i):i[0],T=await this.client.select().from(a).where(d$1);if(T.length===0)return null;let h=this.processResult(T[0],r);if(o){let m=await this.executeRaw(sql`
|
|
30
30
|
SELECT * FROM kyro_versions
|
|
31
31
|
WHERE collection_slug = ${n}
|
|
32
|
-
AND document_id = ${
|
|
32
|
+
AND document_id = ${h.id}
|
|
33
33
|
ORDER BY created_at DESC
|
|
34
34
|
LIMIT 1
|
|
35
|
-
`);if(
|
|
35
|
+
`);if(m.length>0){let g=m[0],E=typeof g.data=="string"?JSON.parse(g.data):g.data;h={...h,...E,status:h.status};}}return h}async create(s){let{collection:n,data:e,tenantID:t}=s,o=this.getCollection(n),r=this.getTable(n),a=this.prepareData(e,o);t&&(a.tenantId=t);let i=await this.client.insert(r).values(a).returning();return this.processResult(i[0],o)}async update(s){let{collection:n,id:e,data:t,tenantID:o}=s,r=this.getCollection(n),a=this.getTable(n),i=this.prepareData(t,r);delete i.id;let c=[eq(a.id,e)];o&&a.tenantId&&c.push(eq(a.tenantId,o));let u=await this.client.update(a).set(i).where(and(...c)).returning();if(u.length===0)throw new Error(`Document not found: ${n}/${e}`);return this.processResult(u[0],r)}async delete(s){let{collection:n,id:e,tenantID:t}=s,o=this.getCollection(n),r=this.getTable(n),a=[eq(r.id,e)];t&&r.tenantId&&a.push(eq(r.tenantId,t));let i=await this.client.delete(r).where(and(...a)).returning();if(i.length===0)throw new Error(`Document not found: ${n}/${e}`);return this.processResult(i[0],o)}async count(s){let{collection:n,where:e={},tenantID:t}=s,o=this.getCollection(n),r=this.getTable(n),a=this.buildWhereClause(e,o,r,t);try{let i=this.client.select({count:sql`count(*)`}).from(r);a.length>0&&(i=i.where(and(...a)));let c=await i;return Number(c[0]?.count||0)}catch{return 0}}async findOne(s){let{collection:n,where:e={},tenantID:t,draft:o}=s;if(n.startsWith("_globals_")){let a=n.replace("_globals_",""),i=this.globals.get(a);if(!i)throw new Error(`Global "${a}" not found`);let c=this.getTable(n),u=this.client.select().from(c),d=i.fields.find(g=>g.name==="status"),T=d?.type==="select"&&d.options?.some(g=>g.value==="published");!o&&c.status&&T&&(u=u.where(eq(c.status,"published")));let h=await u.limit(1);if(h.length===0)return null;let m=this.processResult(h[0],i);if(o){let g=await this.executeRaw(sql`
|
|
36
36
|
SELECT * FROM kyro_versions
|
|
37
37
|
WHERE collection_slug = ${n}
|
|
38
38
|
AND document_id = ${a}
|
|
39
39
|
ORDER BY created_at DESC
|
|
40
40
|
LIMIT 1
|
|
41
|
-
`);if(
|
|
41
|
+
`);if(g.length>0){let E=g[0],R=typeof E.data=="string"?JSON.parse(E.data):E.data;m={...m,...R,status:m.status};}}return m}return (await this.find({...s,limit:1})).docs[0]||null}async findVersions(s){await this.ensureVersionsTable();let{collection:n,documentId:e,limit:t=10,page:o=1,tenantID:r}=s,a=(o-1)*t,i=await this.executeRaw(sql`
|
|
42
42
|
SELECT count(*) as count
|
|
43
43
|
FROM kyro_versions
|
|
44
44
|
WHERE collection_slug = ${n}
|
|
@@ -55,7 +55,7 @@ import {a,c,b as b$1,d}from'./chunk-ZAQOSRP6.js';import {sql,eq,desc,and,or,ne,i
|
|
|
55
55
|
ORDER BY created_at DESC
|
|
56
56
|
LIMIT ${t}
|
|
57
57
|
OFFSET ${a}
|
|
58
|
-
`)).map(
|
|
58
|
+
`)).map(d=>({...d,data:typeof d.data=="string"?JSON.parse(d.data):d.data})),...this.calculatePagination(o,t,c)}}async findVersionByID(s){await this.ensureVersionsTable();let n=await this.executeRaw(sql`
|
|
59
59
|
SELECT * FROM kyro_versions
|
|
60
60
|
WHERE id = ${s.versionId}
|
|
61
61
|
AND collection_slug = ${s.collection}
|
|
@@ -129,5 +129,5 @@ import {a,c,b as b$1,d}from'./chunk-ZAQOSRP6.js';import {sql,eq,desc,and,or,ne,i
|
|
|
129
129
|
created_at text NOT NULL,
|
|
130
130
|
updated_at text NOT NULL
|
|
131
131
|
)
|
|
132
|
-
`,await this.executeRaw(sql.raw(s));try{this.dialect==="postgres"?await this.executeRaw(sql.raw("ALTER TABLE kyro_versions ADD COLUMN IF NOT EXISTS autosave integer NOT NULL DEFAULT 0")):await this.executeRaw(sql.raw("ALTER TABLE kyro_versions ADD COLUMN autosave integer NOT NULL DEFAULT 0"));}catch{}this.versionsTableReady=true;}async executeRaw(s){let n=await this.client.execute(s);return Array.isArray(n)?n:Array.isArray(n?.rows)?n.rows:Array.isArray(n?.[0])?n[0]:[]}};function
|
|
133
|
-
export{
|
|
132
|
+
`,await this.executeRaw(sql.raw(s));try{this.dialect==="postgres"?await this.executeRaw(sql.raw("ALTER TABLE kyro_versions ADD COLUMN IF NOT EXISTS autosave integer NOT NULL DEFAULT 0")):await this.executeRaw(sql.raw("ALTER TABLE kyro_versions ADD COLUMN autosave integer NOT NULL DEFAULT 0"));}catch{}this.versionsTableReady=true;}async executeRaw(s){let n=await this.client.execute(s);return Array.isArray(n)?n:Array.isArray(n?.rows)?n.rows:Array.isArray(n?.[0])?n[0]:[]}};function De(p){return new S(p)}var fe=createRequire(import.meta.url),pe="node:sqlite",{DatabaseSync:he}=fe(pe);function me(){return process.env.DB_TYPE==="postgres"?"postgres":"sqlite"}function P(){return randomBytes(16).toString("hex")}async function $e(){let p=me();if(p==="sqlite"){let r=resolve(process.cwd(),"data","kyro.db");await mkdir(dirname(r),{recursive:true});let a=new he(r);return a.exec("PRAGMA journal_mode = WAL"),{db:a,dialect:p,genId:P}}let s=process.env.DATABASE_URL||"postgresql://postgres:postgres@localhost:5432/kyro_cms",n=parseInt(process.env.DB_POOL_MAX||"10",10),e=process.env.DB_SSL==="true",t=oe(s,{max:n,ssl:e?"require":false,onnotice:()=>{}});return {db:drizzle(t),dialect:p,genId:P}}async function Se(p,s){}async function ve(p){let{roles:s}=await import('./schema-KFYUM674.js');await p.insert(s).values({name:"super_admin",level:100,inherits:[],description:"Full system access across all tenants",isSystem:true}).onConflictDoNothing();}
|
|
133
|
+
export{D as a,Ae as b,S as c,De as d,P as e,$e as f,Se as g,ve as h};
|