@kyro-cms/core 0.13.8 → 0.13.10

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 (52) hide show
  1. package/dist/{WebhookService-BJTCP3cU.d.cts → WebhookService-2ys-dFjb.d.cts} +1 -1
  2. package/dist/{WebhookService-Bqr_66lK.d.ts → WebhookService-Y-X6GgLL.d.ts} +1 -1
  3. package/dist/api-handler-graphql.cjs +1 -1
  4. package/dist/api-handler-graphql.js +1 -1
  5. package/dist/api-handler-trpc.cjs +1 -1
  6. package/dist/api-handler-trpc.js +1 -1
  7. package/dist/api-handler.cjs +1 -1
  8. package/dist/api-handler.js +1 -1
  9. package/dist/{base-C2DOe8wD.d.ts → base-BAApLdlP.d.ts} +1 -1
  10. package/dist/{base-DIpT2Vuz.d.cts → base-C6bzgEN1.d.cts} +1 -1
  11. package/dist/{chunk-ZE2X3FBU.js → chunk-25M5A427.js} +4 -4
  12. package/dist/chunk-3BDAH6FD.cjs +132 -0
  13. package/dist/{chunk-PPGZHOYR.cjs → chunk-77ZGCYHZ.cjs} +1 -1
  14. package/dist/{chunk-A7763NCF.cjs → chunk-JGJPGP4Q.cjs} +3 -3
  15. package/dist/chunk-LCTCEO34.js +5 -0
  16. package/dist/chunk-PYVZJIQ3.js +133 -0
  17. package/dist/{chunk-TVWHTVLI.js → chunk-U7UUABFL.js} +2 -2
  18. package/dist/chunk-V7E74PHS.cjs +4 -0
  19. package/dist/cli/index.cjs +21 -21
  20. package/dist/cli/index.js +21 -21
  21. package/dist/drizzle/index.cjs +1 -1
  22. package/dist/drizzle/index.d.cts +2 -2
  23. package/dist/drizzle/index.d.ts +2 -2
  24. package/dist/drizzle/index.js +1 -1
  25. package/dist/graphql/index.d.cts +2 -2
  26. package/dist/graphql/index.d.ts +2 -2
  27. package/dist/{index-xqpVL2Zq.d.ts → index-94nxUkEf.d.ts} +2 -2
  28. package/dist/{index-B_39z2jP.d.cts → index-CZctgiAx.d.cts} +2 -2
  29. package/dist/{index-C9uBoJtm.d.ts → index-DjhIVdL9.d.ts} +1 -1
  30. package/dist/{index-Ci7aUrmN.d.cts → index-GSRx0kyZ.d.cts} +1 -1
  31. package/dist/index.cjs +16 -16
  32. package/dist/index.d.cts +12 -23
  33. package/dist/index.d.ts +12 -23
  34. package/dist/index.js +22 -22
  35. package/dist/{local-TF5ZMHWW.js → local-32NFEZEC.js} +1 -1
  36. package/dist/local-RVYI6YX4.cjs +1 -0
  37. package/dist/mongodb/index.d.cts +3 -3
  38. package/dist/mongodb/index.d.ts +3 -3
  39. package/dist/rest/index.d.cts +3 -3
  40. package/dist/rest/index.d.ts +3 -3
  41. package/dist/templates/index.d.cts +1 -1
  42. package/dist/templates/index.d.ts +1 -1
  43. package/dist/trpc/index.d.cts +2 -2
  44. package/dist/trpc/index.d.ts +2 -2
  45. package/dist/{types-CdwfDpyW.d.cts → types-BQnOYvym.d.cts} +1 -13
  46. package/dist/{types-CKWnrUAh.d.ts → types-M2BhNVof.d.ts} +1 -13
  47. package/package.json +4 -7
  48. package/dist/chunk-GWUHIIPO.cjs +0 -132
  49. package/dist/chunk-MCK2QRAU.cjs +0 -4
  50. package/dist/chunk-SYE3OS5T.js +0 -5
  51. package/dist/chunk-TJ6N5ZPZ.js +0 -133
  52. package/dist/local-DKP43BWQ.cjs +0 -1
@@ -1,4 +1,4 @@
1
- import { B as BaseAdapter } from './types-CdwfDpyW.cjs';
1
+ import { B as BaseAdapter } from './types-BQnOYvym.cjs';
2
2
 
3
3
  declare const WEBHOOK_EVENTS: {
4
4
  readonly COLLECTION_CREATE: "collection.create";
@@ -1,4 +1,4 @@
1
- import { B as BaseAdapter } from './types-CKWnrUAh.js';
1
+ import { B as BaseAdapter } from './types-M2BhNVof.js';
2
2
 
3
3
  declare const WEBHOOK_EVENTS: {
4
4
  readonly COLLECTION_CREATE: "collection.create";
@@ -1 +1 @@
1
- 'use strict';var chunkPPGZHOYR_cjs=require('./chunk-PPGZHOYR.cjs');require('./chunk-MCK2QRAU.cjs'),require('./chunk-VPBGZW4P.cjs'),require('./chunk-N7CDHWQH.cjs'),require('./chunk-DCKJT247.cjs'),require('./chunk-7KTPBTH5.cjs'),require('./chunk-24W5I6SJ.cjs'),require('./chunk-O2SA56P2.cjs'),require('./chunk-H2IJDTA2.cjs'),require('./chunk-PW6Y5MQL.cjs'),require('./chunk-34LCWI5X.cjs'),require('./chunk-LXTVMP5F.cjs'),require('./chunk-2I2AXTKY.cjs'),require('./chunk-GS4CMYKS.cjs'),require('./chunk-OJBL4CXK.cjs'),require('./chunk-DCFOVCJX.cjs'),require('./chunk-FU76HURF.cjs'),require('./chunk-GWUHIIPO.cjs'),require('./chunk-EG4SRTYS.cjs'),require('./chunk-3A5UO6OQ.cjs'),require('./chunk-23RSKVJP.cjs'),require('./chunk-YOJOVQIH.cjs'),require('./chunk-XL64URKD.cjs'),require('./chunk-UE7DTBD7.cjs'),require('./chunk-O4PPZOVI.cjs'),require('./chunk-JJY2F6NL.cjs'),require('./chunk-OXEJCIOA.cjs'),require('./chunk-KOSR7235.cjs'),require('./chunk-JHFD3IAU.cjs');function r(e){return new Response(e.body,e)}var p={graphqlEnabled:false,trpcEnabled:false,wsEnabled:false,requireAuth:false};function n(){return new Response(JSON.stringify({error:"GraphQL is disabled"}),{status:503,headers:{"Content-Type":"application/json"}})}async function o(){try{return (await chunkPPGZHOYR_cjs.a.db.findOne({collection:"_globals_access-settings",where:{},draft:!0}))?.apiAccess?.graphqlEnabled??p.graphqlEnabled}catch{return true}}var u=async e=>{if(await chunkPPGZHOYR_cjs.b(e),!await o())return n();let s=await chunkPPGZHOYR_cjs.a.getGraphQL().fetch(e.request,e.locals);return r(s)},d=async e=>{if(await chunkPPGZHOYR_cjs.b(e),!await o())return n();let s=await chunkPPGZHOYR_cjs.a.getGraphQL().fetch(e.request,e.locals);return r(s)};exports.GET=d;exports.POST=u;
1
+ 'use strict';var chunk77ZGCYHZ_cjs=require('./chunk-77ZGCYHZ.cjs');require('./chunk-V7E74PHS.cjs'),require('./chunk-VPBGZW4P.cjs'),require('./chunk-N7CDHWQH.cjs'),require('./chunk-DCKJT247.cjs'),require('./chunk-7KTPBTH5.cjs'),require('./chunk-24W5I6SJ.cjs'),require('./chunk-O2SA56P2.cjs'),require('./chunk-H2IJDTA2.cjs'),require('./chunk-PW6Y5MQL.cjs'),require('./chunk-34LCWI5X.cjs'),require('./chunk-LXTVMP5F.cjs'),require('./chunk-2I2AXTKY.cjs'),require('./chunk-GS4CMYKS.cjs'),require('./chunk-OJBL4CXK.cjs'),require('./chunk-DCFOVCJX.cjs'),require('./chunk-FU76HURF.cjs'),require('./chunk-3BDAH6FD.cjs'),require('./chunk-EG4SRTYS.cjs'),require('./chunk-3A5UO6OQ.cjs'),require('./chunk-23RSKVJP.cjs'),require('./chunk-YOJOVQIH.cjs'),require('./chunk-XL64URKD.cjs'),require('./chunk-UE7DTBD7.cjs'),require('./chunk-O4PPZOVI.cjs'),require('./chunk-JJY2F6NL.cjs'),require('./chunk-OXEJCIOA.cjs'),require('./chunk-KOSR7235.cjs'),require('./chunk-JHFD3IAU.cjs');function r(e){return new Response(e.body,e)}var p={graphqlEnabled:false,trpcEnabled:false,wsEnabled:false,requireAuth:false};function n(){return new Response(JSON.stringify({error:"GraphQL is disabled"}),{status:503,headers:{"Content-Type":"application/json"}})}async function o(){try{return (await chunk77ZGCYHZ_cjs.a.db.findOne({collection:"_globals_access-settings",where:{},draft:!0}))?.apiAccess?.graphqlEnabled??p.graphqlEnabled}catch{return true}}var u=async e=>{if(await chunk77ZGCYHZ_cjs.b(e),!await o())return n();let s=await chunk77ZGCYHZ_cjs.a.getGraphQL().fetch(e.request,e.locals);return r(s)},d=async e=>{if(await chunk77ZGCYHZ_cjs.b(e),!await o())return n();let s=await chunk77ZGCYHZ_cjs.a.getGraphQL().fetch(e.request,e.locals);return r(s)};exports.GET=d;exports.POST=u;
@@ -1,2 +1,2 @@
1
- import {b,a}from'./chunk-TVWHTVLI.js';import'./chunk-SYE3OS5T.js';import'./chunk-KUY4QDAL.js';import'./chunk-LGUHXOEW.js';import'./chunk-ZMH35QYG.js';import'./chunk-GTAKGVUY.js';import'./chunk-5RBGM5N5.js';import'./chunk-3RIGRHON.js';import'./chunk-FAG2645P.js';import'./chunk-IIVBEZC2.js';import'./chunk-I22MSXGL.js';import'./chunk-SBFVITY2.js';import'./chunk-5I3BM5TV.js';import'./chunk-W5GDZG64.js';import'./chunk-OPKZYQV7.js';import'./chunk-3N34WXBS.js';import'./chunk-OXH6CANN.js';import'./chunk-TJ6N5ZPZ.js';import'./chunk-JXJTFBHG.js';import'./chunk-IIPSXKNV.js';import'./chunk-7EY3GXRA.js';import'./chunk-WLSVS3NC.js';import'./chunk-O6I26T6A.js';import'./chunk-YNBJGPIU.js';import'./chunk-YNSKDTFG.js';import'./chunk-VLFM66BZ.js';import'./chunk-NGNXOXI5.js';import'./chunk-O4RKZQYQ.js';import'./chunk-RLW6AQF2.js';if (typeof window === "undefined") { const { createRequire } = await import(/* @vite-ignore */ 'module'); createRequire(import.meta.url); }
1
+ import {b,a}from'./chunk-U7UUABFL.js';import'./chunk-LCTCEO34.js';import'./chunk-KUY4QDAL.js';import'./chunk-LGUHXOEW.js';import'./chunk-ZMH35QYG.js';import'./chunk-GTAKGVUY.js';import'./chunk-5RBGM5N5.js';import'./chunk-3RIGRHON.js';import'./chunk-FAG2645P.js';import'./chunk-IIVBEZC2.js';import'./chunk-I22MSXGL.js';import'./chunk-SBFVITY2.js';import'./chunk-5I3BM5TV.js';import'./chunk-W5GDZG64.js';import'./chunk-OPKZYQV7.js';import'./chunk-3N34WXBS.js';import'./chunk-OXH6CANN.js';import'./chunk-PYVZJIQ3.js';import'./chunk-JXJTFBHG.js';import'./chunk-IIPSXKNV.js';import'./chunk-7EY3GXRA.js';import'./chunk-WLSVS3NC.js';import'./chunk-O6I26T6A.js';import'./chunk-YNBJGPIU.js';import'./chunk-YNSKDTFG.js';import'./chunk-VLFM66BZ.js';import'./chunk-NGNXOXI5.js';import'./chunk-O4RKZQYQ.js';import'./chunk-RLW6AQF2.js';if (typeof window === "undefined") { const { createRequire } = await import(/* @vite-ignore */ 'module'); createRequire(import.meta.url); }
2
2
  function r(e){return new Response(e.body,e)}var p={graphqlEnabled:false,trpcEnabled:false,wsEnabled:false,requireAuth:false};function n(){return new Response(JSON.stringify({error:"GraphQL is disabled"}),{status:503,headers:{"Content-Type":"application/json"}})}async function o(){try{return (await a.db.findOne({collection:"_globals_access-settings",where:{},draft:!0}))?.apiAccess?.graphqlEnabled??p.graphqlEnabled}catch{return true}}var d=async e=>{if(await b(e),!await o())return n();let s=await a.getGraphQL().fetch(e.request,e.locals);return r(s)},f=async e=>{if(await b(e),!await o())return n();let s=await a.getGraphQL().fetch(e.request,e.locals);return r(s)};export{f as GET,d as POST};
@@ -1 +1 @@
1
- 'use strict';var chunkPPGZHOYR_cjs=require('./chunk-PPGZHOYR.cjs');require('./chunk-MCK2QRAU.cjs'),require('./chunk-VPBGZW4P.cjs'),require('./chunk-N7CDHWQH.cjs'),require('./chunk-DCKJT247.cjs'),require('./chunk-7KTPBTH5.cjs'),require('./chunk-24W5I6SJ.cjs'),require('./chunk-O2SA56P2.cjs'),require('./chunk-H2IJDTA2.cjs'),require('./chunk-PW6Y5MQL.cjs'),require('./chunk-34LCWI5X.cjs'),require('./chunk-LXTVMP5F.cjs'),require('./chunk-2I2AXTKY.cjs'),require('./chunk-GS4CMYKS.cjs'),require('./chunk-OJBL4CXK.cjs'),require('./chunk-DCFOVCJX.cjs'),require('./chunk-FU76HURF.cjs'),require('./chunk-GWUHIIPO.cjs'),require('./chunk-EG4SRTYS.cjs'),require('./chunk-3A5UO6OQ.cjs'),require('./chunk-23RSKVJP.cjs'),require('./chunk-YOJOVQIH.cjs'),require('./chunk-XL64URKD.cjs'),require('./chunk-UE7DTBD7.cjs'),require('./chunk-O4PPZOVI.cjs'),require('./chunk-JJY2F6NL.cjs'),require('./chunk-OXEJCIOA.cjs'),require('./chunk-KOSR7235.cjs'),require('./chunk-JHFD3IAU.cjs');function r(){return new Response(JSON.stringify({error:"tRPC is disabled"}),{status:503,headers:{"Content-Type":"application/json"}})}var n={graphqlEnabled:false,trpcEnabled:false,wsEnabled:false,requireAuth:false};async function s(){try{return (await chunkPPGZHOYR_cjs.a.db.findOne({collection:"_globals_access-settings",where:{},draft:!0}))?.apiAccess?.trpcEnabled??n.trpcEnabled}catch{return true}}var l=async e=>(await chunkPPGZHOYR_cjs.b(e),await s()?chunkPPGZHOYR_cjs.a.getTRPC().fetch(e.request,e.locals):r());exports.ALL=l;
1
+ 'use strict';var chunk77ZGCYHZ_cjs=require('./chunk-77ZGCYHZ.cjs');require('./chunk-V7E74PHS.cjs'),require('./chunk-VPBGZW4P.cjs'),require('./chunk-N7CDHWQH.cjs'),require('./chunk-DCKJT247.cjs'),require('./chunk-7KTPBTH5.cjs'),require('./chunk-24W5I6SJ.cjs'),require('./chunk-O2SA56P2.cjs'),require('./chunk-H2IJDTA2.cjs'),require('./chunk-PW6Y5MQL.cjs'),require('./chunk-34LCWI5X.cjs'),require('./chunk-LXTVMP5F.cjs'),require('./chunk-2I2AXTKY.cjs'),require('./chunk-GS4CMYKS.cjs'),require('./chunk-OJBL4CXK.cjs'),require('./chunk-DCFOVCJX.cjs'),require('./chunk-FU76HURF.cjs'),require('./chunk-3BDAH6FD.cjs'),require('./chunk-EG4SRTYS.cjs'),require('./chunk-3A5UO6OQ.cjs'),require('./chunk-23RSKVJP.cjs'),require('./chunk-YOJOVQIH.cjs'),require('./chunk-XL64URKD.cjs'),require('./chunk-UE7DTBD7.cjs'),require('./chunk-O4PPZOVI.cjs'),require('./chunk-JJY2F6NL.cjs'),require('./chunk-OXEJCIOA.cjs'),require('./chunk-KOSR7235.cjs'),require('./chunk-JHFD3IAU.cjs');function r(){return new Response(JSON.stringify({error:"tRPC is disabled"}),{status:503,headers:{"Content-Type":"application/json"}})}var n={graphqlEnabled:false,trpcEnabled:false,wsEnabled:false,requireAuth:false};async function s(){try{return (await chunk77ZGCYHZ_cjs.a.db.findOne({collection:"_globals_access-settings",where:{},draft:!0}))?.apiAccess?.trpcEnabled??n.trpcEnabled}catch{return true}}var l=async e=>(await chunk77ZGCYHZ_cjs.b(e),await s()?chunk77ZGCYHZ_cjs.a.getTRPC().fetch(e.request,e.locals):r());exports.ALL=l;
@@ -1,2 +1,2 @@
1
- import {b,a}from'./chunk-TVWHTVLI.js';import'./chunk-SYE3OS5T.js';import'./chunk-KUY4QDAL.js';import'./chunk-LGUHXOEW.js';import'./chunk-ZMH35QYG.js';import'./chunk-GTAKGVUY.js';import'./chunk-5RBGM5N5.js';import'./chunk-3RIGRHON.js';import'./chunk-FAG2645P.js';import'./chunk-IIVBEZC2.js';import'./chunk-I22MSXGL.js';import'./chunk-SBFVITY2.js';import'./chunk-5I3BM5TV.js';import'./chunk-W5GDZG64.js';import'./chunk-OPKZYQV7.js';import'./chunk-3N34WXBS.js';import'./chunk-OXH6CANN.js';import'./chunk-TJ6N5ZPZ.js';import'./chunk-JXJTFBHG.js';import'./chunk-IIPSXKNV.js';import'./chunk-7EY3GXRA.js';import'./chunk-WLSVS3NC.js';import'./chunk-O6I26T6A.js';import'./chunk-YNBJGPIU.js';import'./chunk-YNSKDTFG.js';import'./chunk-VLFM66BZ.js';import'./chunk-NGNXOXI5.js';import'./chunk-O4RKZQYQ.js';import'./chunk-RLW6AQF2.js';if (typeof window === "undefined") { const { createRequire } = await import(/* @vite-ignore */ 'module'); createRequire(import.meta.url); }
1
+ import {b,a}from'./chunk-U7UUABFL.js';import'./chunk-LCTCEO34.js';import'./chunk-KUY4QDAL.js';import'./chunk-LGUHXOEW.js';import'./chunk-ZMH35QYG.js';import'./chunk-GTAKGVUY.js';import'./chunk-5RBGM5N5.js';import'./chunk-3RIGRHON.js';import'./chunk-FAG2645P.js';import'./chunk-IIVBEZC2.js';import'./chunk-I22MSXGL.js';import'./chunk-SBFVITY2.js';import'./chunk-5I3BM5TV.js';import'./chunk-W5GDZG64.js';import'./chunk-OPKZYQV7.js';import'./chunk-3N34WXBS.js';import'./chunk-OXH6CANN.js';import'./chunk-PYVZJIQ3.js';import'./chunk-JXJTFBHG.js';import'./chunk-IIPSXKNV.js';import'./chunk-7EY3GXRA.js';import'./chunk-WLSVS3NC.js';import'./chunk-O6I26T6A.js';import'./chunk-YNBJGPIU.js';import'./chunk-YNSKDTFG.js';import'./chunk-VLFM66BZ.js';import'./chunk-NGNXOXI5.js';import'./chunk-O4RKZQYQ.js';import'./chunk-RLW6AQF2.js';if (typeof window === "undefined") { const { createRequire } = await import(/* @vite-ignore */ 'module'); createRequire(import.meta.url); }
2
2
  function r(){return new Response(JSON.stringify({error:"tRPC is disabled"}),{status:503,headers:{"Content-Type":"application/json"}})}var n={graphqlEnabled:false,trpcEnabled:false,wsEnabled:false,requireAuth:false};async function s(){try{return (await a.db.findOne({collection:"_globals_access-settings",where:{},draft:!0}))?.apiAccess?.trpcEnabled??n.trpcEnabled}catch{return true}}var p=async e=>(await b(e),await s()?a.getTRPC().fetch(e.request,e.locals):r());export{p as ALL};
@@ -1 +1 @@
1
- 'use strict';var chunkPPGZHOYR_cjs=require('./chunk-PPGZHOYR.cjs');require('./chunk-MCK2QRAU.cjs'),require('./chunk-VPBGZW4P.cjs'),require('./chunk-N7CDHWQH.cjs'),require('./chunk-DCKJT247.cjs'),require('./chunk-7KTPBTH5.cjs'),require('./chunk-24W5I6SJ.cjs'),require('./chunk-O2SA56P2.cjs'),require('./chunk-H2IJDTA2.cjs'),require('./chunk-PW6Y5MQL.cjs'),require('./chunk-34LCWI5X.cjs'),require('./chunk-LXTVMP5F.cjs'),require('./chunk-2I2AXTKY.cjs'),require('./chunk-GS4CMYKS.cjs'),require('./chunk-OJBL4CXK.cjs'),require('./chunk-DCFOVCJX.cjs'),require('./chunk-FU76HURF.cjs'),require('./chunk-GWUHIIPO.cjs'),require('./chunk-EG4SRTYS.cjs'),require('./chunk-3A5UO6OQ.cjs'),require('./chunk-23RSKVJP.cjs'),require('./chunk-YOJOVQIH.cjs'),require('./chunk-XL64URKD.cjs'),require('./chunk-UE7DTBD7.cjs'),require('./chunk-O4PPZOVI.cjs'),require('./chunk-JJY2F6NL.cjs'),require('./chunk-OXEJCIOA.cjs'),require('./chunk-KOSR7235.cjs'),require('./chunk-JHFD3IAU.cjs');Object.defineProperty(exports,"ALL",{enumerable:true,get:function(){return chunkPPGZHOYR_cjs.c}});Object.defineProperty(exports,"createKyroHandler",{enumerable:true,get:function(){return chunkPPGZHOYR_cjs.d}});Object.defineProperty(exports,"kyroInstance",{enumerable:true,get:function(){return chunkPPGZHOYR_cjs.a}});Object.defineProperty(exports,"warmKyroInstance",{enumerable:true,get:function(){return chunkPPGZHOYR_cjs.b}});
1
+ 'use strict';var chunk77ZGCYHZ_cjs=require('./chunk-77ZGCYHZ.cjs');require('./chunk-V7E74PHS.cjs'),require('./chunk-VPBGZW4P.cjs'),require('./chunk-N7CDHWQH.cjs'),require('./chunk-DCKJT247.cjs'),require('./chunk-7KTPBTH5.cjs'),require('./chunk-24W5I6SJ.cjs'),require('./chunk-O2SA56P2.cjs'),require('./chunk-H2IJDTA2.cjs'),require('./chunk-PW6Y5MQL.cjs'),require('./chunk-34LCWI5X.cjs'),require('./chunk-LXTVMP5F.cjs'),require('./chunk-2I2AXTKY.cjs'),require('./chunk-GS4CMYKS.cjs'),require('./chunk-OJBL4CXK.cjs'),require('./chunk-DCFOVCJX.cjs'),require('./chunk-FU76HURF.cjs'),require('./chunk-3BDAH6FD.cjs'),require('./chunk-EG4SRTYS.cjs'),require('./chunk-3A5UO6OQ.cjs'),require('./chunk-23RSKVJP.cjs'),require('./chunk-YOJOVQIH.cjs'),require('./chunk-XL64URKD.cjs'),require('./chunk-UE7DTBD7.cjs'),require('./chunk-O4PPZOVI.cjs'),require('./chunk-JJY2F6NL.cjs'),require('./chunk-OXEJCIOA.cjs'),require('./chunk-KOSR7235.cjs'),require('./chunk-JHFD3IAU.cjs');Object.defineProperty(exports,"ALL",{enumerable:true,get:function(){return chunk77ZGCYHZ_cjs.c}});Object.defineProperty(exports,"createKyroHandler",{enumerable:true,get:function(){return chunk77ZGCYHZ_cjs.d}});Object.defineProperty(exports,"kyroInstance",{enumerable:true,get:function(){return chunk77ZGCYHZ_cjs.a}});Object.defineProperty(exports,"warmKyroInstance",{enumerable:true,get:function(){return chunk77ZGCYHZ_cjs.b}});
@@ -1 +1 @@
1
- export{c as ALL,d as createKyroHandler,a as kyroInstance,b as warmKyroInstance}from'./chunk-TVWHTVLI.js';import'./chunk-SYE3OS5T.js';import'./chunk-KUY4QDAL.js';import'./chunk-LGUHXOEW.js';import'./chunk-ZMH35QYG.js';import'./chunk-GTAKGVUY.js';import'./chunk-5RBGM5N5.js';import'./chunk-3RIGRHON.js';import'./chunk-FAG2645P.js';import'./chunk-IIVBEZC2.js';import'./chunk-I22MSXGL.js';import'./chunk-SBFVITY2.js';import'./chunk-5I3BM5TV.js';import'./chunk-W5GDZG64.js';import'./chunk-OPKZYQV7.js';import'./chunk-3N34WXBS.js';import'./chunk-OXH6CANN.js';import'./chunk-TJ6N5ZPZ.js';import'./chunk-JXJTFBHG.js';import'./chunk-IIPSXKNV.js';import'./chunk-7EY3GXRA.js';import'./chunk-WLSVS3NC.js';import'./chunk-O6I26T6A.js';import'./chunk-YNBJGPIU.js';import'./chunk-YNSKDTFG.js';import'./chunk-VLFM66BZ.js';import'./chunk-NGNXOXI5.js';import'./chunk-O4RKZQYQ.js';import'./chunk-RLW6AQF2.js';if (typeof window === "undefined") { const { createRequire } = await import(/* @vite-ignore */ 'module'); createRequire(import.meta.url); }
1
+ export{c as ALL,d as createKyroHandler,a as kyroInstance,b as warmKyroInstance}from'./chunk-U7UUABFL.js';import'./chunk-LCTCEO34.js';import'./chunk-KUY4QDAL.js';import'./chunk-LGUHXOEW.js';import'./chunk-ZMH35QYG.js';import'./chunk-GTAKGVUY.js';import'./chunk-5RBGM5N5.js';import'./chunk-3RIGRHON.js';import'./chunk-FAG2645P.js';import'./chunk-IIVBEZC2.js';import'./chunk-I22MSXGL.js';import'./chunk-SBFVITY2.js';import'./chunk-5I3BM5TV.js';import'./chunk-W5GDZG64.js';import'./chunk-OPKZYQV7.js';import'./chunk-3N34WXBS.js';import'./chunk-OXH6CANN.js';import'./chunk-PYVZJIQ3.js';import'./chunk-JXJTFBHG.js';import'./chunk-IIPSXKNV.js';import'./chunk-7EY3GXRA.js';import'./chunk-WLSVS3NC.js';import'./chunk-O6I26T6A.js';import'./chunk-YNBJGPIU.js';import'./chunk-YNSKDTFG.js';import'./chunk-VLFM66BZ.js';import'./chunk-NGNXOXI5.js';import'./chunk-O4RKZQYQ.js';import'./chunk-RLW6AQF2.js';if (typeof window === "undefined") { const { createRequire } = await import(/* @vite-ignore */ 'module'); createRequire(import.meta.url); }
@@ -1,4 +1,4 @@
1
- import { B as BaseAdapter, C as CollectionConfig, G as GlobalConfig, T as TenantContext, F as FindArgs, b as FindResult, c as FindByIDArgs, d as CreateArgs, U as UpdateArgs, D as DeleteArgs, e as FindOneArgs, f as FindVersionsArgs, V as VersionRecord, g as CreateVersionArgs } from './types-CKWnrUAh.js';
1
+ import { B as BaseAdapter, C as CollectionConfig, G as GlobalConfig, T as TenantContext, F as FindArgs, b as FindResult, c as FindByIDArgs, d as CreateArgs, U as UpdateArgs, D as DeleteArgs, e as FindOneArgs, f as FindVersionsArgs, V as VersionRecord, g as CreateVersionArgs } from './types-M2BhNVof.js';
2
2
  import { F as Field, u as RelationshipField, U as UploadField } from './types-C3QFX0l6.js';
3
3
 
4
4
  type AuditAction = "login" | "logout" | "login_failed" | "register" | "verify_email" | "password_change" | "password_reset" | "password_reset_request" | "role_change" | "permission_change" | "document_create" | "document_update" | "document_delete" | "settings_change" | "user_lockout" | "user_unlock" | "user_create" | "user_update" | "user_delete" | "api_request" | "api_key_create" | "api_key_update" | "api_key_rotate" | "api_key_delete" | "tenant_create" | "tenant_delete";
@@ -1,4 +1,4 @@
1
- import { B as BaseAdapter, C as CollectionConfig, G as GlobalConfig, T as TenantContext, F as FindArgs, b as FindResult, c as FindByIDArgs, d as CreateArgs, U as UpdateArgs, D as DeleteArgs, e as FindOneArgs, f as FindVersionsArgs, V as VersionRecord, g as CreateVersionArgs } from './types-CdwfDpyW.cjs';
1
+ import { B as BaseAdapter, C as CollectionConfig, G as GlobalConfig, T as TenantContext, F as FindArgs, b as FindResult, c as FindByIDArgs, d as CreateArgs, U as UpdateArgs, D as DeleteArgs, e as FindOneArgs, f as FindVersionsArgs, V as VersionRecord, g as CreateVersionArgs } from './types-BQnOYvym.cjs';
2
2
  import { F as Field, u as RelationshipField, U as UploadField } from './types-C3QFX0l6.cjs';
3
3
 
4
4
  type AuditAction = "login" | "logout" | "login_failed" | "register" | "verify_email" | "password_change" | "password_reset" | "password_reset_request" | "role_change" | "permission_change" | "document_create" | "document_update" | "document_delete" | "settings_change" | "user_lockout" | "user_unlock" | "user_create" | "user_update" | "user_delete" | "api_request" | "api_key_create" | "api_key_update" | "api_key_rotate" | "api_key_delete" | "tenant_create" | "tenant_delete";
@@ -1,5 +1,5 @@
1
- import {c,d as d$1}from'./chunk-WLSVS3NC.js';import {a,c as c$1,b,d}from'./chunk-YNSKDTFG.js';import {a as a$1}from'./chunk-NGNXOXI5.js';import {createRequire}from'module';import {randomBytes}from'crypto';if (typeof window === "undefined") { const { createRequire } = await import(/* @vite-ignore */ 'module'); createRequire(import.meta.url); }
2
- function w(T,t){let i=t,n=T[i.name];if(i.type==="json"||i.type==="richtext"||i.type==="array"||i.type==="group"||i.type==="blocks"||i.type==="list"||i.type==="relationship-block")try{n=n?JSON.parse(n):null;}catch{n=null;}if(i.type==="checkbox"&&(n=!!n),i.type==="date"&&n)try{let a=new Date(n);isNaN(a.getTime())?n=null:n=a.toISOString();}catch{n=null;}if((i.type==="upload"||i.type==="image")&&n)try{let a=JSON.parse(n);Array.isArray(a)?n=a.map(o=>typeof o=="object"&&o!==null?o:{id:o}):n=typeof a=="object"?a:{id:a};}catch{n=typeof n=="string"?{id:n}:n;}return n}var C;function U(){return C||(C=createRequire("file:///")("node:sqlite").DatabaseSync,C)}function R(T,t){try{return T.prepare(`PRAGMA table_info(${t})`).all().map(n=>n.name)}catch{return []}}var I=class extends a{db;path;migrations=new Map;versionsTableName="kyro_versions";constructor(t){super(),this.path=t.path,t.db?this.db=t.db:this.db=null;}async connect(){if(!this.db)this.db=new(U())(this.path||":memory:");else try{this.db.exec("SELECT 1");}catch{this.db=new(U())(this.path||":memory:");}if(this.db&&typeof this.db.prepare=="function"&&!this.db.prepare.__wrapped){let t=this.db.prepare.bind(this.db),i=n=>{let a=t(n),o=e=>typeof e=="boolean"?e?1:0:e===void 0?null:e;return new Proxy(a,{get(e,s,r){if(s==="all")return (...c)=>e.all(...c.map(o));if(s==="get")return (...c)=>e.get(...c.map(o));if(s==="run")return (...c)=>e.run(...c.map(o));let l=Reflect.get(e,s,r);return typeof l=="function"?l.bind(e):l}})};i.__wrapped=true,this.db.prepare=i;}this.db.exec("PRAGMA journal_mode = WAL"),this.db.exec("PRAGMA foreign_keys = ON"),this.connected=true;}async disconnect(){if(this.db){try{this.db.close();}catch{}this.db=null;}this.connected=false;}ensureTable(t,i){let n=i||this.getTableNameFor(t.slug),a=["id TEXT PRIMARY KEY"];for(let s of c(t.fields)){if(!s.name||s.name==="id")continue;let r=this.fieldToSQL(s);r&&a.push(r);}let o=c(t.fields);o.some(s=>s.name==="createdAt")||a.push(`${this.col("createdAt")} TEXT DEFAULT (datetime('now'))`),o.some(s=>s.name==="updatedAt")||a.push(`${this.col("updatedAt")} TEXT DEFAULT (datetime('now'))`),o.some(s=>s.name==="status")||a.push("status TEXT DEFAULT 'draft'"),o.some(s=>s.name==="hasDraft")||a.push("hasDraft INTEGER DEFAULT 0"),t.tenantScoped&&a.push("tenant_id TEXT NOT NULL");let e=R(this.db,n);if(e.length===0){let s=`CREATE TABLE IF NOT EXISTS ${n} (${a.join(", ")})`;this.db.exec(s),this.db.exec(`CREATE INDEX IF NOT EXISTS idx_${n}_status ON ${n}(status)`);for(let r of c(t.fields))r.name&&r.indexed&&this.db.exec(`CREATE INDEX IF NOT EXISTS idx_${n}_${r.name} ON ${n}(${this.col(r.name)})`),r.name&&r.unique&&this.db.exec(`CREATE UNIQUE INDEX IF NOT EXISTS idx_${n}_${r.name}_unique ON ${n}(${this.col(r.name)})`);}else {let s=new Set(e);for(let r of a){let l=r.split(" ")[0].replace(/^"/,"").replace(/"$/,"");if(!s.has(l)&&l!=="id")try{l==="status"?this.db.exec(`ALTER TABLE ${n} ADD COLUMN ${this.col(l)} TEXT DEFAULT 'published'`):l==="hasDraft"?this.db.exec(`ALTER TABLE ${n} ADD COLUMN ${this.col(l)} INTEGER DEFAULT 0`):this.db.exec(`ALTER TABLE ${n} ADD COLUMN ${this.col(l)} TEXT`);}catch{}}}this.migrations.set(n,true);}ensureVersionsTable(){this.db.exec(`
1
+ import {c,d as d$1}from'./chunk-WLSVS3NC.js';import {a,c as c$1,b,d}from'./chunk-YNSKDTFG.js';import {a as a$1}from'./chunk-NGNXOXI5.js';import {createRequire}from'module';import {randomBytes}from'crypto';import R from'fs';import I from'path';if (typeof window === "undefined") { const { createRequire } = await import(/* @vite-ignore */ 'module'); createRequire(import.meta.url); }
2
+ function j(T,t){let i=t,n=T[i.name];if(i.type==="json"||i.type==="richtext"||i.type==="array"||i.type==="group"||i.type==="blocks"||i.type==="list"||i.type==="relationship-block")try{n=n?JSON.parse(n):null;}catch{n=null;}if(i.type==="checkbox"&&(n=!!n),i.type==="date"&&n)try{let a=new Date(n);isNaN(a.getTime())?n=null:n=a.toISOString();}catch{n=null;}if((i.type==="upload"||i.type==="image")&&n)try{let a=JSON.parse(n);Array.isArray(a)?n=a.map(o=>typeof o=="object"&&o!==null?o:{id:o}):n=typeof a=="object"?a:{id:a};}catch{n=typeof n=="string"?{id:n}:n;}return n}var C;function M(){return C||(C=createRequire("file:///")("node:sqlite").DatabaseSync,C)}function L(T,t){try{return T.prepare(`PRAGMA table_info(${t})`).all().map(n=>n.name)}catch{return []}}var O=class extends a{db;path;migrations=new Map;versionsTableName="kyro_versions";constructor(t){super(),this.path=t.path,t.db?this.db=t.db:this.db=null;}async connect(){let t=this.path||":memory:";if(t!==":memory:")try{!R.existsSync(t)&&R.existsSync(I.resolve("..",t))&&(t=I.resolve("..",t));let i=I.dirname(I.resolve(t));R.existsSync(i)||R.mkdirSync(i,{recursive:!0}),this.path=t;}catch{}if(!this.db)this.db=new(M())(t);else try{this.db.exec("SELECT 1");}catch{this.db=new(M())(t);}if(this.db&&typeof this.db.prepare=="function"&&!this.db.prepare.__wrapped){let i=this.db.prepare.bind(this.db),n=a=>{let o=i(a),e=s=>typeof s=="boolean"?s?1:0:s===void 0?null:s;return new Proxy(o,{get(s,r,l){if(r==="all")return (...d)=>s.all(...d.map(e));if(r==="get")return (...d)=>s.get(...d.map(e));if(r==="run")return (...d)=>s.run(...d.map(e));let c=Reflect.get(s,r,l);return typeof c=="function"?c.bind(s):c}})};n.__wrapped=true,this.db.prepare=n;}this.db.exec("PRAGMA journal_mode = WAL"),this.db.exec("PRAGMA foreign_keys = ON"),this.connected=true;}async disconnect(){if(this.db){try{this.db.close();}catch{}this.db=null;}this.connected=false;}ensureTable(t,i){let n=i||this.getTableNameFor(t.slug),a=["id TEXT PRIMARY KEY"];for(let s of c(t.fields)){if(!s.name||s.name==="id")continue;let r=this.fieldToSQL(s);r&&a.push(r);}let o=c(t.fields);o.some(s=>s.name==="createdAt")||a.push(`${this.col("createdAt")} TEXT DEFAULT (datetime('now'))`),o.some(s=>s.name==="updatedAt")||a.push(`${this.col("updatedAt")} TEXT DEFAULT (datetime('now'))`),o.some(s=>s.name==="status")||a.push("status TEXT DEFAULT 'draft'"),o.some(s=>s.name==="hasDraft")||a.push("hasDraft INTEGER DEFAULT 0"),t.tenantScoped&&a.push("tenant_id TEXT NOT NULL");let e=L(this.db,n);if(e.length===0){let s=`CREATE TABLE IF NOT EXISTS ${n} (${a.join(", ")})`;this.db.exec(s),this.db.exec(`CREATE INDEX IF NOT EXISTS idx_${n}_status ON ${n}(status)`);for(let r of c(t.fields))r.name&&r.indexed&&this.db.exec(`CREATE INDEX IF NOT EXISTS idx_${n}_${r.name} ON ${n}(${this.col(r.name)})`),r.name&&r.unique&&this.db.exec(`CREATE UNIQUE INDEX IF NOT EXISTS idx_${n}_${r.name}_unique ON ${n}(${this.col(r.name)})`);}else {let s=new Set(e);for(let r of a){let l=r.split(" ")[0].replace(/^"/,"").replace(/"$/,"");if(!s.has(l)&&l!=="id")try{l==="status"?this.db.exec(`ALTER TABLE ${n} ADD COLUMN ${this.col(l)} TEXT DEFAULT 'published'`):l==="hasDraft"?this.db.exec(`ALTER TABLE ${n} ADD COLUMN ${this.col(l)} INTEGER DEFAULT 0`):this.db.exec(`ALTER TABLE ${n} ADD COLUMN ${this.col(l)} TEXT`);}catch{}}}this.migrations.set(n,true);}ensureVersionsTable(){this.db.exec(`
3
3
  CREATE TABLE IF NOT EXISTS ${this.versionsTableName} (
4
4
  id TEXT PRIMARY KEY,
5
5
  collection_slug TEXT NOT NULL,
@@ -15,6 +15,6 @@ function w(T,t){let i=t,n=T[i.name];if(i.type==="json"||i.type==="richtext"||i.t
15
15
  created_at TEXT DEFAULT (datetime('now')),
16
16
  updated_at TEXT DEFAULT (datetime('now'))
17
17
  )
18
- `);try{this.db.exec(`ALTER TABLE ${this.versionsTableName} ADD COLUMN autosave INTEGER NOT NULL DEFAULT 0`);}catch{}this.db.exec(`CREATE INDEX IF NOT EXISTS idx_${this.versionsTableName}_doc ON ${this.versionsTableName}(collection_slug, document_id)`),this.db.exec(`CREATE INDEX IF NOT EXISTS idx_${this.versionsTableName}_status ON ${this.versionsTableName}(status)`),this.db.exec(`CREATE INDEX IF NOT EXISTS idx_${this.versionsTableName}_autosave ON ${this.versionsTableName}(autosave)`);}resolveCol(t,i){let n=i.replace(/^-/,""),a=R(this.db,t);if(!a.includes(n)){if(n==="created_at"&&a.includes("createdAt"))return '"createdAt"';if(n==="createdAt"&&a.includes("created_at"))return '"created_at"';if(n==="updated_at"&&a.includes("updatedAt"))return '"updatedAt"';if(n==="updatedAt"&&a.includes("updated_at"))return '"updated_at"'}return this.col(n)}col(t){return `"${t}"`}fieldToSQL(t){switch(t.type){case "text":case "email":case "password":case "textarea":case "color":case "icon":case "code":case "markdown":case "url":return this.col(t.name)+" TEXT";case "number":return this.col(t.name)+" REAL";case "checkbox":return this.col(t.name)+" INTEGER DEFAULT 0";case "date":return this.col(t.name)+" TEXT";case "select":case "radio":return this.col(t.name)+" TEXT";case "relationship":case "upload":case "image":return this.col(t.name)+" TEXT";case "json":case "richtext":case "array":case "group":case "blocks":return this.col(t.name)+" TEXT";default:return null}}parseGlobalsSlug(t){if(t.startsWith("_globals_")){let i=t.replace("_globals_","");return {isGlobal:true,globalSlug:i,tableName:`global_${i.replace(/-/g,"_")}`}}return {isGlobal:false,globalSlug:"",tableName:this.getTableNameFor(t)}}buildWhere(t,i){let n=[],a=[];for(let[o,e]of Object.entries(t)){let s=o.toUpperCase();if((s==="AND"||s==="OR")&&Array.isArray(e)){let l=[];for(let c of e)if(typeof c=="object"&&c!==null){let d=this.buildWhere(c,i);d.clause&&(l.push(`(${d.clause})`),a.push(...d.params));}l.length>0&&n.push(`(${l.join(` ${s} `)})`);continue}let r=this.resolveCol(i,o);typeof e=="object"&&e!==null&&!Array.isArray(e)?(e.equals!==void 0&&(n.push(`${r} = ?`),a.push(e.equals)),e.not_equals!==void 0&&(n.push(`${r} != ?`),a.push(e.not_equals)),e.in!==void 0&&Array.isArray(e.in)&&(e.in.length===0?n.push("1 = 0"):(n.push(`${r} IN (${e.in.map(()=>"?").join(", ")})`),a.push(...e.in))),e.contains!==void 0&&(n.push(`LOWER(${r}) LIKE LOWER(?)`),a.push(`%${e.contains}%`)),e.like!==void 0&&(n.push(`LOWER(${r}) LIKE LOWER(?)`),a.push(e.like)),e.greater_than!==void 0&&(n.push(`${r} > ?`),a.push(e.greater_than)),e.greater_than_equal!==void 0&&(n.push(`${r} >= ?`),a.push(e.greater_than_equal)),e.less_than!==void 0&&(n.push(`${r} < ?`),a.push(e.less_than)),e.less_than_equal!==void 0&&(n.push(`${r} <= ?`),a.push(e.less_than_equal))):e!==void 0&&(n.push(`${r} = ?`),a.push(e));}return {clause:n.join(" AND "),params:a}}async find(t){let{collection:i,where:n={},sort:a,limit:o=10,page:e=1,tenantId:s,select:r,draft:l=false}=t,c=this.parseGlobalsSlug(i),d$1=c.isGlobal?this.globals.get(c.globalSlug):this.getCollection(i);this.ensureTable(d$1,c.tableName);let m=c.tableName,h=`SELECT * FROM ${m}`,f=[],u=[],y={...n};this.tenantContext&&d$1.tenantScoped&&(y=c$1({where:y},i,this.tenantContext,b).where||{});let b$1=d$1.fields.find(p=>p.name==="status"),g=b$1?.type==="select"&&Array.isArray(b$1.options)&&b$1.options.some(p=>p.value==="published");if(!l&&g&&(u.push("status = ?"),f.push("published")),s&&d$1.tenantScoped&&(u.push("tenant_id = ?"),f.push(s)),y&&Object.keys(y).length>0){let p=this.buildWhere(y,m);p.clause&&(u.push(`(${p.clause})`),f.push(...p.params));}u.length>0&&(h+=` WHERE ${u.join(" AND ")}`);let O=a||"-createdAt",j=this.resolveCol(m,O),M=O.startsWith("-")?"DESC":"ASC";h+=` ORDER BY ${j} ${M}`;let V=h.replace("SELECT *","SELECT COUNT(*) as count"),A=this.db.prepare(V).get(...f)?.count||0;h+=" LIMIT ? OFFSET ?",f.push(o,(e-1)*o);let E=this.db.prepare(h).all(...f).map(p=>this.rowToDoc(p,d$1));return this.tenantContext&&!this.tenantContext.isSuperAdmin&&(E=E.filter(p=>d(p,i,this.tenantContext,b))),l&&(E=await Promise.all(E.map(async p=>{let S=this.db.prepare(`SELECT * FROM ${this.versionsTableName} WHERE collection_slug = ? AND document_id = ? AND tenant_id IS NULL ORDER BY version DESC LIMIT 1`).get(i,p.id);if(S){let X=S.data?JSON.parse(S.data):{};return a$1({...p,...X,status:p.status,_hasUnpublishedChanges:S.status==="draft"})}return p}))),E=E.map(p=>a$1(p)),{docs:E,totalDocs:A,limit:o,totalPages:Math.ceil(A/o),page:e,pagingCounter:(e-1)*o+1,hasPrevPage:e>1,hasNextPage:e<Math.ceil(A/o),prevPage:e>1?e-1:null,nextPage:e<Math.ceil(A/o)?e+1:null}}async findByID(t){let{collection:i,id:n,tenantId:a,draft:o=false}=t,e=this.parseGlobalsSlug(i),s=e.isGlobal?this.globals.get(e.globalSlug):this.getCollection(i);this.ensureTable(s,e.tableName);let l=`SELECT * FROM ${e.tableName} WHERE id = ?`,c=[n];if(this.tenantContext&&s.tenantScoped){let u={id:n,tenant_id:this.tenantContext.tenantId};if(!d(u,i,this.tenantContext,b))return null}let d$1=s.fields.find(u=>u.name==="status"),m=d$1?.type==="select"&&Array.isArray(d$1.options)&&d$1.options.some(u=>u.value==="published");!o&&m&&(l+=" AND status = ?",c.push("published")),a&&s.tenantScoped&&(l+=" AND tenant_id = ?",c.push(a));let h=this.db.prepare(l).get(...c);if(!h)return null;let f=this.rowToDoc(h,s);if(o){let u=this.db.prepare(`SELECT * FROM ${this.versionsTableName} WHERE collection_slug = ? AND document_id = ? AND tenant_id IS NULL ORDER BY version DESC LIMIT 1`).get(i,f.id);if(u){let y=u.data?JSON.parse(u.data):{};f={...f,...y,status:f.status,_hasUnpublishedChanges:u.status==="draft"};}}return a$1(f)}async create(t){let{collection:i,data:n,tenantId:a}=t,o=this.parseGlobalsSlug(i),e=o.isGlobal?this.globals.get(o.globalSlug):this.getCollection(i);this.ensureTable(e,o.tableName);let s=o.tableName,r=o.isGlobal?o.globalSlug:n.id||this.generateId(),l=this.prepareData(n,e);l.id=r;let c=new Date().toISOString();l.created_at=c,l.updated_at=c,a&&e.tenantScoped&&(l.tenant_id=a);let d=Object.keys(l),m=R(this.db,s),h={};for(let g of d)m.includes(g)&&(h[g]=l[g]);let f=Object.keys(h),u=f.map(g=>this.col(g)),y=f.map(()=>"?").join(", "),b=Object.values(h).map(g=>g!==null&&typeof g=="object"?JSON.stringify(g):g);return this.db.prepare(`INSERT OR REPLACE INTO ${s} (${u.join(", ")}) VALUES (${y})`).run(...b),this.ensureVersionsTable(),this.findByID({collection:i,id:r,tenantId:a,draft:true})}async update(t){let{collection:i,id:n,data:a,tenantId:o}=t,e=this.parseGlobalsSlug(i),s=e.isGlobal?this.globals.get(e.globalSlug):this.getCollection(i);this.ensureTable(s,e.tableName);let r=e.tableName,l=this.prepareData(a,s);l.updated_at=new Date().toISOString();let c=R(this.db,r),d={};for(let b of Object.keys(l))c.includes(b)&&(d[b]=l[b]);let h=Object.keys(d).map(b=>`${this.col(b)} = ?`).join(", "),f=Object.values(d).map(b=>b!==null&&typeof b=="object"?JSON.stringify(b):b),u=`UPDATE ${r} SET ${h} WHERE id = ?`,y=[...f,n];return o&&s.tenantScoped&&(u+=" AND tenant_id = ?",y.push(o)),this.db.prepare(u).run(...y),this.ensureVersionsTable(),this.findByID({collection:i,id:n,tenantId:o,draft:true})}async delete(t){let{collection:i,id:n,tenantId:a}=t,o=this.parseGlobalsSlug(i),e=o.isGlobal?this.globals.get(o.globalSlug):this.getCollection(i);this.ensureTable(e,o.tableName),this.ensureVersionsTable();let s=await this.findByID({collection:i,id:n,tenantId:a,draft:true});if(!s)throw new Error(`Document not found: ${i}/${n}`);let l=`DELETE FROM ${o.tableName} WHERE id = ?`,c=[n];return a&&e.tenantScoped&&(l+=" AND tenant_id = ?",c.push(a)),this.db.prepare(l).run(...c),s}async count(t){let{collection:i,tenantId:n}=t,a=this.parseGlobalsSlug(i),o=a.isGlobal?this.globals.get(a.globalSlug):this.getCollection(i);this.ensureTable(o,a.tableName);let e=a.tableName,s=`SELECT COUNT(*) as count FROM ${e}`,r=[],l=[];if(n&&o.tenantScoped&&(r.push("tenant_id = ?"),l.push(n)),t.where&&Object.keys(t.where).length>0){let d=this.buildWhere(t.where,e);d.clause&&(r.push(`(${d.clause})`),l.push(...d.params));}return r.length>0&&(s+=` WHERE ${r.join(" AND ")}`),this.db.prepare(s).get(...l)?.count||0}async findOne(t){let i=this.parseGlobalsSlug(t.collection);if(i.isGlobal){let a=this.globals.get(i.globalSlug);if(!a)throw new Error(`Global "${i.globalSlug}" not found in adapter`);this.ensureTable(a,i.tableName);let o=`SELECT * FROM ${i.tableName}`,e=[],s=[],r=a.fields.find(d=>d.name==="status"),l=r?.type==="select"&&Array.isArray(r.options)&&r.options.some(d=>d.value==="published");!t.draft&&a.versions&&l&&e.push("status = 'published'"),e.length>0&&(o+=` WHERE ${e.join(" AND ")}`),o+=" LIMIT 1";let c=this.db.prepare(o).get(...s);if(c){let d=this.rowToDoc(c,a);if(t.draft){let m=this.db.prepare(`SELECT * FROM ${this.versionsTableName} WHERE collection_slug = ? AND document_id = ? AND tenant_id IS NULL ORDER BY version DESC LIMIT 1`).get(t.collection,i.globalSlug);if(m){let h=m.data?JSON.parse(m.data):{};d={...d,...h,status:d.status,_hasUnpublishedChanges:m.status==="draft"};}}return d}return null}return (await this.find({...t,limit:1})).docs[0]||null}async findVersions(t){this.ensureVersionsTable();let{collection:i,documentId:n,tenantId:a,limit:o=20,page:e=1}=t,s=["collection_slug = ?","document_id = ?","autosave = 0"],r=[i,n];a?(s.push("tenant_id = ?"),r.push(a)):s.push("tenant_id IS NULL");let l=`WHERE ${s.join(" AND ")}`,d=this.db.prepare(`SELECT COUNT(*) as count FROM ${this.versionsTableName} ${l}`).get(...r)?.count||0,m=(e-1)*o;return {docs:this.db.prepare(`SELECT * FROM ${this.versionsTableName} ${l} ORDER BY version DESC LIMIT ? OFFSET ?`).all(...r,o,m).map(u=>this.rowToVersion(u)),totalDocs:d,limit:o,totalPages:Math.ceil(d/o),page:e,pagingCounter:(e-1)*o+1,hasPrevPage:e>1,hasNextPage:e<Math.ceil(d/o),prevPage:e>1?e-1:null,nextPage:e<Math.ceil(d/o)?e+1:null}}async findVersionByID(t){this.ensureVersionsTable();let i=this.db.prepare(`SELECT * FROM ${this.versionsTableName} WHERE id = ? AND collection_slug = ? LIMIT 1`).get(t.versionId,t.collection);return i?this.rowToVersion(i):null}async createVersion(t){this.ensureVersionsTable();let i=new Date().toISOString();if(t.autosave){let s=`SELECT * FROM ${this.versionsTableName} WHERE collection_slug = ? AND document_id = ? AND autosave = 1`,r=[t.collection,t.documentId];t.tenantId?(s+=" AND tenant_id = ?",r.push(t.tenantId)):s+=" AND tenant_id IS NULL",s+=" LIMIT 1";let l=this.db.prepare(s).get(...r);if(l){this.db.prepare(`UPDATE ${this.versionsTableName} SET data = ?, status = ?, updated_at = ? WHERE id = ?`).run(JSON.stringify(t.data),t.status,i,l.id);let c=await this.findVersionByID({collection:t.collection,versionId:l.id});if(c)return c}}let n=this.generateId(),o=(this.db.prepare(`SELECT version FROM ${this.versionsTableName} WHERE collection_slug = ? AND document_id = ? AND autosave = 0 ORDER BY version DESC LIMIT 1`).get(t.collection,t.documentId)?.version??0)+1;if(this.db.prepare(`INSERT INTO ${this.versionsTableName} (
18
+ `);try{this.db.exec(`ALTER TABLE ${this.versionsTableName} ADD COLUMN autosave INTEGER NOT NULL DEFAULT 0`);}catch{}this.db.exec(`CREATE INDEX IF NOT EXISTS idx_${this.versionsTableName}_doc ON ${this.versionsTableName}(collection_slug, document_id)`),this.db.exec(`CREATE INDEX IF NOT EXISTS idx_${this.versionsTableName}_status ON ${this.versionsTableName}(status)`),this.db.exec(`CREATE INDEX IF NOT EXISTS idx_${this.versionsTableName}_autosave ON ${this.versionsTableName}(autosave)`);}resolveCol(t,i){let n=i.replace(/^-/,""),a=L(this.db,t);if(!a.includes(n)){if(n==="created_at"&&a.includes("createdAt"))return '"createdAt"';if(n==="createdAt"&&a.includes("created_at"))return '"created_at"';if(n==="updated_at"&&a.includes("updatedAt"))return '"updatedAt"';if(n==="updatedAt"&&a.includes("updated_at"))return '"updated_at"'}return this.col(n)}col(t){return `"${t}"`}fieldToSQL(t){switch(t.type){case "text":case "email":case "password":case "textarea":case "color":case "icon":case "code":case "markdown":case "url":return this.col(t.name)+" TEXT";case "number":return this.col(t.name)+" REAL";case "checkbox":return this.col(t.name)+" INTEGER DEFAULT 0";case "date":return this.col(t.name)+" TEXT";case "select":case "radio":return this.col(t.name)+" TEXT";case "relationship":case "upload":case "image":return this.col(t.name)+" TEXT";case "json":case "richtext":case "array":case "group":case "blocks":return this.col(t.name)+" TEXT";default:return null}}parseGlobalsSlug(t){if(t.startsWith("_globals_")){let i=t.replace("_globals_","");return {isGlobal:true,globalSlug:i,tableName:`global_${i.replace(/-/g,"_")}`}}return {isGlobal:false,globalSlug:"",tableName:this.getTableNameFor(t)}}buildWhere(t,i){let n=[],a=[];for(let[o,e]of Object.entries(t)){let s=o.toUpperCase();if((s==="AND"||s==="OR")&&Array.isArray(e)){let l=[];for(let c of e)if(typeof c=="object"&&c!==null){let d=this.buildWhere(c,i);d.clause&&(l.push(`(${d.clause})`),a.push(...d.params));}l.length>0&&n.push(`(${l.join(` ${s} `)})`);continue}let r=this.resolveCol(i,o);typeof e=="object"&&e!==null&&!Array.isArray(e)?(e.equals!==void 0&&(n.push(`${r} = ?`),a.push(e.equals)),e.not_equals!==void 0&&(n.push(`${r} != ?`),a.push(e.not_equals)),e.in!==void 0&&Array.isArray(e.in)&&(e.in.length===0?n.push("1 = 0"):(n.push(`${r} IN (${e.in.map(()=>"?").join(", ")})`),a.push(...e.in))),e.contains!==void 0&&(n.push(`LOWER(${r}) LIKE LOWER(?)`),a.push(`%${e.contains}%`)),e.like!==void 0&&(n.push(`LOWER(${r}) LIKE LOWER(?)`),a.push(e.like)),e.greater_than!==void 0&&(n.push(`${r} > ?`),a.push(e.greater_than)),e.greater_than_equal!==void 0&&(n.push(`${r} >= ?`),a.push(e.greater_than_equal)),e.less_than!==void 0&&(n.push(`${r} < ?`),a.push(e.less_than)),e.less_than_equal!==void 0&&(n.push(`${r} <= ?`),a.push(e.less_than_equal))):e!==void 0&&(n.push(`${r} = ?`),a.push(e));}return {clause:n.join(" AND "),params:a}}async find(t){let{collection:i,where:n={},sort:a,limit:o=10,page:e=1,tenantId:s,select:r,draft:l=false}=t,c=this.parseGlobalsSlug(i),d$1=c.isGlobal?this.globals.get(c.globalSlug):this.getCollection(i);this.ensureTable(d$1,c.tableName);let m=c.tableName,h=`SELECT * FROM ${m}`,f=[],u=[],y={...n};this.tenantContext&&d$1.tenantScoped&&(y=c$1({where:y},i,this.tenantContext,b).where||{});let b$1=d$1.fields.find(p=>p.name==="status"),g=b$1?.type==="select"&&Array.isArray(b$1.options)&&b$1.options.some(p=>p.value==="published");if(!l&&g&&(u.push("status = ?"),f.push("published")),s&&d$1.tenantScoped&&(u.push("tenant_id = ?"),f.push(s)),y&&Object.keys(y).length>0){let p=this.buildWhere(y,m);p.clause&&(u.push(`(${p.clause})`),f.push(...p.params));}u.length>0&&(h+=` WHERE ${u.join(" AND ")}`);let F=a||"-createdAt",V=this.resolveCol(m,F),X=F.startsWith("-")?"DESC":"ASC";h+=` ORDER BY ${V} ${X}`;let k=h.replace("SELECT *","SELECT COUNT(*) as count"),A=this.db.prepare(k).get(...f)?.count||0;h+=" LIMIT ? OFFSET ?",f.push(o,(e-1)*o);let E=this.db.prepare(h).all(...f).map(p=>this.rowToDoc(p,d$1));return this.tenantContext&&!this.tenantContext.isSuperAdmin&&(E=E.filter(p=>d(p,i,this.tenantContext,b))),l&&(E=await Promise.all(E.map(async p=>{let S=this.db.prepare(`SELECT * FROM ${this.versionsTableName} WHERE collection_slug = ? AND document_id = ? AND tenant_id IS NULL ORDER BY version DESC LIMIT 1`).get(i,p.id);if(S){let G=S.data?JSON.parse(S.data):{};return a$1({...p,...G,status:p.status,_hasUnpublishedChanges:S.status==="draft"})}return p}))),E=E.map(p=>a$1(p)),{docs:E,totalDocs:A,limit:o,totalPages:Math.ceil(A/o),page:e,pagingCounter:(e-1)*o+1,hasPrevPage:e>1,hasNextPage:e<Math.ceil(A/o),prevPage:e>1?e-1:null,nextPage:e<Math.ceil(A/o)?e+1:null}}async findByID(t){let{collection:i,id:n,tenantId:a,draft:o=false}=t,e=this.parseGlobalsSlug(i),s=e.isGlobal?this.globals.get(e.globalSlug):this.getCollection(i);this.ensureTable(s,e.tableName);let l=`SELECT * FROM ${e.tableName} WHERE id = ?`,c=[n];if(this.tenantContext&&s.tenantScoped){let u={id:n,tenant_id:this.tenantContext.tenantId};if(!d(u,i,this.tenantContext,b))return null}let d$1=s.fields.find(u=>u.name==="status"),m=d$1?.type==="select"&&Array.isArray(d$1.options)&&d$1.options.some(u=>u.value==="published");!o&&m&&(l+=" AND status = ?",c.push("published")),a&&s.tenantScoped&&(l+=" AND tenant_id = ?",c.push(a));let h=this.db.prepare(l).get(...c);if(!h)return null;let f=this.rowToDoc(h,s);if(o){let u=this.db.prepare(`SELECT * FROM ${this.versionsTableName} WHERE collection_slug = ? AND document_id = ? AND tenant_id IS NULL ORDER BY version DESC LIMIT 1`).get(i,f.id);if(u){let y=u.data?JSON.parse(u.data):{};f={...f,...y,status:f.status,_hasUnpublishedChanges:u.status==="draft"};}}return a$1(f)}async create(t){let{collection:i,data:n,tenantId:a}=t,o=this.parseGlobalsSlug(i),e=o.isGlobal?this.globals.get(o.globalSlug):this.getCollection(i);this.ensureTable(e,o.tableName);let s=o.tableName,r=o.isGlobal?o.globalSlug:n.id||this.generateId(),l=this.prepareData(n,e);l.id=r;let c=new Date().toISOString();l.created_at=c,l.updated_at=c,a&&e.tenantScoped&&(l.tenant_id=a);let d=Object.keys(l),m=L(this.db,s),h={};for(let g of d)m.includes(g)&&(h[g]=l[g]);let f=Object.keys(h),u=f.map(g=>this.col(g)),y=f.map(()=>"?").join(", "),b=Object.values(h).map(g=>g!==null&&typeof g=="object"?JSON.stringify(g):g);return this.db.prepare(`INSERT OR REPLACE INTO ${s} (${u.join(", ")}) VALUES (${y})`).run(...b),this.ensureVersionsTable(),this.findByID({collection:i,id:r,tenantId:a,draft:true})}async update(t){let{collection:i,id:n,data:a,tenantId:o}=t,e=this.parseGlobalsSlug(i),s=e.isGlobal?this.globals.get(e.globalSlug):this.getCollection(i);this.ensureTable(s,e.tableName);let r=e.tableName,l=this.prepareData(a,s);l.updated_at=new Date().toISOString();let c=L(this.db,r),d={};for(let b of Object.keys(l))c.includes(b)&&(d[b]=l[b]);let h=Object.keys(d).map(b=>`${this.col(b)} = ?`).join(", "),f=Object.values(d).map(b=>b!==null&&typeof b=="object"?JSON.stringify(b):b),u=`UPDATE ${r} SET ${h} WHERE id = ?`,y=[...f,n];return o&&s.tenantScoped&&(u+=" AND tenant_id = ?",y.push(o)),this.db.prepare(u).run(...y),this.ensureVersionsTable(),this.findByID({collection:i,id:n,tenantId:o,draft:true})}async delete(t){let{collection:i,id:n,tenantId:a}=t,o=this.parseGlobalsSlug(i),e=o.isGlobal?this.globals.get(o.globalSlug):this.getCollection(i);this.ensureTable(e,o.tableName),this.ensureVersionsTable();let s=await this.findByID({collection:i,id:n,tenantId:a,draft:true});if(!s)throw new Error(`Document not found: ${i}/${n}`);let l=`DELETE FROM ${o.tableName} WHERE id = ?`,c=[n];return a&&e.tenantScoped&&(l+=" AND tenant_id = ?",c.push(a)),this.db.prepare(l).run(...c),s}async count(t){let{collection:i,tenantId:n}=t,a=this.parseGlobalsSlug(i),o=a.isGlobal?this.globals.get(a.globalSlug):this.getCollection(i);this.ensureTable(o,a.tableName);let e=a.tableName,s=`SELECT COUNT(*) as count FROM ${e}`,r=[],l=[];if(n&&o.tenantScoped&&(r.push("tenant_id = ?"),l.push(n)),t.where&&Object.keys(t.where).length>0){let d=this.buildWhere(t.where,e);d.clause&&(r.push(`(${d.clause})`),l.push(...d.params));}return r.length>0&&(s+=` WHERE ${r.join(" AND ")}`),this.db.prepare(s).get(...l)?.count||0}async findOne(t){let i=this.parseGlobalsSlug(t.collection);if(i.isGlobal){let a=this.globals.get(i.globalSlug);if(!a)throw new Error(`Global "${i.globalSlug}" not found in adapter`);this.ensureTable(a,i.tableName);let o=`SELECT * FROM ${i.tableName}`,e=[],s=[],r=a.fields.find(d=>d.name==="status"),l=r?.type==="select"&&Array.isArray(r.options)&&r.options.some(d=>d.value==="published");!t.draft&&a.versions&&l&&e.push("status = 'published'"),e.length>0&&(o+=` WHERE ${e.join(" AND ")}`),o+=" LIMIT 1";let c=this.db.prepare(o).get(...s);if(c){let d=this.rowToDoc(c,a);if(t.draft){let m=this.db.prepare(`SELECT * FROM ${this.versionsTableName} WHERE collection_slug = ? AND document_id = ? AND tenant_id IS NULL ORDER BY version DESC LIMIT 1`).get(t.collection,i.globalSlug);if(m){let h=m.data?JSON.parse(m.data):{};d={...d,...h,status:d.status,_hasUnpublishedChanges:m.status==="draft"};}}return d}return null}return (await this.find({...t,limit:1})).docs[0]||null}async findVersions(t){this.ensureVersionsTable();let{collection:i,documentId:n,tenantId:a,limit:o=20,page:e=1}=t,s=["collection_slug = ?","document_id = ?","autosave = 0"],r=[i,n];a?(s.push("tenant_id = ?"),r.push(a)):s.push("tenant_id IS NULL");let l=`WHERE ${s.join(" AND ")}`,d=this.db.prepare(`SELECT COUNT(*) as count FROM ${this.versionsTableName} ${l}`).get(...r)?.count||0,m=(e-1)*o;return {docs:this.db.prepare(`SELECT * FROM ${this.versionsTableName} ${l} ORDER BY version DESC LIMIT ? OFFSET ?`).all(...r,o,m).map(u=>this.rowToVersion(u)),totalDocs:d,limit:o,totalPages:Math.ceil(d/o),page:e,pagingCounter:(e-1)*o+1,hasPrevPage:e>1,hasNextPage:e<Math.ceil(d/o),prevPage:e>1?e-1:null,nextPage:e<Math.ceil(d/o)?e+1:null}}async findVersionByID(t){this.ensureVersionsTable();let i=this.db.prepare(`SELECT * FROM ${this.versionsTableName} WHERE id = ? AND collection_slug = ? LIMIT 1`).get(t.versionId,t.collection);return i?this.rowToVersion(i):null}async createVersion(t){this.ensureVersionsTable();let i=new Date().toISOString();if(t.autosave){let s=`SELECT * FROM ${this.versionsTableName} WHERE collection_slug = ? AND document_id = ? AND autosave = 1`,r=[t.collection,t.documentId];t.tenantId?(s+=" AND tenant_id = ?",r.push(t.tenantId)):s+=" AND tenant_id IS NULL",s+=" LIMIT 1";let l=this.db.prepare(s).get(...r);if(l){this.db.prepare(`UPDATE ${this.versionsTableName} SET data = ?, status = ?, updated_at = ? WHERE id = ?`).run(JSON.stringify(t.data),t.status,i,l.id);let c=await this.findVersionByID({collection:t.collection,versionId:l.id});if(c)return c}}let n=this.generateId(),o=(this.db.prepare(`SELECT version FROM ${this.versionsTableName} WHERE collection_slug = ? AND document_id = ? AND autosave = 0 ORDER BY version DESC LIMIT 1`).get(t.collection,t.documentId)?.version??0)+1;if(this.db.prepare(`INSERT INTO ${this.versionsTableName} (
19
19
  id, collection_slug, document_id, tenant_id, version, status, autosave, data, created_by, change_description, published_at, created_at, updated_at
20
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(n,t.collection,t.documentId,t.tenantId??null,o,t.status,t.autosave?1:0,JSON.stringify(t.data),t.createdBy??null,t.changeDescription??null,t.status==="published"?i:null,i,i),!t.autosave){let r=this.collections.get(t.collection)?.versions?.maxPerDoc;r&&r>0&&await this.deleteVersions({collection:t.collection,documentId:t.documentId,keepLatest:r,tenantId:t.tenantId});}return await this.findVersionByID({collection:t.collection,versionId:n})}async updateLatestVersion(t){return this.createVersion({...t,autosave:true})}async deleteVersions(t){this.ensureVersionsTable();let{collection:i,documentId:n,keepLatest:a,tenantId:o}=t;if(a&&a>0){let e=this.db.prepare(`SELECT id, status, autosave FROM ${this.versionsTableName} WHERE collection_slug = ? AND document_id = ? ORDER BY version DESC`).all(i,n),s=0,r=[];for(let l of e)l.status==="published"||l.autosave===1||(s++,s>a&&r.push(l.id));for(let l of r)this.db.prepare(`DELETE FROM ${this.versionsTableName} WHERE id = ?`).run(l);}else {let e=`DELETE FROM ${this.versionsTableName} WHERE collection_slug = ? AND document_id = ?`,s=[i,n];o&&(e+=" AND tenant_id = ?",s.push(o)),this.db.prepare(e).run(...s);}}rowToVersion(t){return {id:String(t.id),collection:t.collection_slug,documentId:t.document_id,version:t.version,status:t.status,data:t.data?JSON.parse(t.data):{},createdBy:t.created_by??void 0,changeDescription:t.change_description??void 0,publishedAt:t.published_at??null,createdAt:t.created_at,updatedAt:t.updated_at}}prepareData(t,i){let n={},a=c(i.fields),o=(e,s)=>{let r=e;if(r.type==="json"||r.type==="richtext"||r.type==="array"||r.type==="group"||r.type==="blocks"||r.type==="list"||r.type==="relationship-block")return s!=null?JSON.stringify(s):null;if(r.type==="checkbox")return s?1:0;if(r.type==="number")return s!==null&&s!==""?Number(s):null;if(r.type==="upload"||r.type==="image"){if(s==null)return null;if(Array.isArray(s)){let l=s.map(c=>typeof c=="string"?c:typeof c=="object"?c.id||c._id||c:String(c));return JSON.stringify(l)}return typeof s=="string"?s:typeof s=="object"?JSON.stringify(s):String(s)}else if(e.type==="relationship"){if(s==null)return null;if(Array.isArray(s)){let l=s.map(c=>typeof c=="string"?c:typeof c=="object"?JSON.stringify({relationTo:e.relationTo,value:c.id||c}):String(c));return JSON.stringify(l)}return typeof s=="string"?s:typeof s=="object"?JSON.stringify({relationTo:e.relationTo,value:s.id||s}):String(s)}return s};for(let e of a){if(!e.name||e.name==="id"||i.fields.some(l=>l.type==="tabs"&&l.name&&"tabs"in l&&l.tabs.some(c=>c.fields.some(d=>d.name===e.name))))continue;let r=t[e.name];r!==void 0&&(n[e.name]=o(e,r));}for(let e of i.fields)if(e.type==="tabs"&&"tabs"in e&&e.name){let s=t[e.name];if(s&&typeof s=="object"){for(let r of e.tabs)for(let l of r.fields)if(l.name&&l.name!=="id"){let c=s[l.name];c!==void 0&&(n[l.name]=o(l,c));}}}return n}rowToDoc(t,i){let n={id:t.id};for(let a of c(i.fields)){if(!a.name||a.name==="id")continue;let o=a,e=t[o.name];if(o.type==="json"||o.type==="richtext"||o.type==="array"||o.type==="group"||o.type==="blocks"||o.type==="list"||o.type==="relationship-block")try{e=e?JSON.parse(e):null;}catch{e=null;}if(o.type==="blocks"&&e&&Array.isArray(e)){let s=o.blocks||[];e=d$1(e,s);}if(a.type==="checkbox"&&(e=!!e),a.type==="date"&&e)try{let s=new Date(e);isNaN(s.getTime())?(console.warn(`[LocalAdapter] Invalid date value for field "${a.name}":`,e),e=null):e=s.toISOString();}catch{e=null;}if((a.type==="upload"||a.type==="image")&&e)try{let s=JSON.parse(e);Array.isArray(s)?e=s.map(r=>typeof r=="object"&&r!==null?r:{id:r}):e=typeof s=="object"?s:{id:s};}catch{e={id:e};}if(a.type==="relationship"&&e)try{let s=JSON.parse(e);Array.isArray(s),e=s;}catch{e={relationTo:Array.isArray(a.relationTo)?a.relationTo[0]:a.relationTo,value:e};}n[a.name]=e;}for(let a of i.fields)if(!(!a.name||a.name==="id"||a.name==="row"||a.name==="collapsible")&&a.type==="tabs"&&"tabs"in a){let o={};for(let e of a.tabs)for(let s of e.fields)s.name&&s.name!=="id"&&(o[s.name]=w(t,s));n[a.name]=o;}if(i.timestamps){let a=t.createdAt||t.created_at,o=t.updatedAt||t.updated_at;if(a)try{let e=new Date(a);isNaN(e.getTime())||(n.createdAt=e.toISOString());}catch{}if(o)try{let e=new Date(o);isNaN(e.getTime())||(n.updatedAt=e.toISOString());}catch{}}i.tenantScoped&&(n.tenantId=t.tenant_id),n.status=t.status??"published",n.hasDraft=t.hasDraft?!!t.hasDraft:false;for(let a of Object.keys(n))/^\d+$/.test(a)&&delete n[a];return n}generateId(){let t=Date.now().toString(16).padStart(12,"0"),i=randomBytes(6).toString("hex");return t+i}getMediaById(t){try{let i=this.getTableNameFor("media"),n=this.db.prepare(`SELECT id, url, thumbnail_url FROM ${i} WHERE id = ?`).get(t);if(n)return {id:n.id,url:n.url,thumbnailUrl:n.thumbnail_url||n.url}}catch{}return null}getTableNameFor(t){return t.replace(/-/g,"_")}async migrate(){for(let t of this.collections.values())this.ensureTable(t);}async rollback(){}async transaction(t){return new Promise((i,n)=>{let a=this.db.transaction(async()=>t({db:this.db}));try{let o=a();i(o);}catch(o){n(o);}})}getDatabase(){return this.db}exec(t){this.db.exec(t);}prepare(t){return this.db.prepare(t)}};function B(T){return new I(T||{})}export{I as a,B as b};
20
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(n,t.collection,t.documentId,t.tenantId??null,o,t.status,t.autosave?1:0,JSON.stringify(t.data),t.createdBy??null,t.changeDescription??null,t.status==="published"?i:null,i,i),!t.autosave){let r=this.collections.get(t.collection)?.versions?.maxPerDoc;r&&r>0&&await this.deleteVersions({collection:t.collection,documentId:t.documentId,keepLatest:r,tenantId:t.tenantId});}return await this.findVersionByID({collection:t.collection,versionId:n})}async updateLatestVersion(t){return this.createVersion({...t,autosave:true})}async deleteVersions(t){this.ensureVersionsTable();let{collection:i,documentId:n,keepLatest:a,tenantId:o}=t;if(a&&a>0){let e=this.db.prepare(`SELECT id, status, autosave FROM ${this.versionsTableName} WHERE collection_slug = ? AND document_id = ? ORDER BY version DESC`).all(i,n),s=0,r=[];for(let l of e)l.status==="published"||l.autosave===1||(s++,s>a&&r.push(l.id));for(let l of r)this.db.prepare(`DELETE FROM ${this.versionsTableName} WHERE id = ?`).run(l);}else {let e=`DELETE FROM ${this.versionsTableName} WHERE collection_slug = ? AND document_id = ?`,s=[i,n];o&&(e+=" AND tenant_id = ?",s.push(o)),this.db.prepare(e).run(...s);}}rowToVersion(t){return {id:String(t.id),collection:t.collection_slug,documentId:t.document_id,version:t.version,status:t.status,data:t.data?JSON.parse(t.data):{},createdBy:t.created_by??void 0,changeDescription:t.change_description??void 0,publishedAt:t.published_at??null,createdAt:t.created_at,updatedAt:t.updated_at}}prepareData(t,i){let n={},a=c(i.fields),o=(e,s)=>{let r=e;if(r.type==="json"||r.type==="richtext"||r.type==="array"||r.type==="group"||r.type==="blocks"||r.type==="list"||r.type==="relationship-block")return s!=null?JSON.stringify(s):null;if(r.type==="checkbox")return s?1:0;if(r.type==="number")return s!==null&&s!==""?Number(s):null;if(r.type==="upload"||r.type==="image"){if(s==null)return null;if(Array.isArray(s)){let l=s.map(c=>typeof c=="string"?c:typeof c=="object"?c.id||c._id||c:String(c));return JSON.stringify(l)}return typeof s=="string"?s:typeof s=="object"?JSON.stringify(s):String(s)}else if(e.type==="relationship"){if(s==null)return null;if(Array.isArray(s)){let l=s.map(c=>typeof c=="string"?c:typeof c=="object"?JSON.stringify({relationTo:e.relationTo,value:c.id||c}):String(c));return JSON.stringify(l)}return typeof s=="string"?s:typeof s=="object"?JSON.stringify({relationTo:e.relationTo,value:s.id||s}):String(s)}return s};for(let e of a){if(!e.name||e.name==="id"||i.fields.some(l=>l.type==="tabs"&&l.name&&"tabs"in l&&l.tabs.some(c=>c.fields.some(d=>d.name===e.name))))continue;let r=t[e.name];r!==void 0&&(n[e.name]=o(e,r));}for(let e of i.fields)if(e.type==="tabs"&&"tabs"in e&&e.name){let s=t[e.name];if(s&&typeof s=="object"){for(let r of e.tabs)for(let l of r.fields)if(l.name&&l.name!=="id"){let c=s[l.name];c!==void 0&&(n[l.name]=o(l,c));}}}return n}rowToDoc(t,i){let n={id:t.id};for(let a of c(i.fields)){if(!a.name||a.name==="id")continue;let o=a,e=t[o.name];if(o.type==="json"||o.type==="richtext"||o.type==="array"||o.type==="group"||o.type==="blocks"||o.type==="list"||o.type==="relationship-block")try{e=e?JSON.parse(e):null;}catch{e=null;}if(o.type==="blocks"&&e&&Array.isArray(e)){let s=o.blocks||[];e=d$1(e,s);}if(a.type==="checkbox"&&(e=!!e),a.type==="date"&&e)try{let s=new Date(e);isNaN(s.getTime())?(console.warn(`[LocalAdapter] Invalid date value for field "${a.name}":`,e),e=null):e=s.toISOString();}catch{e=null;}if((a.type==="upload"||a.type==="image")&&e)try{let s=JSON.parse(e);Array.isArray(s)?e=s.map(r=>typeof r=="object"&&r!==null?r:{id:r}):e=typeof s=="object"?s:{id:s};}catch{e={id:e};}if(a.type==="relationship"&&e)try{let s=JSON.parse(e);Array.isArray(s),e=s;}catch{e={relationTo:Array.isArray(a.relationTo)?a.relationTo[0]:a.relationTo,value:e};}n[a.name]=e;}for(let a of i.fields)if(!(!a.name||a.name==="id"||a.name==="row"||a.name==="collapsible")&&a.type==="tabs"&&"tabs"in a){let o={};for(let e of a.tabs)for(let s of e.fields)s.name&&s.name!=="id"&&(o[s.name]=j(t,s));n[a.name]=o;}if(i.timestamps){let a=t.createdAt||t.created_at,o=t.updatedAt||t.updated_at;if(a)try{let e=new Date(a);isNaN(e.getTime())||(n.createdAt=e.toISOString());}catch{}if(o)try{let e=new Date(o);isNaN(e.getTime())||(n.updatedAt=e.toISOString());}catch{}}i.tenantScoped&&(n.tenantId=t.tenant_id),n.status=t.status??"published",n.hasDraft=t.hasDraft?!!t.hasDraft:false;for(let a of Object.keys(n))/^\d+$/.test(a)&&delete n[a];return n}generateId(){let t=Date.now().toString(16).padStart(12,"0"),i=randomBytes(6).toString("hex");return t+i}getMediaById(t){try{let i=this.getTableNameFor("media"),n=this.db.prepare(`SELECT id, url, thumbnail_url FROM ${i} WHERE id = ?`).get(t);if(n)return {id:n.id,url:n.url,thumbnailUrl:n.thumbnail_url||n.url}}catch{}return null}getTableNameFor(t){return t.replace(/-/g,"_")}async migrate(){for(let t of this.collections.values())this.ensureTable(t);}async rollback(){}async transaction(t){return new Promise((i,n)=>{let a=this.db.transaction(async()=>t({db:this.db}));try{let o=a();i(o);}catch(o){n(o);}})}getDatabase(){return this.db}exec(t){this.db.exec(t);}prepare(t){return this.db.prepare(t)}};function q(T){return new O(T||{})}export{O as a,q as b};
@@ -0,0 +1,132 @@
1
+ 'use strict';var chunkYOJOVQIH_cjs=require('./chunk-YOJOVQIH.cjs'),chunkO4PPZOVI_cjs=require('./chunk-O4PPZOVI.cjs'),chunkJJY2F6NL_cjs=require('./chunk-JJY2F6NL.cjs'),chunkOXEJCIOA_cjs=require('./chunk-OXEJCIOA.cjs'),drizzleOrm=require('drizzle-orm'),pgCore=require('drizzle-orm/pg-core'),sqliteCore=require('drizzle-orm/sqlite-core');function w(m,s="postgres"){switch(m.type){case "text":case "email":case "password":case "color":case "icon":return s==="sqlite"?"text":"varchar";case "textarea":case "code":case "markdown":case "secret":return "text";case "number":return m.integer?"integer":"decimal";case "checkbox":return "boolean";case "date":return "timestamp";case "select":case "radio":return s==="sqlite"?"text":"varchar";case "richtext":case "json":case "array":case "group":case "blocks":case "row":case "collapsible":case "tabs":return "jsonb";case "relationship":return s==="sqlite"?"text":"varchar";case "upload":return "jsonb";default:return "jsonb"}}function B(m,s="postgres"){let n=m.slug.replace(/-/g,"_"),e=[];e.push(`export const ${n} = pgTable('${n}', {`),e.push(" id: uuid('id').primaryKey().defaultRandom(),");let o=chunkYOJOVQIH_cjs.c(m.fields);for(let t of o){if(t.name==="id"||t.type==="password")continue;let r=w(t,s),l=t.required,a=` ${t.name}: pg.${r}('${t.name}')`;t.unique&&(a+=".unique()"),l||(a+=".nullable()"),t.defaultValue!==void 0&&(typeof t.defaultValue=="string"?a+=`.default('${t.defaultValue}')`:typeof t.defaultValue=="boolean"?a+=`.default(${t.defaultValue})`:a+=`.default(sql\`${JSON.stringify(t.defaultValue)}\`)`),a+=",",e.push(a);}return m.timestamps&&(e.push(" createdAt: pg.timestamp('created_at').defaultNow(),"),e.push(" updatedAt: pg.timestamp('updated_at').defaultNow(),")),e.push(` status: ${s==="sqlite"?"sqlite":"pg"}.varchar('status').default('draft'),`),e.push(` hasDraft: ${s==="sqlite"?"sqlite":"pg"}.boolean('hasDraft').default(false),`),e.push("});"),e.join(`
2
+ `)}function R(m){if(typeof m!="string")return m;let s=m.replace(/-/g,"").toLowerCase();return s.length===32?`${s.slice(0,8)}-${s.slice(8,12)}-${s.slice(12,16)}-${s.slice(16,20)}-${s.slice(20)}`:m}var x=class extends chunkO4PPZOVI_cjs.a{client;schema;_schemaEnsured=false;dialect;connectionString;versionsTableReady=false;rawClient;constructor(s){if(super(),this.schema=s.schema||{},s.connectionString){this.connectionString=s.connectionString;let n=s.connectionString.toLowerCase();n.startsWith("postgres://")||n.startsWith("postgresql://")?this.dialect="postgres":n.includes(".db")||n.includes("sqlite")||n.includes("file:")?this.dialect="sqlite":this.dialect=s.type||"postgres";}else this.rawClient=s.client,this.client=s.client,this.dialect=s.type||"sqlite";}prepareData(s,n){let e=super.prepareData(s,n),o=chunkYOJOVQIH_cjs.c(n.fields);e.createdAt&&typeof e.createdAt=="string"&&(e.createdAt=new Date(e.createdAt)),e.updatedAt&&typeof e.updatedAt=="string"&&(e.updatedAt=new Date(e.updatedAt));for(let t of o)if(t.type==="date"&&t.name){let r=e[t.name];r&&typeof r=="string"&&(e[t.name]=new Date(r));}for(let t of o){let l=w(t,this.dialect)==="jsonb";if(t.type==="tabs"&&"tabs"in t&&t.name){let a=s[t.name];if(a&&typeof a=="object"){let i={};for(let[c,d]of Object.entries(a)){let f=t.tabs.flatMap(E=>E.fields).find(E=>E.name===c);(f?.type==="upload"||f?.type==="image"||f?.type==="list"||f?.type==="relationship-block")&&d?i[c]=Array.isArray(d)||typeof d=="object"?JSON.stringify(d):d:i[c]=d;}e[t.name]=this.dialect==="sqlite"||!l?JSON.stringify(i):i;}}else if(l&&t.name&&s[t.name]!==void 0&&s[t.name]!==null)e[t.name]=this.dialect==="sqlite"?JSON.stringify(s[t.name]):s[t.name];else if((t.type==="upload"||t.type==="image"||t.type==="list"||t.type==="relationship-block")&&t.name){let a=s[t.name];a!=null&&(e[t.name]=this.dialect==="sqlite"||!l?typeof a=="string"?a:JSON.stringify(a):a);}}for(let t of o)if(t.name&&e[t.name]===""){let r=w(t,this.dialect);(r==="timestamp"||r==="jsonb"||r==="decimal"||r==="integer"||r==="numeric"||r==="boolean")&&(e[t.name]=null);}return e}async connect(){if(this.connectionString&&!this.client){if(this.dialect==="postgres"){let s,n;try{s=(await import('postgres')).default,n=(await import('drizzle-orm/postgres-js')).drizzle;}catch{chunkJJY2F6NL_cjs.a(["postgres","drizzle-orm"]),s=(await import('postgres')).default,n=(await import('drizzle-orm/postgres-js')).drizzle;}let e=s(this.connectionString,{onnotice:()=>{}});this.client=n(e,{schema:this.schema});}else if(this.dialect==="sqlite"){let s,n;try{s=(await import('better-sqlite3')).default,n=(await import('drizzle-orm/better-sqlite3')).drizzle;}catch{chunkJJY2F6NL_cjs.a(["better-sqlite3","drizzle-orm"]),s=(await import('better-sqlite3')).default,n=(await import('drizzle-orm/better-sqlite3')).drizzle;}let e=new s(this.connectionString.replace("file:",""));this.client=n(e,{schema:this.schema});}}if(this.rawClient&&typeof this.rawClient.prepare=="function"&&typeof this.client?.select!="function"){let{drizzle:s}=await import('drizzle-orm/d1');this.client=s(this.rawClient,{schema:this.schema});}this.connected=true;}async init(s,n=[]){if(await super.init(s,n),(this.connectionString&&!this.client||this.rawClient&&typeof this.client?.select!="function")&&await this.connect(),this.client&&!this._schemaEnsured){for(let o of s){let t=this.getTableName(o.slug);this.schema[t]||(this.schema[t]=this.createTableFromConfig(o));}await this.ensureCollectionTables(s);let e=n.map(o=>({slug:`_globals_${o.slug}`,fields:o.fields,label:o.label}));for(let o of e){let t=this.getTableName(o.slug);this.schema[t]||(this.schema[t]=this.createTableFromConfig(o,true)),this.collections.has(o.slug)||this.collections.set(o.slug,o);}await this.ensureCollectionTables(e),this._schemaEnsured=true;}}createTableFromConfig(s,n=false){let e=this.getTableName(s.slug),o={id:n?pgCore.text("id").primaryKey():pgCore.uuid("id").primaryKey().defaultRandom()},t=chunkYOJOVQIH_cjs.c(s.fields);for(let r of t){if(!r.name||r.name==="id"||r.type==="password")continue;let l=w(r,this.dialect),a=r.name.replace(/-/g,"_"),i=a.replace(/([A-Z])/g,"_$1").toLowerCase(),c;if(this.dialect==="sqlite")switch(l){case "varchar":case "text":c=sqliteCore.text(i);break;case "integer":c=sqliteCore.integer(i);break;case "decimal":case "numeric":c=sqliteCore.numeric(i);break;case "boolean":c=sqliteCore.integer(i,{mode:"boolean"});break;case "timestamp":c=sqliteCore.text(i);break;case "jsonb":c=sqliteCore.text(i);break;default:c=sqliteCore.text(i);}else switch(l){case "varchar":c=pgCore.varchar(i,{length:255});break;case "integer":c=pgCore.integer(i);break;case "decimal":c=pgCore.decimal(i);break;case "boolean":c=pgCore.boolean(i);break;case "timestamp":c=pgCore.timestamp(i);break;case "jsonb":c=pgCore.jsonb(i);break;default:c=pgCore.text(i);}r.required||(c=c.default(null)),o[a]=c;}return o.createdAt||(o.createdAt=this.dialect==="sqlite"?sqliteCore.text("created_at").default(new Date().toISOString()):pgCore.timestamp("created_at").defaultNow()),o.updatedAt||(o.updatedAt=this.dialect==="sqlite"?sqliteCore.text("updated_at").default(new Date().toISOString()):pgCore.timestamp("updated_at").defaultNow()),e!=="users"&&e!=="audit_logs"&&(o.status||(o.status=this.dialect==="sqlite"?sqliteCore.text("status").default("draft"):pgCore.varchar("status",{length:20}).default("draft")),o.hasDraft||(o.hasDraft=this.dialect==="sqlite"?sqliteCore.integer("hasDraft",{mode:"boolean"}).default(false):pgCore.boolean("hasDraft").default(false))),this.dialect==="sqlite"?sqliteCore.sqliteTable(e,o):pgCore.pgTable(e,o)}async ensureCollectionTables(s){let n=[];for(let e of s){let o=e.slug.startsWith("_globals_"),t=this.getTableName(e.slug),r=this.generateCreateColumns(e),l=chunkYOJOVQIH_cjs.c(e.fields),a=l.some(f=>f.name==="createdAt"),i=l.some(f=>f.name==="updatedAt"),c=l.some(f=>f.name==="status"),d=l.some(f=>f.name==="hasDraft");if(this.dialect==="postgres"){let f=o?'"id" TEXT PRIMARY KEY':'"id" UUID PRIMARY KEY DEFAULT gen_random_uuid()';n.push(`
3
+ CREATE TABLE IF NOT EXISTS "${t}" (
4
+ ${f},
5
+ ${r}
6
+ ${a?"":'"created_at" TIMESTAMP NOT NULL DEFAULT NOW(),'}
7
+ ${i?"":'"updated_at" TIMESTAMP NOT NULL DEFAULT NOW(),'}
8
+ ${c?"":`"status" VARCHAR(20) DEFAULT 'draft',`}
9
+ ${d?"":'"hasDraft" BOOLEAN DEFAULT false'}
10
+ )
11
+ `);}else n.push(`
12
+ CREATE TABLE IF NOT EXISTS "${t}" (
13
+ "id" TEXT PRIMARY KEY,
14
+ ${r}
15
+ ${a?"":`"created_at" TEXT NOT NULL DEFAULT (datetime('now')),`}
16
+ ${i?"":`"updated_at" TEXT NOT NULL DEFAULT (datetime('now')),`}
17
+ ${c?"":`"status" TEXT DEFAULT 'draft',`}
18
+ ${d?"":'"hasDraft" INTEGER DEFAULT 0'}
19
+ )
20
+ `);}if(n.length>0)if(this.dialect==="postgres")await this.executeRaw(drizzleOrm.sql.raw(n.join(`;
21
+ `)));else for(let e of n)await this.executeRaw(drizzleOrm.sql.raw(e));for(let e of s){let o=this.getTableName(e.slug);o==="users"||o==="audit_logs"||await this.syncTableColumns(e,o);}}getColumnSqlDefinition(s,n){let e=w(s,n),o=s.name.replace(/-/g,"_").replace(/([A-Z])/g,"_$1").toLowerCase(),t=this.columnSqlType(e,n);return `"${o}" ${t} DEFAULT NULL`}columnSqlType(s,n){if(n==="sqlite")switch(s){case "varchar":return "TEXT";case "text":return "TEXT";case "integer":return "INTEGER";case "decimal":case "numeric":return "NUMERIC";case "boolean":return "INTEGER";case "timestamp":return "TEXT";case "jsonb":return "TEXT";default:return "TEXT"}switch(s){case "varchar":return "VARCHAR(255)";case "text":return "TEXT";case "integer":return "INTEGER";case "decimal":case "numeric":return "DECIMAL";case "boolean":return "BOOLEAN";case "timestamp":return "TIMESTAMP";case "jsonb":return "JSONB";default:return "TEXT"}}getExpectedColumnDefs(s,n){let e={},o=s.slug.startsWith("_globals_"),t=chunkYOJOVQIH_cjs.c(s.fields),r=t.some(c=>c.name==="createdAt"),l=t.some(c=>c.name==="updatedAt"),a=t.some(c=>c.name==="status"),i=t.some(c=>c.name==="hasDraft");this.dialect==="postgres"?(e.id=o?'"id" TEXT PRIMARY KEY':'"id" UUID PRIMARY KEY DEFAULT gen_random_uuid()',r||(e.created_at='"created_at" TIMESTAMP DEFAULT NULL'),l||(e.updated_at='"updated_at" TIMESTAMP DEFAULT NULL'),a||(e.status='"status" VARCHAR(20) DEFAULT NULL'),i||(e.hasDraft='"hasDraft" BOOLEAN DEFAULT NULL')):(e.id='"id" TEXT PRIMARY KEY',r||(e.created_at='"created_at" TEXT DEFAULT NULL'),l||(e.updated_at='"updated_at" TEXT DEFAULT NULL'),a||(e.status='"status" TEXT DEFAULT NULL'),i||(e.hasDraft='"hasDraft" INTEGER DEFAULT NULL'));for(let c of t){if(!c.name||c.name==="id")continue;let d=this.getColumnSqlDefinition(c,this.dialect),f=c.name.replace(/-/g,"_").replace(/([A-Z])/g,"_$1").toLowerCase();e[f]=d;}return e}async syncTableColumns(s,n){let e;try{if(this.dialect==="postgres"){let r=await this.executeRaw(drizzleOrm.sql`SELECT column_name, data_type, character_maximum_length FROM information_schema.columns WHERE table_name = ${n}`);e=new Map(r.map(l=>[l.column_name,{type:l.data_type,maxLen:l.character_maximum_length}]));}else {let r=await this.executeRaw(drizzleOrm.sql`PRAGMA table_info("${drizzleOrm.sql.raw(n)}")`);e=new Map(r.map(l=>[l.name,{type:l.type,maxLen:null}]));}}catch{return}let o=this.getExpectedColumnDefs(s,n),t=Object.keys(o).filter(r=>!e.has(r));if(t.length>0){let r=t.map(l=>`ALTER TABLE "${n}" ADD COLUMN ${o[l]}`);await this.executeRaw(drizzleOrm.sql.raw(r.join(`;
22
+ `)));}if(this.dialect==="postgres"){let r=chunkYOJOVQIH_cjs.c(s.fields);for(let l of r){if(!l.name||l.name==="id")continue;let a=w(l,this.dialect),i=l.name.replace(/-/g,"_").replace(/([A-Z])/g,"_$1").toLowerCase(),c=e.get(i);!c||c.type!=="character varying"||(a==="text"?await this.executeRaw(drizzleOrm.sql.raw(`ALTER TABLE "${n}" ALTER COLUMN "${i}" TYPE TEXT`)):a==="jsonb"&&(await this.executeRaw(drizzleOrm.sql.raw(`ALTER TABLE "${n}" ALTER COLUMN "${i}" DROP DEFAULT`)),await this.executeRaw(drizzleOrm.sql.raw(`ALTER TABLE "${n}" ALTER COLUMN "${i}" TYPE JSONB USING (CASE WHEN "${i}" IS NULL THEN NULL WHEN "${i}"::text ~ '^\\s*\\{' THEN "${i}"::jsonb ELSE jsonb_build_object('id', "${i}"::text) END)`))));}}}generateCreateColumns(s){let n=[],e=chunkYOJOVQIH_cjs.c(s.fields);for(let o of e){if(!o.name||o.name==="id")continue;let t=w(o,this.dialect),r=o.name.replace(/-/g,"_").replace(/([A-Z])/g,"_$1").toLowerCase(),l=o.required?"NOT NULL":"DEFAULT NULL",a;if(this.dialect==="sqlite")switch(t){case "varchar":case "text":a=`TEXT ${l}`;break;case "integer":a=`INTEGER ${l}`;break;case "decimal":case "numeric":a=`NUMERIC ${l}`;break;case "boolean":a=`INTEGER ${l}`;break;case "timestamp":a=`TEXT ${l}`;break;case "jsonb":a=`TEXT ${l}`;break;default:a=`TEXT ${l}`;}else switch(t){case "varchar":a=`VARCHAR(255) ${l}`;break;case "integer":a=`INTEGER ${l}`;break;case "decimal":a=`DECIMAL ${l}`;break;case "boolean":a=`BOOLEAN ${l}`;break;case "timestamp":a=`TIMESTAMP ${l}`;break;case "jsonb":a=`JSONB ${l}`;break;default:a=`TEXT ${l}`;}n.push(`"${r}" ${a}`);}return n.join(`,
23
+ `)+(n.length>0?",":"")}async disconnect(){this.connected=false;}async find(s){let{collection:n,where:e={},sort:o,limit:t=10,page:r=1,tenantId:l,select:a,draft:i}=s,c=this.getCollection(n),d=this.getTable(n),f={...e};this.tenantContext&&c.tenantScoped&&(f=chunkO4PPZOVI_cjs.c({where:f},n,this.tenantContext,chunkO4PPZOVI_cjs.b).where||{});let L=this.buildWhereClause(f,c,d,l),y=chunkYOJOVQIH_cjs.c(c.fields).find(h=>h.name==="status"),p=y?.type==="select"&&Array.isArray(y.options)&&y.options.some(h=>h.value==="published");!i&&d.status&&p&&L.push(drizzleOrm.eq(d.status,"published"));let b=this.parseSort(o),T=!i&&d.status&&p?{...f,status:"published"}:f,H=await this.count({collection:n,where:T,tenantId:l}),K=(r-1)*t,q=[];try{let h=d[b.field]||d.createdAt||d.id,I=b.direction==="asc"?h:drizzleOrm.desc(h),N=this.client.select().from(d);L.length>0&&(N=N.where(drizzleOrm.and(...L))),q=await N.orderBy(I).limit(t).offset(K);}catch(h){console.error("[DrizzleAdapter] Query error:",h);}let $=q.map(h=>this.processResult(h,c));return this.tenantContext&&!this.tenantContext.isSuperAdmin&&($=$.filter(h=>chunkO4PPZOVI_cjs.d(h,n,this.tenantContext,chunkO4PPZOVI_cjs.b))),i&&($=await Promise.all($.map(async h=>{let I=await this.executeRaw(drizzleOrm.sql`
24
+ SELECT * FROM kyro_versions
25
+ WHERE collection_slug = ${n}
26
+ AND document_id = ${h.id}
27
+ ORDER BY created_at DESC
28
+ LIMIT 1
29
+ `);if(I.length>0){let N=I[0],_=N.data;for(;typeof _=="string";)try{_=JSON.parse(_);}catch{break}return (!_||typeof _!="object"||Array.isArray(_))&&(_={}),{...h,..._,status:h.status,_hasUnpublishedChanges:N.status==="draft"}}return h}))),{docs:$,...this.calculatePagination(r,t,H)}}async findByID(s){let{collection:n,id:e,tenantId:o,draft:t}=s,r=this.getCollection(n),l=this.getTable(n),a=this.dialect==="postgres"&&typeof e=="string"?R(e):e;if(this.tenantContext&&r.tenantScoped){let p={id:a,tenantId:this.tenantContext.tenantId};if(!chunkO4PPZOVI_cjs.d(p,n,this.tenantContext,chunkO4PPZOVI_cjs.b))return null}let i=[drizzleOrm.eq(l.id,a)];o&&l.tenantId&&i.push(drizzleOrm.eq(l.tenantId,o));let d=chunkYOJOVQIH_cjs.c(r.fields).find(p=>p.name==="status"),f=d?.type==="select"&&Array.isArray(d.options)&&d.options.some(p=>p.value==="published");!t&&l.status&&f&&i.push(drizzleOrm.eq(l.status,"published"));let L=i.length>1?drizzleOrm.and(...i):i[0],E=await this.client.select().from(l).where(L);if(E.length===0)return null;let y=this.processResult(E[0],r);if(t){let p=await this.executeRaw(drizzleOrm.sql`
30
+ SELECT * FROM kyro_versions
31
+ WHERE collection_slug = ${n}
32
+ AND document_id = ${y.id}
33
+ ORDER BY created_at DESC
34
+ LIMIT 1
35
+ `);if(p.length>0){let b=p[0],T=b.data;for(;typeof T=="string";)try{T=JSON.parse(T);}catch{break}(!T||typeof T!="object"||Array.isArray(T))&&(T={}),y={...y,...T,status:y.status,_hasUnpublishedChanges:b.status==="draft"};}}return y}async create(s){let{collection:n,data:e,tenantId:o}=s,t=this.getCollection(n),r=this.getTable(n),l=this.prepareData(e,t);o&&t.tenantScoped&&(l.tenantId=o);let a=await this.client.insert(r).values(l).returning();return this.processResult(a[0],t)}async update(s){let{collection:n,id:e,data:o,tenantId:t}=s,r=this.getCollection(n),l=this.getTable(n),a=this.prepareData(o,r),i=this.dialect==="postgres"&&typeof e=="string"?R(e):e,c=[drizzleOrm.eq(l.id,i)];t&&l.tenantId&&c.push(drizzleOrm.eq(l.tenantId,t));let d=await this.client.update(l).set(a).where(drizzleOrm.and(...c)).returning();if(d.length===0)throw new Error(`Document not found: ${n}/${e}`);return this.processResult(d[0],r)}async delete(s){let{collection:n,id:e,tenantId:o}=s,t=this.getCollection(n),r=this.getTable(n),l=this.dialect==="postgres"&&typeof e=="string"?R(e):e,a=[drizzleOrm.eq(r.id,l)];o&&r.tenantId&&a.push(drizzleOrm.eq(r.tenantId,o));let i=await this.client.delete(r).where(drizzleOrm.and(...a)).returning();if(i.length===0)throw new Error(`Document not found: ${n}/${e}`);return this.processResult(i[0],t)}async count(s){let{collection:n,where:e={},tenantId:o}=s,t=this.getCollection(n),r=this.getTable(n),l=this.buildWhereClause(e,t,r,o);try{let a=this.client.select({count:drizzleOrm.sql`count(*)`}).from(r);l.length>0&&(a=a.where(drizzleOrm.and(...l)));let i=await a;return Number(i[0]?.count||0)}catch{return 0}}async findOne(s){let{collection:n,where:e={},tenantId:o,draft:t}=s;if(n.startsWith("_globals_")){let l=n.replace("_globals_",""),a=this.globals.get(l);if(!a)throw new Error(`Global "${l}" not found`);let i=this.getTable(n),c=this.client.select().from(i),f=chunkYOJOVQIH_cjs.c(a.fields).find(p=>p.name==="status"),L=f?.type==="select"&&Array.isArray(f.options)&&f.options.some(p=>p.value==="published");!t&&i.status&&L&&(c=c.where(drizzleOrm.eq(i.status,"published")));let E=await c.limit(1);if(E.length===0)return null;let y=this.processResult(E[0],a);if(t){let p=await this.executeRaw(drizzleOrm.sql`
36
+ SELECT * FROM kyro_versions
37
+ WHERE collection_slug = ${n}
38
+ AND document_id = ${l}
39
+ ORDER BY created_at DESC
40
+ LIMIT 1
41
+ `);if(p.length>0){let b=p[0],T=typeof b.data=="string"?JSON.parse(b.data):b.data;y={...y,...T,status:y.status,_hasUnpublishedChanges:b.status==="draft"};}}return y}return (await this.find({...s,limit:1})).docs[0]||null}async findVersions(s){await this.ensureVersionsTable();let{collection:n,documentId:e,limit:o=10,page:t=1,tenantId:r}=s,l=(t-1)*o,a=this.getCollection(n),i=await this.executeRaw(drizzleOrm.sql`
42
+ SELECT count(*) as count
43
+ FROM kyro_versions
44
+ WHERE collection_slug = ${n}
45
+ AND document_id = ${e}
46
+ AND autosave = 0
47
+ ${r&&a.tenantScoped?drizzleOrm.sql`AND tenant_id = ${r}`:drizzleOrm.sql``}
48
+ `),c=parseInt(i[0]?.count||"0");return {docs:(await this.executeRaw(drizzleOrm.sql`
49
+ SELECT *
50
+ FROM kyro_versions
51
+ WHERE collection_slug = ${n}
52
+ AND document_id = ${e}
53
+ AND autosave = 0
54
+ ${r&&a.tenantScoped?drizzleOrm.sql`AND tenant_id = ${r}`:drizzleOrm.sql``}
55
+ ORDER BY created_at DESC
56
+ LIMIT ${o}
57
+ OFFSET ${l}
58
+ `)).map(f=>({...f,data:typeof f.data=="string"?JSON.parse(f.data):f.data})),...this.calculatePagination(t,o,c)}}async findVersionByID(s){await this.ensureVersionsTable();let n=this.getCollection(s.collection),e=await this.executeRaw(drizzleOrm.sql`
59
+ SELECT * FROM kyro_versions
60
+ WHERE id = ${s.versionId}
61
+ AND collection_slug = ${s.collection}
62
+ ${s.tenantId&&n.tenantScoped?drizzleOrm.sql`AND tenant_id = ${s.tenantId}`:drizzleOrm.sql``}
63
+ LIMIT 1
64
+ `);if(e.length===0)return null;let o=e[0];return {...o,data:typeof o.data=="string"?JSON.parse(o.data):o.data}}async createVersion(s){await this.ensureVersionsTable();let n=this.getCollection(s.collection),e=new Date().toISOString();if(s.autosave){let r=await this.executeRaw(drizzleOrm.sql`
65
+ SELECT * FROM kyro_versions
66
+ WHERE collection_slug = ${s.collection}
67
+ AND document_id = ${s.documentId}
68
+ AND autosave = 1
69
+ ${s.tenantId&&n.tenantScoped?drizzleOrm.sql`AND tenant_id = ${s.tenantId}`:drizzleOrm.sql``}
70
+ LIMIT 1
71
+ `);if(r.length>0)return await this.executeRaw(drizzleOrm.sql`
72
+ UPDATE kyro_versions
73
+ SET data = ${JSON.stringify(s.data)},
74
+ status = ${s.status},
75
+ updated_at = ${e}
76
+ WHERE id = ${r[0].id}
77
+ `),this.findVersionByID({collection:s.collection,versionId:r[0].id,tenantId:s.tenantId})}let o=Math.random().toString(36).substring(2,15),t=typeof s.data=="string"?s.data:JSON.stringify(s.data);if(await this.executeRaw(drizzleOrm.sql`
78
+ INSERT INTO kyro_versions (
79
+ id, collection_slug, document_id, tenant_id, data, status, autosave, created_by, change_description, created_at, updated_at
80
+ ) VALUES (
81
+ ${o}, ${s.collection}, ${s.documentId}, ${s.tenantId&&n.tenantScoped?s.tenantId:null},
82
+ ${t}, ${s.status}, ${s.autosave?1:0}, ${s.createdBy||null},
83
+ ${s.changeDescription||null}, ${e}, ${e}
84
+ )
85
+ `),!s.autosave){let r=this.getCollection(s.collection);r.versions?.maxPerDoc&&await this.deleteVersions({collection:s.collection,documentId:s.documentId,keepLatest:r.versions.maxPerDoc,tenantId:s.tenantId});}return this.findVersionByID({collection:s.collection,versionId:o,tenantId:s.tenantId})}async updateLatestVersion(s){return this.createVersion({...s,autosave:true})}async deleteVersions(s){await this.ensureVersionsTable();let n=this.getCollection(s.collection);if(s.keepLatest){let o=(await this.executeRaw(drizzleOrm.sql`
86
+ SELECT id FROM kyro_versions
87
+ WHERE collection_slug = ${s.collection}
88
+ AND document_id = ${s.documentId}
89
+ AND autosave = 0
90
+ ${s.tenantId&&n.tenantScoped?drizzleOrm.sql`AND tenant_id = ${s.tenantId}`:drizzleOrm.sql``}
91
+ ORDER BY created_at DESC
92
+ LIMIT ${s.keepLatest}
93
+ `)).map(t=>t.id);o.length>0&&await this.executeRaw(drizzleOrm.sql`
94
+ DELETE FROM kyro_versions
95
+ WHERE collection_slug = ${s.collection}
96
+ AND document_id = ${s.documentId}
97
+ AND autosave = 0
98
+ AND id NOT IN (${drizzleOrm.sql.join(o.map(t=>drizzleOrm.sql`${t}`),drizzleOrm.sql`, `)})
99
+ `);}else await this.executeRaw(drizzleOrm.sql`
100
+ DELETE FROM kyro_versions
101
+ WHERE collection_slug = ${s.collection}
102
+ AND document_id = ${s.documentId}
103
+ ${s.tenantId&&n.tenantScoped?drizzleOrm.sql`AND tenant_id = ${s.tenantId}`:drizzleOrm.sql``}
104
+ `);}getTable(s){let n=this.getTableName(s),e=this.schema[n];if(!e)throw new Error(`Table "${n}" not found in schema`);return e}buildWhereClause(s,n,e,o){let t=[];o&&n.tenantScoped&&e.tenantId&&t.push(drizzleOrm.eq(e.tenantId,o));for(let[r,l]of Object.entries(s)){let a=l,i=r,c=i.toUpperCase();if(i==="id"&&this.dialect==="postgres"&&(typeof a=="string"?a=R(a):a&&typeof a=="object"&&(a.equals!==void 0&&typeof a.equals=="string"&&(a={...a,equals:R(a.equals)}),a.in&&Array.isArray(a.in)&&(a={...a,in:a.in.map(d=>typeof d=="string"?R(d):d)}))),c==="AND"&&Array.isArray(a)){let d=a.map(f=>this.buildWhereClause(f,n,e)).flat().filter(Boolean);d.length>0&&t.push(drizzleOrm.and(...d));}else if(c==="OR"&&Array.isArray(a)){let d=a.map(f=>this.buildWhereClause(f,n,e)).flat().filter(Boolean);d.length>0&&t.push(drizzleOrm.or(...d));}else if(typeof a=="object"&&a!==null&&!Array.isArray(a)){let d=e[i]||e[i.replace(/-/g,"_")]||e[i.replace(/([A-Z])/g,"_$1").toLowerCase()]||(i==="created_at"?e.createdAt:void 0)||(i==="createdAt"?e.created_at:void 0)||(i==="updated_at"?e.updatedAt:void 0)||(i==="updatedAt"?e.updated_at:void 0);if(!d)continue;a.equals!==void 0&&t.push(drizzleOrm.eq(d,a.equals)),a.not_equals!==void 0&&t.push(drizzleOrm.ne(d,a.not_equals)),a.in&&Array.isArray(a.in)&&(a.in.length===0?t.push(drizzleOrm.sql`1 = 0`):t.push(drizzleOrm.inArray(d,a.in))),a.like!==void 0&&(this.dialect==="postgres"?t.push(drizzleOrm.ilike(d,a.like)):t.push(drizzleOrm.like(d,a.like))),a.contains!==void 0&&(this.dialect==="postgres"?t.push(drizzleOrm.ilike(d,`%${a.contains}%`)):t.push(drizzleOrm.like(d,`%${a.contains}%`))),a.greater_than!==void 0&&t.push(drizzleOrm.gt(d,a.greater_than)),a.greater_than_equal!==void 0&&t.push(drizzleOrm.gte(d,a.greater_than_equal)),a.less_than!==void 0&&t.push(drizzleOrm.lt(d,a.less_than)),a.less_than_equal!==void 0&&t.push(drizzleOrm.lte(d,a.less_than_equal));}else {let d=e[i]||e[i.replace(/-/g,"_")]||e[i.replace(/([A-Z])/g,"_$1").toLowerCase()];d&&t.push(drizzleOrm.eq(d,a));}}return t}processResult(s,n){if(!s)return null;let e={...s};for(let t of Object.keys(e))/^\d+$/.test(t)&&delete e[t];s.id&&(e.id=String(s.id));let o=chunkYOJOVQIH_cjs.c(n.fields);for(let t of o){if(!t.name)continue;let r=t.name.replace(/-/g,"_").replace(/([A-Z])/g,"_$1").toLowerCase();r!==t.name&&e[r]!==void 0&&e[t.name]===void 0&&(e[t.name]=e[r],delete e[r]);}for(let t of o){if(["json","richtext","array","group","blocks","upload","image","list","relationship-block"].includes(t.type)){let r=t;if(e[r.name]&&typeof e[r.name]=="string")try{let l=JSON.parse(e[r.name]);e[r.name]=l;}catch{}if(t.type==="blocks"&&e[r.name]&&Array.isArray(e[r.name])){let l=r.blocks||[];e[r.name]=chunkYOJOVQIH_cjs.d(e[r.name],l);}}if(t.type==="tabs"&&"tabs"in t&&t.name){if(typeof e[t.name]=="object"&&e[t.name]!==null&&!Array.isArray(e[t.name])){for(let l of t.tabs)for(let a of l.fields)if((a.type==="upload"||a.type==="image")&&a.name){let i=e[t.name][a.name];if(typeof i=="string")try{let c=JSON.parse(i);e[t.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 i&&typeof i=="object"&&(e[t.name][a.name]=Array.isArray(i)?i.map(c=>c&&typeof c=="object"&&typeof c.id=="string"?c.id:String(c||"")):typeof i.id=="string"?i.id:String(i.id||""));}continue}if(typeof e[t.name]=="string")try{let l=JSON.parse(e[t.name]);if(typeof l=="object"&&l!==null){e[t.name]=l;continue}}catch{}let r={};for(let l of t.tabs)for(let a of l.fields)if(a.name&&e[a.name]!==void 0){let i=e[a.name];if(["json","richtext","array","group","blocks","upload","image","list","relationship-block"].includes(a.type)){if(i&&typeof i=="string")try{i=JSON.parse(i);}catch{}(a.type==="upload"||a.type==="image")&&i&&typeof i=="object"&&(i=Array.isArray(i)?i.map(c=>c&&typeof c=="object"&&typeof c.id=="string"?c.id:String(c||"")):typeof i.id=="string"?i.id:String(i.id||""));}r[a.name]=i,delete e[a.name];}e[t.name]=r;}}return e.createdAt&&(e.createdAt=new Date(e.createdAt).toISOString()),e.updatedAt&&(e.updatedAt=new Date(e.updatedAt).toISOString()),chunkOXEJCIOA_cjs.a(e)}async ensureVersionsTable(){if(this.versionsTableReady)return;let s;this.dialect==="sqlite"?s=`
105
+ CREATE TABLE IF NOT EXISTS kyro_versions (
106
+ id text PRIMARY KEY,
107
+ collection_slug text NOT NULL,
108
+ document_id text NOT NULL,
109
+ tenant_id text,
110
+ data text NOT NULL,
111
+ status text NOT NULL DEFAULT 'draft',
112
+ autosave integer NOT NULL DEFAULT 0,
113
+ created_by text,
114
+ change_description text,
115
+ created_at text DEFAULT (datetime('now')),
116
+ updated_at text DEFAULT (datetime('now'))
117
+ )
118
+ `:s=`
119
+ CREATE TABLE IF NOT EXISTS kyro_versions (
120
+ id text PRIMARY KEY,
121
+ collection_slug text NOT NULL,
122
+ document_id text NOT NULL,
123
+ tenant_id text,
124
+ data text NOT NULL,
125
+ status text NOT NULL,
126
+ autosave integer NOT NULL DEFAULT 0,
127
+ created_by text,
128
+ change_description text,
129
+ created_at text NOT NULL,
130
+ updated_at text NOT NULL
131
+ )
132
+ `,await this.executeRaw(drizzleOrm.sql.raw(s));try{this.dialect==="postgres"?await this.executeRaw(drizzleOrm.sql.raw("ALTER TABLE kyro_versions ADD COLUMN IF NOT EXISTS autosave integer NOT NULL DEFAULT 0")):await this.executeRaw(drizzleOrm.sql.raw("ALTER TABLE kyro_versions ADD COLUMN autosave integer NOT NULL DEFAULT 0"));}catch{}this.versionsTableReady=true;}async execute(s){return this.executeRaw(s)}async executeRaw(s){let n="",e=[];if(typeof s=="string")n=s;else if(s&&(s.queryChunks||s.decoder))if(this.dialect==="postgres"){let t=new pgCore.PgDialect().sqlToQuery(s);n=t.sql,e=t.params;}else {let t=new sqliteCore.SQLiteSyncDialect().sqlToQuery(s);n=t.sql,e=t.params;}else if(s&&typeof s.toSQL=="function"){let t=s.toSQL();n=t.sql,e=t.params||[];}else n=String(s);let o=this.rawClient||this.client;if(o?.prepare&&typeof o.prepare=="function"){let t=o.prepare(n);return (e.length>0?await t.bind(...e).all():await t.all()).results||[]}if(typeof this.client?.execute=="function"){let t=await this.client.execute(s);return Array.isArray(t)?t:Array.isArray(t?.rows)?t.rows:Array.isArray(t?.[0])?t[0]:[]}return []}};function he(m){return new x(m)}exports.a=w;exports.b=B;exports.c=x;exports.d=he;
@@ -1 +1 @@
1
- 'use strict';var chunkMCK2QRAU_cjs=require('./chunk-MCK2QRAU.cjs'),chunkVPBGZW4P_cjs=require('./chunk-VPBGZW4P.cjs'),chunkO2SA56P2_cjs=require('./chunk-O2SA56P2.cjs'),chunkPW6Y5MQL_cjs=require('./chunk-PW6Y5MQL.cjs'),chunkGWUHIIPO_cjs=require('./chunk-GWUHIIPO.cjs'),chunk3A5UO6OQ_cjs=require('./chunk-3A5UO6OQ.cjs'),chunkUE7DTBD7_cjs=require('./chunk-UE7DTBD7.cjs'),m=require('kyro:config');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var m__default=/*#__PURE__*/_interopDefault(m);exports.a=null;var c=null;async function T(){if(!exports.a){if(globalThis.__KYRO_INSTANCE__)try{await globalThis.__KYRO_INSTANCE__.shutdown();}catch{}try{let e=m__default.default.default||m__default.default,t=e.adapter,r=t&&!t.dialect&&typeof t.connect=="function";if(globalThis.DB&&(!t||r)){let s=globalThis.DB;e.adapter=new chunkGWUHIIPO_cjs.c({type:"sqlite",client:s}),chunkMCK2QRAU_cjs.J.info("Hot-swapped to D1 DrizzleAdapter");}exports.a=chunkMCK2QRAU_cjs.G(e),await exports.a.init();let a=e.adapter,p=a&&a.dialect&&(a.dialect==="postgres"||a.dialect==="sqlite"),l=a&&a.dialect==="mongodb",o;if(p)a.dialect==="postgres"?o=new chunk3A5UO6OQ_cjs.a({db:a.client}):a.dialect==="sqlite"&&(o=new chunkO2SA56P2_cjs.m({db:a.rawClient||a.client}));else if(r&&!globalThis.DB){let s=process.env.KYRO_AUTH_DB_PATH||"./data/auth.db";o=new chunkPW6Y5MQL_cjs.a({path:s});}else l&&(o=new chunkUE7DTBD7_cjs.a({adapter:a}));if(o?.connect)try{await o.connect();}catch(s){chunkMCK2QRAU_cjs.J.warn("Auth connect warning:",s);}try{await exports.a.loadSettings();}catch(s){chunkMCK2QRAU_cjs.J.warn("loadSettings warning:",s);}try{await chunkVPBGZW4P_cjs.e(o);}catch(s){chunkMCK2QRAU_cjs.J.warn("autoBootstrap warning:",s);}globalThis.__KYRO_INSTANCE__=exports.a;}catch(e){throw exports.a=null,c=null,chunkMCK2QRAU_cjs.J.error("Init failed, will retry:",e),e}}}async function b(e){let t=globalThis.DB?globalThis:null;try{let{env:r}=await import('cloudflare:workers');r&&(t=r);}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),c||(c=T()),await c;}var w={graphqlEnabled:false,trpcEnabled:false,wsEnabled:false,requireAuth:false};function _(e){return exports.a?exports.a.settings?.access?.apiAccess?.[e]??w[e]??true:w[e]??true}var E=async e=>{if(!exports.a)try{await Promise.race([b(e),new Promise((t,r)=>setTimeout(()=>r(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 r=new URL(e.request.url).pathname,a=__KYRO_API_PATH__;if(r===`${a}/graphql`&&typeof exports.a.getGraphQL=="function"){if(!_("graphqlEnabled"))return new Response(JSON.stringify({error:"GraphQL is disabled"}),{status:503,headers:{"Content-Type":"application/json"}});let o=await exports.a.getGraphQL().fetch(e.request,e.locals);return new Response(o.body,o)}if(r.startsWith(`${a}/trpc/`)&&typeof exports.a.getTRPC=="function"){if(!_("trpcEnabled"))return new Response(JSON.stringify({error:"tRPC is disabled"}),{status:503,headers:{"Content-Type":"application/json"}});let o=await exports.a.getTRPC().fetch(e.request,e.locals);return new Response(o.body,o)}return await(await exports.a.getREST()).fetch(e.request,e.locals)}catch(t){let r=process.env.NODE_ENV==="production";return console.error("[Kyro API Execution Error]:",t?.stack||t?.message||t),new Response(JSON.stringify({error:"Internal Server Error",message:r?"An unexpected error occurred":t?.message||String(t),...r?{}:{stack:t?.stack}}),{status:500,headers:{"Content-Type":"application/json"}})}},N=E;exports.b=b;exports.c=E;exports.d=N;
1
+ 'use strict';var chunkV7E74PHS_cjs=require('./chunk-V7E74PHS.cjs'),chunkVPBGZW4P_cjs=require('./chunk-VPBGZW4P.cjs'),chunkO2SA56P2_cjs=require('./chunk-O2SA56P2.cjs'),chunkPW6Y5MQL_cjs=require('./chunk-PW6Y5MQL.cjs'),chunk3BDAH6FD_cjs=require('./chunk-3BDAH6FD.cjs'),chunk3A5UO6OQ_cjs=require('./chunk-3A5UO6OQ.cjs'),chunkUE7DTBD7_cjs=require('./chunk-UE7DTBD7.cjs'),m=require('kyro:config');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var m__default=/*#__PURE__*/_interopDefault(m);exports.a=null;var c=null;async function T(){if(!exports.a){if(globalThis.__KYRO_INSTANCE__)try{await globalThis.__KYRO_INSTANCE__.shutdown();}catch{}try{let e=m__default.default.default||m__default.default,t=e.adapter,r=t&&!t.dialect&&typeof t.connect=="function";if(globalThis.DB&&(!t||r)){let s=globalThis.DB;e.adapter=new chunk3BDAH6FD_cjs.c({type:"sqlite",client:s}),chunkV7E74PHS_cjs.G.info("Hot-swapped to D1 DrizzleAdapter");}exports.a=chunkV7E74PHS_cjs.D(e),await exports.a.init();let a=e.adapter,p=a&&a.dialect&&(a.dialect==="postgres"||a.dialect==="sqlite"),l=a&&a.dialect==="mongodb",o;if(p)a.dialect==="postgres"?o=new chunk3A5UO6OQ_cjs.a({db:a.client}):a.dialect==="sqlite"&&(o=new chunkO2SA56P2_cjs.m({db:a.rawClient||a.client}));else if(r&&!globalThis.DB){let s=process.env.KYRO_AUTH_DB_PATH||"./data/auth.db";o=new chunkPW6Y5MQL_cjs.a({path:s});}else l&&(o=new chunkUE7DTBD7_cjs.a({adapter:a}));if(o?.connect)try{await o.connect();}catch(s){chunkV7E74PHS_cjs.G.warn("Auth connect warning:",s);}try{await exports.a.loadSettings();}catch(s){chunkV7E74PHS_cjs.G.warn("loadSettings warning:",s);}try{await chunkVPBGZW4P_cjs.e(o);}catch(s){chunkV7E74PHS_cjs.G.warn("autoBootstrap warning:",s);}globalThis.__KYRO_INSTANCE__=exports.a;}catch(e){throw exports.a=null,c=null,chunkV7E74PHS_cjs.G.error("Init failed, will retry:",e),e}}}async function b(e){let t=globalThis.DB?globalThis:null;try{let{env:r}=await import('cloudflare:workers');r&&(t=r);}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),c||(c=T()),await c;}var w={graphqlEnabled:false,trpcEnabled:false,wsEnabled:false,requireAuth:false};function _(e){return exports.a?exports.a.settings?.access?.apiAccess?.[e]??w[e]??true:w[e]??true}var E=async e=>{if(!exports.a)try{await Promise.race([b(e),new Promise((t,r)=>setTimeout(()=>r(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 r=new URL(e.request.url).pathname,a=__KYRO_API_PATH__;if(r===`${a}/graphql`&&typeof exports.a.getGraphQL=="function"){if(!_("graphqlEnabled"))return new Response(JSON.stringify({error:"GraphQL is disabled"}),{status:503,headers:{"Content-Type":"application/json"}});let o=await exports.a.getGraphQL().fetch(e.request,e.locals);return new Response(o.body,o)}if(r.startsWith(`${a}/trpc/`)&&typeof exports.a.getTRPC=="function"){if(!_("trpcEnabled"))return new Response(JSON.stringify({error:"tRPC is disabled"}),{status:503,headers:{"Content-Type":"application/json"}});let o=await exports.a.getTRPC().fetch(e.request,e.locals);return new Response(o.body,o)}return await(await exports.a.getREST()).fetch(e.request,e.locals)}catch(t){let r=process.env.NODE_ENV==="production";return console.error("[Kyro API Execution Error]:",t?.stack||t?.message||t),new Response(JSON.stringify({error:"Internal Server Error",message:r?"An unexpected error occurred":t?.message||String(t),...r?{}:{stack:t?.stack}}),{status:500,headers:{"Content-Type":"application/json"}})}},N=E;exports.b=b;exports.c=E;exports.d=N;
@@ -1,4 +1,4 @@
1
- 'use strict';var chunkYOJOVQIH_cjs=require('./chunk-YOJOVQIH.cjs'),chunkO4PPZOVI_cjs=require('./chunk-O4PPZOVI.cjs'),chunkOXEJCIOA_cjs=require('./chunk-OXEJCIOA.cjs'),module$1=require('module'),crypto=require('crypto');function P(T,t){let i=t,n=T[i.name];if(i.type==="json"||i.type==="richtext"||i.type==="array"||i.type==="group"||i.type==="blocks"||i.type==="list"||i.type==="relationship-block")try{n=n?JSON.parse(n):null;}catch{n=null;}if(i.type==="checkbox"&&(n=!!n),i.type==="date"&&n)try{let a=new Date(n);isNaN(a.getTime())?n=null:n=a.toISOString();}catch{n=null;}if((i.type==="upload"||i.type==="image")&&n)try{let a=JSON.parse(n);Array.isArray(a)?n=a.map(o=>typeof o=="object"&&o!==null?o:{id:o}):n=typeof a=="object"?a:{id:a};}catch{n=typeof n=="string"?{id:n}:n;}return n}var C;function w(){return C||(C=module$1.createRequire("file:///")("node:sqlite").DatabaseSync,C)}function R(T,t){try{return T.prepare(`PRAGMA table_info(${t})`).all().map(n=>n.name)}catch{return []}}var I=class extends chunkO4PPZOVI_cjs.a{db;path;migrations=new Map;versionsTableName="kyro_versions";constructor(t){super(),this.path=t.path,t.db?this.db=t.db:this.db=null;}async connect(){if(!this.db)this.db=new(w())(this.path||":memory:");else try{this.db.exec("SELECT 1");}catch{this.db=new(w())(this.path||":memory:");}if(this.db&&typeof this.db.prepare=="function"&&!this.db.prepare.__wrapped){let t=this.db.prepare.bind(this.db),i=n=>{let a=t(n),o=e=>typeof e=="boolean"?e?1:0:e===void 0?null:e;return new Proxy(a,{get(e,s,r){if(s==="all")return (...c)=>e.all(...c.map(o));if(s==="get")return (...c)=>e.get(...c.map(o));if(s==="run")return (...c)=>e.run(...c.map(o));let l=Reflect.get(e,s,r);return typeof l=="function"?l.bind(e):l}})};i.__wrapped=true,this.db.prepare=i;}this.db.exec("PRAGMA journal_mode = WAL"),this.db.exec("PRAGMA foreign_keys = ON"),this.connected=true;}async disconnect(){if(this.db){try{this.db.close();}catch{}this.db=null;}this.connected=false;}ensureTable(t,i){let n=i||this.getTableNameFor(t.slug),a=["id TEXT PRIMARY KEY"];for(let s of chunkYOJOVQIH_cjs.c(t.fields)){if(!s.name||s.name==="id")continue;let r=this.fieldToSQL(s);r&&a.push(r);}let o=chunkYOJOVQIH_cjs.c(t.fields);o.some(s=>s.name==="createdAt")||a.push(`${this.col("createdAt")} TEXT DEFAULT (datetime('now'))`),o.some(s=>s.name==="updatedAt")||a.push(`${this.col("updatedAt")} TEXT DEFAULT (datetime('now'))`),o.some(s=>s.name==="status")||a.push("status TEXT DEFAULT 'draft'"),o.some(s=>s.name==="hasDraft")||a.push("hasDraft INTEGER DEFAULT 0"),t.tenantScoped&&a.push("tenant_id TEXT NOT NULL");let e=R(this.db,n);if(e.length===0){let s=`CREATE TABLE IF NOT EXISTS ${n} (${a.join(", ")})`;this.db.exec(s),this.db.exec(`CREATE INDEX IF NOT EXISTS idx_${n}_status ON ${n}(status)`);for(let r of chunkYOJOVQIH_cjs.c(t.fields))r.name&&r.indexed&&this.db.exec(`CREATE INDEX IF NOT EXISTS idx_${n}_${r.name} ON ${n}(${this.col(r.name)})`),r.name&&r.unique&&this.db.exec(`CREATE UNIQUE INDEX IF NOT EXISTS idx_${n}_${r.name}_unique ON ${n}(${this.col(r.name)})`);}else {let s=new Set(e);for(let r of a){let l=r.split(" ")[0].replace(/^"/,"").replace(/"$/,"");if(!s.has(l)&&l!=="id")try{l==="status"?this.db.exec(`ALTER TABLE ${n} ADD COLUMN ${this.col(l)} TEXT DEFAULT 'published'`):l==="hasDraft"?this.db.exec(`ALTER TABLE ${n} ADD COLUMN ${this.col(l)} INTEGER DEFAULT 0`):this.db.exec(`ALTER TABLE ${n} ADD COLUMN ${this.col(l)} TEXT`);}catch{}}}this.migrations.set(n,true);}ensureVersionsTable(){this.db.exec(`
1
+ 'use strict';var chunkYOJOVQIH_cjs=require('./chunk-YOJOVQIH.cjs'),chunkO4PPZOVI_cjs=require('./chunk-O4PPZOVI.cjs'),chunkOXEJCIOA_cjs=require('./chunk-OXEJCIOA.cjs'),module$1=require('module'),crypto=require('crypto'),R=require('fs'),I=require('path');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var R__default=/*#__PURE__*/_interopDefault(R);var I__default=/*#__PURE__*/_interopDefault(I);function U(T,t){let i=t,n=T[i.name];if(i.type==="json"||i.type==="richtext"||i.type==="array"||i.type==="group"||i.type==="blocks"||i.type==="list"||i.type==="relationship-block")try{n=n?JSON.parse(n):null;}catch{n=null;}if(i.type==="checkbox"&&(n=!!n),i.type==="date"&&n)try{let a=new Date(n);isNaN(a.getTime())?n=null:n=a.toISOString();}catch{n=null;}if((i.type==="upload"||i.type==="image")&&n)try{let a=JSON.parse(n);Array.isArray(a)?n=a.map(o=>typeof o=="object"&&o!==null?o:{id:o}):n=typeof a=="object"?a:{id:a};}catch{n=typeof n=="string"?{id:n}:n;}return n}var C;function j(){return C||(C=module$1.createRequire("file:///")("node:sqlite").DatabaseSync,C)}function L(T,t){try{return T.prepare(`PRAGMA table_info(${t})`).all().map(n=>n.name)}catch{return []}}var O=class extends chunkO4PPZOVI_cjs.a{db;path;migrations=new Map;versionsTableName="kyro_versions";constructor(t){super(),this.path=t.path,t.db?this.db=t.db:this.db=null;}async connect(){let t=this.path||":memory:";if(t!==":memory:")try{!R__default.default.existsSync(t)&&R__default.default.existsSync(I__default.default.resolve("..",t))&&(t=I__default.default.resolve("..",t));let i=I__default.default.dirname(I__default.default.resolve(t));R__default.default.existsSync(i)||R__default.default.mkdirSync(i,{recursive:!0}),this.path=t;}catch{}if(!this.db)this.db=new(j())(t);else try{this.db.exec("SELECT 1");}catch{this.db=new(j())(t);}if(this.db&&typeof this.db.prepare=="function"&&!this.db.prepare.__wrapped){let i=this.db.prepare.bind(this.db),n=a=>{let o=i(a),e=s=>typeof s=="boolean"?s?1:0:s===void 0?null:s;return new Proxy(o,{get(s,r,l){if(r==="all")return (...d)=>s.all(...d.map(e));if(r==="get")return (...d)=>s.get(...d.map(e));if(r==="run")return (...d)=>s.run(...d.map(e));let c=Reflect.get(s,r,l);return typeof c=="function"?c.bind(s):c}})};n.__wrapped=true,this.db.prepare=n;}this.db.exec("PRAGMA journal_mode = WAL"),this.db.exec("PRAGMA foreign_keys = ON"),this.connected=true;}async disconnect(){if(this.db){try{this.db.close();}catch{}this.db=null;}this.connected=false;}ensureTable(t,i){let n=i||this.getTableNameFor(t.slug),a=["id TEXT PRIMARY KEY"];for(let s of chunkYOJOVQIH_cjs.c(t.fields)){if(!s.name||s.name==="id")continue;let r=this.fieldToSQL(s);r&&a.push(r);}let o=chunkYOJOVQIH_cjs.c(t.fields);o.some(s=>s.name==="createdAt")||a.push(`${this.col("createdAt")} TEXT DEFAULT (datetime('now'))`),o.some(s=>s.name==="updatedAt")||a.push(`${this.col("updatedAt")} TEXT DEFAULT (datetime('now'))`),o.some(s=>s.name==="status")||a.push("status TEXT DEFAULT 'draft'"),o.some(s=>s.name==="hasDraft")||a.push("hasDraft INTEGER DEFAULT 0"),t.tenantScoped&&a.push("tenant_id TEXT NOT NULL");let e=L(this.db,n);if(e.length===0){let s=`CREATE TABLE IF NOT EXISTS ${n} (${a.join(", ")})`;this.db.exec(s),this.db.exec(`CREATE INDEX IF NOT EXISTS idx_${n}_status ON ${n}(status)`);for(let r of chunkYOJOVQIH_cjs.c(t.fields))r.name&&r.indexed&&this.db.exec(`CREATE INDEX IF NOT EXISTS idx_${n}_${r.name} ON ${n}(${this.col(r.name)})`),r.name&&r.unique&&this.db.exec(`CREATE UNIQUE INDEX IF NOT EXISTS idx_${n}_${r.name}_unique ON ${n}(${this.col(r.name)})`);}else {let s=new Set(e);for(let r of a){let l=r.split(" ")[0].replace(/^"/,"").replace(/"$/,"");if(!s.has(l)&&l!=="id")try{l==="status"?this.db.exec(`ALTER TABLE ${n} ADD COLUMN ${this.col(l)} TEXT DEFAULT 'published'`):l==="hasDraft"?this.db.exec(`ALTER TABLE ${n} ADD COLUMN ${this.col(l)} INTEGER DEFAULT 0`):this.db.exec(`ALTER TABLE ${n} ADD COLUMN ${this.col(l)} TEXT`);}catch{}}}this.migrations.set(n,true);}ensureVersionsTable(){this.db.exec(`
2
2
  CREATE TABLE IF NOT EXISTS ${this.versionsTableName} (
3
3
  id TEXT PRIMARY KEY,
4
4
  collection_slug TEXT NOT NULL,
@@ -14,6 +14,6 @@
14
14
  created_at TEXT DEFAULT (datetime('now')),
15
15
  updated_at TEXT DEFAULT (datetime('now'))
16
16
  )
17
- `);try{this.db.exec(`ALTER TABLE ${this.versionsTableName} ADD COLUMN autosave INTEGER NOT NULL DEFAULT 0`);}catch{}this.db.exec(`CREATE INDEX IF NOT EXISTS idx_${this.versionsTableName}_doc ON ${this.versionsTableName}(collection_slug, document_id)`),this.db.exec(`CREATE INDEX IF NOT EXISTS idx_${this.versionsTableName}_status ON ${this.versionsTableName}(status)`),this.db.exec(`CREATE INDEX IF NOT EXISTS idx_${this.versionsTableName}_autosave ON ${this.versionsTableName}(autosave)`);}resolveCol(t,i){let n=i.replace(/^-/,""),a=R(this.db,t);if(!a.includes(n)){if(n==="created_at"&&a.includes("createdAt"))return '"createdAt"';if(n==="createdAt"&&a.includes("created_at"))return '"created_at"';if(n==="updated_at"&&a.includes("updatedAt"))return '"updatedAt"';if(n==="updatedAt"&&a.includes("updated_at"))return '"updated_at"'}return this.col(n)}col(t){return `"${t}"`}fieldToSQL(t){switch(t.type){case "text":case "email":case "password":case "textarea":case "color":case "icon":case "code":case "markdown":case "url":return this.col(t.name)+" TEXT";case "number":return this.col(t.name)+" REAL";case "checkbox":return this.col(t.name)+" INTEGER DEFAULT 0";case "date":return this.col(t.name)+" TEXT";case "select":case "radio":return this.col(t.name)+" TEXT";case "relationship":case "upload":case "image":return this.col(t.name)+" TEXT";case "json":case "richtext":case "array":case "group":case "blocks":return this.col(t.name)+" TEXT";default:return null}}parseGlobalsSlug(t){if(t.startsWith("_globals_")){let i=t.replace("_globals_","");return {isGlobal:true,globalSlug:i,tableName:`global_${i.replace(/-/g,"_")}`}}return {isGlobal:false,globalSlug:"",tableName:this.getTableNameFor(t)}}buildWhere(t,i){let n=[],a=[];for(let[o,e]of Object.entries(t)){let s=o.toUpperCase();if((s==="AND"||s==="OR")&&Array.isArray(e)){let l=[];for(let c of e)if(typeof c=="object"&&c!==null){let d=this.buildWhere(c,i);d.clause&&(l.push(`(${d.clause})`),a.push(...d.params));}l.length>0&&n.push(`(${l.join(` ${s} `)})`);continue}let r=this.resolveCol(i,o);typeof e=="object"&&e!==null&&!Array.isArray(e)?(e.equals!==void 0&&(n.push(`${r} = ?`),a.push(e.equals)),e.not_equals!==void 0&&(n.push(`${r} != ?`),a.push(e.not_equals)),e.in!==void 0&&Array.isArray(e.in)&&(e.in.length===0?n.push("1 = 0"):(n.push(`${r} IN (${e.in.map(()=>"?").join(", ")})`),a.push(...e.in))),e.contains!==void 0&&(n.push(`LOWER(${r}) LIKE LOWER(?)`),a.push(`%${e.contains}%`)),e.like!==void 0&&(n.push(`LOWER(${r}) LIKE LOWER(?)`),a.push(e.like)),e.greater_than!==void 0&&(n.push(`${r} > ?`),a.push(e.greater_than)),e.greater_than_equal!==void 0&&(n.push(`${r} >= ?`),a.push(e.greater_than_equal)),e.less_than!==void 0&&(n.push(`${r} < ?`),a.push(e.less_than)),e.less_than_equal!==void 0&&(n.push(`${r} <= ?`),a.push(e.less_than_equal))):e!==void 0&&(n.push(`${r} = ?`),a.push(e));}return {clause:n.join(" AND "),params:a}}async find(t){let{collection:i,where:n={},sort:a,limit:o=10,page:e=1,tenantId:s,select:r,draft:l=false}=t,c=this.parseGlobalsSlug(i),d=c.isGlobal?this.globals.get(c.globalSlug):this.getCollection(i);this.ensureTable(d,c.tableName);let m=c.tableName,h=`SELECT * FROM ${m}`,f=[],u=[],y={...n};this.tenantContext&&d.tenantScoped&&(y=chunkO4PPZOVI_cjs.c({where:y},i,this.tenantContext,chunkO4PPZOVI_cjs.b).where||{});let b=d.fields.find(p=>p.name==="status"),g=b?.type==="select"&&Array.isArray(b.options)&&b.options.some(p=>p.value==="published");if(!l&&g&&(u.push("status = ?"),f.push("published")),s&&d.tenantScoped&&(u.push("tenant_id = ?"),f.push(s)),y&&Object.keys(y).length>0){let p=this.buildWhere(y,m);p.clause&&(u.push(`(${p.clause})`),f.push(...p.params));}u.length>0&&(h+=` WHERE ${u.join(" AND ")}`);let O=a||"-createdAt",U=this.resolveCol(m,O),j=O.startsWith("-")?"DESC":"ASC";h+=` ORDER BY ${U} ${j}`;let M=h.replace("SELECT *","SELECT COUNT(*) as count"),A=this.db.prepare(M).get(...f)?.count||0;h+=" LIMIT ? OFFSET ?",f.push(o,(e-1)*o);let E=this.db.prepare(h).all(...f).map(p=>this.rowToDoc(p,d));return this.tenantContext&&!this.tenantContext.isSuperAdmin&&(E=E.filter(p=>chunkO4PPZOVI_cjs.d(p,i,this.tenantContext,chunkO4PPZOVI_cjs.b))),l&&(E=await Promise.all(E.map(async p=>{let S=this.db.prepare(`SELECT * FROM ${this.versionsTableName} WHERE collection_slug = ? AND document_id = ? AND tenant_id IS NULL ORDER BY version DESC LIMIT 1`).get(i,p.id);if(S){let V=S.data?JSON.parse(S.data):{};return chunkOXEJCIOA_cjs.a({...p,...V,status:p.status,_hasUnpublishedChanges:S.status==="draft"})}return p}))),E=E.map(p=>chunkOXEJCIOA_cjs.a(p)),{docs:E,totalDocs:A,limit:o,totalPages:Math.ceil(A/o),page:e,pagingCounter:(e-1)*o+1,hasPrevPage:e>1,hasNextPage:e<Math.ceil(A/o),prevPage:e>1?e-1:null,nextPage:e<Math.ceil(A/o)?e+1:null}}async findByID(t){let{collection:i,id:n,tenantId:a,draft:o=false}=t,e=this.parseGlobalsSlug(i),s=e.isGlobal?this.globals.get(e.globalSlug):this.getCollection(i);this.ensureTable(s,e.tableName);let l=`SELECT * FROM ${e.tableName} WHERE id = ?`,c=[n];if(this.tenantContext&&s.tenantScoped){let u={id:n,tenant_id:this.tenantContext.tenantId};if(!chunkO4PPZOVI_cjs.d(u,i,this.tenantContext,chunkO4PPZOVI_cjs.b))return null}let d=s.fields.find(u=>u.name==="status"),m=d?.type==="select"&&Array.isArray(d.options)&&d.options.some(u=>u.value==="published");!o&&m&&(l+=" AND status = ?",c.push("published")),a&&s.tenantScoped&&(l+=" AND tenant_id = ?",c.push(a));let h=this.db.prepare(l).get(...c);if(!h)return null;let f=this.rowToDoc(h,s);if(o){let u=this.db.prepare(`SELECT * FROM ${this.versionsTableName} WHERE collection_slug = ? AND document_id = ? AND tenant_id IS NULL ORDER BY version DESC LIMIT 1`).get(i,f.id);if(u){let y=u.data?JSON.parse(u.data):{};f={...f,...y,status:f.status,_hasUnpublishedChanges:u.status==="draft"};}}return chunkOXEJCIOA_cjs.a(f)}async create(t){let{collection:i,data:n,tenantId:a}=t,o=this.parseGlobalsSlug(i),e=o.isGlobal?this.globals.get(o.globalSlug):this.getCollection(i);this.ensureTable(e,o.tableName);let s=o.tableName,r=o.isGlobal?o.globalSlug:n.id||this.generateId(),l=this.prepareData(n,e);l.id=r;let c=new Date().toISOString();l.created_at=c,l.updated_at=c,a&&e.tenantScoped&&(l.tenant_id=a);let d=Object.keys(l),m=R(this.db,s),h={};for(let g of d)m.includes(g)&&(h[g]=l[g]);let f=Object.keys(h),u=f.map(g=>this.col(g)),y=f.map(()=>"?").join(", "),b=Object.values(h).map(g=>g!==null&&typeof g=="object"?JSON.stringify(g):g);return this.db.prepare(`INSERT OR REPLACE INTO ${s} (${u.join(", ")}) VALUES (${y})`).run(...b),this.ensureVersionsTable(),this.findByID({collection:i,id:r,tenantId:a,draft:true})}async update(t){let{collection:i,id:n,data:a,tenantId:o}=t,e=this.parseGlobalsSlug(i),s=e.isGlobal?this.globals.get(e.globalSlug):this.getCollection(i);this.ensureTable(s,e.tableName);let r=e.tableName,l=this.prepareData(a,s);l.updated_at=new Date().toISOString();let c=R(this.db,r),d={};for(let b of Object.keys(l))c.includes(b)&&(d[b]=l[b]);let h=Object.keys(d).map(b=>`${this.col(b)} = ?`).join(", "),f=Object.values(d).map(b=>b!==null&&typeof b=="object"?JSON.stringify(b):b),u=`UPDATE ${r} SET ${h} WHERE id = ?`,y=[...f,n];return o&&s.tenantScoped&&(u+=" AND tenant_id = ?",y.push(o)),this.db.prepare(u).run(...y),this.ensureVersionsTable(),this.findByID({collection:i,id:n,tenantId:o,draft:true})}async delete(t){let{collection:i,id:n,tenantId:a}=t,o=this.parseGlobalsSlug(i),e=o.isGlobal?this.globals.get(o.globalSlug):this.getCollection(i);this.ensureTable(e,o.tableName),this.ensureVersionsTable();let s=await this.findByID({collection:i,id:n,tenantId:a,draft:true});if(!s)throw new Error(`Document not found: ${i}/${n}`);let l=`DELETE FROM ${o.tableName} WHERE id = ?`,c=[n];return a&&e.tenantScoped&&(l+=" AND tenant_id = ?",c.push(a)),this.db.prepare(l).run(...c),s}async count(t){let{collection:i,tenantId:n}=t,a=this.parseGlobalsSlug(i),o=a.isGlobal?this.globals.get(a.globalSlug):this.getCollection(i);this.ensureTable(o,a.tableName);let e=a.tableName,s=`SELECT COUNT(*) as count FROM ${e}`,r=[],l=[];if(n&&o.tenantScoped&&(r.push("tenant_id = ?"),l.push(n)),t.where&&Object.keys(t.where).length>0){let d=this.buildWhere(t.where,e);d.clause&&(r.push(`(${d.clause})`),l.push(...d.params));}return r.length>0&&(s+=` WHERE ${r.join(" AND ")}`),this.db.prepare(s).get(...l)?.count||0}async findOne(t){let i=this.parseGlobalsSlug(t.collection);if(i.isGlobal){let a=this.globals.get(i.globalSlug);if(!a)throw new Error(`Global "${i.globalSlug}" not found in adapter`);this.ensureTable(a,i.tableName);let o=`SELECT * FROM ${i.tableName}`,e=[],s=[],r=a.fields.find(d=>d.name==="status"),l=r?.type==="select"&&Array.isArray(r.options)&&r.options.some(d=>d.value==="published");!t.draft&&a.versions&&l&&e.push("status = 'published'"),e.length>0&&(o+=` WHERE ${e.join(" AND ")}`),o+=" LIMIT 1";let c=this.db.prepare(o).get(...s);if(c){let d=this.rowToDoc(c,a);if(t.draft){let m=this.db.prepare(`SELECT * FROM ${this.versionsTableName} WHERE collection_slug = ? AND document_id = ? AND tenant_id IS NULL ORDER BY version DESC LIMIT 1`).get(t.collection,i.globalSlug);if(m){let h=m.data?JSON.parse(m.data):{};d={...d,...h,status:d.status,_hasUnpublishedChanges:m.status==="draft"};}}return d}return null}return (await this.find({...t,limit:1})).docs[0]||null}async findVersions(t){this.ensureVersionsTable();let{collection:i,documentId:n,tenantId:a,limit:o=20,page:e=1}=t,s=["collection_slug = ?","document_id = ?","autosave = 0"],r=[i,n];a?(s.push("tenant_id = ?"),r.push(a)):s.push("tenant_id IS NULL");let l=`WHERE ${s.join(" AND ")}`,d=this.db.prepare(`SELECT COUNT(*) as count FROM ${this.versionsTableName} ${l}`).get(...r)?.count||0,m=(e-1)*o;return {docs:this.db.prepare(`SELECT * FROM ${this.versionsTableName} ${l} ORDER BY version DESC LIMIT ? OFFSET ?`).all(...r,o,m).map(u=>this.rowToVersion(u)),totalDocs:d,limit:o,totalPages:Math.ceil(d/o),page:e,pagingCounter:(e-1)*o+1,hasPrevPage:e>1,hasNextPage:e<Math.ceil(d/o),prevPage:e>1?e-1:null,nextPage:e<Math.ceil(d/o)?e+1:null}}async findVersionByID(t){this.ensureVersionsTable();let i=this.db.prepare(`SELECT * FROM ${this.versionsTableName} WHERE id = ? AND collection_slug = ? LIMIT 1`).get(t.versionId,t.collection);return i?this.rowToVersion(i):null}async createVersion(t){this.ensureVersionsTable();let i=new Date().toISOString();if(t.autosave){let s=`SELECT * FROM ${this.versionsTableName} WHERE collection_slug = ? AND document_id = ? AND autosave = 1`,r=[t.collection,t.documentId];t.tenantId?(s+=" AND tenant_id = ?",r.push(t.tenantId)):s+=" AND tenant_id IS NULL",s+=" LIMIT 1";let l=this.db.prepare(s).get(...r);if(l){this.db.prepare(`UPDATE ${this.versionsTableName} SET data = ?, status = ?, updated_at = ? WHERE id = ?`).run(JSON.stringify(t.data),t.status,i,l.id);let c=await this.findVersionByID({collection:t.collection,versionId:l.id});if(c)return c}}let n=this.generateId(),o=(this.db.prepare(`SELECT version FROM ${this.versionsTableName} WHERE collection_slug = ? AND document_id = ? AND autosave = 0 ORDER BY version DESC LIMIT 1`).get(t.collection,t.documentId)?.version??0)+1;if(this.db.prepare(`INSERT INTO ${this.versionsTableName} (
17
+ `);try{this.db.exec(`ALTER TABLE ${this.versionsTableName} ADD COLUMN autosave INTEGER NOT NULL DEFAULT 0`);}catch{}this.db.exec(`CREATE INDEX IF NOT EXISTS idx_${this.versionsTableName}_doc ON ${this.versionsTableName}(collection_slug, document_id)`),this.db.exec(`CREATE INDEX IF NOT EXISTS idx_${this.versionsTableName}_status ON ${this.versionsTableName}(status)`),this.db.exec(`CREATE INDEX IF NOT EXISTS idx_${this.versionsTableName}_autosave ON ${this.versionsTableName}(autosave)`);}resolveCol(t,i){let n=i.replace(/^-/,""),a=L(this.db,t);if(!a.includes(n)){if(n==="created_at"&&a.includes("createdAt"))return '"createdAt"';if(n==="createdAt"&&a.includes("created_at"))return '"created_at"';if(n==="updated_at"&&a.includes("updatedAt"))return '"updatedAt"';if(n==="updatedAt"&&a.includes("updated_at"))return '"updated_at"'}return this.col(n)}col(t){return `"${t}"`}fieldToSQL(t){switch(t.type){case "text":case "email":case "password":case "textarea":case "color":case "icon":case "code":case "markdown":case "url":return this.col(t.name)+" TEXT";case "number":return this.col(t.name)+" REAL";case "checkbox":return this.col(t.name)+" INTEGER DEFAULT 0";case "date":return this.col(t.name)+" TEXT";case "select":case "radio":return this.col(t.name)+" TEXT";case "relationship":case "upload":case "image":return this.col(t.name)+" TEXT";case "json":case "richtext":case "array":case "group":case "blocks":return this.col(t.name)+" TEXT";default:return null}}parseGlobalsSlug(t){if(t.startsWith("_globals_")){let i=t.replace("_globals_","");return {isGlobal:true,globalSlug:i,tableName:`global_${i.replace(/-/g,"_")}`}}return {isGlobal:false,globalSlug:"",tableName:this.getTableNameFor(t)}}buildWhere(t,i){let n=[],a=[];for(let[o,e]of Object.entries(t)){let s=o.toUpperCase();if((s==="AND"||s==="OR")&&Array.isArray(e)){let l=[];for(let c of e)if(typeof c=="object"&&c!==null){let d=this.buildWhere(c,i);d.clause&&(l.push(`(${d.clause})`),a.push(...d.params));}l.length>0&&n.push(`(${l.join(` ${s} `)})`);continue}let r=this.resolveCol(i,o);typeof e=="object"&&e!==null&&!Array.isArray(e)?(e.equals!==void 0&&(n.push(`${r} = ?`),a.push(e.equals)),e.not_equals!==void 0&&(n.push(`${r} != ?`),a.push(e.not_equals)),e.in!==void 0&&Array.isArray(e.in)&&(e.in.length===0?n.push("1 = 0"):(n.push(`${r} IN (${e.in.map(()=>"?").join(", ")})`),a.push(...e.in))),e.contains!==void 0&&(n.push(`LOWER(${r}) LIKE LOWER(?)`),a.push(`%${e.contains}%`)),e.like!==void 0&&(n.push(`LOWER(${r}) LIKE LOWER(?)`),a.push(e.like)),e.greater_than!==void 0&&(n.push(`${r} > ?`),a.push(e.greater_than)),e.greater_than_equal!==void 0&&(n.push(`${r} >= ?`),a.push(e.greater_than_equal)),e.less_than!==void 0&&(n.push(`${r} < ?`),a.push(e.less_than)),e.less_than_equal!==void 0&&(n.push(`${r} <= ?`),a.push(e.less_than_equal))):e!==void 0&&(n.push(`${r} = ?`),a.push(e));}return {clause:n.join(" AND "),params:a}}async find(t){let{collection:i,where:n={},sort:a,limit:o=10,page:e=1,tenantId:s,select:r,draft:l=false}=t,c=this.parseGlobalsSlug(i),d=c.isGlobal?this.globals.get(c.globalSlug):this.getCollection(i);this.ensureTable(d,c.tableName);let m=c.tableName,h=`SELECT * FROM ${m}`,f=[],u=[],y={...n};this.tenantContext&&d.tenantScoped&&(y=chunkO4PPZOVI_cjs.c({where:y},i,this.tenantContext,chunkO4PPZOVI_cjs.b).where||{});let b=d.fields.find(p=>p.name==="status"),g=b?.type==="select"&&Array.isArray(b.options)&&b.options.some(p=>p.value==="published");if(!l&&g&&(u.push("status = ?"),f.push("published")),s&&d.tenantScoped&&(u.push("tenant_id = ?"),f.push(s)),y&&Object.keys(y).length>0){let p=this.buildWhere(y,m);p.clause&&(u.push(`(${p.clause})`),f.push(...p.params));}u.length>0&&(h+=` WHERE ${u.join(" AND ")}`);let F=a||"-createdAt",M=this.resolveCol(m,F),V=F.startsWith("-")?"DESC":"ASC";h+=` ORDER BY ${M} ${V}`;let X=h.replace("SELECT *","SELECT COUNT(*) as count"),A=this.db.prepare(X).get(...f)?.count||0;h+=" LIMIT ? OFFSET ?",f.push(o,(e-1)*o);let E=this.db.prepare(h).all(...f).map(p=>this.rowToDoc(p,d));return this.tenantContext&&!this.tenantContext.isSuperAdmin&&(E=E.filter(p=>chunkO4PPZOVI_cjs.d(p,i,this.tenantContext,chunkO4PPZOVI_cjs.b))),l&&(E=await Promise.all(E.map(async p=>{let S=this.db.prepare(`SELECT * FROM ${this.versionsTableName} WHERE collection_slug = ? AND document_id = ? AND tenant_id IS NULL ORDER BY version DESC LIMIT 1`).get(i,p.id);if(S){let k=S.data?JSON.parse(S.data):{};return chunkOXEJCIOA_cjs.a({...p,...k,status:p.status,_hasUnpublishedChanges:S.status==="draft"})}return p}))),E=E.map(p=>chunkOXEJCIOA_cjs.a(p)),{docs:E,totalDocs:A,limit:o,totalPages:Math.ceil(A/o),page:e,pagingCounter:(e-1)*o+1,hasPrevPage:e>1,hasNextPage:e<Math.ceil(A/o),prevPage:e>1?e-1:null,nextPage:e<Math.ceil(A/o)?e+1:null}}async findByID(t){let{collection:i,id:n,tenantId:a,draft:o=false}=t,e=this.parseGlobalsSlug(i),s=e.isGlobal?this.globals.get(e.globalSlug):this.getCollection(i);this.ensureTable(s,e.tableName);let l=`SELECT * FROM ${e.tableName} WHERE id = ?`,c=[n];if(this.tenantContext&&s.tenantScoped){let u={id:n,tenant_id:this.tenantContext.tenantId};if(!chunkO4PPZOVI_cjs.d(u,i,this.tenantContext,chunkO4PPZOVI_cjs.b))return null}let d=s.fields.find(u=>u.name==="status"),m=d?.type==="select"&&Array.isArray(d.options)&&d.options.some(u=>u.value==="published");!o&&m&&(l+=" AND status = ?",c.push("published")),a&&s.tenantScoped&&(l+=" AND tenant_id = ?",c.push(a));let h=this.db.prepare(l).get(...c);if(!h)return null;let f=this.rowToDoc(h,s);if(o){let u=this.db.prepare(`SELECT * FROM ${this.versionsTableName} WHERE collection_slug = ? AND document_id = ? AND tenant_id IS NULL ORDER BY version DESC LIMIT 1`).get(i,f.id);if(u){let y=u.data?JSON.parse(u.data):{};f={...f,...y,status:f.status,_hasUnpublishedChanges:u.status==="draft"};}}return chunkOXEJCIOA_cjs.a(f)}async create(t){let{collection:i,data:n,tenantId:a}=t,o=this.parseGlobalsSlug(i),e=o.isGlobal?this.globals.get(o.globalSlug):this.getCollection(i);this.ensureTable(e,o.tableName);let s=o.tableName,r=o.isGlobal?o.globalSlug:n.id||this.generateId(),l=this.prepareData(n,e);l.id=r;let c=new Date().toISOString();l.created_at=c,l.updated_at=c,a&&e.tenantScoped&&(l.tenant_id=a);let d=Object.keys(l),m=L(this.db,s),h={};for(let g of d)m.includes(g)&&(h[g]=l[g]);let f=Object.keys(h),u=f.map(g=>this.col(g)),y=f.map(()=>"?").join(", "),b=Object.values(h).map(g=>g!==null&&typeof g=="object"?JSON.stringify(g):g);return this.db.prepare(`INSERT OR REPLACE INTO ${s} (${u.join(", ")}) VALUES (${y})`).run(...b),this.ensureVersionsTable(),this.findByID({collection:i,id:r,tenantId:a,draft:true})}async update(t){let{collection:i,id:n,data:a,tenantId:o}=t,e=this.parseGlobalsSlug(i),s=e.isGlobal?this.globals.get(e.globalSlug):this.getCollection(i);this.ensureTable(s,e.tableName);let r=e.tableName,l=this.prepareData(a,s);l.updated_at=new Date().toISOString();let c=L(this.db,r),d={};for(let b of Object.keys(l))c.includes(b)&&(d[b]=l[b]);let h=Object.keys(d).map(b=>`${this.col(b)} = ?`).join(", "),f=Object.values(d).map(b=>b!==null&&typeof b=="object"?JSON.stringify(b):b),u=`UPDATE ${r} SET ${h} WHERE id = ?`,y=[...f,n];return o&&s.tenantScoped&&(u+=" AND tenant_id = ?",y.push(o)),this.db.prepare(u).run(...y),this.ensureVersionsTable(),this.findByID({collection:i,id:n,tenantId:o,draft:true})}async delete(t){let{collection:i,id:n,tenantId:a}=t,o=this.parseGlobalsSlug(i),e=o.isGlobal?this.globals.get(o.globalSlug):this.getCollection(i);this.ensureTable(e,o.tableName),this.ensureVersionsTable();let s=await this.findByID({collection:i,id:n,tenantId:a,draft:true});if(!s)throw new Error(`Document not found: ${i}/${n}`);let l=`DELETE FROM ${o.tableName} WHERE id = ?`,c=[n];return a&&e.tenantScoped&&(l+=" AND tenant_id = ?",c.push(a)),this.db.prepare(l).run(...c),s}async count(t){let{collection:i,tenantId:n}=t,a=this.parseGlobalsSlug(i),o=a.isGlobal?this.globals.get(a.globalSlug):this.getCollection(i);this.ensureTable(o,a.tableName);let e=a.tableName,s=`SELECT COUNT(*) as count FROM ${e}`,r=[],l=[];if(n&&o.tenantScoped&&(r.push("tenant_id = ?"),l.push(n)),t.where&&Object.keys(t.where).length>0){let d=this.buildWhere(t.where,e);d.clause&&(r.push(`(${d.clause})`),l.push(...d.params));}return r.length>0&&(s+=` WHERE ${r.join(" AND ")}`),this.db.prepare(s).get(...l)?.count||0}async findOne(t){let i=this.parseGlobalsSlug(t.collection);if(i.isGlobal){let a=this.globals.get(i.globalSlug);if(!a)throw new Error(`Global "${i.globalSlug}" not found in adapter`);this.ensureTable(a,i.tableName);let o=`SELECT * FROM ${i.tableName}`,e=[],s=[],r=a.fields.find(d=>d.name==="status"),l=r?.type==="select"&&Array.isArray(r.options)&&r.options.some(d=>d.value==="published");!t.draft&&a.versions&&l&&e.push("status = 'published'"),e.length>0&&(o+=` WHERE ${e.join(" AND ")}`),o+=" LIMIT 1";let c=this.db.prepare(o).get(...s);if(c){let d=this.rowToDoc(c,a);if(t.draft){let m=this.db.prepare(`SELECT * FROM ${this.versionsTableName} WHERE collection_slug = ? AND document_id = ? AND tenant_id IS NULL ORDER BY version DESC LIMIT 1`).get(t.collection,i.globalSlug);if(m){let h=m.data?JSON.parse(m.data):{};d={...d,...h,status:d.status,_hasUnpublishedChanges:m.status==="draft"};}}return d}return null}return (await this.find({...t,limit:1})).docs[0]||null}async findVersions(t){this.ensureVersionsTable();let{collection:i,documentId:n,tenantId:a,limit:o=20,page:e=1}=t,s=["collection_slug = ?","document_id = ?","autosave = 0"],r=[i,n];a?(s.push("tenant_id = ?"),r.push(a)):s.push("tenant_id IS NULL");let l=`WHERE ${s.join(" AND ")}`,d=this.db.prepare(`SELECT COUNT(*) as count FROM ${this.versionsTableName} ${l}`).get(...r)?.count||0,m=(e-1)*o;return {docs:this.db.prepare(`SELECT * FROM ${this.versionsTableName} ${l} ORDER BY version DESC LIMIT ? OFFSET ?`).all(...r,o,m).map(u=>this.rowToVersion(u)),totalDocs:d,limit:o,totalPages:Math.ceil(d/o),page:e,pagingCounter:(e-1)*o+1,hasPrevPage:e>1,hasNextPage:e<Math.ceil(d/o),prevPage:e>1?e-1:null,nextPage:e<Math.ceil(d/o)?e+1:null}}async findVersionByID(t){this.ensureVersionsTable();let i=this.db.prepare(`SELECT * FROM ${this.versionsTableName} WHERE id = ? AND collection_slug = ? LIMIT 1`).get(t.versionId,t.collection);return i?this.rowToVersion(i):null}async createVersion(t){this.ensureVersionsTable();let i=new Date().toISOString();if(t.autosave){let s=`SELECT * FROM ${this.versionsTableName} WHERE collection_slug = ? AND document_id = ? AND autosave = 1`,r=[t.collection,t.documentId];t.tenantId?(s+=" AND tenant_id = ?",r.push(t.tenantId)):s+=" AND tenant_id IS NULL",s+=" LIMIT 1";let l=this.db.prepare(s).get(...r);if(l){this.db.prepare(`UPDATE ${this.versionsTableName} SET data = ?, status = ?, updated_at = ? WHERE id = ?`).run(JSON.stringify(t.data),t.status,i,l.id);let c=await this.findVersionByID({collection:t.collection,versionId:l.id});if(c)return c}}let n=this.generateId(),o=(this.db.prepare(`SELECT version FROM ${this.versionsTableName} WHERE collection_slug = ? AND document_id = ? AND autosave = 0 ORDER BY version DESC LIMIT 1`).get(t.collection,t.documentId)?.version??0)+1;if(this.db.prepare(`INSERT INTO ${this.versionsTableName} (
18
18
  id, collection_slug, document_id, tenant_id, version, status, autosave, data, created_by, change_description, published_at, created_at, updated_at
19
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(n,t.collection,t.documentId,t.tenantId??null,o,t.status,t.autosave?1:0,JSON.stringify(t.data),t.createdBy??null,t.changeDescription??null,t.status==="published"?i:null,i,i),!t.autosave){let r=this.collections.get(t.collection)?.versions?.maxPerDoc;r&&r>0&&await this.deleteVersions({collection:t.collection,documentId:t.documentId,keepLatest:r,tenantId:t.tenantId});}return await this.findVersionByID({collection:t.collection,versionId:n})}async updateLatestVersion(t){return this.createVersion({...t,autosave:true})}async deleteVersions(t){this.ensureVersionsTable();let{collection:i,documentId:n,keepLatest:a,tenantId:o}=t;if(a&&a>0){let e=this.db.prepare(`SELECT id, status, autosave FROM ${this.versionsTableName} WHERE collection_slug = ? AND document_id = ? ORDER BY version DESC`).all(i,n),s=0,r=[];for(let l of e)l.status==="published"||l.autosave===1||(s++,s>a&&r.push(l.id));for(let l of r)this.db.prepare(`DELETE FROM ${this.versionsTableName} WHERE id = ?`).run(l);}else {let e=`DELETE FROM ${this.versionsTableName} WHERE collection_slug = ? AND document_id = ?`,s=[i,n];o&&(e+=" AND tenant_id = ?",s.push(o)),this.db.prepare(e).run(...s);}}rowToVersion(t){return {id:String(t.id),collection:t.collection_slug,documentId:t.document_id,version:t.version,status:t.status,data:t.data?JSON.parse(t.data):{},createdBy:t.created_by??void 0,changeDescription:t.change_description??void 0,publishedAt:t.published_at??null,createdAt:t.created_at,updatedAt:t.updated_at}}prepareData(t,i){let n={},a=chunkYOJOVQIH_cjs.c(i.fields),o=(e,s)=>{let r=e;if(r.type==="json"||r.type==="richtext"||r.type==="array"||r.type==="group"||r.type==="blocks"||r.type==="list"||r.type==="relationship-block")return s!=null?JSON.stringify(s):null;if(r.type==="checkbox")return s?1:0;if(r.type==="number")return s!==null&&s!==""?Number(s):null;if(r.type==="upload"||r.type==="image"){if(s==null)return null;if(Array.isArray(s)){let l=s.map(c=>typeof c=="string"?c:typeof c=="object"?c.id||c._id||c:String(c));return JSON.stringify(l)}return typeof s=="string"?s:typeof s=="object"?JSON.stringify(s):String(s)}else if(e.type==="relationship"){if(s==null)return null;if(Array.isArray(s)){let l=s.map(c=>typeof c=="string"?c:typeof c=="object"?JSON.stringify({relationTo:e.relationTo,value:c.id||c}):String(c));return JSON.stringify(l)}return typeof s=="string"?s:typeof s=="object"?JSON.stringify({relationTo:e.relationTo,value:s.id||s}):String(s)}return s};for(let e of a){if(!e.name||e.name==="id"||i.fields.some(l=>l.type==="tabs"&&l.name&&"tabs"in l&&l.tabs.some(c=>c.fields.some(d=>d.name===e.name))))continue;let r=t[e.name];r!==void 0&&(n[e.name]=o(e,r));}for(let e of i.fields)if(e.type==="tabs"&&"tabs"in e&&e.name){let s=t[e.name];if(s&&typeof s=="object"){for(let r of e.tabs)for(let l of r.fields)if(l.name&&l.name!=="id"){let c=s[l.name];c!==void 0&&(n[l.name]=o(l,c));}}}return n}rowToDoc(t,i){let n={id:t.id};for(let a of chunkYOJOVQIH_cjs.c(i.fields)){if(!a.name||a.name==="id")continue;let o=a,e=t[o.name];if(o.type==="json"||o.type==="richtext"||o.type==="array"||o.type==="group"||o.type==="blocks"||o.type==="list"||o.type==="relationship-block")try{e=e?JSON.parse(e):null;}catch{e=null;}if(o.type==="blocks"&&e&&Array.isArray(e)){let s=o.blocks||[];e=chunkYOJOVQIH_cjs.d(e,s);}if(a.type==="checkbox"&&(e=!!e),a.type==="date"&&e)try{let s=new Date(e);isNaN(s.getTime())?(console.warn(`[LocalAdapter] Invalid date value for field "${a.name}":`,e),e=null):e=s.toISOString();}catch{e=null;}if((a.type==="upload"||a.type==="image")&&e)try{let s=JSON.parse(e);Array.isArray(s)?e=s.map(r=>typeof r=="object"&&r!==null?r:{id:r}):e=typeof s=="object"?s:{id:s};}catch{e={id:e};}if(a.type==="relationship"&&e)try{let s=JSON.parse(e);Array.isArray(s),e=s;}catch{e={relationTo:Array.isArray(a.relationTo)?a.relationTo[0]:a.relationTo,value:e};}n[a.name]=e;}for(let a of i.fields)if(!(!a.name||a.name==="id"||a.name==="row"||a.name==="collapsible")&&a.type==="tabs"&&"tabs"in a){let o={};for(let e of a.tabs)for(let s of e.fields)s.name&&s.name!=="id"&&(o[s.name]=P(t,s));n[a.name]=o;}if(i.timestamps){let a=t.createdAt||t.created_at,o=t.updatedAt||t.updated_at;if(a)try{let e=new Date(a);isNaN(e.getTime())||(n.createdAt=e.toISOString());}catch{}if(o)try{let e=new Date(o);isNaN(e.getTime())||(n.updatedAt=e.toISOString());}catch{}}i.tenantScoped&&(n.tenantId=t.tenant_id),n.status=t.status??"published",n.hasDraft=t.hasDraft?!!t.hasDraft:false;for(let a of Object.keys(n))/^\d+$/.test(a)&&delete n[a];return n}generateId(){let t=Date.now().toString(16).padStart(12,"0"),i=crypto.randomBytes(6).toString("hex");return t+i}getMediaById(t){try{let i=this.getTableNameFor("media"),n=this.db.prepare(`SELECT id, url, thumbnail_url FROM ${i} WHERE id = ?`).get(t);if(n)return {id:n.id,url:n.url,thumbnailUrl:n.thumbnail_url||n.url}}catch{}return null}getTableNameFor(t){return t.replace(/-/g,"_")}async migrate(){for(let t of this.collections.values())this.ensureTable(t);}async rollback(){}async transaction(t){return new Promise((i,n)=>{let a=this.db.transaction(async()=>t({db:this.db}));try{let o=a();i(o);}catch(o){n(o);}})}getDatabase(){return this.db}exec(t){this.db.exec(t);}prepare(t){return this.db.prepare(t)}};function G(T){return new I(T||{})}exports.a=I;exports.b=G;
19
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(n,t.collection,t.documentId,t.tenantId??null,o,t.status,t.autosave?1:0,JSON.stringify(t.data),t.createdBy??null,t.changeDescription??null,t.status==="published"?i:null,i,i),!t.autosave){let r=this.collections.get(t.collection)?.versions?.maxPerDoc;r&&r>0&&await this.deleteVersions({collection:t.collection,documentId:t.documentId,keepLatest:r,tenantId:t.tenantId});}return await this.findVersionByID({collection:t.collection,versionId:n})}async updateLatestVersion(t){return this.createVersion({...t,autosave:true})}async deleteVersions(t){this.ensureVersionsTable();let{collection:i,documentId:n,keepLatest:a,tenantId:o}=t;if(a&&a>0){let e=this.db.prepare(`SELECT id, status, autosave FROM ${this.versionsTableName} WHERE collection_slug = ? AND document_id = ? ORDER BY version DESC`).all(i,n),s=0,r=[];for(let l of e)l.status==="published"||l.autosave===1||(s++,s>a&&r.push(l.id));for(let l of r)this.db.prepare(`DELETE FROM ${this.versionsTableName} WHERE id = ?`).run(l);}else {let e=`DELETE FROM ${this.versionsTableName} WHERE collection_slug = ? AND document_id = ?`,s=[i,n];o&&(e+=" AND tenant_id = ?",s.push(o)),this.db.prepare(e).run(...s);}}rowToVersion(t){return {id:String(t.id),collection:t.collection_slug,documentId:t.document_id,version:t.version,status:t.status,data:t.data?JSON.parse(t.data):{},createdBy:t.created_by??void 0,changeDescription:t.change_description??void 0,publishedAt:t.published_at??null,createdAt:t.created_at,updatedAt:t.updated_at}}prepareData(t,i){let n={},a=chunkYOJOVQIH_cjs.c(i.fields),o=(e,s)=>{let r=e;if(r.type==="json"||r.type==="richtext"||r.type==="array"||r.type==="group"||r.type==="blocks"||r.type==="list"||r.type==="relationship-block")return s!=null?JSON.stringify(s):null;if(r.type==="checkbox")return s?1:0;if(r.type==="number")return s!==null&&s!==""?Number(s):null;if(r.type==="upload"||r.type==="image"){if(s==null)return null;if(Array.isArray(s)){let l=s.map(c=>typeof c=="string"?c:typeof c=="object"?c.id||c._id||c:String(c));return JSON.stringify(l)}return typeof s=="string"?s:typeof s=="object"?JSON.stringify(s):String(s)}else if(e.type==="relationship"){if(s==null)return null;if(Array.isArray(s)){let l=s.map(c=>typeof c=="string"?c:typeof c=="object"?JSON.stringify({relationTo:e.relationTo,value:c.id||c}):String(c));return JSON.stringify(l)}return typeof s=="string"?s:typeof s=="object"?JSON.stringify({relationTo:e.relationTo,value:s.id||s}):String(s)}return s};for(let e of a){if(!e.name||e.name==="id"||i.fields.some(l=>l.type==="tabs"&&l.name&&"tabs"in l&&l.tabs.some(c=>c.fields.some(d=>d.name===e.name))))continue;let r=t[e.name];r!==void 0&&(n[e.name]=o(e,r));}for(let e of i.fields)if(e.type==="tabs"&&"tabs"in e&&e.name){let s=t[e.name];if(s&&typeof s=="object"){for(let r of e.tabs)for(let l of r.fields)if(l.name&&l.name!=="id"){let c=s[l.name];c!==void 0&&(n[l.name]=o(l,c));}}}return n}rowToDoc(t,i){let n={id:t.id};for(let a of chunkYOJOVQIH_cjs.c(i.fields)){if(!a.name||a.name==="id")continue;let o=a,e=t[o.name];if(o.type==="json"||o.type==="richtext"||o.type==="array"||o.type==="group"||o.type==="blocks"||o.type==="list"||o.type==="relationship-block")try{e=e?JSON.parse(e):null;}catch{e=null;}if(o.type==="blocks"&&e&&Array.isArray(e)){let s=o.blocks||[];e=chunkYOJOVQIH_cjs.d(e,s);}if(a.type==="checkbox"&&(e=!!e),a.type==="date"&&e)try{let s=new Date(e);isNaN(s.getTime())?(console.warn(`[LocalAdapter] Invalid date value for field "${a.name}":`,e),e=null):e=s.toISOString();}catch{e=null;}if((a.type==="upload"||a.type==="image")&&e)try{let s=JSON.parse(e);Array.isArray(s)?e=s.map(r=>typeof r=="object"&&r!==null?r:{id:r}):e=typeof s=="object"?s:{id:s};}catch{e={id:e};}if(a.type==="relationship"&&e)try{let s=JSON.parse(e);Array.isArray(s),e=s;}catch{e={relationTo:Array.isArray(a.relationTo)?a.relationTo[0]:a.relationTo,value:e};}n[a.name]=e;}for(let a of i.fields)if(!(!a.name||a.name==="id"||a.name==="row"||a.name==="collapsible")&&a.type==="tabs"&&"tabs"in a){let o={};for(let e of a.tabs)for(let s of e.fields)s.name&&s.name!=="id"&&(o[s.name]=U(t,s));n[a.name]=o;}if(i.timestamps){let a=t.createdAt||t.created_at,o=t.updatedAt||t.updated_at;if(a)try{let e=new Date(a);isNaN(e.getTime())||(n.createdAt=e.toISOString());}catch{}if(o)try{let e=new Date(o);isNaN(e.getTime())||(n.updatedAt=e.toISOString());}catch{}}i.tenantScoped&&(n.tenantId=t.tenant_id),n.status=t.status??"published",n.hasDraft=t.hasDraft?!!t.hasDraft:false;for(let a of Object.keys(n))/^\d+$/.test(a)&&delete n[a];return n}generateId(){let t=Date.now().toString(16).padStart(12,"0"),i=crypto.randomBytes(6).toString("hex");return t+i}getMediaById(t){try{let i=this.getTableNameFor("media"),n=this.db.prepare(`SELECT id, url, thumbnail_url FROM ${i} WHERE id = ?`).get(t);if(n)return {id:n.id,url:n.url,thumbnailUrl:n.thumbnail_url||n.url}}catch{}return null}getTableNameFor(t){return t.replace(/-/g,"_")}async migrate(){for(let t of this.collections.values())this.ensureTable(t);}async rollback(){}async transaction(t){return new Promise((i,n)=>{let a=this.db.transaction(async()=>t({db:this.db}));try{let o=a();i(o);}catch(o){n(o);}})}getDatabase(){return this.db}exec(t){this.db.exec(t);}prepare(t){return this.db.prepare(t)}};function W(T){return new O(T||{})}exports.a=O;exports.b=W;