@kyro-cms/core 0.12.17 → 0.12.21

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 (97) hide show
  1. package/README.md +5 -2
  2. package/dist/{WebhookService-i-Kl3dvf.d.cts → WebhookService-BBcCHBo8.d.cts} +1 -1
  3. package/dist/{WebhookService-ByrpAI4d.d.ts → WebhookService-C19xR8qE.d.ts} +1 -1
  4. package/dist/api-handler-graphql.cjs +1 -1
  5. package/dist/api-handler-graphql.js +1 -1
  6. package/dist/api-handler-trpc.cjs +1 -1
  7. package/dist/api-handler-trpc.js +1 -1
  8. package/dist/api-handler.cjs +1 -1
  9. package/dist/api-handler.js +1 -1
  10. package/dist/{base-iyJTfH-3.d.cts → base-C2iwjdJQ.d.cts} +2 -7
  11. package/dist/{base-oUSURe4_.d.ts → base-yXdYZxFK.d.ts} +2 -7
  12. package/dist/bootstrap-4WXRKXMO.cjs +1 -0
  13. package/dist/{bootstrap-A3OBR3YI.js → bootstrap-KFGRTJSD.js} +1 -1
  14. package/dist/chunk-3NC7GXD5.js +3 -0
  15. package/dist/chunk-3Q2WUG63.cjs +2 -0
  16. package/dist/{chunk-I4ZACL66.js → chunk-4D6FG2J6.js} +1 -1
  17. package/dist/chunk-4RMFCTWH.js +1 -0
  18. package/dist/chunk-5K4YG5DA.cjs +300 -0
  19. package/dist/{chunk-TQNM4C7H.js → chunk-5KOQYQEE.js} +1 -1
  20. package/dist/chunk-6J27P5D6.js +300 -0
  21. package/dist/chunk-BVG6VSAJ.cjs +1 -0
  22. package/dist/chunk-DKESD4HI.js +133 -0
  23. package/dist/{chunk-EJDIR56C.cjs → chunk-FHJJKFAU.cjs} +1 -1
  24. package/dist/chunk-FVZ5RFLO.js +2 -0
  25. package/dist/chunk-G7SSHELM.cjs +1 -0
  26. package/dist/chunk-GXVCCKOL.js +1 -0
  27. package/dist/chunk-ILEZ3NYX.cjs +2 -0
  28. package/dist/{chunk-QMQXKCCQ.cjs → chunk-KJT6VTTN.cjs} +1 -1
  29. package/dist/chunk-LHW4R367.js +1 -0
  30. package/dist/chunk-O3OYZQN7.cjs +21 -0
  31. package/dist/chunk-OOQGI3T7.js +1 -0
  32. package/dist/chunk-QJZQOLRN.js +21 -0
  33. package/dist/chunk-SFAD6WPC.cjs +3 -0
  34. package/dist/chunk-VGQ4VUG6.js +2 -0
  35. package/dist/chunk-WG3UQEV7.cjs +133 -0
  36. package/dist/{chunk-RL36RMMG.cjs → chunk-XALG5H27.cjs} +1 -1
  37. package/dist/chunk-XTRY75KC.cjs +210 -0
  38. package/dist/chunk-YVM5BDRD.js +210 -0
  39. package/dist/chunk-ZUVP4UK7.cjs +1 -0
  40. package/dist/cli/index.cjs +1 -1
  41. package/dist/cli/index.js +1 -1
  42. package/dist/client.d.cts +1 -1
  43. package/dist/client.d.ts +1 -1
  44. package/dist/drizzle/index.cjs +1 -1
  45. package/dist/drizzle/index.d.cts +3 -8
  46. package/dist/drizzle/index.d.ts +3 -8
  47. package/dist/drizzle/index.js +1 -1
  48. package/dist/graphql/index.d.cts +2 -2
  49. package/dist/graphql/index.d.ts +2 -2
  50. package/dist/{index-DVDMEql7.d.ts → index-CqR97Q2L.d.ts} +1 -1
  51. package/dist/{index-DNy8jbA2.d.cts → index-DRNSjOte.d.cts} +1 -1
  52. package/dist/index.cjs +3 -3
  53. package/dist/index.d.cts +115 -26
  54. package/dist/index.d.ts +115 -26
  55. package/dist/index.js +1 -1
  56. package/dist/mongo-auth-adapter-AIMZTNG6.js +1 -0
  57. package/dist/{mongo-auth-adapter-6726C5KF.cjs → mongo-auth-adapter-C62QYCYV.cjs} +1 -1
  58. package/dist/mongodb/index.cjs +1 -1
  59. package/dist/mongodb/index.d.cts +6 -9
  60. package/dist/mongodb/index.d.ts +6 -9
  61. package/dist/mongodb/index.js +1 -1
  62. package/dist/rest/index.cjs +1 -1
  63. package/dist/rest/index.d.cts +3 -3
  64. package/dist/rest/index.d.ts +3 -3
  65. package/dist/rest/index.js +1 -1
  66. package/dist/templates/index.cjs +1 -1
  67. package/dist/templates/index.d.cts +1 -1
  68. package/dist/templates/index.d.ts +1 -1
  69. package/dist/templates/index.js +1 -1
  70. package/dist/trpc/index.cjs +1 -1
  71. package/dist/trpc/index.d.cts +2 -2
  72. package/dist/trpc/index.d.ts +2 -2
  73. package/dist/trpc/index.js +1 -1
  74. package/dist/{types-BcZiluXL.d.cts → types-BjivdGbU.d.cts} +10 -7
  75. package/dist/{types-Dc8VAPhF.d.ts → types-CaXXmV9h.d.ts} +10 -7
  76. package/package.json +4 -3
  77. package/dist/bootstrap-YLGVKTQS.cjs +0 -1
  78. package/dist/chunk-2NJR2B4W.cjs +0 -3
  79. package/dist/chunk-3RR6IV5I.js +0 -133
  80. package/dist/chunk-3ZFRP5M2.cjs +0 -133
  81. package/dist/chunk-6NGUY76Y.js +0 -259
  82. package/dist/chunk-BIJHVTNO.cjs +0 -21
  83. package/dist/chunk-CIA3BVH3.js +0 -86
  84. package/dist/chunk-FGSIHWQJ.js +0 -3
  85. package/dist/chunk-GCQTSPX6.cjs +0 -259
  86. package/dist/chunk-HHH4XNNS.cjs +0 -1
  87. package/dist/chunk-I67R6MR5.js +0 -2
  88. package/dist/chunk-ISCIUG37.js +0 -1
  89. package/dist/chunk-IZCTG4RG.js +0 -1
  90. package/dist/chunk-LMIBASPC.cjs +0 -86
  91. package/dist/chunk-O62KJ2J7.js +0 -1
  92. package/dist/chunk-RYIEE2TH.cjs +0 -2
  93. package/dist/chunk-W6P4N3Z7.js +0 -2
  94. package/dist/chunk-WMZEULS2.cjs +0 -1
  95. package/dist/chunk-XUONID6O.cjs +0 -2
  96. package/dist/chunk-YFRLT77I.js +0 -21
  97. package/dist/mongo-auth-adapter-U6SH4OWA.js +0 -1
@@ -1,133 +0,0 @@
1
- import {a,c,b,d}from'./chunk-TQNM4C7H.js';import {a as a$1}from'./chunk-6SPPR5JZ.js';import {sql,eq,desc,and,or,ne,inArray,like,gt,gte,lt,lte}from'drizzle-orm';import {text,uuid,jsonb,timestamp,boolean,decimal,integer as integer$1,varchar,pgTable}from'drizzle-orm/pg-core';import {text as text$1,integer,numeric,sqliteTable}from'drizzle-orm/sqlite-core';import {drizzle}from'drizzle-orm/postgres-js';import ce from'postgres';import {randomBytes}from'crypto';import {mkdir}from'fs/promises';import {resolve,dirname}from'path';import {createRequire}from'module';function _(f){if(typeof f!="string")return f;let t=f.replace(/-/g,"").toLowerCase();return t.length===32?`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`:f}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 _e(f,t="postgres"){let i=f.slug.replace(/-/g,"_"),e=[];e.push(`export const ${i} = pgTable('${i}', {`),e.push(" id: uuid('id').primaryKey().defaultRandom(),");for(let s of f.fields){if(s.name==="id"||s.type==="password")continue;let n=L(s,t),r=s.required,a=` ${s.name}: pg.${n}('${s.name}')`;s.unique&&(a+=".unique()"),r||(a+=".nullable()"),s.defaultValue!==void 0&&(typeof s.defaultValue=="string"?a+=`.default('${s.defaultValue}')`:typeof s.defaultValue=="boolean"?a+=`.default(${s.defaultValue})`:a+=`.default(sql\`${JSON.stringify(s.defaultValue)}\`)`),a+=",",e.push(a);}return f.timestamps&&(e.push(" createdAt: pg.timestamp('created_at').defaultNow(),"),e.push(" updatedAt: pg.timestamp('updated_at').defaultNow(),")),e.push(` status: ${t==="sqlite"?"sqlite":"pg"}.varchar('status').default('draft'),`),e.push(` hasDraft: ${t==="sqlite"?"sqlite":"pg"}.boolean('hasDraft').default(false),`),e.push("});"),e.join(`
2
- `)}function j(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]=j(e[n.name],r);}}return {...i,data:e}}):f}var x=class extends a{client;schema;_schemaEnsured=false;dialect;connectionString;versionsTableReady=false;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.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('postgres')).default,i=(await import('drizzle-orm/postgres-js')).drizzle;}catch{a$1(["postgres","drizzle-orm"]),t=(await import('postgres')).default,i=(await import('drizzle-orm/postgres-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('drizzle-orm/better-sqlite3')).drizzle;}catch{a$1(["better-sqlite3","drizzle-orm"]),t=(await import('better-sqlite3')).default,i=(await import('drizzle-orm/better-sqlite3')).drizzle;}let e=new t(this.connectionString.replace("file:",""));this.client=i(e,{schema:this.schema});}}this.connected=true;}async init(t,i=[]){if(await super.init(t,i),this.connectionString&&!this.client&&await this.connect(),this.client&&!this._schemaEnsured){for(let s of t){let n=this.getTableName(s.slug);this.schema[n]||(this.schema[n]=this.createTableFromConfig(s));}await this.ensureCollectionTables(t);let e=i.map(s=>({slug:`_globals_${s.slug}`,fields:s.fields,label:s.label}));for(let s of e){let n=this.getTableName(s.slug);this.schema[n]||(this.schema[n]=this.createTableFromConfig(s,true)),this.collections.has(s.slug)||this.collections.set(s.slug,s);}await this.ensureCollectionTables(e),this._schemaEnsured=true;}}createTableFromConfig(t,i=false){let e=this.getTableName(t.slug),s={id:i?text("id").primaryKey():uuid("id").primaryKey().defaultRandom()};for(let n of t.fields){if(!n.name||n.name==="id"||n.type==="password")continue;let r=L(n,this.dialect),a=n.name.replace(/-/g,"_"),o=a.replace(/([A-Z])/g,"_$1").toLowerCase(),c;if(this.dialect==="sqlite")switch(r){case "varchar":case "text":c=text$1(o);break;case "integer":c=integer(o);break;case "decimal":case "numeric":c=numeric(o);break;case "boolean":c=integer(o,{mode:"boolean"});break;case "timestamp":c=text$1(o);break;case "jsonb":c=text$1(o);break;default:c=text$1(o);}else switch(r){case "varchar":c=varchar(o,{length:255});break;case "integer":c=integer$1(o);break;case "decimal":c=decimal(o);break;case "boolean":c=boolean(o);break;case "timestamp":c=timestamp(o);break;case "jsonb":c=jsonb(o);break;default:c=text(o);}n.required||(c=c.default(null)),s[a]=c;}return s.createdAt||(s.createdAt=this.dialect==="sqlite"?text$1("created_at").default(new Date().toISOString()):timestamp("created_at").defaultNow()),s.updatedAt||(s.updatedAt=this.dialect==="sqlite"?text$1("updated_at").default(new Date().toISOString()):timestamp("updated_at").defaultNow()),e!=="users"&&e!=="audit_logs"&&(s.status||(s.status=this.dialect==="sqlite"?text$1("status").default("draft"):varchar("status",{length:20}).default("draft")),s.hasDraft||(s.hasDraft=this.dialect==="sqlite"?integer("hasDraft",{mode:"boolean"}).default(false):boolean("hasDraft").default(false))),this.dialect==="sqlite"?sqliteTable(e,s):pgTable(e,s)}async ensureCollectionTables(t){let i=[];for(let e of t){let s=e.slug.startsWith("_globals_"),n=this.getTableName(e.slug),r=this.generateCreateColumns(e),a=e.fields.some(u=>u.name==="createdAt"),o=e.fields.some(u=>u.name==="updatedAt"),c=e.fields.some(u=>u.name==="status"),d=e.fields.some(u=>u.name==="hasDraft");if(this.dialect==="postgres"){let u=s?'"id" TEXT PRIMARY KEY':'"id" UUID PRIMARY KEY DEFAULT gen_random_uuid()';i.push(`
3
- CREATE TABLE IF NOT EXISTS "${n}" (
4
- ${u},
5
- ${r}
6
- ${a?"":'"created_at" TIMESTAMP NOT NULL DEFAULT NOW(),'}
7
- ${o?"":'"updated_at" TIMESTAMP NOT NULL DEFAULT NOW(),'}
8
- ${c?"":`"status" VARCHAR(20) DEFAULT 'draft',`}
9
- ${d?"":'"hasDraft" BOOLEAN DEFAULT false'}
10
- )
11
- `);}else i.push(`
12
- CREATE TABLE IF NOT EXISTS "${n}" (
13
- "id" TEXT PRIMARY KEY,
14
- ${r}
15
- ${a?"":`"created_at" TEXT NOT NULL DEFAULT (datetime('now')),`}
16
- ${o?"":`"updated_at" TEXT NOT NULL DEFAULT (datetime('now')),`}
17
- ${c?"":`"status" TEXT DEFAULT 'draft',`}
18
- ${d?"":'"hasDraft" INTEGER DEFAULT 0'}
19
- )
20
- `);}if(i.length>0)if(this.dialect==="postgres")await this.client.execute(sql.raw(i.join(`;
21
- `)));else for(let e of i)await this.client.execute(sql.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.client.execute(sql`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.client.execute(sql`PRAGMA table_info("${sql.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(sql.raw(r.join(`;
22
- `)));}if(this.dialect==="postgres")for(let r of t.fields){if(!r.name||r.name==="id")continue;let a=L(r,this.dialect),o=r.name.replace(/-/g,"_").replace(/([A-Z])/g,"_$1").toLowerCase(),c=e.get(o);!c||c.type!=="character varying"||(a==="text"?await this.executeRaw(sql.raw(`ALTER TABLE "${i}" ALTER COLUMN "${o}" TYPE TEXT`)):a==="jsonb"&&(await this.executeRaw(sql.raw(`ALTER TABLE "${i}" ALTER COLUMN "${o}" DROP DEFAULT`)),await this.executeRaw(sql.raw(`ALTER TABLE "${i}" ALTER COLUMN "${o}" TYPE JSONB USING (CASE WHEN "${o}" IS NULL THEN NULL WHEN "${o}"::text ~ '^\\s*\\{' THEN "${o}"::jsonb ELSE jsonb_build_object('id', "${o}"::text) END)`))));}}generateCreateColumns(t){let i=[];for(let e of t.fields){if(!e.name||e.name==="id")continue;let s=L(e,this.dialect),n=e.name.replace(/-/g,"_").replace(/([A-Z])/g,"_$1").toLowerCase(),r=e.required?"NOT NULL":"DEFAULT NULL",a;if(this.dialect==="sqlite")switch(s){case "varchar":case "text":a=`TEXT ${r}`;break;case "integer":a=`INTEGER ${r}`;break;case "decimal":case "numeric":a=`NUMERIC ${r}`;break;case "boolean":a=`INTEGER ${r}`;break;case "timestamp":a=`TEXT ${r}`;break;case "jsonb":a=`TEXT ${r}`;break;default:a=`TEXT ${r}`;}else switch(s){case "varchar":a=`VARCHAR(255) ${r}`;break;case "integer":a=`INTEGER ${r}`;break;case "decimal":a=`DECIMAL ${r}`;break;case "boolean":a=`BOOLEAN ${r}`;break;case "timestamp":a=`TIMESTAMP ${r}`;break;case "jsonb":a=`JSONB ${r}`;break;default:a=`TEXT ${r}`;}i.push(`"${n}" ${a}`);}return i.join(`,
23
- `)+(i.length>0?",":"")}async disconnect(){this.connected=false;}async find(t){let{collection:i,where:e={},sort:s,limit:n=10,page:r=1,tenantId:a,select:o,draft:c$1}=t,d$1=this.getCollection(i),u=this.getTable(i),h={...e};this.tenantContext&&d$1.tenantScoped&&(h=c({where:h},i,this.tenantContext,b).where||{});let g=this.buildWhereClause(h,d$1,u,a),y=d$1.fields.find(m=>m.name==="status"),p=y?.type==="select"&&Array.isArray(y.options)&&y.options.some(m=>m.value==="published");!c$1&&u.status&&p&&g.push(eq(u.status,"published"));let A=this.parseSort(s),w=!c$1&&u.status&&p?{...h,status:"published"}:h,X=await this.count({collection:i,where:w,tenantId:a}),W=(r-1)*n,O=[];try{let m=u[A.field]||u.createdAt||u.id,R=A.direction==="asc"?m:desc(m),E=this.client.select().from(u);g.length>0&&(E=E.where(and(...g))),O=await E.orderBy(R).limit(n).offset(W);}catch(m){console.error("[DrizzleAdapter] Query error:",m);}let N=O.map(m=>this.processResult(m,d$1));return this.tenantContext&&!this.tenantContext.isSuperAdmin&&(N=N.filter(m=>d(m,i,this.tenantContext,b))),c$1&&(N=await Promise.all(N.map(async m=>{let R=await this.executeRaw(sql`
24
- SELECT * FROM kyro_versions
25
- WHERE collection_slug = ${i}
26
- AND document_id = ${m.id}
27
- ORDER BY created_at DESC
28
- LIMIT 1
29
- `);if(R.length>0){let E=R[0],V=typeof E.data=="string"?JSON.parse(E.data):E.data;return {...m,...V,status:m.status}}return m}))),{docs:N,...this.calculatePagination(r,n,X)}}async findByID(t){let{collection:i,id:e,tenantId:s,draft:n}=t,r=this.getCollection(i),a=this.getTable(i),o=this.dialect==="postgres"&&typeof e=="string"?_(e):e;if(this.tenantContext&&r.tenantScoped){let p={id:o,tenantId:this.tenantContext.tenantId};if(!d(p,i,this.tenantContext,b))return null}let c=[eq(a.id,o)];s&&a.tenantId&&c.push(eq(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&&a.status&&u&&c.push(eq(a.status,"published"));let h=c.length>1?and(...c):c[0],g=await this.client.select().from(a).where(h);if(g.length===0)return null;let y=this.processResult(g[0],r);if(n){let p=await this.executeRaw(sql`
30
- SELECT * FROM kyro_versions
31
- WHERE collection_slug = ${i}
32
- AND document_id = ${y.id}
33
- ORDER BY created_at DESC
34
- LIMIT 1
35
- `);if(p.length>0){let A=p[0],w=typeof A.data=="string"?JSON.parse(A.data):A.data;y={...y,...w,status:y.status};}}return y}async create(t){let{collection:i,data:e,tenantId:s}=t,n=this.getCollection(i),r=this.getTable(i),a=this.prepareData(e,n);s&&n.tenantScoped&&(a.tenantId=s);let o=await this.client.insert(r).values(a).returning();return this.processResult(o[0],n)}async update(t){let{collection:i,id:e,data:s,tenantId:n}=t,r=this.getCollection(i),a=this.getTable(i),o=this.prepareData(s,r),c=this.dialect==="postgres"&&typeof e=="string"?_(e):e,d=[eq(a.id,c)];n&&a.tenantId&&d.push(eq(a.tenantId,n));let u=await this.client.update(a).set(o).where(and(...d)).returning();if(u.length===0)throw new Error(`Document not found: ${i}/${e}`);return this.processResult(u[0],r)}async delete(t){let{collection:i,id:e,tenantId:s}=t,n=this.getCollection(i),r=this.getTable(i),a=this.dialect==="postgres"&&typeof e=="string"?_(e):e,o=[eq(r.id,a)];s&&r.tenantId&&o.push(eq(r.tenantId,s));let c=await this.client.delete(r).where(and(...o)).returning();if(c.length===0)throw new Error(`Document not found: ${i}/${e}`);return this.processResult(c[0],n)}async count(t){let{collection:i,where:e={},tenantId:s}=t,n=this.getCollection(i),r=this.getTable(i),a=this.buildWhereClause(e,n,r,s);try{let o=this.client.select({count:sql`count(*)`}).from(r);a.length>0&&(o=o.where(and(...a)));let c=await o;return Number(c[0]?.count||0)}catch{return 0}}async findOne(t){let{collection:i,where:e={},tenantId:s,draft:n}=t;if(i.startsWith("_globals_")){let a=i.replace("_globals_",""),o=this.globals.get(a);if(!o)throw new Error(`Global "${a}" not found`);let c=this.getTable(i),d=this.client.select().from(c),u=o.fields.find(p=>p.name==="status"),h=u?.type==="select"&&Array.isArray(u.options)&&u.options.some(p=>p.value==="published");!n&&c.status&&h&&(d=d.where(eq(c.status,"published")));let g=await d.limit(1);if(g.length===0)return null;let y=this.processResult(g[0],o);if(n){let p=await this.executeRaw(sql`
36
- SELECT * FROM kyro_versions
37
- WHERE collection_slug = ${i}
38
- AND document_id = ${a}
39
- ORDER BY created_at DESC
40
- LIMIT 1
41
- `);if(p.length>0){let A=p[0],w=typeof A.data=="string"?JSON.parse(A.data):A.data;y={...y,...w,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:n=1,tenantId:r}=t,a=(n-1)*s,o=this.getCollection(i),c=await this.executeRaw(sql`
42
- SELECT count(*) as count
43
- FROM kyro_versions
44
- WHERE collection_slug = ${i}
45
- AND document_id = ${e}
46
- AND autosave = 0
47
- ${r&&o.tenantScoped?sql`AND tenant_id = ${r}`:sql``}
48
- `),d=parseInt(c[0]?.count||"0");return {docs:(await this.executeRaw(sql`
49
- SELECT *
50
- FROM kyro_versions
51
- WHERE collection_slug = ${i}
52
- AND document_id = ${e}
53
- AND autosave = 0
54
- ${r&&o.tenantScoped?sql`AND tenant_id = ${r}`:sql``}
55
- ORDER BY created_at DESC
56
- LIMIT ${s}
57
- OFFSET ${a}
58
- `)).map(h=>({...h,data:typeof h.data=="string"?JSON.parse(h.data):h.data})),...this.calculatePagination(n,s,d)}}async findVersionByID(t){await this.ensureVersionsTable();let i=this.getCollection(t.collection),e=await this.executeRaw(sql`
59
- SELECT * FROM kyro_versions
60
- WHERE id = ${t.versionId}
61
- AND collection_slug = ${t.collection}
62
- ${t.tenantId&&i.tenantScoped?sql`AND tenant_id = ${t.tenantId}`:sql``}
63
- LIMIT 1
64
- `);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(sql`
65
- SELECT * FROM kyro_versions
66
- WHERE collection_slug = ${t.collection}
67
- AND document_id = ${t.documentId}
68
- AND autosave = 1
69
- ${t.tenantId&&i.tenantScoped?sql`AND tenant_id = ${t.tenantId}`:sql``}
70
- LIMIT 1
71
- `);if(n.length>0)return await this.executeRaw(sql`
72
- UPDATE kyro_versions
73
- SET data = ${JSON.stringify(t.data)},
74
- status = ${t.status},
75
- updated_at = ${e}
76
- WHERE id = ${n[0].id}
77
- `),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(sql`
78
- INSERT INTO kyro_versions (
79
- id, collection_slug, document_id, tenant_id, data, status, autosave, created_by, change_description, created_at, updated_at
80
- ) VALUES (
81
- ${s}, ${t.collection}, ${t.documentId}, ${t.tenantId&&i.tenantScoped?t.tenantId:null},
82
- ${JSON.stringify(t.data)}, ${t.status}, ${t.autosave?1:0}, ${t.createdBy||null},
83
- ${t.changeDescription||null}, ${e}, ${e}
84
- )
85
- `),!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(sql`
86
- SELECT id FROM kyro_versions
87
- WHERE collection_slug = ${t.collection}
88
- AND document_id = ${t.documentId}
89
- AND autosave = 0
90
- ${t.tenantId&&i.tenantScoped?sql`AND tenant_id = ${t.tenantId}`:sql``}
91
- ORDER BY created_at DESC
92
- LIMIT ${t.keepLatest}
93
- `)).map(n=>n.id);s.length>0&&await this.executeRaw(sql`
94
- DELETE FROM kyro_versions
95
- WHERE collection_slug = ${t.collection}
96
- AND document_id = ${t.documentId}
97
- AND autosave = 0
98
- AND id NOT IN (${sql.join(s.map(n=>sql`${n}`),sql`, `)})
99
- `);}else await this.executeRaw(sql`
100
- DELETE FROM kyro_versions
101
- WHERE collection_slug = ${t.collection}
102
- AND document_id = ${t.documentId}
103
- ${t.tenantId&&i.tenantScoped?sql`AND tenant_id = ${t.tenantId}`:sql``}
104
- `);}getTable(t){let i=this.getTableName(t),e=this.schema[i];if(!e)throw new Error(`Table "${i}" not found in schema`);return e}buildWhereClause(t,i,e,s){let n=[];s&&i.tenantScoped&&e.tenantId&&n.push(eq(e.tenantId,s));for(let[r,a]of Object.entries(t))if(r==="id"&&this.dialect==="postgres"&&(typeof a=="string"?a=_(a):a&&typeof a=="object"&&(a.equals!==void 0&&typeof a.equals=="string"&&(a={...a,equals:_(a.equals)}),a.in&&Array.isArray(a.in)&&(a={...a,in:a.in.map(o=>typeof o=="string"?_(o):o)}))),r==="AND"&&Array.isArray(a)){let o=a.map(c=>this.buildWhereClause(c,i,e)).flat().filter(Boolean);o.length>0&&n.push(and(...o));}else if(r==="OR"&&Array.isArray(a)){let o=a.map(c=>this.buildWhereClause(c,i,e)).flat().filter(Boolean);o.length>0&&n.push(or(...o));}else if(typeof a=="object"&&a!==null&&!Array.isArray(a)){let o=e[r];if(!o)continue;a.equals!==void 0&&n.push(eq(o,a.equals)),a.not_equals!==void 0&&n.push(ne(o,a.not_equals)),a.in&&Array.isArray(a.in)&&n.push(inArray(o,a.in)),a.like!==void 0&&n.push(like(o,a.like)),a.contains!==void 0&&n.push(like(o,`%${a.contains}%`)),a.greater_than!==void 0&&n.push(gt(o,a.greater_than)),a.greater_than_equal!==void 0&&n.push(gte(o,a.greater_than_equal)),a.less_than!==void 0&&n.push(lt(o,a.less_than)),a.less_than_equal!==void 0&&n.push(lte(o,a.less_than_equal));}else {let o=e[r];o&&n.push(eq(o,a));}return n}processResult(t,i){if(!t)return null;let e={...t};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]=j(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()),e}async ensureVersionsTable(){if(this.versionsTableReady)return;let t;this.dialect==="sqlite"?t=`
105
- CREATE TABLE IF NOT EXISTS kyro_versions (
106
- id text PRIMARY KEY,
107
- collection_slug text NOT NULL,
108
- document_id text NOT NULL,
109
- tenant_id text,
110
- data text NOT NULL,
111
- status text NOT NULL DEFAULT 'draft',
112
- autosave integer NOT NULL DEFAULT 0,
113
- created_by text,
114
- change_description text,
115
- created_at text DEFAULT (datetime('now')),
116
- updated_at text DEFAULT (datetime('now'))
117
- )
118
- `:t=`
119
- CREATE TABLE IF NOT EXISTS kyro_versions (
120
- id text PRIMARY KEY,
121
- collection_slug text NOT NULL,
122
- document_id text NOT NULL,
123
- tenant_id text,
124
- data text NOT NULL,
125
- status text NOT NULL,
126
- autosave integer NOT NULL DEFAULT 0,
127
- created_by text,
128
- change_description text,
129
- created_at text NOT NULL,
130
- updated_at text NOT NULL
131
- )
132
- `,await this.executeRaw(sql.raw(t));try{this.dialect==="postgres"?await this.executeRaw(sql.raw("ALTER TABLE kyro_versions ADD COLUMN IF NOT EXISTS autosave integer NOT NULL DEFAULT 0")):await this.executeRaw(sql.raw("ALTER TABLE kyro_versions ADD COLUMN autosave integer NOT NULL DEFAULT 0"));}catch{}this.versionsTableReady=true;}async executeRaw(t){let i=await this.client.execute(t);return Array.isArray(i)?i:Array.isArray(i?.rows)?i.rows:Array.isArray(i?.[0])?i[0]:[]}};function we(f){return new x(f)}var me=createRequire(import.meta.url),he="node:sqlite",{DatabaseSync:ye}=me(he);function ge(){return process.env.DB_TYPE==="postgres"?"postgres":"sqlite"}function B(){return randomBytes(16).toString("hex")}async function xe(){let f=ge();if(f==="sqlite"){let r=resolve(process.cwd(),"data","kyro.db");await mkdir(dirname(r),{recursive:true});let a=new ye(r);return a.exec("PRAGMA journal_mode = WAL"),{db:a,dialect:f,genId:B}}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=ce(t,{max:i,ssl:e?"require":false,onnotice:()=>{}});return {db:drizzle(s),dialect:f,genId:B}}async function Oe(f,t){}async function Ue(f){let{roles:t}=await import('./schema-KFYUM674.js');await f.insert(t).values({name:"super_admin",level:100,inherits:[],description:"Full system access across all tenants",isSystem:true}).onConflictDoNothing();}
133
- export{L as a,_e as b,x as c,we as d,B as e,xe as f,Oe as g,Ue as h};
@@ -1,133 +0,0 @@
1
- 'use strict';var chunkEJDIR56C_cjs=require('./chunk-EJDIR56C.cjs'),chunkD5P2IPGX_cjs=require('./chunk-D5P2IPGX.cjs'),drizzleOrm=require('drizzle-orm'),pgCore=require('drizzle-orm/pg-core'),sqliteCore=require('drizzle-orm/sqlite-core'),postgresJs=require('drizzle-orm/postgres-js'),ce=require('postgres'),crypto=require('crypto'),promises=require('fs/promises'),path=require('path'),module$1=require('module');var _documentCurrentScript=typeof document!=='undefined'?document.currentScript:null;function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var ce__default=/*#__PURE__*/_interopDefault(ce);function _(f){if(typeof f!="string")return f;let t=f.replace(/-/g,"").toLowerCase();return t.length===32?`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`:f}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 _e(f,t="postgres"){let i=f.slug.replace(/-/g,"_"),e=[];e.push(`export const ${i} = pgTable('${i}', {`),e.push(" id: uuid('id').primaryKey().defaultRandom(),");for(let s of f.fields){if(s.name==="id"||s.type==="password")continue;let n=L(s,t),r=s.required,a=` ${s.name}: pg.${n}('${s.name}')`;s.unique&&(a+=".unique()"),r||(a+=".nullable()"),s.defaultValue!==void 0&&(typeof s.defaultValue=="string"?a+=`.default('${s.defaultValue}')`:typeof s.defaultValue=="boolean"?a+=`.default(${s.defaultValue})`:a+=`.default(sql\`${JSON.stringify(s.defaultValue)}\`)`),a+=",",e.push(a);}return f.timestamps&&(e.push(" createdAt: pg.timestamp('created_at').defaultNow(),"),e.push(" updatedAt: pg.timestamp('updated_at').defaultNow(),")),e.push(` status: ${t==="sqlite"?"sqlite":"pg"}.varchar('status').default('draft'),`),e.push(` hasDraft: ${t==="sqlite"?"sqlite":"pg"}.boolean('hasDraft').default(false),`),e.push("});"),e.join(`
2
- `)}function j(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]=j(e[n.name],r);}}return {...i,data:e}}):f}var x=class extends chunkEJDIR56C_cjs.a{client;schema;_schemaEnsured=false;dialect;connectionString;versionsTableReady=false;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.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('postgres')).default,i=(await import('drizzle-orm/postgres-js')).drizzle;}catch{chunkD5P2IPGX_cjs.a(["postgres","drizzle-orm"]),t=(await import('postgres')).default,i=(await import('drizzle-orm/postgres-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('drizzle-orm/better-sqlite3')).drizzle;}catch{chunkD5P2IPGX_cjs.a(["better-sqlite3","drizzle-orm"]),t=(await import('better-sqlite3')).default,i=(await import('drizzle-orm/better-sqlite3')).drizzle;}let e=new t(this.connectionString.replace("file:",""));this.client=i(e,{schema:this.schema});}}this.connected=true;}async init(t,i=[]){if(await super.init(t,i),this.connectionString&&!this.client&&await this.connect(),this.client&&!this._schemaEnsured){for(let s of t){let n=this.getTableName(s.slug);this.schema[n]||(this.schema[n]=this.createTableFromConfig(s));}await this.ensureCollectionTables(t);let e=i.map(s=>({slug:`_globals_${s.slug}`,fields:s.fields,label:s.label}));for(let s of e){let n=this.getTableName(s.slug);this.schema[n]||(this.schema[n]=this.createTableFromConfig(s,true)),this.collections.has(s.slug)||this.collections.set(s.slug,s);}await this.ensureCollectionTables(e),this._schemaEnsured=true;}}createTableFromConfig(t,i=false){let e=this.getTableName(t.slug),s={id:i?pgCore.text("id").primaryKey():pgCore.uuid("id").primaryKey().defaultRandom()};for(let n of t.fields){if(!n.name||n.name==="id"||n.type==="password")continue;let r=L(n,this.dialect),a=n.name.replace(/-/g,"_"),o=a.replace(/([A-Z])/g,"_$1").toLowerCase(),c;if(this.dialect==="sqlite")switch(r){case "varchar":case "text":c=sqliteCore.text(o);break;case "integer":c=sqliteCore.integer(o);break;case "decimal":case "numeric":c=sqliteCore.numeric(o);break;case "boolean":c=sqliteCore.integer(o,{mode:"boolean"});break;case "timestamp":c=sqliteCore.text(o);break;case "jsonb":c=sqliteCore.text(o);break;default:c=sqliteCore.text(o);}else switch(r){case "varchar":c=pgCore.varchar(o,{length:255});break;case "integer":c=pgCore.integer(o);break;case "decimal":c=pgCore.decimal(o);break;case "boolean":c=pgCore.boolean(o);break;case "timestamp":c=pgCore.timestamp(o);break;case "jsonb":c=pgCore.jsonb(o);break;default:c=pgCore.text(o);}n.required||(c=c.default(null)),s[a]=c;}return s.createdAt||(s.createdAt=this.dialect==="sqlite"?sqliteCore.text("created_at").default(new Date().toISOString()):pgCore.timestamp("created_at").defaultNow()),s.updatedAt||(s.updatedAt=this.dialect==="sqlite"?sqliteCore.text("updated_at").default(new Date().toISOString()):pgCore.timestamp("updated_at").defaultNow()),e!=="users"&&e!=="audit_logs"&&(s.status||(s.status=this.dialect==="sqlite"?sqliteCore.text("status").default("draft"):pgCore.varchar("status",{length:20}).default("draft")),s.hasDraft||(s.hasDraft=this.dialect==="sqlite"?sqliteCore.integer("hasDraft",{mode:"boolean"}).default(false):pgCore.boolean("hasDraft").default(false))),this.dialect==="sqlite"?sqliteCore.sqliteTable(e,s):pgCore.pgTable(e,s)}async ensureCollectionTables(t){let i=[];for(let e of t){let s=e.slug.startsWith("_globals_"),n=this.getTableName(e.slug),r=this.generateCreateColumns(e),a=e.fields.some(u=>u.name==="createdAt"),o=e.fields.some(u=>u.name==="updatedAt"),c=e.fields.some(u=>u.name==="status"),d=e.fields.some(u=>u.name==="hasDraft");if(this.dialect==="postgres"){let u=s?'"id" TEXT PRIMARY KEY':'"id" UUID PRIMARY KEY DEFAULT gen_random_uuid()';i.push(`
3
- CREATE TABLE IF NOT EXISTS "${n}" (
4
- ${u},
5
- ${r}
6
- ${a?"":'"created_at" TIMESTAMP NOT NULL DEFAULT NOW(),'}
7
- ${o?"":'"updated_at" TIMESTAMP NOT NULL DEFAULT NOW(),'}
8
- ${c?"":`"status" VARCHAR(20) DEFAULT 'draft',`}
9
- ${d?"":'"hasDraft" BOOLEAN DEFAULT false'}
10
- )
11
- `);}else i.push(`
12
- CREATE TABLE IF NOT EXISTS "${n}" (
13
- "id" TEXT PRIMARY KEY,
14
- ${r}
15
- ${a?"":`"created_at" TEXT NOT NULL DEFAULT (datetime('now')),`}
16
- ${o?"":`"updated_at" TEXT NOT NULL DEFAULT (datetime('now')),`}
17
- ${c?"":`"status" TEXT DEFAULT 'draft',`}
18
- ${d?"":'"hasDraft" INTEGER DEFAULT 0'}
19
- )
20
- `);}if(i.length>0)if(this.dialect==="postgres")await this.client.execute(drizzleOrm.sql.raw(i.join(`;
21
- `)));else for(let e of i)await this.client.execute(drizzleOrm.sql.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.client.execute(drizzleOrm.sql`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.client.execute(drizzleOrm.sql`PRAGMA table_info("${drizzleOrm.sql.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(drizzleOrm.sql.raw(r.join(`;
22
- `)));}if(this.dialect==="postgres")for(let r of t.fields){if(!r.name||r.name==="id")continue;let a=L(r,this.dialect),o=r.name.replace(/-/g,"_").replace(/([A-Z])/g,"_$1").toLowerCase(),c=e.get(o);!c||c.type!=="character varying"||(a==="text"?await this.executeRaw(drizzleOrm.sql.raw(`ALTER TABLE "${i}" ALTER COLUMN "${o}" TYPE TEXT`)):a==="jsonb"&&(await this.executeRaw(drizzleOrm.sql.raw(`ALTER TABLE "${i}" ALTER COLUMN "${o}" DROP DEFAULT`)),await this.executeRaw(drizzleOrm.sql.raw(`ALTER TABLE "${i}" ALTER COLUMN "${o}" TYPE JSONB USING (CASE WHEN "${o}" IS NULL THEN NULL WHEN "${o}"::text ~ '^\\s*\\{' THEN "${o}"::jsonb ELSE jsonb_build_object('id', "${o}"::text) END)`))));}}generateCreateColumns(t){let i=[];for(let e of t.fields){if(!e.name||e.name==="id")continue;let s=L(e,this.dialect),n=e.name.replace(/-/g,"_").replace(/([A-Z])/g,"_$1").toLowerCase(),r=e.required?"NOT NULL":"DEFAULT NULL",a;if(this.dialect==="sqlite")switch(s){case "varchar":case "text":a=`TEXT ${r}`;break;case "integer":a=`INTEGER ${r}`;break;case "decimal":case "numeric":a=`NUMERIC ${r}`;break;case "boolean":a=`INTEGER ${r}`;break;case "timestamp":a=`TEXT ${r}`;break;case "jsonb":a=`TEXT ${r}`;break;default:a=`TEXT ${r}`;}else switch(s){case "varchar":a=`VARCHAR(255) ${r}`;break;case "integer":a=`INTEGER ${r}`;break;case "decimal":a=`DECIMAL ${r}`;break;case "boolean":a=`BOOLEAN ${r}`;break;case "timestamp":a=`TIMESTAMP ${r}`;break;case "jsonb":a=`JSONB ${r}`;break;default:a=`TEXT ${r}`;}i.push(`"${n}" ${a}`);}return i.join(`,
23
- `)+(i.length>0?",":"")}async disconnect(){this.connected=false;}async find(t){let{collection:i,where:e={},sort:s,limit:n=10,page:r=1,tenantId:a,select:o,draft:c}=t,d=this.getCollection(i),u=this.getTable(i),h={...e};this.tenantContext&&d.tenantScoped&&(h=chunkEJDIR56C_cjs.c({where:h},i,this.tenantContext,chunkEJDIR56C_cjs.b).where||{});let g=this.buildWhereClause(h,d,u,a),y=d.fields.find(m=>m.name==="status"),p=y?.type==="select"&&Array.isArray(y.options)&&y.options.some(m=>m.value==="published");!c&&u.status&&p&&g.push(drizzleOrm.eq(u.status,"published"));let A=this.parseSort(s),w=!c&&u.status&&p?{...h,status:"published"}:h,X=await this.count({collection:i,where:w,tenantId:a}),W=(r-1)*n,O=[];try{let m=u[A.field]||u.createdAt||u.id,R=A.direction==="asc"?m:drizzleOrm.desc(m),E=this.client.select().from(u);g.length>0&&(E=E.where(drizzleOrm.and(...g))),O=await E.orderBy(R).limit(n).offset(W);}catch(m){console.error("[DrizzleAdapter] Query error:",m);}let N=O.map(m=>this.processResult(m,d));return this.tenantContext&&!this.tenantContext.isSuperAdmin&&(N=N.filter(m=>chunkEJDIR56C_cjs.d(m,i,this.tenantContext,chunkEJDIR56C_cjs.b))),c&&(N=await Promise.all(N.map(async m=>{let R=await this.executeRaw(drizzleOrm.sql`
24
- SELECT * FROM kyro_versions
25
- WHERE collection_slug = ${i}
26
- AND document_id = ${m.id}
27
- ORDER BY created_at DESC
28
- LIMIT 1
29
- `);if(R.length>0){let E=R[0],V=typeof E.data=="string"?JSON.parse(E.data):E.data;return {...m,...V,status:m.status}}return m}))),{docs:N,...this.calculatePagination(r,n,X)}}async findByID(t){let{collection:i,id:e,tenantId:s,draft:n}=t,r=this.getCollection(i),a=this.getTable(i),o=this.dialect==="postgres"&&typeof e=="string"?_(e):e;if(this.tenantContext&&r.tenantScoped){let p={id:o,tenantId:this.tenantContext.tenantId};if(!chunkEJDIR56C_cjs.d(p,i,this.tenantContext,chunkEJDIR56C_cjs.b))return null}let c=[drizzleOrm.eq(a.id,o)];s&&a.tenantId&&c.push(drizzleOrm.eq(a.tenantId,s));let d=r.fields.find(p=>p.name==="status"),u=d?.type==="select"&&Array.isArray(d.options)&&d.options.some(p=>p.value==="published");!n&&a.status&&u&&c.push(drizzleOrm.eq(a.status,"published"));let h=c.length>1?drizzleOrm.and(...c):c[0],g=await this.client.select().from(a).where(h);if(g.length===0)return null;let y=this.processResult(g[0],r);if(n){let p=await this.executeRaw(drizzleOrm.sql`
30
- SELECT * FROM kyro_versions
31
- WHERE collection_slug = ${i}
32
- AND document_id = ${y.id}
33
- ORDER BY created_at DESC
34
- LIMIT 1
35
- `);if(p.length>0){let A=p[0],w=typeof A.data=="string"?JSON.parse(A.data):A.data;y={...y,...w,status:y.status};}}return y}async create(t){let{collection:i,data:e,tenantId:s}=t,n=this.getCollection(i),r=this.getTable(i),a=this.prepareData(e,n);s&&n.tenantScoped&&(a.tenantId=s);let o=await this.client.insert(r).values(a).returning();return this.processResult(o[0],n)}async update(t){let{collection:i,id:e,data:s,tenantId:n}=t,r=this.getCollection(i),a=this.getTable(i),o=this.prepareData(s,r),c=this.dialect==="postgres"&&typeof e=="string"?_(e):e,d=[drizzleOrm.eq(a.id,c)];n&&a.tenantId&&d.push(drizzleOrm.eq(a.tenantId,n));let u=await this.client.update(a).set(o).where(drizzleOrm.and(...d)).returning();if(u.length===0)throw new Error(`Document not found: ${i}/${e}`);return this.processResult(u[0],r)}async delete(t){let{collection:i,id:e,tenantId:s}=t,n=this.getCollection(i),r=this.getTable(i),a=this.dialect==="postgres"&&typeof e=="string"?_(e):e,o=[drizzleOrm.eq(r.id,a)];s&&r.tenantId&&o.push(drizzleOrm.eq(r.tenantId,s));let c=await this.client.delete(r).where(drizzleOrm.and(...o)).returning();if(c.length===0)throw new Error(`Document not found: ${i}/${e}`);return this.processResult(c[0],n)}async count(t){let{collection:i,where:e={},tenantId:s}=t,n=this.getCollection(i),r=this.getTable(i),a=this.buildWhereClause(e,n,r,s);try{let o=this.client.select({count:drizzleOrm.sql`count(*)`}).from(r);a.length>0&&(o=o.where(drizzleOrm.and(...a)));let c=await o;return Number(c[0]?.count||0)}catch{return 0}}async findOne(t){let{collection:i,where:e={},tenantId:s,draft:n}=t;if(i.startsWith("_globals_")){let a=i.replace("_globals_",""),o=this.globals.get(a);if(!o)throw new Error(`Global "${a}" not found`);let c=this.getTable(i),d=this.client.select().from(c),u=o.fields.find(p=>p.name==="status"),h=u?.type==="select"&&Array.isArray(u.options)&&u.options.some(p=>p.value==="published");!n&&c.status&&h&&(d=d.where(drizzleOrm.eq(c.status,"published")));let g=await d.limit(1);if(g.length===0)return null;let y=this.processResult(g[0],o);if(n){let p=await this.executeRaw(drizzleOrm.sql`
36
- SELECT * FROM kyro_versions
37
- WHERE collection_slug = ${i}
38
- AND document_id = ${a}
39
- ORDER BY created_at DESC
40
- LIMIT 1
41
- `);if(p.length>0){let A=p[0],w=typeof A.data=="string"?JSON.parse(A.data):A.data;y={...y,...w,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:n=1,tenantId:r}=t,a=(n-1)*s,o=this.getCollection(i),c=await this.executeRaw(drizzleOrm.sql`
42
- SELECT count(*) as count
43
- FROM kyro_versions
44
- WHERE collection_slug = ${i}
45
- AND document_id = ${e}
46
- AND autosave = 0
47
- ${r&&o.tenantScoped?drizzleOrm.sql`AND tenant_id = ${r}`:drizzleOrm.sql``}
48
- `),d=parseInt(c[0]?.count||"0");return {docs:(await this.executeRaw(drizzleOrm.sql`
49
- SELECT *
50
- FROM kyro_versions
51
- WHERE collection_slug = ${i}
52
- AND document_id = ${e}
53
- AND autosave = 0
54
- ${r&&o.tenantScoped?drizzleOrm.sql`AND tenant_id = ${r}`:drizzleOrm.sql``}
55
- ORDER BY created_at DESC
56
- LIMIT ${s}
57
- OFFSET ${a}
58
- `)).map(h=>({...h,data:typeof h.data=="string"?JSON.parse(h.data):h.data})),...this.calculatePagination(n,s,d)}}async findVersionByID(t){await this.ensureVersionsTable();let i=this.getCollection(t.collection),e=await this.executeRaw(drizzleOrm.sql`
59
- SELECT * FROM kyro_versions
60
- WHERE id = ${t.versionId}
61
- AND collection_slug = ${t.collection}
62
- ${t.tenantId&&i.tenantScoped?drizzleOrm.sql`AND tenant_id = ${t.tenantId}`:drizzleOrm.sql``}
63
- LIMIT 1
64
- `);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(drizzleOrm.sql`
65
- SELECT * FROM kyro_versions
66
- WHERE collection_slug = ${t.collection}
67
- AND document_id = ${t.documentId}
68
- AND autosave = 1
69
- ${t.tenantId&&i.tenantScoped?drizzleOrm.sql`AND tenant_id = ${t.tenantId}`:drizzleOrm.sql``}
70
- LIMIT 1
71
- `);if(n.length>0)return await this.executeRaw(drizzleOrm.sql`
72
- UPDATE kyro_versions
73
- SET data = ${JSON.stringify(t.data)},
74
- status = ${t.status},
75
- updated_at = ${e}
76
- WHERE id = ${n[0].id}
77
- `),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(drizzleOrm.sql`
78
- INSERT INTO kyro_versions (
79
- id, collection_slug, document_id, tenant_id, data, status, autosave, created_by, change_description, created_at, updated_at
80
- ) VALUES (
81
- ${s}, ${t.collection}, ${t.documentId}, ${t.tenantId&&i.tenantScoped?t.tenantId:null},
82
- ${JSON.stringify(t.data)}, ${t.status}, ${t.autosave?1:0}, ${t.createdBy||null},
83
- ${t.changeDescription||null}, ${e}, ${e}
84
- )
85
- `),!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(drizzleOrm.sql`
86
- SELECT id FROM kyro_versions
87
- WHERE collection_slug = ${t.collection}
88
- AND document_id = ${t.documentId}
89
- AND autosave = 0
90
- ${t.tenantId&&i.tenantScoped?drizzleOrm.sql`AND tenant_id = ${t.tenantId}`:drizzleOrm.sql``}
91
- ORDER BY created_at DESC
92
- LIMIT ${t.keepLatest}
93
- `)).map(n=>n.id);s.length>0&&await this.executeRaw(drizzleOrm.sql`
94
- DELETE FROM kyro_versions
95
- WHERE collection_slug = ${t.collection}
96
- AND document_id = ${t.documentId}
97
- AND autosave = 0
98
- AND id NOT IN (${drizzleOrm.sql.join(s.map(n=>drizzleOrm.sql`${n}`),drizzleOrm.sql`, `)})
99
- `);}else await this.executeRaw(drizzleOrm.sql`
100
- DELETE FROM kyro_versions
101
- WHERE collection_slug = ${t.collection}
102
- AND document_id = ${t.documentId}
103
- ${t.tenantId&&i.tenantScoped?drizzleOrm.sql`AND tenant_id = ${t.tenantId}`:drizzleOrm.sql``}
104
- `);}getTable(t){let i=this.getTableName(t),e=this.schema[i];if(!e)throw new Error(`Table "${i}" not found in schema`);return e}buildWhereClause(t,i,e,s){let n=[];s&&i.tenantScoped&&e.tenantId&&n.push(drizzleOrm.eq(e.tenantId,s));for(let[r,a]of Object.entries(t))if(r==="id"&&this.dialect==="postgres"&&(typeof a=="string"?a=_(a):a&&typeof a=="object"&&(a.equals!==void 0&&typeof a.equals=="string"&&(a={...a,equals:_(a.equals)}),a.in&&Array.isArray(a.in)&&(a={...a,in:a.in.map(o=>typeof o=="string"?_(o):o)}))),r==="AND"&&Array.isArray(a)){let o=a.map(c=>this.buildWhereClause(c,i,e)).flat().filter(Boolean);o.length>0&&n.push(drizzleOrm.and(...o));}else if(r==="OR"&&Array.isArray(a)){let o=a.map(c=>this.buildWhereClause(c,i,e)).flat().filter(Boolean);o.length>0&&n.push(drizzleOrm.or(...o));}else if(typeof a=="object"&&a!==null&&!Array.isArray(a)){let o=e[r];if(!o)continue;a.equals!==void 0&&n.push(drizzleOrm.eq(o,a.equals)),a.not_equals!==void 0&&n.push(drizzleOrm.ne(o,a.not_equals)),a.in&&Array.isArray(a.in)&&n.push(drizzleOrm.inArray(o,a.in)),a.like!==void 0&&n.push(drizzleOrm.like(o,a.like)),a.contains!==void 0&&n.push(drizzleOrm.like(o,`%${a.contains}%`)),a.greater_than!==void 0&&n.push(drizzleOrm.gt(o,a.greater_than)),a.greater_than_equal!==void 0&&n.push(drizzleOrm.gte(o,a.greater_than_equal)),a.less_than!==void 0&&n.push(drizzleOrm.lt(o,a.less_than)),a.less_than_equal!==void 0&&n.push(drizzleOrm.lte(o,a.less_than_equal));}else {let o=e[r];o&&n.push(drizzleOrm.eq(o,a));}return n}processResult(t,i){if(!t)return null;let e={...t};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]=j(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()),e}async ensureVersionsTable(){if(this.versionsTableReady)return;let t;this.dialect==="sqlite"?t=`
105
- CREATE TABLE IF NOT EXISTS kyro_versions (
106
- id text PRIMARY KEY,
107
- collection_slug text NOT NULL,
108
- document_id text NOT NULL,
109
- tenant_id text,
110
- data text NOT NULL,
111
- status text NOT NULL DEFAULT 'draft',
112
- autosave integer NOT NULL DEFAULT 0,
113
- created_by text,
114
- change_description text,
115
- created_at text DEFAULT (datetime('now')),
116
- updated_at text DEFAULT (datetime('now'))
117
- )
118
- `:t=`
119
- CREATE TABLE IF NOT EXISTS kyro_versions (
120
- id text PRIMARY KEY,
121
- collection_slug text NOT NULL,
122
- document_id text NOT NULL,
123
- tenant_id text,
124
- data text NOT NULL,
125
- status text NOT NULL,
126
- autosave integer NOT NULL DEFAULT 0,
127
- created_by text,
128
- change_description text,
129
- created_at text NOT NULL,
130
- updated_at text NOT NULL
131
- )
132
- `,await this.executeRaw(drizzleOrm.sql.raw(t));try{this.dialect==="postgres"?await this.executeRaw(drizzleOrm.sql.raw("ALTER TABLE kyro_versions ADD COLUMN IF NOT EXISTS autosave integer NOT NULL DEFAULT 0")):await this.executeRaw(drizzleOrm.sql.raw("ALTER TABLE kyro_versions ADD COLUMN autosave integer NOT NULL DEFAULT 0"));}catch{}this.versionsTableReady=true;}async executeRaw(t){let i=await this.client.execute(t);return Array.isArray(i)?i:Array.isArray(i?.rows)?i.rows:Array.isArray(i?.[0])?i[0]:[]}};function we(f){return new x(f)}var me=module$1.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('chunk-3ZFRP5M2.cjs', document.baseURI).href))),he="node:sqlite",{DatabaseSync:ye}=me(he);function ge(){return process.env.DB_TYPE==="postgres"?"postgres":"sqlite"}function B(){return crypto.randomBytes(16).toString("hex")}async function xe(){let f=ge();if(f==="sqlite"){let r=path.resolve(process.cwd(),"data","kyro.db");await promises.mkdir(path.dirname(r),{recursive:true});let a=new ye(r);return a.exec("PRAGMA journal_mode = WAL"),{db:a,dialect:f,genId:B}}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=ce__default.default(t,{max:i,ssl:e?"require":false,onnotice:()=>{}});return {db:postgresJs.drizzle(s),dialect:f,genId:B}}async function Oe(f,t){}async function Ue(f){let{roles:t}=await import('./schema-HIUSHSUI.cjs');await f.insert(t).values({name:"super_admin",level:100,inherits:[],description:"Full system access across all tenants",isSystem:true}).onConflictDoNothing();}
133
- exports.a=L;exports.b=_e;exports.c=x;exports.d=we;exports.e=B;exports.f=xe;exports.g=Oe;exports.h=Ue;