@kyro-cms/core 0.12.16 → 0.12.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/README.md +5 -2
- package/dist/{WebhookService-i-Kl3dvf.d.cts → WebhookService-BBcCHBo8.d.cts} +1 -1
- package/dist/{WebhookService-ByrpAI4d.d.ts → WebhookService-C19xR8qE.d.ts} +1 -1
- 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/{base-iyJTfH-3.d.cts → base-C2iwjdJQ.d.cts} +2 -7
- package/dist/{base-oUSURe4_.d.ts → base-yXdYZxFK.d.ts} +2 -7
- package/dist/chunk-3Q2WUG63.cjs +2 -0
- package/dist/chunk-4RMFCTWH.js +1 -0
- package/dist/{chunk-TQNM4C7H.js → chunk-5KOQYQEE.js} +1 -1
- package/dist/{chunk-ZZIGN5PZ.js → chunk-7USZ4YRI.js} +1 -1
- package/dist/chunk-BVG6VSAJ.cjs +1 -0
- package/dist/chunk-CPGTIDGM.js +3 -0
- package/dist/chunk-DKESD4HI.js +133 -0
- package/dist/chunk-EQIAXBR4.cjs +86 -0
- package/dist/{chunk-EJDIR56C.cjs → chunk-FHJJKFAU.cjs} +1 -1
- package/dist/chunk-FVZ5RFLO.js +2 -0
- package/dist/chunk-G7SSHELM.cjs +1 -0
- package/dist/chunk-GXVCCKOL.js +1 -0
- package/dist/chunk-HRNAHWDS.js +21 -0
- package/dist/chunk-ILEZ3NYX.cjs +2 -0
- package/dist/{chunk-RY3BG3AN.cjs → chunk-JAJ6ZWAQ.cjs} +1 -1
- package/dist/chunk-LHW4R367.js +1 -0
- package/dist/chunk-ODPUHZUA.js +86 -0
- package/dist/chunk-RDKCMKBE.cjs +21 -0
- package/dist/chunk-RNCVLIKD.cjs +3 -0
- package/dist/chunk-VGQ4VUG6.js +2 -0
- package/dist/chunk-WG3UQEV7.cjs +133 -0
- package/dist/chunk-ZUVP4UK7.cjs +1 -0
- package/dist/cli/index.cjs +1 -1
- package/dist/cli/index.js +1 -1
- package/dist/client.d.cts +1 -1
- package/dist/client.d.ts +1 -1
- package/dist/drizzle/index.cjs +1 -1
- package/dist/drizzle/index.d.cts +3 -8
- package/dist/drizzle/index.d.ts +3 -8
- package/dist/drizzle/index.js +1 -1
- package/dist/graphql/index.d.cts +2 -2
- package/dist/graphql/index.d.ts +2 -2
- package/dist/{index-DVDMEql7.d.ts → index-CqR97Q2L.d.ts} +1 -1
- package/dist/{index-DNy8jbA2.d.cts → index-DRNSjOte.d.cts} +1 -1
- package/dist/index.cjs +26 -19
- package/dist/index.d.cts +200 -15
- package/dist/index.d.ts +200 -15
- package/dist/index.js +26 -19
- package/dist/mongo-auth-adapter-AIMZTNG6.js +1 -0
- package/dist/{mongo-auth-adapter-6726C5KF.cjs → mongo-auth-adapter-C62QYCYV.cjs} +1 -1
- package/dist/mongodb/index.cjs +1 -1
- package/dist/mongodb/index.d.cts +6 -9
- package/dist/mongodb/index.d.ts +6 -9
- package/dist/mongodb/index.js +1 -1
- package/dist/rest/index.cjs +1 -1
- package/dist/rest/index.d.cts +3 -3
- package/dist/rest/index.d.ts +3 -3
- package/dist/rest/index.js +1 -1
- package/dist/templates/index.cjs +1 -1
- package/dist/templates/index.d.cts +1 -1
- package/dist/templates/index.d.ts +1 -1
- package/dist/templates/index.js +1 -1
- package/dist/trpc/index.cjs +1 -1
- package/dist/trpc/index.d.cts +2 -2
- package/dist/trpc/index.d.ts +2 -2
- package/dist/trpc/index.js +1 -1
- package/dist/{types-BcZiluXL.d.cts → types-BjivdGbU.d.cts} +10 -7
- package/dist/{types-Dc8VAPhF.d.ts → types-CaXXmV9h.d.ts} +10 -7
- package/package.json +6 -3
- package/dist/chunk-2NJR2B4W.cjs +0 -3
- package/dist/chunk-3RR6IV5I.js +0 -133
- package/dist/chunk-3ZFRP5M2.cjs +0 -133
- package/dist/chunk-DTSYK7KK.js +0 -21
- package/dist/chunk-FGSIHWQJ.js +0 -3
- package/dist/chunk-HHH4XNNS.cjs +0 -1
- package/dist/chunk-I67R6MR5.js +0 -2
- package/dist/chunk-IQYP3DDJ.cjs +0 -21
- package/dist/chunk-ISCIUG37.js +0 -1
- package/dist/chunk-IZCTG4RG.js +0 -1
- package/dist/chunk-M5JUPA7G.cjs +0 -86
- package/dist/chunk-NI7S5JMH.js +0 -86
- package/dist/chunk-RYIEE2TH.cjs +0 -2
- package/dist/chunk-W6P4N3Z7.js +0 -2
- package/dist/chunk-WMZEULS2.cjs +0 -1
- package/dist/chunk-XUONID6O.cjs +0 -2
- package/dist/mongo-auth-adapter-U6SH4OWA.js +0 -1
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import {a as a$2}from'./chunk-NZ35PV5R.js';import {a as a$1}from'./chunk-5SEHX7ON.js';import {a as a$4,i}from'./chunk-LHW4R367.js';import {c as c$2,a as a$3}from'./chunk-PP7W5UKL.js';import {a,b,c,f,t}from'./chunk-ODPUHZUA.js';import {o,f as f$1,g as g$1}from'./chunk-FVZ5RFLO.js';import {d,f as f$2,e,g as g$2}from'./chunk-HLSB2MCK.js';import {b as b$1,d as d$1}from'./chunk-GKYEJ2UF.js';import {c as c$1}from'./chunk-DKESD4HI.js';import {g}from'./chunk-OG7CNQGU.js';import {a as a$5,c as c$3,b as b$2,d as d$2}from'./chunk-5KOQYQEE.js';import {a as a$6}from'./chunk-4RMFCTWH.js';import {z as z$1}from'zod';import {createYoga}from'graphql-yoga';import {createRequire}from'module';import {randomBytes}from'crypto';function L(n,e){for(let t of n){if(t.name===e)return true;if("tabs"in t&&t.tabs){for(let s of t.tabs)if(L(s.fields,e))return true}if("fields"in t&&t.fields&&L(t.fields,e))return true}return false}var H=class extends Error{errors;constructor(e){super(`Configuration validation failed:
|
|
2
|
+
${e.join(`
|
|
3
|
+
`)}`),this.name="ConfigValidationError",this.errors=e;}};function W(n){let e=[];if(n.slug?/^[a-z][a-z0-9_-]*$/.test(n.slug)||e.push(`Collection slug "${n.slug}" must be lowercase alphanumeric with dashes`):e.push('Collection is missing a "slug" property'),!n.fields||n.fields.length===0)e.push(`Collection "${n.slug}" has no fields defined`);else {let t=w(n.fields,n.slug);e.push(...t);}if(n.access)for(let[t,s]of Object.entries(n.access))typeof s!="boolean"&&typeof s!="function"&&e.push(`Collection "${n.slug}" has invalid access.${t} (must be boolean or function)`);if(n.admin?.useAsTitle&&(L(n.fields,n.admin.useAsTitle)||e.push(`Collection "${n.slug}" admin.useAsTitle references unknown field "${n.admin.useAsTitle}"`)),n.admin?.defaultColumns)for(let t of n.admin.defaultColumns)L(n.fields,t)||e.push(`Collection "${n.slug}" admin.defaultColumns references unknown field "${t}"`);if(n.upload&&n.upload.fileSize&&n.upload.fileSize<=0&&e.push(`Collection "${n.slug}" upload.fileSize must be positive`),n.versions&&n.versions.maxPerDoc&&n.versions.maxPerDoc<=0&&e.push(`Collection "${n.slug}" versions.maxPerDoc must be positive`),n.auth){let t=n.fields.some(i=>i.name==="email"),s=n.fields.some(i=>i.name==="password");t||e.push(`Collection "${n.slug}" with auth enabled requires an "email" field`),s||e.push(`Collection "${n.slug}" with auth enabled requires a "password" field`);}return e}function z(n){let e=[];if(n.slug?/^[a-z][a-z0-9_-]*$/.test(n.slug)||e.push(`Global slug "${n.slug}" must be lowercase alphanumeric with dashes`):e.push('Global is missing a "slug" property'),!n.fields||n.fields.length===0)e.push(`Global "${n.slug}" has no fields defined`);else {let t=w(n.fields,`global:${n.slug}`);e.push(...t);}return e}function w(n,e){let t=[],s=new Set;for(let i=0;i<n.length;i++){let o=n[i];if(o.type==="row"||o.type==="collapsible"||o.type==="tabs"){if("fields"in o&&o.fields){let r=w(o.fields,e);t.push(...r);}else if("tabs"in o)for(let r of o.tabs){let c=w(r.fields,e);t.push(...c);}continue}let a=o.name;if(!a){t.push(`${e}: Field at index ${i} is missing a "name" property`);continue}if(s.has(a)&&t.push(`${e}: Duplicate field name "${a}"`),s.add(a),/^[a-zA-Z][a-zA-Z0-9_]*$/.test(a)||t.push(`${e}: Field name "${a}" must be alphanumeric with underscores`),!o.type){t.push(`${e}: Field "${a}" is missing a "type" property`);continue}switch(o.type){case "relationship":o.relationTo||t.push(`${e}: Relationship field "${a}" is missing "relationTo"`);break;case "array":if(!o.fields||o.fields.length===0)t.push(`${e}: Array field "${a}" has no fields defined`);else {let r=w(o.fields,`${e}.${a}`);t.push(...r);}break;case "group":if(!o.fields||o.fields.length===0)t.push(`${e}: Group field "${a}" has no fields defined`);else {let r=w(o.fields,`${e}.${a}`);t.push(...r);}break;case "blocks":if(!o.blocks||o.blocks.length===0)t.push(`${e}: Blocks field "${a}" has no blocks defined`);else {let r=Ue(o.blocks,`${e}.${a}`);t.push(...r);}break;case "select":case "radio":if(typeof o.options=="function")break;if((!o.options||o.options.length===0)&&!o.dynamicOptions)t.push(`${e}: ${o.type} field "${a}" has no options defined`);else if(Array.isArray(o.options)){let r=o.options.map(d=>d.value),c=new Set(r);r.length!==c.size&&t.push(`${e}: ${o.type} field "${a}" has duplicate option values`);}break;case "upload":o.relationTo||t.push(`${e}: Upload field "${a}" is missing "relationTo"`);break}"min"in o&&"max"in o&&o.min>o.max&&t.push(`${e}: Field "${a}" has min greater than max`),"minLength"in o&&"maxLength"in o&&o.minLength>o.maxLength&&t.push(`${e}: Field "${a}" has minLength greater than maxLength`),"minRows"in o&&"maxRows"in o&&o.minRows>o.maxRows&&t.push(`${e}: Field "${a}" has minRows greater than maxRows`);}return t}function Ue(n,e){let t=[],s=new Set;for(let i of n){if(!i.slug){t.push(`${e}: Block is missing a "slug" property`);continue}if(s.has(i.slug)&&t.push(`${e}: Duplicate block slug "${i.slug}"`),s.add(i.slug),i.label||t.push(`${e}: Block "${i.slug}" is missing a "label" property`),!i.fields||i.fields.length===0)t.push(`${e}: Block "${i.slug}" has no fields defined`);else {let o=w(i.fields,`${e}.${i.slug}`);t.push(...o);}}return t}function ve(n,e=[]){let t=[],s=new Set;for(let i of n)s.has(i.slug)&&t.push(`Duplicate collection slug "${i.slug}"`),s.add(i.slug);for(let i of e)s.has(i.slug)&&t.push(`Duplicate global slug "${i.slug}"`),s.add(i.slug);for(let i of n){let o=W(i);t.push(...o);}for(let i of e){let o=z(i);t.push(...o);}for(let i of n){let o=$(i.fields,n);t.push(...o);}if(t.length>0)throw new H(t)}function $(n,e){let t=[],s=new Set(e.map(i=>i.slug));for(let i of n){if(i.type==="relationship"){let o=Array.isArray(i.relationTo)?i.relationTo:[i.relationTo];for(let a of o)a!=="*"&&!s.has(a)&&console.warn(`[Kyro Config Warning]: Relationship field "${i.name}" references unknown collection "${a}". Select options will not be available until this collection is registered.`);}if(i.type==="upload"){let o=Array.isArray(i.relationTo)?i.relationTo:[i.relationTo];for(let a of o)s.has(a)||t.push(`Upload field "${i.name}" references unknown collection "${a}"`);}if("fields"in i&&i.fields){let o=$(i.fields,e);t.push(...o);}if("tabs"in i)for(let o of i.tabs){let a=$(o.fields,e);t.push(...a);}if("blocks"in i)for(let o of i.blocks){let a=$(o.fields,e);t.push(...a);}}return t}function A(n){switch(n.type){case "text":return Ke(n);case "number":return Me(n);case "checkbox":return Ve(n);case "date":return Be(n);case "email":return He(n);case "password":return We(n);case "textarea":return ze(n);case "select":return Xe(n);case "radio":return Je(n);case "color":return Ye(n);case "richtext":return Qe(n);case "json":return et(n);case "code":return tt(n);case "upload":return Ee(n);case "image":return Ee(n);case "markdown":return st(n);case "relationship":return Re(n);case "relationship-block":return Re(n);case "array":return nt(n);case "list":return it(n);case "group":return ot(n);case "blocks":return at(n);case "row":return rt(n);case "collapsible":return lt(n);case "tabs":return ct(n);default:return z$1.any()}}function Ke(n){let e=z$1.string();return n.minLength&&(e=e.min(n.minLength)),n.maxLength&&(e=e.max(n.maxLength)),n.pattern&&(e=e.regex(new RegExp(n.pattern))),n.variant==="email"&&(e=e.email()),n.variant==="url"&&(e=e.url()),n.hasMany&&(e=z$1.array(e)),n.required||(e=e.optional().nullable()),n.validate&&(e=T(e,n.validate)),e}function Me(n){let e=n.integer?z$1.coerce.number().int():z$1.coerce.number();return n.min!==void 0&&(e=e.min(n.min)),n.max!==void 0&&(e=e.max(n.max)),n.step&&(e=e.refine(t=>Number.isInteger(t/n.step),`Value must be divisible by ${n.step}`)),n.hasMany&&(e=z$1.array(e)),n.required||(e=e.optional().nullable()),n.validate&&(e=T(e,n.validate)),e}function Ve(n){let e=z$1.boolean();return n.required||(e=e.optional().nullable()),n.validate&&(e=T(e,n.validate)),e}function Be(n){let e=z$1.string().refine(t=>!isNaN(Date.parse(t)),"Invalid date format");return n.minDate&&(e=e.refine(t=>new Date(t)>=new Date(n.minDate),`Date must be after ${n.minDate}`)),n.maxDate&&(e=e.refine(t=>new Date(t)<=new Date(n.maxDate),`Date must be before ${n.maxDate}`)),n.required||(e=e.optional().nullable()),n.validate&&(e=T(e,n.validate)),e}function He(n){let e=z$1.string().email("Invalid email");return n.required||(e=e.optional().nullable()),n.validate&&(e=T(e,n.validate)),e}function We(n){let e=z$1.string().min(6,"Password must be at least 6 characters");return n.required||(e=e.optional().nullable()),n.validate&&(e=T(e,n.validate)),e}function ze(n){let e=z$1.string();return n.minLength&&(e=e.min(n.minLength)),n.maxLength&&(e=e.max(n.maxLength)),n.required||(e=e.optional().nullable()),n.validate&&(e=T(e,n.validate)),e}function Xe(n){let e;if(Array.isArray(n.options)&&n.options.length>0){let t=n.options.map(s=>s.value);n.hasMany?e=z$1.array(z$1.enum(t)):e=z$1.enum(t);}else e=n.hasMany?z$1.array(z$1.string()):z$1.string();return n.required||(e=e.optional().nullable()),n.validate&&(e=T(e,n.validate)),e}function Je(n){let e;if(Array.isArray(n.options)&&n.options.length>0){let t=n.options.map(s=>s.value);e=z$1.enum(t);}else e=z$1.string();return n.required||(e=e.optional().nullable()),n.validate&&(e=T(e,n.validate)),e}function Ye(n){let e=z$1.string();return n.format==="hex"&&(e=e.regex(/^#[0-9A-Fa-f]{6}$/)),n.format==="rgb"&&(e=e.regex(/^rgb\(\s*\d{1,3}\s*,\s*\d{1,3}\s*,\s*\d{1,3}\s*\)$/)),n.format==="hsl"&&(e=e.regex(/^hsl\(\s*\d{1,3}\s*,\s*\d{1,3}%\s*,\s*\d{1,3}%\s*\)$/)),n.required||(e=e.optional().nullable()),n.validate&&(e=T(e,n.validate)),e}function Qe(n){let e=z$1.array(z$1.record(z$1.any()));return n.required||(e=e.optional().nullable()),n.validate&&(e=T(e,n.validate)),e}function et(n){let e=z$1.union([z$1.record(z$1.any()),z$1.array(z$1.any())]);return n.required||(e=e.optional().nullable()),n.validate&&(e=T(e,n.validate)),e}function tt(n){let e=z$1.string();return n.required||(e=e.optional().nullable()),n.validate&&(e=T(e,n.validate)),e}function Ee(n){let e;if(n.relationTo){let t=z$1.object({id:z$1.string(),url:z$1.string().optional(),filename:z$1.string().optional(),mimeType:z$1.string().optional()});e=z$1.union([z$1.string(),t]);}else e=z$1.string();return n.hasMany&&(e=z$1.array(e)),n.required||(e=e.optional().nullable()),n.validate&&(e=T(e,n.validate)),e}function st(n){let e=z$1.string();return n.required||(e=e.optional().nullable()),n.validate&&(e=T(e,n.validate)),e}function Re(n){let e;return Array.isArray(n.relationTo)?e=z$1.object({relationTo:z$1.enum(n.relationTo),value:z$1.string()}):e=z$1.union([z$1.string(),z$1.object({relationTo:z$1.string(),value:z$1.string()})]),n.hasMany&&(e=z$1.array(e)),n.required||(e=e.optional().nullable()),n.validate&&(e=T(e,n.validate)),e}function nt(n){let e=z$1.object(Object.fromEntries(n.fields.filter(s=>s.name).map(s=>[s.name,A(s)]))).passthrough(),t=z$1.array(e);return n.minRows&&(t=t.min(n.minRows)),n.maxRows&&(t=t.max(n.maxRows)),n.required||(t=t.optional().nullable()),n.validate&&(t=T(t,n.validate)),t}function it(n){let e=z$1.array(z$1.string());return n.required||(e=e.optional().nullable()),e}function ot(n){let e=z$1.object(Object.fromEntries(n.fields.filter(t=>t.name).map(t=>[t.name,A(t)])));return n.required?e:e.optional().nullable()}function at(n){let e=n.blocks||[];e.map(o=>z$1.object({blockType:z$1.literal(o.slug),...Object.fromEntries(o.fields.filter(a=>a.name).map(a=>[a.name,A(a)]))}));let s=e.map(o=>o.slug),i;if(s.length>0){let o=z$1.object({blockType:z$1.enum(s)}).catchall(z$1.any()),a=z$1.object({blockType:z$1.string()}).catchall(z$1.any());i=z$1.array(z$1.union([o,a,z$1.record(z$1.any())]));}else i=z$1.array(z$1.union([z$1.object({blockType:z$1.string()}).catchall(z$1.any()),z$1.record(z$1.any())]));return n.minRows&&(i=i.min(n.minRows)),n.maxRows&&(i=i.max(n.maxRows)),n.required||(i=i.optional().nullable()),n.validate&&(i=T(i,n.validate)),i}function rt(n){return z$1.object(Object.fromEntries(n.fields.filter(t=>t.name).map(t=>[t.name,A(t)])))}function lt(n){return z$1.object(Object.fromEntries(n.fields.filter(t=>t.name).map(t=>[t.name,A(t)])))}function ct(n){let e={};for(let t of n.tabs)for(let s of t.fields)s.name&&(e[s.name]=A(s));return z$1.object(e).passthrough().optional()}function T(n,e){return n.refine(async t=>await e(t,{required:false})===true,{message:"Custom validation failed"})}function D(n){let e={};for(let t of n)if(t.type==="tabs"&&"tabs"in t){let s={};for(let i of t.tabs){let o=D(i.fields);Object.assign(s,o);}t.name?e[t.name]=z$1.object(s).passthrough().optional():Object.assign(e,s);}else if(t.type==="row"&&"fields"in t){let s=D(t.fields);t.name?e[t.name]=z$1.object(s).passthrough().optional():Object.assign(e,s);}else if(t.type==="collapsible"&&"fields"in t){let s=D(t.fields);t.name?e[t.name]=z$1.object(s).passthrough().optional():Object.assign(e,s);}else {if(!t.name)continue;e[t.name]=A(t);}return e}function v(n){let e={};for(let t of n)if(t.type==="tabs"&&"tabs"in t){let s={};for(let i of t.tabs){let o=v(i.fields);Object.assign(s,o);}t.name?e[t.name]=z$1.object(s).passthrough().optional().nullable():Object.assign(e,s);}else if(t.type==="row"&&"fields"in t){let s=v(t.fields);t.name?e[t.name]=z$1.object(s).passthrough().optional().nullable():Object.assign(e,s);}else if(t.type==="collapsible"&&"fields"in t){let s=v(t.fields);t.name?e[t.name]=z$1.object(s).passthrough().optional().nullable():Object.assign(e,s);}else if(t.type==="group"&&"fields"in t)t.name?e[t.name]=z$1.object(v(t.fields)).passthrough().optional().nullable():Object.assign(e,v(t.fields));else {if(!t.name)continue;e[t.name]=A(t).optional().nullable();}return e}function we(n){let e=D(n.fields);return n.timestamps&&(e.createdAt=z$1.string().optional(),e.updatedAt=z$1.string().optional()),n.tenantScoped&&(e.tenantId=z$1.string().optional()),e.id=z$1.string().optional(),z$1.object(e).passthrough()}function Ne(n){let e=D(n.fields);return z$1.object(e).passthrough()}function De(n){let e={};for(let t of n.fields)if(t.name)if(t.type==="tabs"&&"tabs"in t){let s={};for(let i of t.tabs)for(let o of i.fields)o.name&&(s[o.name]=A(o).optional().nullable());e[t.name]=z$1.object(s).optional().nullable();}else if(t.type==="row"&&"fields"in t){let s={};for(let i of t.fields)i.name&&(s[i.name]=A(i).optional().nullable());Object.assign(e,s);}else t.type==="collapsible"&&"fields"in t?e[t.name]=z$1.object(v(t.fields)).optional().nullable():t.type==="group"&&"fields"in t?e[t.name]=z$1.object(v(t.fields)).optional().nullable():e[t.name]=A(t).optional().nullable();return z$1.object(e).passthrough()}function Fe(n){let e={};for(let t of n.fields)t.name&&(e[t.name]=z$1.object({equals:z$1.any().optional(),not_equals:z$1.any().optional(),in:z$1.array(z$1.any()).optional(),not_in:z$1.array(z$1.any()).optional(),greater_than:z$1.number().optional(),greater_than_equal:z$1.number().optional(),less_than:z$1.number().optional(),less_than_equal:z$1.number().optional(),like:z$1.string().optional(),not_like:z$1.string().optional(),contains:z$1.string().optional(),exists:z$1.boolean().optional()}).optional());return e.AND=z$1.array(z$1.lazy(()=>z$1.object(e))).optional(),e.OR=z$1.array(z$1.lazy(()=>z$1.object(e))).optional(),z$1.object(e).optional()}function ke(n){let e=D(n.fields);return e.id=z$1.string().optional(),z$1.object(e).passthrough()}function Ie(n){let e={};for(let t of n.fields)if(t.name)if(t.type==="tabs"&&"tabs"in t){let s={};for(let i of t.tabs)for(let o of i.fields)o.name&&(s[o.name]=A(o).optional().nullable());e[t.name]=z$1.object(s).optional().nullable();}else t.type==="collapsible"&&"fields"in t?e[t.name]=z$1.object(v(t.fields)).optional().nullable():t.type==="group"&&"fields"in t?e[t.name]=z$1.object(v(t.fields)).optional().nullable():e[t.name]=A(t).optional().nullable();return z$1.object(e).passthrough()}var k=class{storageProviders=f();collections=new Map;globals=new Map;plugins=[];schemaCache=new Map;initialized=false;addCollection(e){if(this.initialized)throw new Error("Cannot add collections after Registry has been initialized");if(this.collections.has(e.slug)){console.warn(`[Registry] Duplicate collection slug "${e.slug}" \u2014 skipping`);return}let t={...e,fields:[...e.fields]};for(let i of this.plugins){let o=i.extensions?.collections?.find(a=>a.slug===t.slug);o&&(t={...t,...o.config,fields:[...t.fields,...o.config.fields||[]]});}if(t.seo){let i=a$1(),o=t.fields.findIndex(a=>a.type==="tabs");if(o!==-1){let a=t.fields[o];t.fields[o]={...a,tabs:[...a.tabs,{label:"SEO Settings",fields:i.fields}]};}else t.fields.push(i);}t.fields=this.applyFieldDefaults(t);let s=W(t);if(s.length>0)throw new Error(`Invalid collection config: ${s.join(", ")}`);this.collections.set(t.slug,t),this.clearSchemaCache(t.slug);}addCollections(e){for(let t of e)this.addCollection(t);}getCollection(e){return this.collections.get(e)}getCollections(){return Array.from(this.collections.values())}getCollectionSlugs(){return Array.from(this.collections.keys())}hasCollection(e){return this.collections.has(e)}removeCollection(e){if(this.initialized)throw new Error("Cannot remove collections after Registry has been initialized");return this.clearSchemaCache(e),this.collections.delete(e)}addGlobal(e){if(this.initialized)throw new Error("Cannot add globals after Registry has been initialized");this._addGlobalUnsafe(e);}addGlobalPostInit(e){this.globals.has(e.slug)&&this.globals.delete(e.slug),this._addGlobalUnsafe(e);}_addGlobalUnsafe(e){if(this.globals.has(e.slug)){console.warn(`[Registry] Duplicate global slug "${e.slug}" \u2014 skipping`);return}let t=z(e);if(t.length>0)throw new Error(`Invalid global config: ${t.join(", ")}`);let s={...e};for(let i of this.plugins){let o=i.extensions?.globals?.find(a=>a.slug===s.slug);o&&(s={...s,...o.config,fields:[...s.fields||[],...o.config.fields||[]]});}this.globals.set(s.slug,s),this.clearSchemaCache(`global:${s.slug}`);}addGlobals(e){for(let t of e)this.addGlobal(t);}getGlobal(e){return this.globals.get(e)}getGlobals(){return Array.from(this.globals.values())}getGlobalSlugs(){return Array.from(this.globals.keys())}hasGlobal(e){return this.globals.has(e)}removeGlobal(e){if(this.initialized)throw new Error("Cannot remove globals after Registry has been initialized");return this.clearSchemaCache(`global:${e}`),this.globals.delete(e)}addPlugin(e){if(this.initialized)throw new Error("Cannot add plugins after Registry has been initialized");this.plugins.push(e);}getPlugins(){return [...this.plugins]}getZodSchema(e){let t=this.schemaCache.get(e);if(t)return t;let s=this.collections.get(e);if(s){let o=we(s);return this.schemaCache.set(e,o),o}let i=this.globals.get(e);if(i){let o=ke(i);return this.schemaCache.set(`global:${e}`,o),o}throw new Error(`No collection or global found with slug "${e}"`)}getCreateZodSchema(e){let t=`${e}:create`,s=this.schemaCache.get(t);if(s)return s;let i=this.collections.get(e);if(i){let o=Ne(i);return this.schemaCache.set(t,o),o}throw new Error(`No collection found with slug "${e}"`)}getUpdateZodSchema(e){let t=`${e}:update`,s=this.schemaCache.get(t);if(s)return s;let i=this.collections.get(e);if(i){let a=De(i);return this.schemaCache.set(t,a),a}let o=this.globals.get(e);if(o){let a=Ie(o);return this.schemaCache.set(`global:${e}:update`,a),a}throw new Error(`No collection or global found with slug "${e}"`)}getWhereZodSchema(e){let t=`${e}:where`,s=this.schemaCache.get(t);if(s)return s;let i=this.collections.get(e);if(i){let o=Fe(i);return this.schemaCache.set(t,o),o}throw new Error(`No collection found with slug "${e}"`)}getFieldZodSchema(e){return A(e)}clearSchemaCache(e){this.schemaCache.delete(e),this.schemaCache.delete(`${e}:create`),this.schemaCache.delete(`${e}:update`),this.schemaCache.delete(`${e}:where`);}applyFieldDefaults(e){let t=[...e.fields];return t.some(s=>s.name==="id")||t.unshift({name:"id",type:"text",admin:{readOnly:true,hidden:true}}),e.tenantScoped&&!t.some(s=>s.name==="tenantId")&&t.push({name:"tenantId",type:"text",required:true,admin:{readOnly:true,hidden:true}}),e.timestamps&&!t.some(s=>s.name==="createdAt")&&(t.push({name:"createdAt",type:"date",admin:{readOnly:true,hidden:true}}),t.push({name:"updatedAt",type:"date",admin:{readOnly:true,hidden:true}})),e.versions?.drafts&&!t.some(s=>s.name==="status")&&t.push({name:"status",type:"select",options:[{value:"draft",label:"Draft"},{value:"published",label:"Published"}],admin:{readOnly:true,hidden:true}}),e.auth&&!t.some(s=>s.name==="password")&&t.push({name:"password",type:"password",required:true,admin:{hidden:true}}),t}getFields(e){let t=this.collections.get(e);if(t)return t.fields;let s=this.globals.get(e);if(s)return s.fields;throw new Error(`No collection or global found with slug "${e}"`)}getFieldMap(e){let t=this.getFields(e),s=new Map,i=o=>{for(let a of o){if(a.name&&s.set(a.name,a),"fields"in a&&a.fields&&i(a.fields),"tabs"in a)for(let r of a.tabs)i(r.fields);if("blocks"in a)for(let r of a.blocks)i(r.fields);}};return i(t),s}getVisibleFields(e){return this.getFields(e).filter(s=>!s.admin?.hidden)}validate(){let e=this.getCollections(),t=this.getGlobals();ve(e,t);}async init(e){this.validate();for(let t of this.plugins){t.init&&await t.init(e||this);let s=t.collections||[];for(let o of s)o.slug&&!this.hasCollection(o.slug)&&this.addCollection(o);let i=t.globals||[];for(let o of i)o.slug&&!this.hasGlobal(o.slug)&&this.addGlobal(o);}this.initialized=true;}isInitialized(){return this.initialized}getPaginationDefaults(e){let t=this.collections.get(e);return {defaultLimit:t?.admin?.pagination?.defaultLimit||10,limits:t?.admin?.pagination?.limits||[10,25,50,100]}}getDefaultSort(e){let s=this.collections.get(e)?.admin?.useAsTitle;return s||"createdAt"}getDefaultColumns(e){let t=this.collections.get(e);return t?.admin?.defaultColumns?t.admin.defaultColumns:this.getVisibleFields(e).slice(0,4).map(i=>i.name)}getAdminTitle(e){let t=this.collections.get(e);return t?.label||t?.admin?.description||e}getAdminLabel(e){let t=this.collections.get(e);return t?.singularLabel||t?.label||e}getAdminGroup(e){return this.collections.get(e)?.admin?.group}getStats(){let e=0;for(let t of this.collections.values())e+=t.fields.length;for(let t of this.globals.values())e+=t.fields.length;return {collections:this.collections.size,globals:this.globals.size,plugins:this.plugins.length,fields:e}}toJSON(){return {collections:this.getCollections(),globals:this.getGlobals()}}},F=null;function dt(){return F||(F=new k),F}function ut(){F=null;}function X(){return F=new k,F}var x=class{name;displayName;adminEntry;version;description;hooks={};collections=[];globals=[];fields=[];extensions={collections:[],globals:[]};adminComponents={};adminStyles=[];serverMiddleware;clientMiddleware;constructor(e){this.name=e;}async init(e){}async beforeInit(e){}async afterInit(e){}getCollections(){return this.collections}getGlobals(){return this.globals}getHooks(){return this.hooks}},_=class{plugins=new Map;hooks=new Map;register(e){if(this.plugins.has(e.name))throw new Error(`Plugin "${e.name}" is already registered`);this.plugins.set(e.name,e);let t=e.getHooks?.()||{};for(let[s,i]of Object.entries(t))if(Array.isArray(i))for(let o of i)this.registerHook(s,o);}unregister(e){let t=this.plugins.get(e);if(!t)return;let s=t.getHooks?.()||{};for(let[i,o]of Object.entries(s))if(Array.isArray(o))for(let a of o)this.unregisterHook(i,a);this.plugins.delete(e);}get(e){return this.plugins.get(e)}getAll(){return Array.from(this.plugins.values())}has(e){return this.plugins.has(e)}registerHook(e,t){this.hooks.has(e)||this.hooks.set(e,[]),this.hooks.get(e).push(t);}unregisterHook(e,t){let s=this.hooks.get(e);if(s){let i=s.indexOf(t);i>-1&&s.splice(i,1);}}async executeHook(e,t){let s=this.hooks.get(e)||[],i=t;for(let o of s)try{let a=await o({...t,data:i});a!==void 0&&(i=a);}catch(a){console.error(`[PluginManager] Error in hook "${e}":`,a);}return i}getAllCollections(){let e=[];for(let t of this.plugins.values()){let s=t.getCollections?.()||[];e.push(...s);}return e}getAllGlobals(){let e=[];for(let t of this.plugins.values()){let s=t.getGlobals?.()||[];e.push(...s);}return e}getAllFields(){let e=[];for(let t of this.plugins.values())e.push(...t.fields);return e}getAdminComponents(){let e={};for(let t of this.plugins.values())Object.assign(e,t.adminComponents);return e}getAdminStyles(){let e=[];for(let t of this.plugins.values())e.push(...t.adminStyles);return e}},J=class extends x{constructor(){super("seo"),this.displayName="Core SEO",this.description="Advanced SEO features including sitemaps, robots.txt, and structured data",this.adminEntry="@kyro-cms/admin/plugins/seo-admin",this.collections.push({slug:"seo-settings",label:"SEO Settings",fields:[{name:"sitemap",type:"checkbox",label:"Enable Sitemap",defaultValue:true},{name:"robotsTxt",type:"richtext",label:"robots.txt Content"},{name:"canonicalUrl",type:"text",variant:"url",label:"Canonical URL"},{name:"ogImage",type:"text",label:"Default OG Image URL"}]});}},Y=class extends x{constructor(){super("analytics"),this.displayName="Core Analytics",this.description="Built-in privacy-friendly analytics and dashboards",this.collections.push({slug:"analytics-events",label:"Analytics Events",fields:[{name:"name",type:"text",required:true},{name:"properties",type:"json",label:"Event Properties"},{name:"timestamp",type:"date",required:true},{name:"userId",type:"text",label:"User ID"},{name:"sessionId",type:"text",label:"Session ID"}]}),this.adminComponents.AnalyticsDashboard={};}},Q=class extends x{constructor(){super("comments"),this.description="Commenting system for products and posts",this.collections.push({slug:"comments",label:"Comments",fields:[{name:"content",type:"richtext",required:true},{name:"author",type:"text",required:true},{name:"email",type:"email"},{name:"approved",type:"checkbox",defaultValue:false},{name:"parent",type:"text",label:"Parent Comment ID"},{name:"resourceType",type:"text",required:true},{name:"resourceId",type:"text",required:true}]}),this.adminComponents.CommentModeration={};}},ee=class extends x{constructor(){super("reviews"),this.description="Product reviews and ratings",this.collections.push({slug:"reviews",label:"Reviews",fields:[{name:"rating",type:"number",required:true,min:1,max:5},{name:"title",type:"text"},{name:"content",type:"richtext",required:true},{name:"author",type:"relationship",relationTo:"customers"},{name:"product",type:"relationship",relationTo:"products",required:true},{name:"approved",type:"checkbox",defaultValue:false},{name:"verified",type:"checkbox",label:"Verified Purchase"},{name:"helpful",type:"number",label:"Helpful Count",defaultValue:0}]}),this.adminComponents.ReviewModeration={};}},te=class extends x{constructor(){super("wishlist"),this.description="Customer wishlists",this.collections.push({slug:"wishlists",label:"Wishlists",fields:[{name:"customer",type:"relationship",relationTo:"customers",required:true},{name:"name",type:"text",label:"Wishlist Name",defaultValue:"My Wishlist"},{name:"items",type:"blocks",label:"Items",blocks:[{slug:"wishlist-item",label:"Item",fields:[{name:"product",type:"relationship",relationTo:"products"},{name:"quantity",type:"number",defaultValue:1},{name:"addedAt",type:"date"},{name:"priority",type:"select",options:[{label:"Low",value:"low"},{label:"Medium",value:"medium"},{label:"High",value:"high"}]}]}]}]});}},$t={SEO:J,Analytics:Y,Comments:Q,Reviews:ee,Wishlist:te};var pt={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 ft(n,e){switch(n){case "r2":return e?.endpoint||`https://${e?.accountId||""}.r2.cloudflarestorage.com`;case "digitalocean":return e?.endpoint||`https://${e?.region||"nyc3"}.digitaloceanspaces.com`;case "backblaze":return e?.endpoint||"https://s3.backblazeb2.com";case "wasabi":return e?.endpoint||`https://s3.${e?.region||"us-east-1"}.wasabisys.com`;default:return e?.endpoint}}function Pe(n,e){return {provider:n,bucket:e?.bucket||"",region:e?.region||"us-east-1",accessKeyId:e?.accessKeyId||e?.clientEmail||e?.applicationKeyId||"",secretAccessKey:e?.secretAccessKey||e?.privateKey||e?.applicationKey||"",endpoint:ft(n,e),cdnUrl:e?.cdnUrl,prefix:e?.prefix,accountId:e?.accountId,publicDevUrl:e?.publicDevUrl}}function yt(n,e,t){let s=t[e.configKey]||{};return Pe(n,s)}function gt(n,e,t){let s=t?.[e.configKey]||t;return Pe(n,s)}var se=class extends x{constructor(){super("@kyro-cms/storage-s3"),this.version="1.0.0",this.description="S3-compatible storage (AWS R2 GCS DigitalOcean Backblaze Wasabi)";}async init(e){let t=e.registry?.storageProviders;if(!t)return;let s=this.name;for(let i of Object.values(pt))t.register({type:i.type,displayName:i.displayName,pluginName:s,configKey:i.configKey,configFields:i.configFields,extractConfig:o=>yt(i.type,i,o),extractRawConfig:o=>gt(i.type,i,o),factory:o=>a(o)});}},Oe=new se;var ne=class extends x{constructor(){super("@kyro-cms/storage-cloudinary"),this.version="1.0.0",this.description="Cloudinary image and video storage";}async init(e){let t=e.registry?.storageProviders;t&&t.register({type:"cloudinary",displayName:"Cloudinary",pluginName:this.name,configKey:"cloudinary",configFields:[{name:"cloudName",type:"text",label:"Cloud Name",required:true},{name:"apiKey",type:"text",label:"API Key",required:true},{name:"apiSecret",type:"password",label:"API Secret",required:true},{name:"folder",type:"text",label:"Folder",admin:{placeholder:"Optional folder path"}},{name:"uploadPreset",type:"text",label:"Upload Preset (optional)",admin:{placeholder:"Leave empty for signed uploads",description:"If not set, uploads will be signed with API Secret"}}],extractConfig:s=>({cloudName:s.cloudinary?.cloudName||"",apiKey:s.cloudinary?.apiKey||"",apiSecret:s.cloudinary?.apiSecret||"",folder:s.cloudinary?.folder,uploadPreset:s.cloudinary?.uploadPreset}),extractRawConfig:s=>{let i=s?.cloudinary||s;return {cloudName:i?.cloudName||"",apiKey:i?.apiKey||"",apiSecret:i?.apiSecret||"",folder:i?.folder,uploadPreset:i?.uploadPreset}},factory:s=>b(s)});}},$e=new ne;var ie=class extends x{constructor(){super("@kyro-cms/storage-ftp"),this.version="1.0.0",this.description="FTP/SFTP storage provider";}async init(e){let t=e.registry?.storageProviders;t&&t.register({type:"ftp",displayName:"FTP",pluginName:this.name,configKey:"ftp",configFields:[{name:"host",type:"text",label:"Host",required:true,admin:{placeholder:"ftp.example.com"}},{name:"port",type:"number",label:"Port",defaultValue:21,admin:{placeholder:"21 for FTP"}},{name:"user",type:"text",label:"Username",required:true},{name:"password",type:"password",label:"Password",required:true},{name:"secure",type:"checkbox",label:"Use TLS/SSL",defaultValue:false,admin:{description:"Enable TLS/SSL for secure connections (FTP only)"}},{name:"baseUrl",type:"text",label:"Base URL",required:true,admin:{placeholder:"https://files.example.com"}},{name:"prefix",type:"text",label:"Path Prefix",admin:{placeholder:"uploads"}}],extractConfig:s=>({host:s.ftp?.host||"",port:s.ftp?.port||21,user:s.ftp?.user||"",password:s.ftp?.password||"",secure:s.ftp?.secure||false,baseUrl:s.ftp?.baseUrl||"",prefix:s.ftp?.prefix,type:"ftp"}),extractRawConfig:s=>{let i=s?.ftp||s;return {host:i?.host||"",port:i?.port||21,user:i?.user||"",password:i?.password||"",secure:i?.secure||false,baseUrl:i?.baseUrl||"",prefix:i?.prefix,type:"ftp"}},factory:s=>c(s)});}},Le=new ie;var mt=[Oe,$e,Le];function N(n,e,t){let s=e.split(".");if(s.length===0)return false;let i=s[0],o=s.slice(1).join(".");for(let a of n)if(a.name===i)if(o){if(a.fields&&Array.isArray(a.fields))return N(a.fields,o,t);if(a.type==="tabs"&&a.tabs&&Array.isArray(a.tabs)){for(let r of a.tabs)if(r.fields&&Array.isArray(r.fields)&&N(r.fields,o,t))return true;return false}if(a.type==="blocks"&&a.blocks&&Array.isArray(a.blocks)){let r=o.split(".")[0],c=o.split(".").slice(1).join(".");if(!c)return false;for(let d of a.blocks)if(d.slug===r&&d.fields&&Array.isArray(d.fields))return N(d.fields,c,t);return false}return a.type==="array"&&a.fields&&Array.isArray(a.fields)?N(a.fields,o,t):false}else return Object.assign(a,t),true;for(let a of n)if(!a.name||a.type==="tabs"||a.type==="row"||a.type==="collapsible"){if(a.fields&&Array.isArray(a.fields)&&N(a.fields,e,t))return true;if(a.type==="tabs"&&a.tabs&&Array.isArray(a.tabs)){for(let c of a.tabs)if(c.fields&&Array.isArray(c.fields)&&N(c.fields,e,t))return true}}return o?false:(n.push({name:i,...t}),true)}function bt(n,e){if(e)for(let t of n){let s=e[t.slug];if(s){let{fields:i,...o}=s;if(t.admin={...t.admin,...o},i&&t.fields&&Array.isArray(t.fields))for(let[a,r]of Object.entries(i))N(t.fields,a,r);}}}var oe=class{registry;db;pubsub;webhookService;settings;pluginManager;wsServer;config;constructor(e){this.config=e,this.registry=X(),this.db=e.adapter,this.pubsub=new b$1(this.registry),this.webhookService=o(this.db),this.pluginManager=new _;for(let t of mt)this.pluginManager.register(t),this.registry.addPlugin(t);if(e.plugins)for(let t of e.plugins)this.pluginManager.register(t),this.registry.addPlugin(t);e.collections&&e.admin?.collectionOverrides&&bt(e.collections,e.admin.collectionOverrides),e.collections&&this.registry.addCollections(e.collections),e.globals&&this.registry.addGlobals(e.globals);}async init(){await this.pluginManager.executeHook("beforeInit",{kyro:this}),await this.registry.init(this),await this.pluginManager.executeHook("afterInit",{kyro:this}),this.registry.addGlobalPostInit(a$2);let e={slug:"plugin-settings",admin:{hidden:true},fields:[{name:"states",type:"json"}]};if(this.registry.addGlobalPostInit(e),!this.db)throw new Error("Database adapter is null \u2014 failed to load at startup. Check the server console for the exact error.");let t={slug:d,fields:[{name:"userId",type:"text",required:true},{name:"name",type:"text",required:true},{name:"key",type:"text",required:true},{name:"keyPrefix",type:"text",required:true},{name:"permissions",type:"json"},{name:"lastUsedAt",type:"date"},{name:"expiresAt",type:"date"}]},s={slug:f$1,fields:[{name:"name",type:"text",required:true},{name:"url",type:"text",required:true},{name:"events",type:"json",required:true},{name:"collections",type:"json"},{name:"status",type:"text",required:true},{name:"secret",type:"text"},{name:"headers",type:"json"},{name:"action",type:"text"},{name:"config",type:"json"},{name:"lastTriggered",type:"date"},{name:"lastError",type:"text"}]},i={slug:g$1,fields:[{name:"webhookId",type:"text",required:true},{name:"event",type:"text",required:true},{name:"payload",type:"json",required:true},{name:"attempt",type:"number",required:true},{name:"status",type:"text",required:true},{name:"responseStatus",type:"number"},{name:"responseBody",type:"text"},{name:"error",type:"text"},{name:"duration",type:"number"},{name:"deliveredAt",type:"date"},{name:"nextRetryAt",type:"date"}]},o=this.registry.getGlobals();if(this.db instanceof c$1&&this.db.dialect==="postgres"){let a=this.db,r=d.replace(/-/g,"_");a.schema[r]||(a.schema[r]=g);}await this.db.init([...this.registry.getCollections(),t,s,i],o),await this.loadPluginState(),this.pubsub.autoRegisterHooks();}async loadSettings(){if(this.settings)return this.settings;try{let e=await this.db.findOne({collection:"_globals_access-settings",where:{},draft:!0});e&&(this.settings={access:e});}catch{}return this.settings||{}}async loadPluginState(){let e=this.registry.storageProviders,t=e.getAllPluginNames(),s={};try{let i=await this.db.findOne({collection:"_globals_plugin-settings",where:{},draft:!0});i&&i.states&&(s=i.states);}catch{}for(let i of t)s[i]!==void 0&&e.setPluginEnabled(i,s[i]);}getREST(e){let t$1=typeof this.config.auth=="object"?this.config.auth:null,s=t$1?.secret,i=t$1?.checkSession!==false;return t({registry:this.registry,db:this.db,authSecret:s,authAdapter:this.config.authAdapter,checkSession:i,...e,cors:this.config.cors,webhookService:this.webhookService,settings:this.settings})}getGraphQL(e$1){let t=c$2({registry:this.registry,db:this.db,settings:this.settings});return {fetch:createYoga({schema:t,context:async({request:i})=>{let o=f$2(i),a,r;if(o&&this.db){let d=await e(o,this.db);d.user&&(a=d.user,r=g$2(d));}let c=e$1?.tenantId;return {db:this.db,registry:this.registry,user:a,req:i,tenantId:c,apiKey:r,relationLoader:new a$3({db:this.db,tenantId:c,user:a})}},graphiql:this.config.graphQL?.disablePlayground!==true,plugins:[]}).fetch,schema:t}}getTRPC(e){return {fetch:async(t,s)=>{let o=new URL(t.url).pathname.replace(/^\/api\/trpc\//,""),[a,...r]=o.split("."),c=r.join(".");if(c=c.replace(/\.(query|mutate|subscribe)$/,""),!a||!c)return new Response(JSON.stringify({error:{message:"Invalid tRPC path",code:-32600,data:{code:"BAD_REQUEST",httpStatus:400}}}),{status:400,headers:{"Content-Type":"application/json"}});let d=await a$4({db:this.db,registry:this.registry,req:t,user:e?.user,tenantId:e?.tenantId,settings:this.settings}),p=i(d)[a];if(!p)return new Response(JSON.stringify({error:{message:`Collection '${a}' not found`,code:-32601,data:{code:"NOT_FOUND",httpStatus:404}}}),{status:404,headers:{"Content-Type":"application/json"}});let b=p[c];if(typeof b!="function")return new Response(JSON.stringify({error:{message:`Procedure '${c}' not found`,code:-32601,data:{code:"NOT_FOUND",httpStatus:404}}}),{status:404,headers:{"Content-Type":"application/json"}});try{let y={};if(t.method==="POST"||t.method==="PATCH")y=await t.json().catch(()=>({}));else {let C=new URL(t.url).searchParams.get("input");if(C)try{y=JSON.parse(decodeURIComponent(C));}catch{}}let g=y?.["0"]??y,f=await b({...g,collection:a});return new Response(JSON.stringify({result:{data:f}}),{status:200,headers:{"Content-Type":"application/json"}})}catch(y){let g=y.message||"Internal error",f=g.includes("not found")?404:g.includes("denied")||g.includes("authentication required")?403:g.includes("conflict")?409:500,C=f===404?-32601:f===403?-32001:f===409?-32002:-32603;return new Response(JSON.stringify({error:{message:g,code:C,data:{code:"INTERNAL_SERVER_ERROR",httpStatus:f}}}),{status:f,headers:{"Content-Type":"application/json"}})}},router:null}}getWS(){return this.wsServer}async startWebSocket(e$1){let t=this.settings?.access?.apiAccess;if(t?.wsEnabled===false)return null;let s=async o=>{let a=await e(o,this.db);if(!a.valid)throw new Error(a.error||"Invalid API key");if(!a.user)throw new Error("API key has no associated user");return a.user},i=e$1?.port||8080;if(globalThis.__KYRO_WS_SERVER__)try{await globalThis.__KYRO_WS_SERVER__.close();}catch{}return this.wsServer=d$1({pubsub:this.pubsub,port:i,requireAuth:e$1?.requireAuth??t?.requireAuth,verifyToken:e$1?.verifyToken||s}),globalThis.__KYRO_WS_SERVER__=this.wsServer,this.wsServer}async shutdown(){await this.pluginManager.executeHook("beforeServerStop",{kyro:this}),this.wsServer&&await this.wsServer.close(),await this.db.disconnect(),await this.pluginManager.executeHook("afterServerStop",{kyro:this});}};function ys(n){return new oe(n)}var Ct=createRequire(import.meta.url),At="node:sqlite",{DatabaseSync:St}=Ct(At);function E(n){let e=[];for(let t of n)if(t.type==="tabs"&&"tabs"in t)for(let s of t.tabs)e.push(...E(s.fields));else t.type==="row"&&"fields"in t?e.push(...E(t.fields)):t.type==="collapsible"&&"fields"in t?e.push(...E(t.fields)):e.push(t);return e}function vt(n,e){let t=e,s=n[t.name];if(t.type==="json"||t.type==="richtext"||t.type==="array"||t.type==="group"||t.type==="blocks"||t.type==="list"||t.type==="relationship-block")try{s=s?JSON.parse(s):null;}catch{s=null;}if(t.type==="checkbox"&&(s=!!s),t.type==="date"&&s)try{let i=new Date(s);isNaN(i.getTime())?s=null:s=i.toISOString();}catch{s=null;}if((t.type==="upload"||t.type==="image")&&s)try{let i=JSON.parse(s);Array.isArray(i)?s=i.map(o=>typeof o=="object"&&o!==null?o:{id:o}):s=typeof i=="object"?i:{id:i};}catch{s={id:s};}if(t.type==="relationship"&&s)try{let i=JSON.parse(s);Array.isArray(i),s=i;}catch{s={relationTo:Array.isArray(t.relationTo)?t.relationTo[0]:t.relationTo,value:s};}if(t.type==="list"&&s)try{let i=JSON.parse(s);s=Array.isArray(i)?i:[];}catch{s=[];}if(t.type==="relationship-block"&&s)try{let i=JSON.parse(s);s=Array.isArray(i)?i:[];}catch{s=[];}return s}function _e(n,e){return Array.isArray(n)?n.map(t=>{if(!t||typeof t!="object")return t;let s=t.data?{...t.data}:void 0;if(!s)return t;let i=e.find(o=>o.slug===t.type||o.slug===t.slug);if(!i||!Array.isArray(i.fields))return t;for(let o of i.fields){if(o.name&&(o.type==="upload"||o.type==="image")&&s[o.name]){let a=s[o.name];Array.isArray(a)?s[o.name]=a.map(r=>typeof r=="string"?{id:r}:r):typeof a=="string"&&(s[o.name]={id:a});}if(o.type==="blocks"&&o.name&&s[o.name]){let a=o.blocks||[];s[o.name]=_e(s[o.name],a);}}return {...t,data:s}}):n}function ae(n,e){try{return n.prepare(`PRAGMA table_info(${e})`).all().map(s=>s.name)}catch{return []}}var re=class extends a$5{db;path;migrations=new Map;versionsTableName="kyro_versions";constructor(e){super(),this.path=e.path,e.db?this.db=e.db:this.db=null;}async connect(){if(this.db||(this.db=new St(this.path||":memory:")),this.db&&typeof this.db.prepare=="function"&&!this.db.prepare.__wrapped){let e=this.db.prepare.bind(this.db),t=s=>{let i=e(s),o=a=>typeof a=="boolean"?a?1:0:a===void 0?null:a;return new Proxy(i,{get(a,r,c){if(r==="all")return (...u)=>a.all(...u.map(o));if(r==="get")return (...u)=>a.get(...u.map(o));if(r==="run")return (...u)=>a.run(...u.map(o));let d=Reflect.get(a,r,c);return typeof d=="function"?d.bind(a):d}})};t.__wrapped=true,this.db.prepare=t;}this.db.exec("PRAGMA journal_mode = WAL"),this.db.exec("PRAGMA foreign_keys = ON"),this.connected=true;}async disconnect(){this.db&&this.db.close(),this.connected=false;}ensureTable(e,t){let s=t||this.getTableNameFor(e.slug),i=["id TEXT PRIMARY KEY"];for(let r of E(e.fields)){if(!r.name||r.name==="id")continue;let c=this.fieldToSQL(r);c&&i.push(c);}let o=E(e.fields);o.some(r=>r.name==="createdAt")||i.push(`${this.col("createdAt")} TEXT DEFAULT (datetime('now'))`),o.some(r=>r.name==="updatedAt")||i.push(`${this.col("updatedAt")} TEXT DEFAULT (datetime('now'))`),o.some(r=>r.name==="status")||i.push("status TEXT DEFAULT 'draft'"),o.some(r=>r.name==="hasDraft")||i.push("hasDraft INTEGER DEFAULT 0"),e.tenantScoped&&i.push("tenant_id TEXT NOT NULL");let a=ae(this.db,s);if(a.length===0){let r=`CREATE TABLE IF NOT EXISTS ${s} (${i.join(", ")})`;this.db.exec(r),this.db.exec(`CREATE INDEX IF NOT EXISTS idx_${s}_status ON ${s}(status)`);for(let c of E(e.fields))c.name&&c.indexed&&this.db.exec(`CREATE INDEX IF NOT EXISTS idx_${s}_${c.name} ON ${s}(${this.col(c.name)})`),c.name&&c.unique&&this.db.exec(`CREATE UNIQUE INDEX IF NOT EXISTS idx_${s}_${c.name}_unique ON ${s}(${this.col(c.name)})`);}else {let r=new Set(a);for(let c of i){let d=c.split(" ")[0].replace(/^"/,"").replace(/"$/,"");if(!r.has(d)&&d!=="id")try{d==="status"?this.db.exec(`ALTER TABLE ${s} ADD COLUMN ${this.col(d)} TEXT DEFAULT 'published'`):d==="hasDraft"?this.db.exec(`ALTER TABLE ${s} ADD COLUMN ${this.col(d)} INTEGER DEFAULT 0`):this.db.exec(`ALTER TABLE ${s} ADD COLUMN ${this.col(d)} TEXT`);}catch{}}}this.migrations.set(s,true);}ensureVersionsTable(){this.db.exec(`
|
|
4
|
+
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 "icon":case "code":case "markdown":case "url":return this.col(e.name)+" TEXT";case "number":return this.col(e.name)+" REAL";case "checkbox":return this.col(e.name)+" INTEGER DEFAULT 0";case "date":return this.col(e.name)+" TEXT";case "select":case "radio":return this.col(e.name)+" TEXT";case "relationship":case "upload":return this.col(e.name)+" TEXT";case "json":case "richtext":case "array":case "group":case "blocks":return this.col(e.name)+" TEXT";default:return null}}parseGlobalsSlug(e){if(e.startsWith("_globals_")){let t=e.replace("_globals_","");return {isGlobal:true,globalSlug:t,tableName:`global_${t.replace(/-/g,"_")}`}}return {isGlobal:false,globalSlug:"",tableName:this.getTableNameFor(e)}}async find(e){let{collection:t,where:s={},sort:i,limit:o=10,page:a=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 b=`SELECT * FROM ${d.tableName}`,y=[],g=[],f={...s};this.tenantContext&&u.tenantScoped&&(f=c$3({where:f},t,this.tenantContext,b$2).where||{});let C=u.fields.find(m=>m.name==="status"),h=C?.type==="select"&&Array.isArray(C.options)&&C.options.some(m=>m.value==="published");!c&&h&&(g.push("status = ?"),y.push("published")),r&&u.tenantScoped&&(g.push("tenant_id = ?"),y.push(r));for(let[m,S]of Object.entries(f))m==="AND"||m==="OR"||(typeof S=="object"&&S!==null?(S.equals!==void 0&&(g.push(`${this.col(m)} = ?`),y.push(S.equals)),S.in!==void 0&&(g.push(`${this.col(m)} IN (${S.in.map(()=>"?").join(", ")})`),y.push(...S.in)),S.not_equals!==void 0&&(g.push(`${this.col(m)} != ?`),y.push(S.not_equals))):(g.push(`${this.col(m)} = ?`),y.push(S)));g.length>0&&(b+=` WHERE ${g.join(" AND ")}`);let je=this.col(i?.replace("-","")||"createdAt"),qe=i?.startsWith("-")?"DESC":"ASC";b+=` ORDER BY ${je} ${qe}`;let Ze=b.replace("SELECT *","SELECT COUNT(*) as count"),I=this.db.prepare(Ze).get(...y)?.count||0;b+=" LIMIT ? OFFSET ?",y.push(o,(a-1)*o);let R=this.db.prepare(b).all(...y).map(m=>this.rowToDoc(m,u));return this.tenantContext&&!this.tenantContext.isSuperAdmin&&(R=R.filter(m=>d$2(m,t,this.tenantContext,b$2))),c&&(R=await Promise.all(R.map(async m=>{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,m.id);if(S){let Ge=S.data?JSON.parse(S.data):{};return a$6({...m,...Ge,status:m.status})}return m}))),R=R.map(m=>a$6(m)),{docs:R,totalDocs:I,limit:o,totalPages:Math.ceil(I/o),page:a,pagingCounter:(a-1)*o+1,hasPrevPage:a>1,hasNextPage:a<Math.ceil(I/o),prevPage:a>1?a-1:null,nextPage:a<Math.ceil(I/o)?a+1:null}}async findByID(e){let{collection:t,id:s,tenantId:i,draft:o=false}=e,a=this.parseGlobalsSlug(t),r=a.isGlobal?this.globals.get(a.globalSlug):this.getCollection(t);this.ensureTable(r,a.tableName);let d=`SELECT * FROM ${a.tableName} WHERE id = ?`,u=[s];if(this.tenantContext&&r.tenantScoped){let f={id:s,tenant_id:this.tenantContext.tenantId};if(!d$2(f,t,this.tenantContext,b$2))return null}let p=r.fields.find(f=>f.name==="status"),b=p?.type==="select"&&Array.isArray(p.options)&&p.options.some(f=>f.value==="published");!o&&b&&(d+=" AND status = ?",u.push("published")),i&&r.tenantScoped&&(d+=" AND tenant_id = ?",u.push(i));let y=this.db.prepare(d).get(...u);if(!y)return null;let g=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,g.id);if(f){let C=f.data?JSON.parse(f.data):{};g={...g,...C,status:g.status};}}return a$6(g)}async create(e){let{collection:t,data:s,tenantId:i}=e,o=this.parseGlobalsSlug(t),a=o.isGlobal?this.globals.get(o.globalSlug):this.getCollection(t);this.ensureTable(a,o.tableName);let r=o.tableName,c=o.isGlobal?o.globalSlug:s.id||this.generateId(),d=this.prepareData(s,a);d.id=c,d.created_at=new Date().toISOString(),d.updated_at=new Date().toISOString(),i&&a.tenantScoped&&(d.tenant_id=i);let u=Object.keys(d),p=ae(this.db,r),b={};for(let h of u)p.includes(h)&&(b[h]=d[h]);let y=Object.keys(b),g=y.map(h=>this.col(h)),f=y.map(()=>"?").join(", "),C=Object.values(b).map(h=>h!==null&&typeof h=="object"?JSON.stringify(h):h);return this.db.prepare(`INSERT OR REPLACE INTO ${r} (${g.join(", ")}) VALUES (${f})`).run(...C),this.ensureVersionsTable(),this.findByID({collection:t,id:c,tenantId:i,draft:true})}async update(e){let{collection:t,id:s,data:i,tenantId:o}=e,a=this.parseGlobalsSlug(t),r=a.isGlobal?this.globals.get(a.globalSlug):this.getCollection(t);this.ensureTable(r,a.tableName);let c=a.tableName,d=this.prepareData(i,r);d.updated_at=new Date().toISOString();let u=ae(this.db,c),p={};for(let h of Object.keys(d))u.includes(h)&&(p[h]=d[h]);let y=Object.keys(p).map(h=>`${this.col(h)} = ?`).join(", "),g=Object.values(p).map(h=>h!==null&&typeof h=="object"?JSON.stringify(h):h),f=`UPDATE ${c} SET ${y} WHERE id = ?`,C=[...g,s];return o&&r.tenantScoped&&(f+=" AND tenant_id = ?",C.push(o)),this.db.prepare(f).run(...C),this.ensureVersionsTable(),this.findByID({collection:t,id:s,tenantId:o,draft:true})}async delete(e){let{collection:t,id:s,tenantId:i}=e,o=this.parseGlobalsSlug(t),a=o.isGlobal?this.globals.get(o.globalSlug):this.getCollection(t);this.ensureTable(a,o.tableName),this.ensureVersionsTable();let r=await this.findByID({collection:t,id:s,tenantId:i,draft:true});if(!r)throw new Error(`Document not found: ${t}/${s}`);let d=`DELETE FROM ${o.tableName} WHERE id = ?`,u=[s];return i&&a.tenantScoped&&(d+=" AND tenant_id = ?",u.push(i)),this.db.prepare(d).run(...u),r}async count(e){let{collection:t,tenantId:s}=e,i=this.parseGlobalsSlug(t),o=i.isGlobal?this.globals.get(i.globalSlug):this.getCollection(t);this.ensureTable(o,i.tableName);let r=`SELECT COUNT(*) as count FROM ${i.tableName}`,c=[];return s&&o.tenantScoped&&(r+=" WHERE tenant_id = ?",c.push(s)),this.db.prepare(r).get(...c)?.count||0}async findOne(e){let t=this.parseGlobalsSlug(e.collection);if(t.isGlobal){let i=this.globals.get(t.globalSlug);if(!i)throw new Error(`Global "${t.globalSlug}" not found in adapter`);this.ensureTable(i,t.tableName);let o=`SELECT * FROM ${t.tableName}`,a=[],r=[],c=i.fields.find(p=>p.name==="status"),d=c?.type==="select"&&Array.isArray(c.options)&&c.options.some(p=>p.value==="published");!e.draft&&i.versions&&d&&a.push("status = 'published'"),a.length>0&&(o+=` WHERE ${a.join(" AND ")}`),o+=" LIMIT 1";let u=this.db.prepare(o).get(...r);if(u){let p=this.rowToDoc(u,i);if(e.draft){let b=this.db.prepare(`SELECT * FROM ${this.versionsTableName} WHERE collection_slug = ? AND document_id = ? AND tenant_id IS NULL ORDER BY version DESC LIMIT 1`).get(e.collection,t.globalSlug);if(b){let y=b.data?JSON.parse(b.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:s,tenantId:i,limit:o=20,page:a=1}=e,r=["collection_slug = ?","document_id = ?","autosave = 0"],c=[t,s];i?(r.push("tenant_id = ?"),c.push(i)):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,b=(a-1)*o;return {docs:this.db.prepare(`SELECT * FROM ${this.versionsTableName} ${d} ORDER BY version DESC LIMIT ? OFFSET ?`).all(...c,o,b).map(f=>this.rowToVersion(f)),totalDocs:p,limit:o,totalPages:Math.ceil(p/o),page:a,pagingCounter:(a-1)*o+1,hasPrevPage:a>1,hasNextPage:a<Math.ceil(p/o),prevPage:a>1?a-1:null,nextPage:a<Math.ceil(p/o)?a+1:null}}async findVersionByID(e){this.ensureVersionsTable();let t=this.db.prepare(`SELECT * FROM ${this.versionsTableName} WHERE id = ? AND collection_slug = ? LIMIT 1`).get(e.versionId,e.collection);return t?this.rowToVersion(t):null}async createVersion(e){this.ensureVersionsTable();let t=new Date().toISOString();if(e.autosave){let r=`SELECT * FROM ${this.versionsTableName} WHERE collection_slug = ? AND document_id = ? AND autosave = 1`,c=[e.collection,e.documentId];e.tenantId?(r+=" AND tenant_id = ?",c.push(e.tenantId)):r+=" AND tenant_id IS NULL",r+=" LIMIT 1";let d=this.db.prepare(r).get(...c);if(d){this.db.prepare(`UPDATE ${this.versionsTableName} SET data = ?, status = ?, updated_at = ? WHERE id = ?`).run(JSON.stringify(e.data),e.status,t,d.id);let u=await this.findVersionByID({collection:e.collection,versionId:d.id});if(u)return u}}let s=this.generateId(),o=(this.db.prepare(`SELECT version FROM ${this.versionsTableName} WHERE collection_slug = ? AND document_id = ? AND autosave = 0 ORDER BY version DESC LIMIT 1`).get(e.collection,e.documentId)?.version??0)+1;if(this.db.prepare(`INSERT INTO ${this.versionsTableName} (
|
|
20
|
+
id, collection_slug, document_id, tenant_id, version, status, autosave, data, created_by, change_description, published_at, created_at, updated_at
|
|
21
|
+
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(s,e.collection,e.documentId,e.tenantId??null,o,e.status,e.autosave?1:0,JSON.stringify(e.data),e.createdBy??null,e.changeDescription??null,e.status==="published"?t:null,t,t),!e.autosave){let c=this.collections.get(e.collection)?.versions?.maxPerDoc;c&&c>0&&await this.deleteVersions({collection:e.collection,documentId:e.documentId,keepLatest:c,tenantId:e.tenantId});}return await this.findVersionByID({collection:e.collection,versionId:s})}async updateLatestVersion(e){return this.createVersion({...e,autosave:true})}async deleteVersions(e){this.ensureVersionsTable();let{collection:t,documentId:s,keepLatest:i,tenantId:o}=e;if(i&&i>0){let a=this.db.prepare(`SELECT id, status, autosave FROM ${this.versionsTableName} WHERE collection_slug = ? AND document_id = ? ORDER BY version DESC`).all(t,s),r=0,c=[];for(let d of a)d.status==="published"||d.autosave===1||(r++,r>i&&c.push(d.id));for(let d of c)this.db.prepare(`DELETE FROM ${this.versionsTableName} WHERE id = ?`).run(d);}else {let a=`DELETE FROM ${this.versionsTableName} WHERE collection_slug = ? AND document_id = ?`,r=[t,s];o&&(a+=" AND tenant_id = ?",r.push(o)),this.db.prepare(a).run(...r);}}rowToVersion(e){return {id:String(e.id),collection:e.collection_slug,documentId:e.document_id,version:e.version,status:e.status,data:e.data?JSON.parse(e.data):{},createdBy:e.created_by??void 0,changeDescription:e.change_description??void 0,publishedAt:e.published_at??null,createdAt:e.created_at,updatedAt:e.updated_at}}prepareData(e,t){let s={},i=E(t.fields),o=(a,r)=>{let c=a;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(a.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:a.relationTo,value:u.id||u}):String(u));return JSON.stringify(d)}return typeof r=="string"?r:typeof r=="object"?JSON.stringify({relationTo:a.relationTo,value:r.id||r}):String(r)}return r};for(let a of i){if(!a.name||a.name==="id"||t.fields.some(d=>d.type==="tabs"&&d.name&&"tabs"in d&&d.tabs.some(u=>u.fields.some(p=>p.name===a.name))))continue;let c=e[a.name];c!==void 0&&(s[a.name]=o(a,c));}for(let a of t.fields)if(a.type==="tabs"&&"tabs"in a&&a.name){let r=e[a.name];if(r&&typeof r=="object"){for(let c of a.tabs)for(let d of c.fields)if(d.name&&d.name!=="id"){let u=r[d.name];u!==void 0&&(s[d.name]=o(d,u));}}}return s}rowToDoc(e,t){let s={id:e.id};for(let i of E(t.fields)){if(!i.name||i.name==="id")continue;let o=i,a=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{a=a?JSON.parse(a):null;}catch{a=null;}if(o.type==="blocks"&&a&&Array.isArray(a)){let r=o.blocks||[];a=_e(a,r);}if(i.type==="checkbox"&&(a=!!a),i.type==="date"&&a)try{let r=new Date(a);isNaN(r.getTime())?(console.warn(`[LocalAdapter] Invalid date value for field "${i.name}":`,a),a=null):a=r.toISOString();}catch{a=null;}if((i.type==="upload"||i.type==="image")&&a)try{let r=JSON.parse(a);Array.isArray(r)?a=r.map(c=>typeof c=="object"&&c!==null?c:{id:c}):a=typeof r=="object"?r:{id:r};}catch{a={id:a};}if(i.type==="relationship"&&a)try{let r=JSON.parse(a);Array.isArray(r),a=r;}catch{a={relationTo:Array.isArray(i.relationTo)?i.relationTo[0]:i.relationTo,value:a};}s[i.name]=a;}for(let i of t.fields)if(!(!i.name||i.name==="id"||i.name==="row"||i.name==="collapsible")&&i.type==="tabs"&&"tabs"in i){let o={};for(let a of i.tabs)for(let r of a.fields)r.name&&r.name!=="id"&&(o[r.name]=vt(e,r));s[i.name]=o;}if(t.timestamps){let i=e.createdAt||e.created_at,o=e.updatedAt||e.updated_at;if(i)try{let a=new Date(i);isNaN(a.getTime())||(s.createdAt=a.toISOString());}catch{}if(o)try{let a=new Date(o);isNaN(a.getTime())||(s.updatedAt=a.toISOString());}catch{}}t.tenantScoped&&(s.tenantId=e.tenant_id),s.status=e.status??"published",s.hasDraft=e.hasDraft?!!e.hasDraft:false;for(let i of Object.keys(s))/^\d+$/.test(i)&&delete s[i];return s}generateId(){let e=Date.now().toString(16).padStart(12,"0"),t=randomBytes(6).toString("hex");return e+t}getMediaById(e){try{let t=this.getTableNameFor("media"),s=this.db.prepare(`SELECT id, url, thumbnail_url FROM ${t} WHERE id = ?`).get(e);if(s)return {id:s.id,url:s.url,thumbnailUrl:s.thumbnail_url||s.url}}catch{}return null}getTableNameFor(e){return e.replace(/-/g,"_")}async migrate(){for(let e of this.collections.values())this.ensureTable(e);}async rollback(){}async transaction(e){return new Promise((t,s)=>{let i=this.db.transaction(async()=>e({db:this.db}));try{let o=i();t(o);}catch(o){s(o);}})}getDatabase(){return this.db}exec(e){this.db.exec(e);}prepare(e){return this.db.prepare(e)}};function Fs(n){return new re(n||{})}export{re as A,Fs as B,H as a,W as b,z as c,w as d,ve as e,A as f,we as g,Ne as h,De as i,Fe as j,ke as k,k as l,dt as m,ut as n,X as o,x as p,_ as q,J as r,Y as s,Q as t,ee as u,te as v,$t as w,bt as x,oe as y,ys as z};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
'use strict';var chunkNY47CFVP_cjs=require('./chunk-NY47CFVP.cjs'),chunkG7SSHELM_cjs=require('./chunk-G7SSHELM.cjs'),chunkQ3Q7BJVQ_cjs=require('./chunk-Q3Q7BJVQ.cjs'),crypto=require('crypto');var x={COLLECTION_CREATE:"collection.create",COLLECTION_UPDATE:"collection.update",COLLECTION_DELETE:"collection.delete",MEDIA_UPLOAD:"media.upload",MEDIA_DELETE:"media.delete",AUTH_LOGIN:"auth.login",AUTH_REGISTER:"auth.register",AUTH_LOGOUT:"auth.logout",ORDER_CREATED:"order.created",ORDER_PAID:"order.paid",ORDER_SHIPPED:"order.shipped",ORDER_DELIVERED:"order.delivered"},K=Object.values(x);var h="_webhooks",k="_webhook_deliveries";async function I(r,o,n,e={}){let t=e.timeout||3e4,a=Date.now(),l=new AbortController,i=setTimeout(()=>l.abort(),t);try{let s=await fetch(r,{method:"POST",headers:o,body:n,signal:l.signal});clearTimeout(i);let c=Date.now()-a,u;try{u=(await s.text()).slice(0,1e3);}catch{}let d={success:s.ok,status:s.status,statusText:s.statusText,body:u,duration:c};return d.success&&e.onSuccess?e.onSuccess(d):!d.success&&e.onFailure&&e.onFailure(`HTTP ${s.status}: ${s.statusText}`),d}catch(s){clearTimeout(i);let c=Date.now()-a,u=s.name==="AbortError"?`Request timed out after ${t}ms`:s.message||"Unknown error";return e.onFailure&&e.onFailure(u),{success:false,status:0,duration:c,error:u}}}async function H(r,o,n={}){let e=JSON.stringify(o),t={"Content-Type":"application/json","User-Agent":"Kyro-CMS-Webhook/1.0","X-Webhook-Event":o.event,"X-Webhook-Delivery":o.id,"X-Webhook-Timestamp":o.timestamp,...r.headers||{}};return r.secret&&(t["X-Webhook-Signature"]=O(e,r.secret)),I(r.url,t,e,n)}async function B(r,o,n={}){let e=r.config||{},t=process.env.GITHUB_TOKEN;if(!t)return {success:false,status:0,duration:0,error:"GITHUB_TOKEN environment variable is not set"};if(!e.githubOwner||!e.githubRepo)return {success:false,status:0,duration:0,error:"GitHub owner and repo are required"};let a=e.githubBranch||"main",l=Date.now(),i=async(s,c,u)=>{let d=await fetch(s,{method:c,headers:{"Content-Type":"application/json",Accept:"application/vnd.github+json",Authorization:`Bearer ${t}`,"X-GitHub-Api-Version":"2022-11-28","User-Agent":"Kyro-CMS-Webhook/1.0"},body:u?JSON.stringify(u):void 0});if(!d.ok){let y=await d.text();throw new Error(`GitHub API HTTP ${d.status}: ${y}`)}return d.json()};try{let s=`https://api.github.com/repos/${e.githubOwner}/${e.githubRepo}/git/refs/heads/${a}`,u=(await i(s,"GET")).object.sha,d=`https://api.github.com/repos/${e.githubOwner}/${e.githubRepo}/git/commits/${u}`,g=(await i(d,"GET")).tree.sha,f=`https://api.github.com/repos/${e.githubOwner}/${e.githubRepo}/git/commits`,p=(await i(f,"POST",{message:`Content updated via Kyro CMS (${o.event})`,tree:g,parents:[u]})).sha;return await i(s,"PATCH",{sha:p,force:!1}),{success:!0,status:201,duration:Date.now()-l,body:`Successfully pushed empty commit ${p} to branch ${a}`}}catch(s){return {success:false,status:0,duration:Date.now()-l,error:s.message||"Failed to push empty commit to GitHub"}}}var _={generic:H,"github-push":B};function R(r){return _[r||"generic"]||_.generic}function O(r,o){return `sha256=${crypto.createHmac("sha256",o).update(r).digest("hex")}`}function E(){return crypto.randomBytes(32).toString("hex")}async function L(r,o,n={}){return R(r.action)(r,o,n)}async function C(r,o,n,e={}){let t=e.maxRetries??5,a=e.retryDelay??1e3,l=null;for(let i=0;i<=t;i++){if(i>0){let s=Math.min(a*Math.pow(2,i-1),3e4);e.onRetry&&e.onRetry(i,`Retrying in ${s}ms...`),await M(s);}if(e.onRetry&&i>0&&e.onRetry(i,`Attempt ${i+1}/${t+1}`),l=await L(r,o,{...e,onRetry:void 0,onSuccess:void 0,onFailure:void 0}),l.success)return l;if(!(l.error?.includes("timed out")&&i<t)&&l.status>=400&&l.status<500)return l}return l||{success:false,status:0,duration:0,error:"All delivery attempts failed"}}function P(r,o,n,e,t,a){return {id:r,webhookId:o,event:n,payload:e,attempt:t,status:a.success?"success":"failed",responseStatus:a.status||void 0,responseBody:a.body,duration:a.duration,error:a.error,createdAt:new Date().toISOString(),deliveredAt:a.success?new Date().toISOString():void 0}}function M(r){return new Promise(o=>setTimeout(o,r))}function G(){return {id:`test_${Date.now()}`,event:"collection.create",timestamp:new Date().toISOString(),collection:"test",operation:"create",data:{message:"This is a test webhook delivery"},user:{id:"system",email:"system@kyro.dev",role:"super_admin"}}}function $(r){let o=new Set,n=[];for(let e of r){let t=e==="create"||e==="update"||e==="delete"?`collection.${e}`:e;o.has(t)||(o.add(t),n.push(t));}return n}var D=class{db;constructor(o){this.db=o;}async getWebhooks(o){let e=(await this.db.find({collection:h,where:o?.status?{status:{equals:o.status}}:{},limit:100,page:1,draft:true})).docs;return o?.event?e.filter(t=>t.events.includes(o.event)):e}async getWebhookById(o){return this.db.findByID({collection:h,id:o,draft:true})}async createWebhook(o){let n=new Date().toISOString(),e=o.secret||E(),t={id:crypto.randomUUID(),name:o.name,url:o.url,events:$(o.events),collections:o.collections||[],status:o.status||"active",secret:e,headers:o.headers||{},action:o.action||"generic",config:o.config||{},createdAt:n,updatedAt:n};return await this.db.create({collection:h,data:t}),t}async updateWebhook(o,n){let e=await this.getWebhookById(o);if(!e)return null;let t={...e,...n,events:n.events?$(n.events):e.events,collections:n.collections!==void 0?n.collections:e.collections,action:n.action!==void 0?n.action:e.action,config:n.config!==void 0?{...e.config,...n.config}:e.config,updatedAt:new Date().toISOString()};return n.secret===""&&"secret"in n&&delete t.secret,await this.db.update({collection:h,id:o,data:t}),t}async deleteWebhook(o){await this.db.delete({collection:h,id:o});}async trigger(o,n){let e=await this.getWebhooks({status:"active",event:o}),t=n.collection,a=e.filter(s=>!s.collections||s.collections.length===0||!t?true:s.collections.includes(t));if(a.length===0)return [];let l={id:crypto.randomUUID(),event:o,timestamp:new Date().toISOString(),...n},i=[];for(let s of a){let c=await this.triggerWebhook(s,l);i.push(c);}return i}async triggerWebhook(o,n){let e=crypto.randomUUID();try{let t=await C(o,n,e,{maxRetries:5,retryDelay:1e3}),a=P(e,o.id,o.events[0],n,1,t);try{await this.db.create({collection:k,data:a});}catch{console.warn("[WebhookService] Failed to save delivery record:",e);}return t.success?await this.updateWebhook(o.id,{lastTriggered:new Date().toISOString(),lastError:null}).catch(()=>{}):await this.updateWebhook(o.id,{lastError:t.error||`HTTP ${t.status}`}).catch(()=>{}),{deliveryId:e,webhookId:o.id,event:o.events[0],status:t.success?"success":"failed",responseStatus:t.status,duration:t.duration,error:t.error}}catch(t){return {deliveryId:e,webhookId:o.id,event:o.events[0],status:"failed",error:t.message}}}async testWebhook(o){let n=await this.getWebhookById(o);if(!n)return null;let e={id:crypto.randomUUID(),event:n.events[0]||"collection.create",timestamp:new Date().toISOString(),collection:"test",operation:"create",data:{message:"This is a test webhook delivery from Kyro CMS"},user:{id:"system",email:"system@kyro.dev",role:"super_admin"}};return this.triggerWebhook(n,e)}async getDeliveryHistory(o,n=50){return (await this.db.find({collection:k,where:{webhookId:{equals:o}},sort:"-createdAt",limit:n,page:1})).docs}async retryDelivery(o){let n=await this.db.findByID({collection:k,id:o});if(!n)return null;let e=await this.getWebhookById(n.webhookId);return e?this.triggerWebhook(e,n.payload):null}};function q(r){return new D(r)}function V(r){if(!r)return [];if(typeof r=="string")return [{id:r}];if(Array.isArray(r))return r.map(o=>typeof o=="object"?{id:o.value??o.id??o,relationTo:o.relationTo}:{id:o});if(typeof r=="object"){let o=r.value??r.id??r;if(typeof o=="string")return [{id:o,relationTo:r.relationTo}];if(Array.isArray(o))return o.map(n=>({id:n,relationTo:r.relationTo}))}return []}function W(r,o,n){if(!(!r||typeof r!="object")){for(let e of o)if(!(!e.name&&e.type!=="row"&&e.type!=="collapsible"&&e.type!=="tabs")){if(e.type==="relationship"||e.type==="upload"){let t=r[e.name];if(!t)continue;let a=Array.isArray(e.relationTo)?e.relationTo:[e.relationTo],l=V(t);for(let i of l){if(!i.id)continue;let s=i.relationTo?[i.relationTo]:a;for(let c of s)c!=="*"&&(n.has(c)||n.set(c,new Set),n.get(c).add(i.id));}}else if(e.type==="group"||e.type==="collapsible"||e.type==="row"){let t=e.name?r[e.name]:r;W(t,e.fields||[],n);}else if(e.type==="tabs"&&e.tabs){let t=e.name?r[e.name]:r;for(let a of e.tabs)W(t,a.fields||[],n);}else if(e.type==="array"&&e.name&&Array.isArray(r[e.name]))for(let t of r[e.name])W(t,e.fields||[],n);else if(e.type==="blocks"&&e.name&&Array.isArray(r[e.name]))for(let t of r[e.name]){if(!t||typeof t!="object")continue;let a=t.type||t.blockType;if(!a)continue;let l=e.blocks?.find(i=>i.slug===a);if(l&&Array.isArray(l.fields)){let i=t.data&&typeof t.data=="object"?t.data:t;W(i,l.fields,n);}}}}}function v(r,o,n){if(!(!r||typeof r!="object")){for(let e of o)if(!(!e.name&&e.type!=="row"&&e.type!=="collapsible"&&e.type!=="tabs")){if(e.type==="relationship"||e.type==="upload"){let t=r[e.name];if(!t)continue;let a=Array.isArray(e.relationTo)?e.relationTo:[e.relationTo],l=s=>{r[e.name]=s;},i=(s,c)=>{let u=c?[c]:a;for(let d of u){let y=n.get(d);if(y&&y.has(s))return y.get(s)}return null};if(typeof t=="string"){let s=i(t);l(s||{id:t});}else if(Array.isArray(t))l(t.map(s=>{let c=typeof s=="object"?s.value??s.id:s,u=typeof s=="object"?s.relationTo:void 0,d=i(c,u);return d||{id:c}}));else if(typeof t=="object"){let s=t.value??t.id,c=t.relationTo,u=i(s,c);l(u||{id:s});}}else if(e.type==="group"||e.type==="collapsible"||e.type==="row"){let t=e.name?r[e.name]:r;v(t,e.fields||[],n);}else if(e.type==="tabs"&&e.tabs){let t=e.name?r[e.name]:r;for(let a of e.tabs)v(t,a.fields||[],n);}else if(e.type==="array"&&e.name&&Array.isArray(r[e.name]))for(let t of r[e.name])v(t,e.fields||[],n);else if(e.type==="blocks"&&e.name&&Array.isArray(r[e.name]))for(let t of r[e.name]){if(!t||typeof t!="object")continue;let a=t.type||t.blockType;if(!a)continue;let l=e.blocks?.find(i=>i.slug===a);if(l&&Array.isArray(l.fields)){let i=t.data&&typeof t.data=="object"?t.data:t;v(i,l.fields,n);}}}}}async function F(r,o,n,e,t=1,a=0){if(!r||r.length===0||t>a)return;let l=new Map;for(let c of r)W(c,o,l);if(l.size===0)return;let i=new Map,s=new Map;for(let[c,u]of l.entries()){if(u.size===0||!e.getCollection(c))continue;let y=new Map,g=Array.from(u),f=[];for(let m of g)try{let p=await n.findByID({collection:c,id:m,draft:!0});p&&(y.set(m,p),f.push(p));}catch{}i.set(c,y),f.length>0&&s.set(c,f);}if(t<a)for(let[c,u]of s.entries()){let d=e.getCollection(c);d&&await F(u,d.fields,n,e,t+1,a);}for(let c=0;c<r.length;c++)v(r[c],o,i),r[c]=chunkG7SSHELM_cjs.a(r[c]);}function j(r){return r==="read"?"read":r==="create"?"create":r==="update"?"update":"delete"}function z(r,o){return {none:false,read:r==="read",create:r==="read"||r==="create",update:r==="read"||r==="create"||r==="update",delete:r==="read"||r==="create"||r==="update"||r==="delete",admin:true}[o]||false}async function Ae(r,o,n,e={}){let{user:t,req:a,tenantId:l,apiKey:i}=n,{enablePublicAccess:s=true,defaultAccess:c="none"}=e,u=r.access?.[o];if(u){let y=await chunkNY47CFVP_cjs.a(u,{req:a,user:t,tenantId:l});return y===false?{allowed:false,error:"Access denied",status:403}:typeof y=="object"?{allowed:true,extraWhere:y}:{allowed:true}}if(i?.permissions?.length>0){let y=r.slug,g=j(o),f=`${y}:${g}`;return !chunkNY47CFVP_cjs.h(i.permissions,f)&&!chunkNY47CFVP_cjs.h(i.permissions,`${y}:admin`)?{allowed:false,error:"Access denied: insufficient permissions",status:403}:{allowed:true}}if(t){let y=r.slug,g=j(o),f=`${y}:${g}`,m=chunkQ3Q7BJVQ_cjs.a({id:t.id,email:t.email,role:t.role},f),p=chunkQ3Q7BJVQ_cjs.a({id:t.id,email:t.email,role:t.role},`${y}:admin`);return m||p?{allowed:true}:{allowed:false,error:"Access denied: missing RBAC permission",status:403}}let d=z(o,c);return s&&d?{allowed:true}:{allowed:false,error:"Authentication required",status:401}}async function De(r,o,n,e={}){let{user:t,req:a,tenantId:l}=n,{enablePublicAccess:i=true}=e,s=r.access?.[o];if(s)return await chunkNY47CFVP_cjs.a(s,{req:a,user:t,tenantId:l})===false?{allowed:false,error:"Access denied",status:403}:{allowed:true};if(t){let c=`globals:${o}`,u=chunkQ3Q7BJVQ_cjs.a({id:t.id,email:t.email,role:t.role},c),d=chunkQ3Q7BJVQ_cjs.a({id:t.id,email:t.email,role:t.role},"globals:admin");return u||d?{allowed:true}:{allowed:false,error:"Access denied: missing RBAC permission",status:403}}return i?{allowed:true}:{allowed:false,error:"Authentication required",status:401}}
|
|
2
|
+
exports.a=F;exports.b=Ae;exports.c=De;exports.d=x;exports.e=K;exports.f=h;exports.g=k;exports.h=O;exports.i=E;exports.j=L;exports.k=C;exports.l=P;exports.m=G;exports.n=D;exports.o=q;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
'use strict';var
|
|
1
|
+
'use strict';var chunkRDKCMKBE_cjs=require('./chunk-RDKCMKBE.cjs'),chunkQMQXKCCQ_cjs=require('./chunk-QMQXKCCQ.cjs'),chunkHOP4D5XZ_cjs=require('./chunk-HOP4D5XZ.cjs'),chunkWG3UQEV7_cjs=require('./chunk-WG3UQEV7.cjs'),chunkGYQMNXXW_cjs=require('./chunk-GYQMNXXW.cjs'),chunk3Q2WUG63_cjs=require('./chunk-3Q2WUG63.cjs'),chunkBVG6VSAJ_cjs=require('./chunk-BVG6VSAJ.cjs'),m=require('kyro:config');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var m__default=/*#__PURE__*/_interopDefault(m);exports.a=null;var n=null;async function b(){if(!exports.a){if(globalThis.__KYRO_INSTANCE__)try{await globalThis.__KYRO_INSTANCE__.shutdown();}catch{}try{let t=m__default.default.default||m__default.default;exports.a=chunkRDKCMKBE_cjs.z(t),await exports.a.init(),await exports.a.loadSettings();let a=exports.a.db,r;if(a instanceof chunkWG3UQEV7_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 chunkHOP4D5XZ_cjs.a({path:s});}}else if(a instanceof chunkRDKCMKBE_cjs.A){let s=process.env.KYRO_AUTH_DB_PATH||"./data/auth.db";r=new chunkHOP4D5XZ_cjs.a({path:s});}else a instanceof chunk3Q2WUG63_cjs.a&&(r=new chunkBVG6VSAJ_cjs.a({db:a.db}));r?.connect&&await r.connect(),(await chunkQMQXKCCQ_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(t){throw exports.a=null,n=null,console.error("[Kyro API] Init failed, will retry:",t),t}}}async function O(){n||(n=b()),await n;}var g={graphqlEnabled:false,trpcEnabled:false,wsEnabled:false,requireAuth:false};async function A(t){try{return (await exports.a.db.findOne({collection:"_globals_access-settings",where:{},draft:!0}))?.apiAccess?.[t]??g[t]??!0}catch{return true}}var q=async t=>{if(!exports.a){n||(n=b());try{await Promise.race([n,new Promise((l,o)=>setTimeout(()=>o(new Error("Initialization timeout")),3e4))]);}catch{return new Response(JSON.stringify({error:"Service Unavailable",message:"Kyro CMS is still starting up. Please try again in a moment."}),{status:503,headers:{"Content-Type":"application/json","Retry-After":"5"}})}}let r=new URL(t.request.url).pathname,i=__KYRO_API_PATH__;if(r===`${i}/graphql`&&typeof exports.a.getGraphQL=="function"){if(!await A("graphqlEnabled"))return new Response(JSON.stringify({error:"GraphQL is disabled"}),{status:503,headers:{"Content-Type":"application/json"}});let o=await exports.a.getGraphQL().fetch(t.request,t.locals);return new Response(o.body,o)}if(r.startsWith(`${i}/trpc/`)&&typeof exports.a.getTRPC=="function"){if(!await A("trpcEnabled"))return new Response(JSON.stringify({error:"tRPC is disabled"}),{status:503,headers:{"Content-Type":"application/json"}});let o=await exports.a.getTRPC().fetch(t.request,t.locals);return new Response(o.body,o)}return exports.a.getREST().fetch(t.request,t.locals)};exports.b=O;exports.c=q;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import {d,o,a,b,c}from'./chunk-FVZ5RFLO.js';import {f,e,g as g$1}from'./chunk-HLSB2MCK.js';import {a as a$1}from'./chunk-4RMFCTWH.js';async function W(e$1){let a=o(e$1.db),t={db:e$1.db,registry:e$1.registry,req:e$1.req,user:e$1.user,tenantId:e$1.tenantId,webhookService:a,settings:e$1.settings},n=f(e$1.req);if(n){let r=await e(n,e$1.db,async o=>{try{return await e$1.db.findByID({collection:"users",id:o})||null}catch{return null}});r.valid&&(t.user=r.user||e$1.user,t.tenantId=r.tenantId||e$1.tenantId,t.apiKey=g$1(r));}return t}var O={_media:{create:d.MEDIA_UPLOAD,update:d.MEDIA_UPLOAD,delete:d.MEDIA_DELETE}};function C(e,a){let t=O[e];return t?t[a]:`collection.${a}`}async function D(e,a,t){if(e.webhookService)try{await e.webhookService.trigger(a,{collection:t.collection,operation:t.operation,data:t.data,previousData:t.previousData,user:e.user?{id:e.user.id,email:e.user.email,role:e.user.role}:void 0,tenantId:e.tenantId});}catch(n){console.error(`[Webhook] Failed to trigger ${a}:`,n);}}function m(e,a){if(!(!e||typeof e!="object"))for(let t of a){if(t.type==="tabs"&&Array.isArray(t.tabs)){let r=t.name?e[t.name]:e;if(r&&typeof r=="object")for(let o of t.tabs)Array.isArray(o.fields)&&m(r,o.fields);continue}if(!t.name||!(t.name in e))continue;if(e[t.name]===""&&(t.type==="text"||t.type==="textarea"||t.type==="code"||t.type==="markdown"||t.type==="email"||t.type==="password"||t.type==="color"||(e[t.name]=null)),(t.type==="group"||t.type==="collapsible")&&t.name&&Array.isArray(t.fields)&&e[t.name]&&typeof e[t.name]=="object")m(e[t.name],t.fields);else if(t.type==="array"&&t.name&&Array.isArray(t.fields)&&Array.isArray(e[t.name]))for(let r of e[t.name])r&&typeof r=="object"&&m(r,t.fields);else if(t.type==="blocks"&&t.name&&Array.isArray(t.blocks)&&Array.isArray(e[t.name]))for(let r of e[t.name]){if(!r||typeof r!="object")continue;let o=r.type||r.blockType;if(!o)continue;let s=t.blocks.find(i=>i.slug===o);if(!s||!Array.isArray(s.fields))continue;let u=r.data&&typeof r.data=="object"?r.data:r;m(u,s.fields);}}}async function g(e,a,t){let n=await b(e,a,{user:t.user,req:t.req,tenantId:t.tenantId,apiKey:t.apiKey});if(!n.allowed)throw new Error(n.error||"Access denied");t.tenantId&&t.db.setTenantContext({tenantId:t.tenantId,userId:t.user?.id??"",role:t.user?.role,isSuperAdmin:t.user?.role==="super_admin"});}function R(e){return async a$2=>{let{collection:t,where:n,sort:r,limit:o,page:s,depth:u,select:i,draft:d}=a$2,l=e.registry.getCollection(t);if(await g(l,"read",e),l.hooks?.beforeRead)for(let y of l.hooks.beforeRead)await y({collection:t,req:e.req,user:e.user,tenantId:e.tenantId,operation:"read",where:n});let c=d??!!e.user,b=await e.db.find({collection:t,where:n||{},sort:r,limit:o||10,page:s||1,depth:u||0,tenantId:e.tenantId,select:i,draft:c});if(l.hooks?.afterRead)for(let y of b.docs)for(let w of l.hooks.afterRead)await w({collection:t,doc:y,req:e.req,user:e.user,tenantId:e.tenantId,operation:"read"});return await a(b.docs,l.fields,e.db,e.registry,1,u||0),a$1(b)}}function q(e){return async a$2=>{let{collection:t,id:n,depth:r,select:o,draft:s}=a$2,u=e.registry.getCollection(t);await g(u,"read",e);let i=s??!!e.user,d=await e.db.findByID({collection:t,id:n,depth:r||0,tenantId:e.tenantId,select:o,draft:i});if(!d)throw new Error(`Document not found: ${t}/${n}`);if(u.hooks?.afterRead)for(let l of u.hooks.afterRead)await l({collection:t,doc:d,req:e.req,user:e.user,tenantId:e.tenantId,operation:"read",id:n});return await a([d],u.fields,e.db,e.registry,1,r||0),a$1(d)}}function P(e){return async a=>{let{collection:t,data:n,depth:r,select:o}=a,s=e.registry.getCollection(t);await g(s,"create",e);let i=e.registry.getCreateZodSchema(t).parse(n);if(s.tenantScoped&&e.tenantId&&(i.tenantId=e.tenantId),s.hooks?.beforeValidate)for(let l of s.hooks.beforeValidate){let c=await l({collection:t,data:i,req:e.req,user:e.user,tenantId:e.tenantId,operation:"create"});c&&typeof c=="object"&&!Array.isArray(c)&&Object.assign(i,c);}if(s.hooks?.beforeChange)for(let l of s.hooks.beforeChange){let c=await l({collection:t,data:i,req:e.req,user:e.user,tenantId:e.tenantId,operation:"create"});c&&typeof c=="object"&&!Array.isArray(c)&&Object.assign(i,c);}let d=await e.db.create({collection:t,data:i,depth:r||0,tenantId:e.tenantId,select:o});if(s.hooks?.afterChange)for(let l of s.hooks.afterChange)await l({collection:t,doc:d,data:i,req:e.req,user:e.user,tenantId:e.tenantId,operation:"create"});return await D(e,C(t,"create"),{collection:t,data:d,operation:"create"}),{doc:d}}}function v(e){return async a=>{let{collection:t,id:n,data:r,depth:o,select:s,baseUpdatedAt:u}=a,i=e.registry.getCollection(t);await g(i,"update",e);let d=await e.db.findByID({collection:t,id:n,tenantId:e.tenantId,draft:true});if(!d)throw new Error(`Document not found: ${t}/${n}`);if(u&&d.updatedAt&&u!==d.updatedAt)throw new Error(`Revision conflict: document has changed since ${u}. Current updatedAt: ${d.updatedAt}`);m(r,i.fields);let c=e.registry.getUpdateZodSchema(t).parse(r);if(i.tenantScoped&&e.tenantId&&(c.tenantId=e.tenantId),i.hooks?.beforeValidate)for(let h of i.hooks.beforeValidate){let f=await h({collection:t,data:c,originalDoc:d,req:e.req,user:e.user,tenantId:e.tenantId,operation:"update",id:n});f&&typeof f=="object"&&!Array.isArray(f)&&Object.assign(c,f);}if(i.hooks?.beforeChange)for(let h of i.hooks.beforeChange){let f=await h({collection:t,data:c,originalDoc:d,req:e.req,user:e.user,tenantId:e.tenantId,operation:"update",id:n});f&&typeof f=="object"&&!Array.isArray(f)&&Object.assign(c,f);}let b=e.req&&typeof e.req.headers?.get=="function"&&e.req.headers.get("x-draft")==="true"||a.draft===true,y=i.versions?.drafts===true,w=e.req?.query?.autosave==="true"||e.req?.url?.includes("autosave=true")||a.autosave===true,p;if(y&&b?(await e.db.createVersion({collection:t,documentId:n,data:c,status:"draft",autosave:w,createdBy:e.user?.id,tenantId:e.tenantId}),p=await e.db.findByID({collection:t,id:n,tenantId:e.tenantId,draft:true})):y?(p=await e.db.update({collection:t,id:n,data:{...c,status:"published"},depth:o||0,tenantId:e.tenantId,select:s}),await e.db.createVersion({collection:t,documentId:n,data:c,status:"published",createdBy:e.user?.id,tenantId:e.tenantId})):p=await e.db.update({collection:t,id:n,data:c,depth:o||0,tenantId:e.tenantId,select:s}),i.hooks?.afterChange)for(let h of i.hooks.afterChange)await h({collection:t,doc:p,data:c,originalDoc:d,req:e.req,user:e.user,tenantId:e.tenantId,operation:"update",id:n});return await D(e,C(t,"update"),{collection:t,data:p,previousData:d,operation:"update"}),{doc:p}}}function K(e){return async a=>{let{collection:t,id:n}=a,r=e.registry.getCollection(t);await g(r,"delete",e);let o=await e.db.findByID({collection:t,id:n,tenantId:e.tenantId,draft:true});if(!o)throw new Error(`Document not found: ${t}/${n}`);if(r.hooks?.beforeDelete)for(let u of r.hooks.beforeDelete)await u({collection:t,doc:o,req:e.req,user:e.user,tenantId:e.tenantId,operation:"delete",id:n});let s=await e.db.delete({collection:t,id:n,tenantId:e.tenantId});if(r.hooks?.afterDelete)for(let u of r.hooks.afterDelete)await u({collection:t,doc:s,req:e.req,user:e.user,tenantId:e.tenantId,operation:"delete",id:n});return await D(e,C(t,"delete"),{collection:t,data:s,previousData:o,operation:"delete"}),{doc:s,message:"Deleted successfully"}}}function E(e){return async a=>{let{collection:t,where:n}=a,r=e.registry.getCollection(t);return await g(r,"read",e),{totalDocs:await e.db.count({collection:t,where:n||{},tenantId:e.tenantId})}}}async function $(e,a,t){let n=await c(e,a,{user:t.user,req:t.req,tenantId:t.tenantId});if(!n.allowed)throw new Error(n.error||"Access denied");t.tenantId&&t.db.setTenantContext({tenantId:t.tenantId,userId:t.user?.id??"",role:t.user?.role,isSuperAdmin:t.user?.role==="super_admin"});}function T(e){let a={},t=e.registry.getCollections();for(let r of t){let o=r.slug;a[o]={find:R(e),findByID:q(e),create:P(e),update:v(e),delete:K(e),count:E(e)};}let n=e.registry.getGlobals();for(let r of n){let o=r.slug;a[`_globals_${o}`]={get:async s=>(await $(r,"read",e),await e.db.findOne({collection:`_globals_${o}`,where:{},tenantId:e.tenantId,depth:s?.depth,draft:s?.draft,select:s?.select})),update:async s=>{await $(r,"update",e);let i=e.registry.getZodSchema(o).parse(s.data),d=await e.db.findOne({collection:`_globals_${o}`,where:{},tenantId:e.tenantId,draft:true}),l;return d?l=await e.db.update({collection:`_globals_${o}`,id:d.id,data:i,tenantId:e.tenantId}):l=await e.db.create({collection:`_globals_${o}`,data:{...i,id:o},tenantId:e.tenantId}),l}};}return a}function V(e){if(e.settings?.access?.apiAccess?.trpcEnabled===false)throw new Error("tRPC API is disabled");return T(e)}export{W as a,R as b,q as c,P as d,v as e,K as f,E as g,T as h,V as i};
|