@kyro-cms/core 0.13.5 → 0.13.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/api-handler-graphql.cjs +1 -1
- package/dist/api-handler-graphql.js +2 -2
- package/dist/api-handler-trpc.cjs +1 -1
- package/dist/api-handler-trpc.js +2 -2
- package/dist/api-handler.cjs +1 -1
- package/dist/api-handler.js +1 -1
- package/dist/auth-session-4WJUKESW.js +1 -0
- package/dist/auth-session-VHUHDBCL.cjs +1 -0
- package/dist/bootstrap-JYAUQ52D.cjs +1 -0
- package/dist/bootstrap-TTMLNQM3.js +1 -0
- package/dist/chunk-23RSKVJP.cjs +1 -0
- package/dist/chunk-24W5I6SJ.cjs +2 -0
- package/dist/{chunk-CH4TZZI5.js → chunk-2I2AXTKY.cjs} +38 -39
- package/dist/chunk-34LCWI5X.cjs +1 -0
- package/dist/chunk-3A5UO6OQ.cjs +114 -0
- package/dist/chunk-3N34WXBS.js +2 -0
- package/dist/chunk-3RIGRHON.js +109 -0
- package/dist/chunk-5BUAWCU6.js +91 -0
- package/dist/{chunk-7NKNSRCB.cjs → chunk-5I3BM5TV.js} +33 -32
- package/dist/chunk-5RBGM5N5.js +3 -0
- package/dist/chunk-7EY3GXRA.js +2 -0
- package/dist/chunk-7KTPBTH5.cjs +1 -0
- package/dist/chunk-A7763NCF.cjs +19 -0
- package/dist/chunk-AQWTJGML.cjs +1 -0
- package/dist/chunk-DCFOVCJX.cjs +1 -0
- package/dist/chunk-DCKJT247.cjs +1 -0
- package/dist/chunk-EG4SRTYS.cjs +2 -0
- package/dist/chunk-FAG2645P.js +2 -0
- package/dist/chunk-FIVTKI25.cjs +3 -0
- package/dist/chunk-FU76HURF.cjs +1 -0
- package/dist/chunk-GS4CMYKS.cjs +1 -0
- package/dist/chunk-GTAKGVUY.js +2 -0
- package/dist/chunk-GWUHIIPO.cjs +132 -0
- package/dist/chunk-H2IJDTA2.cjs +1 -0
- package/dist/chunk-HCM2G674.cjs +20 -0
- package/dist/chunk-I22MSXGL.js +2 -0
- package/dist/chunk-IIPSXKNV.js +115 -0
- package/dist/{chunk-WNU76M2C.js → chunk-IIVBEZC2.js} +6 -6
- package/dist/chunk-JHFD3IAU.cjs +1 -0
- package/dist/chunk-JJY2F6NL.cjs +3 -0
- package/dist/chunk-JQ4V2MGJ.cjs +2 -0
- package/dist/chunk-JXJTFBHG.js +3 -0
- package/dist/chunk-KOSR7235.cjs +1 -0
- package/dist/chunk-KUY4QDAL.js +2 -0
- package/dist/chunk-LGUHXOEW.js +3 -0
- package/dist/chunk-LXTVMP5F.cjs +6 -0
- package/dist/chunk-MCK2QRAU.cjs +4 -0
- package/dist/chunk-N2BMGZIX.cjs +90 -0
- package/dist/chunk-N7CDHWQH.cjs +2 -0
- package/dist/chunk-NGNXOXI5.js +2 -0
- package/dist/chunk-O2SA56P2.cjs +108 -0
- package/dist/chunk-O4PPZOVI.cjs +1 -0
- package/dist/chunk-O4RKZQYQ.js +2 -0
- package/dist/chunk-O6I26T6A.js +3 -0
- package/dist/chunk-OJBL4CXK.cjs +2 -0
- package/dist/chunk-OPKZYQV7.js +3 -0
- package/dist/chunk-OXEJCIOA.cjs +1 -0
- package/dist/chunk-OXH6CANN.js +2 -0
- package/dist/chunk-PPGZHOYR.cjs +1 -0
- package/dist/{chunk-EQN3HDES.cjs → chunk-PW6Y5MQL.cjs} +5 -5
- package/dist/chunk-RLW6AQF2.js +2 -0
- package/dist/chunk-SBFVITY2.js +7 -0
- package/dist/chunk-SEJ7LMYY.js +4 -0
- package/dist/chunk-SYE3OS5T.js +5 -0
- package/dist/chunk-SZY25KAE.js +21 -0
- package/dist/chunk-TJ6N5ZPZ.js +133 -0
- package/dist/chunk-TVWHTVLI.js +2 -0
- package/dist/chunk-UE7DTBD7.cjs +1 -0
- package/dist/chunk-V2RMDMWN.js +2 -0
- package/dist/chunk-V4SR7DU5.js +3 -0
- package/dist/chunk-VLFM66BZ.js +4 -0
- package/dist/chunk-VPBGZW4P.cjs +1 -0
- package/dist/chunk-W5GDZG64.js +2 -0
- package/dist/chunk-WLSVS3NC.js +2 -0
- package/dist/chunk-XL64URKD.cjs +2 -0
- package/dist/chunk-YNBJGPIU.js +2 -0
- package/dist/chunk-YNSKDTFG.js +2 -0
- package/dist/chunk-YOJOVQIH.cjs +1 -0
- package/dist/chunk-ZE2X3FBU.js +20 -0
- package/dist/chunk-ZMH35QYG.js +2 -0
- package/dist/cli/index.cjs +53 -182
- package/dist/cli/index.js +54 -183
- package/dist/drizzle/index.cjs +1 -1
- package/dist/drizzle/index.js +1 -1
- package/dist/fields/index.cjs +1 -1
- package/dist/fields/index.js +1 -1
- package/dist/graphql/index.cjs +1 -1
- package/dist/graphql/index.js +1 -1
- package/dist/index-B_39z2jP.d.cts +217 -0
- package/dist/index-xqpVL2Zq.d.ts +217 -0
- package/dist/index.cjs +30 -30
- package/dist/index.d.cts +2 -31
- package/dist/index.d.ts +2 -31
- package/dist/index.js +31 -31
- package/dist/integration.cjs +1 -1
- package/dist/integration.js +1 -1
- package/dist/local-DKP43BWQ.cjs +1 -0
- package/dist/local-TF5ZMHWW.js +1 -0
- package/dist/media-M3EIZ4QS.cjs +1 -0
- package/dist/media-WYEILC6K.js +1 -0
- package/dist/mongo-auth-adapter-22MV3TI3.cjs +1 -0
- package/dist/mongo-auth-adapter-66PWVRZW.js +1 -0
- package/dist/mongodb/index.cjs +1 -1
- package/dist/mongodb/index.d.cts +3 -130
- package/dist/mongodb/index.d.ts +3 -130
- package/dist/mongodb/index.js +1 -1
- package/dist/nodemailer-transport-7F3VLLBW.js +1 -0
- package/dist/nodemailer-transport-WAPZD3SJ.cjs +1 -0
- package/dist/postgres-auth-adapter-7BCPXNBO.js +1 -0
- package/dist/postgres-auth-adapter-HMXFUM5W.cjs +1 -0
- package/dist/redis-adapter-2E5AWMMA.cjs +1 -0
- package/dist/redis-adapter-GFH74CF4.js +1 -0
- package/dist/rest/index.cjs +1 -1
- package/dist/rest/index.js +1 -1
- package/dist/schema-FNIDQKIJ.cjs +1 -0
- package/dist/schema-KD736QFN.js +1 -0
- package/dist/sqlite-adapter-HL53RLSN.cjs +1 -0
- package/dist/sqlite-adapter-TT6ZASDG.js +1 -0
- package/dist/templates/index.cjs +1 -1
- package/dist/templates/index.js +1 -1
- package/dist/trpc/index.cjs +1 -1
- package/dist/trpc/index.js +1 -1
- package/dist/ws/index.cjs +1 -1
- package/dist/ws/index.js +1 -1
- package/package.json +2 -10
- package/dist/WebhookService-CGxHtw7E.d.cts +0 -143
- package/dist/WebhookService-CNC1lYz7.d.ts +0 -143
- package/dist/auth-session-DHVGXHOH.cjs +0 -1
- package/dist/auth-session-O7IIH7EP.js +0 -1
- package/dist/base-A9AJPCG5.d.ts +0 -219
- package/dist/base-C6wyX2nC.d.cts +0 -219
- package/dist/bcryptjs-WIQSWJGK.cjs +0 -1
- package/dist/bcryptjs-ZEEHSMAG.js +0 -2
- package/dist/better-sqlite3-5IISPX34.cjs +0 -1
- package/dist/better-sqlite3-B34RIU4C.js +0 -2
- package/dist/bootstrap-PG2LGDLB.js +0 -1
- package/dist/bootstrap-YD3GLTWX.cjs +0 -1
- package/dist/bowser-SB3ZUPO4.js +0 -11
- package/dist/bowser-VX6B6ZSE.cjs +0 -10
- package/dist/chokidar-5RVQZVHP.cjs +0 -5
- package/dist/chokidar-BOYGRT4Q.js +0 -6
- package/dist/chunk-262YP5XA.cjs +0 -1
- package/dist/chunk-2HA6EKXX.js +0 -24
- package/dist/chunk-2SPWRQ5O.js +0 -122
- package/dist/chunk-2TYITUOC.js +0 -122
- package/dist/chunk-35PGCW3S.cjs +0 -1
- package/dist/chunk-3CIMGC2F.cjs +0 -56
- package/dist/chunk-3KZXF4US.js +0 -2
- package/dist/chunk-3NSZZCOJ.js +0 -2
- package/dist/chunk-3TAUNYEM.js +0 -8
- package/dist/chunk-3VXEK5ZW.cjs +0 -1
- package/dist/chunk-47CXBWMA.js +0 -2
- package/dist/chunk-4BMWWGJN.js +0 -384
- package/dist/chunk-4NTIK6DF.cjs +0 -2
- package/dist/chunk-6E44MQQ5.js +0 -115
- package/dist/chunk-6LWF5MPL.js +0 -20
- package/dist/chunk-6NBZDW53.js +0 -133
- package/dist/chunk-6TPICJ2L.js +0 -7
- package/dist/chunk-6YS6XLOD.cjs +0 -121
- package/dist/chunk-73D2PNHD.cjs +0 -7
- package/dist/chunk-7ACHOBWY.cjs +0 -13
- package/dist/chunk-7GGZA5YU.cjs +0 -2
- package/dist/chunk-7JWQ2PZP.cjs +0 -1
- package/dist/chunk-7KLEANTO.cjs +0 -1
- package/dist/chunk-7MNDQU6K.js +0 -8
- package/dist/chunk-7NH7H3WA.js +0 -10
- package/dist/chunk-7WMMKGEO.cjs +0 -1
- package/dist/chunk-ALTU3FDG.js +0 -2
- package/dist/chunk-BAVN7VDR.cjs +0 -1
- package/dist/chunk-BCEE4NBZ.cjs +0 -2
- package/dist/chunk-BUNLC3II.cjs +0 -1
- package/dist/chunk-C7QCZX7X.js +0 -2
- package/dist/chunk-D6SDGHY6.js +0 -2
- package/dist/chunk-DVWYO3KK.cjs +0 -1
- package/dist/chunk-EHWUALGH.cjs +0 -1
- package/dist/chunk-EML5FDUU.js +0 -2
- package/dist/chunk-EN65ZEK2.cjs +0 -2
- package/dist/chunk-EW424IBO.cjs +0 -1
- package/dist/chunk-EZIDQBXI.cjs +0 -1
- package/dist/chunk-F2O4QO5N.cjs +0 -383
- package/dist/chunk-F4ITQ6XQ.cjs +0 -3
- package/dist/chunk-FK2BG4HU.js +0 -3
- package/dist/chunk-FLMUMPDE.js +0 -2
- package/dist/chunk-GIS6X43A.cjs +0 -3
- package/dist/chunk-GNEVCEJU.cjs +0 -3
- package/dist/chunk-GNOSG3PK.cjs +0 -1
- package/dist/chunk-GQGFNTDZ.js +0 -2
- package/dist/chunk-GTR7JAKP.cjs +0 -3
- package/dist/chunk-HPIJI7TM.js +0 -3
- package/dist/chunk-HPYH7GTS.cjs +0 -1
- package/dist/chunk-HRAY65XH.js +0 -3
- package/dist/chunk-HTYVI2HK.cjs +0 -9
- package/dist/chunk-IKGVPXMK.js +0 -3
- package/dist/chunk-J6V573PE.cjs +0 -1
- package/dist/chunk-JA44K75G.js +0 -2
- package/dist/chunk-JRUQ5ABB.js +0 -4
- package/dist/chunk-JV4HJBXW.js +0 -14
- package/dist/chunk-KEITOXIP.js +0 -2
- package/dist/chunk-KMFLHGD5.cjs +0 -1
- package/dist/chunk-KZHXYXSH.cjs +0 -10
- package/dist/chunk-L3Q64RUX.js +0 -3
- package/dist/chunk-LEBM6ZSZ.cjs +0 -10
- package/dist/chunk-LKRI5X2V.cjs +0 -1
- package/dist/chunk-LQ3YZTPU.cjs +0 -15
- package/dist/chunk-LVBHOZZF.js +0 -4
- package/dist/chunk-LWM4WABU.js +0 -3
- package/dist/chunk-LY7N3UHH.cjs +0 -23
- package/dist/chunk-MCIZG4A3.cjs +0 -1
- package/dist/chunk-MDLJTZLV.cjs +0 -1
- package/dist/chunk-N4FXLQE3.cjs +0 -132
- package/dist/chunk-N5POANYV.js +0 -2
- package/dist/chunk-NGNJSUGL.cjs +0 -1
- package/dist/chunk-NRE6VKL6.cjs +0 -121
- package/dist/chunk-O4YE57OS.cjs +0 -6
- package/dist/chunk-OBYAIJVU.js +0 -11
- package/dist/chunk-OLRCZ6E3.js +0 -2
- package/dist/chunk-OOVNTOZC.cjs +0 -56
- package/dist/chunk-P6JITOFF.js +0 -4
- package/dist/chunk-PITMDQYN.cjs +0 -18
- package/dist/chunk-PYUWSKKP.js +0 -57
- package/dist/chunk-Q5TFO66G.cjs +0 -1
- package/dist/chunk-QO5ZWQA3.cjs +0 -74
- package/dist/chunk-QYN6C3FZ.cjs +0 -114
- package/dist/chunk-REQ622YC.js +0 -3
- package/dist/chunk-RPRGGGIW.js +0 -11
- package/dist/chunk-RVBSJ4UQ.cjs +0 -7
- package/dist/chunk-RYHOWZLK.js +0 -2
- package/dist/chunk-RYXLEFS5.js +0 -2
- package/dist/chunk-SBNMXQNO.cjs +0 -2
- package/dist/chunk-SLMIYECU.js +0 -2
- package/dist/chunk-SRIXRJHL.js +0 -4
- package/dist/chunk-TBHNE4VV.js +0 -2
- package/dist/chunk-TCFL3UWT.cjs +0 -2
- package/dist/chunk-TYQYKKWJ.js +0 -16
- package/dist/chunk-U6KFONKM.js +0 -2
- package/dist/chunk-UNYXWPLZ.cjs +0 -2
- package/dist/chunk-UWHWSWDE.js +0 -2
- package/dist/chunk-V4FAL7AG.js +0 -2
- package/dist/chunk-VQ53TFYA.cjs +0 -1
- package/dist/chunk-VRZC4TTF.cjs +0 -1
- package/dist/chunk-W45TLOOT.js +0 -2
- package/dist/chunk-WAVGRSE6.js +0 -2
- package/dist/chunk-WPM6LFCY.js +0 -2
- package/dist/chunk-WXT2XW7T.js +0 -13
- package/dist/chunk-X473JI7Z.js +0 -75
- package/dist/chunk-X6HUA6EF.cjs +0 -20
- package/dist/chunk-XDPLVJRO.js +0 -21
- package/dist/chunk-XDQVYCIR.cjs +0 -1
- package/dist/chunk-XFYSADHV.cjs +0 -2
- package/dist/chunk-XOR64WUQ.cjs +0 -19
- package/dist/chunk-Y2YAKDEQ.js +0 -2
- package/dist/chunk-YENNL5HG.js +0 -2
- package/dist/chunk-YGI5W4RS.js +0 -2
- package/dist/chunk-YIFKTA5N.js +0 -57
- package/dist/chunk-YUUXFD73.js +0 -19
- package/dist/chunk-ZAKYTBEN.js +0 -3
- package/dist/chunk-ZHA446FA.cjs +0 -1
- package/dist/chunk-ZTLGK6R4.cjs +0 -12
- package/dist/chunk-ZUBJ6RLQ.cjs +0 -1
- package/dist/client.d.cts +0 -1291
- package/dist/client.d.ts +0 -1291
- package/dist/d1-5ZQJOFDX.cjs +0 -1
- package/dist/d1-HPB6B253.js +0 -2
- package/dist/dist-es-3SSNUZST.cjs +0 -1
- package/dist/dist-es-64F22JL2.js +0 -2
- package/dist/dist-es-A5OF2STN.cjs +0 -2
- package/dist/dist-es-BOW5V247.cjs +0 -6
- package/dist/dist-es-CRIMATLL.cjs +0 -2
- package/dist/dist-es-DL3VLVP6.cjs +0 -1
- package/dist/dist-es-F2ZR55UK.js +0 -4
- package/dist/dist-es-IPSSZNFP.js +0 -1
- package/dist/dist-es-M2F7M27Y.js +0 -2
- package/dist/dist-es-M66JKZF5.js +0 -7
- package/dist/dist-es-OKLLRYI3.js +0 -2
- package/dist/dist-es-P25IKLBI.cjs +0 -1
- package/dist/dist-es-SRPWSAF4.cjs +0 -1
- package/dist/dist-es-SVHZDVUF.js +0 -3
- package/dist/dist-es-T2H2W5BX.cjs +0 -3
- package/dist/dist-es-WFI55HKT.js +0 -3
- package/dist/drizzle-orm-47ELDEM6.cjs +0 -1
- package/dist/drizzle-orm-XRTSOQJS.js +0 -1
- package/dist/event-streams-7NAWZW2I.js +0 -1
- package/dist/event-streams-JBMWCI2O.cjs +0 -1
- package/dist/fs-KWBRQ6T6.js +0 -1
- package/dist/fs-ZQYOJOIO.cjs +0 -1
- package/dist/index-NGnJpSgf.d.ts +0 -105
- package/dist/index-Zrg3sZ6R.d.cts +0 -105
- package/dist/jsonwebtoken-DFB6ZBZA.cjs +0 -8
- package/dist/jsonwebtoken-OD67R5JS.js +0 -9
- package/dist/lib-A2D63VXD.cjs +0 -1
- package/dist/lib-JQD2JAOO.js +0 -2
- package/dist/loadSso-JY4WDQPS.cjs +0 -2
- package/dist/loadSso-UQR6545M.js +0 -3
- package/dist/local-6UUGBZ4M.js +0 -1
- package/dist/local-ZYHV3J2K.cjs +0 -1
- package/dist/media-3Z6YW5J4.cjs +0 -1
- package/dist/media-E762GEHL.js +0 -1
- package/dist/mongo-auth-adapter-2H2AXDRH.cjs +0 -1
- package/dist/mongo-auth-adapter-YWMEOC42.js +0 -1
- package/dist/nodemailer-IDML4L6W.cjs +0 -53
- package/dist/nodemailer-NITB45SS.js +0 -54
- package/dist/nodemailer-transport-3VWVUBM5.cjs +0 -1
- package/dist/nodemailer-transport-7RHATUKL.js +0 -1
- package/dist/postgres-auth-adapter-QKBNXVPT.js +0 -1
- package/dist/postgres-auth-adapter-WMLM4UUC.cjs +0 -1
- package/dist/postgres-js-7YBZKGXG.cjs +0 -1
- package/dist/postgres-js-JLFIWOBH.js +0 -1
- package/dist/redis-adapter-EVK2SMKH.cjs +0 -1
- package/dist/redis-adapter-LY2NBSAG.js +0 -1
- package/dist/schema-RT6WSUYC.cjs +0 -1
- package/dist/schema-YFMSJK2P.js +0 -2
- package/dist/signin-N3T2KF5Q.js +0 -3
- package/dist/signin-VFBLX7EL.cjs +0 -2
- package/dist/sqlite-adapter-KPSISY6E.cjs +0 -1
- package/dist/sqlite-adapter-PI6SIY7O.js +0 -1
- package/dist/src-6LAUXXDM.cjs +0 -1
- package/dist/src-QBADSZV4.js +0 -1
- package/dist/sso-oidc-54BIRYR6.cjs +0 -2
- package/dist/sso-oidc-UB7G4END.js +0 -3
- package/dist/sts-WAA6I22C.js +0 -3
- package/dist/sts-YLXXIB3X.cjs +0 -2
- package/dist/types-BCOhfwHC.d.ts +0 -839
- package/dist/types-DxaK39ix.d.cts +0 -330
- package/dist/types-DxaK39ix.d.ts +0 -330
- package/dist/types-QglJ7PwT.d.cts +0 -839
package/dist/chunk-4NTIK6DF.cjs
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
'use strict';var chunkF4ITQ6XQ_cjs=require('./chunk-F4ITQ6XQ.cjs'),chunkHTYVI2HK_cjs=require('./chunk-HTYVI2HK.cjs'),chunkBUNLC3II_cjs=require('./chunk-BUNLC3II.cjs'),crypto=require('crypto');chunkBUNLC3II_cjs.h();var g=chunkBUNLC3II_cjs.e(chunkHTYVI2HK_cjs.a(),1);var f="kyro:auth:",A=86400,x=604800,w=class{_redis=null;prefix;tokenExpiration;refreshExpiration;options;constructor(e={}){this.options=e,this.prefix=e.keyPrefix||f,this.tokenExpiration=e.tokenExpiration||A,this.refreshExpiration=e.refreshTokenExpiration||x;}async getRedis(){if(!this._redis){let e,t="ioredis";try{e=(await import(t)).Redis;}catch{chunkF4ITQ6XQ_cjs.a([t]),e=(await import(t)).Redis;}let s=this.options.url||`redis://${this.options.host||"localhost"}:${this.options.port||6379}`;this._redis=new e(s,{password:this.options.password,db:this.options.db,lazyConnect:true,tls:this.options.tls?{}:void 0});}return this._redis}async connect(){await this.getRedis();}async disconnect(){await(await this.getRedis()).quit();}userKey(e){return `${this.prefix}users:${e}`}sessionKey(e){return `${this.prefix}sessions:${e}`}refreshKey(e){return `${this.prefix}refresh:${e}`}userByEmailKey(e){return `${this.prefix}users:email:${e.toLowerCase()}`}passwordHistoryKey(e){return `${this.prefix}users:${e}:password_history`}async createUser(e){let t=crypto.randomBytes(16).toString("hex"),s=new Date().toISOString(),i=await this.hashPassword(e.password),r={id:t,email:e.email.toLowerCase(),passwordHash:i,role:e.role||"customer",tenantId:e.tenantId,createdAt:s,updatedAt:s},n=(await this.getRedis()).pipeline();return n.hset(this.userKey(t),this.userToHash(r)),n.set(this.userByEmailKey(e.email),t),await n.exec(),r}async findUserByEmail(e){let t=await(await this.getRedis()).get(this.userByEmailKey(e.toLowerCase()));return t?this.findUserById(t):null}async findUserById(e){let t=await(await this.getRedis()).hgetall(this.userKey(e));return !t||Object.keys(t).length===0?null:this.hashToUser(t)}async updateUser(e,t){let s=await this.findUserById(e);if(!s)return null;let i={...s,...t,id:e,updatedAt:new Date().toISOString()};if(t.email&&t.email!==s.email){let r=(await this.getRedis()).pipeline();r.del(this.userByEmailKey(s.email)),r.set(this.userByEmailKey(t.email),e),await r.exec();}return await(await this.getRedis()).hset(this.userKey(e),this.userToHash(i)),i}async deleteUser(e){let t=await this.findUserById(e);if(!t)return false;let s=(await this.getRedis()).pipeline();return s.del(this.userKey(e)),s.del(this.userByEmailKey(t.email)),s.del(this.passwordHistoryKey(e)),await s.exec(),true}async hashPassword(e){return g.default.hash(e,12)}async verifyPassword(e,t){let s=await(await this.getRedis()).get(this.userByEmailKey(e));if(!s)return null;let i=await this.findUserById(s);return !i||!i.passwordHash?null:await g.default.compare(t,i.passwordHash)?i:null}async createSession(e,t={}){let s=crypto.randomBytes(32).toString("hex"),i=crypto.randomBytes(32).toString("base64url"),r=crypto.randomBytes(32).toString("base64url"),n=new Date,a={id:s,userId:e,token:i,refreshToken:r,expiresAt:new Date(n.getTime()+this.tokenExpiration*1e3).toISOString(),createdAt:n.toISOString(),ipAddress:t.ipAddress,userAgent:t.userAgent},o=(await this.getRedis()).pipeline();return o.hset(this.sessionKey(s),this.sessionToHash(a)),o.setex(this.refreshKey(r),this.refreshExpiration,s),await o.exec(),a}async findSessionByToken(e){let t=await(await this.getRedis()).hgetall(this.sessionKey(e));return !t||Object.keys(t).length===0?null:this.hashToSession(t)}async findSessionByRefreshToken(e){let t=await(await this.getRedis()).get(this.refreshKey(e));if(!t)return null;let s=await(await this.getRedis()).hgetall(this.sessionKey(t));return !s||Object.keys(s).length===0?null:this.hashToSession(s)}async deleteSession(e){let t=await(await this.getRedis()).hgetall(this.sessionKey(e));if(!t||Object.keys(t).length===0)return false;let s=(await this.getRedis()).pipeline();return s.del(this.sessionKey(e)),t.refreshToken&&s.del(this.refreshKey(t.refreshToken)),await s.exec(),true}async deleteUserSessions(e){let t=`${this.prefix}sessions:*`,s="0",i=0;do{let[r,n]=await(await this.getRedis()).scan(s,"MATCH",t,"COUNT",100);s=r;for(let a of n)if((await(await this.getRedis()).hgetall(a)).userId===e){let l=a.replace(`${this.prefix}sessions:`,"");await this.deleteSession(l),i++;}}while(s!=="0");return i}async addPasswordToHistory(e,t){await(await this.getRedis()).lpush(this.passwordHistoryKey(e),t),await(await this.getRedis()).ltrim(this.passwordHistoryKey(e),0,4);}async getPasswordHistory(e,t=5){return (await this.getRedis()).lrange(this.passwordHistoryKey(e),0,t-1)}async isPasswordInHistory(e,t,s=5){let i=await this.getPasswordHistory(t,s);for(let r of i)if(await g.default.compare(e,r))return true;return false}userToHash(e){let t={id:e.id,email:e.email,passwordHash:e.passwordHash||"",role:e.role,createdAt:e.createdAt,updatedAt:e.updatedAt};return e.avatar&&(t.avatar=e.avatar),e.tenantId&&(t.tenantId=e.tenantId),e.metadata&&(t.metadata=JSON.stringify(e.metadata)),e.emailVerified!==void 0&&(t.emailVerified=String(e.emailVerified)),e.locked!==void 0&&(t.locked=String(e.locked)),e.lastLogin&&(t.lastLogin=e.lastLogin),e.failedLoginAttempts!==void 0&&(t.failedLoginAttempts=String(e.failedLoginAttempts)),t}hashToUser(e){return {id:e.id,email:e.email,passwordHash:e.passwordHash,role:e.role,tenantId:e.tenantId,avatar:e.avatar,metadata:e.metadata?JSON.parse(e.metadata):void 0,createdAt:e.createdAt,updatedAt:e.updatedAt,emailVerified:e.emailVerified==="true",locked:e.locked==="true",lastLogin:e.lastLogin,failedLoginAttempts:e.failedLoginAttempts?parseInt(e.failedLoginAttempts,10):0}}sessionToHash(e){let t={id:e.id,userId:e.userId,token:e.token,expiresAt:e.expiresAt,createdAt:e.createdAt};return e.refreshToken&&(t.refreshToken=e.refreshToken),e.ipAddress&&(t.ipAddress=e.ipAddress),e.userAgent&&(t.userAgent=e.userAgent),t}hashToSession(e){return {id:e.id,userId:e.userId,token:e.token,refreshToken:e.refreshToken,expiresAt:e.expiresAt,createdAt:e.createdAt,ipAddress:e.ipAddress,userAgent:e.userAgent}}tokenKey(e,t){return `${this.prefix}tokens:${e}:${t}`}async createEmailVerificationToken(e){let t=crypto.randomBytes(32).toString("hex"),s=new Date(Date.now()+1440*60*1e3);return await(await this.getRedis()).setex(this.tokenKey("email-verify",t),86400,e),{token:t,expiresAt:s}}async verifyEmailToken(e){let t=await this.getRedis(),s=await t.get(this.tokenKey("email-verify",e));return s?(await t.del(this.tokenKey("email-verify",e)),{success:true,userId:s}):{success:false,error:"Invalid or expired token"}}async createPasswordResetToken(e){let t=await this.findUserByEmail(e);if(!t)return {token:"",expiresAt:new Date,error:"User not found"};let s=crypto.randomBytes(32).toString("hex"),i=new Date(Date.now()+3600*1e3);return await(await this.getRedis()).setex(this.tokenKey("password-reset",s),3600,t.id),{token:s,expiresAt:i}}async resetPasswordWithToken(e,t){let s=await this.getRedis(),i=await s.get(this.tokenKey("password-reset",e));if(!i)return {success:false,error:"Invalid or expired token"};let r=await this.hashPassword(t);return await this.updateUser(i,{passwordHash:r}),await s.del(this.tokenKey("password-reset",e)),{success:true}}auditLogKey(e){return `${this.prefix}audit:logs:${e}`}auditLogIndexKey(){return `${this.prefix}audit:index`}async findAuditLogs(e){let{limit:t=50,offset:s=0}=e,i=this.auditLogIndexKey(),r=await(await this.getRedis()).zrevrange(i,0,-1),n=r.length,a=r.slice(s,s+t),o=[];for(let l of a){let u=await(await this.getRedis()).get(this.auditLogKey(l));if(u){let d=JSON.parse(u);(!e.userId||d.userId===e.userId)&&(!e.action||(Array.isArray(e.action)?e.action.includes(d.action):d.action===e.action))&&(!e.resource||d.resource===e.resource)&&(e.success===void 0||d.success===e.success)&&o.push({...d,timestamp:new Date(d.timestamp)});}}return {logs:o,total:n}}async createAuditLog(e){let t=crypto.randomBytes(16).toString("hex"),i={...e,id:t,timestamp:new Date};await(await this.getRedis()).set(this.auditLogKey(t),JSON.stringify(i)),await(await this.getRedis()).zadd(this.auditLogIndexKey(),Date.now(),t);let r=await(await this.getRedis()).zcard(this.auditLogIndexKey());if(r>1e4){let n=await(await this.getRedis()).zrange(this.auditLogIndexKey(),0,r-10001);for(let a of n)await(await this.getRedis()).del(this.auditLogKey(a)),await(await this.getRedis()).zrem(this.auditLogIndexKey(),a);}return i}};
|
|
2
|
-
exports.a=w;
|
package/dist/chunk-6E44MQQ5.js
DELETED
|
@@ -1,115 +0,0 @@
|
|
|
1
|
-
import {a as a$1,d,j,k,e as e$1,h,i}from'./chunk-47CXBWMA.js';import {n,M,p,s}from'./chunk-HRAY65XH.js';import {J}from'./chunk-3NSZZCOJ.js';import {a}from'./chunk-7NH7H3WA.js';import {g as g$1,e}from'./chunk-Y2YAKDEQ.js';import {randomBytes}from'crypto';if (typeof window === "undefined") { const { createRequire } = await import(/* @vite-ignore */ 'module'); createRequire(import.meta.url); }
|
|
2
|
-
g$1();var D=e(a(),1);var g=false,_=class{db;prefix;sessionTTL;refreshTokenTTL;constructor(e){this.db=e.db,this.prefix=e.prefix||"kyro:",this.sessionTTL=e.sessionTTL||86400,this.refreshTokenTTL=e.refreshTokenTTL||604800;}async connect(){if(!g){await this.db.execute(J`
|
|
3
|
-
CREATE TABLE IF NOT EXISTS "users" (
|
|
4
|
-
"id" UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
|
5
|
-
"name" VARCHAR(255),
|
|
6
|
-
"email" VARCHAR(255) NOT NULL,
|
|
7
|
-
"password_hash" VARCHAR(255),
|
|
8
|
-
"role" VARCHAR(50) NOT NULL DEFAULT 'customer',
|
|
9
|
-
"tenant_id" UUID,
|
|
10
|
-
"email_verified" BOOLEAN DEFAULT false,
|
|
11
|
-
"locked" BOOLEAN DEFAULT false,
|
|
12
|
-
"last_login" TIMESTAMP,
|
|
13
|
-
"failed_login_attempts" INTEGER DEFAULT 0,
|
|
14
|
-
"metadata" JSONB,
|
|
15
|
-
"avatar" VARCHAR(255),
|
|
16
|
-
"created_at" TIMESTAMP NOT NULL DEFAULT NOW(),
|
|
17
|
-
"updated_at" TIMESTAMP NOT NULL DEFAULT NOW()
|
|
18
|
-
)
|
|
19
|
-
`),await this.db.execute(J`ALTER TABLE "users" ADD COLUMN IF NOT EXISTS "avatar" VARCHAR(255)`),await this.db.execute(J`ALTER TABLE "users" ADD COLUMN IF NOT EXISTS "metadata" JSONB`),await this.db.execute(J`ALTER TABLE "users" ADD COLUMN IF NOT EXISTS "tenant_id" UUID`),await this.db.execute(J`ALTER TABLE "users" ADD COLUMN IF NOT EXISTS "email_verified" BOOLEAN DEFAULT false`),await this.db.execute(J`ALTER TABLE "users" ADD COLUMN IF NOT EXISTS "locked" BOOLEAN DEFAULT false`),await this.db.execute(J`ALTER TABLE "users" ADD COLUMN IF NOT EXISTS "last_login" TIMESTAMP`),await this.db.execute(J`ALTER TABLE "users" ADD COLUMN IF NOT EXISTS "failed_login_attempts" INTEGER DEFAULT 0`),await this.db.execute(J`CREATE UNIQUE INDEX IF NOT EXISTS "users_email_idx" ON "users" ("email")`),await this.db.execute(J`CREATE INDEX IF NOT EXISTS "users_tenant_idx" ON "users" ("tenant_id")`),await this.db.execute(J`CREATE INDEX IF NOT EXISTS "users_role_idx" ON "users" ("role")`),await this.db.execute(J`
|
|
20
|
-
CREATE TABLE IF NOT EXISTS "sessions" (
|
|
21
|
-
"id" UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
|
22
|
-
"user_id" UUID NOT NULL REFERENCES "users"("id") ON DELETE CASCADE,
|
|
23
|
-
"token" VARCHAR(512) NOT NULL UNIQUE,
|
|
24
|
-
"refresh_token" VARCHAR(512),
|
|
25
|
-
"ip_address" VARCHAR(45),
|
|
26
|
-
"user_agent" TEXT,
|
|
27
|
-
"expires_at" TIMESTAMP NOT NULL,
|
|
28
|
-
"created_at" TIMESTAMP NOT NULL DEFAULT NOW()
|
|
29
|
-
)
|
|
30
|
-
`),await this.db.execute(J`CREATE INDEX IF NOT EXISTS "sessions_user_idx" ON "sessions" ("user_id")`),await this.db.execute(J`CREATE INDEX IF NOT EXISTS "sessions_token_idx" ON "sessions" ("token")`),await this.db.execute(J`CREATE INDEX IF NOT EXISTS "sessions_expires_idx" ON "sessions" ("expires_at")`),await this.db.execute(J`
|
|
31
|
-
CREATE TABLE IF NOT EXISTS "audit_logs" (
|
|
32
|
-
"id" UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
|
33
|
-
"action" VARCHAR(100) NOT NULL,
|
|
34
|
-
"user_id" UUID REFERENCES "users"("id") ON DELETE SET NULL,
|
|
35
|
-
"user_email" VARCHAR(255),
|
|
36
|
-
"role" VARCHAR(50),
|
|
37
|
-
"resource" VARCHAR(100) NOT NULL,
|
|
38
|
-
"resource_id" VARCHAR(255),
|
|
39
|
-
"changes" JSONB,
|
|
40
|
-
"ip_address" VARCHAR(45),
|
|
41
|
-
"user_agent" TEXT,
|
|
42
|
-
"success" BOOLEAN NOT NULL DEFAULT true,
|
|
43
|
-
"error" TEXT,
|
|
44
|
-
"metadata" JSONB,
|
|
45
|
-
"timestamp" TIMESTAMP NOT NULL DEFAULT NOW()
|
|
46
|
-
)
|
|
47
|
-
`),await this.db.execute(J`ALTER TABLE "audit_logs" ADD COLUMN IF NOT EXISTS "resource_id" VARCHAR(255)`),await this.db.execute(J`ALTER TABLE "audit_logs" ADD COLUMN IF NOT EXISTS "changes" JSONB`),await this.db.execute(J`ALTER TABLE "audit_logs" ADD COLUMN IF NOT EXISTS "user_agent" TEXT`),await this.db.execute(J`ALTER TABLE "audit_logs" ADD COLUMN IF NOT EXISTS "error" TEXT`),await this.db.execute(J`ALTER TABLE "audit_logs" ADD COLUMN IF NOT EXISTS "metadata" JSONB`);try{await this.db.execute(J`ALTER TABLE "audit_logs" ALTER COLUMN "resource_id" TYPE VARCHAR(255)`);}catch{}await this.db.execute(J`CREATE INDEX IF NOT EXISTS "audit_logs_user_idx" ON "audit_logs" ("user_id")`),await this.db.execute(J`CREATE INDEX IF NOT EXISTS "audit_logs_action_idx" ON "audit_logs" ("action")`),await this.db.execute(J`CREATE INDEX IF NOT EXISTS "audit_logs_resource_idx" ON "audit_logs" ("resource")`),await this.db.execute(J`CREATE INDEX IF NOT EXISTS "audit_logs_timestamp_idx" ON "audit_logs" ("timestamp")`),await this.db.execute(J`
|
|
48
|
-
CREATE TABLE IF NOT EXISTS "password_history" (
|
|
49
|
-
"id" UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
|
50
|
-
"user_id" UUID NOT NULL REFERENCES "users"("id") ON DELETE CASCADE,
|
|
51
|
-
"password_hash" VARCHAR(255) NOT NULL,
|
|
52
|
-
"created_at" TIMESTAMP NOT NULL DEFAULT NOW()
|
|
53
|
-
)
|
|
54
|
-
`),await this.db.execute(J`CREATE INDEX IF NOT EXISTS "password_history_user_idx" ON "password_history" ("user_id")`),await this.db.execute(J`
|
|
55
|
-
CREATE TABLE IF NOT EXISTS "lockouts" (
|
|
56
|
-
"id" UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
|
57
|
-
"user_id" UUID NOT NULL REFERENCES "users"("id") ON DELETE CASCADE,
|
|
58
|
-
"ip_address" VARCHAR(45),
|
|
59
|
-
"reason" VARCHAR(255),
|
|
60
|
-
"locked_until" TIMESTAMP NOT NULL,
|
|
61
|
-
"released_at" TIMESTAMP,
|
|
62
|
-
"created_at" TIMESTAMP NOT NULL DEFAULT NOW()
|
|
63
|
-
)
|
|
64
|
-
`),await this.db.execute(J`CREATE INDEX IF NOT EXISTS "lockouts_user_idx" ON "lockouts" ("user_id")`),await this.db.execute(J`CREATE INDEX IF NOT EXISTS "lockouts_locked_until_idx" ON "lockouts" ("locked_until")`),await this.db.execute(J`
|
|
65
|
-
CREATE TABLE IF NOT EXISTS "roles" (
|
|
66
|
-
"id" UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
|
67
|
-
"name" VARCHAR(100) NOT NULL UNIQUE,
|
|
68
|
-
"level" INTEGER NOT NULL DEFAULT 0,
|
|
69
|
-
"inherits" TEXT[],
|
|
70
|
-
"description" TEXT,
|
|
71
|
-
"permissions" JSONB DEFAULT '[]',
|
|
72
|
-
"is_system" BOOLEAN DEFAULT false,
|
|
73
|
-
"created_at" TIMESTAMP NOT NULL DEFAULT NOW(),
|
|
74
|
-
"updated_at" TIMESTAMP NOT NULL DEFAULT NOW()
|
|
75
|
-
)
|
|
76
|
-
`),await this.db.execute(J`CREATE INDEX IF NOT EXISTS "roles_level_idx" ON "roles" ("level")`),await this.db.execute(J`
|
|
77
|
-
CREATE TABLE IF NOT EXISTS "tenants" (
|
|
78
|
-
"id" UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
|
79
|
-
"name" VARCHAR(255) NOT NULL,
|
|
80
|
-
"slug" VARCHAR(100) NOT NULL UNIQUE,
|
|
81
|
-
"settings" JSONB DEFAULT '{}',
|
|
82
|
-
"is_active" BOOLEAN DEFAULT true,
|
|
83
|
-
"created_at" TIMESTAMP NOT NULL DEFAULT NOW(),
|
|
84
|
-
"updated_at" TIMESTAMP NOT NULL DEFAULT NOW()
|
|
85
|
-
)
|
|
86
|
-
`),await this.db.execute(J`
|
|
87
|
-
CREATE TABLE IF NOT EXISTS "api_keys" (
|
|
88
|
-
"id" UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
|
89
|
-
"user_id" UUID NOT NULL REFERENCES "users"("id") ON DELETE CASCADE,
|
|
90
|
-
"name" VARCHAR(255) NOT NULL,
|
|
91
|
-
"key" VARCHAR(64) NOT NULL UNIQUE,
|
|
92
|
-
"key_prefix" VARCHAR(8) NOT NULL,
|
|
93
|
-
"permissions" JSONB DEFAULT '[]',
|
|
94
|
-
"last_used_at" TIMESTAMP,
|
|
95
|
-
"expires_at" TIMESTAMP,
|
|
96
|
-
"created_at" TIMESTAMP NOT NULL DEFAULT NOW()
|
|
97
|
-
)
|
|
98
|
-
`),await this.db.execute(J`
|
|
99
|
-
CREATE TABLE IF NOT EXISTS "email_verifications" (
|
|
100
|
-
"id" UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
|
101
|
-
"user_id" UUID NOT NULL REFERENCES "users"("id") ON DELETE CASCADE,
|
|
102
|
-
"token" VARCHAR(64) NOT NULL UNIQUE,
|
|
103
|
-
"expires_at" TIMESTAMP NOT NULL,
|
|
104
|
-
"created_at" TIMESTAMP NOT NULL DEFAULT NOW()
|
|
105
|
-
)
|
|
106
|
-
`),await this.db.execute(J`
|
|
107
|
-
CREATE TABLE IF NOT EXISTS "password_resets" (
|
|
108
|
-
"id" UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
|
109
|
-
"user_id" UUID NOT NULL REFERENCES "users"("id") ON DELETE CASCADE,
|
|
110
|
-
"token" VARCHAR(64) NOT NULL UNIQUE,
|
|
111
|
-
"expires_at" TIMESTAMP NOT NULL,
|
|
112
|
-
"used_at" TIMESTAMP,
|
|
113
|
-
"created_at" TIMESTAMP NOT NULL DEFAULT NOW()
|
|
114
|
-
)
|
|
115
|
-
`),g=true;}}async disconnect(){}async createUser(e){let s=await this.hashPassword(e.password),[i]=await this.db.insert(a$1).values({email:e.email.toLowerCase(),name:e.name,passwordHash:s,role:e.role||"customer",avatar:e.avatar,tenantId:e.tenantId,emailVerified:e.emailVerified??true}).returning();return this.userToAuthUser(i)}async findUserByEmail(e){let[s]=await this.db.select().from(a$1).where(n(a$1.email,e.toLowerCase())).limit(1);return s?this.userToAuthUser(s):null}async findUserById(e){let[s]=await this.db.select().from(a$1).where(n(a$1.id,e)).limit(1);return s?this.userToAuthUser(s):null}async updateUser(e,s){let i={updatedAt:new Date};s.name!==void 0&&(i.name=s.name),s.email!==void 0&&(i.email=s.email),s.passwordHash!==void 0&&(i.passwordHash=s.passwordHash),s.role!==void 0&&(i.role=s.role),s.tenantId!==void 0&&(i.tenantId=s.tenantId),s.avatar!==void 0&&(i.avatar=s.avatar),s.emailVerified!==void 0&&(i.emailVerified=s.emailVerified),s.locked!==void 0&&(i.locked=s.locked),s.lastLogin!==void 0&&(i.lastLogin=s.lastLogin?new Date(s.lastLogin):null),s.failedLoginAttempts!==void 0&&(i.failedLoginAttempts=s.failedLoginAttempts);let[r]=await this.db.update(a$1).set(i).where(n(a$1.id,e)).returning();return r?this.userToAuthUser(r):null}async deleteUser(e){return await this.db.delete(a$1).where(n(a$1.id,e)),true}async findUsers(e={}){let s=e.page??1,i=e.limit??10,r=(s-1)*i,u=e.search;if(u){let L=`%${u}%`,[w,[{count:O}]]=await Promise.all([this.db.select().from(a$1).where(J`${a$1.email} ILIKE ${L}`).orderBy(M(a$1.createdAt)).limit(i).offset(r),this.db.select({count:J`count(*)`}).from(a$1).where(J`${a$1.email} ILIKE ${L}`)]);return {users:w.map(A=>this.userToAuthUser(A)),total:Number(O)}}let[E,[{count:c}]]=await Promise.all([this.db.select().from(a$1).orderBy(M(a$1.createdAt)).limit(i).offset(r),this.db.select({count:J`count(*)`}).from(a$1)]);return {users:E.map(L=>this.userToAuthUser(L)),total:Number(c)}}async verifyPassword(e,s){let i=await this.findUserByEmail(e);if(!i)return null;let[r]=await this.db.select().from(a$1).where(n(a$1.email,e.toLowerCase())).limit(1);return r?.passwordHash&&await D.default.compare(s,r.passwordHash)?i:null}async hashPassword(e){return D.default.hash(e,12)}async createSession(e,s){let i=randomBytes(32).toString("base64url"),r=randomBytes(32).toString("base64url"),u=new Date(Date.now()+this.sessionTTL*1e3);new Date(Date.now()+this.refreshTokenTTL*1e3);let [c]=await this.db.insert(d).values({userId:e,token:i,refreshToken:r,ipAddress:s?.ipAddress,userAgent:s?.userAgent,expiresAt:u}).returning();return this.sessionToSession(c)}async findSessionByToken(e){let[s$1]=await this.db.select().from(d).where(p(n(d.token,e),s(d.expiresAt,new Date))).limit(1);return s$1?this.sessionToSession(s$1):null}async findSessionByRefreshToken(e){let[s$1]=await this.db.select().from(d).where(p(n(d.refreshToken,e),s(d.expiresAt,new Date))).limit(1);return s$1?this.sessionToSession(s$1):null}async deleteSession(e){return await this.db.delete(d).where(n(d.id,e)),true}async deleteUserSessions(e){return await this.db.delete(d).where(n(d.userId,e)),1}async addPasswordToHistory(e,s){await this.db.insert(j).values({userId:e,passwordHash:s});}async getPasswordHistory(e,s=5){return (await this.db.select({passwordHash:j.passwordHash}).from(j).where(n(j.userId,e)).orderBy(M(j.createdAt)).limit(s)).map(r=>r.passwordHash)}async isPasswordInHistory(e,s,i=5){let r=await this.getPasswordHistory(s,i);for(let u of r)if(await this.verifyPassword(e,u))return true;return false}async isLocked(e){let[s$1]=await this.db.select().from(k).where(p(n(k.userId,e),s(k.lockedUntil,new Date))).limit(1);return !!s$1}async getLockout(e){let[s$1]=await this.db.select().from(k).where(p(n(k.userId,e),s(k.lockedUntil,new Date))).limit(1);return s$1?{lockedUntil:s$1.lockedUntil}:null}async recordFailedAttempt(e,s){let r=((await this.findUserById(e))?.failedLoginAttempts||0)+1;await this.updateUser(e,{failedLoginAttempts:r});let E=r>=5;return E&&await this.db.insert(k).values({userId:e,ipAddress:s,reason:"Too many failed login attempts",lockedUntil:new Date(Date.now()+9e5)}),{attempts:r,locked:E}}async resetAttempts(e){await this.updateUser(e,{failedLoginAttempts:0});}async findAuditLogs(e){let{limit:s=50,offset:i=0,userId:r,action:u,resource:E,resourceId:c,success:L,startDate:w,endDate:O}=e,A=[];r&&A.push(n(e$1.userId,r)),u&&(Array.isArray(u)?A.push(J`${e$1.action} = ANY(${u})`):A.push(n(e$1.action,u))),E&&A.push(n(e$1.resource,E)),c&&A.push(n(e$1.resourceId,c)),L!==void 0&&A.push(n(e$1.success,L)),w&&A.push(J`${e$1.timestamp} >= ${w}`),O&&A.push(J`${e$1.timestamp} <= ${O}`);let S=A.length>0?p(...A):void 0,b=await this.db.select({count:J`count(*)`}).from(e$1).where(S);return {logs:(await this.db.select().from(e$1).where(S).orderBy(M(e$1.timestamp)).limit(s).offset(i)).map(o=>({id:o.id,timestamp:o.timestamp,action:o.action,userId:o.userId||void 0,userEmail:o.userEmail||void 0,role:o.role||void 0,resource:o.resource,resourceId:o.resourceId||void 0,changes:o.changes||void 0,ipAddress:o.ipAddress||void 0,userAgent:o.userAgent||void 0,success:o.success,error:o.error||void 0,metadata:o.metadata||void 0})),total:Number(b[0]?.count||0)}}async createAuditLog(e){let s=crypto.randomUUID(),i=new Date;return await this.db.insert(e$1).values({id:s,action:e.action,userId:e.userId??null,userEmail:e.userEmail??null,role:e.role??null,resource:e.resource,resourceId:e.resourceId??null,changes:e.changes??null,ipAddress:e.ipAddress??null,userAgent:e.userAgent??null,success:e.success,error:e.error??null,metadata:e.metadata??null,timestamp:i}),{...e,id:s,timestamp:i}}userToAuthUser(e){return {id:e.id,name:e.name||void 0,email:e.email,passwordHash:e.passwordHash||void 0,role:e.role,avatar:e.avatar&&typeof e.avatar=="object"?e.avatar.id||void 0:e.avatar||void 0,tenantId:e.tenantId||void 0,emailVerified:e.emailVerified||false,locked:e.locked||false,lastLogin:e.lastLogin?new Date(e.lastLogin).toISOString():void 0,failedLoginAttempts:e.failedLoginAttempts||0,createdAt:new Date(e.createdAt).toISOString(),updatedAt:new Date(e.updatedAt).toISOString()}}sessionToSession(e){return {id:e.id,userId:e.userId,token:e.token,refreshToken:e.refreshToken||void 0,expiresAt:new Date(e.expiresAt).toISOString(),createdAt:new Date(e.createdAt).toISOString(),ipAddress:e.ipAddress||void 0,userAgent:e.userAgent||void 0}}async createEmailVerificationToken(e){let s=randomBytes(32).toString("hex"),i=new Date(Date.now()+1440*60*1e3);return await this.db.insert(h).values({userId:e,token:s,expiresAt:i}),{token:s,expiresAt:i}}async verifyEmailToken(e){let[s]=await this.db.select().from(h).where(n(h.token,e)).limit(1);return s?s.expiresAt<new Date?{success:false,error:"Verification token has expired"}:(await this.db.update(a$1).set({emailVerified:true}).where(n(a$1.id,s.userId)),await this.db.delete(h).where(n(h.id,s.id)),{success:true,userId:s.userId}):{success:false,error:"Invalid verification token"}}async createPasswordResetToken(e){let s=await this.findUserByEmail(e);if(!s)return {token:"",expiresAt:new Date,error:"User not found"};let i$1=randomBytes(32).toString("hex"),r=new Date(Date.now()+3600*1e3);return await this.db.insert(i).values({userId:s.id,token:i$1,expiresAt:r}),{token:i$1,expiresAt:r}}async resetPasswordWithToken(e,s){let[i$1]=await this.db.select().from(i).where(n(i.token,e)).limit(1);if(!i$1)return {success:false,error:"Invalid reset token"};if(i$1.expiresAt<new Date)return {success:false,error:"Reset token has expired"};if(i$1.usedAt)return {success:false,error:"Reset token has already been used"};let r=await this.hashPassword(s);return await this.db.update(a$1).set({passwordHash:r,updatedAt:new Date}).where(n(a$1.id,i$1.userId)),await this.db.update(i).set({usedAt:new Date}).where(n(i.id,i$1.id)),await this.db.delete(d).where(n(d.userId,i$1.userId)),{success:true}}};export{_ as a};
|
package/dist/chunk-6LWF5MPL.js
DELETED
|
@@ -1,20 +0,0 @@
|
|
|
1
|
-
import {a,c,b,d}from'./chunk-SLMIYECU.js';import {a as a$1}from'./chunk-JA44K75G.js';import {g}from'./chunk-Y2YAKDEQ.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
|
-
g();g();g();function E(m){let t=[];for(let a of m)if(a.type==="tabs"&&"tabs"in a)for(let n of a.tabs)t.push(...E(n.fields));else a.type==="row"&&"fields"in a?t.push(...E(a.fields)):a.type==="collapsible"&&"fields"in a?t.push(...E(a.fields)):t.push(a);return t}function P(m,t){let a=t,n=m[a.name];if(a.type==="json"||a.type==="richtext"||a.type==="array"||a.type==="group"||a.type==="blocks"||a.type==="list"||a.type==="relationship-block")try{n=n?JSON.parse(n):null;}catch{n=null;}if(a.type==="checkbox"&&(n=!!n),a.type==="date"&&n)try{let i=new Date(n);isNaN(i.getTime())?n=null:n=i.toISOString();}catch{n=null;}if((a.type==="upload"||a.type==="image")&&n)try{let i=JSON.parse(n);Array.isArray(i)?n=i.map(o=>typeof o=="object"&&o!==null?o:{id:o}):n=typeof i=="object"?i:{id:i};}catch{n=typeof n=="string"?{id:n}:n;}return n}var R;function U(){return R||(R=createRequire("file:///")("node:sqlite").DatabaseSync,R)}function j(m,t){return Array.isArray(m)?m.map(a=>{if(!a||typeof a!="object")return a;let n=a.data?{...a.data}:void 0;if(!n)return a;let i=t.find(o=>o.slug===a.type||o.slug===a.slug);if(!i||!Array.isArray(i.fields))return a;for(let o of i.fields){if(o.name&&(o.type==="upload"||o.type==="image")&&n[o.name]){let e=n[o.name];Array.isArray(e)?n[o.name]=e.map(s=>typeof s=="string"?{id:s}:s):typeof e=="string"&&(n[o.name]={id:e});}if(o.type==="blocks"&&o.name&&n[o.name]){let e=o.blocks||[];n[o.name]=j(n[o.name],e);}}return {...a,data:n}}):m}function I(m,t){try{return m.prepare(`PRAGMA table_info(${t})`).all().map(n=>n.name)}catch{return []}}var L=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),a=n=>{let i=t(n),o=e=>typeof e=="boolean"?e?1:0:e===void 0?null:e;return new Proxy(i,{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}})};a.__wrapped=true,this.db.prepare=a;}this.db.exec("PRAGMA journal_mode = WAL"),this.db.exec("PRAGMA foreign_keys = ON"),this.connected=true;}async disconnect(){if(this.db){try{this.db.close();}catch{}this.db=null;}this.connected=false;}ensureTable(t,a){let n=a||this.getTableNameFor(t.slug),i=["id TEXT PRIMARY KEY"];for(let s of E(t.fields)){if(!s.name||s.name==="id")continue;let r=this.fieldToSQL(s);r&&i.push(r);}let o=E(t.fields);o.some(s=>s.name==="createdAt")||i.push(`${this.col("createdAt")} TEXT DEFAULT (datetime('now'))`),o.some(s=>s.name==="updatedAt")||i.push(`${this.col("updatedAt")} TEXT DEFAULT (datetime('now'))`),o.some(s=>s.name==="status")||i.push("status TEXT DEFAULT 'draft'"),o.some(s=>s.name==="hasDraft")||i.push("hasDraft INTEGER DEFAULT 0"),t.tenantScoped&&i.push("tenant_id TEXT NOT NULL");let e=I(this.db,n);if(e.length===0){let s=`CREATE TABLE IF NOT EXISTS ${n} (${i.join(", ")})`;this.db.exec(s),this.db.exec(`CREATE INDEX IF NOT EXISTS idx_${n}_status ON ${n}(status)`);for(let r of E(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 i){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
|
-
CREATE TABLE IF NOT EXISTS ${this.versionsTableName} (
|
|
4
|
-
id TEXT PRIMARY KEY,
|
|
5
|
-
collection_slug TEXT NOT NULL,
|
|
6
|
-
document_id TEXT NOT NULL,
|
|
7
|
-
tenant_id TEXT,
|
|
8
|
-
version INTEGER NOT NULL,
|
|
9
|
-
status TEXT NOT NULL DEFAULT 'draft',
|
|
10
|
-
autosave INTEGER NOT NULL DEFAULT 0,
|
|
11
|
-
data TEXT NOT NULL,
|
|
12
|
-
created_by TEXT,
|
|
13
|
-
change_description TEXT,
|
|
14
|
-
published_at TEXT,
|
|
15
|
-
created_at TEXT DEFAULT (datetime('now')),
|
|
16
|
-
updated_at TEXT DEFAULT (datetime('now'))
|
|
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,a){let n=a.replace(/^-/,""),i=I(this.db,t);if(!i.includes(n)){if(n==="created_at"&&i.includes("createdAt"))return '"createdAt"';if(n==="createdAt"&&i.includes("created_at"))return '"created_at"';if(n==="updated_at"&&i.includes("updatedAt"))return '"updatedAt"';if(n==="updatedAt"&&i.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 a=t.replace("_globals_","");return {isGlobal:true,globalSlug:a,tableName:`global_${a.replace(/-/g,"_")}`}}return {isGlobal:false,globalSlug:"",tableName:this.getTableNameFor(t)}}buildWhere(t,a){let n=[],i=[];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,a);d.clause&&(l.push(`(${d.clause})`),i.push(...d.params));}l.length>0&&n.push(`(${l.join(` ${s} `)})`);continue}let r=this.resolveCol(a,o);typeof e=="object"&&e!==null&&!Array.isArray(e)?(e.equals!==void 0&&(n.push(`${r} = ?`),i.push(e.equals)),e.not_equals!==void 0&&(n.push(`${r} != ?`),i.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(", ")})`),i.push(...e.in))),e.contains!==void 0&&(n.push(`LOWER(${r}) LIKE LOWER(?)`),i.push(`%${e.contains}%`)),e.like!==void 0&&(n.push(`LOWER(${r}) LIKE LOWER(?)`),i.push(e.like)),e.greater_than!==void 0&&(n.push(`${r} > ?`),i.push(e.greater_than)),e.greater_than_equal!==void 0&&(n.push(`${r} >= ?`),i.push(e.greater_than_equal)),e.less_than!==void 0&&(n.push(`${r} < ?`),i.push(e.less_than)),e.less_than_equal!==void 0&&(n.push(`${r} <= ?`),i.push(e.less_than_equal))):e!==void 0&&(n.push(`${r} = ?`),i.push(e));}return {clause:n.join(" AND "),params:i}}async find(t){let{collection:a,where:n={},sort:i,limit:o=10,page:e=1,tenantId:s,select:r,draft:l=false}=t,c$1=this.parseGlobalsSlug(a),d$1=c$1.isGlobal?this.globals.get(c$1.globalSlug):this.getCollection(a);this.ensureTable(d$1,c$1.tableName);let y=c$1.tableName,h=`SELECT * FROM ${y}`,f=[],u=[],g={...n};this.tenantContext&&d$1.tenantScoped&&(g=c({where:g},a,this.tenantContext,b).where||{});let b$1=d$1.fields.find(p=>p.name==="status"),T=b$1?.type==="select"&&Array.isArray(b$1.options)&&b$1.options.some(p=>p.value==="published");if(!l&&T&&(u.push("status = ?"),f.push("published")),s&&d$1.tenantScoped&&(u.push("tenant_id = ?"),f.push(s)),g&&Object.keys(g).length>0){let p=this.buildWhere(g,y);p.clause&&(u.push(`(${p.clause})`),f.push(...p.params));}u.length>0&&(h+=` WHERE ${u.join(" AND ")}`);let $=i||"-createdAt",M=this.resolveCol(y,$),V=$.startsWith("-")?"DESC":"ASC";h+=` ORDER BY ${M} ${V}`;let X=h.replace("SELECT *","SELECT COUNT(*) as count"),S=this.db.prepare(X).get(...f)?.count||0;h+=" LIMIT ? OFFSET ?",f.push(o,(e-1)*o);let N=this.db.prepare(h).all(...f).map(p=>this.rowToDoc(p,d$1));return this.tenantContext&&!this.tenantContext.isSuperAdmin&&(N=N.filter(p=>d(p,a,this.tenantContext,b))),l&&(N=await Promise.all(N.map(async p=>{let D=this.db.prepare(`SELECT * FROM ${this.versionsTableName} WHERE collection_slug = ? AND document_id = ? AND tenant_id IS NULL ORDER BY version DESC LIMIT 1`).get(a,p.id);if(D){let G=D.data?JSON.parse(D.data):{};return a$1({...p,...G,status:p.status,_hasUnpublishedChanges:D.status==="draft"})}return p}))),N=N.map(p=>a$1(p)),{docs:N,totalDocs:S,limit:o,totalPages:Math.ceil(S/o),page:e,pagingCounter:(e-1)*o+1,hasPrevPage:e>1,hasNextPage:e<Math.ceil(S/o),prevPage:e>1?e-1:null,nextPage:e<Math.ceil(S/o)?e+1:null}}async findByID(t){let{collection:a,id:n,tenantId:i,draft:o=false}=t,e=this.parseGlobalsSlug(a),s=e.isGlobal?this.globals.get(e.globalSlug):this.getCollection(a);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,a,this.tenantContext,b))return null}let d$1=s.fields.find(u=>u.name==="status"),y=d$1?.type==="select"&&Array.isArray(d$1.options)&&d$1.options.some(u=>u.value==="published");!o&&y&&(l+=" AND status = ?",c.push("published")),i&&s.tenantScoped&&(l+=" AND tenant_id = ?",c.push(i));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(a,f.id);if(u){let g=u.data?JSON.parse(u.data):{};f={...f,...g,status:f.status,_hasUnpublishedChanges:u.status==="draft"};}}return a$1(f)}async create(t){let{collection:a,data:n,tenantId:i}=t,o=this.parseGlobalsSlug(a),e=o.isGlobal?this.globals.get(o.globalSlug):this.getCollection(a);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,i&&e.tenantScoped&&(l.tenant_id=i);let d=Object.keys(l),y=I(this.db,s),h={};for(let T of d)y.includes(T)&&(h[T]=l[T]);let f=Object.keys(h),u=f.map(T=>this.col(T)),g=f.map(()=>"?").join(", "),b=Object.values(h).map(T=>T!==null&&typeof T=="object"?JSON.stringify(T):T);return this.db.prepare(`INSERT OR REPLACE INTO ${s} (${u.join(", ")}) VALUES (${g})`).run(...b),this.ensureVersionsTable(),this.findByID({collection:a,id:r,tenantId:i,draft:true})}async update(t){let{collection:a,id:n,data:i,tenantId:o}=t,e=this.parseGlobalsSlug(a),s=e.isGlobal?this.globals.get(e.globalSlug):this.getCollection(a);this.ensureTable(s,e.tableName);let r=e.tableName,l=this.prepareData(i,s);l.updated_at=new Date().toISOString();let c=I(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 = ?`,g=[...f,n];return o&&s.tenantScoped&&(u+=" AND tenant_id = ?",g.push(o)),this.db.prepare(u).run(...g),this.ensureVersionsTable(),this.findByID({collection:a,id:n,tenantId:o,draft:true})}async delete(t){let{collection:a,id:n,tenantId:i}=t,o=this.parseGlobalsSlug(a),e=o.isGlobal?this.globals.get(o.globalSlug):this.getCollection(a);this.ensureTable(e,o.tableName),this.ensureVersionsTable();let s=await this.findByID({collection:a,id:n,tenantId:i,draft:true});if(!s)throw new Error(`Document not found: ${a}/${n}`);let l=`DELETE FROM ${o.tableName} WHERE id = ?`,c=[n];return i&&e.tenantScoped&&(l+=" AND tenant_id = ?",c.push(i)),this.db.prepare(l).run(...c),s}async count(t){let{collection:a,tenantId:n}=t,i=this.parseGlobalsSlug(a),o=i.isGlobal?this.globals.get(i.globalSlug):this.getCollection(a);this.ensureTable(o,i.tableName);let e=i.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 a=this.parseGlobalsSlug(t.collection);if(a.isGlobal){let i=this.globals.get(a.globalSlug);if(!i)throw new Error(`Global "${a.globalSlug}" not found in adapter`);this.ensureTable(i,a.tableName);let o=`SELECT * FROM ${a.tableName}`,e=[],s=[],r=i.fields.find(d=>d.name==="status"),l=r?.type==="select"&&Array.isArray(r.options)&&r.options.some(d=>d.value==="published");!t.draft&&i.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,i);if(t.draft){let y=this.db.prepare(`SELECT * FROM ${this.versionsTableName} WHERE collection_slug = ? AND document_id = ? AND tenant_id IS NULL ORDER BY version DESC LIMIT 1`).get(t.collection,a.globalSlug);if(y){let h=y.data?JSON.parse(y.data):{};d={...d,...h,status:d.status,_hasUnpublishedChanges:y.status==="draft"};}}return d}return null}return (await this.find({...t,limit:1})).docs[0]||null}async findVersions(t){this.ensureVersionsTable();let{collection:a,documentId:n,tenantId:i,limit:o=20,page:e=1}=t,s=["collection_slug = ?","document_id = ?","autosave = 0"],r=[a,n];i?(s.push("tenant_id = ?"),r.push(i)):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,y=(e-1)*o;return {docs:this.db.prepare(`SELECT * FROM ${this.versionsTableName} ${l} ORDER BY version DESC LIMIT ? OFFSET ?`).all(...r,o,y).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 a=this.db.prepare(`SELECT * FROM ${this.versionsTableName} WHERE id = ? AND collection_slug = ? LIMIT 1`).get(t.versionId,t.collection);return a?this.rowToVersion(a):null}async createVersion(t){this.ensureVersionsTable();let a=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,a,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
|
-
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"?a:null,a,a),!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:a,documentId:n,keepLatest:i,tenantId:o}=t;if(i&&i>0){let e=this.db.prepare(`SELECT id, status, autosave FROM ${this.versionsTableName} WHERE collection_slug = ? AND document_id = ? ORDER BY version DESC`).all(a,n),s=0,r=[];for(let l of e)l.status==="published"||l.autosave===1||(s++,s>i&&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=[a,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,a){let n={},i=E(a.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 i){if(!e.name||e.name==="id"||a.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 a.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,a){let n={id:t.id};for(let i of E(a.fields)){if(!i.name||i.name==="id")continue;let o=i,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=j(e,s);}if(i.type==="checkbox"&&(e=!!e),i.type==="date"&&e)try{let s=new Date(e);isNaN(s.getTime())?(console.warn(`[LocalAdapter] Invalid date value for field "${i.name}":`,e),e=null):e=s.toISOString();}catch{e=null;}if((i.type==="upload"||i.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(i.type==="relationship"&&e)try{let s=JSON.parse(e);Array.isArray(s),e=s;}catch{e={relationTo:Array.isArray(i.relationTo)?i.relationTo[0]:i.relationTo,value:e};}n[i.name]=e;}for(let i of a.fields)if(!(!i.name||i.name==="id"||i.name==="row"||i.name==="collapsible")&&i.type==="tabs"&&"tabs"in i){let o={};for(let e of i.tabs)for(let s of e.fields)s.name&&s.name!=="id"&&(o[s.name]=P(t,s));n[i.name]=o;}if(a.timestamps){let i=t.createdAt||t.created_at,o=t.updatedAt||t.updated_at;if(i)try{let e=new Date(i);isNaN(e.getTime())||(n.createdAt=e.toISOString());}catch{}if(o)try{let e=new Date(o);isNaN(e.getTime())||(n.updatedAt=e.toISOString());}catch{}}a.tenantScoped&&(n.tenantId=t.tenant_id),n.status=t.status??"published",n.hasDraft=t.hasDraft?!!t.hasDraft:false;for(let i of Object.keys(n))/^\d+$/.test(i)&&delete n[i];return n}generateId(){let t=Date.now().toString(16).padStart(12,"0"),a=randomBytes(6).toString("hex");return t+a}getMediaById(t){try{let a=this.getTableNameFor("media"),n=this.db.prepare(`SELECT id, url, thumbnail_url FROM ${a} 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((a,n)=>{let i=this.db.transaction(async()=>t({db:this.db}));try{let o=i();a(o);}catch(o){n(o);}})}getDatabase(){return this.db}exec(t){this.db.exec(t);}prepare(t){return this.db.prepare(t)}};function W(m){return new L(m||{})}export{L as a,W as b};
|
package/dist/chunk-6NBZDW53.js
DELETED
|
@@ -1,133 +0,0 @@
|
|
|
1
|
-
import {c,a as a$2,b as b$1,e,h}from'./chunk-JV4HJBXW.js';import {a as a$4}from'./chunk-3TAUNYEM.js';import {n,M,p,q,o,w,G,E,s,t,u,v}from'./chunk-HRAY65XH.js';import {ia,oa,fa,ma,$,ha,ca,pa,ra,J}from'./chunk-3NSZZCOJ.js';import {a,c as c$1,b as b$2,d}from'./chunk-SLMIYECU.js';import {a as a$1}from'./chunk-P6JITOFF.js';import {a as a$3}from'./chunk-JA44K75G.js';import {g}from'./chunk-Y2YAKDEQ.js';if (typeof window === "undefined") { const { createRequire } = await import(/* @vite-ignore */ 'module'); createRequire(import.meta.url); }
|
|
2
|
-
g();g();g();function b(f,t="postgres"){switch(f.type){case "text":case "email":case "password":case "color":case "icon":return t==="sqlite"?"text":"varchar";case "textarea":case "code":case "markdown":case "secret":return "text";case "number":return f.integer?"integer":"decimal";case "checkbox":return "boolean";case "date":return "timestamp";case "select":case "radio":return t==="sqlite"?"text":"varchar";case "richtext":case "json":case "array":case "group":case "blocks":case "row":case "collapsible":case "tabs":return "jsonb";case "relationship":return t==="sqlite"?"text":"varchar";case "upload":return "jsonb";default:return "jsonb"}}function ue(f,t="postgres"){let i=f.slug.replace(/-/g,"_"),e=[];e.push(`export const ${i} = pgTable('${i}', {`),e.push(" id: uuid('id').primaryKey().defaultRandom(),");for(let s of f.fields){if(s.name==="id"||s.type==="password")continue;let n=b(s,t),o=s.required,a=` ${s.name}: pg.${n}('${s.name}')`;s.unique&&(a+=".unique()"),o||(a+=".nullable()"),s.defaultValue!==void 0&&(typeof s.defaultValue=="string"?a+=`.default('${s.defaultValue}')`:typeof s.defaultValue=="boolean"?a+=`.default(${s.defaultValue})`:a+=`.default(sql\`${JSON.stringify(s.defaultValue)}\`)`),a+=",",e.push(a);}return f.timestamps&&(e.push(" createdAt: pg.timestamp('created_at').defaultNow(),"),e.push(" updatedAt: pg.timestamp('updated_at').defaultNow(),")),e.push(` status: ${t==="sqlite"?"sqlite":"pg"}.varchar('status').default('draft'),`),e.push(` hasDraft: ${t==="sqlite"?"sqlite":"pg"}.boolean('hasDraft').default(false),`),e.push("});"),e.join(`
|
|
3
|
-
`)}function j(f,t){return Array.isArray(f)?f.map(i=>{if(!i||typeof i!="object")return i;let e=i.data?{...i.data}:void 0;if(!e)return i;let s=t.find(n=>n.slug===i.type||n.slug===i.slug);if(!s||!Array.isArray(s.fields))return i;for(let n of s.fields){if(n.name&&(n.type==="upload"||n.type==="image")&&e[n.name]){let o=e[n.name];Array.isArray(o)?e[n.name]=o.map(a=>typeof a=="string"?{id:a}:a):typeof o=="string"&&(e[n.name]={id:o});}if(n.type==="blocks"&&n.name&&e[n.name]){let o=n.blocks||[];e[n.name]=j(e[n.name],o);}}return {...i,data:e}}):f}function C(f){if(typeof f!="string")return f;let t=f.replace(/-/g,"").toLowerCase();return t.length===32?`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`:f}var O=class extends a{client;schema;_schemaEnsured=false;dialect;connectionString;versionsTableReady=false;rawClient;constructor(t){if(super(),this.schema=t.schema||{},t.connectionString){this.connectionString=t.connectionString;let i=t.connectionString.toLowerCase();i.startsWith("postgres://")||i.startsWith("postgresql://")?this.dialect="postgres":i.includes(".db")||i.includes("sqlite")||i.includes("file:")?this.dialect="sqlite":this.dialect=t.type||"postgres";}else this.rawClient=t.client,this.client=t.client,this.dialect=t.type||"sqlite";}prepareData(t,i){let e=super.prepareData(t,i);e.createdAt&&typeof e.createdAt=="string"&&(e.createdAt=new Date(e.createdAt)),e.updatedAt&&typeof e.updatedAt=="string"&&(e.updatedAt=new Date(e.updatedAt));for(let s of i.fields)if(s.type==="date"&&s.name){let n=e[s.name];n&&typeof n=="string"&&(e[s.name]=new Date(n));}for(let s of i.fields){let o=b(s,this.dialect)==="jsonb";if(s.type==="tabs"&&"tabs"in s&&s.name){let a=t[s.name];if(a&&typeof a=="object"){let r={};for(let[l,c]of Object.entries(a)){let u=s.tabs.flatMap(g=>g.fields).find(g=>g.name===l);(u?.type==="upload"||u?.type==="image"||u?.type==="list"||u?.type==="relationship-block")&&c?r[l]=Array.isArray(c)||typeof c=="object"?JSON.stringify(c):c:r[l]=c;}e[s.name]=this.dialect==="sqlite"||!o?JSON.stringify(r):r;}}else if(o&&s.name&&t[s.name]!==void 0&&t[s.name]!==null)e[s.name]=this.dialect==="sqlite"?JSON.stringify(t[s.name]):t[s.name];else if((s.type==="upload"||s.type==="image"||s.type==="list"||s.type==="relationship-block")&&s.name){let a=t[s.name];a!=null&&(e[s.name]=this.dialect==="sqlite"||!o?typeof a=="string"?a:JSON.stringify(a):a);}}for(let s of i.fields)if(s.name&&e[s.name]===""){let n=b(s,this.dialect);(n==="timestamp"||n==="jsonb"||n==="decimal"||n==="integer"||n==="numeric"||n==="boolean")&&(e[s.name]=null);}return e}async connect(){if(this.connectionString&&!this.client){if(this.dialect==="postgres"){let t,i;try{t=(await import('./src-QBADSZV4.js')).default,i=(await import('./postgres-js-JLFIWOBH.js')).drizzle;}catch{a$1(["postgres","drizzle-orm"]),t=(await import('./src-QBADSZV4.js')).default,i=(await import('./postgres-js-JLFIWOBH.js')).drizzle;}let e=t(this.connectionString,{onnotice:()=>{}});this.client=i(e,{schema:this.schema});}else if(this.dialect==="sqlite"){let t,i;try{t=(await import('better-sqlite3')).default,i=(await import('./better-sqlite3-B34RIU4C.js')).drizzle;}catch{a$1(["better-sqlite3","drizzle-orm"]),t=(await import('better-sqlite3')).default,i=(await import('./better-sqlite3-B34RIU4C.js')).drizzle;}let e=new t(this.connectionString.replace("file:",""));this.client=i(e,{schema:this.schema});}}if(this.rawClient&&typeof this.rawClient.prepare=="function"&&typeof this.client?.select!="function"){let{drizzle:t}=await import('./d1-HPB6B253.js');this.client=t(this.rawClient,{schema:this.schema});}this.connected=true;}async init(t,i=[]){if(await super.init(t,i),(this.connectionString&&!this.client||this.rawClient&&typeof this.client?.select!="function")&&await this.connect(),this.client&&!this._schemaEnsured){for(let s of t){let n=this.getTableName(s.slug);this.schema[n]||(this.schema[n]=this.createTableFromConfig(s));}await this.ensureCollectionTables(t);let e=i.map(s=>({slug:`_globals_${s.slug}`,fields:s.fields,label:s.label}));for(let s of e){let n=this.getTableName(s.slug);this.schema[n]||(this.schema[n]=this.createTableFromConfig(s,true)),this.collections.has(s.slug)||this.collections.set(s.slug,s);}await this.ensureCollectionTables(e),this._schemaEnsured=true;}}createTableFromConfig(t,i=false){let e$1=this.getTableName(t.slug),s={id:i?ia("id").primaryKey():oa("id").primaryKey().defaultRandom()};for(let n of t.fields){if(!n.name||n.name==="id"||n.type==="password")continue;let o=b(n,this.dialect),a=n.name.replace(/-/g,"_"),r=a.replace(/([A-Z])/g,"_$1").toLowerCase(),l;if(this.dialect==="sqlite")switch(o){case "varchar":case "text":l=c(r);break;case "integer":l=a$2(r);break;case "decimal":case "numeric":l=b$1(r);break;case "boolean":l=a$2(r,{mode:"boolean"});break;case "timestamp":l=c(r);break;case "jsonb":l=c(r);break;default:l=c(r);}else switch(o){case "varchar":l=pa(r,{length:255});break;case "integer":l=ca(r);break;case "decimal":l=ha(r);break;case "boolean":l=$(r);break;case "timestamp":l=ma(r);break;case "jsonb":l=fa(r);break;default:l=ia(r);}n.required||(l=l.default(null)),s[a]=l;}return s.createdAt||(s.createdAt=this.dialect==="sqlite"?c("created_at").default(new Date().toISOString()):ma("created_at").defaultNow()),s.updatedAt||(s.updatedAt=this.dialect==="sqlite"?c("updated_at").default(new Date().toISOString()):ma("updated_at").defaultNow()),e$1!=="users"&&e$1!=="audit_logs"&&(s.status||(s.status=this.dialect==="sqlite"?c("status").default("draft"):pa("status",{length:20}).default("draft")),s.hasDraft||(s.hasDraft=this.dialect==="sqlite"?a$2("hasDraft",{mode:"boolean"}).default(false):$("hasDraft").default(false))),this.dialect==="sqlite"?e(e$1,s):ra(e$1,s)}async ensureCollectionTables(t){let i=[];for(let e of t){let s=e.slug.startsWith("_globals_"),n=this.getTableName(e.slug),o=this.generateCreateColumns(e),a=e.fields.some(u=>u.name==="createdAt"),r=e.fields.some(u=>u.name==="updatedAt"),l=e.fields.some(u=>u.name==="status"),c=e.fields.some(u=>u.name==="hasDraft");if(this.dialect==="postgres"){let u=s?'"id" TEXT PRIMARY KEY':'"id" UUID PRIMARY KEY DEFAULT gen_random_uuid()';i.push(`
|
|
4
|
-
CREATE TABLE IF NOT EXISTS "${n}" (
|
|
5
|
-
${u},
|
|
6
|
-
${o}
|
|
7
|
-
${a?"":'"created_at" TIMESTAMP NOT NULL DEFAULT NOW(),'}
|
|
8
|
-
${r?"":'"updated_at" TIMESTAMP NOT NULL DEFAULT NOW(),'}
|
|
9
|
-
${l?"":`"status" VARCHAR(20) DEFAULT 'draft',`}
|
|
10
|
-
${c?"":'"hasDraft" BOOLEAN DEFAULT false'}
|
|
11
|
-
)
|
|
12
|
-
`);}else i.push(`
|
|
13
|
-
CREATE TABLE IF NOT EXISTS "${n}" (
|
|
14
|
-
"id" TEXT PRIMARY KEY,
|
|
15
|
-
${o}
|
|
16
|
-
${a?"":`"created_at" TEXT NOT NULL DEFAULT (datetime('now')),`}
|
|
17
|
-
${r?"":`"updated_at" TEXT NOT NULL DEFAULT (datetime('now')),`}
|
|
18
|
-
${l?"":`"status" TEXT DEFAULT 'draft',`}
|
|
19
|
-
${c?"":'"hasDraft" INTEGER DEFAULT 0'}
|
|
20
|
-
)
|
|
21
|
-
`);}if(i.length>0)if(this.dialect==="postgres")await this.executeRaw(J.raw(i.join(`;
|
|
22
|
-
`)));else for(let e of i)await this.executeRaw(J.raw(e));for(let e of t){let s=this.getTableName(e.slug);s==="users"||s==="audit_logs"||await this.syncTableColumns(e,s);}}getColumnSqlDefinition(t,i){let e=b(t,i),s=t.name.replace(/-/g,"_").replace(/([A-Z])/g,"_$1").toLowerCase(),n=this.columnSqlType(e,i);return `"${s}" ${n} DEFAULT NULL`}columnSqlType(t,i){if(i==="sqlite")switch(t){case "varchar":return "TEXT";case "text":return "TEXT";case "integer":return "INTEGER";case "decimal":case "numeric":return "NUMERIC";case "boolean":return "INTEGER";case "timestamp":return "TEXT";case "jsonb":return "TEXT";default:return "TEXT"}switch(t){case "varchar":return "VARCHAR(255)";case "text":return "TEXT";case "integer":return "INTEGER";case "decimal":case "numeric":return "DECIMAL";case "boolean":return "BOOLEAN";case "timestamp":return "TIMESTAMP";case "jsonb":return "JSONB";default:return "TEXT"}}getExpectedColumnDefs(t,i){let e={},s=t.slug.startsWith("_globals_"),n=t.fields.some(l=>l.name==="createdAt"),o=t.fields.some(l=>l.name==="updatedAt"),a=t.fields.some(l=>l.name==="status"),r=t.fields.some(l=>l.name==="hasDraft");this.dialect==="postgres"?(e.id=s?'"id" TEXT PRIMARY KEY':'"id" UUID PRIMARY KEY DEFAULT gen_random_uuid()',n||(e.created_at='"created_at" TIMESTAMP DEFAULT NULL'),o||(e.updated_at='"updated_at" TIMESTAMP DEFAULT NULL'),a||(e.status='"status" VARCHAR(20) DEFAULT NULL'),r||(e.hasDraft='"hasDraft" BOOLEAN DEFAULT NULL')):(e.id='"id" TEXT PRIMARY KEY',n||(e.created_at='"created_at" TEXT DEFAULT NULL'),o||(e.updated_at='"updated_at" TEXT DEFAULT NULL'),a||(e.status='"status" TEXT DEFAULT NULL'),r||(e.hasDraft='"hasDraft" INTEGER DEFAULT NULL'));for(let l of t.fields){if(!l.name||l.name==="id")continue;let c=this.getColumnSqlDefinition(l,this.dialect),u=l.name.replace(/-/g,"_").replace(/([A-Z])/g,"_$1").toLowerCase();e[u]=c;}return e}async syncTableColumns(t,i){let e;try{if(this.dialect==="postgres"){let o=await this.executeRaw(J`SELECT column_name, data_type, character_maximum_length FROM information_schema.columns WHERE table_name = ${i}`);e=new Map(o.map(a=>[a.column_name,{type:a.data_type,maxLen:a.character_maximum_length}]));}else {let o=await this.executeRaw(J`PRAGMA table_info("${J.raw(i)}")`);e=new Map(o.map(a=>[a.name,{type:a.type,maxLen:null}]));}}catch{return}let s=this.getExpectedColumnDefs(t,i),n=Object.keys(s).filter(o=>!e.has(o));if(n.length>0){let o=n.map(a=>`ALTER TABLE "${i}" ADD COLUMN ${s[a]}`);await this.executeRaw(J.raw(o.join(`;
|
|
23
|
-
`)));}if(this.dialect==="postgres")for(let o of t.fields){if(!o.name||o.name==="id")continue;let a=b(o,this.dialect),r=o.name.replace(/-/g,"_").replace(/([A-Z])/g,"_$1").toLowerCase(),l=e.get(r);!l||l.type!=="character varying"||(a==="text"?await this.executeRaw(J.raw(`ALTER TABLE "${i}" ALTER COLUMN "${r}" TYPE TEXT`)):a==="jsonb"&&(await this.executeRaw(J.raw(`ALTER TABLE "${i}" ALTER COLUMN "${r}" DROP DEFAULT`)),await this.executeRaw(J.raw(`ALTER TABLE "${i}" ALTER COLUMN "${r}" TYPE JSONB USING (CASE WHEN "${r}" IS NULL THEN NULL WHEN "${r}"::text ~ '^\\s*\\{' THEN "${r}"::jsonb ELSE jsonb_build_object('id', "${r}"::text) END)`))));}}generateCreateColumns(t){let i=[];for(let e of t.fields){if(!e.name||e.name==="id")continue;let s=b(e,this.dialect),n=e.name.replace(/-/g,"_").replace(/([A-Z])/g,"_$1").toLowerCase(),o=e.required?"NOT NULL":"DEFAULT NULL",a;if(this.dialect==="sqlite")switch(s){case "varchar":case "text":a=`TEXT ${o}`;break;case "integer":a=`INTEGER ${o}`;break;case "decimal":case "numeric":a=`NUMERIC ${o}`;break;case "boolean":a=`INTEGER ${o}`;break;case "timestamp":a=`TEXT ${o}`;break;case "jsonb":a=`TEXT ${o}`;break;default:a=`TEXT ${o}`;}else switch(s){case "varchar":a=`VARCHAR(255) ${o}`;break;case "integer":a=`INTEGER ${o}`;break;case "decimal":a=`DECIMAL ${o}`;break;case "boolean":a=`BOOLEAN ${o}`;break;case "timestamp":a=`TIMESTAMP ${o}`;break;case "jsonb":a=`JSONB ${o}`;break;default:a=`TEXT ${o}`;}i.push(`"${n}" ${a}`);}return i.join(`,
|
|
24
|
-
`)+(i.length>0?",":"")}async disconnect(){this.connected=false;}async find(t){let{collection:i,where:e={},sort:s,limit:n$1=10,page:o=1,tenantId:a,select:r,draft:l}=t,c=this.getCollection(i),u=this.getTable(i),m={...e};this.tenantContext&&c.tenantScoped&&(m=c$1({where:m},i,this.tenantContext,b$2).where||{});let g=this.buildWhereClause(m,c,u,a),y=c.fields.find(h=>h.name==="status"),p$1=y?.type==="select"&&Array.isArray(y.options)&&y.options.some(h=>h.value==="published");!l&&u.status&&p$1&&g.push(n(u.status,"published"));let E=this.parseSort(s),A=!l&&u.status&&p$1?{...m,status:"published"}:m,fe=await this.count({collection:i,where:A,tenantId:a}),pe=(o-1)*n$1,z=[];try{let h=u[E.field]||u.createdAt||u.id,$=E.direction==="asc"?h:M(h),D=this.client.select().from(u);g.length>0&&(D=D.where(p(...g))),z=await D.orderBy($).limit(n$1).offset(pe);}catch(h){console.error("[DrizzleAdapter] Query error:",h);}let R=z.map(h=>this.processResult(h,c));return this.tenantContext&&!this.tenantContext.isSuperAdmin&&(R=R.filter(h=>d(h,i,this.tenantContext,b$2))),l&&(R=await Promise.all(R.map(async h=>{let $=await this.executeRaw(J`
|
|
25
|
-
SELECT * FROM kyro_versions
|
|
26
|
-
WHERE collection_slug = ${i}
|
|
27
|
-
AND document_id = ${h.id}
|
|
28
|
-
ORDER BY created_at DESC
|
|
29
|
-
LIMIT 1
|
|
30
|
-
`);if($.length>0){let D=$[0],w=D.data;for(;typeof w=="string";)try{w=JSON.parse(w);}catch{break}return (!w||typeof w!="object"||Array.isArray(w))&&(w={}),{...h,...w,status:h.status,_hasUnpublishedChanges:D.status==="draft"}}return h}))),{docs:R,...this.calculatePagination(o,n$1,fe)}}async findByID(t){let{collection:i,id:e,tenantId:s,draft:n$1}=t,o=this.getCollection(i),a=this.getTable(i),r=this.dialect==="postgres"&&typeof e=="string"?C(e):e;if(this.tenantContext&&o.tenantScoped){let p={id:r,tenantId:this.tenantContext.tenantId};if(!d(p,i,this.tenantContext,b$2))return null}let l=[n(a.id,r)];s&&a.tenantId&&l.push(n(a.tenantId,s));let c=o.fields.find(p=>p.name==="status"),u=c?.type==="select"&&Array.isArray(c.options)&&c.options.some(p=>p.value==="published");!n$1&&a.status&&u&&l.push(n(a.status,"published"));let m=l.length>1?p(...l):l[0],g=await this.client.select().from(a).where(m);if(g.length===0)return null;let y=this.processResult(g[0],o);if(n$1){let p=await this.executeRaw(J`
|
|
31
|
-
SELECT * FROM kyro_versions
|
|
32
|
-
WHERE collection_slug = ${i}
|
|
33
|
-
AND document_id = ${y.id}
|
|
34
|
-
ORDER BY created_at DESC
|
|
35
|
-
LIMIT 1
|
|
36
|
-
`);if(p.length>0){let E=p[0],A=E.data;for(;typeof A=="string";)try{A=JSON.parse(A);}catch{break}(!A||typeof A!="object"||Array.isArray(A))&&(A={}),y={...y,...A,status:y.status,_hasUnpublishedChanges:E.status==="draft"};}}return y}async create(t){let{collection:i,data:e,tenantId:s}=t,n=this.getCollection(i),o=this.getTable(i),a=this.prepareData(e,n);s&&n.tenantScoped&&(a.tenantId=s);let r=await this.client.insert(o).values(a).returning();return this.processResult(r[0],n)}async update(t){let{collection:i,id:e,data:s,tenantId:n$1}=t,o=this.getCollection(i),a=this.getTable(i),r=this.prepareData(s,o),l=this.dialect==="postgres"&&typeof e=="string"?C(e):e,c=[n(a.id,l)];n$1&&a.tenantId&&c.push(n(a.tenantId,n$1));let u=await this.client.update(a).set(r).where(p(...c)).returning();if(u.length===0)throw new Error(`Document not found: ${i}/${e}`);return this.processResult(u[0],o)}async delete(t){let{collection:i,id:e,tenantId:s}=t,n$1=this.getCollection(i),o=this.getTable(i),a=this.dialect==="postgres"&&typeof e=="string"?C(e):e,r=[n(o.id,a)];s&&o.tenantId&&r.push(n(o.tenantId,s));let l=await this.client.delete(o).where(p(...r)).returning();if(l.length===0)throw new Error(`Document not found: ${i}/${e}`);return this.processResult(l[0],n$1)}async count(t){let{collection:i,where:e={},tenantId:s}=t,n=this.getCollection(i),o=this.getTable(i),a=this.buildWhereClause(e,n,o,s);try{let r=this.client.select({count:J`count(*)`}).from(o);a.length>0&&(r=r.where(p(...a)));let l=await r;return Number(l[0]?.count||0)}catch{return 0}}async findOne(t){let{collection:i,where:e={},tenantId:s,draft:n$1}=t;if(i.startsWith("_globals_")){let a=i.replace("_globals_",""),r=this.globals.get(a);if(!r)throw new Error(`Global "${a}" not found`);let l=this.getTable(i),c=this.client.select().from(l),u=r.fields.find(p=>p.name==="status"),m=u?.type==="select"&&Array.isArray(u.options)&&u.options.some(p=>p.value==="published");!n$1&&l.status&&m&&(c=c.where(n(l.status,"published")));let g=await c.limit(1);if(g.length===0)return null;let y=this.processResult(g[0],r);if(n$1){let p=await this.executeRaw(J`
|
|
37
|
-
SELECT * FROM kyro_versions
|
|
38
|
-
WHERE collection_slug = ${i}
|
|
39
|
-
AND document_id = ${a}
|
|
40
|
-
ORDER BY created_at DESC
|
|
41
|
-
LIMIT 1
|
|
42
|
-
`);if(p.length>0){let E=p[0],A=typeof E.data=="string"?JSON.parse(E.data):E.data;y={...y,...A,status:y.status,_hasUnpublishedChanges:E.status==="draft"};}}return y}return (await this.find({...t,limit:1})).docs[0]||null}async findVersions(t){await this.ensureVersionsTable();let{collection:i,documentId:e,limit:s=10,page:n=1,tenantId:o}=t,a=(n-1)*s,r=this.getCollection(i),l=await this.executeRaw(J`
|
|
43
|
-
SELECT count(*) as count
|
|
44
|
-
FROM kyro_versions
|
|
45
|
-
WHERE collection_slug = ${i}
|
|
46
|
-
AND document_id = ${e}
|
|
47
|
-
AND autosave = 0
|
|
48
|
-
${o&&r.tenantScoped?J`AND tenant_id = ${o}`:J``}
|
|
49
|
-
`),c=parseInt(l[0]?.count||"0");return {docs:(await this.executeRaw(J`
|
|
50
|
-
SELECT *
|
|
51
|
-
FROM kyro_versions
|
|
52
|
-
WHERE collection_slug = ${i}
|
|
53
|
-
AND document_id = ${e}
|
|
54
|
-
AND autosave = 0
|
|
55
|
-
${o&&r.tenantScoped?J`AND tenant_id = ${o}`:J``}
|
|
56
|
-
ORDER BY created_at DESC
|
|
57
|
-
LIMIT ${s}
|
|
58
|
-
OFFSET ${a}
|
|
59
|
-
`)).map(m=>({...m,data:typeof m.data=="string"?JSON.parse(m.data):m.data})),...this.calculatePagination(n,s,c)}}async findVersionByID(t){await this.ensureVersionsTable();let i=this.getCollection(t.collection),e=await this.executeRaw(J`
|
|
60
|
-
SELECT * FROM kyro_versions
|
|
61
|
-
WHERE id = ${t.versionId}
|
|
62
|
-
AND collection_slug = ${t.collection}
|
|
63
|
-
${t.tenantId&&i.tenantScoped?J`AND tenant_id = ${t.tenantId}`:J``}
|
|
64
|
-
LIMIT 1
|
|
65
|
-
`);if(e.length===0)return null;let s=e[0];return {...s,data:typeof s.data=="string"?JSON.parse(s.data):s.data}}async createVersion(t){await this.ensureVersionsTable();let i=this.getCollection(t.collection),e=new Date().toISOString();if(t.autosave){let o=await this.executeRaw(J`
|
|
66
|
-
SELECT * FROM kyro_versions
|
|
67
|
-
WHERE collection_slug = ${t.collection}
|
|
68
|
-
AND document_id = ${t.documentId}
|
|
69
|
-
AND autosave = 1
|
|
70
|
-
${t.tenantId&&i.tenantScoped?J`AND tenant_id = ${t.tenantId}`:J``}
|
|
71
|
-
LIMIT 1
|
|
72
|
-
`);if(o.length>0)return await this.executeRaw(J`
|
|
73
|
-
UPDATE kyro_versions
|
|
74
|
-
SET data = ${JSON.stringify(t.data)},
|
|
75
|
-
status = ${t.status},
|
|
76
|
-
updated_at = ${e}
|
|
77
|
-
WHERE id = ${o[0].id}
|
|
78
|
-
`),this.findVersionByID({collection:t.collection,versionId:o[0].id,tenantId:t.tenantId})}let s=Math.random().toString(36).substring(2,15),n=typeof t.data=="string"?t.data:JSON.stringify(t.data);if(await this.executeRaw(J`
|
|
79
|
-
INSERT INTO kyro_versions (
|
|
80
|
-
id, collection_slug, document_id, tenant_id, data, status, autosave, created_by, change_description, created_at, updated_at
|
|
81
|
-
) VALUES (
|
|
82
|
-
${s}, ${t.collection}, ${t.documentId}, ${t.tenantId&&i.tenantScoped?t.tenantId:null},
|
|
83
|
-
${n}, ${t.status}, ${t.autosave?1:0}, ${t.createdBy||null},
|
|
84
|
-
${t.changeDescription||null}, ${e}, ${e}
|
|
85
|
-
)
|
|
86
|
-
`),!t.autosave){let o=this.getCollection(t.collection);o.versions?.maxPerDoc&&await this.deleteVersions({collection:t.collection,documentId:t.documentId,keepLatest:o.versions.maxPerDoc,tenantId:t.tenantId});}return this.findVersionByID({collection:t.collection,versionId:s,tenantId:t.tenantId})}async updateLatestVersion(t){return this.createVersion({...t,autosave:true})}async deleteVersions(t){await this.ensureVersionsTable();let i=this.getCollection(t.collection);if(t.keepLatest){let s=(await this.executeRaw(J`
|
|
87
|
-
SELECT id FROM kyro_versions
|
|
88
|
-
WHERE collection_slug = ${t.collection}
|
|
89
|
-
AND document_id = ${t.documentId}
|
|
90
|
-
AND autosave = 0
|
|
91
|
-
${t.tenantId&&i.tenantScoped?J`AND tenant_id = ${t.tenantId}`:J``}
|
|
92
|
-
ORDER BY created_at DESC
|
|
93
|
-
LIMIT ${t.keepLatest}
|
|
94
|
-
`)).map(n=>n.id);s.length>0&&await this.executeRaw(J`
|
|
95
|
-
DELETE FROM kyro_versions
|
|
96
|
-
WHERE collection_slug = ${t.collection}
|
|
97
|
-
AND document_id = ${t.documentId}
|
|
98
|
-
AND autosave = 0
|
|
99
|
-
AND id NOT IN (${J.join(s.map(n=>J`${n}`),J`, `)})
|
|
100
|
-
`);}else await this.executeRaw(J`
|
|
101
|
-
DELETE FROM kyro_versions
|
|
102
|
-
WHERE collection_slug = ${t.collection}
|
|
103
|
-
AND document_id = ${t.documentId}
|
|
104
|
-
${t.tenantId&&i.tenantScoped?J`AND tenant_id = ${t.tenantId}`:J``}
|
|
105
|
-
`);}getTable(t){let i=this.getTableName(t),e=this.schema[i];if(!e)throw new Error(`Table "${i}" not found in schema`);return e}buildWhereClause(t$1,i,e,s$1){let n$1=[];s$1&&i.tenantScoped&&e.tenantId&&n$1.push(n(e.tenantId,s$1));for(let[o$1,a]of Object.entries(t$1)){let r=o$1,l=r.toUpperCase();if(r==="id"&&this.dialect==="postgres"&&(typeof a=="string"?a=C(a):a&&typeof a=="object"&&(a.equals!==void 0&&typeof a.equals=="string"&&(a={...a,equals:C(a.equals)}),a.in&&Array.isArray(a.in)&&(a={...a,in:a.in.map(c=>typeof c=="string"?C(c):c)}))),l==="AND"&&Array.isArray(a)){let c=a.map(u=>this.buildWhereClause(u,i,e)).flat().filter(Boolean);c.length>0&&n$1.push(p(...c));}else if(l==="OR"&&Array.isArray(a)){let c=a.map(u=>this.buildWhereClause(u,i,e)).flat().filter(Boolean);c.length>0&&n$1.push(q(...c));}else if(typeof a=="object"&&a!==null&&!Array.isArray(a)){let c=e[r]||e[r.replace(/-/g,"_")]||e[r.replace(/([A-Z])/g,"_$1").toLowerCase()]||(r==="created_at"?e.createdAt:void 0)||(r==="createdAt"?e.created_at:void 0)||(r==="updated_at"?e.updatedAt:void 0)||(r==="updatedAt"?e.updated_at:void 0);if(!c)continue;a.equals!==void 0&&n$1.push(n(c,a.equals)),a.not_equals!==void 0&&n$1.push(o(c,a.not_equals)),a.in&&Array.isArray(a.in)&&(a.in.length===0?n$1.push(J`1 = 0`):n$1.push(w(c,a.in))),a.like!==void 0&&(this.dialect==="postgres"?n$1.push(G(c,a.like)):n$1.push(E(c,a.like))),a.contains!==void 0&&(this.dialect==="postgres"?n$1.push(G(c,`%${a.contains}%`)):n$1.push(E(c,`%${a.contains}%`))),a.greater_than!==void 0&&n$1.push(s(c,a.greater_than)),a.greater_than_equal!==void 0&&n$1.push(t(c,a.greater_than_equal)),a.less_than!==void 0&&n$1.push(u(c,a.less_than)),a.less_than_equal!==void 0&&n$1.push(v(c,a.less_than_equal));}else {let c=e[r]||e[r.replace(/-/g,"_")]||e[r.replace(/([A-Z])/g,"_$1").toLowerCase()];c&&n$1.push(n(c,a));}}return n$1}processResult(t,i){if(!t)return null;let e={...t};for(let s of Object.keys(e))/^\d+$/.test(s)&&delete e[s];t.id&&(e.id=String(t.id));for(let s of i.fields){if(!s.name)continue;let n=s.name.replace(/-/g,"_").replace(/([A-Z])/g,"_$1").toLowerCase();n!==s.name&&e[n]!==void 0&&e[s.name]===void 0&&(e[s.name]=e[n],delete e[n]);}for(let s of i.fields){if(["json","richtext","array","group","blocks","upload","image","list","relationship-block"].includes(s.type)){let n=s;if(e[n.name]&&typeof e[n.name]=="string")try{let o=JSON.parse(e[n.name]);e[n.name]=o;}catch{}if(s.type==="blocks"&&e[n.name]&&Array.isArray(e[n.name])){let o=n.blocks||[];e[n.name]=j(e[n.name],o);}}if(s.type==="tabs"&&"tabs"in s&&s.name){if(typeof e[s.name]=="object"&&e[s.name]!==null&&!Array.isArray(e[s.name])){for(let o of s.tabs)for(let a of o.fields)if((a.type==="upload"||a.type==="image")&&a.name){let r=e[s.name][a.name];if(typeof r=="string")try{let l=JSON.parse(r);e[s.name][a.name]=Array.isArray(l)?l.map(c=>c&&typeof c=="object"&&typeof c.id=="string"?c.id:String(c||"")):typeof l.id=="string"?l.id:String(l.id||"");}catch{}else r&&typeof r=="object"&&(e[s.name][a.name]=Array.isArray(r)?r.map(l=>l&&typeof l=="object"&&typeof l.id=="string"?l.id:String(l||"")):typeof r.id=="string"?r.id:String(r.id||""));}continue}if(typeof e[s.name]=="string")try{let o=JSON.parse(e[s.name]);if(typeof o=="object"&&o!==null){e[s.name]=o;continue}}catch{}let n={};for(let o of s.tabs)for(let a of o.fields)if(a.name&&e[a.name]!==void 0){let r=e[a.name];if(["json","richtext","array","group","blocks","upload","image","list","relationship-block"].includes(a.type)){if(r&&typeof r=="string")try{r=JSON.parse(r);}catch{}(a.type==="upload"||a.type==="image")&&r&&typeof r=="object"&&(r=Array.isArray(r)?r.map(l=>l&&typeof l=="object"&&typeof l.id=="string"?l.id:String(l||"")):typeof r.id=="string"?r.id:String(r.id||""));}n[a.name]=r,delete e[a.name];}e[s.name]=n;}}return e.createdAt&&(e.createdAt=new Date(e.createdAt).toISOString()),e.updatedAt&&(e.updatedAt=new Date(e.updatedAt).toISOString()),a$3(e)}async ensureVersionsTable(){if(this.versionsTableReady)return;let t;this.dialect==="sqlite"?t=`
|
|
106
|
-
CREATE TABLE IF NOT EXISTS kyro_versions (
|
|
107
|
-
id text PRIMARY KEY,
|
|
108
|
-
collection_slug text NOT NULL,
|
|
109
|
-
document_id text NOT NULL,
|
|
110
|
-
tenant_id text,
|
|
111
|
-
data text NOT NULL,
|
|
112
|
-
status text NOT NULL DEFAULT 'draft',
|
|
113
|
-
autosave integer NOT NULL DEFAULT 0,
|
|
114
|
-
created_by text,
|
|
115
|
-
change_description text,
|
|
116
|
-
created_at text DEFAULT (datetime('now')),
|
|
117
|
-
updated_at text DEFAULT (datetime('now'))
|
|
118
|
-
)
|
|
119
|
-
`:t=`
|
|
120
|
-
CREATE TABLE IF NOT EXISTS kyro_versions (
|
|
121
|
-
id text PRIMARY KEY,
|
|
122
|
-
collection_slug text NOT NULL,
|
|
123
|
-
document_id text NOT NULL,
|
|
124
|
-
tenant_id text,
|
|
125
|
-
data text NOT NULL,
|
|
126
|
-
status text NOT NULL,
|
|
127
|
-
autosave integer NOT NULL DEFAULT 0,
|
|
128
|
-
created_by text,
|
|
129
|
-
change_description text,
|
|
130
|
-
created_at text NOT NULL,
|
|
131
|
-
updated_at text NOT NULL
|
|
132
|
-
)
|
|
133
|
-
`,await this.executeRaw(J.raw(t));try{this.dialect==="postgres"?await this.executeRaw(J.raw("ALTER TABLE kyro_versions ADD COLUMN IF NOT EXISTS autosave integer NOT NULL DEFAULT 0")):await this.executeRaw(J.raw("ALTER TABLE kyro_versions ADD COLUMN autosave integer NOT NULL DEFAULT 0"));}catch{}this.versionsTableReady=true;}async execute(t){return this.executeRaw(t)}async executeRaw(t){let i="",e=[];if(typeof t=="string")i=t;else if(t&&(t.queryChunks||t.decoder))if(this.dialect==="postgres"){let n=new a$4().sqlToQuery(t);i=n.sql,e=n.params;}else {let n=new h().sqlToQuery(t);i=n.sql,e=n.params;}else if(t&&typeof t.toSQL=="function"){let n=t.toSQL();i=n.sql,e=n.params||[];}else i=String(t);let s=this.rawClient||this.client;if(s?.prepare&&typeof s.prepare=="function"){let n=s.prepare(i);return (e.length>0?await n.bind(...e).all():await n.all()).results||[]}if(typeof this.client?.execute=="function"){let n=await this.client.execute(t);return Array.isArray(n)?n:Array.isArray(n?.rows)?n.rows:Array.isArray(n?.[0])?n[0]:[]}return []}};function he(f){return new O(f)}export{b as a,ue as b,O as c,he as d};
|
package/dist/chunk-6TPICJ2L.js
DELETED
|
@@ -1,7 +0,0 @@
|
|
|
1
|
-
import {g}from'./chunk-Y2YAKDEQ.js';import Z from'crypto';if (typeof window === "undefined") { const { createRequire } = await import(/* @vite-ignore */ 'module'); createRequire(import.meta.url); }
|
|
2
|
-
g();g();var k=null,I=null;function Ee(e){k=e;}async function Pe(){if(k)try{let e=await k.findOne({collection:"_globals_system",where:{}});if(e){I={appSecret:e.appSecret||null,encryptionKey:e.encryptionKey||null,sessionConfig:e.sessionMaxAge||e.maxSessionsPerUser?{maxAge:(e.sessionMaxAge||7)*24*60*60*1e3,maxSessionsPerUser:e.maxSessionsPerUser||3}:null};return}}catch{}I={appSecret:process.env.APP_SECRET||"development-secret-key",encryptionKey:null,sessionConfig:null};}function ee(){return I?.appSecret?I.appSecret:process.env.APP_SECRET||"development-secret-key"}function Ae(){if(I?.encryptionKey)return I.encryptionKey;let e=ee();return Z.createHash("sha256").update(e).digest("hex")}function F(){return I?.sessionConfig?I.sessionConfig:{maxAge:10080*60*1e3,maxSessionsPerUser:3}}g();g();var te=/"(?:_|\\u0{2}5[Ff]){2}(?:p|\\u0{2}70)(?:r|\\u0{2}72)(?:o|\\u0{2}6[Ff])(?:t|\\u0{2}74)(?:o|\\u0{2}6[Ff])(?:_|\\u0{2}5[Ff]){2}"\s*:/,re=/"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/,se=/^\s*["[{]|^\s*-?\d{1,16}(\.\d{1,17})?([Ee][+-]?\d+)?\s*$/;function ne(e,t){if(e==="__proto__"||e==="constructor"&&t&&typeof t=="object"&&"prototype"in t){ie(e);return}return t}function ie(e){console.warn(`[destr] Dropping "${e}" key to prevent prototype pollution.`);}function M(e,t={}){if(typeof e!="string")return e;if(e[0]==='"'&&e[e.length-1]==='"'&&e.indexOf("\\")===-1)return e.slice(1,-1);let n=e.trim();if(n.length<=9)switch(n.toLowerCase()){case "true":return true;case "false":return false;case "undefined":return;case "null":return null;case "nan":return Number.NaN;case "infinity":return Number.POSITIVE_INFINITY;case "-infinity":return Number.NEGATIVE_INFINITY}if(!se.test(e)){if(t.strict)throw new SyntaxError("[destr] Invalid JSON");return e}try{if(te.test(e)||re.test(e)){if(t.strict)throw new Error("[destr] Possible prototype pollution");return JSON.parse(e,ne)}return JSON.parse(e)}catch(o){if(t.strict)throw o;return e}}g();function oe(e){return !e||typeof e.then!="function"?Promise.resolve(e):e}function p(e,...t){try{return oe(e(...t))}catch(n){return Promise.reject(n)}}function ae(e){let t=typeof e;return e===null||t!=="object"&&t!=="function"}function ue(e){let t=Object.getPrototypeOf(e);return !t||t.isPrototypeOf(Object)}function _(e){if(ae(e))return String(e);if(ue(e)||Array.isArray(e))return JSON.stringify(e);if(typeof e.toJSON=="function")return _(e.toJSON());throw new Error("[unstorage] Cannot stringify value!")}var B="base64:";function L(e){return typeof e=="string"?e:B+le(e)}function U(e){return typeof e!="string"||!e.startsWith(B)?e:ce(e.slice(B.length))}function ce(e){return globalThis.Buffer?Buffer.from(e,"base64"):Uint8Array.from(globalThis.atob(e),t=>t.codePointAt(0))}function le(e){return globalThis.Buffer?Buffer.from(e).toString("base64"):globalThis.btoa(String.fromCodePoint(...e))}function v(e){return e&&e.split("?")[0]?.replace(/[/\\]/g,":").replace(/:+/g,":").replace(/^:|:$/g,"")||""}function j(...e){return v(e.join(":"))}function D(e){return e=v(e),e?e+":":""}function W(e,t){if(t===void 0)return true;let n=0,o=e.indexOf(":");for(;o>-1;)n++,o=e.indexOf(":",o+1);return n<=t}function H(e,t){return t?e.startsWith(t)&&e[e.length-1]!=="$":e[e.length-1]!=="$"}var fe="memory",de=()=>{let e=new Map;return {name:fe,getInstance:()=>e,hasItem(t){return e.has(t)},getItem(t){return e.get(t)??null},getItemRaw(t){return e.get(t)??null},setItem(t,n){e.set(t,n);},setItemRaw(t,n){e.set(t,n);},removeItem(t){e.delete(t);},getKeys(){return [...e.keys()]},clear(){e.clear();},dispose(){e.clear();}}};function O(e={}){let t={mounts:{"":e.driver||de()},mountpoints:[""],watching:false,watchListeners:[],unwatch:{}},n=r=>{for(let s of t.mountpoints)if(r.startsWith(s))return {base:s,relativeKey:r.slice(s.length),driver:t.mounts[s]};return {base:"",relativeKey:r,driver:t.mounts[""]}},o=(r,s)=>t.mountpoints.filter(i=>i.startsWith(r)||s&&r.startsWith(i)).map(i=>({relativeBase:r.length>i.length?r.slice(i.length):void 0,mountpoint:i,driver:t.mounts[i]})),c=(r,s)=>{if(t.watching){s=v(s);for(let i of t.watchListeners)i(r,s);}},u=async()=>{if(!t.watching){t.watching=true;for(let r in t.mounts)t.unwatch[r]=await V(t.mounts[r],c,r);}},d=async()=>{if(t.watching){for(let r in t.unwatch)await t.unwatch[r]();t.unwatch={},t.watching=false;}},g=(r,s,i)=>{let a=new Map,l=f=>{let y=a.get(f.base);return y||(y={driver:f.driver,base:f.base,items:[]},a.set(f.base,y)),y};for(let f of r){let y=typeof f=="string",w=v(y?f:f.key),N=y?void 0:f.value,A=y||!f.options?s:{...s,...f.options},b=n(w);l(b).items.push({key:w,value:N,relativeKey:b.relativeKey,options:A});}return Promise.all([...a.values()].map(f=>i(f))).then(f=>f.flat())},m={hasItem(r,s={}){r=v(r);let{relativeKey:i,driver:a}=n(r);return p(a.hasItem,i,s)},getItem(r,s={}){r=v(r);let{relativeKey:i,driver:a}=n(r);return p(a.getItem,i,s).then(l=>M(l))},getItems(r,s={}){return g(r,s,i=>i.driver.getItems?p(i.driver.getItems,i.items.map(a=>({key:a.relativeKey,options:a.options})),s).then(a=>a.map(l=>({key:j(i.base,l.key),value:M(l.value)}))):Promise.all(i.items.map(a=>p(i.driver.getItem,a.relativeKey,a.options).then(l=>({key:a.key,value:M(l)})))))},getItemRaw(r,s={}){r=v(r);let{relativeKey:i,driver:a}=n(r);return a.getItemRaw?p(a.getItemRaw,i,s):p(a.getItem,i,s).then(l=>U(l))},async setItem(r,s,i={}){if(s===void 0)return m.removeItem(r);r=v(r);let{relativeKey:a,driver:l}=n(r);l.setItem&&(await p(l.setItem,a,_(s),i),l.watch||c("update",r));},async setItems(r,s){await g(r,s,async i=>{if(i.driver.setItems)return p(i.driver.setItems,i.items.map(a=>({key:a.relativeKey,value:_(a.value),options:a.options})),s);i.driver.setItem&&await Promise.all(i.items.map(a=>p(i.driver.setItem,a.relativeKey,_(a.value),a.options)));});},async setItemRaw(r,s,i={}){if(s===void 0)return m.removeItem(r,i);r=v(r);let{relativeKey:a,driver:l}=n(r);if(l.setItemRaw)await p(l.setItemRaw,a,s,i);else if(l.setItem)await p(l.setItem,a,L(s),i);else return;l.watch||c("update",r);},async removeItem(r,s={}){typeof s=="boolean"&&(s={removeMeta:s}),r=v(r);let{relativeKey:i,driver:a}=n(r);a.removeItem&&(await p(a.removeItem,i,s),(s.removeMeta||s.removeMata)&&await p(a.removeItem,i+"$",s),a.watch||c("remove",r));},async getMeta(r,s={}){typeof s=="boolean"&&(s={nativeOnly:s}),r=v(r);let{relativeKey:i,driver:a}=n(r),l=Object.create(null);if(a.getMeta&&Object.assign(l,await p(a.getMeta,i,s)),!s.nativeOnly){let f=await p(a.getItem,i+"$",s).then(y=>M(y));f&&typeof f=="object"&&(typeof f.atime=="string"&&(f.atime=new Date(f.atime)),typeof f.mtime=="string"&&(f.mtime=new Date(f.mtime)),Object.assign(l,f));}return l},setMeta(r,s,i={}){return this.setItem(r+"$",s,i)},removeMeta(r,s={}){return this.removeItem(r+"$",s)},async getKeys(r,s={}){r=D(r);let i=o(r,true),a=[],l=[],f=true;for(let w of i){w.driver.flags?.maxDepth||(f=false);let N=await p(w.driver.getKeys,w.relativeBase,s);for(let A of N){let b=w.mountpoint+v(A);a.some(Q=>b.startsWith(Q))||l.push(b);}a=[w.mountpoint,...a.filter(A=>!A.startsWith(w.mountpoint))];}let y=s.maxDepth!==void 0&&!f;return l.filter(w=>(!y||W(w,s.maxDepth))&&H(w,r))},async clear(r,s={}){r=D(r),await Promise.all(o(r,false).map(async i=>{if(i.driver.clear)return p(i.driver.clear,i.relativeBase,s);if(i.driver.removeItem){let a=await i.driver.getKeys(i.relativeBase||"",s);return Promise.all(a.map(l=>i.driver.removeItem(l,s)))}}));},async dispose(){await Promise.all(Object.values(t.mounts).map(r=>J(r)));},async watch(r){return await u(),t.watchListeners.push(r),async()=>{t.watchListeners=t.watchListeners.filter(s=>s!==r),t.watchListeners.length===0&&await d();}},async unwatch(){t.watchListeners=[],await d();},mount(r,s){if(r=D(r),r&&t.mounts[r])throw new Error(`already mounted at ${r}`);return r&&(t.mountpoints.push(r),t.mountpoints.sort((i,a)=>a.length-i.length)),t.mounts[r]=s,t.watching&&Promise.resolve(V(s,c,r)).then(i=>{t.unwatch[r]=i;}).catch(console.error),m},async unmount(r,s=true){r=D(r),!(!r||!t.mounts[r])&&(t.watching&&r in t.unwatch&&(t.unwatch[r]?.(),delete t.unwatch[r]),s&&await J(t.mounts[r]),t.mountpoints=t.mountpoints.filter(i=>i!==r),delete t.mounts[r]);},getMount(r=""){r=v(r)+":";let s=n(r);return {driver:s.driver,base:s.base}},getMounts(r="",s={}){return r=v(r),o(r,s.parents).map(a=>({driver:a.driver,base:a.mountpoint}))},keys:(r,s={})=>m.getKeys(r,s),get:(r,s={})=>m.getItem(r,s),set:(r,s,i={})=>m.setItem(r,s,i),has:(r,s={})=>m.hasItem(r,s),del:(r,s={})=>m.removeItem(r,s),remove:(r,s={})=>m.removeItem(r,s)};return m}function V(e,t,n){return e.watch?e.watch((o,c)=>t(o,n+c)):()=>{}}async function J(e){typeof e.dispose=="function"&&await p(e.dispose);}g();var ge="memory",G=()=>{let e=new Map;return {name:ge,getInstance:()=>e,hasItem(t){return e.has(t)},getItem(t){return e.get(t)??null},getItemRaw(t){return e.get(t)??null},setItem(t,n){e.set(t,n);},setItemRaw(t,n){e.set(t,n);},removeItem(t){e.delete(t);},getKeys(){return [...e.keys()]},clear(){e.clear();},dispose(){e.clear();}}};var X=F(),x={absoluteMaxAge:X.maxAge,maxSessionsPerUser:X.maxSessionsPerUser,refreshThreshold:300*1e3,activityDebounce:30*1e3,pollInterval:30*1e3},$="kyro-session",S=null;function C(){return globalThis.DB}function pe(){let e=null,t=()=>(e||(e=(async()=>{let u=C();u?.prepare&&await u.prepare(`CREATE TABLE IF NOT EXISTS kyro_session_store (
|
|
3
|
-
key TEXT PRIMARY KEY,
|
|
4
|
-
value TEXT,
|
|
5
|
-
expires_at INTEGER
|
|
6
|
-
)`).run();})()),e),n=()=>Date.now(),o=async(u,d=[])=>{let g=C();if(!g?.prepare)return null;let m=g.prepare(u);return d.length>0?m.bind(...d):m},c=async(u,d=[])=>{await t();let g=await o(u,d);g&&await g.run();};return {name:"kyro-d1",options:{},getInstance:()=>null,async hasItem(u){await t();let d=await o("SELECT expires_at FROM kyro_session_store WHERE key = ?",[u]);if(!d)return false;let g=await d.first();return g?!(g.expires_at&&g.expires_at<n()):false},async getItem(u){await t();let d=await o("SELECT value, expires_at FROM kyro_session_store WHERE key = ?",[u]);if(!d)return null;let g=await d.first();return g?g.expires_at&&g.expires_at<n()?(await o("DELETE FROM kyro_session_store WHERE key = ?",[u]),null):g.value:null},async setItem(u,d,g={}){let m=g?.ttl?Number(g.ttl):null,r=m?n()+m*1e3:null,s=typeof d=="string"?d:JSON.stringify(d);await c(`INSERT INTO kyro_session_store (key, value, expires_at) VALUES (?, ?, ?)
|
|
7
|
-
ON CONFLICT(key) DO UPDATE SET value = excluded.value, expires_at = excluded.expires_at`,[u,s,r]);},async removeItem(u){await c("DELETE FROM kyro_session_store WHERE key = ?",[u]);},async getKeys(u=""){await t();let d=await o("SELECT key FROM kyro_session_store WHERE key LIKE ?",[u+"%"]);return d?((await d.all()).results||[]).map(m=>m.key):[]},async clear(){await c("DELETE FROM kyro_session_store");},async dispose(){},async getMeta(){return {}},async setMeta(){},async removeMeta(){}}}async function E(){if(S)return S;if(!(typeof window>"u"&&(typeof process<"u"&&(process.env?.CLOUDFLARE||process.env?.CF_PAGES)||C())))try{let{default:t}=await import('./fs-KWBRQ6T6.js');return S=O({driver:t({base:".astro/sessions"})}),S}catch{}return C()?.prepare?(S=O({driver:pe()}),S):(S=O({driver:G()}),S)}function ve(){return Z.randomUUID()}function Y(e){let t="Unknown",n="Unknown",o="Unknown";return e.includes("Firefox")?t="Firefox":e.includes("Edg/")?t="Edge":e.includes("Chrome")?t="Chrome":e.includes("Safari")&&!e.includes("Chrome")&&(t="Safari"),e.includes("iPhone")?(n="iPhone",o="iOS"):e.includes("iPad")?(n="iPad",o="iOS"):e.includes("Mac")?(n="MacBook",o="macOS"):e.includes("Windows")?(n="Windows PC",o="Windows"):e.includes("Linux")?(n="Linux PC",o="Linux"):e.includes("Android")&&(n="Android Phone",o="Android"),{browser:t,device:n,platform:o}}function ye(e){if(!e?.userAgent)return "Session";let{browser:t,device:n}=Y(e.userAgent);return `${n} - ${t}`}function we(e){let t=e.headers.get("Cookie");return t&&Object.fromEntries(t.split("; ").map(o=>o.split("=")))[$]||null}function q(e){let t=e.headers.get("x-forwarded-for");return t?t.split(",")[0].trim():e.headers.get("x-real-ip")||"unknown"}function Ue(e,t){let o=process.env.NODE_ENV==="production"?"Secure; ":"",c=new Headers(e.headers);return c.append("Set-Cookie",`${$}=${t}; HttpOnly; Path=/; Max-Age=${x.absoluteMaxAge/1e3}; SameSite=Strict; ${o}`),new Response(e.body,{status:e.status,statusText:e.statusText,headers:c})}function je(e){let n=process.env.NODE_ENV==="production"?"Secure; ":"",o=new Headers(e.headers);return o.append("Set-Cookie",`${$}=; HttpOnly; Path=/; Max-Age=0; Expires=Thu, 01 Jan 1970 00:00:00 GMT; SameSite=Strict; ${n}`),new Response(e.body,{status:e.status,statusText:e.statusText,headers:o})}async function T(e){return await(await E()).getItem(`user:${e}`)||[]}async function z(e,t){let n=await E();t.length>0?await n.setItem(`user:${e}`,t):await n.removeItem(`user:${e}`);}async function We(e,t){let n=await E(),o=await T(e.id);for(;o.length>=x.maxSessionsPerUser;){let s=o.shift();s&&await n.removeItem(`session:${s}`);}let c=ve(),u=Date.now(),d=t?.headers.get("user-agent"),g=t?q(t):"unknown",m=d?{userAgent:d,ip:g,...Y(d)}:{ip:g},r={id:c,userId:e.id,email:e.email,role:e.role,tenantId:e.tenantId,permissions:e.permissions,createdAt:u,expiresAt:u+x.absoluteMaxAge,lastActivityAt:u,deviceInfo:m,sessionName:ye(m)};return await n.setItem(`session:${c}`,r,{ttl:Math.floor(x.absoluteMaxAge/1e3)}),o.push(c),await z(e.id,o),c}async function P(e){return await(await E()).getItem(`session:${e}`)||null}async function he(e){let t=await P(e);return t?t.expiresAt<Date.now()?(await Se(e),{valid:false,reason:"Session expired"}):{valid:true}:{valid:false,reason:"Session not found"}}async function Ie(e,t){let n=await E(),o=await P(e);if(!o)return null;let c=Date.now(),u=o.expiresAt-c,d=o.deviceInfo;if(t){let r=q(t);r!==o.deviceInfo?.ip&&(d={...o.deviceInfo,ip:r});}let g={...o,lastActivityAt:c,expiresAt:u<x.refreshThreshold?c+x.absoluteMaxAge:o.expiresAt,deviceInfo:d},m=u<x.refreshThreshold?x.absoluteMaxAge:void 0;return await n.setItem(`session:${e}`,g,m?{ttl:Math.floor(m/1e3)}:void 0),g}async function Se(e){let t=await E(),n=await P(e);if(n){let c=(await T(n.userId)).filter(u=>u!==e);await z(n.userId,c);}await t.removeItem(`session:${e}`),await t.removeItem(`activity:${e}`);}async function He(e){let t=await T(e),n=await E();for(let o of t)await n.removeItem(`session:${o}`),await n.removeItem(`activity:${o}`);await z(e,[]);}async function Ve(e,t){let n=await T(e),o=[];for(let c of n){let u=await P(c);u&&o.push({id:u.id,sessionName:u.sessionName||"Session",deviceInfo:u.deviceInfo,createdAt:u.createdAt,lastActivityAt:u.lastActivityAt,currentSession:u.id===t});}return o.sort((c,u)=>u.lastActivityAt-c.lastActivityAt),o}async function Je(e,t){let n=await P(e);return n?(await(await E()).setItem(`session:${e}`,{...n,sessionName:t}),true):false}async function Ge(e){let t=we(e);if(!t||!(await he(t)).valid)return null;let o=await P(t);return o?(await Ie(t,e),o):null}export{Ee as a,Pe as b,ee as c,Ae as d,F as e,O as f,x as g,we as h,q as i,Ue as j,je as k,We as l,P as m,he as n,Ie as o,Se as p,He as q,Ve as r,Je as s,Ge as t};
|