@kyro-cms/core 0.12.55 → 0.12.56

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/dist/api-handler-graphql.cjs +1 -1
  2. package/dist/api-handler-graphql.js +1 -1
  3. package/dist/api-handler-trpc.cjs +1 -1
  4. package/dist/api-handler-trpc.js +1 -1
  5. package/dist/api-handler.cjs +1 -1
  6. package/dist/api-handler.js +1 -1
  7. package/dist/{chunk-4MVLIR77.cjs → chunk-3I6T73A5.cjs} +9 -9
  8. package/dist/{chunk-5YQ2HVHD.js → chunk-5BIZIO6T.js} +10 -10
  9. package/dist/chunk-5ZEYOFAK.js +2 -0
  10. package/dist/chunk-6KERPHAL.cjs +2 -0
  11. package/dist/chunk-72VOOMJI.js +20 -0
  12. package/dist/chunk-7DUKWHRN.cjs +1 -0
  13. package/dist/{chunk-AIE7BKVY.js → chunk-E555R77V.js} +1 -1
  14. package/dist/chunk-FJPY42VZ.cjs +20 -0
  15. package/dist/{chunk-V65273ZG.cjs → chunk-KJ3I35YV.cjs} +3 -3
  16. package/dist/{chunk-BU6O3TP7.js → chunk-KNOFTUQV.js} +24 -24
  17. package/dist/chunk-LVHWORV4.js +3 -0
  18. package/dist/chunk-PCN6QV3Z.js +21 -0
  19. package/dist/chunk-PCVQNVSU.cjs +19 -0
  20. package/dist/{chunk-6KUL2BSA.cjs → chunk-TDGSIF5H.cjs} +24 -24
  21. package/dist/{chunk-M645XO2L.js → chunk-UZEDY2UL.js} +1 -1
  22. package/dist/{chunk-QEZKIR5V.cjs → chunk-VV47TO2O.cjs} +1 -1
  23. package/dist/cli/index.cjs +1 -1
  24. package/dist/cli/index.js +1 -1
  25. package/dist/drizzle/index.cjs +1 -1
  26. package/dist/drizzle/index.js +1 -1
  27. package/dist/index.cjs +5 -5
  28. package/dist/index.d.cts +1 -14
  29. package/dist/index.d.ts +1 -14
  30. package/dist/index.js +8 -8
  31. package/dist/integration.cjs +1 -1
  32. package/dist/integration.js +1 -1
  33. package/dist/{local-3V3XEQUY.js → local-2IFOTHAA.js} +1 -1
  34. package/dist/{local-YCWBUF3R.cjs → local-UESCNPQP.cjs} +1 -1
  35. package/dist/{mongo-auth-adapter-W3HLB7OR.cjs → mongo-auth-adapter-EUHAYWJ6.cjs} +1 -1
  36. package/dist/{mongo-auth-adapter-QDXVHREJ.js → mongo-auth-adapter-FW7ATYQ6.js} +1 -1
  37. package/dist/mongodb/index.cjs +1 -1
  38. package/dist/mongodb/index.js +1 -1
  39. package/dist/rest/index.cjs +1 -1
  40. package/dist/rest/index.js +1 -1
  41. package/package.json +2 -2
  42. package/dist/chunk-CMQYYIGC.js +0 -21
  43. package/dist/chunk-LELK3TYX.js +0 -3
  44. package/dist/chunk-OW3HFVPX.cjs +0 -20
  45. package/dist/chunk-PRMILS4Y.js +0 -20
  46. package/dist/chunk-UT7RGIYS.js +0 -2
  47. package/dist/chunk-WJBQ2NBD.cjs +0 -1
  48. package/dist/chunk-XDE7CFV6.cjs +0 -19
  49. package/dist/chunk-ZKHTFR5S.cjs +0 -2
@@ -1,45 +1,45 @@
1
1
  import {a as a$4,f}from'./chunk-OXGJOYEO.js';import {a as a$5}from'./chunk-2HA6EKXX.js';import {c,a as a$2,b,e,h}from'./chunk-JV4HJBXW.js';import {n,M as M$1,p,q,o,w,E,s,t,u,v}from'./chunk-HRAY65XH.js';import {ia,oa,fa,ma,$,ha,ca,pa,ra,J}from'./chunk-3NSZZCOJ.js';import {a,c as c$1,b as b$1,d}from'./chunk-SLMIYECU.js';import {a as a$1}from'./chunk-P6JITOFF.js';import {a as a$3}from'./chunk-VVVCCB6R.js';import {g}from'./chunk-Y2YAKDEQ.js';import {randomBytes}from'crypto';import {mkdir}from'fs/promises';import {resolve,dirname}from'path';import {createRequire}from'module';if (typeof window === "undefined") { const { createRequire } = await import(/* @vite-ignore */ 'module'); createRequire(import.meta.url); }
2
- g();function D(f){if(typeof f!="string")return f;let t=f.replace(/-/g,"").toLowerCase();return t.length===32?`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`:f}function L(f,t="postgres"){switch(f.type){case "text":case "email":case "password":case "color":case "icon":return t==="sqlite"?"text":"varchar";case "textarea":case "code":case "markdown":case "secret":return "text";case "number":return f.integer?"integer":"decimal";case "checkbox":return "boolean";case "date":return "timestamp";case "select":case "radio":return t==="sqlite"?"text":"varchar";case "richtext":case "json":case "array":case "group":case "blocks":case "row":case "collapsible":case "tabs":return "jsonb";case "relationship":return t==="sqlite"?"text":"varchar";case "upload":return "jsonb";default:return "jsonb"}}function Ie(f,t="postgres"){let i=f.slug.replace(/-/g,"_"),e=[];e.push(`export const ${i} = pgTable('${i}', {`),e.push(" id: uuid('id').primaryKey().defaultRandom(),");for(let s of f.fields){if(s.name==="id"||s.type==="password")continue;let a=L(s,t),r=s.required,n=` ${s.name}: pg.${a}('${s.name}')`;s.unique&&(n+=".unique()"),r||(n+=".nullable()"),s.defaultValue!==void 0&&(typeof s.defaultValue=="string"?n+=`.default('${s.defaultValue}')`:typeof s.defaultValue=="boolean"?n+=`.default(${s.defaultValue})`:n+=`.default(sql\`${JSON.stringify(s.defaultValue)}\`)`),n+=",",e.push(n);}return f.timestamps&&(e.push(" createdAt: pg.timestamp('created_at').defaultNow(),"),e.push(" updatedAt: pg.timestamp('updated_at').defaultNow(),")),e.push(` status: ${t==="sqlite"?"sqlite":"pg"}.varchar('status').default('draft'),`),e.push(` hasDraft: ${t==="sqlite"?"sqlite":"pg"}.boolean('hasDraft').default(false),`),e.push("});"),e.join(`
3
- `)}function le(f,t){return Array.isArray(f)?f.map(i=>{if(!i||typeof i!="object")return i;let e=i.data?{...i.data}:void 0;if(!e)return i;let s=t.find(a=>a.slug===i.type||a.slug===i.slug);if(!s||!Array.isArray(s.fields))return i;for(let a of s.fields){if(a.name&&(a.type==="upload"||a.type==="image")&&e[a.name]){let r=e[a.name];Array.isArray(r)?e[a.name]=r.map(n=>typeof n=="string"?{id:n}:n):typeof r=="string"&&(e[a.name]={id:r});}if(a.type==="blocks"&&a.name&&e[a.name]){let r=a.blocks||[];e[a.name]=le(e[a.name],r);}}return {...i,data:e}}):f}var M=class extends a{client;schema;_schemaEnsured=false;dialect;connectionString;versionsTableReady=false;rawClient;constructor(t){if(super(),this.schema=t.schema||{},t.connectionString){this.connectionString=t.connectionString;let i=t.connectionString.toLowerCase();i.startsWith("postgres://")||i.startsWith("postgresql://")?this.dialect="postgres":i.includes(".db")||i.includes("sqlite")||i.includes("file:")?this.dialect="sqlite":this.dialect=t.type||"postgres";}else this.rawClient=t.client,this.client=t.client,this.dialect=t.type||"sqlite";}prepareData(t,i){let e=super.prepareData(t,i);e.createdAt&&typeof e.createdAt=="string"&&(e.createdAt=new Date(e.createdAt)),e.updatedAt&&typeof e.updatedAt=="string"&&(e.updatedAt=new Date(e.updatedAt));for(let s of i.fields)if(s.type==="date"&&s.name){let a=e[s.name];a&&typeof a=="string"&&(e[s.name]=new Date(a));}for(let s of i.fields){let r=L(s,this.dialect)==="jsonb";if(s.type==="tabs"&&"tabs"in s&&s.name){let n=t[s.name];if(n&&typeof n=="object"){let o={};for(let[c,d]of Object.entries(n)){let u=s.tabs.flatMap(g=>g.fields).find(g=>g.name===c);(u?.type==="upload"||u?.type==="image"||u?.type==="list"||u?.type==="relationship-block")&&d?o[c]=Array.isArray(d)||typeof d=="object"?JSON.stringify(d):d:o[c]=d;}e[s.name]=this.dialect==="sqlite"||!r?JSON.stringify(o):o;}}else if(r&&s.name&&t[s.name]!==void 0&&t[s.name]!==null)e[s.name]=this.dialect==="sqlite"?JSON.stringify(t[s.name]):t[s.name];else if((s.type==="upload"||s.type==="image"||s.type==="list"||s.type==="relationship-block")&&s.name){let n=t[s.name];n!=null&&(e[s.name]=this.dialect==="sqlite"||!r?typeof n=="string"?n:JSON.stringify(n):n);}}for(let s of i.fields)if(s.name&&e[s.name]===""){let a=L(s,this.dialect);(a==="timestamp"||a==="jsonb"||a==="decimal"||a==="integer"||a==="numeric"||a==="boolean")&&(e[s.name]=null);}return e}async connect(){if(this.connectionString&&!this.client){if(this.dialect==="postgres"){let t,i;try{t=(await import('./src-QBADSZV4.js')).default,i=(await import('./postgres-js-4CI7FMYS.js')).drizzle;}catch{a$1(["postgres","drizzle-orm"]),t=(await import('./src-QBADSZV4.js')).default,i=(await import('./postgres-js-4CI7FMYS.js')).drizzle;}let e=t(this.connectionString,{onnotice:()=>{}});this.client=i(e,{schema:this.schema});}else if(this.dialect==="sqlite"){let t,i;try{t=(await import('better-sqlite3')).default,i=(await import('./better-sqlite3-B34RIU4C.js')).drizzle;}catch{a$1(["better-sqlite3","drizzle-orm"]),t=(await import('better-sqlite3')).default,i=(await import('./better-sqlite3-B34RIU4C.js')).drizzle;}let e=new t(this.connectionString.replace("file:",""));this.client=i(e,{schema:this.schema});}}if(this.rawClient&&typeof this.rawClient.prepare=="function"&&typeof this.client?.select!="function"){let{drizzle:t}=await import('./d1-HPB6B253.js');this.client=t(this.rawClient,{schema:this.schema});}this.connected=true;}async init(t,i=[]){if(await super.init(t,i),(this.connectionString&&!this.client||this.rawClient&&typeof this.client?.select!="function")&&await this.connect(),this.client&&!this._schemaEnsured){for(let s of t){let a=this.getTableName(s.slug);this.schema[a]||(this.schema[a]=this.createTableFromConfig(s));}await this.ensureCollectionTables(t);let e=i.map(s=>({slug:`_globals_${s.slug}`,fields:s.fields,label:s.label}));for(let s of e){let a=this.getTableName(s.slug);this.schema[a]||(this.schema[a]=this.createTableFromConfig(s,true)),this.collections.has(s.slug)||this.collections.set(s.slug,s);}await this.ensureCollectionTables(e),this._schemaEnsured=true;}}createTableFromConfig(t,i=false){let e$1=this.getTableName(t.slug),s={id:i?ia("id").primaryKey():oa("id").primaryKey().defaultRandom()};for(let a of t.fields){if(!a.name||a.name==="id"||a.type==="password")continue;let r=L(a,this.dialect),n=a.name.replace(/-/g,"_"),o=n.replace(/([A-Z])/g,"_$1").toLowerCase(),c$1;if(this.dialect==="sqlite")switch(r){case "varchar":case "text":c$1=c(o);break;case "integer":c$1=a$2(o);break;case "decimal":case "numeric":c$1=b(o);break;case "boolean":c$1=a$2(o,{mode:"boolean"});break;case "timestamp":c$1=c(o);break;case "jsonb":c$1=c(o);break;default:c$1=c(o);}else switch(r){case "varchar":c$1=pa(o,{length:255});break;case "integer":c$1=ca(o);break;case "decimal":c$1=ha(o);break;case "boolean":c$1=$(o);break;case "timestamp":c$1=ma(o);break;case "jsonb":c$1=fa(o);break;default:c$1=ia(o);}a.required||(c$1=c$1.default(null)),s[n]=c$1;}return s.createdAt||(s.createdAt=this.dialect==="sqlite"?c("created_at").default(new Date().toISOString()):ma("created_at").defaultNow()),s.updatedAt||(s.updatedAt=this.dialect==="sqlite"?c("updated_at").default(new Date().toISOString()):ma("updated_at").defaultNow()),e$1!=="users"&&e$1!=="audit_logs"&&(s.status||(s.status=this.dialect==="sqlite"?c("status").default("draft"):pa("status",{length:20}).default("draft")),s.hasDraft||(s.hasDraft=this.dialect==="sqlite"?a$2("hasDraft",{mode:"boolean"}).default(false):$("hasDraft").default(false))),this.dialect==="sqlite"?e(e$1,s):ra(e$1,s)}async ensureCollectionTables(t){let i=[];for(let e of t){let s=e.slug.startsWith("_globals_"),a=this.getTableName(e.slug),r=this.generateCreateColumns(e),n=e.fields.some(u=>u.name==="createdAt"),o=e.fields.some(u=>u.name==="updatedAt"),c=e.fields.some(u=>u.name==="status"),d=e.fields.some(u=>u.name==="hasDraft");if(this.dialect==="postgres"){let u=s?'"id" TEXT PRIMARY KEY':'"id" UUID PRIMARY KEY DEFAULT gen_random_uuid()';i.push(`
4
- CREATE TABLE IF NOT EXISTS "${a}" (
2
+ g();function D(f){if(typeof f!="string")return f;let t=f.replace(/-/g,"").toLowerCase();return t.length===32?`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`:f}function L(f,t="postgres"){switch(f.type){case "text":case "email":case "password":case "color":case "icon":return t==="sqlite"?"text":"varchar";case "textarea":case "code":case "markdown":case "secret":return "text";case "number":return f.integer?"integer":"decimal";case "checkbox":return "boolean";case "date":return "timestamp";case "select":case "radio":return t==="sqlite"?"text":"varchar";case "richtext":case "json":case "array":case "group":case "blocks":case "row":case "collapsible":case "tabs":return "jsonb";case "relationship":return t==="sqlite"?"text":"varchar";case "upload":return "jsonb";default:return "jsonb"}}function Ie(f,t="postgres"){let i=f.slug.replace(/-/g,"_"),e=[];e.push(`export const ${i} = pgTable('${i}', {`),e.push(" id: uuid('id').primaryKey().defaultRandom(),");for(let s of f.fields){if(s.name==="id"||s.type==="password")continue;let n=L(s,t),r=s.required,a=` ${s.name}: pg.${n}('${s.name}')`;s.unique&&(a+=".unique()"),r||(a+=".nullable()"),s.defaultValue!==void 0&&(typeof s.defaultValue=="string"?a+=`.default('${s.defaultValue}')`:typeof s.defaultValue=="boolean"?a+=`.default(${s.defaultValue})`:a+=`.default(sql\`${JSON.stringify(s.defaultValue)}\`)`),a+=",",e.push(a);}return f.timestamps&&(e.push(" createdAt: pg.timestamp('created_at').defaultNow(),"),e.push(" updatedAt: pg.timestamp('updated_at').defaultNow(),")),e.push(` status: ${t==="sqlite"?"sqlite":"pg"}.varchar('status').default('draft'),`),e.push(` hasDraft: ${t==="sqlite"?"sqlite":"pg"}.boolean('hasDraft').default(false),`),e.push("});"),e.join(`
3
+ `)}function le(f,t){return Array.isArray(f)?f.map(i=>{if(!i||typeof i!="object")return i;let e=i.data?{...i.data}:void 0;if(!e)return i;let s=t.find(n=>n.slug===i.type||n.slug===i.slug);if(!s||!Array.isArray(s.fields))return i;for(let n of s.fields){if(n.name&&(n.type==="upload"||n.type==="image")&&e[n.name]){let r=e[n.name];Array.isArray(r)?e[n.name]=r.map(a=>typeof a=="string"?{id:a}:a):typeof r=="string"&&(e[n.name]={id:r});}if(n.type==="blocks"&&n.name&&e[n.name]){let r=n.blocks||[];e[n.name]=le(e[n.name],r);}}return {...i,data:e}}):f}var M=class extends a{client;schema;_schemaEnsured=false;dialect;connectionString;versionsTableReady=false;rawClient;constructor(t){if(super(),this.schema=t.schema||{},t.connectionString){this.connectionString=t.connectionString;let i=t.connectionString.toLowerCase();i.startsWith("postgres://")||i.startsWith("postgresql://")?this.dialect="postgres":i.includes(".db")||i.includes("sqlite")||i.includes("file:")?this.dialect="sqlite":this.dialect=t.type||"postgres";}else this.rawClient=t.client,this.client=t.client,this.dialect=t.type||"sqlite";}prepareData(t,i){let e=super.prepareData(t,i);e.createdAt&&typeof e.createdAt=="string"&&(e.createdAt=new Date(e.createdAt)),e.updatedAt&&typeof e.updatedAt=="string"&&(e.updatedAt=new Date(e.updatedAt));for(let s of i.fields)if(s.type==="date"&&s.name){let n=e[s.name];n&&typeof n=="string"&&(e[s.name]=new Date(n));}for(let s of i.fields){let r=L(s,this.dialect)==="jsonb";if(s.type==="tabs"&&"tabs"in s&&s.name){let a=t[s.name];if(a&&typeof a=="object"){let o={};for(let[c,d]of Object.entries(a)){let u=s.tabs.flatMap(g=>g.fields).find(g=>g.name===c);(u?.type==="upload"||u?.type==="image"||u?.type==="list"||u?.type==="relationship-block")&&d?o[c]=Array.isArray(d)||typeof d=="object"?JSON.stringify(d):d:o[c]=d;}e[s.name]=this.dialect==="sqlite"||!r?JSON.stringify(o):o;}}else if(r&&s.name&&t[s.name]!==void 0&&t[s.name]!==null)e[s.name]=this.dialect==="sqlite"?JSON.stringify(t[s.name]):t[s.name];else if((s.type==="upload"||s.type==="image"||s.type==="list"||s.type==="relationship-block")&&s.name){let a=t[s.name];a!=null&&(e[s.name]=this.dialect==="sqlite"||!r?typeof a=="string"?a:JSON.stringify(a):a);}}for(let s of i.fields)if(s.name&&e[s.name]===""){let n=L(s,this.dialect);(n==="timestamp"||n==="jsonb"||n==="decimal"||n==="integer"||n==="numeric"||n==="boolean")&&(e[s.name]=null);}return e}async connect(){if(this.connectionString&&!this.client){if(this.dialect==="postgres"){let t,i;try{t=(await import('./src-QBADSZV4.js')).default,i=(await import('./postgres-js-4CI7FMYS.js')).drizzle;}catch{a$1(["postgres","drizzle-orm"]),t=(await import('./src-QBADSZV4.js')).default,i=(await import('./postgres-js-4CI7FMYS.js')).drizzle;}let e=t(this.connectionString,{onnotice:()=>{}});this.client=i(e,{schema:this.schema});}else if(this.dialect==="sqlite"){let t,i;try{t=(await import('better-sqlite3')).default,i=(await import('./better-sqlite3-B34RIU4C.js')).drizzle;}catch{a$1(["better-sqlite3","drizzle-orm"]),t=(await import('better-sqlite3')).default,i=(await import('./better-sqlite3-B34RIU4C.js')).drizzle;}let e=new t(this.connectionString.replace("file:",""));this.client=i(e,{schema:this.schema});}}if(this.rawClient&&typeof this.rawClient.prepare=="function"&&typeof this.client?.select!="function"){let{drizzle:t}=await import('./d1-HPB6B253.js');this.client=t(this.rawClient,{schema:this.schema});}this.connected=true;}async init(t,i=[]){if(await super.init(t,i),(this.connectionString&&!this.client||this.rawClient&&typeof this.client?.select!="function")&&await this.connect(),this.client&&!this._schemaEnsured){for(let s of t){let n=this.getTableName(s.slug);this.schema[n]||(this.schema[n]=this.createTableFromConfig(s));}await this.ensureCollectionTables(t);let e=i.map(s=>({slug:`_globals_${s.slug}`,fields:s.fields,label:s.label}));for(let s of e){let n=this.getTableName(s.slug);this.schema[n]||(this.schema[n]=this.createTableFromConfig(s,true)),this.collections.has(s.slug)||this.collections.set(s.slug,s);}await this.ensureCollectionTables(e),this._schemaEnsured=true;}}createTableFromConfig(t,i=false){let e$1=this.getTableName(t.slug),s={id:i?ia("id").primaryKey():oa("id").primaryKey().defaultRandom()};for(let n of t.fields){if(!n.name||n.name==="id"||n.type==="password")continue;let r=L(n,this.dialect),a=n.name.replace(/-/g,"_"),o=a.replace(/([A-Z])/g,"_$1").toLowerCase(),c$1;if(this.dialect==="sqlite")switch(r){case "varchar":case "text":c$1=c(o);break;case "integer":c$1=a$2(o);break;case "decimal":case "numeric":c$1=b(o);break;case "boolean":c$1=a$2(o,{mode:"boolean"});break;case "timestamp":c$1=c(o);break;case "jsonb":c$1=c(o);break;default:c$1=c(o);}else switch(r){case "varchar":c$1=pa(o,{length:255});break;case "integer":c$1=ca(o);break;case "decimal":c$1=ha(o);break;case "boolean":c$1=$(o);break;case "timestamp":c$1=ma(o);break;case "jsonb":c$1=fa(o);break;default:c$1=ia(o);}n.required||(c$1=c$1.default(null)),s[a]=c$1;}return s.createdAt||(s.createdAt=this.dialect==="sqlite"?c("created_at").default(new Date().toISOString()):ma("created_at").defaultNow()),s.updatedAt||(s.updatedAt=this.dialect==="sqlite"?c("updated_at").default(new Date().toISOString()):ma("updated_at").defaultNow()),e$1!=="users"&&e$1!=="audit_logs"&&(s.status||(s.status=this.dialect==="sqlite"?c("status").default("draft"):pa("status",{length:20}).default("draft")),s.hasDraft||(s.hasDraft=this.dialect==="sqlite"?a$2("hasDraft",{mode:"boolean"}).default(false):$("hasDraft").default(false))),this.dialect==="sqlite"?e(e$1,s):ra(e$1,s)}async ensureCollectionTables(t){let i=[];for(let e of t){let s=e.slug.startsWith("_globals_"),n=this.getTableName(e.slug),r=this.generateCreateColumns(e),a=e.fields.some(u=>u.name==="createdAt"),o=e.fields.some(u=>u.name==="updatedAt"),c=e.fields.some(u=>u.name==="status"),d=e.fields.some(u=>u.name==="hasDraft");if(this.dialect==="postgres"){let u=s?'"id" TEXT PRIMARY KEY':'"id" UUID PRIMARY KEY DEFAULT gen_random_uuid()';i.push(`
4
+ CREATE TABLE IF NOT EXISTS "${n}" (
5
5
  ${u},
6
6
  ${r}
7
- ${n?"":'"created_at" TIMESTAMP NOT NULL DEFAULT NOW(),'}
7
+ ${a?"":'"created_at" TIMESTAMP NOT NULL DEFAULT NOW(),'}
8
8
  ${o?"":'"updated_at" TIMESTAMP NOT NULL DEFAULT NOW(),'}
9
9
  ${c?"":`"status" VARCHAR(20) DEFAULT 'draft',`}
10
10
  ${d?"":'"hasDraft" BOOLEAN DEFAULT false'}
11
11
  )
12
12
  `);}else i.push(`
13
- CREATE TABLE IF NOT EXISTS "${a}" (
13
+ CREATE TABLE IF NOT EXISTS "${n}" (
14
14
  "id" TEXT PRIMARY KEY,
15
15
  ${r}
16
- ${n?"":`"created_at" TEXT NOT NULL DEFAULT (datetime('now')),`}
16
+ ${a?"":`"created_at" TEXT NOT NULL DEFAULT (datetime('now')),`}
17
17
  ${o?"":`"updated_at" TEXT NOT NULL DEFAULT (datetime('now')),`}
18
18
  ${c?"":`"status" TEXT DEFAULT 'draft',`}
19
19
  ${d?"":'"hasDraft" INTEGER DEFAULT 0'}
20
20
  )
21
21
  `);}if(i.length>0)if(this.dialect==="postgres")await this.executeRaw(J.raw(i.join(`;
22
- `)));else for(let e of i)await this.executeRaw(J.raw(e));for(let e of t){let s=this.getTableName(e.slug);s==="users"||s==="audit_logs"||await this.syncTableColumns(e,s);}}getColumnSqlDefinition(t,i){let e=L(t,i),s=t.name.replace(/-/g,"_").replace(/([A-Z])/g,"_$1").toLowerCase(),a=this.columnSqlType(e,i);return `"${s}" ${a} DEFAULT NULL`}columnSqlType(t,i){if(i==="sqlite")switch(t){case "varchar":return "TEXT";case "text":return "TEXT";case "integer":return "INTEGER";case "decimal":case "numeric":return "NUMERIC";case "boolean":return "INTEGER";case "timestamp":return "TEXT";case "jsonb":return "TEXT";default:return "TEXT"}switch(t){case "varchar":return "VARCHAR(255)";case "text":return "TEXT";case "integer":return "INTEGER";case "decimal":case "numeric":return "DECIMAL";case "boolean":return "BOOLEAN";case "timestamp":return "TIMESTAMP";case "jsonb":return "JSONB";default:return "TEXT"}}getExpectedColumnDefs(t,i){let e={},s=t.slug.startsWith("_globals_"),a=t.fields.some(c=>c.name==="createdAt"),r=t.fields.some(c=>c.name==="updatedAt"),n=t.fields.some(c=>c.name==="status"),o=t.fields.some(c=>c.name==="hasDraft");this.dialect==="postgres"?(e.id=s?'"id" TEXT PRIMARY KEY':'"id" UUID PRIMARY KEY DEFAULT gen_random_uuid()',a||(e.created_at='"created_at" TIMESTAMP DEFAULT NULL'),r||(e.updated_at='"updated_at" TIMESTAMP DEFAULT NULL'),n||(e.status='"status" VARCHAR(20) DEFAULT NULL'),o||(e.hasDraft='"hasDraft" BOOLEAN DEFAULT NULL')):(e.id='"id" TEXT PRIMARY KEY',a||(e.created_at='"created_at" TEXT DEFAULT NULL'),r||(e.updated_at='"updated_at" TEXT DEFAULT NULL'),n||(e.status='"status" TEXT DEFAULT NULL'),o||(e.hasDraft='"hasDraft" INTEGER DEFAULT NULL'));for(let c of t.fields){if(!c.name||c.name==="id")continue;let d=this.getColumnSqlDefinition(c,this.dialect),u=c.name.replace(/-/g,"_").replace(/([A-Z])/g,"_$1").toLowerCase();e[u]=d;}return e}async syncTableColumns(t,i){let e;try{if(this.dialect==="postgres"){let r=await this.executeRaw(J`SELECT column_name, data_type, character_maximum_length FROM information_schema.columns WHERE table_name = ${i}`);e=new Map(r.map(n=>[n.column_name,{type:n.data_type,maxLen:n.character_maximum_length}]));}else {let r=await this.executeRaw(J`PRAGMA table_info("${J.raw(i)}")`);e=new Map(r.map(n=>[n.name,{type:n.type,maxLen:null}]));}}catch{return}let s=this.getExpectedColumnDefs(t,i),a=Object.keys(s).filter(r=>!e.has(r));if(a.length>0){let r=a.map(n=>`ALTER TABLE "${i}" ADD COLUMN ${s[n]}`);await this.executeRaw(J.raw(r.join(`;
23
- `)));}if(this.dialect==="postgres")for(let r of t.fields){if(!r.name||r.name==="id")continue;let n=L(r,this.dialect),o=r.name.replace(/-/g,"_").replace(/([A-Z])/g,"_$1").toLowerCase(),c=e.get(o);!c||c.type!=="character varying"||(n==="text"?await this.executeRaw(J.raw(`ALTER TABLE "${i}" ALTER COLUMN "${o}" TYPE TEXT`)):n==="jsonb"&&(await this.executeRaw(J.raw(`ALTER TABLE "${i}" ALTER COLUMN "${o}" DROP DEFAULT`)),await this.executeRaw(J.raw(`ALTER TABLE "${i}" ALTER COLUMN "${o}" TYPE JSONB USING (CASE WHEN "${o}" IS NULL THEN NULL WHEN "${o}"::text ~ '^\\s*\\{' THEN "${o}"::jsonb ELSE jsonb_build_object('id', "${o}"::text) END)`))));}}generateCreateColumns(t){let i=[];for(let e of t.fields){if(!e.name||e.name==="id")continue;let s=L(e,this.dialect),a=e.name.replace(/-/g,"_").replace(/([A-Z])/g,"_$1").toLowerCase(),r=e.required?"NOT NULL":"DEFAULT NULL",n;if(this.dialect==="sqlite")switch(s){case "varchar":case "text":n=`TEXT ${r}`;break;case "integer":n=`INTEGER ${r}`;break;case "decimal":case "numeric":n=`NUMERIC ${r}`;break;case "boolean":n=`INTEGER ${r}`;break;case "timestamp":n=`TEXT ${r}`;break;case "jsonb":n=`TEXT ${r}`;break;default:n=`TEXT ${r}`;}else switch(s){case "varchar":n=`VARCHAR(255) ${r}`;break;case "integer":n=`INTEGER ${r}`;break;case "decimal":n=`DECIMAL ${r}`;break;case "boolean":n=`BOOLEAN ${r}`;break;case "timestamp":n=`TIMESTAMP ${r}`;break;case "jsonb":n=`JSONB ${r}`;break;default:n=`TEXT ${r}`;}i.push(`"${a}" ${n}`);}return i.join(`,
24
- `)+(i.length>0?",":"")}async disconnect(){this.connected=false;}async find(t){let{collection:i,where:e={},sort:s,limit:a=10,page:r=1,tenantId:n$1,select:o,draft:c}=t,d$1=this.getCollection(i),u=this.getTable(i),m={...e};this.tenantContext&&d$1.tenantScoped&&(m=c$1({where:m},i,this.tenantContext,b$1).where||{});let g=this.buildWhereClause(m,d$1,u,n$1),y=d$1.fields.find(h=>h.name==="status"),p$1=y?.type==="select"&&Array.isArray(y.options)&&y.options.some(h=>h.value==="published");!c&&u.status&&p$1&&g.push(n(u.status,"published"));let A=this.parseSort(s),_=!c&&u.status&&p$1?{...m,status:"published"}:m,ue=await this.count({collection:i,where:_,tenantId:n$1}),fe=(r-1)*a,P=[];try{let h=u[A.field]||u.createdAt||u.id,R=A.direction==="asc"?h:M$1(h),E=this.client.select().from(u);g.length>0&&(E=E.where(p(...g))),P=await E.orderBy(R).limit(a).offset(fe);}catch(h){console.error("[DrizzleAdapter] Query error:",h);}let N=P.map(h=>this.processResult(h,d$1));return this.tenantContext&&!this.tenantContext.isSuperAdmin&&(N=N.filter(h=>d(h,i,this.tenantContext,b$1))),c&&(N=await Promise.all(N.map(async h=>{let R=await this.executeRaw(J`
22
+ `)));else for(let e of i)await this.executeRaw(J.raw(e));for(let e of t){let s=this.getTableName(e.slug);s==="users"||s==="audit_logs"||await this.syncTableColumns(e,s);}}getColumnSqlDefinition(t,i){let e=L(t,i),s=t.name.replace(/-/g,"_").replace(/([A-Z])/g,"_$1").toLowerCase(),n=this.columnSqlType(e,i);return `"${s}" ${n} DEFAULT NULL`}columnSqlType(t,i){if(i==="sqlite")switch(t){case "varchar":return "TEXT";case "text":return "TEXT";case "integer":return "INTEGER";case "decimal":case "numeric":return "NUMERIC";case "boolean":return "INTEGER";case "timestamp":return "TEXT";case "jsonb":return "TEXT";default:return "TEXT"}switch(t){case "varchar":return "VARCHAR(255)";case "text":return "TEXT";case "integer":return "INTEGER";case "decimal":case "numeric":return "DECIMAL";case "boolean":return "BOOLEAN";case "timestamp":return "TIMESTAMP";case "jsonb":return "JSONB";default:return "TEXT"}}getExpectedColumnDefs(t,i){let e={},s=t.slug.startsWith("_globals_"),n=t.fields.some(c=>c.name==="createdAt"),r=t.fields.some(c=>c.name==="updatedAt"),a=t.fields.some(c=>c.name==="status"),o=t.fields.some(c=>c.name==="hasDraft");this.dialect==="postgres"?(e.id=s?'"id" TEXT PRIMARY KEY':'"id" UUID PRIMARY KEY DEFAULT gen_random_uuid()',n||(e.created_at='"created_at" TIMESTAMP DEFAULT NULL'),r||(e.updated_at='"updated_at" TIMESTAMP DEFAULT NULL'),a||(e.status='"status" VARCHAR(20) DEFAULT NULL'),o||(e.hasDraft='"hasDraft" BOOLEAN DEFAULT NULL')):(e.id='"id" TEXT PRIMARY KEY',n||(e.created_at='"created_at" TEXT DEFAULT NULL'),r||(e.updated_at='"updated_at" TEXT DEFAULT NULL'),a||(e.status='"status" TEXT DEFAULT NULL'),o||(e.hasDraft='"hasDraft" INTEGER DEFAULT NULL'));for(let c of t.fields){if(!c.name||c.name==="id")continue;let d=this.getColumnSqlDefinition(c,this.dialect),u=c.name.replace(/-/g,"_").replace(/([A-Z])/g,"_$1").toLowerCase();e[u]=d;}return e}async syncTableColumns(t,i){let e;try{if(this.dialect==="postgres"){let r=await this.executeRaw(J`SELECT column_name, data_type, character_maximum_length FROM information_schema.columns WHERE table_name = ${i}`);e=new Map(r.map(a=>[a.column_name,{type:a.data_type,maxLen:a.character_maximum_length}]));}else {let r=await this.executeRaw(J`PRAGMA table_info("${J.raw(i)}")`);e=new Map(r.map(a=>[a.name,{type:a.type,maxLen:null}]));}}catch{return}let s=this.getExpectedColumnDefs(t,i),n=Object.keys(s).filter(r=>!e.has(r));if(n.length>0){let r=n.map(a=>`ALTER TABLE "${i}" ADD COLUMN ${s[a]}`);await this.executeRaw(J.raw(r.join(`;
23
+ `)));}if(this.dialect==="postgres")for(let r of t.fields){if(!r.name||r.name==="id")continue;let a=L(r,this.dialect),o=r.name.replace(/-/g,"_").replace(/([A-Z])/g,"_$1").toLowerCase(),c=e.get(o);!c||c.type!=="character varying"||(a==="text"?await this.executeRaw(J.raw(`ALTER TABLE "${i}" ALTER COLUMN "${o}" TYPE TEXT`)):a==="jsonb"&&(await this.executeRaw(J.raw(`ALTER TABLE "${i}" ALTER COLUMN "${o}" DROP DEFAULT`)),await this.executeRaw(J.raw(`ALTER TABLE "${i}" ALTER COLUMN "${o}" TYPE JSONB USING (CASE WHEN "${o}" IS NULL THEN NULL WHEN "${o}"::text ~ '^\\s*\\{' THEN "${o}"::jsonb ELSE jsonb_build_object('id', "${o}"::text) END)`))));}}generateCreateColumns(t){let i=[];for(let e of t.fields){if(!e.name||e.name==="id")continue;let s=L(e,this.dialect),n=e.name.replace(/-/g,"_").replace(/([A-Z])/g,"_$1").toLowerCase(),r=e.required?"NOT NULL":"DEFAULT NULL",a;if(this.dialect==="sqlite")switch(s){case "varchar":case "text":a=`TEXT ${r}`;break;case "integer":a=`INTEGER ${r}`;break;case "decimal":case "numeric":a=`NUMERIC ${r}`;break;case "boolean":a=`INTEGER ${r}`;break;case "timestamp":a=`TEXT ${r}`;break;case "jsonb":a=`TEXT ${r}`;break;default:a=`TEXT ${r}`;}else switch(s){case "varchar":a=`VARCHAR(255) ${r}`;break;case "integer":a=`INTEGER ${r}`;break;case "decimal":a=`DECIMAL ${r}`;break;case "boolean":a=`BOOLEAN ${r}`;break;case "timestamp":a=`TIMESTAMP ${r}`;break;case "jsonb":a=`JSONB ${r}`;break;default:a=`TEXT ${r}`;}i.push(`"${n}" ${a}`);}return i.join(`,
24
+ `)+(i.length>0?",":"")}async disconnect(){this.connected=false;}async find(t){let{collection:i,where:e={},sort:s,limit:n$1=10,page:r=1,tenantId:a,select:o,draft:c}=t,d$1=this.getCollection(i),u=this.getTable(i),m={...e};this.tenantContext&&d$1.tenantScoped&&(m=c$1({where:m},i,this.tenantContext,b$1).where||{});let g=this.buildWhereClause(m,d$1,u,a),y=d$1.fields.find(h=>h.name==="status"),p$1=y?.type==="select"&&Array.isArray(y.options)&&y.options.some(h=>h.value==="published");!c&&u.status&&p$1&&g.push(n(u.status,"published"));let b=this.parseSort(s),_=!c&&u.status&&p$1?{...m,status:"published"}:m,ue=await this.count({collection:i,where:_,tenantId:a}),fe=(r-1)*n$1,P=[];try{let h=u[b.field]||u.createdAt||u.id,R=b.direction==="asc"?h:M$1(h),A=this.client.select().from(u);g.length>0&&(A=A.where(p(...g))),P=await A.orderBy(R).limit(n$1).offset(fe);}catch(h){console.error("[DrizzleAdapter] Query error:",h);}let N=P.map(h=>this.processResult(h,d$1));return this.tenantContext&&!this.tenantContext.isSuperAdmin&&(N=N.filter(h=>d(h,i,this.tenantContext,b$1))),c&&(N=await Promise.all(N.map(async h=>{let R=await this.executeRaw(J`
25
25
  SELECT * FROM kyro_versions
26
26
  WHERE collection_slug = ${i}
27
27
  AND document_id = ${h.id}
28
28
  ORDER BY created_at DESC
29
29
  LIMIT 1
30
- `);if(R.length>0){let E=R[0],pe=typeof E.data=="string"?JSON.parse(E.data):E.data;return {...h,...pe,status:h.status}}return h}))),{docs:N,...this.calculatePagination(r,a,ue)}}async findByID(t){let{collection:i,id:e,tenantId:s,draft:a}=t,r=this.getCollection(i),n$1=this.getTable(i),o=this.dialect==="postgres"&&typeof e=="string"?D(e):e;if(this.tenantContext&&r.tenantScoped){let p={id:o,tenantId:this.tenantContext.tenantId};if(!d(p,i,this.tenantContext,b$1))return null}let c=[n(n$1.id,o)];s&&n$1.tenantId&&c.push(n(n$1.tenantId,s));let d$1=r.fields.find(p=>p.name==="status"),u=d$1?.type==="select"&&Array.isArray(d$1.options)&&d$1.options.some(p=>p.value==="published");!a&&n$1.status&&u&&c.push(n(n$1.status,"published"));let m=c.length>1?p(...c):c[0],g=await this.client.select().from(n$1).where(m);if(g.length===0)return null;let y=this.processResult(g[0],r);if(a){let p=await this.executeRaw(J`
30
+ `);if(R.length>0){let A=R[0],pe=typeof A.data=="string"?JSON.parse(A.data):A.data;return {...h,...pe,status:h.status,_hasUnpublishedChanges:A.status==="draft"}}return h}))),{docs:N,...this.calculatePagination(r,n$1,ue)}}async findByID(t){let{collection:i,id:e,tenantId:s,draft:n$1}=t,r=this.getCollection(i),a=this.getTable(i),o=this.dialect==="postgres"&&typeof e=="string"?D(e):e;if(this.tenantContext&&r.tenantScoped){let p={id:o,tenantId:this.tenantContext.tenantId};if(!d(p,i,this.tenantContext,b$1))return null}let c=[n(a.id,o)];s&&a.tenantId&&c.push(n(a.tenantId,s));let d$1=r.fields.find(p=>p.name==="status"),u=d$1?.type==="select"&&Array.isArray(d$1.options)&&d$1.options.some(p=>p.value==="published");!n$1&&a.status&&u&&c.push(n(a.status,"published"));let m=c.length>1?p(...c):c[0],g=await this.client.select().from(a).where(m);if(g.length===0)return null;let y=this.processResult(g[0],r);if(n$1){let p=await this.executeRaw(J`
31
31
  SELECT * FROM kyro_versions
32
32
  WHERE collection_slug = ${i}
33
33
  AND document_id = ${y.id}
34
34
  ORDER BY created_at DESC
35
35
  LIMIT 1
36
- `);if(p.length>0){let A=p[0],_=typeof A.data=="string"?JSON.parse(A.data):A.data;y={...y,..._,status:y.status};}}return y}async create(t){let{collection:i,data:e,tenantId:s}=t,a=this.getCollection(i),r=this.getTable(i),n=this.prepareData(e,a);s&&a.tenantScoped&&(n.tenantId=s);let o=await this.client.insert(r).values(n).returning();return this.processResult(o[0],a)}async update(t){let{collection:i,id:e,data:s,tenantId:a}=t,r=this.getCollection(i),n$1=this.getTable(i),o=this.prepareData(s,r),c=this.dialect==="postgres"&&typeof e=="string"?D(e):e,d=[n(n$1.id,c)];a&&n$1.tenantId&&d.push(n(n$1.tenantId,a));let u=await this.client.update(n$1).set(o).where(p(...d)).returning();if(u.length===0)throw new Error(`Document not found: ${i}/${e}`);return this.processResult(u[0],r)}async delete(t){let{collection:i,id:e,tenantId:s}=t,a=this.getCollection(i),r=this.getTable(i),n$1=this.dialect==="postgres"&&typeof e=="string"?D(e):e,o=[n(r.id,n$1)];s&&r.tenantId&&o.push(n(r.tenantId,s));let c=await this.client.delete(r).where(p(...o)).returning();if(c.length===0)throw new Error(`Document not found: ${i}/${e}`);return this.processResult(c[0],a)}async count(t){let{collection:i,where:e={},tenantId:s}=t,a=this.getCollection(i),r=this.getTable(i),n=this.buildWhereClause(e,a,r,s);try{let o=this.client.select({count:J`count(*)`}).from(r);n.length>0&&(o=o.where(p(...n)));let c=await o;return Number(c[0]?.count||0)}catch{return 0}}async findOne(t){let{collection:i,where:e={},tenantId:s,draft:a}=t;if(i.startsWith("_globals_")){let n$1=i.replace("_globals_",""),o=this.globals.get(n$1);if(!o)throw new Error(`Global "${n$1}" not found`);let c=this.getTable(i),d=this.client.select().from(c),u=o.fields.find(p=>p.name==="status"),m=u?.type==="select"&&Array.isArray(u.options)&&u.options.some(p=>p.value==="published");!a&&c.status&&m&&(d=d.where(n(c.status,"published")));let g=await d.limit(1);if(g.length===0)return null;let y=this.processResult(g[0],o);if(a){let p=await this.executeRaw(J`
36
+ `);if(p.length>0){let b=p[0],_=typeof b.data=="string"?JSON.parse(b.data):b.data;y={...y,..._,status:y.status,_hasUnpublishedChanges:b.status==="draft"};}}return y}async create(t){let{collection:i,data:e,tenantId:s}=t,n=this.getCollection(i),r=this.getTable(i),a=this.prepareData(e,n);s&&n.tenantScoped&&(a.tenantId=s);let o=await this.client.insert(r).values(a).returning();return this.processResult(o[0],n)}async update(t){let{collection:i,id:e,data:s,tenantId:n$1}=t,r=this.getCollection(i),a=this.getTable(i),o=this.prepareData(s,r),c=this.dialect==="postgres"&&typeof e=="string"?D(e):e,d=[n(a.id,c)];n$1&&a.tenantId&&d.push(n(a.tenantId,n$1));let u=await this.client.update(a).set(o).where(p(...d)).returning();if(u.length===0)throw new Error(`Document not found: ${i}/${e}`);return this.processResult(u[0],r)}async delete(t){let{collection:i,id:e,tenantId:s}=t,n$1=this.getCollection(i),r=this.getTable(i),a=this.dialect==="postgres"&&typeof e=="string"?D(e):e,o=[n(r.id,a)];s&&r.tenantId&&o.push(n(r.tenantId,s));let c=await this.client.delete(r).where(p(...o)).returning();if(c.length===0)throw new Error(`Document not found: ${i}/${e}`);return this.processResult(c[0],n$1)}async count(t){let{collection:i,where:e={},tenantId:s}=t,n=this.getCollection(i),r=this.getTable(i),a=this.buildWhereClause(e,n,r,s);try{let o=this.client.select({count:J`count(*)`}).from(r);a.length>0&&(o=o.where(p(...a)));let c=await o;return Number(c[0]?.count||0)}catch{return 0}}async findOne(t){let{collection:i,where:e={},tenantId:s,draft:n$1}=t;if(i.startsWith("_globals_")){let a=i.replace("_globals_",""),o=this.globals.get(a);if(!o)throw new Error(`Global "${a}" not found`);let c=this.getTable(i),d=this.client.select().from(c),u=o.fields.find(p=>p.name==="status"),m=u?.type==="select"&&Array.isArray(u.options)&&u.options.some(p=>p.value==="published");!n$1&&c.status&&m&&(d=d.where(n(c.status,"published")));let g=await d.limit(1);if(g.length===0)return null;let y=this.processResult(g[0],o);if(n$1){let p=await this.executeRaw(J`
37
37
  SELECT * FROM kyro_versions
38
38
  WHERE collection_slug = ${i}
39
- AND document_id = ${n$1}
39
+ AND document_id = ${a}
40
40
  ORDER BY created_at DESC
41
41
  LIMIT 1
42
- `);if(p.length>0){let A=p[0],_=typeof A.data=="string"?JSON.parse(A.data):A.data;y={...y,..._,status:y.status};}}return y}return (await this.find({...t,limit:1})).docs[0]||null}async findVersions(t){await this.ensureVersionsTable();let{collection:i,documentId:e,limit:s=10,page:a=1,tenantId:r}=t,n=(a-1)*s,o=this.getCollection(i),c=await this.executeRaw(J`
42
+ `);if(p.length>0){let b=p[0],_=typeof b.data=="string"?JSON.parse(b.data):b.data;y={...y,..._,status:y.status,_hasUnpublishedChanges:b.status==="draft"};}}return y}return (await this.find({...t,limit:1})).docs[0]||null}async findVersions(t){await this.ensureVersionsTable();let{collection:i,documentId:e,limit:s=10,page:n=1,tenantId:r}=t,a=(n-1)*s,o=this.getCollection(i),c=await this.executeRaw(J`
43
43
  SELECT count(*) as count
44
44
  FROM kyro_versions
45
45
  WHERE collection_slug = ${i}
@@ -55,27 +55,27 @@ g();function D(f){if(typeof f!="string")return f;let t=f.replace(/-/g,"").toLowe
55
55
  ${r&&o.tenantScoped?J`AND tenant_id = ${r}`:J``}
56
56
  ORDER BY created_at DESC
57
57
  LIMIT ${s}
58
- OFFSET ${n}
59
- `)).map(m=>({...m,data:typeof m.data=="string"?JSON.parse(m.data):m.data})),...this.calculatePagination(a,s,d)}}async findVersionByID(t){await this.ensureVersionsTable();let i=this.getCollection(t.collection),e=await this.executeRaw(J`
58
+ OFFSET ${a}
59
+ `)).map(m=>({...m,data:typeof m.data=="string"?JSON.parse(m.data):m.data})),...this.calculatePagination(n,s,d)}}async findVersionByID(t){await this.ensureVersionsTable();let i=this.getCollection(t.collection),e=await this.executeRaw(J`
60
60
  SELECT * FROM kyro_versions
61
61
  WHERE id = ${t.versionId}
62
62
  AND collection_slug = ${t.collection}
63
63
  ${t.tenantId&&i.tenantScoped?J`AND tenant_id = ${t.tenantId}`:J``}
64
64
  LIMIT 1
65
- `);if(e.length===0)return null;let s=e[0];return {...s,data:typeof s.data=="string"?JSON.parse(s.data):s.data}}async createVersion(t){await this.ensureVersionsTable();let i=this.getCollection(t.collection),e=new Date().toISOString();if(t.autosave){let a=await this.executeRaw(J`
65
+ `);if(e.length===0)return null;let s=e[0];return {...s,data:typeof s.data=="string"?JSON.parse(s.data):s.data}}async createVersion(t){await this.ensureVersionsTable();let i=this.getCollection(t.collection),e=new Date().toISOString();if(t.autosave){let n=await this.executeRaw(J`
66
66
  SELECT * FROM kyro_versions
67
67
  WHERE collection_slug = ${t.collection}
68
68
  AND document_id = ${t.documentId}
69
69
  AND autosave = 1
70
70
  ${t.tenantId&&i.tenantScoped?J`AND tenant_id = ${t.tenantId}`:J``}
71
71
  LIMIT 1
72
- `);if(a.length>0)return await this.executeRaw(J`
72
+ `);if(n.length>0)return await this.executeRaw(J`
73
73
  UPDATE kyro_versions
74
74
  SET data = ${JSON.stringify(t.data)},
75
75
  status = ${t.status},
76
76
  updated_at = ${e}
77
- WHERE id = ${a[0].id}
78
- `),this.findVersionByID({collection:t.collection,versionId:a[0].id,tenantId:t.tenantId})}let s=Math.random().toString(36).substring(2,15);if(await this.executeRaw(J`
77
+ WHERE id = ${n[0].id}
78
+ `),this.findVersionByID({collection:t.collection,versionId:n[0].id,tenantId:t.tenantId})}let s=Math.random().toString(36).substring(2,15);if(await this.executeRaw(J`
79
79
  INSERT INTO kyro_versions (
80
80
  id, collection_slug, document_id, tenant_id, data, status, autosave, created_by, change_description, created_at, updated_at
81
81
  ) VALUES (
@@ -83,7 +83,7 @@ g();function D(f){if(typeof f!="string")return f;let t=f.replace(/-/g,"").toLowe
83
83
  ${JSON.stringify(t.data)}, ${t.status}, ${t.autosave?1:0}, ${t.createdBy||null},
84
84
  ${t.changeDescription||null}, ${e}, ${e}
85
85
  )
86
- `),!t.autosave){let a=this.getCollection(t.collection);a.versions?.maxPerDoc&&await this.deleteVersions({collection:t.collection,documentId:t.documentId,keepLatest:a.versions.maxPerDoc,tenantId:t.tenantId});}return this.findVersionByID({collection:t.collection,versionId:s,tenantId:t.tenantId})}async updateLatestVersion(t){return this.createVersion({...t,autosave:true})}async deleteVersions(t){await this.ensureVersionsTable();let i=this.getCollection(t.collection);if(t.keepLatest){let s=(await this.executeRaw(J`
86
+ `),!t.autosave){let n=this.getCollection(t.collection);n.versions?.maxPerDoc&&await this.deleteVersions({collection:t.collection,documentId:t.documentId,keepLatest:n.versions.maxPerDoc,tenantId:t.tenantId});}return this.findVersionByID({collection:t.collection,versionId:s,tenantId:t.tenantId})}async updateLatestVersion(t){return this.createVersion({...t,autosave:true})}async deleteVersions(t){await this.ensureVersionsTable();let i=this.getCollection(t.collection);if(t.keepLatest){let s=(await this.executeRaw(J`
87
87
  SELECT id FROM kyro_versions
88
88
  WHERE collection_slug = ${t.collection}
89
89
  AND document_id = ${t.documentId}
@@ -91,18 +91,18 @@ g();function D(f){if(typeof f!="string")return f;let t=f.replace(/-/g,"").toLowe
91
91
  ${t.tenantId&&i.tenantScoped?J`AND tenant_id = ${t.tenantId}`:J``}
92
92
  ORDER BY created_at DESC
93
93
  LIMIT ${t.keepLatest}
94
- `)).map(a=>a.id);s.length>0&&await this.executeRaw(J`
94
+ `)).map(n=>n.id);s.length>0&&await this.executeRaw(J`
95
95
  DELETE FROM kyro_versions
96
96
  WHERE collection_slug = ${t.collection}
97
97
  AND document_id = ${t.documentId}
98
98
  AND autosave = 0
99
- AND id NOT IN (${J.join(s.map(a=>J`${a}`),J`, `)})
99
+ AND id NOT IN (${J.join(s.map(n=>J`${n}`),J`, `)})
100
100
  `);}else await this.executeRaw(J`
101
101
  DELETE FROM kyro_versions
102
102
  WHERE collection_slug = ${t.collection}
103
103
  AND document_id = ${t.documentId}
104
104
  ${t.tenantId&&i.tenantScoped?J`AND tenant_id = ${t.tenantId}`:J``}
105
- `);}getTable(t){let i=this.getTableName(t),e=this.schema[i];if(!e)throw new Error(`Table "${i}" not found in schema`);return e}buildWhereClause(t$1,i,e,s$1){let a=[];s$1&&i.tenantScoped&&e.tenantId&&a.push(n(e.tenantId,s$1));for(let[r,n$1]of Object.entries(t$1))if(r==="id"&&this.dialect==="postgres"&&(typeof n$1=="string"?n$1=D(n$1):n$1&&typeof n$1=="object"&&(n$1.equals!==void 0&&typeof n$1.equals=="string"&&(n$1={...n$1,equals:D(n$1.equals)}),n$1.in&&Array.isArray(n$1.in)&&(n$1={...n$1,in:n$1.in.map(o=>typeof o=="string"?D(o):o)}))),r==="AND"&&Array.isArray(n$1)){let o=n$1.map(c=>this.buildWhereClause(c,i,e)).flat().filter(Boolean);o.length>0&&a.push(p(...o));}else if(r==="OR"&&Array.isArray(n$1)){let o=n$1.map(c=>this.buildWhereClause(c,i,e)).flat().filter(Boolean);o.length>0&&a.push(q(...o));}else if(typeof n$1=="object"&&n$1!==null&&!Array.isArray(n$1)){let o$1=e[r];if(!o$1)continue;n$1.equals!==void 0&&a.push(n(o$1,n$1.equals)),n$1.not_equals!==void 0&&a.push(o(o$1,n$1.not_equals)),n$1.in&&Array.isArray(n$1.in)&&a.push(w(o$1,n$1.in)),n$1.like!==void 0&&a.push(E(o$1,n$1.like)),n$1.contains!==void 0&&a.push(E(o$1,`%${n$1.contains}%`)),n$1.greater_than!==void 0&&a.push(s(o$1,n$1.greater_than)),n$1.greater_than_equal!==void 0&&a.push(t(o$1,n$1.greater_than_equal)),n$1.less_than!==void 0&&a.push(u(o$1,n$1.less_than)),n$1.less_than_equal!==void 0&&a.push(v(o$1,n$1.less_than_equal));}else {let o=e[r];o&&a.push(n(o,n$1));}return a}processResult(t,i){if(!t)return null;let e={...t};for(let s of Object.keys(e))/^\d+$/.test(s)&&delete e[s];t.id&&(e.id=String(t.id));for(let s of i.fields){if(!s.name)continue;let a=s.name.replace(/-/g,"_").replace(/([A-Z])/g,"_$1").toLowerCase();a!==s.name&&e[a]!==void 0&&e[s.name]===void 0&&(e[s.name]=e[a],delete e[a]);}for(let s of i.fields){if(["json","richtext","array","group","blocks","upload","image","list","relationship-block"].includes(s.type)){let a=s;if(e[a.name]&&typeof e[a.name]=="string")try{let r=JSON.parse(e[a.name]);e[a.name]=r;}catch{}if(s.type==="blocks"&&e[a.name]&&Array.isArray(e[a.name])){let r=a.blocks||[];e[a.name]=le(e[a.name],r);}}if(s.type==="tabs"&&"tabs"in s&&s.name){if(typeof e[s.name]=="object"&&e[s.name]!==null&&!Array.isArray(e[s.name])){for(let r of s.tabs)for(let n of r.fields)if((n.type==="upload"||n.type==="image")&&n.name){let o=e[s.name][n.name];if(typeof o=="string")try{let c=JSON.parse(o);e[s.name][n.name]=Array.isArray(c)?c.map(d=>d&&typeof d=="object"&&typeof d.id=="string"?d.id:String(d||"")):typeof c.id=="string"?c.id:String(c.id||"");}catch{}else o&&typeof o=="object"&&(e[s.name][n.name]=Array.isArray(o)?o.map(c=>c&&typeof c=="object"&&typeof c.id=="string"?c.id:String(c||"")):typeof o.id=="string"?o.id:String(o.id||""));}continue}if(typeof e[s.name]=="string")try{let r=JSON.parse(e[s.name]);if(typeof r=="object"&&r!==null){e[s.name]=r;continue}}catch{}let a={};for(let r of s.tabs)for(let n of r.fields)if(n.name&&e[n.name]!==void 0){let o=e[n.name];if(["json","richtext","array","group","blocks","upload","image","list","relationship-block"].includes(n.type)){if(o&&typeof o=="string")try{o=JSON.parse(o);}catch{}(n.type==="upload"||n.type==="image")&&o&&typeof o=="object"&&(o=Array.isArray(o)?o.map(c=>c&&typeof c=="object"&&typeof c.id=="string"?c.id:String(c||"")):typeof o.id=="string"?o.id:String(o.id||""));}a[n.name]=o,delete e[n.name];}e[s.name]=a;}}return e.createdAt&&(e.createdAt=new Date(e.createdAt).toISOString()),e.updatedAt&&(e.updatedAt=new Date(e.updatedAt).toISOString()),a$3(e)}async ensureVersionsTable(){if(this.versionsTableReady)return;let t;this.dialect==="sqlite"?t=`
105
+ `);}getTable(t){let i=this.getTableName(t),e=this.schema[i];if(!e)throw new Error(`Table "${i}" not found in schema`);return e}buildWhereClause(t$1,i,e,s$1){let n$1=[];s$1&&i.tenantScoped&&e.tenantId&&n$1.push(n(e.tenantId,s$1));for(let[r,a]of Object.entries(t$1))if(r==="id"&&this.dialect==="postgres"&&(typeof a=="string"?a=D(a):a&&typeof a=="object"&&(a.equals!==void 0&&typeof a.equals=="string"&&(a={...a,equals:D(a.equals)}),a.in&&Array.isArray(a.in)&&(a={...a,in:a.in.map(o=>typeof o=="string"?D(o):o)}))),r==="AND"&&Array.isArray(a)){let o=a.map(c=>this.buildWhereClause(c,i,e)).flat().filter(Boolean);o.length>0&&n$1.push(p(...o));}else if(r==="OR"&&Array.isArray(a)){let o=a.map(c=>this.buildWhereClause(c,i,e)).flat().filter(Boolean);o.length>0&&n$1.push(q(...o));}else if(typeof a=="object"&&a!==null&&!Array.isArray(a)){let o$1=e[r];if(!o$1)continue;a.equals!==void 0&&n$1.push(n(o$1,a.equals)),a.not_equals!==void 0&&n$1.push(o(o$1,a.not_equals)),a.in&&Array.isArray(a.in)&&n$1.push(w(o$1,a.in)),a.like!==void 0&&n$1.push(E(o$1,a.like)),a.contains!==void 0&&n$1.push(E(o$1,`%${a.contains}%`)),a.greater_than!==void 0&&n$1.push(s(o$1,a.greater_than)),a.greater_than_equal!==void 0&&n$1.push(t(o$1,a.greater_than_equal)),a.less_than!==void 0&&n$1.push(u(o$1,a.less_than)),a.less_than_equal!==void 0&&n$1.push(v(o$1,a.less_than_equal));}else {let o=e[r];o&&n$1.push(n(o,a));}return n$1}processResult(t,i){if(!t)return null;let e={...t};for(let s of Object.keys(e))/^\d+$/.test(s)&&delete e[s];t.id&&(e.id=String(t.id));for(let s of i.fields){if(!s.name)continue;let n=s.name.replace(/-/g,"_").replace(/([A-Z])/g,"_$1").toLowerCase();n!==s.name&&e[n]!==void 0&&e[s.name]===void 0&&(e[s.name]=e[n],delete e[n]);}for(let s of i.fields){if(["json","richtext","array","group","blocks","upload","image","list","relationship-block"].includes(s.type)){let n=s;if(e[n.name]&&typeof e[n.name]=="string")try{let r=JSON.parse(e[n.name]);e[n.name]=r;}catch{}if(s.type==="blocks"&&e[n.name]&&Array.isArray(e[n.name])){let r=n.blocks||[];e[n.name]=le(e[n.name],r);}}if(s.type==="tabs"&&"tabs"in s&&s.name){if(typeof e[s.name]=="object"&&e[s.name]!==null&&!Array.isArray(e[s.name])){for(let r of s.tabs)for(let a of r.fields)if((a.type==="upload"||a.type==="image")&&a.name){let o=e[s.name][a.name];if(typeof o=="string")try{let c=JSON.parse(o);e[s.name][a.name]=Array.isArray(c)?c.map(d=>d&&typeof d=="object"&&typeof d.id=="string"?d.id:String(d||"")):typeof c.id=="string"?c.id:String(c.id||"");}catch{}else o&&typeof o=="object"&&(e[s.name][a.name]=Array.isArray(o)?o.map(c=>c&&typeof c=="object"&&typeof c.id=="string"?c.id:String(c||"")):typeof o.id=="string"?o.id:String(o.id||""));}continue}if(typeof e[s.name]=="string")try{let r=JSON.parse(e[s.name]);if(typeof r=="object"&&r!==null){e[s.name]=r;continue}}catch{}let n={};for(let r of s.tabs)for(let a of r.fields)if(a.name&&e[a.name]!==void 0){let o=e[a.name];if(["json","richtext","array","group","blocks","upload","image","list","relationship-block"].includes(a.type)){if(o&&typeof o=="string")try{o=JSON.parse(o);}catch{}(a.type==="upload"||a.type==="image")&&o&&typeof o=="object"&&(o=Array.isArray(o)?o.map(c=>c&&typeof c=="object"&&typeof c.id=="string"?c.id:String(c||"")):typeof o.id=="string"?o.id:String(o.id||""));}n[a.name]=o,delete e[a.name];}e[s.name]=n;}}return e.createdAt&&(e.createdAt=new Date(e.createdAt).toISOString()),e.updatedAt&&(e.updatedAt=new Date(e.updatedAt).toISOString()),a$3(e)}async ensureVersionsTable(){if(this.versionsTableReady)return;let t;this.dialect==="sqlite"?t=`
106
106
  CREATE TABLE IF NOT EXISTS kyro_versions (
107
107
  id text PRIMARY KEY,
108
108
  collection_slug text NOT NULL,
@@ -130,5 +130,5 @@ g();function D(f){if(typeof f!="string")return f;let t=f.replace(/-/g,"").toLowe
130
130
  created_at text NOT NULL,
131
131
  updated_at text NOT NULL
132
132
  )
133
- `,await this.executeRaw(J.raw(t));try{this.dialect==="postgres"?await this.executeRaw(J.raw("ALTER TABLE kyro_versions ADD COLUMN IF NOT EXISTS autosave integer NOT NULL DEFAULT 0")):await this.executeRaw(J.raw("ALTER TABLE kyro_versions ADD COLUMN autosave integer NOT NULL DEFAULT 0"));}catch{}this.versionsTableReady=true;}async execute(t){return this.executeRaw(t)}async executeRaw(t){let i="",e=[];if(typeof t=="string")i=t;else if(t&&(t.queryChunks||t.decoder))if(this.dialect==="postgres"){let a=new a$4().sqlToQuery(t);i=a.sql,e=a.params;}else {let a=new h().sqlToQuery(t);i=a.sql,e=a.params;}else if(t&&typeof t.toSQL=="function"){let a=t.toSQL();i=a.sql,e=a.params||[];}else i=String(t);let s=this.rawClient||this.client;if(s?.prepare&&typeof s.prepare=="function"){let a=s.prepare(i);return (e.length>0?await a.bind(...e).all():await a.all()).results||[]}if(typeof this.client?.execute=="function"){let a=await this.client.execute(t);return Array.isArray(a)?a:Array.isArray(a?.rows)?a.rows:Array.isArray(a?.[0])?a[0]:[]}return []}};function $e(f){return new M(f)}g();var x;function Ee(){return x||(x=createRequire("file:///")("node:sqlite").DatabaseSync,x)}function we(){return process.env.DB_TYPE==="postgres"?"postgres":"sqlite"}function de(){return randomBytes(16).toString("hex")}async function Pe(){let f$1=we();if(f$1==="sqlite"){let r=resolve(process.cwd(),"data","kyro.db");await mkdir(dirname(r),{recursive:true});let n=new(Ee())(r);return n.exec("PRAGMA journal_mode = WAL"),{db:n,dialect:f$1,genId:de}}let t=process.env.DATABASE_URL||"postgresql://postgres:postgres@localhost:5432/kyro_cms",i=parseInt(process.env.DB_POOL_MAX||"10",10),e=process.env.DB_SSL==="true",s=a$5(t,{max:i,ssl:e?"require":false,onnotice:()=>{}});return {db:f(s),dialect:f$1,genId:de}}async function je(f,t){}async function Be(f){let{roles:t}=await import('./schema-YFMSJK2P.js');await f.insert(t).values({name:"super_admin",level:100,inherits:[],description:"Full system access across all tenants",isSystem:true}).onConflictDoNothing();}
133
+ `,await this.executeRaw(J.raw(t));try{this.dialect==="postgres"?await this.executeRaw(J.raw("ALTER TABLE kyro_versions ADD COLUMN IF NOT EXISTS autosave integer NOT NULL DEFAULT 0")):await this.executeRaw(J.raw("ALTER TABLE kyro_versions ADD COLUMN autosave integer NOT NULL DEFAULT 0"));}catch{}this.versionsTableReady=true;}async execute(t){return this.executeRaw(t)}async executeRaw(t){let i="",e=[];if(typeof t=="string")i=t;else if(t&&(t.queryChunks||t.decoder))if(this.dialect==="postgres"){let n=new a$4().sqlToQuery(t);i=n.sql,e=n.params;}else {let n=new h().sqlToQuery(t);i=n.sql,e=n.params;}else if(t&&typeof t.toSQL=="function"){let n=t.toSQL();i=n.sql,e=n.params||[];}else i=String(t);let s=this.rawClient||this.client;if(s?.prepare&&typeof s.prepare=="function"){let n=s.prepare(i);return (e.length>0?await n.bind(...e).all():await n.all()).results||[]}if(typeof this.client?.execute=="function"){let n=await this.client.execute(t);return Array.isArray(n)?n:Array.isArray(n?.rows)?n.rows:Array.isArray(n?.[0])?n[0]:[]}return []}};function $e(f){return new M(f)}g();var x;function Ee(){return x||(x=createRequire("file:///")("node:sqlite").DatabaseSync,x)}function we(){return process.env.DB_TYPE==="postgres"?"postgres":"sqlite"}function de(){return randomBytes(16).toString("hex")}async function Pe(){let f$1=we();if(f$1==="sqlite"){let r=resolve(process.cwd(),"data","kyro.db");await mkdir(dirname(r),{recursive:true});let a=new(Ee())(r);return a.exec("PRAGMA journal_mode = WAL"),{db:a,dialect:f$1,genId:de}}let t=process.env.DATABASE_URL||"postgresql://postgres:postgres@localhost:5432/kyro_cms",i=parseInt(process.env.DB_POOL_MAX||"10",10),e=process.env.DB_SSL==="true",s=a$5(t,{max:i,ssl:e?"require":false,onnotice:()=>{}});return {db:f(s),dialect:f$1,genId:de}}async function je(f,t){}async function Be(f){let{roles:t}=await import('./schema-YFMSJK2P.js');await f.insert(t).values({name:"super_admin",level:100,inherits:[],description:"Full system access across all tenants",isSystem:true}).onConflictDoNothing();}
134
134
  export{L as a,Ie as b,M as c,$e as d,de as e,Pe as f,je as g,Be as h};
@@ -0,0 +1,3 @@
1
+ import {a,c,b as b$1,d}from'./chunk-SLMIYECU.js';import {a as a$1}from'./chunk-P6JITOFF.js';import {a as a$2}from'./chunk-VVVCCB6R.js';import {g}from'./chunk-Y2YAKDEQ.js';import {randomBytes}from'crypto';if (typeof window === "undefined") { const { createRequire } = await import(/* @vite-ignore */ 'module'); createRequire(import.meta.url); }
2
+ g();g();var b=class extends a{dialect="mongodb";client;db;database;connectionString;constructor(o){if(super(),o.connectionString){this.connectionString=o.connectionString;try{let e=new URL(o.connectionString);this.database=e.pathname.replace(/^\//,"")||"kyro_cms";}catch{this.database="kyro_cms";}}else this.client=o.client,this.database=o.database;}async connect(){if(this.connectionString&&!this.client){let o;try{let e=await import('./lib-XXYYUPMW.js');o=e.MongoClient??e.default?.MongoClient;}catch{a$1(["mongodb"]);let n=await import('./lib-XXYYUPMW.js');o=n.MongoClient??n.default?.MongoClient;}this.client=new o(this.connectionString),await this.client.connect();}this.db=this.client.db(this.database),this.connected=true;}async disconnect(){this.client&&(await this.client.close(),this.connected=false);}getMongoCollection(o){if(!this.db)throw new Error("MongoDB not connected");return this.db.collection(o)}async find(o){let{collection:e,where:n={},sort:s,limit:t=10,page:i=1,tenantId:r,select:a,draft:d$1}=o,l=this.getCollectionConfig(e),f=this.getMongoCollection(e),g={...n};this.tenantContext&&l.tenantScoped&&(g=c({where:g},e,this.tenantContext,b$1).where||{});let u=this.buildFilter(g,l.tenantScoped?r:void 0),c$1=l.fields.find(p=>p.name==="status"),h=c$1?.type==="select"&&Array.isArray(c$1.options)&&c$1.options.some(p=>p.value==="published");!d$1&&h&&(u.status="published");let y=this.parseSort(s),O={[y.field]:y.direction==="asc"?1:-1},$=(i-1)*t,[x,M]=await Promise.all([f.find(u).sort(O).skip($).limit(t).project(this.buildProjection(a)).toArray(),f.countDocuments(u)]),C=x.map(p=>this.processResult(p,l));return this.tenantContext&&!this.tenantContext.isSuperAdmin&&(C=C.filter(p=>d(p,e,this.tenantContext,b$1))),d$1&&(C=await Promise.all(C.map(async p=>{let m=await this.getMongoCollection(`${e}_versions`).findOne({document_id:p.id},{sort:{createdAt:-1}});if(m){let P=typeof m.data=="string"?JSON.parse(m.data):m.data&&typeof m.data=="object"?m.data:{};return {...p,...P,status:p.status,_hasUnpublishedChanges:m.status==="draft"}}return p}))),{docs:C,...this.calculatePagination(i,t,M)}}async findByID(o){let{collection:e,id:n,tenantId:s,draft:t}=o,i=this.getCollectionConfig(e),r=this.getMongoCollection(e);if(this.tenantContext&&i.tenantScoped){let u={_id:n,tenantId:this.tenantContext.tenantId};if(!d(u,e,this.tenantContext,b$1))return null}let a={_id:n};s&&i.tenantScoped&&(a.tenantId=s);let d$1=i.fields.find(u=>u.name==="status"),l=d$1?.type==="select"&&Array.isArray(d$1.options)&&d$1.options.some(u=>u.value==="published");!t&&l&&(a.status="published");let f=await r.findOne(a);if(!f)return null;let g=this.processResult(f,i);if(t){let c=await this.getMongoCollection(`${e}_versions`).findOne({document_id:g.id},{sort:{createdAt:-1}});if(c){let h=typeof c.data=="string"?JSON.parse(c.data):c.data&&typeof c.data=="object"?c.data:{};g={...g,...h,status:g.status,_hasUnpublishedChanges:c.status==="draft"};}}return g}async create(o){let{collection:e,data:n,tenantId:s}=o,t=this.getCollectionConfig(e),i=this.getMongoCollection(e),r=this.prepareData(n,t),a=r.id||this.generateId();delete r.id;let d={...r,_id:a};return s&&t.tenantScoped&&(d.tenantId=s),await i.insertOne(d),this.processResult(d,t)}async update(o){let{collection:e,id:n,data:s,tenantId:t}=o,i=this.getCollectionConfig(e),r=this.getMongoCollection(e),a={_id:n};t&&i.tenantScoped&&(a.tenantId=t);let d=this.prepareData(s,i),l=await r.findOneAndUpdate(a,{$set:d},{returnDocument:"after"});if(!l)throw new Error(`Document not found: ${e}/${n}`);return this.processResult(l,i)}async delete(o){let{collection:e,id:n,tenantId:s}=o,t=this.getCollectionConfig(e),i=this.getMongoCollection(e),r={_id:n};s&&t.tenantScoped&&(r.tenantId=s);let a=await i.findOneAndDelete(r);if(!a)throw new Error(`Document not found: ${e}/${n}`);return this.processResult(a,t)}async count(o){let{collection:e,where:n={},tenantId:s}=o,t=this.getCollectionConfig(e),i=this.getMongoCollection(e),r=this.buildFilter(n,t.tenantScoped?s:void 0);return i.countDocuments(r)}async findOne(o){let{collection:e,where:n={},tenantId:s,draft:t}=o,i=this.getCollectionConfig(e),r=this.getMongoCollection(e),a=this.buildFilter(n,i.tenantScoped?s:void 0),d=i.fields.find(u=>u.name==="status"),l=d?.type==="select"&&Array.isArray(d.options)&&d.options.some(u=>u.value==="published");!t&&l&&(a.status="published");let f=await r.findOne(a);if(!f)return null;let g=this.processResult(f,i);if(t){let c=await this.getMongoCollection(`${e}_versions`).findOne({document_id:g.id},{sort:{createdAt:-1}});if(c){let h=typeof c.data=="string"?JSON.parse(c.data):c.data&&typeof c.data=="object"?c.data:{};g={...g,...h,status:g.status};}}return g}async findVersions(o){let{collection:e,documentId:n,sort:s,limit:t=10,page:i=1,tenantId:r}=o,a=this.getCollectionConfig(e),d=this.getMongoCollection(`${e}_versions`),l={document_id:n,autosave:{$ne:true}};r&&a.tenantScoped&&(l.tenant_id=r);let f=(i-1)*t,g=this.parseSort(s),u={[g.field]:g.direction==="asc"?1:-1},[c,h]=await Promise.all([d.find(l).sort(u).skip(f).limit(t).toArray(),d.countDocuments(l)]);return {docs:c.map(y=>this.processResult(y,{})),...this.calculatePagination(i,t,h)}}async findVersionByID(o){let{collection:e,versionId:n,tenantId:s}=o,t=this.getCollectionConfig(e),i=this.getMongoCollection(`${e}_versions`),r={_id:n};s&&t.tenantScoped&&(r.tenant_id=s);let a=await i.findOne(r);return a?this.processResult(a,{}):null}async createVersion(o){let{collection:e,documentId:n,data:s,status:t,createdBy:i,changeDescription:r,tenantId:a,autosave:d}=o,l=this.getCollectionConfig(e),f=this.getMongoCollection(`${e}_versions`);if(d){let c={document_id:n,collection_slug:e,autosave:true};a&&l.tenantScoped&&(c.tenant_id=a);let h=await f.findOne(c);if(h){let y=new Date().toISOString();return await f.updateOne({_id:h._id},{$set:{data:s,status:t,updatedAt:y}}),this.processResult({...h,data:s,status:t,updatedAt:y},{})}}let g=new Date().toISOString(),u={_id:this.generateId(),document_id:n,collection_slug:e,data:s,status:t,autosave:d===true,created_by:i,change_description:r,createdAt:g,updatedAt:g};if(a&&l.tenantScoped&&(u.tenant_id=a),await f.insertOne(u),!d){let c=this.getCollectionConfig(e);c.versions?.maxPerDoc&&await this.deleteVersions({collection:e,documentId:n,keepLatest:c.versions.maxPerDoc,tenantId:a});}return this.processResult(u,{})}async updateLatestVersion(o){return this.createVersion({...o,autosave:true})}async deleteVersions(o){let{collection:e,documentId:n,keepLatest:s,tenantId:t}=o,i=this.getCollectionConfig(e),r=this.getMongoCollection(`${e}_versions`);if(s){let a={document_id:n,autosave:{$ne:true}};t&&i.tenantScoped&&(a.tenant_id=t);let l=(await r.find(a).sort({createdAt:-1}).limit(s).project({_id:1}).toArray()).map(f=>f._id);l.length>0&&await r.deleteMany({document_id:n,autosave:{$ne:true},_id:{$nin:l},...t&&i.tenantScoped?{tenant_id:t}:{}});}else {let a={document_id:n};t&&i.tenantScoped&&(a.tenant_id=t),await r.deleteMany(a);}}async migrate(){for(let o of this.collections.values()){let e=this.getMongoCollection(o.slug);await e.createIndex({_id:1}),o.tenantScoped&&await e.createIndex({tenantId:1}),o.timestamps&&await e.createIndex({createdAt:-1});for(let n of o.fields)n.unique&&n.name&&await e.createIndex({[n.name]:1},{unique:true}),n.indexed&&n.name&&await e.createIndex({[n.name]:1});}}getCollectionConfig(o){if(o.startsWith("_globals_")){let n=o.replace("_globals_",""),s=this.globals.get(n);if(!s)throw new Error(`Global "${n}" not found`);return s}let e=this.collections.get(o);if(!e)throw new Error(`Collection "${o}" not found`);return e}buildFilter(o={},e){let n={};e&&(n.tenantId=e);for(let[s,t]of Object.entries(o))if(s==="AND"&&Array.isArray(t)){let i=t.map(r=>this.buildFilter(r));Object.assign(n,...i);}else if(s==="OR"&&Array.isArray(t))n.$or=t.map(i=>this.buildFilter(i));else if(typeof t=="object"&&t!==null&&!Array.isArray(t)){let i={};if(t.equals!==void 0){n[s==="id"?"_id":s]=t.equals;continue}t.not_equals!==void 0&&(i.$ne=t.not_equals),t.in!==void 0&&(i.$in=t.in),t.not_in!==void 0&&(i.$nin=t.not_in),t.greater_than!==void 0&&(i.$gt=t.greater_than),t.greater_than_equal!==void 0&&(i.$gte=t.greater_than_equal),t.less_than!==void 0&&(i.$lt=t.less_than),t.less_than_equal!==void 0&&(i.$lte=t.less_than_equal),t.like!==void 0&&(i.$regex=new RegExp(t.like.replace(/%/g,".*"),"i")),t.not_like!==void 0&&(i.$not=new RegExp(t.not_like.replace(/%/g,".*"),"i")),t.contains!==void 0&&(i.$regex=new RegExp(`.*${t.contains}.*`,"i")),t.exists!==void 0&&(i.$exists=t.exists),Object.keys(i).length>0&&(n[s==="id"?"_id":s]=i);}else n[s==="id"?"_id":s]=t;return n}buildProjection(o){if(!o||o.length===0)return;let e={_id:1};for(let n of o)e[n]=1;return e}processResult(o,e){if(!o)return null;let n={...o};for(let s of Object.keys(n))/^\d+$/.test(s)&&delete n[s];return o._id&&(n.id=o._id,delete n._id),delete n.__v,n.createdAt&&(n.createdAt=new Date(n.createdAt).toISOString()),n.updatedAt&&(n.updatedAt=new Date(n.updatedAt).toISOString()),a$2(n)}generateId(){let o=Date.now().toString(16).padStart(12,"0"),e=randomBytes(6).toString("hex");return o+e}};function k(v){return new b(v)}
3
+ export{b as a,k as b};
@@ -0,0 +1,21 @@
1
+ import {g as g$1}from'./chunk-Y2YAKDEQ.js';import r from'path';import m from'fs';if (typeof window === "undefined") { const { createRequire } = await import(/* @vite-ignore */ 'module'); createRequire(import.meta.url); }
2
+ g$1();var l=o=>{let s=r.join(process.cwd(),"node_modules","@kyro-cms","core"),e=r.resolve(s,"src",`${o}.ts`);return m.existsSync(e)?e:r.resolve(s,"dist",`${o}.js`)},g=l("api-handler"),A=l("api-handler-graphql"),P=l("api-handler-trpc"),S=["@kyro-cms/core","@kyro-cms/admin","@kyro-cms/astro","@kyro-cms/ai"],x=["@kyro-cms/connect"],R=[...S,...x],_=["better-sqlite3","pg","mongodb","ioredis","sharp","ssh2","cpu-features","ssh2-sftp-client","nodemailer","jsonwebtoken","@mapbox/node-pre-gyp","mock-aws-s3","aws-sdk","nock","cloudflare:workers"],N=["crypto","node:crypto","module","node:module","fs","node:fs","fs/promises","node:fs/promises","path","node:path","util","node:util","stream","node:stream","events","node:events","url","node:url","http","node:http","https","node:https","os","node:os","child_process","node:child_process","assert","node:assert","zlib","node:zlib","buffer","node:buffer"],h=[...S,..._],O=[...R,...N,..._];function k(o={}){let{configPath:s="./kyro.config.ts",apiPath:e="/api",adminPath:a="/admin",admin:v=true,enableGraphQL:c=false,enableTRPC:p=false,enableWebSocket:u=false}=o;return {name:"@kyro-cms/core",hooks:{"astro:config:setup":async({config:y,updateConfig:E,injectRoute:i,logger:n})=>{if(n.info(`Setting up Kyro CMS (API: ${e}, Admin: ${a})`),e===a)throw new Error(`Kyro CMS: apiPath and adminPath cannot be the same ("${e}")`);let d=r.resolve(y.root.pathname,s),b=d;m.existsSync(d)||n.warn(`Kyro config file not found at ${s}. The API will fail to boot if collections are needed.`),E({security:{checkOrigin:false},vite:{ssr:{external:O},build:{rollupOptions:{external:h}},optimizeDeps:{exclude:h},server:{watch:{ignored:["**/*.db","**/*.db-*","**/data/**","**/public/uploads/**","**/.kyro/**"]}},plugins:[{name:"use-sync-external-store-shim-fix",enforce:"pre",resolveId(t){if(t==="use-sync-external-store/shim"||t==="use-sync-external-store/shim/index.js")return "\0virtual:use-sync-external-store-shim";if(t==="use-sync-external-store/shim/with-selector"||t==="use-sync-external-store/shim/with-selector.js")return "\0virtual:use-sync-external-store-shim-with-selector"},load(t){if(t==="\0virtual:use-sync-external-store-shim")return 'export { useSyncExternalStore } from "react";';if(t==="\0virtual:use-sync-external-store-shim-with-selector")return `
3
+ import { useSyncExternalStore, useMemo } from "react";
4
+ export function useSyncExternalStoreWithSelector(subscribe, getSnapshot, getServerSnapshot, selector, isEqual) {
5
+ const memoizedSelector = useMemo(() => {
6
+ let last, lastSnap, hasMemo = false;
7
+ return (snap) => {
8
+ if (!hasMemo || !Object.is(lastSnap, snap)) {
9
+ const next = selector(snap);
10
+ if (!hasMemo || !(isEqual ? isEqual(last, next) : Object.is(last, next))) {
11
+ last = next; lastSnap = snap; hasMemo = true;
12
+ }
13
+ }
14
+ return last;
15
+ };
16
+ }, [selector, isEqual]);
17
+ const getSelection = () => memoizedSelector(getSnapshot());
18
+ const getServerSelection = getServerSnapshot != null ? () => memoizedSelector(getServerSnapshot()) : undefined;
19
+ return useSyncExternalStore(subscribe, getSelection, getServerSelection);
20
+ }
21
+ `}}],resolve:{alias:{"kyro:config":b}},define:{__KYRO_API_PATH__:JSON.stringify(e),__KYRO_ADMIN_PATH__:JSON.stringify(a),__KYRO_ENABLE_GRAPHQL__:JSON.stringify(c),__KYRO_ENABLE_TRPC__:JSON.stringify(p),__KYRO_ENABLE_WS__:JSON.stringify(u)}}}),i({pattern:`${e}/[...path]`,entrypoint:g}),c&&(i({pattern:`${e}/graphql`,entrypoint:A}),n.info(`GraphQL endpoint enabled at ${e}/graphql`)),p&&(i({pattern:`${e}/trpc/[...path]`,entrypoint:P}),n.info(`tRPC endpoint enabled at ${e}/trpc`)),u&&n.info("WebSocket support enabled (auto-starts at first request)");}}}}export{k as a};
@@ -0,0 +1,19 @@
1
+ 'use strict';var chunkVQ53TFYA_cjs=require('./chunk-VQ53TFYA.cjs'),chunkZOVH6QT5_cjs=require('./chunk-ZOVH6QT5.cjs'),chunkBUNLC3II_cjs=require('./chunk-BUNLC3II.cjs'),module$1=require('module'),crypto=require('crypto');chunkBUNLC3II_cjs.h();chunkBUNLC3II_cjs.h();var R;function x(){return R||(R=module$1.createRequire("file:///")("node:sqlite").DatabaseSync,R)}function N(T){let e=[];for(let a of T)if(a.type==="tabs"&&"tabs"in a)for(let s of a.tabs)e.push(...N(s.fields));else a.type==="row"&&"fields"in a?e.push(...N(a.fields)):a.type==="collapsible"&&"fields"in a?e.push(...N(a.fields)):e.push(a);return e}function G(T,e){let a=e,s=T[a.name];if(a.type==="json"||a.type==="richtext"||a.type==="array"||a.type==="group"||a.type==="blocks"||a.type==="list"||a.type==="relationship-block")try{s=s?JSON.parse(s):null;}catch{s=null;}if(a.type==="checkbox"&&(s=!!s),a.type==="date"&&s)try{let i=new Date(s);isNaN(i.getTime())?s=null:s=i.toISOString();}catch{s=null;}if((a.type==="upload"||a.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(a.type==="relationship"&&s)try{let i=JSON.parse(s);Array.isArray(i),s=i;}catch{s={relationTo:Array.isArray(a.relationTo)?a.relationTo[0]:a.relationTo,value:s};}if(a.type==="list"&&s)try{let i=JSON.parse(s);s=Array.isArray(i)?i:[];}catch{s=[];}if(a.type==="relationship-block"&&s)try{let i=JSON.parse(s);s=Array.isArray(i)?i:[];}catch{s=[];}return s}function P(T,e){return Array.isArray(T)?T.map(a=>{if(!a||typeof a!="object")return a;let s=a.data?{...a.data}:void 0;if(!s)return a;let i=e.find(o=>o.slug===a.type||o.slug===a.slug);if(!i||!Array.isArray(i.fields))return a;for(let o of i.fields){if(o.name&&(o.type==="upload"||o.type==="image")&&s[o.name]){let t=s[o.name];Array.isArray(t)?s[o.name]=t.map(n=>typeof n=="string"?{id:n}:n):typeof t=="string"&&(s[o.name]={id:t});}if(o.type==="blocks"&&o.name&&s[o.name]){let t=o.blocks||[];s[o.name]=P(s[o.name],t);}}return {...a,data:s}}):T}function O(T,e){try{return T.prepare(`PRAGMA table_info(${e})`).all().map(s=>s.name)}catch{return []}}var L=class extends chunkVQ53TFYA_cjs.a{db;path;migrations=new Map;versionsTableName="kyro_versions";constructor(e){super(),this.path=e.path,e.db?this.db=e.db:this.db=null;}async connect(){if(!this.db)this.db=new(x())(this.path||":memory:");else try{this.db.exec("SELECT 1");}catch{this.db=new(x())(this.path||":memory:");}if(this.db&&typeof this.db.prepare=="function"&&!this.db.prepare.__wrapped){let e=this.db.prepare.bind(this.db),a=s=>{let i=e(s),o=t=>typeof t=="boolean"?t?1:0:t===void 0?null:t;return new Proxy(i,{get(t,n,r){if(n==="all")return (...c)=>t.all(...c.map(o));if(n==="get")return (...c)=>t.get(...c.map(o));if(n==="run")return (...c)=>t.run(...c.map(o));let l=Reflect.get(t,n,r);return typeof l=="function"?l.bind(t):l}})};a.__wrapped=true,this.db.prepare=a;}this.db.exec("PRAGMA journal_mode = WAL"),this.db.exec("PRAGMA foreign_keys = ON"),this.connected=true;}async disconnect(){if(this.db){try{this.db.close();}catch{}this.db=null;}this.connected=false;}ensureTable(e,a){let s=a||this.getTableNameFor(e.slug),i=["id TEXT PRIMARY KEY"];for(let n of N(e.fields)){if(!n.name||n.name==="id")continue;let r=this.fieldToSQL(n);r&&i.push(r);}let o=N(e.fields);o.some(n=>n.name==="createdAt")||i.push(`${this.col("createdAt")} TEXT DEFAULT (datetime('now'))`),o.some(n=>n.name==="updatedAt")||i.push(`${this.col("updatedAt")} TEXT DEFAULT (datetime('now'))`),o.some(n=>n.name==="status")||i.push("status TEXT DEFAULT 'draft'"),o.some(n=>n.name==="hasDraft")||i.push("hasDraft INTEGER DEFAULT 0"),e.tenantScoped&&i.push("tenant_id TEXT NOT NULL");let t=O(this.db,s);if(t.length===0){let n=`CREATE TABLE IF NOT EXISTS ${s} (${i.join(", ")})`;this.db.exec(n),this.db.exec(`CREATE INDEX IF NOT EXISTS idx_${s}_status ON ${s}(status)`);for(let r of N(e.fields))r.name&&r.indexed&&this.db.exec(`CREATE INDEX IF NOT EXISTS idx_${s}_${r.name} ON ${s}(${this.col(r.name)})`),r.name&&r.unique&&this.db.exec(`CREATE UNIQUE INDEX IF NOT EXISTS idx_${s}_${r.name}_unique ON ${s}(${this.col(r.name)})`);}else {let n=new Set(t);for(let r of i){let l=r.split(" ")[0].replace(/^"/,"").replace(/"$/,"");if(!n.has(l)&&l!=="id")try{l==="status"?this.db.exec(`ALTER TABLE ${s} ADD COLUMN ${this.col(l)} TEXT DEFAULT 'published'`):l==="hasDraft"?this.db.exec(`ALTER TABLE ${s} ADD COLUMN ${this.col(l)} INTEGER DEFAULT 0`):this.db.exec(`ALTER TABLE ${s} ADD COLUMN ${this.col(l)} TEXT`);}catch{}}}this.migrations.set(s,true);}ensureVersionsTable(){this.db.exec(`
2
+ CREATE TABLE IF NOT EXISTS ${this.versionsTableName} (
3
+ id TEXT PRIMARY KEY,
4
+ collection_slug TEXT NOT NULL,
5
+ document_id TEXT NOT NULL,
6
+ tenant_id TEXT,
7
+ version INTEGER NOT NULL,
8
+ status TEXT NOT NULL DEFAULT 'draft',
9
+ autosave INTEGER NOT NULL DEFAULT 0,
10
+ data TEXT NOT NULL,
11
+ created_by TEXT,
12
+ change_description TEXT,
13
+ published_at TEXT,
14
+ created_at TEXT DEFAULT (datetime('now')),
15
+ updated_at TEXT DEFAULT (datetime('now'))
16
+ )
17
+ `);try{this.db.exec(`ALTER TABLE ${this.versionsTableName} ADD COLUMN autosave INTEGER NOT NULL DEFAULT 0`);}catch{}this.db.exec(`CREATE INDEX IF NOT EXISTS idx_${this.versionsTableName}_doc ON ${this.versionsTableName}(collection_slug, document_id)`),this.db.exec(`CREATE INDEX IF NOT EXISTS idx_${this.versionsTableName}_status ON ${this.versionsTableName}(status)`),this.db.exec(`CREATE INDEX IF NOT EXISTS idx_${this.versionsTableName}_autosave ON ${this.versionsTableName}(autosave)`);}resolveCol(e,a){let s=a.replace(/^-/,""),i=O(this.db,e);if(!i.includes(s)){if(s==="created_at"&&i.includes("createdAt"))return '"createdAt"';if(s==="createdAt"&&i.includes("created_at"))return '"created_at"';if(s==="updated_at"&&i.includes("updatedAt"))return '"updatedAt"';if(s==="updatedAt"&&i.includes("updated_at"))return '"updated_at"'}return this.col(s)}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 a=e.replace("_globals_","");return {isGlobal:true,globalSlug:a,tableName:`global_${a.replace(/-/g,"_")}`}}return {isGlobal:false,globalSlug:"",tableName:this.getTableNameFor(e)}}async find(e){let{collection:a,where:s={},sort:i,limit:o=10,page:t=1,tenantId:n,draft:r=false}=e,l=this.parseGlobalsSlug(a),c=l.isGlobal?this.globals.get(l.globalSlug):this.getCollection(a);this.ensureTable(c,l.tableName);let d=l.tableName,b=`SELECT * FROM ${d}`,u=[],f=[],p={...s};this.tenantContext&&c.tenantScoped&&(p=chunkVQ53TFYA_cjs.c({where:p},a,this.tenantContext,chunkVQ53TFYA_cjs.b).where||{});let E=c.fields.find(h=>h.name==="status"),m=E?.type==="select"&&Array.isArray(E.options)&&E.options.some(h=>h.value==="published");!r&&m&&(f.push("status = ?"),u.push("published")),n&&c.tenantScoped&&(f.push("tenant_id = ?"),u.push(n));for(let[h,y]of Object.entries(p)){if(h==="AND"||h==="OR")continue;let S=this.resolveCol(d,h);typeof y=="object"&&y!==null?(y.equals!==void 0&&(f.push(`${S} = ?`),u.push(y.equals)),y.in!==void 0&&(f.push(`${S} IN (${y.in.map(()=>"?").join(", ")})`),u.push(...y.in)),y.not_equals!==void 0&&(f.push(`${S} != ?`),u.push(y.not_equals))):(f.push(`${S} = ?`),u.push(y));}f.length>0&&(b+=` WHERE ${f.join(" AND ")}`);let g=i||"-createdAt",U=this.resolveCol(d,g),w=g.startsWith("-")?"DESC":"ASC";b+=` ORDER BY ${U} ${w}`;let M=b.replace("SELECT *","SELECT COUNT(*) as count"),D=this.db.prepare(M).get(...u)?.count||0;b+=" LIMIT ? OFFSET ?",u.push(o,(t-1)*o);let A=this.db.prepare(b).all(...u).map(h=>this.rowToDoc(h,c));return this.tenantContext&&!this.tenantContext.isSuperAdmin&&(A=A.filter(h=>chunkVQ53TFYA_cjs.d(h,a,this.tenantContext,chunkVQ53TFYA_cjs.b))),r&&(A=await Promise.all(A.map(async h=>{let y=this.db.prepare(`SELECT * FROM ${this.versionsTableName} WHERE collection_slug = ? AND document_id = ? AND tenant_id IS NULL ORDER BY version DESC LIMIT 1`).get(a,h.id);if(y){let S=y.data?JSON.parse(y.data):{};return chunkZOVH6QT5_cjs.a({...h,...S,status:h.status,_hasUnpublishedChanges:y.status==="draft"})}return h}))),A=A.map(h=>chunkZOVH6QT5_cjs.a(h)),{docs:A,totalDocs:D,limit:o,totalPages:Math.ceil(D/o),page:t,pagingCounter:(t-1)*o+1,hasPrevPage:t>1,hasNextPage:t<Math.ceil(D/o),prevPage:t>1?t-1:null,nextPage:t<Math.ceil(D/o)?t+1:null}}async findByID(e){let{collection:a,id:s,tenantId:i,draft:o=false}=e,t=this.parseGlobalsSlug(a),n=t.isGlobal?this.globals.get(t.globalSlug):this.getCollection(a);this.ensureTable(n,t.tableName);let l=`SELECT * FROM ${t.tableName} WHERE id = ?`,c=[s];if(this.tenantContext&&n.tenantScoped){let p={id:s,tenant_id:this.tenantContext.tenantId};if(!chunkVQ53TFYA_cjs.d(p,a,this.tenantContext,chunkVQ53TFYA_cjs.b))return null}let d=n.fields.find(p=>p.name==="status"),b=d?.type==="select"&&Array.isArray(d.options)&&d.options.some(p=>p.value==="published");!o&&b&&(l+=" AND status = ?",c.push("published")),i&&n.tenantScoped&&(l+=" AND tenant_id = ?",c.push(i));let u=this.db.prepare(l).get(...c);if(!u)return null;let f=this.rowToDoc(u,n);if(o){let p=this.db.prepare(`SELECT * FROM ${this.versionsTableName} WHERE collection_slug = ? AND document_id = ? AND tenant_id IS NULL ORDER BY version DESC LIMIT 1`).get(a,f.id);if(p){let E=p.data?JSON.parse(p.data):{};f={...f,...E,status:f.status,_hasUnpublishedChanges:p.status==="draft"};}}return chunkZOVH6QT5_cjs.a(f)}async create(e){let{collection:a,data:s,tenantId:i}=e,o=this.parseGlobalsSlug(a),t=o.isGlobal?this.globals.get(o.globalSlug):this.getCollection(a);this.ensureTable(t,o.tableName);let n=o.tableName,r=o.isGlobal?o.globalSlug:s.id||this.generateId(),l=this.prepareData(s,t);l.id=r;let c=new Date().toISOString();l.created_at=c,l.updated_at=c,i&&t.tenantScoped&&(l.tenant_id=i);let d=Object.keys(l),b=O(this.db,n),u={};for(let g of d)b.includes(g)&&(u[g]=l[g]);let f=Object.keys(u),p=f.map(g=>this.col(g)),E=f.map(()=>"?").join(", "),m=Object.values(u).map(g=>g!==null&&typeof g=="object"?JSON.stringify(g):g);return this.db.prepare(`INSERT OR REPLACE INTO ${n} (${p.join(", ")}) VALUES (${E})`).run(...m),this.ensureVersionsTable(),this.findByID({collection:a,id:r,tenantId:i,draft:true})}async update(e){let{collection:a,id:s,data:i,tenantId:o}=e,t=this.parseGlobalsSlug(a),n=t.isGlobal?this.globals.get(t.globalSlug):this.getCollection(a);this.ensureTable(n,t.tableName);let r=t.tableName,l=this.prepareData(i,n);l.updated_at=new Date().toISOString();let c=O(this.db,r),d={};for(let m of Object.keys(l))c.includes(m)&&(d[m]=l[m]);let u=Object.keys(d).map(m=>`${this.col(m)} = ?`).join(", "),f=Object.values(d).map(m=>m!==null&&typeof m=="object"?JSON.stringify(m):m),p=`UPDATE ${r} SET ${u} WHERE id = ?`,E=[...f,s];return o&&n.tenantScoped&&(p+=" AND tenant_id = ?",E.push(o)),this.db.prepare(p).run(...E),this.ensureVersionsTable(),this.findByID({collection:a,id:s,tenantId:o,draft:true})}async delete(e){let{collection:a,id:s,tenantId:i}=e,o=this.parseGlobalsSlug(a),t=o.isGlobal?this.globals.get(o.globalSlug):this.getCollection(a);this.ensureTable(t,o.tableName),this.ensureVersionsTable();let n=await this.findByID({collection:a,id:s,tenantId:i,draft:true});if(!n)throw new Error(`Document not found: ${a}/${s}`);let l=`DELETE FROM ${o.tableName} WHERE id = ?`,c=[s];return i&&t.tenantScoped&&(l+=" AND tenant_id = ?",c.push(i)),this.db.prepare(l).run(...c),n}async count(e){let{collection:a,tenantId:s}=e,i=this.parseGlobalsSlug(a),o=i.isGlobal?this.globals.get(i.globalSlug):this.getCollection(a);this.ensureTable(o,i.tableName);let n=`SELECT COUNT(*) as count FROM ${i.tableName}`,r=[];return s&&o.tenantScoped&&(n+=" WHERE tenant_id = ?",r.push(s)),this.db.prepare(n).get(...r)?.count||0}async findOne(e){let a=this.parseGlobalsSlug(e.collection);if(a.isGlobal){let i=this.globals.get(a.globalSlug);if(!i)throw new Error(`Global "${a.globalSlug}" not found in adapter`);this.ensureTable(i,a.tableName);let o=`SELECT * FROM ${a.tableName}`,t=[],n=[],r=i.fields.find(d=>d.name==="status"),l=r?.type==="select"&&Array.isArray(r.options)&&r.options.some(d=>d.value==="published");!e.draft&&i.versions&&l&&t.push("status = 'published'"),t.length>0&&(o+=` WHERE ${t.join(" AND ")}`),o+=" LIMIT 1";let c=this.db.prepare(o).get(...n);if(c){let d=this.rowToDoc(c,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,a.globalSlug);if(b){let u=b.data?JSON.parse(b.data):{};d={...d,...u,status:d.status,_hasUnpublishedChanges:b.status==="draft"};}}return d}return null}return (await this.find({...e,limit:1})).docs[0]||null}async findVersions(e){this.ensureVersionsTable();let{collection:a,documentId:s,tenantId:i,limit:o=20,page:t=1}=e,n=["collection_slug = ?","document_id = ?","autosave = 0"],r=[a,s];i?(n.push("tenant_id = ?"),r.push(i)):n.push("tenant_id IS NULL");let l=`WHERE ${n.join(" AND ")}`,d=this.db.prepare(`SELECT COUNT(*) as count FROM ${this.versionsTableName} ${l}`).get(...r)?.count||0,b=(t-1)*o;return {docs:this.db.prepare(`SELECT * FROM ${this.versionsTableName} ${l} ORDER BY version DESC LIMIT ? OFFSET ?`).all(...r,o,b).map(p=>this.rowToVersion(p)),totalDocs:d,limit:o,totalPages:Math.ceil(d/o),page:t,pagingCounter:(t-1)*o+1,hasPrevPage:t>1,hasNextPage:t<Math.ceil(d/o),prevPage:t>1?t-1:null,nextPage:t<Math.ceil(d/o)?t+1:null}}async findVersionByID(e){this.ensureVersionsTable();let a=this.db.prepare(`SELECT * FROM ${this.versionsTableName} WHERE id = ? AND collection_slug = ? LIMIT 1`).get(e.versionId,e.collection);return a?this.rowToVersion(a):null}async createVersion(e){this.ensureVersionsTable();let a=new Date().toISOString();if(e.autosave){let n=`SELECT * FROM ${this.versionsTableName} WHERE collection_slug = ? AND document_id = ? AND autosave = 1`,r=[e.collection,e.documentId];e.tenantId?(n+=" AND tenant_id = ?",r.push(e.tenantId)):n+=" AND tenant_id IS NULL",n+=" LIMIT 1";let l=this.db.prepare(n).get(...r);if(l){this.db.prepare(`UPDATE ${this.versionsTableName} SET data = ?, status = ?, updated_at = ? WHERE id = ?`).run(JSON.stringify(e.data),e.status,a,l.id);let c=await this.findVersionByID({collection:e.collection,versionId:l.id});if(c)return c}}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} (
18
+ id, collection_slug, document_id, tenant_id, version, status, autosave, data, created_by, change_description, published_at, created_at, updated_at
19
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(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"?a:null,a,a),!e.autosave){let r=this.collections.get(e.collection)?.versions?.maxPerDoc;r&&r>0&&await this.deleteVersions({collection:e.collection,documentId:e.documentId,keepLatest:r,tenantId:e.tenantId});}return await this.findVersionByID({collection:e.collection,versionId:s})}async updateLatestVersion(e){return this.createVersion({...e,autosave:true})}async deleteVersions(e){this.ensureVersionsTable();let{collection:a,documentId:s,keepLatest:i,tenantId:o}=e;if(i&&i>0){let t=this.db.prepare(`SELECT id, status, autosave FROM ${this.versionsTableName} WHERE collection_slug = ? AND document_id = ? ORDER BY version DESC`).all(a,s),n=0,r=[];for(let l of t)l.status==="published"||l.autosave===1||(n++,n>i&&r.push(l.id));for(let l of r)this.db.prepare(`DELETE FROM ${this.versionsTableName} WHERE id = ?`).run(l);}else {let t=`DELETE FROM ${this.versionsTableName} WHERE collection_slug = ? AND document_id = ?`,n=[a,s];o&&(t+=" AND tenant_id = ?",n.push(o)),this.db.prepare(t).run(...n);}}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,a){let s={},i=N(a.fields),o=(t,n)=>{let r=t;if(r.type==="json"||r.type==="richtext"||r.type==="array"||r.type==="group"||r.type==="blocks"||r.type==="list"||r.type==="relationship-block")return n!=null?JSON.stringify(n):null;if(r.type==="checkbox")return n?1:0;if(r.type==="number")return n!==null&&n!==""?Number(n):null;if(r.type==="upload"||r.type==="image"){if(n==null)return null;if(Array.isArray(n)){let l=n.map(c=>typeof c=="string"?c:typeof c=="object"?c.id||c._id||c:String(c));return JSON.stringify(l)}return typeof n=="string"?n:typeof n=="object"?JSON.stringify(n):String(n)}else if(t.type==="relationship"){if(n==null)return null;if(Array.isArray(n)){let l=n.map(c=>typeof c=="string"?c:typeof c=="object"?JSON.stringify({relationTo:t.relationTo,value:c.id||c}):String(c));return JSON.stringify(l)}return typeof n=="string"?n:typeof n=="object"?JSON.stringify({relationTo:t.relationTo,value:n.id||n}):String(n)}return n};for(let t of i){if(!t.name||t.name==="id"||a.fields.some(l=>l.type==="tabs"&&l.name&&"tabs"in l&&l.tabs.some(c=>c.fields.some(d=>d.name===t.name))))continue;let r=e[t.name];r!==void 0&&(s[t.name]=o(t,r));}for(let t of a.fields)if(t.type==="tabs"&&"tabs"in t&&t.name){let n=e[t.name];if(n&&typeof n=="object"){for(let r of t.tabs)for(let l of r.fields)if(l.name&&l.name!=="id"){let c=n[l.name];c!==void 0&&(s[l.name]=o(l,c));}}}return s}rowToDoc(e,a){let s={id:e.id};for(let i of N(a.fields)){if(!i.name||i.name==="id")continue;let o=i,t=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{t=t?JSON.parse(t):null;}catch{t=null;}if(o.type==="blocks"&&t&&Array.isArray(t)){let n=o.blocks||[];t=P(t,n);}if(i.type==="checkbox"&&(t=!!t),i.type==="date"&&t)try{let n=new Date(t);isNaN(n.getTime())?(console.warn(`[LocalAdapter] Invalid date value for field "${i.name}":`,t),t=null):t=n.toISOString();}catch{t=null;}if((i.type==="upload"||i.type==="image")&&t)try{let n=JSON.parse(t);Array.isArray(n)?t=n.map(r=>typeof r=="object"&&r!==null?r:{id:r}):t=typeof n=="object"?n:{id:n};}catch{t={id:t};}if(i.type==="relationship"&&t)try{let n=JSON.parse(t);Array.isArray(n),t=n;}catch{t={relationTo:Array.isArray(i.relationTo)?i.relationTo[0]:i.relationTo,value:t};}s[i.name]=t;}for(let i of a.fields)if(!(!i.name||i.name==="id"||i.name==="row"||i.name==="collapsible")&&i.type==="tabs"&&"tabs"in i){let o={};for(let t of i.tabs)for(let n of t.fields)n.name&&n.name!=="id"&&(o[n.name]=G(e,n));s[i.name]=o;}if(a.timestamps){let i=e.createdAt||e.created_at,o=e.updatedAt||e.updated_at;if(i)try{let t=new Date(i);isNaN(t.getTime())||(s.createdAt=t.toISOString());}catch{}if(o)try{let t=new Date(o);isNaN(t.getTime())||(s.updatedAt=t.toISOString());}catch{}}a.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"),a=crypto.randomBytes(6).toString("hex");return e+a}getMediaById(e){try{let a=this.getTableNameFor("media"),s=this.db.prepare(`SELECT id, url, thumbnail_url FROM ${a} 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((a,s)=>{let i=this.db.transaction(async()=>e({db:this.db}));try{let o=i();a(o);}catch(o){s(o);}})}getDatabase(){return this.db}exec(e){this.db.exec(e);}prepare(e){return this.db.prepare(e)}};function B(T){return new L(T||{})}exports.a=L;exports.b=B;