@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,44 +1,44 @@
1
- 'use strict';var chunkKCHPADCH_cjs=require('./chunk-KCHPADCH.cjs'),chunkLY7N3UHH_cjs=require('./chunk-LY7N3UHH.cjs'),chunk7ACHOBWY_cjs=require('./chunk-7ACHOBWY.cjs'),chunkBCEE4NBZ_cjs=require('./chunk-BCEE4NBZ.cjs'),chunkVRZC4TTF_cjs=require('./chunk-VRZC4TTF.cjs'),chunkVQ53TFYA_cjs=require('./chunk-VQ53TFYA.cjs'),chunkF4ITQ6XQ_cjs=require('./chunk-F4ITQ6XQ.cjs'),chunkZOVH6QT5_cjs=require('./chunk-ZOVH6QT5.cjs'),chunkBUNLC3II_cjs=require('./chunk-BUNLC3II.cjs'),crypto=require('crypto'),promises=require('fs/promises'),path=require('path'),module$1=require('module');chunkBUNLC3II_cjs.h();function D(f){if(typeof f!="string")return f;let t=f.replace(/-/g,"").toLowerCase();return t.length===32?`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`:f}function L(f,t="postgres"){switch(f.type){case "text":case "email":case "password":case "color":case "icon":return t==="sqlite"?"text":"varchar";case "textarea":case "code":case "markdown":case "secret":return "text";case "number":return f.integer?"integer":"decimal";case "checkbox":return "boolean";case "date":return "timestamp";case "select":case "radio":return t==="sqlite"?"text":"varchar";case "richtext":case "json":case "array":case "group":case "blocks":case "row":case "collapsible":case "tabs":return "jsonb";case "relationship":return t==="sqlite"?"text":"varchar";case "upload":return "jsonb";default:return "jsonb"}}function Se(f,t="postgres"){let i=f.slug.replace(/-/g,"_"),e=[];e.push(`export const ${i} = pgTable('${i}', {`),e.push(" id: uuid('id').primaryKey().defaultRandom(),");for(let s of f.fields){if(s.name==="id"||s.type==="password")continue;let 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(`
2
- `)}function le(f,t){return Array.isArray(f)?f.map(i=>{if(!i||typeof i!="object")return i;let e=i.data?{...i.data}:void 0;if(!e)return i;let s=t.find(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 chunkVQ53TFYA_cjs.a{client;schema;_schemaEnsured=false;dialect;connectionString;versionsTableReady=false;rawClient;constructor(t){if(super(),this.schema=t.schema||{},t.connectionString){this.connectionString=t.connectionString;let i=t.connectionString.toLowerCase();i.startsWith("postgres://")||i.startsWith("postgresql://")?this.dialect="postgres":i.includes(".db")||i.includes("sqlite")||i.includes("file:")?this.dialect="sqlite":this.dialect=t.type||"postgres";}else this.rawClient=t.client,this.client=t.client,this.dialect=t.type||"sqlite";}prepareData(t,i){let e=super.prepareData(t,i);e.createdAt&&typeof e.createdAt=="string"&&(e.createdAt=new Date(e.createdAt)),e.updatedAt&&typeof e.updatedAt=="string"&&(e.updatedAt=new Date(e.updatedAt));for(let s of i.fields)if(s.type==="date"&&s.name){let 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-6LAUXXDM.cjs')).default,i=(await import('./postgres-js-3Y54EXVQ.cjs')).drizzle;}catch{chunkF4ITQ6XQ_cjs.a(["postgres","drizzle-orm"]),t=(await import('./src-6LAUXXDM.cjs')).default,i=(await import('./postgres-js-3Y54EXVQ.cjs')).drizzle;}let e=t(this.connectionString,{onnotice:()=>{}});this.client=i(e,{schema:this.schema});}else if(this.dialect==="sqlite"){let t,i;try{t=(await import('better-sqlite3')).default,i=(await import('./better-sqlite3-5IISPX34.cjs')).drizzle;}catch{chunkF4ITQ6XQ_cjs.a(["better-sqlite3","drizzle-orm"]),t=(await import('better-sqlite3')).default,i=(await import('./better-sqlite3-5IISPX34.cjs')).drizzle;}let e=new t(this.connectionString.replace("file:",""));this.client=i(e,{schema:this.schema});}}if(this.rawClient&&typeof this.rawClient.prepare=="function"&&typeof this.client?.select!="function"){let{drizzle:t}=await import('./d1-5ZQJOFDX.cjs');this.client=t(this.rawClient,{schema:this.schema});}this.connected=true;}async init(t,i=[]){if(await super.init(t,i),(this.connectionString&&!this.client||this.rawClient&&typeof this.client?.select!="function")&&await this.connect(),this.client&&!this._schemaEnsured){for(let s of t){let 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=this.getTableName(t.slug),s={id:i?chunkVRZC4TTF_cjs.ia("id").primaryKey():chunkVRZC4TTF_cjs.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;if(this.dialect==="sqlite")switch(r){case "varchar":case "text":c=chunk7ACHOBWY_cjs.c(o);break;case "integer":c=chunk7ACHOBWY_cjs.a(o);break;case "decimal":case "numeric":c=chunk7ACHOBWY_cjs.b(o);break;case "boolean":c=chunk7ACHOBWY_cjs.a(o,{mode:"boolean"});break;case "timestamp":c=chunk7ACHOBWY_cjs.c(o);break;case "jsonb":c=chunk7ACHOBWY_cjs.c(o);break;default:c=chunk7ACHOBWY_cjs.c(o);}else switch(r){case "varchar":c=chunkVRZC4TTF_cjs.pa(o,{length:255});break;case "integer":c=chunkVRZC4TTF_cjs.ca(o);break;case "decimal":c=chunkVRZC4TTF_cjs.ha(o);break;case "boolean":c=chunkVRZC4TTF_cjs.$(o);break;case "timestamp":c=chunkVRZC4TTF_cjs.ma(o);break;case "jsonb":c=chunkVRZC4TTF_cjs.fa(o);break;default:c=chunkVRZC4TTF_cjs.ia(o);}a.required||(c=c.default(null)),s[n]=c;}return s.createdAt||(s.createdAt=this.dialect==="sqlite"?chunk7ACHOBWY_cjs.c("created_at").default(new Date().toISOString()):chunkVRZC4TTF_cjs.ma("created_at").defaultNow()),s.updatedAt||(s.updatedAt=this.dialect==="sqlite"?chunk7ACHOBWY_cjs.c("updated_at").default(new Date().toISOString()):chunkVRZC4TTF_cjs.ma("updated_at").defaultNow()),e!=="users"&&e!=="audit_logs"&&(s.status||(s.status=this.dialect==="sqlite"?chunk7ACHOBWY_cjs.c("status").default("draft"):chunkVRZC4TTF_cjs.pa("status",{length:20}).default("draft")),s.hasDraft||(s.hasDraft=this.dialect==="sqlite"?chunk7ACHOBWY_cjs.a("hasDraft",{mode:"boolean"}).default(false):chunkVRZC4TTF_cjs.$("hasDraft").default(false))),this.dialect==="sqlite"?chunk7ACHOBWY_cjs.e(e,s):chunkVRZC4TTF_cjs.ra(e,s)}async ensureCollectionTables(t){let i=[];for(let e of t){let s=e.slug.startsWith("_globals_"),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(`
3
- CREATE TABLE IF NOT EXISTS "${a}" (
1
+ 'use strict';var chunkKCHPADCH_cjs=require('./chunk-KCHPADCH.cjs'),chunkLY7N3UHH_cjs=require('./chunk-LY7N3UHH.cjs'),chunk7ACHOBWY_cjs=require('./chunk-7ACHOBWY.cjs'),chunkBCEE4NBZ_cjs=require('./chunk-BCEE4NBZ.cjs'),chunkVRZC4TTF_cjs=require('./chunk-VRZC4TTF.cjs'),chunkVQ53TFYA_cjs=require('./chunk-VQ53TFYA.cjs'),chunkF4ITQ6XQ_cjs=require('./chunk-F4ITQ6XQ.cjs'),chunkZOVH6QT5_cjs=require('./chunk-ZOVH6QT5.cjs'),chunkBUNLC3II_cjs=require('./chunk-BUNLC3II.cjs'),crypto=require('crypto'),promises=require('fs/promises'),path=require('path'),module$1=require('module');chunkBUNLC3II_cjs.h();function D(f){if(typeof f!="string")return f;let t=f.replace(/-/g,"").toLowerCase();return t.length===32?`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`:f}function L(f,t="postgres"){switch(f.type){case "text":case "email":case "password":case "color":case "icon":return t==="sqlite"?"text":"varchar";case "textarea":case "code":case "markdown":case "secret":return "text";case "number":return f.integer?"integer":"decimal";case "checkbox":return "boolean";case "date":return "timestamp";case "select":case "radio":return t==="sqlite"?"text":"varchar";case "richtext":case "json":case "array":case "group":case "blocks":case "row":case "collapsible":case "tabs":return "jsonb";case "relationship":return t==="sqlite"?"text":"varchar";case "upload":return "jsonb";default:return "jsonb"}}function Se(f,t="postgres"){let i=f.slug.replace(/-/g,"_"),e=[];e.push(`export const ${i} = pgTable('${i}', {`),e.push(" id: uuid('id').primaryKey().defaultRandom(),");for(let s of f.fields){if(s.name==="id"||s.type==="password")continue;let n=L(s,t),r=s.required,a=` ${s.name}: pg.${n}('${s.name}')`;s.unique&&(a+=".unique()"),r||(a+=".nullable()"),s.defaultValue!==void 0&&(typeof s.defaultValue=="string"?a+=`.default('${s.defaultValue}')`:typeof s.defaultValue=="boolean"?a+=`.default(${s.defaultValue})`:a+=`.default(sql\`${JSON.stringify(s.defaultValue)}\`)`),a+=",",e.push(a);}return f.timestamps&&(e.push(" createdAt: pg.timestamp('created_at').defaultNow(),"),e.push(" updatedAt: pg.timestamp('updated_at').defaultNow(),")),e.push(` status: ${t==="sqlite"?"sqlite":"pg"}.varchar('status').default('draft'),`),e.push(` hasDraft: ${t==="sqlite"?"sqlite":"pg"}.boolean('hasDraft').default(false),`),e.push("});"),e.join(`
2
+ `)}function le(f,t){return Array.isArray(f)?f.map(i=>{if(!i||typeof i!="object")return i;let e=i.data?{...i.data}:void 0;if(!e)return i;let s=t.find(n=>n.slug===i.type||n.slug===i.slug);if(!s||!Array.isArray(s.fields))return i;for(let n of s.fields){if(n.name&&(n.type==="upload"||n.type==="image")&&e[n.name]){let r=e[n.name];Array.isArray(r)?e[n.name]=r.map(a=>typeof a=="string"?{id:a}:a):typeof r=="string"&&(e[n.name]={id:r});}if(n.type==="blocks"&&n.name&&e[n.name]){let r=n.blocks||[];e[n.name]=le(e[n.name],r);}}return {...i,data:e}}):f}var M=class extends chunkVQ53TFYA_cjs.a{client;schema;_schemaEnsured=false;dialect;connectionString;versionsTableReady=false;rawClient;constructor(t){if(super(),this.schema=t.schema||{},t.connectionString){this.connectionString=t.connectionString;let i=t.connectionString.toLowerCase();i.startsWith("postgres://")||i.startsWith("postgresql://")?this.dialect="postgres":i.includes(".db")||i.includes("sqlite")||i.includes("file:")?this.dialect="sqlite":this.dialect=t.type||"postgres";}else this.rawClient=t.client,this.client=t.client,this.dialect=t.type||"sqlite";}prepareData(t,i){let e=super.prepareData(t,i);e.createdAt&&typeof e.createdAt=="string"&&(e.createdAt=new Date(e.createdAt)),e.updatedAt&&typeof e.updatedAt=="string"&&(e.updatedAt=new Date(e.updatedAt));for(let s of i.fields)if(s.type==="date"&&s.name){let n=e[s.name];n&&typeof n=="string"&&(e[s.name]=new Date(n));}for(let s of i.fields){let r=L(s,this.dialect)==="jsonb";if(s.type==="tabs"&&"tabs"in s&&s.name){let a=t[s.name];if(a&&typeof a=="object"){let o={};for(let[c,d]of Object.entries(a)){let u=s.tabs.flatMap(g=>g.fields).find(g=>g.name===c);(u?.type==="upload"||u?.type==="image"||u?.type==="list"||u?.type==="relationship-block")&&d?o[c]=Array.isArray(d)||typeof d=="object"?JSON.stringify(d):d:o[c]=d;}e[s.name]=this.dialect==="sqlite"||!r?JSON.stringify(o):o;}}else if(r&&s.name&&t[s.name]!==void 0&&t[s.name]!==null)e[s.name]=this.dialect==="sqlite"?JSON.stringify(t[s.name]):t[s.name];else if((s.type==="upload"||s.type==="image"||s.type==="list"||s.type==="relationship-block")&&s.name){let a=t[s.name];a!=null&&(e[s.name]=this.dialect==="sqlite"||!r?typeof a=="string"?a:JSON.stringify(a):a);}}for(let s of i.fields)if(s.name&&e[s.name]===""){let n=L(s,this.dialect);(n==="timestamp"||n==="jsonb"||n==="decimal"||n==="integer"||n==="numeric"||n==="boolean")&&(e[s.name]=null);}return e}async connect(){if(this.connectionString&&!this.client){if(this.dialect==="postgres"){let t,i;try{t=(await import('./src-6LAUXXDM.cjs')).default,i=(await import('./postgres-js-3Y54EXVQ.cjs')).drizzle;}catch{chunkF4ITQ6XQ_cjs.a(["postgres","drizzle-orm"]),t=(await import('./src-6LAUXXDM.cjs')).default,i=(await import('./postgres-js-3Y54EXVQ.cjs')).drizzle;}let e=t(this.connectionString,{onnotice:()=>{}});this.client=i(e,{schema:this.schema});}else if(this.dialect==="sqlite"){let t,i;try{t=(await import('better-sqlite3')).default,i=(await import('./better-sqlite3-5IISPX34.cjs')).drizzle;}catch{chunkF4ITQ6XQ_cjs.a(["better-sqlite3","drizzle-orm"]),t=(await import('better-sqlite3')).default,i=(await import('./better-sqlite3-5IISPX34.cjs')).drizzle;}let e=new t(this.connectionString.replace("file:",""));this.client=i(e,{schema:this.schema});}}if(this.rawClient&&typeof this.rawClient.prepare=="function"&&typeof this.client?.select!="function"){let{drizzle:t}=await import('./d1-5ZQJOFDX.cjs');this.client=t(this.rawClient,{schema:this.schema});}this.connected=true;}async init(t,i=[]){if(await super.init(t,i),(this.connectionString&&!this.client||this.rawClient&&typeof this.client?.select!="function")&&await this.connect(),this.client&&!this._schemaEnsured){for(let s of t){let n=this.getTableName(s.slug);this.schema[n]||(this.schema[n]=this.createTableFromConfig(s));}await this.ensureCollectionTables(t);let e=i.map(s=>({slug:`_globals_${s.slug}`,fields:s.fields,label:s.label}));for(let s of e){let n=this.getTableName(s.slug);this.schema[n]||(this.schema[n]=this.createTableFromConfig(s,true)),this.collections.has(s.slug)||this.collections.set(s.slug,s);}await this.ensureCollectionTables(e),this._schemaEnsured=true;}}createTableFromConfig(t,i=false){let e=this.getTableName(t.slug),s={id:i?chunkVRZC4TTF_cjs.ia("id").primaryKey():chunkVRZC4TTF_cjs.oa("id").primaryKey().defaultRandom()};for(let n of t.fields){if(!n.name||n.name==="id"||n.type==="password")continue;let r=L(n,this.dialect),a=n.name.replace(/-/g,"_"),o=a.replace(/([A-Z])/g,"_$1").toLowerCase(),c;if(this.dialect==="sqlite")switch(r){case "varchar":case "text":c=chunk7ACHOBWY_cjs.c(o);break;case "integer":c=chunk7ACHOBWY_cjs.a(o);break;case "decimal":case "numeric":c=chunk7ACHOBWY_cjs.b(o);break;case "boolean":c=chunk7ACHOBWY_cjs.a(o,{mode:"boolean"});break;case "timestamp":c=chunk7ACHOBWY_cjs.c(o);break;case "jsonb":c=chunk7ACHOBWY_cjs.c(o);break;default:c=chunk7ACHOBWY_cjs.c(o);}else switch(r){case "varchar":c=chunkVRZC4TTF_cjs.pa(o,{length:255});break;case "integer":c=chunkVRZC4TTF_cjs.ca(o);break;case "decimal":c=chunkVRZC4TTF_cjs.ha(o);break;case "boolean":c=chunkVRZC4TTF_cjs.$(o);break;case "timestamp":c=chunkVRZC4TTF_cjs.ma(o);break;case "jsonb":c=chunkVRZC4TTF_cjs.fa(o);break;default:c=chunkVRZC4TTF_cjs.ia(o);}n.required||(c=c.default(null)),s[a]=c;}return s.createdAt||(s.createdAt=this.dialect==="sqlite"?chunk7ACHOBWY_cjs.c("created_at").default(new Date().toISOString()):chunkVRZC4TTF_cjs.ma("created_at").defaultNow()),s.updatedAt||(s.updatedAt=this.dialect==="sqlite"?chunk7ACHOBWY_cjs.c("updated_at").default(new Date().toISOString()):chunkVRZC4TTF_cjs.ma("updated_at").defaultNow()),e!=="users"&&e!=="audit_logs"&&(s.status||(s.status=this.dialect==="sqlite"?chunk7ACHOBWY_cjs.c("status").default("draft"):chunkVRZC4TTF_cjs.pa("status",{length:20}).default("draft")),s.hasDraft||(s.hasDraft=this.dialect==="sqlite"?chunk7ACHOBWY_cjs.a("hasDraft",{mode:"boolean"}).default(false):chunkVRZC4TTF_cjs.$("hasDraft").default(false))),this.dialect==="sqlite"?chunk7ACHOBWY_cjs.e(e,s):chunkVRZC4TTF_cjs.ra(e,s)}async ensureCollectionTables(t){let i=[];for(let e of t){let s=e.slug.startsWith("_globals_"),n=this.getTableName(e.slug),r=this.generateCreateColumns(e),a=e.fields.some(u=>u.name==="createdAt"),o=e.fields.some(u=>u.name==="updatedAt"),c=e.fields.some(u=>u.name==="status"),d=e.fields.some(u=>u.name==="hasDraft");if(this.dialect==="postgres"){let u=s?'"id" TEXT PRIMARY KEY':'"id" UUID PRIMARY KEY DEFAULT gen_random_uuid()';i.push(`
3
+ CREATE TABLE IF NOT EXISTS "${n}" (
4
4
  ${u},
5
5
  ${r}
6
- ${n?"":'"created_at" TIMESTAMP NOT NULL DEFAULT NOW(),'}
6
+ ${a?"":'"created_at" TIMESTAMP NOT NULL DEFAULT NOW(),'}
7
7
  ${o?"":'"updated_at" TIMESTAMP NOT NULL DEFAULT NOW(),'}
8
8
  ${c?"":`"status" VARCHAR(20) DEFAULT 'draft',`}
9
9
  ${d?"":'"hasDraft" BOOLEAN DEFAULT false'}
10
10
  )
11
11
  `);}else i.push(`
12
- CREATE TABLE IF NOT EXISTS "${a}" (
12
+ CREATE TABLE IF NOT EXISTS "${n}" (
13
13
  "id" TEXT PRIMARY KEY,
14
14
  ${r}
15
- ${n?"":`"created_at" TEXT NOT NULL DEFAULT (datetime('now')),`}
15
+ ${a?"":`"created_at" TEXT NOT NULL DEFAULT (datetime('now')),`}
16
16
  ${o?"":`"updated_at" TEXT NOT NULL DEFAULT (datetime('now')),`}
17
17
  ${c?"":`"status" TEXT DEFAULT 'draft',`}
18
18
  ${d?"":'"hasDraft" INTEGER DEFAULT 0'}
19
19
  )
20
20
  `);}if(i.length>0)if(this.dialect==="postgres")await this.executeRaw(chunkVRZC4TTF_cjs.J.raw(i.join(`;
21
- `)));else for(let e of i)await this.executeRaw(chunkVRZC4TTF_cjs.J.raw(e));for(let e of t){let s=this.getTableName(e.slug);s==="users"||s==="audit_logs"||await this.syncTableColumns(e,s);}}getColumnSqlDefinition(t,i){let e=L(t,i),s=t.name.replace(/-/g,"_").replace(/([A-Z])/g,"_$1").toLowerCase(),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(chunkVRZC4TTF_cjs.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(chunkVRZC4TTF_cjs.J`PRAGMA table_info("${chunkVRZC4TTF_cjs.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(chunkVRZC4TTF_cjs.J.raw(r.join(`;
22
- `)));}if(this.dialect==="postgres")for(let r of t.fields){if(!r.name||r.name==="id")continue;let 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(chunkVRZC4TTF_cjs.J.raw(`ALTER TABLE "${i}" ALTER COLUMN "${o}" TYPE TEXT`)):n==="jsonb"&&(await this.executeRaw(chunkVRZC4TTF_cjs.J.raw(`ALTER TABLE "${i}" ALTER COLUMN "${o}" DROP DEFAULT`)),await this.executeRaw(chunkVRZC4TTF_cjs.J.raw(`ALTER TABLE "${i}" ALTER COLUMN "${o}" TYPE JSONB USING (CASE WHEN "${o}" IS NULL THEN NULL WHEN "${o}"::text ~ '^\\s*\\{' THEN "${o}"::jsonb ELSE jsonb_build_object('id', "${o}"::text) END)`))));}}generateCreateColumns(t){let i=[];for(let e of t.fields){if(!e.name||e.name==="id")continue;let s=L(e,this.dialect),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(`,
23
- `)+(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,select:o,draft:c}=t,d=this.getCollection(i),u=this.getTable(i),m={...e};this.tenantContext&&d.tenantScoped&&(m=chunkVQ53TFYA_cjs.c({where:m},i,this.tenantContext,chunkVQ53TFYA_cjs.b).where||{});let g=this.buildWhereClause(m,d,u,n),y=d.fields.find(h=>h.name==="status"),p=y?.type==="select"&&Array.isArray(y.options)&&y.options.some(h=>h.value==="published");!c&&u.status&&p&&g.push(chunkBCEE4NBZ_cjs.n(u.status,"published"));let A=this.parseSort(s),_=!c&&u.status&&p?{...m,status:"published"}:m,ue=await this.count({collection:i,where:_,tenantId:n}),fe=(r-1)*a,P=[];try{let h=u[A.field]||u.createdAt||u.id,R=A.direction==="asc"?h:chunkBCEE4NBZ_cjs.M(h),E=this.client.select().from(u);g.length>0&&(E=E.where(chunkBCEE4NBZ_cjs.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));return this.tenantContext&&!this.tenantContext.isSuperAdmin&&(N=N.filter(h=>chunkVQ53TFYA_cjs.d(h,i,this.tenantContext,chunkVQ53TFYA_cjs.b))),c&&(N=await Promise.all(N.map(async h=>{let R=await this.executeRaw(chunkVRZC4TTF_cjs.J`
21
+ `)));else for(let e of i)await this.executeRaw(chunkVRZC4TTF_cjs.J.raw(e));for(let e of t){let s=this.getTableName(e.slug);s==="users"||s==="audit_logs"||await this.syncTableColumns(e,s);}}getColumnSqlDefinition(t,i){let e=L(t,i),s=t.name.replace(/-/g,"_").replace(/([A-Z])/g,"_$1").toLowerCase(),n=this.columnSqlType(e,i);return `"${s}" ${n} DEFAULT NULL`}columnSqlType(t,i){if(i==="sqlite")switch(t){case "varchar":return "TEXT";case "text":return "TEXT";case "integer":return "INTEGER";case "decimal":case "numeric":return "NUMERIC";case "boolean":return "INTEGER";case "timestamp":return "TEXT";case "jsonb":return "TEXT";default:return "TEXT"}switch(t){case "varchar":return "VARCHAR(255)";case "text":return "TEXT";case "integer":return "INTEGER";case "decimal":case "numeric":return "DECIMAL";case "boolean":return "BOOLEAN";case "timestamp":return "TIMESTAMP";case "jsonb":return "JSONB";default:return "TEXT"}}getExpectedColumnDefs(t,i){let e={},s=t.slug.startsWith("_globals_"),n=t.fields.some(c=>c.name==="createdAt"),r=t.fields.some(c=>c.name==="updatedAt"),a=t.fields.some(c=>c.name==="status"),o=t.fields.some(c=>c.name==="hasDraft");this.dialect==="postgres"?(e.id=s?'"id" TEXT PRIMARY KEY':'"id" UUID PRIMARY KEY DEFAULT gen_random_uuid()',n||(e.created_at='"created_at" TIMESTAMP DEFAULT NULL'),r||(e.updated_at='"updated_at" TIMESTAMP DEFAULT NULL'),a||(e.status='"status" VARCHAR(20) DEFAULT NULL'),o||(e.hasDraft='"hasDraft" BOOLEAN DEFAULT NULL')):(e.id='"id" TEXT PRIMARY KEY',n||(e.created_at='"created_at" TEXT DEFAULT NULL'),r||(e.updated_at='"updated_at" TEXT DEFAULT NULL'),a||(e.status='"status" TEXT DEFAULT NULL'),o||(e.hasDraft='"hasDraft" INTEGER DEFAULT NULL'));for(let c of t.fields){if(!c.name||c.name==="id")continue;let d=this.getColumnSqlDefinition(c,this.dialect),u=c.name.replace(/-/g,"_").replace(/([A-Z])/g,"_$1").toLowerCase();e[u]=d;}return e}async syncTableColumns(t,i){let e;try{if(this.dialect==="postgres"){let r=await this.executeRaw(chunkVRZC4TTF_cjs.J`SELECT column_name, data_type, character_maximum_length FROM information_schema.columns WHERE table_name = ${i}`);e=new Map(r.map(a=>[a.column_name,{type:a.data_type,maxLen:a.character_maximum_length}]));}else {let r=await this.executeRaw(chunkVRZC4TTF_cjs.J`PRAGMA table_info("${chunkVRZC4TTF_cjs.J.raw(i)}")`);e=new Map(r.map(a=>[a.name,{type:a.type,maxLen:null}]));}}catch{return}let s=this.getExpectedColumnDefs(t,i),n=Object.keys(s).filter(r=>!e.has(r));if(n.length>0){let r=n.map(a=>`ALTER TABLE "${i}" ADD COLUMN ${s[a]}`);await this.executeRaw(chunkVRZC4TTF_cjs.J.raw(r.join(`;
22
+ `)));}if(this.dialect==="postgres")for(let r of t.fields){if(!r.name||r.name==="id")continue;let a=L(r,this.dialect),o=r.name.replace(/-/g,"_").replace(/([A-Z])/g,"_$1").toLowerCase(),c=e.get(o);!c||c.type!=="character varying"||(a==="text"?await this.executeRaw(chunkVRZC4TTF_cjs.J.raw(`ALTER TABLE "${i}" ALTER COLUMN "${o}" TYPE TEXT`)):a==="jsonb"&&(await this.executeRaw(chunkVRZC4TTF_cjs.J.raw(`ALTER TABLE "${i}" ALTER COLUMN "${o}" DROP DEFAULT`)),await this.executeRaw(chunkVRZC4TTF_cjs.J.raw(`ALTER TABLE "${i}" ALTER COLUMN "${o}" TYPE JSONB USING (CASE WHEN "${o}" IS NULL THEN NULL WHEN "${o}"::text ~ '^\\s*\\{' THEN "${o}"::jsonb ELSE jsonb_build_object('id', "${o}"::text) END)`))));}}generateCreateColumns(t){let i=[];for(let e of t.fields){if(!e.name||e.name==="id")continue;let s=L(e,this.dialect),n=e.name.replace(/-/g,"_").replace(/([A-Z])/g,"_$1").toLowerCase(),r=e.required?"NOT NULL":"DEFAULT NULL",a;if(this.dialect==="sqlite")switch(s){case "varchar":case "text":a=`TEXT ${r}`;break;case "integer":a=`INTEGER ${r}`;break;case "decimal":case "numeric":a=`NUMERIC ${r}`;break;case "boolean":a=`INTEGER ${r}`;break;case "timestamp":a=`TEXT ${r}`;break;case "jsonb":a=`TEXT ${r}`;break;default:a=`TEXT ${r}`;}else switch(s){case "varchar":a=`VARCHAR(255) ${r}`;break;case "integer":a=`INTEGER ${r}`;break;case "decimal":a=`DECIMAL ${r}`;break;case "boolean":a=`BOOLEAN ${r}`;break;case "timestamp":a=`TIMESTAMP ${r}`;break;case "jsonb":a=`JSONB ${r}`;break;default:a=`TEXT ${r}`;}i.push(`"${n}" ${a}`);}return i.join(`,
23
+ `)+(i.length>0?",":"")}async disconnect(){this.connected=false;}async find(t){let{collection:i,where:e={},sort:s,limit:n=10,page:r=1,tenantId:a,select:o,draft:c}=t,d=this.getCollection(i),u=this.getTable(i),m={...e};this.tenantContext&&d.tenantScoped&&(m=chunkVQ53TFYA_cjs.c({where:m},i,this.tenantContext,chunkVQ53TFYA_cjs.b).where||{});let g=this.buildWhereClause(m,d,u,a),y=d.fields.find(h=>h.name==="status"),p=y?.type==="select"&&Array.isArray(y.options)&&y.options.some(h=>h.value==="published");!c&&u.status&&p&&g.push(chunkBCEE4NBZ_cjs.n(u.status,"published"));let b=this.parseSort(s),_=!c&&u.status&&p?{...m,status:"published"}:m,ue=await this.count({collection:i,where:_,tenantId:a}),fe=(r-1)*n,P=[];try{let h=u[b.field]||u.createdAt||u.id,R=b.direction==="asc"?h:chunkBCEE4NBZ_cjs.M(h),A=this.client.select().from(u);g.length>0&&(A=A.where(chunkBCEE4NBZ_cjs.p(...g))),P=await A.orderBy(R).limit(n).offset(fe);}catch(h){console.error("[DrizzleAdapter] Query error:",h);}let N=P.map(h=>this.processResult(h,d));return this.tenantContext&&!this.tenantContext.isSuperAdmin&&(N=N.filter(h=>chunkVQ53TFYA_cjs.d(h,i,this.tenantContext,chunkVQ53TFYA_cjs.b))),c&&(N=await Promise.all(N.map(async h=>{let R=await this.executeRaw(chunkVRZC4TTF_cjs.J`
24
24
  SELECT * FROM kyro_versions
25
25
  WHERE collection_slug = ${i}
26
26
  AND document_id = ${h.id}
27
27
  ORDER BY created_at DESC
28
28
  LIMIT 1
29
- `);if(R.length>0){let 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=this.getTable(i),o=this.dialect==="postgres"&&typeof e=="string"?D(e):e;if(this.tenantContext&&r.tenantScoped){let p={id:o,tenantId:this.tenantContext.tenantId};if(!chunkVQ53TFYA_cjs.d(p,i,this.tenantContext,chunkVQ53TFYA_cjs.b))return null}let c=[chunkBCEE4NBZ_cjs.n(n.id,o)];s&&n.tenantId&&c.push(chunkBCEE4NBZ_cjs.n(n.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");!a&&n.status&&u&&c.push(chunkBCEE4NBZ_cjs.n(n.status,"published"));let m=c.length>1?chunkBCEE4NBZ_cjs.p(...c):c[0],g=await this.client.select().from(n).where(m);if(g.length===0)return null;let y=this.processResult(g[0],r);if(a){let p=await this.executeRaw(chunkVRZC4TTF_cjs.J`
29
+ `);if(R.length>0){let A=R[0],pe=typeof A.data=="string"?JSON.parse(A.data):A.data;return {...h,...pe,status:h.status,_hasUnpublishedChanges:A.status==="draft"}}return h}))),{docs:N,...this.calculatePagination(r,n,ue)}}async findByID(t){let{collection:i,id:e,tenantId:s,draft:n}=t,r=this.getCollection(i),a=this.getTable(i),o=this.dialect==="postgres"&&typeof e=="string"?D(e):e;if(this.tenantContext&&r.tenantScoped){let p={id:o,tenantId:this.tenantContext.tenantId};if(!chunkVQ53TFYA_cjs.d(p,i,this.tenantContext,chunkVQ53TFYA_cjs.b))return null}let c=[chunkBCEE4NBZ_cjs.n(a.id,o)];s&&a.tenantId&&c.push(chunkBCEE4NBZ_cjs.n(a.tenantId,s));let d=r.fields.find(p=>p.name==="status"),u=d?.type==="select"&&Array.isArray(d.options)&&d.options.some(p=>p.value==="published");!n&&a.status&&u&&c.push(chunkBCEE4NBZ_cjs.n(a.status,"published"));let m=c.length>1?chunkBCEE4NBZ_cjs.p(...c):c[0],g=await this.client.select().from(a).where(m);if(g.length===0)return null;let y=this.processResult(g[0],r);if(n){let p=await this.executeRaw(chunkVRZC4TTF_cjs.J`
30
30
  SELECT * FROM kyro_versions
31
31
  WHERE collection_slug = ${i}
32
32
  AND document_id = ${y.id}
33
33
  ORDER BY created_at DESC
34
34
  LIMIT 1
35
- `);if(p.length>0){let 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=this.getTable(i),o=this.prepareData(s,r),c=this.dialect==="postgres"&&typeof e=="string"?D(e):e,d=[chunkBCEE4NBZ_cjs.n(n.id,c)];a&&n.tenantId&&d.push(chunkBCEE4NBZ_cjs.n(n.tenantId,a));let u=await this.client.update(n).set(o).where(chunkBCEE4NBZ_cjs.p(...d)).returning();if(u.length===0)throw new Error(`Document not found: ${i}/${e}`);return this.processResult(u[0],r)}async delete(t){let{collection:i,id:e,tenantId:s}=t,a=this.getCollection(i),r=this.getTable(i),n=this.dialect==="postgres"&&typeof e=="string"?D(e):e,o=[chunkBCEE4NBZ_cjs.n(r.id,n)];s&&r.tenantId&&o.push(chunkBCEE4NBZ_cjs.n(r.tenantId,s));let c=await this.client.delete(r).where(chunkBCEE4NBZ_cjs.p(...o)).returning();if(c.length===0)throw new Error(`Document not found: ${i}/${e}`);return this.processResult(c[0],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:chunkVRZC4TTF_cjs.J`count(*)`}).from(r);n.length>0&&(o=o.where(chunkBCEE4NBZ_cjs.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=i.replace("_globals_",""),o=this.globals.get(n);if(!o)throw new Error(`Global "${n}" 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(chunkBCEE4NBZ_cjs.n(c.status,"published")));let g=await d.limit(1);if(g.length===0)return null;let y=this.processResult(g[0],o);if(a){let p=await this.executeRaw(chunkVRZC4TTF_cjs.J`
35
+ `);if(p.length>0){let b=p[0],_=typeof b.data=="string"?JSON.parse(b.data):b.data;y={...y,..._,status:y.status,_hasUnpublishedChanges:b.status==="draft"};}}return y}async create(t){let{collection:i,data:e,tenantId:s}=t,n=this.getCollection(i),r=this.getTable(i),a=this.prepareData(e,n);s&&n.tenantScoped&&(a.tenantId=s);let o=await this.client.insert(r).values(a).returning();return this.processResult(o[0],n)}async update(t){let{collection:i,id:e,data:s,tenantId:n}=t,r=this.getCollection(i),a=this.getTable(i),o=this.prepareData(s,r),c=this.dialect==="postgres"&&typeof e=="string"?D(e):e,d=[chunkBCEE4NBZ_cjs.n(a.id,c)];n&&a.tenantId&&d.push(chunkBCEE4NBZ_cjs.n(a.tenantId,n));let u=await this.client.update(a).set(o).where(chunkBCEE4NBZ_cjs.p(...d)).returning();if(u.length===0)throw new Error(`Document not found: ${i}/${e}`);return this.processResult(u[0],r)}async delete(t){let{collection:i,id:e,tenantId:s}=t,n=this.getCollection(i),r=this.getTable(i),a=this.dialect==="postgres"&&typeof e=="string"?D(e):e,o=[chunkBCEE4NBZ_cjs.n(r.id,a)];s&&r.tenantId&&o.push(chunkBCEE4NBZ_cjs.n(r.tenantId,s));let c=await this.client.delete(r).where(chunkBCEE4NBZ_cjs.p(...o)).returning();if(c.length===0)throw new Error(`Document not found: ${i}/${e}`);return this.processResult(c[0],n)}async count(t){let{collection:i,where:e={},tenantId:s}=t,n=this.getCollection(i),r=this.getTable(i),a=this.buildWhereClause(e,n,r,s);try{let o=this.client.select({count:chunkVRZC4TTF_cjs.J`count(*)`}).from(r);a.length>0&&(o=o.where(chunkBCEE4NBZ_cjs.p(...a)));let c=await o;return Number(c[0]?.count||0)}catch{return 0}}async findOne(t){let{collection:i,where:e={},tenantId:s,draft:n}=t;if(i.startsWith("_globals_")){let a=i.replace("_globals_",""),o=this.globals.get(a);if(!o)throw new Error(`Global "${a}" not found`);let c=this.getTable(i),d=this.client.select().from(c),u=o.fields.find(p=>p.name==="status"),m=u?.type==="select"&&Array.isArray(u.options)&&u.options.some(p=>p.value==="published");!n&&c.status&&m&&(d=d.where(chunkBCEE4NBZ_cjs.n(c.status,"published")));let g=await d.limit(1);if(g.length===0)return null;let y=this.processResult(g[0],o);if(n){let p=await this.executeRaw(chunkVRZC4TTF_cjs.J`
36
36
  SELECT * FROM kyro_versions
37
37
  WHERE collection_slug = ${i}
38
- AND document_id = ${n}
38
+ AND document_id = ${a}
39
39
  ORDER BY created_at DESC
40
40
  LIMIT 1
41
- `);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(chunkVRZC4TTF_cjs.J`
41
+ `);if(p.length>0){let b=p[0],_=typeof b.data=="string"?JSON.parse(b.data):b.data;y={...y,..._,status:y.status,_hasUnpublishedChanges:b.status==="draft"};}}return y}return (await this.find({...t,limit:1})).docs[0]||null}async findVersions(t){await this.ensureVersionsTable();let{collection:i,documentId:e,limit:s=10,page:n=1,tenantId:r}=t,a=(n-1)*s,o=this.getCollection(i),c=await this.executeRaw(chunkVRZC4TTF_cjs.J`
42
42
  SELECT count(*) as count
43
43
  FROM kyro_versions
44
44
  WHERE collection_slug = ${i}
@@ -54,27 +54,27 @@
54
54
  ${r&&o.tenantScoped?chunkVRZC4TTF_cjs.J`AND tenant_id = ${r}`:chunkVRZC4TTF_cjs.J``}
55
55
  ORDER BY created_at DESC
56
56
  LIMIT ${s}
57
- OFFSET ${n}
58
- `)).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(chunkVRZC4TTF_cjs.J`
57
+ OFFSET ${a}
58
+ `)).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(chunkVRZC4TTF_cjs.J`
59
59
  SELECT * FROM kyro_versions
60
60
  WHERE id = ${t.versionId}
61
61
  AND collection_slug = ${t.collection}
62
62
  ${t.tenantId&&i.tenantScoped?chunkVRZC4TTF_cjs.J`AND tenant_id = ${t.tenantId}`:chunkVRZC4TTF_cjs.J``}
63
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 a=await this.executeRaw(chunkVRZC4TTF_cjs.J`
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(chunkVRZC4TTF_cjs.J`
65
65
  SELECT * FROM kyro_versions
66
66
  WHERE collection_slug = ${t.collection}
67
67
  AND document_id = ${t.documentId}
68
68
  AND autosave = 1
69
69
  ${t.tenantId&&i.tenantScoped?chunkVRZC4TTF_cjs.J`AND tenant_id = ${t.tenantId}`:chunkVRZC4TTF_cjs.J``}
70
70
  LIMIT 1
71
- `);if(a.length>0)return await this.executeRaw(chunkVRZC4TTF_cjs.J`
71
+ `);if(n.length>0)return await this.executeRaw(chunkVRZC4TTF_cjs.J`
72
72
  UPDATE kyro_versions
73
73
  SET data = ${JSON.stringify(t.data)},
74
74
  status = ${t.status},
75
75
  updated_at = ${e}
76
- WHERE id = ${a[0].id}
77
- `),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(chunkVRZC4TTF_cjs.J`
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(chunkVRZC4TTF_cjs.J`
78
78
  INSERT INTO kyro_versions (
79
79
  id, collection_slug, document_id, tenant_id, data, status, autosave, created_by, change_description, created_at, updated_at
80
80
  ) VALUES (
@@ -82,7 +82,7 @@
82
82
  ${JSON.stringify(t.data)}, ${t.status}, ${t.autosave?1:0}, ${t.createdBy||null},
83
83
  ${t.changeDescription||null}, ${e}, ${e}
84
84
  )
85
- `),!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(chunkVRZC4TTF_cjs.J`
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(chunkVRZC4TTF_cjs.J`
86
86
  SELECT id FROM kyro_versions
87
87
  WHERE collection_slug = ${t.collection}
88
88
  AND document_id = ${t.documentId}
@@ -90,18 +90,18 @@
90
90
  ${t.tenantId&&i.tenantScoped?chunkVRZC4TTF_cjs.J`AND tenant_id = ${t.tenantId}`:chunkVRZC4TTF_cjs.J``}
91
91
  ORDER BY created_at DESC
92
92
  LIMIT ${t.keepLatest}
93
- `)).map(a=>a.id);s.length>0&&await this.executeRaw(chunkVRZC4TTF_cjs.J`
93
+ `)).map(n=>n.id);s.length>0&&await this.executeRaw(chunkVRZC4TTF_cjs.J`
94
94
  DELETE FROM kyro_versions
95
95
  WHERE collection_slug = ${t.collection}
96
96
  AND document_id = ${t.documentId}
97
97
  AND autosave = 0
98
- AND id NOT IN (${chunkVRZC4TTF_cjs.J.join(s.map(a=>chunkVRZC4TTF_cjs.J`${a}`),chunkVRZC4TTF_cjs.J`, `)})
98
+ AND id NOT IN (${chunkVRZC4TTF_cjs.J.join(s.map(n=>chunkVRZC4TTF_cjs.J`${n}`),chunkVRZC4TTF_cjs.J`, `)})
99
99
  `);}else await this.executeRaw(chunkVRZC4TTF_cjs.J`
100
100
  DELETE FROM kyro_versions
101
101
  WHERE collection_slug = ${t.collection}
102
102
  AND document_id = ${t.documentId}
103
103
  ${t.tenantId&&i.tenantScoped?chunkVRZC4TTF_cjs.J`AND tenant_id = ${t.tenantId}`:chunkVRZC4TTF_cjs.J``}
104
- `);}getTable(t){let i=this.getTableName(t),e=this.schema[i];if(!e)throw new Error(`Table "${i}" not found in schema`);return e}buildWhereClause(t,i,e,s){let a=[];s&&i.tenantScoped&&e.tenantId&&a.push(chunkBCEE4NBZ_cjs.n(e.tenantId,s));for(let[r,n]of Object.entries(t))if(r==="id"&&this.dialect==="postgres"&&(typeof n=="string"?n=D(n):n&&typeof n=="object"&&(n.equals!==void 0&&typeof n.equals=="string"&&(n={...n,equals:D(n.equals)}),n.in&&Array.isArray(n.in)&&(n={...n,in:n.in.map(o=>typeof o=="string"?D(o):o)}))),r==="AND"&&Array.isArray(n)){let o=n.map(c=>this.buildWhereClause(c,i,e)).flat().filter(Boolean);o.length>0&&a.push(chunkBCEE4NBZ_cjs.p(...o));}else if(r==="OR"&&Array.isArray(n)){let o=n.map(c=>this.buildWhereClause(c,i,e)).flat().filter(Boolean);o.length>0&&a.push(chunkBCEE4NBZ_cjs.q(...o));}else if(typeof n=="object"&&n!==null&&!Array.isArray(n)){let o=e[r];if(!o)continue;n.equals!==void 0&&a.push(chunkBCEE4NBZ_cjs.n(o,n.equals)),n.not_equals!==void 0&&a.push(chunkBCEE4NBZ_cjs.o(o,n.not_equals)),n.in&&Array.isArray(n.in)&&a.push(chunkBCEE4NBZ_cjs.w(o,n.in)),n.like!==void 0&&a.push(chunkBCEE4NBZ_cjs.E(o,n.like)),n.contains!==void 0&&a.push(chunkBCEE4NBZ_cjs.E(o,`%${n.contains}%`)),n.greater_than!==void 0&&a.push(chunkBCEE4NBZ_cjs.s(o,n.greater_than)),n.greater_than_equal!==void 0&&a.push(chunkBCEE4NBZ_cjs.t(o,n.greater_than_equal)),n.less_than!==void 0&&a.push(chunkBCEE4NBZ_cjs.u(o,n.less_than)),n.less_than_equal!==void 0&&a.push(chunkBCEE4NBZ_cjs.v(o,n.less_than_equal));}else {let o=e[r];o&&a.push(chunkBCEE4NBZ_cjs.n(o,n));}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()),chunkZOVH6QT5_cjs.a(e)}async ensureVersionsTable(){if(this.versionsTableReady)return;let t;this.dialect==="sqlite"?t=`
104
+ `);}getTable(t){let i=this.getTableName(t),e=this.schema[i];if(!e)throw new Error(`Table "${i}" not found in schema`);return e}buildWhereClause(t,i,e,s){let n=[];s&&i.tenantScoped&&e.tenantId&&n.push(chunkBCEE4NBZ_cjs.n(e.tenantId,s));for(let[r,a]of Object.entries(t))if(r==="id"&&this.dialect==="postgres"&&(typeof a=="string"?a=D(a):a&&typeof a=="object"&&(a.equals!==void 0&&typeof a.equals=="string"&&(a={...a,equals:D(a.equals)}),a.in&&Array.isArray(a.in)&&(a={...a,in:a.in.map(o=>typeof o=="string"?D(o):o)}))),r==="AND"&&Array.isArray(a)){let o=a.map(c=>this.buildWhereClause(c,i,e)).flat().filter(Boolean);o.length>0&&n.push(chunkBCEE4NBZ_cjs.p(...o));}else if(r==="OR"&&Array.isArray(a)){let o=a.map(c=>this.buildWhereClause(c,i,e)).flat().filter(Boolean);o.length>0&&n.push(chunkBCEE4NBZ_cjs.q(...o));}else if(typeof a=="object"&&a!==null&&!Array.isArray(a)){let o=e[r];if(!o)continue;a.equals!==void 0&&n.push(chunkBCEE4NBZ_cjs.n(o,a.equals)),a.not_equals!==void 0&&n.push(chunkBCEE4NBZ_cjs.o(o,a.not_equals)),a.in&&Array.isArray(a.in)&&n.push(chunkBCEE4NBZ_cjs.w(o,a.in)),a.like!==void 0&&n.push(chunkBCEE4NBZ_cjs.E(o,a.like)),a.contains!==void 0&&n.push(chunkBCEE4NBZ_cjs.E(o,`%${a.contains}%`)),a.greater_than!==void 0&&n.push(chunkBCEE4NBZ_cjs.s(o,a.greater_than)),a.greater_than_equal!==void 0&&n.push(chunkBCEE4NBZ_cjs.t(o,a.greater_than_equal)),a.less_than!==void 0&&n.push(chunkBCEE4NBZ_cjs.u(o,a.less_than)),a.less_than_equal!==void 0&&n.push(chunkBCEE4NBZ_cjs.v(o,a.less_than_equal));}else {let o=e[r];o&&n.push(chunkBCEE4NBZ_cjs.n(o,a));}return n}processResult(t,i){if(!t)return null;let e={...t};for(let s of Object.keys(e))/^\d+$/.test(s)&&delete e[s];t.id&&(e.id=String(t.id));for(let s of i.fields){if(!s.name)continue;let n=s.name.replace(/-/g,"_").replace(/([A-Z])/g,"_$1").toLowerCase();n!==s.name&&e[n]!==void 0&&e[s.name]===void 0&&(e[s.name]=e[n],delete e[n]);}for(let s of i.fields){if(["json","richtext","array","group","blocks","upload","image","list","relationship-block"].includes(s.type)){let n=s;if(e[n.name]&&typeof e[n.name]=="string")try{let r=JSON.parse(e[n.name]);e[n.name]=r;}catch{}if(s.type==="blocks"&&e[n.name]&&Array.isArray(e[n.name])){let r=n.blocks||[];e[n.name]=le(e[n.name],r);}}if(s.type==="tabs"&&"tabs"in s&&s.name){if(typeof e[s.name]=="object"&&e[s.name]!==null&&!Array.isArray(e[s.name])){for(let r of s.tabs)for(let a of r.fields)if((a.type==="upload"||a.type==="image")&&a.name){let o=e[s.name][a.name];if(typeof o=="string")try{let c=JSON.parse(o);e[s.name][a.name]=Array.isArray(c)?c.map(d=>d&&typeof d=="object"&&typeof d.id=="string"?d.id:String(d||"")):typeof c.id=="string"?c.id:String(c.id||"");}catch{}else o&&typeof o=="object"&&(e[s.name][a.name]=Array.isArray(o)?o.map(c=>c&&typeof c=="object"&&typeof c.id=="string"?c.id:String(c||"")):typeof o.id=="string"?o.id:String(o.id||""));}continue}if(typeof e[s.name]=="string")try{let r=JSON.parse(e[s.name]);if(typeof r=="object"&&r!==null){e[s.name]=r;continue}}catch{}let n={};for(let r of s.tabs)for(let a of r.fields)if(a.name&&e[a.name]!==void 0){let o=e[a.name];if(["json","richtext","array","group","blocks","upload","image","list","relationship-block"].includes(a.type)){if(o&&typeof o=="string")try{o=JSON.parse(o);}catch{}(a.type==="upload"||a.type==="image")&&o&&typeof o=="object"&&(o=Array.isArray(o)?o.map(c=>c&&typeof c=="object"&&typeof c.id=="string"?c.id:String(c||"")):typeof o.id=="string"?o.id:String(o.id||""));}n[a.name]=o,delete e[a.name];}e[s.name]=n;}}return e.createdAt&&(e.createdAt=new Date(e.createdAt).toISOString()),e.updatedAt&&(e.updatedAt=new Date(e.updatedAt).toISOString()),chunkZOVH6QT5_cjs.a(e)}async ensureVersionsTable(){if(this.versionsTableReady)return;let t;this.dialect==="sqlite"?t=`
105
105
  CREATE TABLE IF NOT EXISTS kyro_versions (
106
106
  id text PRIMARY KEY,
107
107
  collection_slug text NOT NULL,
@@ -129,5 +129,5 @@
129
129
  created_at text NOT NULL,
130
130
  updated_at text NOT NULL
131
131
  )
132
- `,await this.executeRaw(chunkVRZC4TTF_cjs.J.raw(t));try{this.dialect==="postgres"?await this.executeRaw(chunkVRZC4TTF_cjs.J.raw("ALTER TABLE kyro_versions ADD COLUMN IF NOT EXISTS autosave integer NOT NULL DEFAULT 0")):await this.executeRaw(chunkVRZC4TTF_cjs.J.raw("ALTER TABLE kyro_versions ADD COLUMN autosave integer NOT NULL DEFAULT 0"));}catch{}this.versionsTableReady=true;}async execute(t){return this.executeRaw(t)}async executeRaw(t){let i="",e=[];if(typeof t=="string")i=t;else if(t&&(t.queryChunks||t.decoder))if(this.dialect==="postgres"){let a=new chunkKCHPADCH_cjs.a().sqlToQuery(t);i=a.sql,e=a.params;}else {let a=new chunk7ACHOBWY_cjs.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 Ie(f){return new M(f)}chunkBUNLC3II_cjs.h();var x;function be(){return x||(x=module$1.createRequire("file:///")("node:sqlite").DatabaseSync,x)}function Ee(){return process.env.DB_TYPE==="postgres"?"postgres":"sqlite"}function de(){return crypto.randomBytes(16).toString("hex")}async function Me(){let f=Ee();if(f==="sqlite"){let r=path.resolve(process.cwd(),"data","kyro.db");await promises.mkdir(path.dirname(r),{recursive:true});let n=new(be())(r);return n.exec("PRAGMA journal_mode = WAL"),{db:n,dialect:f,genId:de}}let t=process.env.DATABASE_URL||"postgresql://postgres:postgres@localhost:5432/kyro_cms",i=parseInt(process.env.DB_POOL_MAX||"10",10),e=process.env.DB_SSL==="true",s=chunkLY7N3UHH_cjs.a(t,{max:i,ssl:e?"require":false,onnotice:()=>{}});return {db:chunkKCHPADCH_cjs.f(s),dialect:f,genId:de}}async function Pe(f,t){}async function je(f){let{roles:t}=await import('./schema-RT6WSUYC.cjs');await f.insert(t).values({name:"super_admin",level:100,inherits:[],description:"Full system access across all tenants",isSystem:true}).onConflictDoNothing();}
132
+ `,await this.executeRaw(chunkVRZC4TTF_cjs.J.raw(t));try{this.dialect==="postgres"?await this.executeRaw(chunkVRZC4TTF_cjs.J.raw("ALTER TABLE kyro_versions ADD COLUMN IF NOT EXISTS autosave integer NOT NULL DEFAULT 0")):await this.executeRaw(chunkVRZC4TTF_cjs.J.raw("ALTER TABLE kyro_versions ADD COLUMN autosave integer NOT NULL DEFAULT 0"));}catch{}this.versionsTableReady=true;}async execute(t){return this.executeRaw(t)}async executeRaw(t){let i="",e=[];if(typeof t=="string")i=t;else if(t&&(t.queryChunks||t.decoder))if(this.dialect==="postgres"){let n=new chunkKCHPADCH_cjs.a().sqlToQuery(t);i=n.sql,e=n.params;}else {let n=new chunk7ACHOBWY_cjs.h().sqlToQuery(t);i=n.sql,e=n.params;}else if(t&&typeof t.toSQL=="function"){let n=t.toSQL();i=n.sql,e=n.params||[];}else i=String(t);let s=this.rawClient||this.client;if(s?.prepare&&typeof s.prepare=="function"){let n=s.prepare(i);return (e.length>0?await n.bind(...e).all():await n.all()).results||[]}if(typeof this.client?.execute=="function"){let n=await this.client.execute(t);return Array.isArray(n)?n:Array.isArray(n?.rows)?n.rows:Array.isArray(n?.[0])?n[0]:[]}return []}};function Ie(f){return new M(f)}chunkBUNLC3II_cjs.h();var x;function Ae(){return x||(x=module$1.createRequire("file:///")("node:sqlite").DatabaseSync,x)}function Ee(){return process.env.DB_TYPE==="postgres"?"postgres":"sqlite"}function de(){return crypto.randomBytes(16).toString("hex")}async function Me(){let f=Ee();if(f==="sqlite"){let r=path.resolve(process.cwd(),"data","kyro.db");await promises.mkdir(path.dirname(r),{recursive:true});let a=new(Ae())(r);return a.exec("PRAGMA journal_mode = WAL"),{db:a,dialect:f,genId:de}}let t=process.env.DATABASE_URL||"postgresql://postgres:postgres@localhost:5432/kyro_cms",i=parseInt(process.env.DB_POOL_MAX||"10",10),e=process.env.DB_SSL==="true",s=chunkLY7N3UHH_cjs.a(t,{max:i,ssl:e?"require":false,onnotice:()=>{}});return {db:chunkKCHPADCH_cjs.f(s),dialect:f,genId:de}}async function Pe(f,t){}async function je(f){let{roles:t}=await import('./schema-RT6WSUYC.cjs');await f.insert(t).values({name:"super_admin",level:100,inherits:[],description:"Full system access across all tenants",isSystem:true}).onConflictDoNothing();}
133
133
  exports.a=L;exports.b=Se;exports.c=M;exports.d=Ie;exports.e=de;exports.f=Me;exports.g=Pe;exports.h=je;
@@ -1,4 +1,4 @@
1
- import {a as a$3}from'./chunk-LWM4WABU.js';import {a as a$2}from'./chunk-SQBTIMWF.js';import {a as a$4,i as i$1}from'./chunk-PA4ZZREG.js';import {r as r$1,p as p$1,n as n$1,c as c$2,q as q$1,o as o$1,J as J$1,b as b$3,a as a$5,F as F$2,D as D$1,C as C$2,e as e$3,H as H$2,x as x$1,d as d$4,y as y$2,k as k$1,f as f$4,A as A$1,j as j$1,z as z$2,u as u$1,v as v$1,w as w$1,g as g$5,E as E$1,B as B$1,t as t$1,s as s$1,m as m$1,i as i$2,l as l$1,h as h$1}from'./chunk-ZMG7Z3KF.js';import {wa as wa$1,a as a$1,ua as ua$1,Aa as Aa$1,ra as ra$1,Da as Da$1,Na as Na$1,qa as qa$1,ka as ka$1,za as za$1,i,Ga as Ga$1,Ea as Ea$1,f as f$1,Ma as Ma$1,Qa as Qa$1,Ra,Sa as Sa$1,Oa as Oa$1,Ta as Ta$1,Ua as Ua$1,b as b$1,ya as ya$1,la as la$1,Pa as Pa$1,sa as sa$1,va as va$1,La as La$1,ma as ma$1,Fa as Fa$1,k,Ja as Ja$1,Ia as Ia$1,ha as ha$1,t,s,u,r,Ca as Ca$1,ja as ja$1,d as d$1,j,Ha as Ha$1,Ka as Ka$1,Ba as Ba$1,h,w,pa as pa$1,ga as ga$1,Va as Va$1,oa as oa$1,na as na$1,xa as xa$1,ta as ta$1,m,I,G as G$1,L,D,v,O,Y,C as C$1,x,R,P,fa as fa$1,X,ea as ea$1,c as c$1,Z,K,y as y$1,_,E,H as H$1,W,ba as ba$1,Q as Q$1,U,T,e,N as N$1,S,ia as ia$1,g as g$1,V,M as M$1,$,B,aa as aa$1,da as da$1,A,z as z$1,J,F as F$1,n,q,Wa as Wa$1,o,l,p,ca as ca$1,Xa as Xa$1,Ya as Ya$1,$a as $a$1,ib}from'./chunk-5YQ2HVHD.js';import {o as o$2,f as f$2,g as g$3}from'./chunk-YZEMLLD2.js';import {d as d$2,e as e$2,f as f$3,g as g$4}from'./chunk-RTHJ6SS5.js';import {b as b$2,d as d$3}from'./chunk-5M3FKE2V.js';import {c as c$3}from'./chunk-BU6O3TP7.js';import {g as g$2}from'./chunk-47CXBWMA.js';import {c,g,b,d,a,f,e as e$1}from'./chunk-Y2YAKDEQ.js';if (typeof window === "undefined") { const { createRequire } = await import(/* @vite-ignore */ 'module'); createRequire(import.meta.url); }
1
+ import {a as a$3}from'./chunk-LWM4WABU.js';import {a as a$2}from'./chunk-SQBTIMWF.js';import {a as a$4,i as i$1}from'./chunk-PA4ZZREG.js';import {r as r$1,p as p$1,n as n$1,c as c$2,q as q$1,o as o$1,J as J$1,b as b$3,a as a$5,F as F$2,D as D$1,C as C$2,e as e$3,H as H$2,x as x$1,d as d$4,y as y$2,k as k$1,f as f$4,A as A$1,j as j$1,z as z$2,u as u$1,v as v$1,w as w$1,g as g$5,E as E$1,B as B$1,t as t$1,s as s$1,m as m$1,i as i$2,l as l$1,h as h$1}from'./chunk-ZMG7Z3KF.js';import {wa as wa$1,a as a$1,ua as ua$1,Aa as Aa$1,ra as ra$1,Da as Da$1,Na as Na$1,qa as qa$1,ka as ka$1,za as za$1,i,Ga as Ga$1,Ea as Ea$1,f as f$1,Ma as Ma$1,Qa as Qa$1,Ra,Sa as Sa$1,Oa as Oa$1,Ta as Ta$1,Ua as Ua$1,b as b$1,ya as ya$1,la as la$1,Pa as Pa$1,sa as sa$1,va as va$1,La as La$1,ma as ma$1,Fa as Fa$1,k,Ja as Ja$1,Ia as Ia$1,ha as ha$1,t,s,u,r,Ca as Ca$1,ja as ja$1,d as d$1,j,Ha as Ha$1,Ka as Ka$1,Ba as Ba$1,h,w,pa as pa$1,ga as ga$1,Va as Va$1,oa as oa$1,na as na$1,xa as xa$1,ta as ta$1,m,I,G as G$1,L,D,v,O,Y,C as C$1,x,R,P,fa as fa$1,X,ea as ea$1,c as c$1,Z,K,y as y$1,_,E,H as H$1,W,ba as ba$1,Q as Q$1,U,T,e,N as N$1,S,ia as ia$1,g as g$1,V,M as M$1,$,B,aa as aa$1,da as da$1,A,z as z$1,J,F as F$1,n,q,Wa as Wa$1,o,l,p,ca as ca$1,Xa as Xa$1,Ya as Ya$1,$a as $a$1,ib}from'./chunk-5BIZIO6T.js';import {o as o$2,f as f$2,g as g$3}from'./chunk-YZEMLLD2.js';import {d as d$2,e as e$2,f as f$3,g as g$4}from'./chunk-RTHJ6SS5.js';import {b as b$2,d as d$3}from'./chunk-5M3FKE2V.js';import {c as c$3}from'./chunk-KNOFTUQV.js';import {g as g$2}from'./chunk-47CXBWMA.js';import {c,g,b,d,a,f,e as e$1}from'./chunk-Y2YAKDEQ.js';if (typeof window === "undefined") { const { createRequire } = await import(/* @vite-ignore */ 'module'); createRequire(import.meta.url); }
2
2
  var ms=c((hw,Ra)=>{g();function Rp(){return Object.keys(globalThis).some(t=>t.startsWith("__NEXT"))}Ra.exports=function(){return !!(globalThis.Deno||globalThis.Bun||Rp())};});function Aa(t,e){return (e?/^[\x00-\xFF]*$/:/^[\x00-\x7F]*$/).test(t)}function _s(t,e=false){let r=[],n=0;for(;n<t.length;){let s=t[n],i=F(function(o){if(!e)throw new TypeError(o);r.push({type:"INVALID_CHAR",index:n,value:t[n++]});},"ErrorOrInvalid");if(s==="*"){r.push({type:"ASTERISK",index:n,value:t[n++]});continue}if(s==="+"||s==="?"){r.push({type:"OTHER_MODIFIER",index:n,value:t[n++]});continue}if(s==="\\"){r.push({type:"ESCAPED_CHAR",index:n++,value:t[n++]});continue}if(s==="{"){r.push({type:"OPEN",index:n,value:t[n++]});continue}if(s==="}"){r.push({type:"CLOSE",index:n,value:t[n++]});continue}if(s===":"){let o="",a=n+1;for(;a<t.length;){let c=t.substr(a,1);if(a===n+1&&Lp.test(c)||a!==n+1&&Op.test(c)){o+=t[a++];continue}break}if(!o){i(`Missing parameter name at ${n}`);continue}r.push({type:"NAME",index:n,value:o}),n=a;continue}if(s==="("){let o=1,a="",c=n+1,l=false;if(t[c]==="?"){i(`Pattern cannot start with "?" at ${c}`);continue}for(;c<t.length;){if(!Aa(t[c],false)){i(`Invalid character '${t[c]}' at ${c}.`),l=true;break}if(t[c]==="\\"){a+=t[c++]+t[c++];continue}if(t[c]===")"){if(o--,o===0){c++;break}}else if(t[c]==="("&&(o++,t[c+1]!=="?")){i(`Capturing groups are not allowed at ${c}`),l=true;break}a+=t[c++];}if(l)continue;if(o){i(`Unbalanced pattern at ${n}`);continue}if(!a){i(`Missing pattern at ${n}`);continue}r.push({type:"REGEX",index:n,value:a}),n=c;continue}r.push({type:"CHAR",index:n,value:t[n++]});}return r.push({type:"END",index:n,value:""}),r}function ws(t,e={}){let r=_s(t);e.delimiter??="/#?",e.prefixes??="./";let n=`[^${me(e.delimiter)}]+?`,s=[],i=0,o=0,c=new Set,l=F(P=>{if(o<r.length&&r[o].type===P)return r[o++].value},"tryConsume"),u=F(()=>l("OTHER_MODIFIER")??l("ASTERISK"),"tryConsumeModifier"),h=F(P=>{let k=l(P);if(k!==void 0)return k;let{type:S,index:v}=r[o];throw new TypeError(`Unexpected ${S} at ${v}, expected ${P}`)},"mustConsume"),d=F(()=>{let P="",k;for(;k=l("CHAR")??l("ESCAPED_CHAR");)P+=k;return P},"consumeText"),p=F(P=>P,"DefaultEncodePart"),_=e.encodePart||p,E="",A=F(P=>{E+=P;},"appendToPendingFixedValue"),R=F(()=>{E.length&&(s.push(new wt(3,"","",_(E),"",3)),E="");},"maybeAddPartFromPendingFixedValue"),j=F((P,k,S,v,O)=>{let g=3;switch(O){case "?":g=1;break;case "*":g=0;break;case "+":g=2;break}if(!k&&!S&&g===3){A(P);return}if(R(),!k&&!S){if(!P)return;s.push(new wt(3,"","",_(P),"",g));return}let x;S?S==="*"?x=ys:x=S:x=n;let w=2;x===n?(w=1,x=""):x===ys&&(w=0,x="");let T;if(k?T=k:S&&(T=i++),c.has(T))throw new TypeError(`Duplicate name '${T}'.`);c.add(T),s.push(new wt(w,T,_(P),x,_(v),g));},"addPart");for(;o<r.length;){let P=l("CHAR"),k=l("NAME"),S=l("REGEX");if(!k&&!S&&(S=l("ASTERISK")),k||S){let O=P??"";e.prefixes.indexOf(O)===-1&&(A(O),O=""),R();let g=u();j(O,k,S,"",g);continue}let v=P??l("ESCAPED_CHAR");if(v){A(v);continue}if(l("OPEN")){let O=d(),g=l("NAME"),x=l("REGEX");!g&&!x&&(x=l("ASTERISK"));let w=d();h("CLOSE");let T=u();j(O,g,x,w,T);continue}R(),h("END");}return s}function me(t){return t.replace(/([.+*?^${}()[\]|/\\])/g,"\\$1")}function gs(t){return t&&t.ignoreCase?"ui":"u"}function La(t,e,r){return Ss(ws(t,r),e,r)}function tt(t){switch(t){case 0:return "*";case 1:return "?";case 2:return "+";case 3:return ""}}function Ss(t,e,r={}){r.delimiter??="/#?",r.prefixes??="./",r.sensitive??=false,r.strict??=false,r.end??=true,r.start??=true,r.endsWith="";let n=r.start?"^":"";for(let a of t){if(a.type===3){a.modifier===3?n+=me(a.value):n+=`(?:${me(a.value)})${tt(a.modifier)}`;continue}e&&e.push(a.name);let c=`[^${me(r.delimiter)}]+?`,l=a.value;if(a.type===1?l=c:a.type===0&&(l=ys),!a.prefix.length&&!a.suffix.length){a.modifier===3||a.modifier===1?n+=`(${l})${tt(a.modifier)}`:n+=`((?:${l})${tt(a.modifier)})`;continue}if(a.modifier===3||a.modifier===1){n+=`(?:${me(a.prefix)}(${l})${me(a.suffix)})`,n+=tt(a.modifier);continue}n+=`(?:${me(a.prefix)}`,n+=`((?:${l})(?:`,n+=me(a.suffix),n+=me(a.prefix),n+=`(?:${l}))*)${me(a.suffix)})`,a.modifier===0&&(n+="?");}let s=`[${me(r.endsWith)}]|$`,i=`[${me(r.delimiter)}]`;if(r.end)return r.strict||(n+=`${i}?`),r.endsWith.length?n+=`(?=${s})`:n+="$",new RegExp(n,gs(r));r.strict||(n+=`(?:${i}(?=${s}))?`);let o=false;if(t.length){let a=t[t.length-1];a.type===3&&a.modifier===3&&(o=r.delimiter.indexOf(a)>-1);}return o||(n+=`(?=${i}|${s})`),new RegExp(n,gs(r))}function Oa(t,e){return t.length?t[0]==="/"?true:!e||t.length<2?false:(t[0]=="\\"||t[0]=="{")&&t[1]=="/":false}function Es(t,e){return t.startsWith(e)?t.substring(e.length,t.length):t}function Fa(t,e){return t.endsWith(e)?t.substr(0,t.length-e.length):t}function Ps(t){return !t||t.length<2?false:t[0]==="["||(t[0]==="\\"||t[0]==="{")&&t[1]==="["}function vs(t){if(!t)return true;for(let e of Ia)if(t.test(e))return true;return false}function Da(t,e){if(t=Es(t,"#"),e||t==="")return t;let r=new URL("https://example.com");return r.hash=t,r.hash?r.hash.substring(1,r.hash.length):""}function ja(t,e){if(t=Es(t,"?"),e||t==="")return t;let r=new URL("https://example.com");return r.search=t,r.search?r.search.substring(1,r.search.length):""}function qa(t,e){return e||t===""?t:Ps(t)?Cs(t):ks(t)}function Ua(t,e){if(e||t==="")return t;let r=new URL("https://example.com");return r.password=t,r.password}function Ma(t,e){if(e||t==="")return t;let r=new URL("https://example.com");return r.username=t,r.username}function Ba(t,e,r){if(r||t==="")return t;if(e&&!Ia.includes(e))return new URL(`${e}:${t}`).pathname;let n=t[0]=="/";return t=new URL(n?t:"/-"+t,"https://example.com").pathname,n||(t=t.substring(2,t.length)),t}function $a(t,e,r){return Ts(e)===t&&(t=""),r||t===""?t:Rs(t)}function Na(t,e){return t=Fa(t,":"),e||t===""?t:Ar(t)}function Ts(t){switch(t){case "ws":case "http":return "80";case "wws":case "https":return "443";case "ftp":return "21";default:return ""}}function Ar(t){if(t==="")return t;if(/^[-+.A-Za-z0-9]*$/.test(t))return t.toLowerCase();throw new TypeError(`Invalid protocol '${t}'.`)}function Ga(t){if(t==="")return t;let e=new URL("https://example.com");return e.username=t,e.username}function Ha(t){if(t==="")return t;let e=new URL("https://example.com");return e.password=t,e.password}function ks(t){if(t==="")return t;if(/[\t\n\r #%/:<>?@[\]^\\|]/g.test(t))throw new TypeError(`Invalid hostname '${t}'`);let e=new URL("https://example.com");return e.hostname=t,e.hostname}function Cs(t){if(t==="")return t;if(/[^0-9a-fA-F[\]:]/g.test(t))throw new TypeError(`Invalid IPv6 hostname '${t}'`);return t.toLowerCase()}function Rs(t){if(t===""||/^[0-9]*$/.test(t)&&parseInt(t)<=65535)return t;throw new TypeError(`Invalid port '${t}'.`)}function za(t){if(t==="")return t;let e=new URL("https://example.com");return e.pathname=t[0]!=="/"?"/-"+t:t,t[0]!=="/"?e.pathname.substring(2,e.pathname.length):e.pathname}function Va(t){return t===""?t:new URL(`data:${t}`).pathname}function Wa(t){if(t==="")return t;let e=new URL("https://example.com");return e.search=t,e.search.substring(1,e.search.length)}function Ka(t){if(t==="")return t;let e=new URL("https://example.com");return e.hash=t,e.hash.substring(1,e.hash.length)}function xs(t,e){if(typeof t!="string")throw new TypeError("parameter 1 is not of type 'string'.");let r=new URL(t,e);return {protocol:r.protocol.substring(0,r.protocol.length-1),username:r.username,password:r.password,hostname:r.hostname,port:r.port,pathname:r.pathname,search:r.search!==""?r.search.substring(1,r.search.length):void 0,hash:r.hash!==""?r.hash.substring(1,r.hash.length):void 0}}function Te(t,e){return e?_t(t):t}function xt(t,e,r){let n;if(typeof e.baseURL=="string")try{n=new URL(e.baseURL),e.protocol===void 0&&(t.protocol=Te(n.protocol.substring(0,n.protocol.length-1),r)),!r&&e.protocol===void 0&&e.hostname===void 0&&e.port===void 0&&e.username===void 0&&(t.username=Te(n.username,r)),!r&&e.protocol===void 0&&e.hostname===void 0&&e.port===void 0&&e.username===void 0&&e.password===void 0&&(t.password=Te(n.password,r)),e.protocol===void 0&&e.hostname===void 0&&(t.hostname=Te(n.hostname,r)),e.protocol===void 0&&e.hostname===void 0&&e.port===void 0&&(t.port=Te(n.port,r)),e.protocol===void 0&&e.hostname===void 0&&e.port===void 0&&e.pathname===void 0&&(t.pathname=Te(n.pathname,r)),e.protocol===void 0&&e.hostname===void 0&&e.port===void 0&&e.pathname===void 0&&e.search===void 0&&(t.search=Te(n.search.substring(1,n.search.length),r)),e.protocol===void 0&&e.hostname===void 0&&e.port===void 0&&e.pathname===void 0&&e.search===void 0&&e.hash===void 0&&(t.hash=Te(n.hash.substring(1,n.hash.length),r));}catch{throw new TypeError(`invalid baseURL '${e.baseURL}'.`)}if(typeof e.protocol=="string"&&(t.protocol=Na(e.protocol,r)),typeof e.username=="string"&&(t.username=Ma(e.username,r)),typeof e.password=="string"&&(t.password=Ua(e.password,r)),typeof e.hostname=="string"&&(t.hostname=qa(e.hostname,r)),typeof e.port=="string"&&(t.port=$a(e.port,t.protocol,r)),typeof e.pathname=="string"){if(t.pathname=e.pathname,n&&!Oa(t.pathname,r)){let s=n.pathname.lastIndexOf("/");s>=0&&(t.pathname=Te(n.pathname.substring(0,s+1),r)+t.pathname);}t.pathname=Ba(t.pathname,t.protocol,r);}return typeof e.search=="string"&&(t.search=ja(e.search,r)),typeof e.hash=="string"&&(t.hash=Da(e.hash,r)),t}function _t(t){return t.replace(/([+*?:{}()\\])/g,"\\$1")}function Za(t){return t.replace(/([.+*?^${}()[\]|/\\])/g,"\\$1")}function Ja(t,e){e.delimiter??="/#?",e.prefixes??="./",e.sensitive??=false,e.strict??=false,e.end??=true,e.start??=true,e.endsWith="";let r=".*",n=`[^${Za(e.delimiter)}]+?`,s=/[$_\u200C\u200D\p{ID_Continue}]/u,i="";for(let o=0;o<t.length;++o){let a=t[o];if(a.type===3){if(a.modifier===3){i+=_t(a.value);continue}i+=`{${_t(a.value)}}${tt(a.modifier)}`;continue}let c=a.hasCustomName(),l=!!a.suffix.length||!!a.prefix.length&&(a.prefix.length!==1||!e.prefixes.includes(a.prefix)),u=o>0?t[o-1]:null,h=o<t.length-1?t[o+1]:null;if(!l&&c&&a.type===1&&a.modifier===3&&h&&!h.prefix.length&&!h.suffix.length)if(h.type===3){let d=h.value.length>0?h.value[0]:"";l=s.test(d);}else l=!h.hasCustomName();if(!l&&!a.prefix.length&&u&&u.type===3){let d=u.value[u.value.length-1];l=e.prefixes.includes(d);}l&&(i+="{"),i+=_t(a.prefix),c&&(i+=`:${a.name}`),a.type===2?i+=`(${a.value})`:a.type===1?c||(i+=`(${n})`):a.type===0&&(!c&&(!u||u.type===3||u.modifier!==3||l||a.prefix!=="")?i+="*":i+=`(${r})`),a.type===1&&c&&a.suffix.length&&s.test(a.suffix[0])&&(i+="\\"),i+=_t(a.suffix),l&&(i+="}"),a.modifier!==3&&(i+=tt(a.modifier));}return i}var Ap,F,wt,Lp,Op,ys,He,Fp,Ip,Ia,Qa,bs,Ge,Lr,Ya=b(()=>{g();Ap=Object.defineProperty,F=(t,e)=>Ap(t,"name",{value:e,configurable:true}),wt=class{type=3;name="";prefix="";value="";suffix="";modifier=3;constructor(t,e,r,n,s,i){this.type=t,this.name=e,this.prefix=r,this.value=n,this.suffix=s,this.modifier=i;}hasCustomName(){return this.name!==""&&typeof this.name!="number"}};F(wt,"Part");Lp=/[$_\p{ID_Start}]/u,Op=/[$_\u200C\u200D\p{ID_Continue}]/u,ys=".*";F(Aa,"isASCII");F(_s,"lexer");F(ws,"parse");F(me,"escapeString");F(gs,"flags");F(La,"stringToRegexp");F(tt,"modifierToString");F(Ss,"partsToRegexp");He={delimiter:"",prefixes:"",sensitive:true,strict:true},Fp={delimiter:".",prefixes:"",sensitive:true,strict:true},Ip={delimiter:"/",prefixes:"/",sensitive:true,strict:true};F(Oa,"isAbsolutePathname");F(Es,"maybeStripPrefix");F(Fa,"maybeStripSuffix");F(Ps,"treatAsIPv6Hostname");Ia=["ftp","file","http","https","ws","wss"];F(vs,"isSpecialScheme");F(Da,"canonicalizeHash");F(ja,"canonicalizeSearch");F(qa,"canonicalizeHostname");F(Ua,"canonicalizePassword");F(Ma,"canonicalizeUsername");F(Ba,"canonicalizePathname");F($a,"canonicalizePort");F(Na,"canonicalizeProtocol");F(Ts,"defaultPortForProtocol");F(Ar,"protocolEncodeCallback");F(Ga,"usernameEncodeCallback");F(Ha,"passwordEncodeCallback");F(ks,"hostnameEncodeCallback");F(Cs,"ipv6HostnameEncodeCallback");F(Rs,"portEncodeCallback");F(za,"standardURLPathnameEncodeCallback");F(Va,"pathURLPathnameEncodeCallback");F(Wa,"searchEncodeCallback");F(Ka,"hashEncodeCallback");Qa=class{#o;#r=[];#n={};#t=0;#p=1;#w=0;#s=0;#y=0;#l=0;#i=false;constructor(t){this.#o=t;}get result(){return this.#n}parse(){for(this.#r=_s(this.#o,true);this.#t<this.#r.length;this.#t+=this.#p){if(this.#p=1,this.#r[this.#t].type==="END"){if(this.#s===0){this.#b(),this.#T()?this.#e(9,1):this.#d()?this.#e(8,1):this.#e(7,0);continue}else if(this.#s===2){this.#f(5);continue}this.#e(10,0);break}if(this.#y>0)if(this.#k())this.#y-=1;else continue;if(this.#L()){this.#y+=1;continue}switch(this.#s){case 0:this.#h()&&this.#f(1);break;case 1:if(this.#h()){this.#O();let t=7,e=1;this.#E()?(t=2,e=3):this.#i&&(t=2),this.#e(t,e);}break;case 2:this.#g()?this.#f(3):(this.#v()||this.#d()||this.#T())&&this.#f(5);break;case 3:this.#x()?this.#e(4,1):this.#g()&&this.#e(5,1);break;case 4:this.#g()&&this.#e(5,1);break;case 5:this.#F()?this.#l+=1:this.#_()&&(this.#l-=1),this.#P()&&!this.#l?this.#e(6,1):this.#v()?this.#e(7,0):this.#d()?this.#e(8,1):this.#T()&&this.#e(9,1);break;case 6:this.#v()?this.#e(7,0):this.#d()?this.#e(8,1):this.#T()&&this.#e(9,1);break;case 7:this.#d()?this.#e(8,1):this.#T()&&this.#e(9,1);break;case 8:this.#T()&&this.#e(9,1);break;}}this.#n.hostname!==void 0&&this.#n.port===void 0&&(this.#n.port="");}#e(t,e){switch(this.#s){case 0:break;case 1:this.#n.protocol=this.#S();break;case 2:break;case 3:this.#n.username=this.#S();break;case 4:this.#n.password=this.#S();break;case 5:this.#n.hostname=this.#S();break;case 6:this.#n.port=this.#S();break;case 7:this.#n.pathname=this.#S();break;case 8:this.#n.search=this.#S();break;case 9:this.#n.hash=this.#S();break;}this.#s!==0&&t!==10&&([1,2,3,4].includes(this.#s)&&[6,7,8,9].includes(t)&&(this.#n.hostname??=""),[1,2,3,4,5,6].includes(this.#s)&&[8,9].includes(t)&&(this.#n.pathname??=this.#i?"/":""),[1,2,3,4,5,6,7].includes(this.#s)&&t===9&&(this.#n.search??="")),this.#m(t,e);}#m(t,e){this.#s=t,this.#w=this.#t+e,this.#t+=e,this.#p=0;}#b(){this.#t=this.#w,this.#p=0;}#f(t){this.#b(),this.#s=t;}#u(t){return t<0&&(t=this.#r.length-t),t<this.#r.length?this.#r[t]:this.#r[this.#r.length-1]}#c(t,e){let r=this.#u(t);return r.value===e&&(r.type==="CHAR"||r.type==="ESCAPED_CHAR"||r.type==="INVALID_CHAR")}#h(){return this.#c(this.#t,":")}#E(){return this.#c(this.#t+1,"/")&&this.#c(this.#t+2,"/")}#g(){return this.#c(this.#t,"@")}#x(){return this.#c(this.#t,":")}#P(){return this.#c(this.#t,":")}#v(){return this.#c(this.#t,"/")}#d(){if(this.#c(this.#t,"?"))return true;if(this.#r[this.#t].value!=="?")return false;let t=this.#u(this.#t-1);return t.type!=="NAME"&&t.type!=="REGEX"&&t.type!=="CLOSE"&&t.type!=="ASTERISK"}#T(){return this.#c(this.#t,"#")}#L(){return this.#r[this.#t].type=="OPEN"}#k(){return this.#r[this.#t].type=="CLOSE"}#F(){return this.#c(this.#t,"[")}#_(){return this.#c(this.#t,"]")}#S(){let t=this.#r[this.#t],e=this.#u(this.#w).index;return this.#o.substring(e,t.index)}#O(){let t={};Object.assign(t,He),t.encodePart=Ar;let e=La(this.#S(),void 0,t);this.#i=vs(e);}};F(Qa,"Parser");bs=["protocol","username","password","hostname","port","pathname","search","hash"],Ge="*";F(xs,"extractValues");F(Te,"processBaseURLString");F(xt,"applyInit");F(_t,"escapePatternString");F(Za,"escapeRegexpString");F(Ja,"partsToPattern");Lr=class{#o;#r={};#n={};#t={};#p={};#w=false;constructor(t={},e,r){try{let n;if(typeof e=="string"?n=e:r=e,typeof t=="string"){let a=new Qa(t);if(a.parse(),t=a.result,n===void 0&&typeof t.protocol!="string")throw new TypeError("A base URL must be provided for a relative constructor string.");t.baseURL=n;}else {if(!t||typeof t!="object")throw new TypeError("parameter 1 is not of type 'string' and cannot convert to dictionary.");if(n)throw new TypeError("parameter 1 is not of type 'string'.")}typeof r>"u"&&(r={ignoreCase:!1});let s={ignoreCase:r.ignoreCase===!0},i={pathname:Ge,protocol:Ge,username:Ge,password:Ge,hostname:Ge,port:Ge,search:Ge,hash:Ge};this.#o=xt(i,t,!0),Ts(this.#o.protocol)===this.#o.port&&(this.#o.port="");let o;for(o of bs){if(!(o in this.#o))continue;let a={},c=this.#o[o];switch(this.#n[o]=[],o){case "protocol":Object.assign(a,He),a.encodePart=Ar;break;case "username":Object.assign(a,He),a.encodePart=Ga;break;case "password":Object.assign(a,He),a.encodePart=Ha;break;case "hostname":Object.assign(a,Fp),Ps(c)?a.encodePart=Cs:a.encodePart=ks;break;case "port":Object.assign(a,He),a.encodePart=Rs;break;case "pathname":vs(this.#r.protocol)?(Object.assign(a,Ip,s),a.encodePart=za):(Object.assign(a,He,s),a.encodePart=Va);break;case "search":Object.assign(a,He,s),a.encodePart=Wa;break;case "hash":Object.assign(a,He,s),a.encodePart=Ka;break}try{this.#p[o]=ws(c,a),this.#r[o]=Ss(this.#p[o],this.#n[o],a),this.#t[o]=Ja(this.#p[o],a),this.#w=this.#w||this.#p[o].some(l=>l.type===2);}catch{throw new TypeError(`invalid ${o} pattern '${this.#o[o]}'.`)}}}catch(n){throw new TypeError(`Failed to construct 'URLPattern': ${n.message}`)}}get[Symbol.toStringTag](){return "URLPattern"}test(t={},e){let r={pathname:"",protocol:"",username:"",password:"",hostname:"",port:"",search:"",hash:""};if(typeof t!="string"&&e)throw new TypeError("parameter 1 is not of type 'string'.");if(typeof t>"u")return false;try{typeof t=="object"?r=xt(r,t,!1):r=xt(r,xs(t,e),!1);}catch{return false}let n;for(n of bs)if(!this.#r[n].exec(r[n]))return false;return true}exec(t={},e){let r={pathname:"",protocol:"",username:"",password:"",hostname:"",port:"",search:"",hash:""};if(typeof t!="string"&&e)throw new TypeError("parameter 1 is not of type 'string'.");if(typeof t>"u")return;try{typeof t=="object"?r=xt(r,t,!1):r=xt(r,xs(t,e),!1);}catch{return null}let n={};e?n.inputs=[t,e]:n.inputs=[t];let s;for(s of bs){let i=this.#r[s].exec(r[s]);if(!i)return null;let o={};for(let[a,c]of this.#n[s].entries())if(typeof c=="string"||typeof c=="number"){let l=i[a+1];o[c]=l;}n[s]={input:r[s]??"",groups:o};}return n}static compareComponent(t,e,r){let n=F((a,c)=>{for(let l of ["type","modifier","prefix","value","suffix"]){if(a[l]<c[l])return -1;if(a[l]!==c[l])return 1}return 0},"comparePart"),s=new wt(3,"","","","",3),i=new wt(0,"","","","",3),o=F((a,c)=>{let l=0;for(;l<Math.min(a.length,c.length);++l){let u=n(a[l],c[l]);if(u)return u}return a.length===c.length?0:n(a[l]??s,c[l]??s)},"comparePartList");return !e.#t[t]&&!r.#t[t]?0:e.#t[t]&&!r.#t[t]?o(e.#p[t],[i]):!e.#t[t]&&r.#t[t]?o([i],r.#p[t]):o(e.#p[t],r.#p[t])}get protocol(){return this.#t.protocol}get username(){return this.#t.username}get password(){return this.#t.password}get hostname(){return this.#t.hostname}get port(){return this.#t.port}get pathname(){return this.#t.pathname}get search(){return this.#t.search}get hash(){return this.#t.hash}get hasRegExpGroups(){return this.#w}};F(Lr,"URLPattern");});var Xa={};d(Xa,{URLPattern:()=>Lr});var el=b(()=>{g();Ya();globalThis.URLPattern||(globalThis.URLPattern=Lr);});var Ve=c(de=>{g();Object.defineProperty(de,"__esModule",{value:true});de.isPromise=Or;de.isActualPromise=rl;de.handleMaybePromise=ze;de.fakePromise=ke;de.createDeferredPromise=Dp;de.iterateAsync=nl;de.iterateAsyncVoid=nl;de.fakeRejectPromise=rt;de.mapMaybePromise=jp;de.mapAsyncIterator=qp;de.promiseLikeFinally=sl;de.unfakePromise=il;var Fr=Symbol.for("@whatwg-node/promise-helpers/FakePromise");function Or(t){return t?.then!=null}function rl(t){let e=t;return e&&e.then&&e.catch&&e.finally}function ze(t,e,r,n){let s=ke().then(t).then(e,r);return n&&(s=s.finally(n)),il(s)}function ke(t){return t&&rl(t)?t:Or(t)?{then:(e,r)=>ke(t.then(e,r)),catch:e=>ke(t.then(r=>r,e)),finally:e=>ke(e?sl(t,e):t),[Symbol.toStringTag]:"Promise"}:{then(e){if(e)try{return ke(e(t))}catch(r){return rt(r)}return this},catch(){return this},finally(e){if(e)try{return ke(e()).then(()=>t,()=>t)}catch(r){return rt(r)}return this},[Symbol.toStringTag]:"Promise",__fakePromiseValue:t,[Fr]:"resolved"}}function Dp(){if(Promise.withResolvers)return Promise.withResolvers();let t,e;return {promise:new Promise(function(s,i){t=s,e=i;}),get resolve(){return t},get reject(){return e}}}function nl(t,e,r){if(t?.length===0)return;let n=t[Symbol.iterator](),s=0;function i(){let{done:o,value:a}=n.next();if(o)return;let c=false;function l(){c=true;}return ze(function(){return e(a,l,s++)},function(h){if(h&&r?.push(h),!c)return i()})}return i()}function rt(t){return {then(e,r){if(r)try{return ke(r(t))}catch(n){return rt(n)}return this},catch(e){if(e)try{return ke(e(t))}catch(r){return rt(r)}return this},finally(e){if(e)try{e();}catch(r){return rt(r)}return this},__fakeRejectError:t,[Symbol.toStringTag]:"Promise",[Fr]:"rejected"}}function jp(t,e,r){return ze(()=>t,e,r)}function qp(t,e,r,n){Symbol.asyncIterator in t&&(t=t[Symbol.asyncIterator]());let s,i,o;if(n){let l;o=u=>(l||=ze(n,()=>u,()=>u),l);}typeof t.return=="function"&&(s=t.return,i=l=>{let u=()=>{throw l};return s.call(t).then(u,u)});function a(l){return l.done?o?o(l):l:ze(()=>l.value,u=>ze(()=>e(u),tl,i))}let c;if(r){let l,u=r;c=h=>(l||=ze(()=>h,d=>ze(()=>u(d),tl,i)),l);}return {next(){return t.next().then(a,c)},return(){let l=s?s.call(t).then(a,c):ke({value:void 0,done:true});return o?l.then(o):l},throw(l){return typeof t.throw=="function"?t.throw(l).then(a,c):i?i(l):rt(l)},[Symbol.asyncIterator](){return this}}}function tl(t){return {value:t,done:false}}function Up(t){return t?.[Fr]==="resolved"}function Mp(t){return t?.[Fr]==="rejected"}function sl(t,e){return "finally"in t?t.finally(e):t.then(r=>{let n=e();return Or(n)?n.then(()=>r):r},r=>{let n=e();if(Or(n))return n.then(()=>{throw r});throw r})}function il(t){if(Up(t))return t.__fakePromiseValue;if(Mp(t))throw t.__fakeRejectError;return t}});var As=c((Ew,ol)=>{g();var{EventEmitter:Bp}=a("events"),{inherits:$p}=a("util");function nt(t){if(typeof t=="string"&&(t=Buffer.from(t)),!Buffer.isBuffer(t))throw new TypeError("The needle has to be a String or a Buffer.");let e=t.length,r=e-1;if(e===0)throw new Error("The needle cannot be an empty String/Buffer.");if(e>256)throw new Error("The needle cannot have a length bigger than 256.");this.maxMatches=1/0,this.matches=0,this._occ=new Uint8Array(256).fill(e),this._lookbehind_size=0,this._needle=t,this._bufpos=0,this._lookbehind=Buffer.alloc(r);for(var n=0;n<r;++n)this._occ[t[n]]=r-n;}$p(nt,Bp);nt.prototype.reset=function(){this._lookbehind_size=0,this.matches=0,this._bufpos=0;};nt.prototype.push=function(t,e){Buffer.isBuffer(t)||(t=Buffer.from(t,"binary"));let r=t.length;this._bufpos=e||0;let n;for(;n!==r&&this.matches<this.maxMatches;)n=this._sbmh_feed(t);return n};nt.prototype._sbmh_feed=function(t){let e=t.length,r=this._needle,n=r.length,s=n-1,i=r[s],o=-this._lookbehind_size,a;if(o<0){for(;o<0&&o<=e-n;){if(a=t[o+s],a===i&&this._sbmh_memcmp(t,o,s))return this._lookbehind_size=0,++this.matches,this.emit("info",true),this._bufpos=o+n;o+=this._occ[a];}for(;o<0&&!this._sbmh_memcmp(t,o,e-o);)++o;if(o>=0)this.emit("info",false,this._lookbehind,0,this._lookbehind_size),this._lookbehind_size=0;else {let c=this._lookbehind_size+o;return c>0&&this.emit("info",false,this._lookbehind,0,c),this._lookbehind_size-=c,this._lookbehind.copy(this._lookbehind,0,c,this._lookbehind_size),t.copy(this._lookbehind,this._lookbehind_size),this._lookbehind_size+=e,this._bufpos=e,e}}if(o=t.indexOf(r,o+this._bufpos),o!==-1)return ++this.matches,o===0?this.emit("info",true):this.emit("info",true,t,this._bufpos,o),this._bufpos=o+n;for(o=e-s,o<0&&(o=0);o!==e&&(t[o]!==r[0]||Buffer.compare(t.subarray(o+1,e),r.subarray(1,e-o))!==0);)++o;return o!==e&&(t.copy(this._lookbehind,0,o,e),this._lookbehind_size=e-o),o!==0&&this.emit("info",false,t,this._bufpos,o),this._bufpos=e,e};nt.prototype._sbmh_lookup_char=function(t,e){return e<0?this._lookbehind[this._lookbehind_size+e]:t[e]};nt.prototype._sbmh_memcmp=function(t,e,r){for(var n=0;n<r;++n)if(this._sbmh_lookup_char(t,e+n)!==this._needle[n])return false;return true};ol.exports=nt;});var cl=c((vw,ll)=>{g();var Np=a("util").inherits,al=a("stream").Readable;function Ls(t){al.call(this,t);}Np(Ls,al);Ls.prototype._read=function(t){};ll.exports=Ls;});var Ir=c((kw,ul)=>{g();ul.exports=function(e,r,n){if(!e||e[r]===void 0||e[r]===null)return n;if(typeof e[r]!="number"||isNaN(e[r]))throw new TypeError("Limit "+r+" is not a valid number");return e[r]};});var pl=c((Rw,dl)=>{g();var hl=a("events").EventEmitter,Gp=a("util").inherits,fl=Ir(),Hp=As(),zp=Buffer.from(`\r
3
3
  \r
4
4
  `),Vp=/\r\n/g,Wp=/^([^:]+):[ \t]?([\x00-\xFF]+)?$/;function St(t){hl.call(this),t=t||{};let e=this;this.nread=0,this.maxed=false,this.npairs=0,this.maxHeaderPairs=fl(t,"maxHeaderPairs",2e3),this.maxHeaderSize=fl(t,"maxHeaderSize",80*1024),this.buffer="",this.header={},this.finished=false,this.ss=new Hp(zp),this.ss.on("info",function(r,n,s,i){n&&!e.maxed&&(e.nread+i-s>=e.maxHeaderSize?(i=e.maxHeaderSize-e.nread+s,e.nread=e.maxHeaderSize,e.maxed=true):e.nread+=i-s,e.buffer+=n.toString("binary",s,i)),r&&e._finish();});}Gp(St,hl);St.prototype.push=function(t){let e=this.ss.push(t);if(this.finished)return e};St.prototype.reset=function(){this.finished=false,this.buffer="",this.header={},this.ss.reset();};St.prototype._finish=function(){this.buffer&&this._parseHeader(),this.ss.matches=this.ss.maxMatches;let t=this.header;this.header={},this.buffer="",this.finished=true,this.nread=this.npairs=0,this.maxed=false,this.emit("header",t);};St.prototype._parseHeader=function(){if(this.npairs===this.maxHeaderPairs)return;let t=this.buffer.split(Vp),e=t.length,r,n;for(var s=0;s<e;++s){if(t[s].length===0)continue;if((t[s][0]===" "||t[s][0]===" ")&&n){this.header[n][this.header[n].length-1]+=t[s];continue}let i=t[s].indexOf(":");if(i===-1||i===0)return;if(r=Wp.exec(t[s]),n=r[1].toLowerCase(),this.header[n]=this.header[n]||[],this.header[n].push(r[2]||""),++this.npairs===this.maxHeaderPairs)break}};dl.exports=St;});var Fs=c((Lw,bl)=>{g();var Os=a("stream").Writable,Kp=a("util").inherits,Qp=As(),ml=cl(),Zp=pl(),Jp=45,Yp=Buffer.from("-"),Xp=Buffer.from(`\r
@@ -1 +1 @@
1
- 'use strict';var chunkV65273ZG_cjs=require('./chunk-V65273ZG.cjs'),chunkECFZEY5B_cjs=require('./chunk-ECFZEY5B.cjs'),chunk4MVLIR77_cjs=require('./chunk-4MVLIR77.cjs'),chunkBHR7OAU4_cjs=require('./chunk-BHR7OAU4.cjs'),chunk6KUL2BSA_cjs=require('./chunk-6KUL2BSA.cjs'),chunkXBQ6HV3T_cjs=require('./chunk-XBQ6HV3T.cjs'),chunkWJBQ2NBD_cjs=require('./chunk-WJBQ2NBD.cjs'),chunkBUNLC3II_cjs=require('./chunk-BUNLC3II.cjs'),w=require('kyro:config');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var w__default=/*#__PURE__*/_interopDefault(w);chunkBUNLC3II_cjs.h();exports.a=null;var l=null;async function b(){if(!exports.a){if(globalThis.__KYRO_INSTANCE__)try{await globalThis.__KYRO_INSTANCE__.shutdown();}catch{}try{let e=w__default.default.default||w__default.default,t=e.adapter,o=t&&!t.dialect&&typeof t.connect=="function";if(globalThis.DB&&(!t||o)){let s=globalThis.DB;e.adapter=new chunk6KUL2BSA_cjs.c({type:"sqlite",client:s}),chunkV65273ZG_cjs.D.info("Hot-swapped to D1 DrizzleAdapter");}exports.a=chunkV65273ZG_cjs.A(e),await exports.a.init();let a=e.adapter,p=a&&a.dialect&&(a.dialect==="postgres"||a.dialect==="sqlite"),c=a&&a.dialect==="mongodb",n;if(p)a.dialect==="postgres"?n=new chunkXBQ6HV3T_cjs.a({db:a.client}):a.dialect==="sqlite"&&(n=new chunk4MVLIR77_cjs.fb({db:a.rawClient||a.client}));else if(o&&!globalThis.DB){let s=process.env.KYRO_AUTH_DB_PATH||"./data/auth.db";n=new chunkBHR7OAU4_cjs.a({path:s});}else c&&(n=new chunkWJBQ2NBD_cjs.a({adapter:a}));if(n?.connect)try{await n.connect();}catch(s){chunkV65273ZG_cjs.D.warn("Auth connect warning:",s);}try{await exports.a.loadSettings();}catch(s){chunkV65273ZG_cjs.D.warn("loadSettings warning:",s);}try{await chunkECFZEY5B_cjs.e(n);}catch(s){chunkV65273ZG_cjs.D.warn("autoBootstrap warning:",s);}globalThis.__KYRO_INSTANCE__=exports.a;}catch(e){throw exports.a=null,l=null,chunkV65273ZG_cjs.D.error("Init failed, will retry:",e),e}}}async function E(e){let t=globalThis.DB?globalThis:null;try{let{env:o}=await import('cloudflare:workers');o&&(t=o);}catch{}if(e)try{t=e.locals?.cfContext?.env||e?.env||t;}catch{}if(!t)try{t=process.env;}catch{}t?.DB&&(globalThis.DB=t.DB),t?.STORAGE_BUCKET&&(globalThis.STORAGE_BUCKET=t.STORAGE_BUCKET),l||(l=b()),await l;}var _={graphqlEnabled:false,trpcEnabled:false,wsEnabled:false,requireAuth:false};function T(e){return exports.a?exports.a.settings?.access?.apiAccess?.[e]??_[e]??true:_[e]??true}var R=async e=>{if(!exports.a)try{await Promise.race([E(e),new Promise((t,o)=>setTimeout(()=>o(new Error("Initialization timeout")),3e4))]);}catch(t){return console.error("[Kyro API] Warm error:",t?.stack||t?.message||t),new Response(JSON.stringify({error:"Service Unavailable",message:"Kyro CMS is still starting up. Please try again in a moment."}),{status:503,headers:{"Content-Type":"application/json","Retry-After":"5"}})}try{let o=new URL(e.request.url).pathname,a=__KYRO_API_PATH__;if(o===`${a}/graphql`&&typeof exports.a.getGraphQL=="function"){if(!T("graphqlEnabled"))return new Response(JSON.stringify({error:"GraphQL is disabled"}),{status:503,headers:{"Content-Type":"application/json"}});let n=await exports.a.getGraphQL().fetch(e.request,e.locals);return new Response(n.body,n)}if(o.startsWith(`${a}/trpc/`)&&typeof exports.a.getTRPC=="function"){if(!T("trpcEnabled"))return new Response(JSON.stringify({error:"tRPC is disabled"}),{status:503,headers:{"Content-Type":"application/json"}});let n=await exports.a.getTRPC().fetch(e.request,e.locals);return new Response(n.body,n)}return await(await exports.a.getREST()).fetch(e.request,e.locals)}catch(t){return console.error("[Kyro API Execution Error]:",t?.stack||t?.message||t),new Response(JSON.stringify({error:"Internal Server Error",message:t?.message||String(t),stack:t?.stack}),{status:500,headers:{"Content-Type":"application/json"}})}},L=R;exports.b=E;exports.c=R;exports.d=L;
1
+ 'use strict';var chunkKJ3I35YV_cjs=require('./chunk-KJ3I35YV.cjs'),chunkECFZEY5B_cjs=require('./chunk-ECFZEY5B.cjs'),chunk3I6T73A5_cjs=require('./chunk-3I6T73A5.cjs'),chunkBHR7OAU4_cjs=require('./chunk-BHR7OAU4.cjs'),chunkTDGSIF5H_cjs=require('./chunk-TDGSIF5H.cjs'),chunkXBQ6HV3T_cjs=require('./chunk-XBQ6HV3T.cjs'),chunk7DUKWHRN_cjs=require('./chunk-7DUKWHRN.cjs'),chunkBUNLC3II_cjs=require('./chunk-BUNLC3II.cjs'),w=require('kyro:config');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var w__default=/*#__PURE__*/_interopDefault(w);chunkBUNLC3II_cjs.h();exports.a=null;var l=null;async function b(){if(!exports.a){if(globalThis.__KYRO_INSTANCE__)try{await globalThis.__KYRO_INSTANCE__.shutdown();}catch{}try{let e=w__default.default.default||w__default.default,t=e.adapter,o=t&&!t.dialect&&typeof t.connect=="function";if(globalThis.DB&&(!t||o)){let s=globalThis.DB;e.adapter=new chunkTDGSIF5H_cjs.c({type:"sqlite",client:s}),chunkKJ3I35YV_cjs.D.info("Hot-swapped to D1 DrizzleAdapter");}exports.a=chunkKJ3I35YV_cjs.A(e),await exports.a.init();let a=e.adapter,p=a&&a.dialect&&(a.dialect==="postgres"||a.dialect==="sqlite"),c=a&&a.dialect==="mongodb",n;if(p)a.dialect==="postgres"?n=new chunkXBQ6HV3T_cjs.a({db:a.client}):a.dialect==="sqlite"&&(n=new chunk3I6T73A5_cjs.fb({db:a.rawClient||a.client}));else if(o&&!globalThis.DB){let s=process.env.KYRO_AUTH_DB_PATH||"./data/auth.db";n=new chunkBHR7OAU4_cjs.a({path:s});}else c&&(n=new chunk7DUKWHRN_cjs.a({adapter:a}));if(n?.connect)try{await n.connect();}catch(s){chunkKJ3I35YV_cjs.D.warn("Auth connect warning:",s);}try{await exports.a.loadSettings();}catch(s){chunkKJ3I35YV_cjs.D.warn("loadSettings warning:",s);}try{await chunkECFZEY5B_cjs.e(n);}catch(s){chunkKJ3I35YV_cjs.D.warn("autoBootstrap warning:",s);}globalThis.__KYRO_INSTANCE__=exports.a;}catch(e){throw exports.a=null,l=null,chunkKJ3I35YV_cjs.D.error("Init failed, will retry:",e),e}}}async function E(e){let t=globalThis.DB?globalThis:null;try{let{env:o}=await import('cloudflare:workers');o&&(t=o);}catch{}if(e)try{t=e.locals?.cfContext?.env||e?.env||t;}catch{}if(!t)try{t=process.env;}catch{}t?.DB&&(globalThis.DB=t.DB),t?.STORAGE_BUCKET&&(globalThis.STORAGE_BUCKET=t.STORAGE_BUCKET),l||(l=b()),await l;}var _={graphqlEnabled:false,trpcEnabled:false,wsEnabled:false,requireAuth:false};function T(e){return exports.a?exports.a.settings?.access?.apiAccess?.[e]??_[e]??true:_[e]??true}var R=async e=>{if(!exports.a)try{await Promise.race([E(e),new Promise((t,o)=>setTimeout(()=>o(new Error("Initialization timeout")),3e4))]);}catch(t){return console.error("[Kyro API] Warm error:",t?.stack||t?.message||t),new Response(JSON.stringify({error:"Service Unavailable",message:"Kyro CMS is still starting up. Please try again in a moment."}),{status:503,headers:{"Content-Type":"application/json","Retry-After":"5"}})}try{let o=new URL(e.request.url).pathname,a=__KYRO_API_PATH__;if(o===`${a}/graphql`&&typeof exports.a.getGraphQL=="function"){if(!T("graphqlEnabled"))return new Response(JSON.stringify({error:"GraphQL is disabled"}),{status:503,headers:{"Content-Type":"application/json"}});let n=await exports.a.getGraphQL().fetch(e.request,e.locals);return new Response(n.body,n)}if(o.startsWith(`${a}/trpc/`)&&typeof exports.a.getTRPC=="function"){if(!T("trpcEnabled"))return new Response(JSON.stringify({error:"tRPC is disabled"}),{status:503,headers:{"Content-Type":"application/json"}});let n=await exports.a.getTRPC().fetch(e.request,e.locals);return new Response(n.body,n)}return await(await exports.a.getREST()).fetch(e.request,e.locals)}catch(t){return console.error("[Kyro API Execution Error]:",t?.stack||t?.message||t),new Response(JSON.stringify({error:"Internal Server Error",message:t?.message||String(t),stack:t?.stack}),{status:500,headers:{"Content-Type":"application/json"}})}},L=R;exports.b=E;exports.c=R;exports.d=L;
@@ -390,4 +390,4 @@ bucket_name = "${u}"
390
390
  `);}catch(x){let _=x?.stdout?.toString?.()||"",L=x?.stderr?.toString?.()||"";ee.fail("Deployment failed"),_&&process.stdout.write(_),L&&process.stdout.write(L),console.log(`
391
391
  ${C.red.bold("\u2716 Deployment Failed!")}`),console.log(` ${C.dim("See the Wrangler error above.")}
392
392
  `),f&&process.stdout.write(JSON.stringify({ok:false,error:"Deployment failed"})+`
393
- `),process.exit(1);}}),i}var ng=url.fileURLToPath(chunkBUNLC3II_cjs.g),og=Gt.dirname(ng),Gl="0.1.0";try{Gl=JSON.parse(et.readFileSync(Gt.join(og,"../../package.json"),"utf-8")).version;}catch{}var jt=new ie;jt.name("kyro").description("Kyro CMS - Astro-native headless CMS").version(Gl);jt.command("dev").description("Start Kyro CMS development server").option("-p, --port <port>","Port to run on","4321").option("-h, --host <host>","Host to bind to","localhost").action(async i=>{let{exec:t}=await import('child_process'),e=t(`astro dev --port ${i.port} --host ${i.host}`,{env:{...process.env,NODE_NO_WARNINGS:"1"}});e.stdout?.on("data",s=>process.stdout.write(s)),e.stderr?.on("data",s=>process.stderr.write(s)),process.on("SIGINT",()=>{e.kill("SIGINT"),process.exit(0);}),process.on("SIGTERM",()=>{e.kill("SIGTERM"),process.exit(0);});});jt.addCommand(Bo());jt.addCommand(Vl());var ts=jt.command("db").description("Database management commands");ts.command("generate").description("Generate migrations from schema").action(async()=>{let{exec:i}=await import('child_process');i("npx drizzle-kit generate",(t,e,s)=>{t&&(console.error("\u274C Generation failed:",t.message),process.exit(1));});});ts.command("migrate").description("Run database migrations").action(async()=>{let{exec:i}=await import('child_process');i("npx drizzle-kit migrate",(t,e,s)=>{t&&(console.error("\u274C Migration failed:",t.message),process.exit(1));});});ts.command("push").description("Push schema to database (development)").action(async()=>{let{exec:i}=await import('child_process');i("npx drizzle-kit push",(t,e,s)=>{t&&(console.error("\u274C Push failed:",t.message),process.exit(1));});});ts.command("seed").description("Seed database with initial data").action(async()=>{let{exec:i}=await import('child_process');i("npx tsx src/database/drizzle/seed.ts",(t,e,s)=>{t&&(console.error("\u274C Seeding failed:",t.message),process.exit(1));});});ts.command("studio").description("Open Drizzle Studio").action(async()=>{let{exec:i}=await import('child_process');i("npx drizzle-kit studio",(t,e,s)=>{t&&(console.error("\u274C Studio failed:",t.message),process.exit(1));});});var ug=jt.command("auth").description("Authentication management commands");ug.command("bootstrap").description("Create initial admin user").option("-e, --email <email>","Admin email",process.env.KYRO_ADMIN_EMAIL).option("-p, --password <password>","Admin password",process.env.KYRO_ADMIN_PASSWORD).option("-r, --role <role>","Admin role",process.env.KYRO_ADMIN_ROLE||"admin").action(async i=>{(!i.email||!i.password)&&(console.error("\u274C Email and password are required. Set KYRO_ADMIN_EMAIL and KYRO_ADMIN_PASSWORD env vars or use -e and -p options."),process.exit(1));try{let{bootstrapAdmin:t}=await import('../bootstrap-FTVBJ47D.cjs'),e=process.env.DATABASE_URL||"",s=e.toLowerCase().startsWith("postgres://")||e.toLowerCase().startsWith("postgresql://"),r=e.toLowerCase().startsWith("mongodb://")||e.toLowerCase().startsWith("mongodb+srv://"),n=!e||e.includes(".db")||e.includes("sqlite")||e.includes("file:"),o;if(s){let{PostgresAuthAdapter:a}=await import('../postgres-auth-adapter-ZO6HK5AK.cjs'),{drizzle:h}=await import('../postgres-js-3Y54EXVQ.cjs'),{default:d}=await import('../src-6LAUXXDM.cjs'),c=d(e,{max:1,onnotice:()=>{}}),f=h(c);o=new a({db:f});}else if(r){let{MongoDBAuthAdapter:a}=await import('../mongo-auth-adapter-W3HLB7OR.cjs'),h=await import('../lib-5QYYN6ML.cjs'),d=h.MongoClient??h.default?.MongoClient,c=new d(e);await c.connect();let f=c.db();o=new a({db:f});}else {let{SQLiteAuthAdapter:a}=await import('../sqlite-adapter-ZTABLT2X.cjs'),h=process.env.KYRO_AUTH_DB_PATH||"./data/auth.db";o=new a({path:h});}o.connect&&await o.connect();let u=await t({authAdapter:o,adminEmail:i.email,adminPassword:i.password,adminRole:i.role});o.disconnect&&await o.disconnect(),u.success||(console.error("\u274C Failed to create admin:",u.error),process.exit(1));}catch(t){console.error("\u274C Bootstrap failed:",t),process.exit(1);}});jt.command("health").description("Check system health").action(async()=>{let i=process.env.DATABASE_URL||"",t=i.toLowerCase().startsWith("postgres://")||i.toLowerCase().startsWith("postgresql://"),e=i.toLowerCase().startsWith("mongodb://")||i.toLowerCase().startsWith("mongodb+srv://"),s=!i||i.includes(".db")||i.includes("sqlite")||i.includes("file:");if(t)try{let{default:r}=await import('../src-6LAUXXDM.cjs'),n=r(i,{max:1,onnotice:()=>{}});await n.unsafe("SELECT 1"),await n.end();}catch{}else if(e)try{let r=await import('../lib-5QYYN6ML.cjs'),n=r.MongoClient??r.default?.MongoClient,o=new n(i);await o.connect(),await o.db().admin().ping(),await o.close();}catch{}else if(s)try{let r=process.env.KYRO_AUTH_DB_PATH||"./data/auth.db",{existsSync:n}=await import('fs');n(r);}catch{}});jt.parse();process.argv.slice(2).length||jt.outputHelp();
393
+ `),process.exit(1);}}),i}var ng=url.fileURLToPath(chunkBUNLC3II_cjs.g),og=Gt.dirname(ng),Gl="0.1.0";try{Gl=JSON.parse(et.readFileSync(Gt.join(og,"../../package.json"),"utf-8")).version;}catch{}var jt=new ie;jt.name("kyro").description("Kyro CMS - Astro-native headless CMS").version(Gl);jt.command("dev").description("Start Kyro CMS development server").option("-p, --port <port>","Port to run on","4321").option("-h, --host <host>","Host to bind to","localhost").action(async i=>{let{exec:t}=await import('child_process'),e=t(`astro dev --port ${i.port} --host ${i.host}`,{env:{...process.env,NODE_NO_WARNINGS:"1"}});e.stdout?.on("data",s=>process.stdout.write(s)),e.stderr?.on("data",s=>process.stderr.write(s)),process.on("SIGINT",()=>{e.kill("SIGINT"),process.exit(0);}),process.on("SIGTERM",()=>{e.kill("SIGTERM"),process.exit(0);});});jt.addCommand(Bo());jt.addCommand(Vl());var ts=jt.command("db").description("Database management commands");ts.command("generate").description("Generate migrations from schema").action(async()=>{let{exec:i}=await import('child_process');i("npx drizzle-kit generate",(t,e,s)=>{t&&(console.error("\u274C Generation failed:",t.message),process.exit(1));});});ts.command("migrate").description("Run database migrations").action(async()=>{let{exec:i}=await import('child_process');i("npx drizzle-kit migrate",(t,e,s)=>{t&&(console.error("\u274C Migration failed:",t.message),process.exit(1));});});ts.command("push").description("Push schema to database (development)").action(async()=>{let{exec:i}=await import('child_process');i("npx drizzle-kit push",(t,e,s)=>{t&&(console.error("\u274C Push failed:",t.message),process.exit(1));});});ts.command("seed").description("Seed database with initial data").action(async()=>{let{exec:i}=await import('child_process');i("npx tsx src/database/drizzle/seed.ts",(t,e,s)=>{t&&(console.error("\u274C Seeding failed:",t.message),process.exit(1));});});ts.command("studio").description("Open Drizzle Studio").action(async()=>{let{exec:i}=await import('child_process');i("npx drizzle-kit studio",(t,e,s)=>{t&&(console.error("\u274C Studio failed:",t.message),process.exit(1));});});var ug=jt.command("auth").description("Authentication management commands");ug.command("bootstrap").description("Create initial admin user").option("-e, --email <email>","Admin email",process.env.KYRO_ADMIN_EMAIL).option("-p, --password <password>","Admin password",process.env.KYRO_ADMIN_PASSWORD).option("-r, --role <role>","Admin role",process.env.KYRO_ADMIN_ROLE||"admin").action(async i=>{(!i.email||!i.password)&&(console.error("\u274C Email and password are required. Set KYRO_ADMIN_EMAIL and KYRO_ADMIN_PASSWORD env vars or use -e and -p options."),process.exit(1));try{let{bootstrapAdmin:t}=await import('../bootstrap-FTVBJ47D.cjs'),e=process.env.DATABASE_URL||"",s=e.toLowerCase().startsWith("postgres://")||e.toLowerCase().startsWith("postgresql://"),r=e.toLowerCase().startsWith("mongodb://")||e.toLowerCase().startsWith("mongodb+srv://"),n=!e||e.includes(".db")||e.includes("sqlite")||e.includes("file:"),o;if(s){let{PostgresAuthAdapter:a}=await import('../postgres-auth-adapter-ZO6HK5AK.cjs'),{drizzle:h}=await import('../postgres-js-3Y54EXVQ.cjs'),{default:d}=await import('../src-6LAUXXDM.cjs'),c=d(e,{max:1,onnotice:()=>{}}),f=h(c);o=new a({db:f});}else if(r){let{MongoDBAuthAdapter:a}=await import('../mongo-auth-adapter-EUHAYWJ6.cjs'),h=await import('../lib-5QYYN6ML.cjs'),d=h.MongoClient??h.default?.MongoClient,c=new d(e);await c.connect();let f=c.db();o=new a({db:f});}else {let{SQLiteAuthAdapter:a}=await import('../sqlite-adapter-ZTABLT2X.cjs'),h=process.env.KYRO_AUTH_DB_PATH||"./data/auth.db";o=new a({path:h});}o.connect&&await o.connect();let u=await t({authAdapter:o,adminEmail:i.email,adminPassword:i.password,adminRole:i.role});o.disconnect&&await o.disconnect(),u.success||(console.error("\u274C Failed to create admin:",u.error),process.exit(1));}catch(t){console.error("\u274C Bootstrap failed:",t),process.exit(1);}});jt.command("health").description("Check system health").action(async()=>{let i=process.env.DATABASE_URL||"",t=i.toLowerCase().startsWith("postgres://")||i.toLowerCase().startsWith("postgresql://"),e=i.toLowerCase().startsWith("mongodb://")||i.toLowerCase().startsWith("mongodb+srv://"),s=!i||i.includes(".db")||i.includes("sqlite")||i.includes("file:");if(t)try{let{default:r}=await import('../src-6LAUXXDM.cjs'),n=r(i,{max:1,onnotice:()=>{}});await n.unsafe("SELECT 1"),await n.end();}catch{}else if(e)try{let r=await import('../lib-5QYYN6ML.cjs'),n=r.MongoClient??r.default?.MongoClient,o=new n(i);await o.connect(),await o.db().admin().ping(),await o.close();}catch{}else if(s)try{let r=process.env.KYRO_AUTH_DB_PATH||"./data/auth.db",{existsSync:n}=await import('fs');n(r);}catch{}});jt.parse();process.argv.slice(2).length||jt.outputHelp();
package/dist/cli/index.js CHANGED
@@ -391,4 +391,4 @@ bucket_name = "${u}"
391
391
  `);}catch(v){let S=v?.stdout?.toString?.()||"",W=v?.stderr?.toString?.()||"";se.fail("Deployment failed"),S&&process.stdout.write(S),W&&process.stdout.write(W),console.log(`
392
392
  ${E.red.bold("\u2716 Deployment Failed!")}`),console.log(` ${E.dim("See the Wrangler error above.")}
393
393
  `),f&&process.stdout.write(JSON.stringify({ok:false,error:"Deployment failed"})+`
394
- `),process.exit(1);}}),i}var og=fileURLToPath(import.meta.url),ug=dirname(og),zl="0.1.0";try{zl=JSON.parse(readFileSync(join(ug,"../../package.json"),"utf-8")).version;}catch{}var Nt=new re;Nt.name("kyro").description("Kyro CMS - Astro-native headless CMS").version(zl);Nt.command("dev").description("Start Kyro CMS development server").option("-p, --port <port>","Port to run on","4321").option("-h, --host <host>","Host to bind to","localhost").action(async i=>{let{exec:t}=await import('child_process'),e=t(`astro dev --port ${i.port} --host ${i.host}`,{env:{...process.env,NODE_NO_WARNINGS:"1"}});e.stdout?.on("data",s=>process.stdout.write(s)),e.stderr?.on("data",s=>process.stderr.write(s)),process.on("SIGINT",()=>{e.kill("SIGINT"),process.exit(0);}),process.on("SIGTERM",()=>{e.kill("SIGTERM"),process.exit(0);});});Nt.addCommand(Mo());Nt.addCommand(Gl());var es=Nt.command("db").description("Database management commands");es.command("generate").description("Generate migrations from schema").action(async()=>{let{exec:i}=await import('child_process');i("npx drizzle-kit generate",(t,e,s)=>{t&&(console.error("\u274C Generation failed:",t.message),process.exit(1));});});es.command("migrate").description("Run database migrations").action(async()=>{let{exec:i}=await import('child_process');i("npx drizzle-kit migrate",(t,e,s)=>{t&&(console.error("\u274C Migration failed:",t.message),process.exit(1));});});es.command("push").description("Push schema to database (development)").action(async()=>{let{exec:i}=await import('child_process');i("npx drizzle-kit push",(t,e,s)=>{t&&(console.error("\u274C Push failed:",t.message),process.exit(1));});});es.command("seed").description("Seed database with initial data").action(async()=>{let{exec:i}=await import('child_process');i("npx tsx src/database/drizzle/seed.ts",(t,e,s)=>{t&&(console.error("\u274C Seeding failed:",t.message),process.exit(1));});});es.command("studio").description("Open Drizzle Studio").action(async()=>{let{exec:i}=await import('child_process');i("npx drizzle-kit studio",(t,e,s)=>{t&&(console.error("\u274C Studio failed:",t.message),process.exit(1));});});var ag=Nt.command("auth").description("Authentication management commands");ag.command("bootstrap").description("Create initial admin user").option("-e, --email <email>","Admin email",process.env.KYRO_ADMIN_EMAIL).option("-p, --password <password>","Admin password",process.env.KYRO_ADMIN_PASSWORD).option("-r, --role <role>","Admin role",process.env.KYRO_ADMIN_ROLE||"admin").action(async i=>{(!i.email||!i.password)&&(console.error("\u274C Email and password are required. Set KYRO_ADMIN_EMAIL and KYRO_ADMIN_PASSWORD env vars or use -e and -p options."),process.exit(1));try{let{bootstrapAdmin:t}=await import('../bootstrap-IGHJFNYG.js'),e=process.env.DATABASE_URL||"",s=e.toLowerCase().startsWith("postgres://")||e.toLowerCase().startsWith("postgresql://"),r=e.toLowerCase().startsWith("mongodb://")||e.toLowerCase().startsWith("mongodb+srv://"),n=!e||e.includes(".db")||e.includes("sqlite")||e.includes("file:"),o;if(s){let{PostgresAuthAdapter:a}=await import('../postgres-auth-adapter-SK3N3OSS.js'),{drizzle:h}=await import('../postgres-js-4CI7FMYS.js'),{default:d}=await import('../src-QBADSZV4.js'),c=d(e,{max:1,onnotice:()=>{}}),f=h(c);o=new a({db:f});}else if(r){let{MongoDBAuthAdapter:a}=await import('../mongo-auth-adapter-QDXVHREJ.js'),h=await import('../lib-XXYYUPMW.js'),d=h.MongoClient??h.default?.MongoClient,c=new d(e);await c.connect();let f=c.db();o=new a({db:f});}else {let{SQLiteAuthAdapter:a}=await import('../sqlite-adapter-4TPNROJK.js'),h=process.env.KYRO_AUTH_DB_PATH||"./data/auth.db";o=new a({path:h});}o.connect&&await o.connect();let u=await t({authAdapter:o,adminEmail:i.email,adminPassword:i.password,adminRole:i.role});o.disconnect&&await o.disconnect(),u.success||(console.error("\u274C Failed to create admin:",u.error),process.exit(1));}catch(t){console.error("\u274C Bootstrap failed:",t),process.exit(1);}});Nt.command("health").description("Check system health").action(async()=>{let i=process.env.DATABASE_URL||"",t=i.toLowerCase().startsWith("postgres://")||i.toLowerCase().startsWith("postgresql://"),e=i.toLowerCase().startsWith("mongodb://")||i.toLowerCase().startsWith("mongodb+srv://"),s=!i||i.includes(".db")||i.includes("sqlite")||i.includes("file:");if(t)try{let{default:r}=await import('../src-QBADSZV4.js'),n=r(i,{max:1,onnotice:()=>{}});await n.unsafe("SELECT 1"),await n.end();}catch{}else if(e)try{let r=await import('../lib-XXYYUPMW.js'),n=r.MongoClient??r.default?.MongoClient,o=new n(i);await o.connect(),await o.db().admin().ping(),await o.close();}catch{}else if(s)try{let r=process.env.KYRO_AUTH_DB_PATH||"./data/auth.db",{existsSync:n}=await import('fs');n(r);}catch{}});Nt.parse();process.argv.slice(2).length||Nt.outputHelp();
394
+ `),process.exit(1);}}),i}var og=fileURLToPath(import.meta.url),ug=dirname(og),zl="0.1.0";try{zl=JSON.parse(readFileSync(join(ug,"../../package.json"),"utf-8")).version;}catch{}var Nt=new re;Nt.name("kyro").description("Kyro CMS - Astro-native headless CMS").version(zl);Nt.command("dev").description("Start Kyro CMS development server").option("-p, --port <port>","Port to run on","4321").option("-h, --host <host>","Host to bind to","localhost").action(async i=>{let{exec:t}=await import('child_process'),e=t(`astro dev --port ${i.port} --host ${i.host}`,{env:{...process.env,NODE_NO_WARNINGS:"1"}});e.stdout?.on("data",s=>process.stdout.write(s)),e.stderr?.on("data",s=>process.stderr.write(s)),process.on("SIGINT",()=>{e.kill("SIGINT"),process.exit(0);}),process.on("SIGTERM",()=>{e.kill("SIGTERM"),process.exit(0);});});Nt.addCommand(Mo());Nt.addCommand(Gl());var es=Nt.command("db").description("Database management commands");es.command("generate").description("Generate migrations from schema").action(async()=>{let{exec:i}=await import('child_process');i("npx drizzle-kit generate",(t,e,s)=>{t&&(console.error("\u274C Generation failed:",t.message),process.exit(1));});});es.command("migrate").description("Run database migrations").action(async()=>{let{exec:i}=await import('child_process');i("npx drizzle-kit migrate",(t,e,s)=>{t&&(console.error("\u274C Migration failed:",t.message),process.exit(1));});});es.command("push").description("Push schema to database (development)").action(async()=>{let{exec:i}=await import('child_process');i("npx drizzle-kit push",(t,e,s)=>{t&&(console.error("\u274C Push failed:",t.message),process.exit(1));});});es.command("seed").description("Seed database with initial data").action(async()=>{let{exec:i}=await import('child_process');i("npx tsx src/database/drizzle/seed.ts",(t,e,s)=>{t&&(console.error("\u274C Seeding failed:",t.message),process.exit(1));});});es.command("studio").description("Open Drizzle Studio").action(async()=>{let{exec:i}=await import('child_process');i("npx drizzle-kit studio",(t,e,s)=>{t&&(console.error("\u274C Studio failed:",t.message),process.exit(1));});});var ag=Nt.command("auth").description("Authentication management commands");ag.command("bootstrap").description("Create initial admin user").option("-e, --email <email>","Admin email",process.env.KYRO_ADMIN_EMAIL).option("-p, --password <password>","Admin password",process.env.KYRO_ADMIN_PASSWORD).option("-r, --role <role>","Admin role",process.env.KYRO_ADMIN_ROLE||"admin").action(async i=>{(!i.email||!i.password)&&(console.error("\u274C Email and password are required. Set KYRO_ADMIN_EMAIL and KYRO_ADMIN_PASSWORD env vars or use -e and -p options."),process.exit(1));try{let{bootstrapAdmin:t}=await import('../bootstrap-IGHJFNYG.js'),e=process.env.DATABASE_URL||"",s=e.toLowerCase().startsWith("postgres://")||e.toLowerCase().startsWith("postgresql://"),r=e.toLowerCase().startsWith("mongodb://")||e.toLowerCase().startsWith("mongodb+srv://"),n=!e||e.includes(".db")||e.includes("sqlite")||e.includes("file:"),o;if(s){let{PostgresAuthAdapter:a}=await import('../postgres-auth-adapter-SK3N3OSS.js'),{drizzle:h}=await import('../postgres-js-4CI7FMYS.js'),{default:d}=await import('../src-QBADSZV4.js'),c=d(e,{max:1,onnotice:()=>{}}),f=h(c);o=new a({db:f});}else if(r){let{MongoDBAuthAdapter:a}=await import('../mongo-auth-adapter-FW7ATYQ6.js'),h=await import('../lib-XXYYUPMW.js'),d=h.MongoClient??h.default?.MongoClient,c=new d(e);await c.connect();let f=c.db();o=new a({db:f});}else {let{SQLiteAuthAdapter:a}=await import('../sqlite-adapter-4TPNROJK.js'),h=process.env.KYRO_AUTH_DB_PATH||"./data/auth.db";o=new a({path:h});}o.connect&&await o.connect();let u=await t({authAdapter:o,adminEmail:i.email,adminPassword:i.password,adminRole:i.role});o.disconnect&&await o.disconnect(),u.success||(console.error("\u274C Failed to create admin:",u.error),process.exit(1));}catch(t){console.error("\u274C Bootstrap failed:",t),process.exit(1);}});Nt.command("health").description("Check system health").action(async()=>{let i=process.env.DATABASE_URL||"",t=i.toLowerCase().startsWith("postgres://")||i.toLowerCase().startsWith("postgresql://"),e=i.toLowerCase().startsWith("mongodb://")||i.toLowerCase().startsWith("mongodb+srv://"),s=!i||i.includes(".db")||i.includes("sqlite")||i.includes("file:");if(t)try{let{default:r}=await import('../src-QBADSZV4.js'),n=r(i,{max:1,onnotice:()=>{}});await n.unsafe("SELECT 1"),await n.end();}catch{}else if(e)try{let r=await import('../lib-XXYYUPMW.js'),n=r.MongoClient??r.default?.MongoClient,o=new n(i);await o.connect(),await o.db().admin().ping(),await o.close();}catch{}else if(s)try{let r=process.env.KYRO_AUTH_DB_PATH||"./data/auth.db",{existsSync:n}=await import('fs');n(r);}catch{}});Nt.parse();process.argv.slice(2).length||Nt.outputHelp();
@@ -1 +1 @@
1
- 'use strict';require('../chunk-AMGJ5AFH.cjs');var chunk6KUL2BSA_cjs=require('../chunk-6KUL2BSA.cjs'),chunkXBQ6HV3T_cjs=require('../chunk-XBQ6HV3T.cjs');require('../chunk-7JWQ2PZP.cjs'),require('../chunk-NGNJSUGL.cjs'),require('../chunk-KCHPADCH.cjs'),require('../chunk-BAVN7VDR.cjs'),require('../chunk-LY7N3UHH.cjs'),require('../chunk-7ACHOBWY.cjs'),require('../chunk-GNOSG3PK.cjs'),require('../chunk-BCEE4NBZ.cjs'),require('../chunk-VRZC4TTF.cjs'),require('../chunk-VQ53TFYA.cjs'),require('../chunk-F4ITQ6XQ.cjs'),require('../chunk-HTYVI2HK.cjs'),require('../chunk-ZOVH6QT5.cjs'),require('../chunk-7WMMKGEO.cjs'),require('../chunk-BUNLC3II.cjs');Object.defineProperty(exports,"DrizzleAdapter",{enumerable:true,get:function(){return chunk6KUL2BSA_cjs.c}});Object.defineProperty(exports,"collectionToDrizzleSchema",{enumerable:true,get:function(){return chunk6KUL2BSA_cjs.b}});Object.defineProperty(exports,"createDatabase",{enumerable:true,get:function(){return chunk6KUL2BSA_cjs.f}});Object.defineProperty(exports,"createDrizzleAdapter",{enumerable:true,get:function(){return chunk6KUL2BSA_cjs.d}});Object.defineProperty(exports,"fieldToDrizzleType",{enumerable:true,get:function(){return chunk6KUL2BSA_cjs.a}});Object.defineProperty(exports,"runMigrations",{enumerable:true,get:function(){return chunk6KUL2BSA_cjs.g}});Object.defineProperty(exports,"seedDefaultRoles",{enumerable:true,get:function(){return chunk6KUL2BSA_cjs.h}});Object.defineProperty(exports,"PostgresAuthAdapter",{enumerable:true,get:function(){return chunkXBQ6HV3T_cjs.a}});
1
+ 'use strict';require('../chunk-AMGJ5AFH.cjs');var chunkTDGSIF5H_cjs=require('../chunk-TDGSIF5H.cjs'),chunkXBQ6HV3T_cjs=require('../chunk-XBQ6HV3T.cjs');require('../chunk-7JWQ2PZP.cjs'),require('../chunk-NGNJSUGL.cjs'),require('../chunk-KCHPADCH.cjs'),require('../chunk-BAVN7VDR.cjs'),require('../chunk-LY7N3UHH.cjs'),require('../chunk-7ACHOBWY.cjs'),require('../chunk-GNOSG3PK.cjs'),require('../chunk-BCEE4NBZ.cjs'),require('../chunk-VRZC4TTF.cjs'),require('../chunk-VQ53TFYA.cjs'),require('../chunk-F4ITQ6XQ.cjs'),require('../chunk-HTYVI2HK.cjs'),require('../chunk-ZOVH6QT5.cjs'),require('../chunk-7WMMKGEO.cjs'),require('../chunk-BUNLC3II.cjs');Object.defineProperty(exports,"DrizzleAdapter",{enumerable:true,get:function(){return chunkTDGSIF5H_cjs.c}});Object.defineProperty(exports,"collectionToDrizzleSchema",{enumerable:true,get:function(){return chunkTDGSIF5H_cjs.b}});Object.defineProperty(exports,"createDatabase",{enumerable:true,get:function(){return chunkTDGSIF5H_cjs.f}});Object.defineProperty(exports,"createDrizzleAdapter",{enumerable:true,get:function(){return chunkTDGSIF5H_cjs.d}});Object.defineProperty(exports,"fieldToDrizzleType",{enumerable:true,get:function(){return chunkTDGSIF5H_cjs.a}});Object.defineProperty(exports,"runMigrations",{enumerable:true,get:function(){return chunkTDGSIF5H_cjs.g}});Object.defineProperty(exports,"seedDefaultRoles",{enumerable:true,get:function(){return chunkTDGSIF5H_cjs.h}});Object.defineProperty(exports,"PostgresAuthAdapter",{enumerable:true,get:function(){return chunkXBQ6HV3T_cjs.a}});
@@ -1 +1 @@
1
- import'../chunk-QDBGBDCT.js';export{c as DrizzleAdapter,b as collectionToDrizzleSchema,f as createDatabase,d as createDrizzleAdapter,a as fieldToDrizzleType,g as runMigrations,h as seedDefaultRoles}from'../chunk-BU6O3TP7.js';export{a as PostgresAuthAdapter}from'../chunk-ZWDBPEXL.js';import'../chunk-47CXBWMA.js';import'../chunk-EML5FDUU.js';import'../chunk-OXGJOYEO.js';import'../chunk-FLMUMPDE.js';import'../chunk-2HA6EKXX.js';import'../chunk-JV4HJBXW.js';import'../chunk-N5POANYV.js';import'../chunk-HRAY65XH.js';import'../chunk-3NSZZCOJ.js';import'../chunk-SLMIYECU.js';import'../chunk-P6JITOFF.js';import'../chunk-7NH7H3WA.js';import'../chunk-VVVCCB6R.js';import'../chunk-TBHNE4VV.js';import'../chunk-Y2YAKDEQ.js';if (typeof window === "undefined") { const { createRequire } = await import(/* @vite-ignore */ 'module'); createRequire(import.meta.url); }
1
+ import'../chunk-QDBGBDCT.js';export{c as DrizzleAdapter,b as collectionToDrizzleSchema,f as createDatabase,d as createDrizzleAdapter,a as fieldToDrizzleType,g as runMigrations,h as seedDefaultRoles}from'../chunk-KNOFTUQV.js';export{a as PostgresAuthAdapter}from'../chunk-ZWDBPEXL.js';import'../chunk-47CXBWMA.js';import'../chunk-EML5FDUU.js';import'../chunk-OXGJOYEO.js';import'../chunk-FLMUMPDE.js';import'../chunk-2HA6EKXX.js';import'../chunk-JV4HJBXW.js';import'../chunk-N5POANYV.js';import'../chunk-HRAY65XH.js';import'../chunk-3NSZZCOJ.js';import'../chunk-SLMIYECU.js';import'../chunk-P6JITOFF.js';import'../chunk-7NH7H3WA.js';import'../chunk-VVVCCB6R.js';import'../chunk-TBHNE4VV.js';import'../chunk-Y2YAKDEQ.js';if (typeof window === "undefined") { const { createRequire } = await import(/* @vite-ignore */ 'module'); createRequire(import.meta.url); }