@kyro-cms/core 0.12.16 → 0.12.17
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 +1 -1
- package/dist/api-handler-trpc.cjs +1 -1
- package/dist/api-handler-trpc.js +1 -1
- package/dist/api-handler.cjs +1 -1
- package/dist/api-handler.js +1 -1
- package/dist/{chunk-IQYP3DDJ.cjs → chunk-BIJHVTNO.cjs} +2 -2
- package/dist/{chunk-NI7S5JMH.js → chunk-CIA3BVH3.js} +5 -5
- package/dist/{chunk-ZZIGN5PZ.js → chunk-I4ZACL66.js} +1 -1
- package/dist/{chunk-M5JUPA7G.cjs → chunk-LMIBASPC.cjs} +5 -5
- package/dist/{chunk-RY3BG3AN.cjs → chunk-RL36RMMG.cjs} +1 -1
- package/dist/{chunk-DTSYK7KK.js → chunk-YFRLT77I.js} +2 -2
- package/dist/index.cjs +26 -19
- package/dist/index.d.cts +202 -2
- package/dist/index.d.ts +202 -2
- package/dist/index.js +26 -19
- package/dist/rest/index.cjs +1 -1
- package/dist/rest/index.js +1 -1
- package/package.json +4 -2
package/dist/index.js
CHANGED
|
@@ -1,25 +1,25 @@
|
|
|
1
|
-
export{a as RedisAuthAdapter}from'./chunk-QOCHBPMK.js';export{R as allSettingsGlobals,c as blogCollections,d as blogGlobals,S as coreSettingsGlobals,W as createTemplateConfig,e as ecommerceCollections,f as ecommerceGlobals,g as kitchenSinkCollections,i as mediaCollections,a as minimalCollections,V as templateCollections}from'./chunk-FGSIHWQJ.js';export{a as kyro}from'./chunk-PTS33SK5.js';export{s as AnalyticsPlugin,t as CommentsPlugin,a as ConfigValidationError,y as Kyro,p as KyroPlugin,A as LocalAdapter,q as PluginManager,l as Registry,u as ReviewsPlugin,r as SEOPlugin,v as WishlistPlugin,x as applyCollectionOverrides,h as collectionToCreateZod,i as collectionToUpdateZod,j as collectionToWhereZod,g as collectionToZod,z as createKyro,B as createLocalAdapter,o as createRegistry,f as fieldToZod,m as getRegistry,k as globalToZod,w as presetPlugins,n as resetRegistry,b as validateCollection,e as validateConfig,d as validateFields,c as validateGlobal}from'./chunk-DTSYK7KK.js';export{d as autoBootstrap,a as bootstrapAdmin,e as bootstrapWithRetry,c as getBootstrapFromEnv}from'./chunk-O62KJ2J7.js';import'./chunk-NZ35PV5R.js';export{a as CSSGenerator,g as createAdminStyling,d as defaultDarkTheme,h as defaultFieldStyling,c as defaultLightTheme,e as ecommerce2026Theme,f as generateCSSVariables,b as generateTailwindConfig}from'./chunk-UHFDH3PG.js';export{q as ALL_FIELD_TYPES,n as COMPLEX_FIELD_TYPES,p as LAYOUT_FIELD_TYPES,m as PRIMITIVE_FIELD_TYPES,o as RELATIONAL_FIELD_TYPES,d as isArrayField,f as isBlocksField,e as isGroupField,h as isImageField,k as isLayoutField,b as isNumberField,c as isRelationshipField,i as isRichTextField,j as isSelectField,a as isTextField,g as isUploadField,t as normalizeRichTextValue,u as renderRichText,s as richTextStyles}from'./chunk-INB4LNA6.js';import'./chunk-5SEHX7ON.js';export{a as createContext,g as createCountProcedure,d as createCreateProcedure,f as createDeleteProcedure,h as createDynamicRouter,c as createFindByIDProcedure,b as createFindProcedure,i as createKyroServer,e as createUpdateProcedure}from'./chunk-ISCIUG37.js';export{c as buildGraphQLSchema,d as createGraphQLSchema}from'./chunk-PP7W5UKL.js';import {l,n,m,p,q}from'./chunk-NI7S5JMH.js';export{n as AuditLogger,p as InMemoryAuditLogger,m as InMemoryRateLimiter,r as MediaService,o as createAuditContext,s as createHonoApp,e as createLocalStorage,t as createRESTAPI,i as getAppSecret,j as getEncryptionKey,k as getSessionConfig,h as loadSecrets,d as resolveProvider,g as setDbAdapter}from'./chunk-NI7S5JMH.js';import {b,c}from'./chunk-6NGUY76Y.js';export{a as ConfigService,b as EmailTransport,c as PasswordPolicy}from'./chunk-6NGUY76Y.js';import'./chunk-K6WUOU6P.js';import'./chunk-IETGL7WJ.js';import {a as a$2}from'./chunk-IKOXCJYO.js';export{a as SQLiteAuthAdapter}from'./chunk-IKOXCJYO.js';import'./chunk-NRLIGDYF.js';export{e as ALL_WEBHOOK_EVENTS,f as WEBHOOK_COLLECTION,g as WEBHOOK_DELIVERY_COLLECTION,d as WEBHOOK_EVENTS,n as WebhookService,l as buildDeliveryRecord,m as createTestPayload,o as createWebhookService,j as deliverWebhook,k as deliverWithRetry,i as generateWebhookSecret,h as signPayload}from'./chunk-I67R6MR5.js';export{a as evaluateAccess,c as getWhereClause,b as mergeWhereClauses}from'./chunk-HLSB2MCK.js';export{b as KyroPubSub,c as KyroWSServer,a as PubSub,d as createWSServer}from'./chunk-GKYEJ2UF.js';import'./chunk-PP5S2UBV.js';export{c as DrizzleAdapter,b as collectionToDrizzleSchema,f as createDatabase,d as createDrizzleAdapter,a as fieldToDrizzleType,g as runMigrations,h as seedDefaultRoles}from'./chunk-3RR6IV5I.js';import {a as a$3}from'./chunk-RHCWCG3O.js';export{a as PostgresAuthAdapter}from'./chunk-RHCWCG3O.js';import'./chunk-OG7CNQGU.js';export{a as MongoDBAdapter,b as createMongoDBAdapter}from'./chunk-W6P4N3Z7.js';import {a as a$1}from'./chunk-IZCTG4RG.js';export{a as MongoDBAuthAdapter}from'./chunk-IZCTG4RG.js';export{a as AbstractBaseAdapter}from'./chunk-TQNM4C7H.js';import {a}from'./chunk-6SPPR5JZ.js';import'./chunk-KDNYHLD2.js';import'./chunk-5J6HXUF6.js';import K,{randomBytes}from'crypto';import {readFileSync}from'fs';import Ee,{join,resolve}from'path';export{z}from'zod';import {createStorage}from'unstorage';import jr from'unstorage/drivers/indexedb';import Qr from'unstorage/drivers/fs';async function Te(s,e){let t=e.data;for(let r of s){let o=await r({...e,data:t});o!==void 0&&(t=o);}return t}async function Sr(s,e){return Te(s,e)}var kr={maxAttempts:5,lockDuration:9e5,notifyUser:true,notifyAdmin:true,adminNotifyAfter:3},S=class{redis;prefix;config;constructor(e,t={},r="kyro:lockout:"){this.redis=e,this.prefix=r,this.config={...kr,...t};}lockKey(e){return `${this.prefix}${e}`}historyKey(e){return `${this.prefix}${e}:history`}async checkLockout(e){let t=this.lockKey(e),r=await this.redis.hgetall(t);if(!r||Object.keys(r).length===0)return {locked:false,attemptsRemaining:this.config.maxAttempts,totalAttempts:0};let o=parseInt(r.attempts,10),i=r.lockedUntil?new Date(parseInt(r.lockedUntil,10)):void 0;return i&&i>new Date?{locked:true,attemptsRemaining:0,lockedUntil:i,totalAttempts:o}:i&&i<=new Date?(await this.unlockAccount(e),{locked:false,attemptsRemaining:this.config.maxAttempts,totalAttempts:0}):{locked:false,attemptsRemaining:Math.max(0,this.config.maxAttempts-o),totalAttempts:o}}async recordFailedAttempt(e){let t=this.lockKey(e),r=this.historyKey(e),o=Date.now(),i=await this.redis.hincrby(t,"attempts",1);if(await this.redis.hset(t,"lastAttempt",o.toString()),await this.redis.lpush(r,o.toString()),await this.redis.ltrim(r,0,99),i>=this.config.maxAttempts){let n=new Date(o+this.config.lockDuration);return await this.redis.hset(t,{lockedAt:o.toString(),lockedUntil:n.getTime().toString()}),await this.redis.expire(t,Math.ceil(this.config.lockDuration/1e3)+3600),{locked:true,attemptsRemaining:0,lockedUntil:n,totalAttempts:i}}return {locked:false,attemptsRemaining:Math.max(0,this.config.maxAttempts-i),totalAttempts:i}}async lockAccount(e,t){let r=this.lockKey(e),o=Date.now(),i=t||this.config.lockDuration,n=new Date(o+i),a=this.redis.pipeline();a.hset(r,{attempts:this.config.maxAttempts.toString(),lockedAt:o.toString(),lockedUntil:n.getTime().toString()}),a.expire(r,Math.ceil(i/1e3)+3600),await a.exec();}async unlockAccount(e){let t=this.lockKey(e);await this.redis.del(t);}async resetAttempts(e){let t=this.lockKey(e);(await this.redis.hgetall(t)).lockedAt?await this.redis.hset(t,{attempts:"0",lockedAt:"",lockedUntil:""}):await this.redis.del(t);}async getLockoutHistory(e,t=10){let r=this.historyKey(e);return (await this.redis.lrange(r,0,t-1)).map(i=>new Date(parseInt(i,10)))}async getLockoutStats(e){let t=this.historyKey(e),r=await this.redis.lrange(t,0,-1),o=r.filter((n,a)=>(a+1)%this.config.maxAttempts===0).length,i=await this.redis.hget(this.lockKey(e),"lockedAt");return {totalFailedAttempts:r.length,lockoutCount:o,lastLockout:i?new Date(parseInt(i,10)):null,averageAttemptsBeforeLockout:o>0?this.config.maxAttempts:0}}shouldNotifyAdmin(e){return this.config.notifyAdmin&&e>=this.config.adminNotifyAfter}getConfig(){return {...this.config}}setConfig(e){this.config={...this.config,...e};}};var xr={"auth:login":{window:9e5,max:5},"auth:register":{window:36e5,max:3},"auth:forgot":{window:36e5,max:3},"auth:reset":{window:36e5,max:5},"auth:verify":{window:36e5,max:5},"api:general":{window:6e4,max:100},"api:authenticated":{window:6e4,max:200}},k=class{redis;prefix;limits;userLimits;constructor(e,t,r,o="kyro:ratelimit:"){this.redis=e,this.prefix=o,this.limits={...xr,...t},this.userLimits=r||{"user:api":{window:6e4,max:500},"user:write":{window:36e5,max:100}};}getKey(e,t){return `${this.prefix}${e}:${t}`}async check(e,t){let r=this.limits[e]||this.limits["api:general"],o=this.getKey(e,t),i=Date.now(),n=i-r.window,a=this.redis.pipeline();a.zremrangebyscore(o,0,n),a.zcard(o),a.zadd(o,i,`${i}:${Math.random()}`),a.expire(o,Math.ceil(r.window/1e3)+1);let l=(await a.exec())?.[1]?.[1]||0;if(l>=r.max){let p=await this.redis.zrange(o,0,0,"WITHSCORES"),d=p.length>1?parseInt(p[1],10)+r.window:i+r.window;return {allowed:false,remaining:0,resetAt:d,retryAfter:Math.ceil((d-i)/1e3)}}return {allowed:true,remaining:r.max-l-1,resetAt:i+r.window}}async checkUser(e,t,r){let o=this.userLimits[e]||this.userLimits["user:api"],i=this.getKey(`user:${e}:${t}`,r),n=Date.now(),a=n-o.window,c=this.redis.pipeline();c.zremrangebyscore(i,0,a),c.zcard(i),c.zadd(i,n,`${n}:${Math.random()}`),c.expire(i,Math.ceil(o.window/1e3)+1);let p=(await c.exec())?.[1]?.[1]||0;if(p>=o.max){let d=await this.redis.zrange(i,0,0,"WITHSCORES"),u=d.length>1?parseInt(d[1],10)+o.window:n+o.window;return {allowed:false,remaining:0,resetAt:u,retryAfter:Math.ceil((u-n)/1e3)}}return {allowed:true,remaining:o.max-p-1,resetAt:n+o.window}}async reset(e,t){let r=this.getKey(e,t);await this.redis.del(r);}async resetUser(e,t,r){let o=this.getKey(`user:${e}:${t}`,r);await this.redis.del(o);}async getStatus(e,t){let r=this.limits[e]||this.limits["api:general"],o=this.getKey(e,t),i=Date.now(),n=i-r.window;await this.redis.zremrangebyscore(o,0,n);let a=await this.redis.zcard(o);return {count:a,limit:r.max,remaining:Math.max(0,r.max-a),resetAt:i+r.window}}setLimit(e,t){this.limits[e]=t;}setUserLimit(e,t){this.userLimits[e]=t;}};var x=class{users=new Map;sessions=new Map;refreshTokens=new Map;emailToUserId=new Map;passwordHistory=new Map;emailVerificationTokens=new Map;passwordResetTokens=new Map;auditLogs=[];externalDb=false;constructor(){}async connect(){}async disconnect(){this.users.clear(),this.sessions.clear(),this.refreshTokens.clear(),this.emailToUserId.clear(),this.passwordHistory.clear();}async createUser(e){let t=randomBytes(16).toString("hex"),r=new Date().toISOString(),o=await this.hashPassword(e.password),i={id:t,email:e.email.toLowerCase(),passwordHash:o,role:e.role||"customer",tenantId:e.tenantId,createdAt:r,updatedAt:r};return this.users.set(t,i),this.emailToUserId.set(e.email.toLowerCase(),t),this.passwordHistory.set(t,[]),i}async findUserByEmail(e){let t=this.emailToUserId.get(e.toLowerCase());return t?this.findUserById(t):null}async findUserById(e){return this.users.get(e)||null}async updateUser(e,t){let r=await this.findUserById(e);if(!r)return null;let o={...r,...t,id:e,updatedAt:new Date().toISOString()};return t.email&&t.email!==r.email&&(this.emailToUserId.delete(r.email.toLowerCase()),this.emailToUserId.set(t.email.toLowerCase(),e)),this.users.set(e,o),o}async deleteUser(e){let t=await this.findUserById(e);return t?(this.users.delete(e),this.emailToUserId.delete(t.email.toLowerCase()),this.refreshTokens.forEach((r,o)=>{this.sessions.get(r)?.userId===e&&(this.refreshTokens.delete(o),this.sessions.delete(r));}),this.passwordHistory.delete(e),this.sessions.forEach((r,o)=>{r.userId===e&&this.sessions.delete(o);}),true):false}async hashPassword(e){return (await import('bcryptjs')).default.hash(e,12)}async verifyPassword(e,t){let r=await this.findUserByEmail(e);return !r||!r.passwordHash?null:await(await import('bcryptjs')).default.compare(t,r.passwordHash)?r:null}async createSession(e,t={}){let r=randomBytes(32).toString("hex"),o=randomBytes(32).toString("base64url"),i=randomBytes(32).toString("base64url"),n=new Date,a={id:r,userId:e,token:o,refreshToken:i,expiresAt:new Date(n.getTime()+86400*1e3).toISOString(),createdAt:n.toISOString(),ipAddress:t.ipAddress,userAgent:t.userAgent};return this.sessions.set(r,a),this.refreshTokens.set(i,r),a}async findSessionByToken(e){return this.sessions.get(e)||null}async findSessionByRefreshToken(e){let t=this.refreshTokens.get(e);return t&&this.sessions.get(t)||null}async deleteSession(e){let t=this.sessions.get(e);return t?(t.refreshToken&&this.refreshTokens.delete(t.refreshToken),this.sessions.delete(e),true):false}async deleteUserSessions(e){let t=0;return this.sessions.forEach((r,o)=>{r.userId===e&&(r.refreshToken&&this.refreshTokens.delete(r.refreshToken),this.sessions.delete(o),t++);}),t}async addPasswordToHistory(e,t){let r=this.passwordHistory.get(e)||[];r.push(t),r.length>5&&r.splice(0,r.length-5),this.passwordHistory.set(e,r);}async getPasswordHistory(e,t=5){return this.passwordHistory.get(e)||[]}async isPasswordInHistory(e,t,r=5){let o=await this.getPasswordHistory(t,r),i=(await import('bcryptjs')).default;for(let n of o)if(await i.compare(e,n))return true;return false}async createEmailVerificationToken(e){let t=randomBytes(32).toString("hex"),r=new Date(Date.now()+1440*60*1e3);return this.emailVerificationTokens.set(t,{userId:e,expiresAt:r}),{token:t,expiresAt:r}}async verifyEmailToken(e){let t=this.emailVerificationTokens.get(e);return !t||t.expiresAt<new Date?(this.emailVerificationTokens.delete(e),{success:false,error:"Invalid or expired token"}):(this.emailVerificationTokens.delete(e),{success:true,userId:t.userId})}async createPasswordResetToken(e){let t=await this.findUserByEmail(e);if(!t)return {token:"",expiresAt:new Date,error:"User not found"};let r=randomBytes(32).toString("hex"),o=new Date(Date.now()+3600*1e3);return this.passwordResetTokens.set(r,{userId:t.id,expiresAt:o}),{token:r,expiresAt:o}}async resetPasswordWithToken(e,t){let r=this.passwordResetTokens.get(e);if(!r||r.expiresAt<new Date)return this.passwordResetTokens.delete(e),{success:false,error:"Invalid or expired token"};let o=await this.hashPassword(t);return await this.updateUser(r.userId,{passwordHash:o}),this.passwordResetTokens.delete(e),{success:true}}async hasAnyUsers(){return this.users.size>0}async findAuditLogs(e){let{limit:t=50,offset:r=0}=e,o=this.auditLogs.slice().reverse();return e.userId&&(o=o.filter(i=>i.userId===e.userId)),e.action&&(Array.isArray(e.action)?o=o.filter(i=>e.action.includes(String(i.action))):o=o.filter(i=>i.action===e.action)),e.resource&&(o=o.filter(i=>i.resource===e.resource)),e.success!==void 0&&(o=o.filter(i=>i.success===e.success)),{logs:o.slice(r,r+t),total:o.length}}async createAuditLog(e){let t=randomBytes(16).toString("hex"),o={...e,id:t,timestamp:new Date};return this.auditLogs.push(o),o}};var T=class{storage=new Map;history=new Map;config;constructor(e={}){this.config={maxAttempts:5,lockDuration:9e5,notifyUser:true,notifyAdmin:true,adminNotifyAfter:3,...e};}async checkLockout(e){let t=Date.now(),r=this.storage.get(e);if(r&&r.lockedUntil!==null&&r.lockedUntil<=t)return await this.resetAttempts(e),{locked:false,attemptsRemaining:this.config.maxAttempts,totalAttempts:0};if(!r)return {locked:false,attemptsRemaining:this.config.maxAttempts,totalAttempts:0};let{attempts:o,lockedUntil:i}=r;return i!==null&&i>t?{locked:true,attemptsRemaining:0,lockedUntil:new Date(i),totalAttempts:o}:{locked:false,attemptsRemaining:Math.max(0,this.config.maxAttempts-o),totalAttempts:o}}async recordFailedAttempt(e){let t=Date.now(),r=this.storage.get(e)||{attempts:0,lastAttempt:null,lockedAt:null,lockedUntil:null};r.attempts+=1,r.lastAttempt=t;let o=this.history.get(e)||[];if(o.push(t),o.length>100&&o.splice(0,o.length-100),this.history.set(e,o),this.storage.set(e,r),r.attempts>=this.config.maxAttempts){let i=new Date(t+this.config.lockDuration);return r.lockedAt=t,r.lockedUntil=i.getTime(),this.storage.set(e,r),{locked:true,attemptsRemaining:0,lockedUntil:i,totalAttempts:r.attempts}}return {locked:false,attemptsRemaining:Math.max(0,this.config.maxAttempts-r.attempts),totalAttempts:r.attempts}}async lockAccount(e,t){let r=Date.now(),o=t||this.config.lockDuration,i=new Date(r+o),n=this.storage.get(e)||{attempts:0,lastAttempt:null,lockedAt:null,lockedUntil:null};n.attempts=this.config.maxAttempts,n.lockedAt=r,n.lockedUntil=i.getTime(),this.storage.set(e,n);}async unlockAccount(e){await this.resetAttempts(e);}async resetAttempts(e){let t=this.storage.get(e);t&&(t.attempts=0,t.lockedAt=null,t.lockedUntil=null,this.storage.set(e,t)),this.history.delete(e);}async getLockoutHistory(e,t=10){return (this.history.get(e)||[]).slice(-t).reverse().map(o=>new Date(o))}async getLockoutStats(e){let r=(this.history.get(e)||[]).length,o=Math.floor(r/this.config.maxAttempts),i=null,n=this.storage.get(e);n&&n.lockedAt!==null&&(i=new Date(n.lockedAt));let a=o>0?this.config.maxAttempts:0;return {totalFailedAttempts:r,lockoutCount:o,lastLockout:i,averageAttemptsBeforeLockout:a}}shouldNotifyAdmin(e){return this.config.notifyAdmin&&e>=this.config.adminNotifyAfter}getConfig(){return {...this.config}}setConfig(e){this.config={...this.config,...e};}};function h(s,e=""){return process.env[s]||e}function A(s,e=false){let t=process.env[s];return t?t.toLowerCase()==="true":e}function g(s,e=0){let t=process.env[s];return t?parseInt(t,10):e}function Pe(){let s=process.env.KYRO_AUTH_DATABASE?.toLowerCase();if(s&&["sqlite","postgres","mongodb","memory"].includes(s))return s;try{let e=join(process.cwd(),"kyro.config.ts"),t=readFileSync(e,"utf8");if(t.includes("createLocalAdapter"))return "sqlite";if(t.includes("createDrizzleAdapter"))return t.includes("postgres")||t.includes("postgresql"),"postgres";if(t.includes("createMongoDBAdapter"))return "mongodb"}catch{}return "memory"}async function Cr(s){let e=process.cwd(),t=e.endsWith("admin")?join(e,".."):e,r=resolve(t,"data","auth.db");switch(s){case "sqlite":return new a$2({path:h("KYRO_AUTH_DB_PATH",r)});case "postgres":{let o=h("DATABASE_URL","");if(o){let i,n;try{i=(await import('drizzle-orm/postgres-js')).drizzle,n=await import('postgres');}catch{a(["postgres","drizzle-orm"]),i=(await import('drizzle-orm/postgres-js')).drizzle,n=await import('postgres');}let a$1=n.default(o,{onnotice:()=>{}}),c=i(a$1);return new a$3({db:c})}return new a$2({path:h("KYRO_AUTH_DB_PATH",r)})}case "mongodb":{let o=h("MONGODB_URI","");if(o){let i;try{i=(await import('mongodb')).MongoClient;}catch{a(["mongodb"]),i=(await import('mongodb')).MongoClient;}let n=new i(o);await n.connect();let c=new URL(o).pathname.replace(/^\//,"")||"kyro_cms",l=n.db(c);return new a$1({db:l})}return new a$2({path:h("KYRO_AUTH_DB_PATH",r)})}default:return new x}}async function F(s,e){let t=A("KYRO_DISTRIBUTED",false),r;if(t){let{RedisAuthAdapter:d}=await import('./redis-adapter-NN3H4GRX.js'),u=h("REDIS_URL","redis://localhost:6379"),y=A("REDIS_TLS",false),f=new d({url:u,tls:y});await f.connect?.(),r=f;}else {let d=s||Pe();r=await Cr(d),r.connect&&await r.connect();}let o=e?await b.fromConfig(e).catch(()=>null)||b.fromEnv()||void 0:b.fromEnv()||void 0,i=new c({minLength:g("PASSWORD_MIN_LENGTH",12),requireUppercase:A("PASSWORD_REQUIRE_UPPERCASE",true),requireLowercase:A("PASSWORD_REQUIRE_LOWERCASE",true),requireNumbers:A("PASSWORD_REQUIRE_NUMBERS",true),requireSpecialChars:A("PASSWORD_REQUIRE_SPECIAL",true),preventReuse:g("PASSWORD_PREVENT_REUSE",5),maxLength:g("PASSWORD_MAX_LENGTH",128)}),n$1,a,c$1;if(t){let u=r.redis;n$1=new S(u,{maxAttempts:g("LOCKOUT_MAX_ATTEMPTS",5),lockDuration:g("LOCKOUT_DURATION_MINUTES",15)*60*1e3}),a=new k(u,{"auth:login":{window:g("RATE_LIMIT_AUTH_WINDOW_MS",9e5),max:g("RATE_LIMIT_AUTH_MAX_REQUESTS",10)},"api:general":{window:g("RATE_LIMIT_WINDOW_MS",6e4),max:g("RATE_LIMIT_MAX_REQUESTS",100)}}),c$1=new n(u,g("AUDIT_LOG_RETENTION_DAYS",30));}else n$1=new T({maxAttempts:g("LOCKOUT_MAX_ATTEMPTS",5),lockDuration:g("LOCKOUT_DURATION_MINUTES",15)*60*1e3}),a=new m({"auth:login":{window:g("RATE_LIMIT_AUTH_WINDOW_MS",9e5),max:g("RATE_LIMIT_AUTH_MAX_REQUESTS",10)},"api:general":{window:g("RATE_LIMIT_WINDOW_MS",6e4),max:g("RATE_LIMIT_MAX_REQUESTS",100)}}),c$1=A("AUDIT_LOG_ENABLED",true)?new p(g("AUDIT_LOG_RETENTION_DAYS",30)):void 0;let l=new q({redis:r,email:o,jwtSecret:h("APP_SECRET","change-me"),jwtExpiresIn:h("JWT_EXPIRES_IN","24h"),jwtIssuer:h("JWT_ISSUER","kyro-cms"),jwtAudience:h("JWT_AUDIENCE","kyro-cms-client"),passwordPolicy:i,lockout:n$1,rateLimiter:a,auditLogger:c$1,baseUrl:h("EMAIL_BASE_URL","http://localhost:4321"),emailVerificationRequired:A("EMAIL_VERIFICATION_REQUIRED",true)}),p$1=t?"distributed":s||Pe();return {authAdapter:r,databaseType:p$1,email:o,passwordPolicy:i,lockout:n$1,rateLimiter:a,auditLogger:c$1,routes:l}}var Re=F().catch(s=>(console.warn("[AuthConfig] Failed to initialize auth config:",s.message),null));var Rr=12,Dr="24h",vr="7d",L=class{adapter;config;constructor(e,t){this.adapter=e,this.config={secret:t.secret,expiresIn:t.expiresIn??Dr,refreshExpiresIn:t.refreshExpiresIn??vr,issuer:t.issuer??"kyro-cms",audience:t.audience??[],saltRounds:t.saltRounds??Rr};}async register(e){try{if(await this.adapter.findUserByEmail(e.email))return {success:!1,error:"Email already registered"};let r=await this.adapter.createUser({email:e.email,password:e.password,role:e.role??"customer",tenantId:e.tenantId});return this.createSessionForUser(r)}catch(t){return {success:false,error:String(t)}}}async login(e){try{let t=await this.adapter.verifyPassword(e.email,e.password);return t?this.createSessionForUser(t):{success:!1,error:"Invalid credentials"}}catch(t){return {success:false,error:String(t)}}}async logout(e){await this.adapter.deleteSession(e);}async refreshToken(e){try{let t=await this.adapter.findSessionByToken(e);if(!t||new Date(t.expiresAt)<new Date)return {success:!1,error:"Invalid or expired refresh token"};let r=await this.adapter.findUserById(t.userId);return r?(await this.adapter.deleteSession(e),this.createSessionForUser(r)):{success:!1,error:"User not found"}}catch(t){return {success:false,error:String(t)}}}async verifyToken(e){try{let{default:t}=await import('jsonwebtoken');return t.verify(e,this.config.secret,{issuer:this.config.issuer,audience:this.config.audience.length>0?this.config.audience[0]:void 0})}catch{return null}}async getUserFromToken(e){let t=await this.verifyToken(e);return t?this.adapter.findUserById(t.sub):null}async changePassword(e,t,r){try{let o=await this.adapter.findUserById(e);return o?await this.adapter.verifyPassword(o.email,t)?(await this.adapter.updateUser(e,{password:r}),await this.adapter.deleteUserSessions(e),{success:!0,user:o}):{success:!1,error:"Current password is incorrect"}:{success:!1,error:"User not found"}}catch(o){return {success:false,error:String(o)}}}async resetPassword(e,t){try{let r=await this.adapter.findUserByEmail(e);return r?(await this.adapter.updateUser(r.id,{password:t}),await this.adapter.deleteUserSessions(r.id),{success:!0,user:r}):{success:!1,error:"User not found"}}catch(r){return {success:false,error:String(r)}}}async sendEmailVerification(e){try{let{token:t,expiresAt:r}=await this.adapter.createEmailVerificationToken(e);return {success:!0}}catch(t){return {success:false,error:String(t)}}}async verifyEmail(e){try{return await this.adapter.verifyEmailToken(e)}catch(t){return {success:false,error:String(t)}}}async requestPasswordReset(e){try{let t=await this.adapter.createPasswordResetToken(e);return t.error?{success:!1,error:t.error}:{success:!0}}catch(t){return {success:false,error:String(t)}}}async resetPasswordWithToken(e,t){try{return await this.adapter.resetPasswordWithToken(e,t)}catch(r){return {success:false,error:String(r)}}}async deleteAccount(e){try{return await this.adapter.findUserById(e)?(await this.adapter.deleteUserSessions(e),await this.adapter.deleteUser(e),{success:!0}):{success:!1,error:"User not found"}}catch(t){return {success:false,error:String(t)}}}async createSessionForUser(e){let t=await this.generateToken(e),r=await this.adapter.createSession(e.id);return {success:true,user:e,session:r,token:t}}async generateToken(e){let{default:t}=await import('jsonwebtoken'),r={sub:e.id,email:e.email,role:e.role,tenantId:e.tenantId},o={expiresIn:this.parseExpiresIn(this.config.expiresIn)/1e3,issuer:this.config.issuer};return this.config.audience.length>0&&(o.audience=this.config.audience[0]),t.sign(r,this.config.secret,o)}async hashPassword(e){let{default:t}=await import('bcryptjs');return t.hash(e,this.config.saltRounds)}parseExpiresIn(e){if(typeof e=="number")return e;let t=e.match(/^(\d+)([smhd])$/);if(!t)return 864e5;let r=parseInt(t[1],10);switch(t[2]){case "s":return r*1e3;case "m":return r*6e4;case "h":return r*36e5;case "d":return r*864e5;default:return 864e5}}};function Lr(s,e){return new L(s,e)}function I(){return {enabled:true,draftsEnabled:true,publishEnabled:true,scheduleEnabled:false,versioningEnabled:true,maxVersionsPerDocument:50,autoPublish:false,requirePublishPermission:true}}var E=class{adapter;config;constructor(e,t){this.adapter=e,this.config={...I(),...t};}async createVersion(e){let r=((await this.adapter.getLatestVersion(e.collection,e.documentId))?.version??0)+1,o={...e,version:r},i=await this.adapter.createVersion(o);return this.config.maxVersionsPerDocument>0&&await this.pruneOldVersions(e.collection,e.documentId),i}async publishVersion(e){let t=await this.adapter.getVersion(e.collection,e.versionId);if(!t)throw new Error("Version not found");if(t.status==="published")throw new Error("Version is already published");await this.adapter.publishVersion(e);}async unpublishDocument(e,t){let r=await this.adapter.getVersions({collection:e,documentId:t,limit:1e3});for(let o of r)if(o.status==="published"){await this.createVersion({collection:e,documentId:t,data:o.data,status:"draft",createdBy:"system",changeDescription:"Unpublished document"});break}}async revertToVersion(e,t,r,o){if(!await this.adapter.getVersion(e,r))throw new Error("Version not found");return await this.adapter.revertToVersion({collection:e,documentId:t,versionId:r,userId:o})}async getVersionHistory(e,t,r=20,o=0){return this.adapter.getVersions({collection:e,documentId:t,limit:r,offset:o})}async compareTwoVersions(e,t,r,o){return this.adapter.compareVersions({collection:e,documentId:t,versionA:r,versionB:o})}async getLatestDraft(e,t){return this.adapter.getLatestVersion(e,t)}async getPublishedVersion(e,t){return this.adapter.getPublishedVersion(e,t)}async getVersion(e,t){return this.adapter.getVersion(e,t)}async schedulePublish(e,t,r,o){if(!this.config.scheduleEnabled)throw new Error("Scheduled publishing is not enabled");if(!await this.adapter.getVersion(e,r))throw new Error("Version not found")}async deleteVersionHistory(e,t){await this.adapter.deleteVersions(e,t);}async pruneOldVersions(e,t){let r=await this.adapter.getVersions({collection:e,documentId:t,limit:this.config.maxVersionsPerDocument+100});if(r.length<=this.config.maxVersionsPerDocument)return;r.slice(0,this.config.maxVersionsPerDocument);let i=r.slice(this.config.maxVersionsPerDocument);for(let n of i)if(n.status!=="published"){await this.adapter.deleteVersions(e,t);break}}};function Ir(s,e){return new E(s,e)}function Er(s){return s==="published"}function Ur(s){return s==="draft"}function Vr(s){return s==="archived"}function Or(s){return s?Array.isArray(s)?s:Object.values(s):[]}function _r(s){return s?Array.isArray(s)?s:Object.values(s):[]}function De(s){return {collections:Or(s.collections),globals:_r(s.globals),adapter:s.adapter,plugins:s.plugins,auth:s.auth,cors:s.cors,admin:s.admin,upload:s.upload,graphQL:s.graphQL,typescript:s.typescript,localization:s.localization,rateLimit:s.rateLimit,debug:s.debug}}var Mr=De;function Hr(s){let{siteSettings:e,seoSettings:t,title:r,description:o,image:i,url:n}=s;if(!e)return "";let a=e.siteName||"",c=r||t?.defaultTitle||a,l=t?.titleTemplate,p=t?.separator||" | ",d=t?.siteNameInTitle!==false,u=l?l.replace(/\{\{title\}\}/g,c).replace(/\{\{siteName\}\}/g,d?a:"").replace(/\{\{separator\}\}/g,p).replace(/\s+/g," ").trim():c,y=o||t?.defaultDescription||e.siteDescription||"",f=i||e.siteOgImage?.url||"",U=n||e.siteUrl||"",m=`
|
|
2
|
-
<title>${
|
|
1
|
+
export{a as RedisAuthAdapter}from'./chunk-QOCHBPMK.js';export{R as allSettingsGlobals,c as blogCollections,d as blogGlobals,S as coreSettingsGlobals,W as createTemplateConfig,e as ecommerceCollections,f as ecommerceGlobals,g as kitchenSinkCollections,i as mediaCollections,a as minimalCollections,V as templateCollections}from'./chunk-FGSIHWQJ.js';export{a as kyro}from'./chunk-PTS33SK5.js';export{s as AnalyticsPlugin,t as CommentsPlugin,a as ConfigValidationError,y as Kyro,p as KyroPlugin,A as LocalAdapter,q as PluginManager,l as Registry,u as ReviewsPlugin,r as SEOPlugin,v as WishlistPlugin,x as applyCollectionOverrides,h as collectionToCreateZod,i as collectionToUpdateZod,j as collectionToWhereZod,g as collectionToZod,z as createKyro,B as createLocalAdapter,o as createRegistry,f as fieldToZod,m as getRegistry,k as globalToZod,w as presetPlugins,n as resetRegistry,b as validateCollection,e as validateConfig,d as validateFields,c as validateGlobal}from'./chunk-YFRLT77I.js';export{d as autoBootstrap,a as bootstrapAdmin,e as bootstrapWithRetry,c as getBootstrapFromEnv}from'./chunk-O62KJ2J7.js';import'./chunk-NZ35PV5R.js';export{a as CSSGenerator,g as createAdminStyling,d as defaultDarkTheme,h as defaultFieldStyling,c as defaultLightTheme,e as ecommerce2026Theme,f as generateCSSVariables,b as generateTailwindConfig}from'./chunk-UHFDH3PG.js';export{q as ALL_FIELD_TYPES,n as COMPLEX_FIELD_TYPES,p as LAYOUT_FIELD_TYPES,m as PRIMITIVE_FIELD_TYPES,o as RELATIONAL_FIELD_TYPES,d as isArrayField,f as isBlocksField,e as isGroupField,h as isImageField,k as isLayoutField,b as isNumberField,c as isRelationshipField,i as isRichTextField,j as isSelectField,a as isTextField,g as isUploadField,t as normalizeRichTextValue,u as renderRichText,s as richTextStyles}from'./chunk-INB4LNA6.js';import'./chunk-5SEHX7ON.js';export{a as createContext,g as createCountProcedure,d as createCreateProcedure,f as createDeleteProcedure,h as createDynamicRouter,c as createFindByIDProcedure,b as createFindProcedure,i as createKyroServer,e as createUpdateProcedure}from'./chunk-ISCIUG37.js';export{c as buildGraphQLSchema,d as createGraphQLSchema}from'./chunk-PP7W5UKL.js';import {l,n,m,p,q as q$1}from'./chunk-CIA3BVH3.js';export{n as AuditLogger,p as InMemoryAuditLogger,m as InMemoryRateLimiter,s as MediaService,o as createAuditContext,t as createHonoApp,e as createLocalStorage,u as createRESTAPI,i as getAppSecret,j as getEncryptionKey,k as getSessionConfig,r as isEdgeRuntime,h as loadSecrets,d as resolveProvider,g as setDbAdapter}from'./chunk-CIA3BVH3.js';import {b,c}from'./chunk-6NGUY76Y.js';export{a as ConfigService,b as EmailTransport,c as PasswordPolicy}from'./chunk-6NGUY76Y.js';import'./chunk-K6WUOU6P.js';import'./chunk-IETGL7WJ.js';import {a as a$2}from'./chunk-IKOXCJYO.js';export{a as SQLiteAuthAdapter}from'./chunk-IKOXCJYO.js';import'./chunk-NRLIGDYF.js';export{e as ALL_WEBHOOK_EVENTS,f as WEBHOOK_COLLECTION,g as WEBHOOK_DELIVERY_COLLECTION,d as WEBHOOK_EVENTS,n as WebhookService,l as buildDeliveryRecord,m as createTestPayload,o as createWebhookService,j as deliverWebhook,k as deliverWithRetry,i as generateWebhookSecret,h as signPayload}from'./chunk-I67R6MR5.js';export{a as evaluateAccess,c as getWhereClause,b as mergeWhereClauses}from'./chunk-HLSB2MCK.js';export{b as KyroPubSub,c as KyroWSServer,a as PubSub,d as createWSServer}from'./chunk-GKYEJ2UF.js';import'./chunk-PP5S2UBV.js';export{c as DrizzleAdapter,b as collectionToDrizzleSchema,f as createDatabase,d as createDrizzleAdapter,a as fieldToDrizzleType,g as runMigrations,h as seedDefaultRoles}from'./chunk-3RR6IV5I.js';import {a as a$3}from'./chunk-RHCWCG3O.js';export{a as PostgresAuthAdapter}from'./chunk-RHCWCG3O.js';import'./chunk-OG7CNQGU.js';export{a as MongoDBAdapter,b as createMongoDBAdapter}from'./chunk-W6P4N3Z7.js';import {a as a$1}from'./chunk-IZCTG4RG.js';export{a as MongoDBAuthAdapter}from'./chunk-IZCTG4RG.js';import {a as a$4}from'./chunk-TQNM4C7H.js';export{a as AbstractBaseAdapter}from'./chunk-TQNM4C7H.js';import {a}from'./chunk-6SPPR5JZ.js';import'./chunk-KDNYHLD2.js';import'./chunk-5J6HXUF6.js';import W,{randomBytes}from'crypto';import {readFileSync}from'fs';import Me,{join,resolve}from'path';import {z as z$1}from'zod';export{z}from'zod';import {createStorage}from'unstorage';import Xr from'unstorage/drivers/indexedb';import to from'unstorage/drivers/fs';async function Re(s,e){let t=e.data;for(let r of s){let o=await r({...e,data:t});o!==void 0&&(t=o);}return t}async function Rr(s,e){return Re(s,e)}var R=class extends a$4{connectionString;constructor(e){super(),this.connectionString=e.connectionString;}async connect(){this.connected=true;}async disconnect(){this.connected=false;}async query(e,t=[]){if(!this.connectionString)throw new Error("NeonAdapter: Connection string is required.");try{let r=await fetch(`${this.connectionString}/sql`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({query:e,params:t})});return r.ok?(await r.json()).rows||[]:[]}catch{return []}}async find(e){return {docs:[],totalDocs:0,limit:e.limit||10,totalPages:1,page:e.page||1,hasNextPage:false,hasPrevPage:false}}async findByID(e){return null}async create(e){return e.data}async update(e){return e.data}async delete(e){return {success:true,id:e.id}}async count(e){return 0}async findOne(e){return null}async findVersions(e){return {docs:[],totalDocs:0,limit:10,totalPages:1,page:1,hasNextPage:false,hasPrevPage:false}}async findVersionByID(e){return null}async createVersion(e){return {id:"v1",parentId:e.documentId,version:e.version||1,snapshot:e.snapshot||{},createdAt:new Date().toISOString()}}async updateLatestVersion(e){return {id:"v1",parentId:e.documentId,version:e.version||1,snapshot:e.snapshot||{},createdAt:new Date().toISOString()}}async deleteVersions(e){}};function ve(s){return new R(s)}var v=class extends a$4{url;authToken;constructor(e){super(),this.url=e.url.replace(/^libsql:\/\//,"https://"),this.authToken=e.authToken;}async connect(){this.connected=true;}async disconnect(){this.connected=false;}async query(e,t=[]){if(!this.url)throw new Error("TursoAdapter: Database URL is required.");try{let r={"Content-Type":"application/json"};this.authToken&&(r.Authorization=`Bearer ${this.authToken}`);let o=await fetch(`${this.url}/v2/pipeline`,{method:"POST",headers:r,body:JSON.stringify({requests:[{type:"execute",stmt:{sql:e,args:t.map(c=>({type:"text",value:String(c)}))}},{type:"close"}]})});if(!o.ok)return [];let i=(await o.json())?.results?.[0]?.response?.result;if(!i||!i.rows)return [];let a=i.cols.map(c=>c.name);return i.rows.map(c=>{let l={};return a.forEach((d,u)=>{l[d]=c[u]?.value??null;}),l})}catch{return []}}async find(e){return {docs:[],totalDocs:0,limit:e.limit||10,totalPages:1,page:e.page||1,hasNextPage:false,hasPrevPage:false}}async findByID(e){return null}async create(e){return e.data}async update(e){return e.data}async delete(e){return {success:true,id:e.id}}async count(e){return 0}async findOne(e){return null}async findVersions(e){return {docs:[],totalDocs:0,limit:10,totalPages:1,page:1,hasNextPage:false,hasPrevPage:false}}async findVersionByID(e){return null}async createVersion(e){return {id:"v1",parentId:e.documentId,version:e.version||1,snapshot:e.snapshot||{},createdAt:new Date().toISOString()}}async updateLatestVersion(e){return {id:"v1",parentId:e.documentId,version:e.version||1,snapshot:e.snapshot||{},createdAt:new Date().toISOString()}}async deleteVersions(e){}};function De(s){return new v(s)}var vr={maxAttempts:5,lockDuration:9e5,notifyUser:true,notifyAdmin:true,adminNotifyAfter:3},x=class{redis;prefix;config;constructor(e,t={},r="kyro:lockout:"){this.redis=e,this.prefix=r,this.config={...vr,...t};}lockKey(e){return `${this.prefix}${e}`}historyKey(e){return `${this.prefix}${e}:history`}async checkLockout(e){let t=this.lockKey(e),r=await this.redis.hgetall(t);if(!r||Object.keys(r).length===0)return {locked:false,attemptsRemaining:this.config.maxAttempts,totalAttempts:0};let o=parseInt(r.attempts,10),n=r.lockedUntil?new Date(parseInt(r.lockedUntil,10)):void 0;return n&&n>new Date?{locked:true,attemptsRemaining:0,lockedUntil:n,totalAttempts:o}:n&&n<=new Date?(await this.unlockAccount(e),{locked:false,attemptsRemaining:this.config.maxAttempts,totalAttempts:0}):{locked:false,attemptsRemaining:Math.max(0,this.config.maxAttempts-o),totalAttempts:o}}async recordFailedAttempt(e){let t=this.lockKey(e),r=this.historyKey(e),o=Date.now(),n=await this.redis.hincrby(t,"attempts",1);if(await this.redis.hset(t,"lastAttempt",o.toString()),await this.redis.lpush(r,o.toString()),await this.redis.ltrim(r,0,99),n>=this.config.maxAttempts){let i=new Date(o+this.config.lockDuration);return await this.redis.hset(t,{lockedAt:o.toString(),lockedUntil:i.getTime().toString()}),await this.redis.expire(t,Math.ceil(this.config.lockDuration/1e3)+3600),{locked:true,attemptsRemaining:0,lockedUntil:i,totalAttempts:n}}return {locked:false,attemptsRemaining:Math.max(0,this.config.maxAttempts-n),totalAttempts:n}}async lockAccount(e,t){let r=this.lockKey(e),o=Date.now(),n=t||this.config.lockDuration,i=new Date(o+n),a=this.redis.pipeline();a.hset(r,{attempts:this.config.maxAttempts.toString(),lockedAt:o.toString(),lockedUntil:i.getTime().toString()}),a.expire(r,Math.ceil(n/1e3)+3600),await a.exec();}async unlockAccount(e){let t=this.lockKey(e);await this.redis.del(t);}async resetAttempts(e){let t=this.lockKey(e);(await this.redis.hgetall(t)).lockedAt?await this.redis.hset(t,{attempts:"0",lockedAt:"",lockedUntil:""}):await this.redis.del(t);}async getLockoutHistory(e,t=10){let r=this.historyKey(e);return (await this.redis.lrange(r,0,t-1)).map(n=>new Date(parseInt(n,10)))}async getLockoutStats(e){let t=this.historyKey(e),r=await this.redis.lrange(t,0,-1),o=r.filter((i,a)=>(a+1)%this.config.maxAttempts===0).length,n=await this.redis.hget(this.lockKey(e),"lockedAt");return {totalFailedAttempts:r.length,lockoutCount:o,lastLockout:n?new Date(parseInt(n,10)):null,averageAttemptsBeforeLockout:o>0?this.config.maxAttempts:0}}shouldNotifyAdmin(e){return this.config.notifyAdmin&&e>=this.config.adminNotifyAfter}getConfig(){return {...this.config}}setConfig(e){this.config={...this.config,...e};}};var Dr={"auth:login":{window:9e5,max:5},"auth:register":{window:36e5,max:3},"auth:forgot":{window:36e5,max:3},"auth:reset":{window:36e5,max:5},"auth:verify":{window:36e5,max:5},"api:general":{window:6e4,max:100},"api:authenticated":{window:6e4,max:200}},P=class{redis;prefix;limits;userLimits;constructor(e,t,r,o="kyro:ratelimit:"){this.redis=e,this.prefix=o,this.limits={...Dr,...t},this.userLimits=r||{"user:api":{window:6e4,max:500},"user:write":{window:36e5,max:100}};}getKey(e,t){return `${this.prefix}${e}:${t}`}async check(e,t){let r=this.limits[e]||this.limits["api:general"],o=this.getKey(e,t),n=Date.now(),i=n-r.window,a=this.redis.pipeline();a.zremrangebyscore(o,0,i),a.zcard(o),a.zadd(o,n,`${n}:${Math.random()}`),a.expire(o,Math.ceil(r.window/1e3)+1);let l=(await a.exec())?.[1]?.[1]||0;if(l>=r.max){let d=await this.redis.zrange(o,0,0,"WITHSCORES"),u=d.length>1?parseInt(d[1],10)+r.window:n+r.window;return {allowed:false,remaining:0,resetAt:u,retryAfter:Math.ceil((u-n)/1e3)}}return {allowed:true,remaining:r.max-l-1,resetAt:n+r.window}}async checkUser(e,t,r){let o=this.userLimits[e]||this.userLimits["user:api"],n=this.getKey(`user:${e}:${t}`,r),i=Date.now(),a=i-o.window,c=this.redis.pipeline();c.zremrangebyscore(n,0,a),c.zcard(n),c.zadd(n,i,`${i}:${Math.random()}`),c.expire(n,Math.ceil(o.window/1e3)+1);let d=(await c.exec())?.[1]?.[1]||0;if(d>=o.max){let u=await this.redis.zrange(n,0,0,"WITHSCORES"),p=u.length>1?parseInt(u[1],10)+o.window:i+o.window;return {allowed:false,remaining:0,resetAt:p,retryAfter:Math.ceil((p-i)/1e3)}}return {allowed:true,remaining:o.max-d-1,resetAt:i+o.window}}async reset(e,t){let r=this.getKey(e,t);await this.redis.del(r);}async resetUser(e,t,r){let o=this.getKey(`user:${e}:${t}`,r);await this.redis.del(o);}async getStatus(e,t){let r=this.limits[e]||this.limits["api:general"],o=this.getKey(e,t),n=Date.now(),i=n-r.window;await this.redis.zremrangebyscore(o,0,i);let a=await this.redis.zcard(o);return {count:a,limit:r.max,remaining:Math.max(0,r.max-a),resetAt:n+r.window}}setLimit(e,t){this.limits[e]=t;}setUserLimit(e,t){this.userLimits[e]=t;}};var T=class{users=new Map;sessions=new Map;refreshTokens=new Map;emailToUserId=new Map;passwordHistory=new Map;emailVerificationTokens=new Map;passwordResetTokens=new Map;auditLogs=[];externalDb=false;constructor(){}async connect(){}async disconnect(){this.users.clear(),this.sessions.clear(),this.refreshTokens.clear(),this.emailToUserId.clear(),this.passwordHistory.clear();}async createUser(e){let t=randomBytes(16).toString("hex"),r=new Date().toISOString(),o=await this.hashPassword(e.password),n={id:t,email:e.email.toLowerCase(),passwordHash:o,role:e.role||"customer",tenantId:e.tenantId,createdAt:r,updatedAt:r};return this.users.set(t,n),this.emailToUserId.set(e.email.toLowerCase(),t),this.passwordHistory.set(t,[]),n}async findUserByEmail(e){let t=this.emailToUserId.get(e.toLowerCase());return t?this.findUserById(t):null}async findUserById(e){return this.users.get(e)||null}async updateUser(e,t){let r=await this.findUserById(e);if(!r)return null;let o={...r,...t,id:e,updatedAt:new Date().toISOString()};return t.email&&t.email!==r.email&&(this.emailToUserId.delete(r.email.toLowerCase()),this.emailToUserId.set(t.email.toLowerCase(),e)),this.users.set(e,o),o}async deleteUser(e){let t=await this.findUserById(e);return t?(this.users.delete(e),this.emailToUserId.delete(t.email.toLowerCase()),this.refreshTokens.forEach((r,o)=>{this.sessions.get(r)?.userId===e&&(this.refreshTokens.delete(o),this.sessions.delete(r));}),this.passwordHistory.delete(e),this.sessions.forEach((r,o)=>{r.userId===e&&this.sessions.delete(o);}),true):false}async hashPassword(e){return (await import('bcryptjs')).default.hash(e,12)}async verifyPassword(e,t){let r=await this.findUserByEmail(e);return !r||!r.passwordHash?null:await(await import('bcryptjs')).default.compare(t,r.passwordHash)?r:null}async createSession(e,t={}){let r=randomBytes(32).toString("hex"),o=randomBytes(32).toString("base64url"),n=randomBytes(32).toString("base64url"),i=new Date,a={id:r,userId:e,token:o,refreshToken:n,expiresAt:new Date(i.getTime()+86400*1e3).toISOString(),createdAt:i.toISOString(),ipAddress:t.ipAddress,userAgent:t.userAgent};return this.sessions.set(r,a),this.refreshTokens.set(n,r),a}async findSessionByToken(e){return this.sessions.get(e)||null}async findSessionByRefreshToken(e){let t=this.refreshTokens.get(e);return t&&this.sessions.get(t)||null}async deleteSession(e){let t=this.sessions.get(e);return t?(t.refreshToken&&this.refreshTokens.delete(t.refreshToken),this.sessions.delete(e),true):false}async deleteUserSessions(e){let t=0;return this.sessions.forEach((r,o)=>{r.userId===e&&(r.refreshToken&&this.refreshTokens.delete(r.refreshToken),this.sessions.delete(o),t++);}),t}async addPasswordToHistory(e,t){let r=this.passwordHistory.get(e)||[];r.push(t),r.length>5&&r.splice(0,r.length-5),this.passwordHistory.set(e,r);}async getPasswordHistory(e,t=5){return this.passwordHistory.get(e)||[]}async isPasswordInHistory(e,t,r=5){let o=await this.getPasswordHistory(t,r),n=(await import('bcryptjs')).default;for(let i of o)if(await n.compare(e,i))return true;return false}async createEmailVerificationToken(e){let t=randomBytes(32).toString("hex"),r=new Date(Date.now()+1440*60*1e3);return this.emailVerificationTokens.set(t,{userId:e,expiresAt:r}),{token:t,expiresAt:r}}async verifyEmailToken(e){let t=this.emailVerificationTokens.get(e);return !t||t.expiresAt<new Date?(this.emailVerificationTokens.delete(e),{success:false,error:"Invalid or expired token"}):(this.emailVerificationTokens.delete(e),{success:true,userId:t.userId})}async createPasswordResetToken(e){let t=await this.findUserByEmail(e);if(!t)return {token:"",expiresAt:new Date,error:"User not found"};let r=randomBytes(32).toString("hex"),o=new Date(Date.now()+3600*1e3);return this.passwordResetTokens.set(r,{userId:t.id,expiresAt:o}),{token:r,expiresAt:o}}async resetPasswordWithToken(e,t){let r=this.passwordResetTokens.get(e);if(!r||r.expiresAt<new Date)return this.passwordResetTokens.delete(e),{success:false,error:"Invalid or expired token"};let o=await this.hashPassword(t);return await this.updateUser(r.userId,{passwordHash:o}),this.passwordResetTokens.delete(e),{success:true}}async hasAnyUsers(){return this.users.size>0}async findAuditLogs(e){let{limit:t=50,offset:r=0}=e,o=this.auditLogs.slice().reverse();return e.userId&&(o=o.filter(n=>n.userId===e.userId)),e.action&&(Array.isArray(e.action)?o=o.filter(n=>e.action.includes(String(n.action))):o=o.filter(n=>n.action===e.action)),e.resource&&(o=o.filter(n=>n.resource===e.resource)),e.success!==void 0&&(o=o.filter(n=>n.success===e.success)),{logs:o.slice(r,r+t),total:o.length}}async createAuditLog(e){let t=randomBytes(16).toString("hex"),o={...e,id:t,timestamp:new Date};return this.auditLogs.push(o),o}};var k=class{storage=new Map;history=new Map;config;constructor(e={}){this.config={maxAttempts:5,lockDuration:9e5,notifyUser:true,notifyAdmin:true,adminNotifyAfter:3,...e};}async checkLockout(e){let t=Date.now(),r=this.storage.get(e);if(r&&r.lockedUntil!==null&&r.lockedUntil<=t)return await this.resetAttempts(e),{locked:false,attemptsRemaining:this.config.maxAttempts,totalAttempts:0};if(!r)return {locked:false,attemptsRemaining:this.config.maxAttempts,totalAttempts:0};let{attempts:o,lockedUntil:n}=r;return n!==null&&n>t?{locked:true,attemptsRemaining:0,lockedUntil:new Date(n),totalAttempts:o}:{locked:false,attemptsRemaining:Math.max(0,this.config.maxAttempts-o),totalAttempts:o}}async recordFailedAttempt(e){let t=Date.now(),r=this.storage.get(e)||{attempts:0,lastAttempt:null,lockedAt:null,lockedUntil:null};r.attempts+=1,r.lastAttempt=t;let o=this.history.get(e)||[];if(o.push(t),o.length>100&&o.splice(0,o.length-100),this.history.set(e,o),this.storage.set(e,r),r.attempts>=this.config.maxAttempts){let n=new Date(t+this.config.lockDuration);return r.lockedAt=t,r.lockedUntil=n.getTime(),this.storage.set(e,r),{locked:true,attemptsRemaining:0,lockedUntil:n,totalAttempts:r.attempts}}return {locked:false,attemptsRemaining:Math.max(0,this.config.maxAttempts-r.attempts),totalAttempts:r.attempts}}async lockAccount(e,t){let r=Date.now(),o=t||this.config.lockDuration,n=new Date(r+o),i=this.storage.get(e)||{attempts:0,lastAttempt:null,lockedAt:null,lockedUntil:null};i.attempts=this.config.maxAttempts,i.lockedAt=r,i.lockedUntil=n.getTime(),this.storage.set(e,i);}async unlockAccount(e){await this.resetAttempts(e);}async resetAttempts(e){let t=this.storage.get(e);t&&(t.attempts=0,t.lockedAt=null,t.lockedUntil=null,this.storage.set(e,t)),this.history.delete(e);}async getLockoutHistory(e,t=10){return (this.history.get(e)||[]).slice(-t).reverse().map(o=>new Date(o))}async getLockoutStats(e){let r=(this.history.get(e)||[]).length,o=Math.floor(r/this.config.maxAttempts),n=null,i=this.storage.get(e);i&&i.lockedAt!==null&&(n=new Date(i.lockedAt));let a=o>0?this.config.maxAttempts:0;return {totalFailedAttempts:r,lockoutCount:o,lastLockout:n,averageAttemptsBeforeLockout:a}}shouldNotifyAdmin(e){return this.config.notifyAdmin&&e>=this.config.adminNotifyAfter}getConfig(){return {...this.config}}setConfig(e){this.config={...this.config,...e};}};function h(s,e=""){return process.env[s]||e}function A(s,e=false){let t=process.env[s];return t?t.toLowerCase()==="true":e}function g(s,e=0){let t=process.env[s];return t?parseInt(t,10):e}function Ie(){let s=process.env.KYRO_AUTH_DATABASE?.toLowerCase();if(s&&["sqlite","postgres","mongodb","memory"].includes(s))return s;try{let e=join(process.cwd(),"kyro.config.ts"),t=readFileSync(e,"utf8");if(t.includes("createLocalAdapter"))return "sqlite";if(t.includes("createDrizzleAdapter"))return t.includes("postgres")||t.includes("postgresql"),"postgres";if(t.includes("createMongoDBAdapter"))return "mongodb"}catch{}return "memory"}async function Er(s){let e=process.cwd(),t=e.endsWith("admin")?join(e,".."):e,r=resolve(t,"data","auth.db");switch(s){case "sqlite":return new a$2({path:h("KYRO_AUTH_DB_PATH",r)});case "postgres":{let o=h("DATABASE_URL","");if(o){let n,i;try{n=(await import('drizzle-orm/postgres-js')).drizzle,i=await import('postgres');}catch{a(["postgres","drizzle-orm"]),n=(await import('drizzle-orm/postgres-js')).drizzle,i=await import('postgres');}let a$1=i.default(o,{onnotice:()=>{}}),c=n(a$1);return new a$3({db:c})}return new a$2({path:h("KYRO_AUTH_DB_PATH",r)})}case "mongodb":{let o=h("MONGODB_URI","");if(o){let n;try{n=(await import('mongodb')).MongoClient;}catch{a(["mongodb"]),n=(await import('mongodb')).MongoClient;}let i=new n(o);await i.connect();let c=new URL(o).pathname.replace(/^\//,"")||"kyro_cms",l=i.db(c);return new a$1({db:l})}return new a$2({path:h("KYRO_AUTH_DB_PATH",r)})}default:return new T}}async function $(s,e){let t=A("KYRO_DISTRIBUTED",false),r;if(t){let{RedisAuthAdapter:u}=await import('./redis-adapter-NN3H4GRX.js'),p=h("REDIS_URL","redis://localhost:6379"),y=A("REDIS_TLS",false),m=new u({url:p,tls:y});await m.connect?.(),r=m;}else {let u=s||Ie();r=await Er(u),r.connect&&await r.connect();}let o=e?await b.fromConfig(e).catch(()=>null)||b.fromEnv()||void 0:b.fromEnv()||void 0,n$1=new c({minLength:g("PASSWORD_MIN_LENGTH",12),requireUppercase:A("PASSWORD_REQUIRE_UPPERCASE",true),requireLowercase:A("PASSWORD_REQUIRE_LOWERCASE",true),requireNumbers:A("PASSWORD_REQUIRE_NUMBERS",true),requireSpecialChars:A("PASSWORD_REQUIRE_SPECIAL",true),preventReuse:g("PASSWORD_PREVENT_REUSE",5),maxLength:g("PASSWORD_MAX_LENGTH",128)}),i,a,c$1;if(t){let p=r.redis;i=new x(p,{maxAttempts:g("LOCKOUT_MAX_ATTEMPTS",5),lockDuration:g("LOCKOUT_DURATION_MINUTES",15)*60*1e3}),a=new P(p,{"auth:login":{window:g("RATE_LIMIT_AUTH_WINDOW_MS",9e5),max:g("RATE_LIMIT_AUTH_MAX_REQUESTS",10)},"api:general":{window:g("RATE_LIMIT_WINDOW_MS",6e4),max:g("RATE_LIMIT_MAX_REQUESTS",100)}}),c$1=new n(p,g("AUDIT_LOG_RETENTION_DAYS",30));}else i=new k({maxAttempts:g("LOCKOUT_MAX_ATTEMPTS",5),lockDuration:g("LOCKOUT_DURATION_MINUTES",15)*60*1e3}),a=new m({"auth:login":{window:g("RATE_LIMIT_AUTH_WINDOW_MS",9e5),max:g("RATE_LIMIT_AUTH_MAX_REQUESTS",10)},"api:general":{window:g("RATE_LIMIT_WINDOW_MS",6e4),max:g("RATE_LIMIT_MAX_REQUESTS",100)}}),c$1=A("AUDIT_LOG_ENABLED",true)?new p(g("AUDIT_LOG_RETENTION_DAYS",30)):void 0;let l=new q$1({redis:r,email:o,jwtSecret:h("APP_SECRET","change-me"),jwtExpiresIn:h("JWT_EXPIRES_IN","24h"),jwtIssuer:h("JWT_ISSUER","kyro-cms"),jwtAudience:h("JWT_AUDIENCE","kyro-cms-client"),passwordPolicy:n$1,lockout:i,rateLimiter:a,auditLogger:c$1,baseUrl:h("EMAIL_BASE_URL","http://localhost:4321"),emailVerificationRequired:A("EMAIL_VERIFICATION_REQUIRED",true)}),d=t?"distributed":s||Ie();return {authAdapter:r,databaseType:d,email:o,passwordPolicy:n$1,lockout:i,rateLimiter:a,auditLogger:c$1,routes:l}}var Ee=$().catch(s=>(console.warn("[AuthConfig] Failed to initialize auth config:",s.message),null));var Or=12,Ur="24h",Vr="7d",U=class{adapter;config;constructor(e,t){this.adapter=e,this.config={secret:t.secret,expiresIn:t.expiresIn??Ur,refreshExpiresIn:t.refreshExpiresIn??Vr,issuer:t.issuer??"kyro-cms",audience:t.audience??[],saltRounds:t.saltRounds??Or};}async register(e){try{if(await this.adapter.findUserByEmail(e.email))return {success:!1,error:"Email already registered"};let r=await this.adapter.createUser({email:e.email,password:e.password,role:e.role??"customer",tenantId:e.tenantId});return this.createSessionForUser(r)}catch(t){return {success:false,error:String(t)}}}async login(e){try{let t=await this.adapter.verifyPassword(e.email,e.password);return t?this.createSessionForUser(t):{success:!1,error:"Invalid credentials"}}catch(t){return {success:false,error:String(t)}}}async logout(e){await this.adapter.deleteSession(e);}async refreshToken(e){try{let t=await this.adapter.findSessionByToken(e);if(!t||new Date(t.expiresAt)<new Date)return {success:!1,error:"Invalid or expired refresh token"};let r=await this.adapter.findUserById(t.userId);return r?(await this.adapter.deleteSession(e),this.createSessionForUser(r)):{success:!1,error:"User not found"}}catch(t){return {success:false,error:String(t)}}}async verifyToken(e){try{let{default:t}=await import('jsonwebtoken');return t.verify(e,this.config.secret,{issuer:this.config.issuer,audience:this.config.audience.length>0?this.config.audience[0]:void 0})}catch{return null}}async getUserFromToken(e){let t=await this.verifyToken(e);return t?this.adapter.findUserById(t.sub):null}async changePassword(e,t,r){try{let o=await this.adapter.findUserById(e);return o?await this.adapter.verifyPassword(o.email,t)?(await this.adapter.updateUser(e,{password:r}),await this.adapter.deleteUserSessions(e),{success:!0,user:o}):{success:!1,error:"Current password is incorrect"}:{success:!1,error:"User not found"}}catch(o){return {success:false,error:String(o)}}}async resetPassword(e,t){try{let r=await this.adapter.findUserByEmail(e);return r?(await this.adapter.updateUser(r.id,{password:t}),await this.adapter.deleteUserSessions(r.id),{success:!0,user:r}):{success:!1,error:"User not found"}}catch(r){return {success:false,error:String(r)}}}async sendEmailVerification(e){try{let{token:t,expiresAt:r}=await this.adapter.createEmailVerificationToken(e);return {success:!0}}catch(t){return {success:false,error:String(t)}}}async verifyEmail(e){try{return await this.adapter.verifyEmailToken(e)}catch(t){return {success:false,error:String(t)}}}async requestPasswordReset(e){try{let t=await this.adapter.createPasswordResetToken(e);return t.error?{success:!1,error:t.error}:{success:!0}}catch(t){return {success:false,error:String(t)}}}async resetPasswordWithToken(e,t){try{return await this.adapter.resetPasswordWithToken(e,t)}catch(r){return {success:false,error:String(r)}}}async deleteAccount(e){try{return await this.adapter.findUserById(e)?(await this.adapter.deleteUserSessions(e),await this.adapter.deleteUser(e),{success:!0}):{success:!1,error:"User not found"}}catch(t){return {success:false,error:String(t)}}}async createSessionForUser(e){let t=await this.generateToken(e),r=await this.adapter.createSession(e.id);return {success:true,user:e,session:r,token:t}}async generateToken(e){let{default:t}=await import('jsonwebtoken'),r={sub:e.id,email:e.email,role:e.role,tenantId:e.tenantId},o={expiresIn:this.parseExpiresIn(this.config.expiresIn)/1e3,issuer:this.config.issuer};return this.config.audience.length>0&&(o.audience=this.config.audience[0]),t.sign(r,this.config.secret,o)}async hashPassword(e){let{default:t}=await import('bcryptjs');return t.hash(e,this.config.saltRounds)}parseExpiresIn(e){if(typeof e=="number")return e;let t=e.match(/^(\d+)([smhd])$/);if(!t)return 864e5;let r=parseInt(t[1],10);switch(t[2]){case "s":return r*1e3;case "m":return r*6e4;case "h":return r*36e5;case "d":return r*864e5;default:return 864e5}}};function _r(s,e){return new U(s,e)}function V(){return {enabled:true,draftsEnabled:true,publishEnabled:true,scheduleEnabled:false,versioningEnabled:true,maxVersionsPerDocument:50,autoPublish:false,requirePublishPermission:true}}var _=class{adapter;config;constructor(e,t){this.adapter=e,this.config={...V(),...t};}async createVersion(e){let r=((await this.adapter.getLatestVersion(e.collection,e.documentId))?.version??0)+1,o={...e,version:r},n=await this.adapter.createVersion(o);return this.config.maxVersionsPerDocument>0&&await this.pruneOldVersions(e.collection,e.documentId),n}async publishVersion(e){let t=await this.adapter.getVersion(e.collection,e.versionId);if(!t)throw new Error("Version not found");if(t.status==="published")throw new Error("Version is already published");await this.adapter.publishVersion(e);}async unpublishDocument(e,t){let r=await this.adapter.getVersions({collection:e,documentId:t,limit:1e3});for(let o of r)if(o.status==="published"){await this.createVersion({collection:e,documentId:t,data:o.data,status:"draft",createdBy:"system",changeDescription:"Unpublished document"});break}}async revertToVersion(e,t,r,o){if(!await this.adapter.getVersion(e,r))throw new Error("Version not found");return await this.adapter.revertToVersion({collection:e,documentId:t,versionId:r,userId:o})}async getVersionHistory(e,t,r=20,o=0){return this.adapter.getVersions({collection:e,documentId:t,limit:r,offset:o})}async compareTwoVersions(e,t,r,o){return this.adapter.compareVersions({collection:e,documentId:t,versionA:r,versionB:o})}async getLatestDraft(e,t){return this.adapter.getLatestVersion(e,t)}async getPublishedVersion(e,t){return this.adapter.getPublishedVersion(e,t)}async getVersion(e,t){return this.adapter.getVersion(e,t)}async schedulePublish(e,t,r,o){if(!this.config.scheduleEnabled)throw new Error("Scheduled publishing is not enabled");if(!await this.adapter.getVersion(e,r))throw new Error("Version not found")}async deleteVersionHistory(e,t){await this.adapter.deleteVersions(e,t);}async pruneOldVersions(e,t){let r=await this.adapter.getVersions({collection:e,documentId:t,limit:this.config.maxVersionsPerDocument+100});if(r.length<=this.config.maxVersionsPerDocument)return;r.slice(0,this.config.maxVersionsPerDocument);let n=r.slice(this.config.maxVersionsPerDocument);for(let i of n)if(i.status!=="published"){await this.adapter.deleteVersions(e,t);break}}};function Mr(s,e){return new _(s,e)}function Hr(s){return s==="published"}function Fr(s){return s==="draft"}function Nr(s){return s==="archived"}function Br(s){return s?Array.isArray(s)?s:Object.values(s):[]}function Kr(s){return s?Array.isArray(s)?s:Object.values(s):[]}function Oe(s){return {collections:Br(s.collections),globals:Kr(s.globals),adapter:s.adapter,plugins:s.plugins,auth:s.auth,cors:s.cors,admin:s.admin,upload:s.upload,graphQL:s.graphQL,typescript:s.typescript,localization:s.localization,rateLimit:s.rateLimit,debug:s.debug}}var $r=Oe;function zr(s){let{siteSettings:e,seoSettings:t,title:r,description:o,image:n,url:i}=s;if(!e)return "";let a=e.siteName||"",c=r||t?.defaultTitle||a,l=t?.titleTemplate,d=t?.separator||" | ",u=t?.siteNameInTitle!==false,p=l?l.replace(/\{\{title\}\}/g,c).replace(/\{\{siteName\}\}/g,u?a:"").replace(/\{\{separator\}\}/g,d).replace(/\s+/g," ").trim():c,y=o||t?.defaultDescription||e.siteDescription||"",m=n||e.siteOgImage?.url||"",D=i||e.siteUrl||"",f=`
|
|
2
|
+
<title>${p}</title>
|
|
3
3
|
<meta name="description" content="${y}">
|
|
4
|
-
`;e.siteFavicon?.url&&(
|
|
5
|
-
<link rel="icon" type="${e.siteFavicon.mimeType||"image/x-icon"}" href="${e.siteFavicon.url}">`);let
|
|
6
|
-
<meta name="robots" content="${
|
|
7
|
-
<link rel="canonical" href="${
|
|
8
|
-
<meta property="og:type" content="${
|
|
9
|
-
<meta property="og:title" content="${
|
|
4
|
+
`;e.siteFavicon?.url&&(f+=`
|
|
5
|
+
<link rel="icon" type="${e.siteFavicon.mimeType||"image/x-icon"}" href="${e.siteFavicon.url}">`);let Q=t?.meta?.robots;Q&&(f+=`
|
|
6
|
+
<meta name="robots" content="${Q}">`);let Y=t?.meta?.canonicalUrl||D;Y&&(f+=`
|
|
7
|
+
<link rel="canonical" href="${Y}">`);let Fe=t?.meta?.ogType||"website";f+=`
|
|
8
|
+
<meta property="og:type" content="${Fe}">
|
|
9
|
+
<meta property="og:title" content="${p}">
|
|
10
10
|
<meta property="og:description" content="${y}">
|
|
11
11
|
<meta property="og:site_name" content="${a}">
|
|
12
|
-
`,
|
|
13
|
-
<meta property="og:url" content="${
|
|
14
|
-
<meta property="og:image" content="${
|
|
15
|
-
<meta property="fb:app_id" content="${t.social.fbAppId}">`);let
|
|
16
|
-
<meta name="twitter:card" content="${
|
|
17
|
-
<meta name="twitter:title" content="${
|
|
12
|
+
`,D&&(f+=`
|
|
13
|
+
<meta property="og:url" content="${D}">`),m&&(f+=`
|
|
14
|
+
<meta property="og:image" content="${m}">`),t?.social?.fbAppId&&(f+=`
|
|
15
|
+
<meta property="fb:app_id" content="${t.social.fbAppId}">`);let Ne=t?.social?.twitterCardType||"summary_large_image";return f+=`
|
|
16
|
+
<meta name="twitter:card" content="${Ne}">
|
|
17
|
+
<meta name="twitter:title" content="${p}">
|
|
18
18
|
<meta name="twitter:description" content="${y}">
|
|
19
|
-
`,t?.social?.twitterHandle&&(
|
|
20
|
-
<meta name="twitter:site" content="${t.social.twitterHandle}">`),
|
|
21
|
-
<meta name="twitter:image" content="${
|
|
22
|
-
<meta http-equiv="content-language" content="${e.i18n.language}">`),
|
|
19
|
+
`,t?.social?.twitterHandle&&(f+=`
|
|
20
|
+
<meta name="twitter:site" content="${t.social.twitterHandle}">`),m&&(f+=`
|
|
21
|
+
<meta name="twitter:image" content="${m}">`),e.enableI18n&&e.i18n?.language&&(f+=`
|
|
22
|
+
<meta http-equiv="content-language" content="${e.i18n.language}">`),f}function jr(s){if(!s||!s.analyticsEnabled||!s.analytics)return "";let{googleAnalyticsId:e,googleTagManagerId:t,plausibleDomain:r}=s.analytics,o="";return e&&(o+=`
|
|
23
23
|
<!-- Google Analytics -->
|
|
24
24
|
<script async src="https://www.googletagmanager.com/gtag/js?id=${e}"></script>
|
|
25
25
|
<script>
|
|
@@ -40,4 +40,11 @@ export{a as RedisAuthAdapter}from'./chunk-QOCHBPMK.js';export{R as allSettingsGl
|
|
|
40
40
|
`),r&&(o+=`
|
|
41
41
|
<!-- Plausible Analytics -->
|
|
42
42
|
<script defer data-domain="${r}" src="https://plausible.io/js/script.js"></script>
|
|
43
|
-
`),o}var
|
|
43
|
+
`),o}var Wr={facebook:{label:"Facebook"},twitter:{label:"Twitter / X"},instagram:{label:"Instagram"},linkedin:{label:"LinkedIn"},youtube:{label:"YouTube"},tiktok:{label:"TikTok"},pinterest:{label:"Pinterest"},discord:{label:"Discord"},twitch:{label:"Twitch"},github:{label:"GitHub"},mastodon:{label:"Mastodon"}},qr=["facebook","twitter","instagram","linkedin","youtube","tiktok","pinterest","discord","twitch","github","mastodon"];function Ue(s){if(!s)return [];let e=s.showAll===true,t=[];for(let r of qr){let o=s[r];if(!o||["tiktok","pinterest","discord","twitch","github","mastodon"].includes(r)&&!e)continue;let i=Wr[r];t.push({platform:r,url:o,label:i?.label||r});}return t}async function Gr(s,e){try{let t=await s.findOne({collection:"_globals_social-settings",where:{},draft:e?.draft??!1});return Ue(t)}catch{return []}}function Ve(s){return s?{storeName:s.storeName,storeEmail:s.storeEmail,storePhone:s.storePhone,address:s.address,currency:s.currency,tax:s.tax,shipping:s.shipping,orders:s.orders}:{}}async function Qr(s,e){try{let t=await s.findOne({collection:"_globals_store-settings",where:{},draft:e?.draft??!1});return Ve(t)}catch{return {}}}function _e(s){return s?{testMode:s.testMode,provider:s.provider,stripe:s.stripe,paypal:s.paypal,square:s.square,methods:s.methods,bankTransfer:s.bankTransfer}:{}}async function Yr(s,e){try{let t=await s.findOne({collection:"_globals_payment-settings",where:{},draft:e?.draft??!1});return _e(t)}catch{return {}}}async function z(s={}){let{namespace:e="kyro",ttl:t}=s,r=createStorage({driver:Xr({dbName:"kyro-cms",storeName:e})}),o=e?`${e}:`:"";return {storage:{getItem:async i=>{let a=`${o}${i}`,c=await r.getItem(a);if(c==null)return null;try{let l=JSON.parse(c);return l.expiry&&Date.now()>l.expiry?(await r.removeItem(a),null):l.value}catch{return c}},setItem:async(i,a)=>{let c=`${o}${i}`,l=JSON.stringify(t?{value:a,expiry:Date.now()+t}:{value:a});await r.setItem(c,l);},removeItem:async i=>{await r.removeItem(`${o}${i}`);}},cleanup:async()=>{await r.dispose?.();}}}function j(s){let e=s||process.env.APP_SECRET||process.env.AUTH_SECRET||"development-secret-key";return W.createHash("sha256").update(e).digest("hex")}function ro(s,e){let t=W.randomBytes(16),r=W.createCipheriv("aes-256-gcm",Buffer.from(e,"hex").subarray(0,32),t),o=r.update(s,"utf8","hex");o+=r.final("hex");let n=r.getAuthTag().toString("hex");return `${t.toString("hex")}:${n}:${o}`}function oo(s,e){let[t,r,o]=s.split(":"),n=Buffer.from(t,"hex"),i=Buffer.from(r,"hex"),a=W.createDecipheriv("aes-256-gcm",Buffer.from(e,"hex").subarray(0,32),n);a.setAuthTag(i);let c=a.update(o,"hex","utf8");return c+=a.final("utf8"),c}async function q(s={}){let{namespace:e="kyro",ttl:t,encryption:r=true,secret:o,basePath:n}=s,i=n?Me.join(n,".astro","kyro.json"):Me.join(process.cwd(),".astro","kyro.json"),a=createStorage({driver:to({base:i})}),c=r?j(o):null,l=e?`${e}:`:"";return {storage:{getItem:async d=>{let u=`${l}${d}`,p=await a.getItem(u);if(p==null)return null;try{let y=c?oo(p,c):p,m=JSON.parse(y);return m.expiry&&Date.now()>m.expiry?(await a.removeItem(u),null):m.value}catch{return p}},setItem:async(d,u)=>{let p=`${l}${d}`,y=JSON.stringify(t?{value:u,expiry:Date.now()+t}:{value:u});await a.setItem(p,c?ro(y,c):y);},removeItem:async d=>{await a.removeItem(`${l}${d}`);}},cleanup:async()=>{await a.dispose?.();}}}async function G(s){let{environment:e,adapter:t,connectionString:r,encryption:o}=s,n=process.env.APP_SECRET||process.env.AUTH_SECRET,i={enabled:o?.enabled??true,algorithm:o?.algorithm};return e==="browser"?z({namespace:"kyro"}):q({namespace:"kyro",encryption:i.enabled,secret:n})}async function He(s){let e={...s,encryption:{enabled:true,algorithm:s.encryption?.algorithm}};return G(e)}l();function so(s){return {name:"kyro-loader",load:async e=>{let{store:t,logger:r,parseData:o}=e;r.info(`Loading Kyro CMS collection: "${s.collection}"`);try{let n=[];t.clear();for(let i of n){let a=String(i.id||i._id),c=await o({id:a,data:i});t.set({id:a,data:c,digest:JSON.stringify(c)});}r.info(`Successfully synced ${n.length} entries for "${s.collection}" into Astro store.`);}catch(n){r.error(`Failed to load Kyro collection "${s.collection}": ${n.message}`);}},schema:z$1.object({id:z$1.string(),createdAt:z$1.string().optional(),updatedAt:z$1.string().optional()}).passthrough()}}function io(s){return {input:s.schema||z$1.object({}).passthrough(),handler:async(t,r)=>{try{return {success:!0,collection:s.collection,action:s.action,data:t,timestamp:new Date().toISOString()}}catch(o){return {success:false,error:o.message||"CMS Action Execution Failed"}}}}}function ao(s={}){let e=s.protectedRoutes||[],t=s.loginPath||"/admin/login",r=s.cookieName||"kyro_session";return async(o,n)=>{let{request:i,cookies:a,redirect:c,locals:l}=o,d=new URL(i.url),u=a?.get?.(r)?.value||i.headers.get("authorization")?.replace("Bearer ",""),p=null;return u&&(p={id:"user_1",email:"admin@kyro.dev",role:"admin"}),l.kyroUser=p,e.some(m=>new RegExp("^"+m.replace(/\*/g,".*")+"$").test(d.pathname))&&!p?c(`${t}?redirect=${encodeURIComponent(d.pathname)}`):n()}}function co(s){let e=s?.collections||[],t=`// Auto-generated by Kyro CMS
|
|
44
|
+
declare module 'kyro:collections' {
|
|
45
|
+
export interface KyroCollections {
|
|
46
|
+
`;for(let r of e){let o=r.name||r.slug;t+=` '${o}': Record<string, any>;
|
|
47
|
+
`;}return t+=` }
|
|
48
|
+
}
|
|
49
|
+
`,t}function lo(s={}){return {APP_SECRET:{context:"server",access:"secret",type:"string",optional:false},DATABASE_URL:{context:"server",access:"secret",type:"string",optional:!s.requireDatabase},PUBLIC_KYRO_URL:{context:"client",access:"public",type:"string",optional:true,default:"http://localhost:4321"}}}function uo(s={}){return {name:"kyro-dev-toolbar-integration",hooks:{"astro:config:setup":({addDevToolbarApp:e})=>{s.enabled!==false&&typeof e=="function"&&e({id:"kyro-cms",name:"Kyro CMS",icon:'<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M12 2L2 7l10 5 10-5-10-5zM2 17l10 5 10-5M2 12l10 5 10-5"/></svg>',entrypoint:"@kyro-cms/core/dev-toolbar-app"});}}}}
|
|
50
|
+
export{x as AccountLockout,U as Auth,k as InMemoryAccountLockout,T as InMemoryAuthAdapter,R as NeonAdapter,P as RateLimiter,v as TursoAdapter,_ as VersionManager,Ee as authConfig,_r as createAuth,$ as createAuthConfig,He as createAuthStorage,ve as createNeonAdapter,G as createStorage,De as createTursoAdapter,Mr as createVersionManager,Oe as defineConfig,$r as defineKyroConfig,jr as generateAnalyticsTags,co as generateKyroAstroTypes,zr as generateSeoTags,V as getDefaultDraftPublishConfig,Yr as getPaymentConfig,_e as getPaymentConfigFromSettings,Gr as getSocialLinks,Ue as getSocialLinksFromSettings,Qr as getStoreConfig,Ve as getStoreConfigFromSettings,Nr as isArchived,Fr as isDraft,Hr as isPublished,io as kyroAction,ao as kyroAuthMiddleware,uo as kyroDevToolbarIntegration,lo as kyroEnvSchema,so as kyroLoader,Rr as runFieldHooks,Re as runHooks};
|
package/dist/rest/index.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
'use strict';var
|
|
1
|
+
'use strict';var chunkLMIBASPC_cjs=require('../chunk-LMIBASPC.cjs');require('../chunk-GCQTSPX6.cjs'),require('../chunk-WIZ6C5QZ.cjs'),require('../chunk-GO34AOBZ.cjs'),require('../chunk-HOP4D5XZ.cjs'),require('../chunk-HVXO3OFB.cjs'),require('../chunk-XUONID6O.cjs'),require('../chunk-NY47CFVP.cjs'),require('../chunk-3ZFRP5M2.cjs'),require('../chunk-GYQMNXXW.cjs'),require('../chunk-MIOMMB23.cjs'),require('../chunk-HHH4XNNS.cjs'),require('../chunk-EJDIR56C.cjs'),require('../chunk-D5P2IPGX.cjs'),require('../chunk-Q3Q7BJVQ.cjs'),require('../chunk-AHSFSERC.cjs');Object.defineProperty(exports,"createHonoApp",{enumerable:true,get:function(){return chunkLMIBASPC_cjs.t}});Object.defineProperty(exports,"createRESTAPI",{enumerable:true,get:function(){return chunkLMIBASPC_cjs.u}});
|
package/dist/rest/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export{
|
|
1
|
+
export{t as createHonoApp,u as createRESTAPI}from'../chunk-CIA3BVH3.js';import'../chunk-6NGUY76Y.js';import'../chunk-K6WUOU6P.js';import'../chunk-IETGL7WJ.js';import'../chunk-IKOXCJYO.js';import'../chunk-NRLIGDYF.js';import'../chunk-I67R6MR5.js';import'../chunk-HLSB2MCK.js';import'../chunk-3RR6IV5I.js';import'../chunk-RHCWCG3O.js';import'../chunk-OG7CNQGU.js';import'../chunk-IZCTG4RG.js';import'../chunk-TQNM4C7H.js';import'../chunk-6SPPR5JZ.js';import'../chunk-KDNYHLD2.js';import'../chunk-5J6HXUF6.js';
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@kyro-cms/core",
|
|
3
|
-
"version": "0.12.
|
|
3
|
+
"version": "0.12.17",
|
|
4
4
|
"description": "Astro-native headless CMS with multi-database adapters, multi-protocol APIs, and multi-vendor support",
|
|
5
5
|
"engines": {
|
|
6
6
|
"node": ">=22"
|
|
@@ -190,7 +190,7 @@
|
|
|
190
190
|
"ws": "^8.18.0",
|
|
191
191
|
"zod": "^3.24.0",
|
|
192
192
|
"zod-to-json-schema": "^3.25.2",
|
|
193
|
-
"@kyro-cms/ai": "0.12.
|
|
193
|
+
"@kyro-cms/ai": "0.12.17"
|
|
194
194
|
},
|
|
195
195
|
"devDependencies": {
|
|
196
196
|
"@types/better-sqlite3": "^7.6.13",
|
|
@@ -253,6 +253,8 @@
|
|
|
253
253
|
"db:push": "drizzle-kit push",
|
|
254
254
|
"db:studio": "drizzle-kit studio",
|
|
255
255
|
"db:seed": "tsx src/database/drizzle/seed.ts",
|
|
256
|
+
"docs:dev": "pnpm --filter @kyro-cms/docs dev",
|
|
257
|
+
"docs:build": "pnpm --filter @kyro-cms/docs build",
|
|
256
258
|
"publish:packages": "node scripts/publish.js",
|
|
257
259
|
"publish:dry": "node scripts/publish.js --dry-run"
|
|
258
260
|
}
|