@kyro-cms/core 0.12.49 → 0.12.51
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.d.cts +2 -1
- package/dist/api-handler.d.ts +2 -1
- package/dist/api-handler.js +1 -1
- package/dist/{bootstrap-4FK3LPPH.js → bootstrap-5DPLIKCR.js} +1 -1
- package/dist/bootstrap-ND37CWFL.cjs +1 -0
- package/dist/{chunk-LGYBTBWE.js → chunk-6OIEZHOE.js} +2 -2
- package/dist/{chunk-HKNQVI76.cjs → chunk-754DLK7M.cjs} +1 -1
- package/dist/{chunk-26Q7JXM4.cjs → chunk-EEBI65GB.cjs} +2 -2
- package/dist/{chunk-JR6IOJO7.js → chunk-EVCRNJBG.js} +9 -9
- package/dist/{chunk-7N7U2ERH.js → chunk-G3B5RM2F.js} +2 -2
- package/dist/{chunk-EFGOYI57.js → chunk-HJXUDJC4.js} +15 -15
- package/dist/{chunk-YUER4JU3.cjs → chunk-KBQTMHP3.cjs} +153 -34
- package/dist/{chunk-63BSQ3FK.cjs → chunk-LHYVQSFE.cjs} +1 -1
- package/dist/{chunk-PENOCINR.js → chunk-Q63LWE6P.js} +154 -35
- package/dist/{chunk-CFZVJTXW.cjs → chunk-RYTA4NYP.cjs} +14 -14
- package/dist/chunk-VF6IW6WG.js +2 -0
- package/dist/{chunk-WC7H45ZG.cjs → chunk-XYICMRHL.cjs} +8 -8
- package/dist/cli/index.cjs +1 -1
- package/dist/cli/index.js +1 -1
- package/dist/index.cjs +5 -5
- package/dist/index.d.cts +102 -1
- package/dist/index.d.ts +102 -1
- package/dist/index.js +6 -6
- package/dist/rest/index.cjs +1 -1
- package/dist/rest/index.js +1 -1
- package/dist/templates/index.cjs +1 -1
- package/dist/templates/index.js +1 -1
- package/package.json +2 -2
- package/dist/bootstrap-F4SDJLPK.cjs +0 -1
- package/dist/chunk-24L3UEJJ.js +0 -2
package/dist/index.d.ts
CHANGED
|
@@ -122,6 +122,7 @@ declare class Kyro {
|
|
|
122
122
|
shutdown(): Promise<void>;
|
|
123
123
|
}
|
|
124
124
|
declare function createKyro(config: KyroConfig): Kyro;
|
|
125
|
+
declare function createKyroHandler(config: KyroConfig): (req: Request$1 | any, context?: any) => Promise<Response>;
|
|
125
126
|
|
|
126
127
|
interface BaseEmailOptions {
|
|
127
128
|
title: string;
|
|
@@ -178,6 +179,42 @@ declare function renderUserInvite(inviteUrl: string, roleName?: string, inviterN
|
|
|
178
179
|
text: string;
|
|
179
180
|
};
|
|
180
181
|
|
|
182
|
+
declare function renderNewLogin(location: string, time: string, userName?: string): {
|
|
183
|
+
subject: string;
|
|
184
|
+
html: string;
|
|
185
|
+
text: string;
|
|
186
|
+
};
|
|
187
|
+
|
|
188
|
+
declare function renderOrderConfirmation(orderId: string, customerName: string | undefined, totalAmount: string, trackingUrl?: string): {
|
|
189
|
+
subject: string;
|
|
190
|
+
html: string;
|
|
191
|
+
text: string;
|
|
192
|
+
};
|
|
193
|
+
|
|
194
|
+
declare function renderOrderShipped(orderId: string, customerName: string | undefined, trackingNumber: string, trackingUrl: string): {
|
|
195
|
+
subject: string;
|
|
196
|
+
html: string;
|
|
197
|
+
text: string;
|
|
198
|
+
};
|
|
199
|
+
|
|
200
|
+
declare function renderOrderDelivered(orderId: string, customerName: string | undefined, reviewUrl: string): {
|
|
201
|
+
subject: string;
|
|
202
|
+
html: string;
|
|
203
|
+
text: string;
|
|
204
|
+
};
|
|
205
|
+
|
|
206
|
+
declare function renderOrderRefunded(orderId: string, customerName: string | undefined, refundAmount: string): {
|
|
207
|
+
subject: string;
|
|
208
|
+
html: string;
|
|
209
|
+
text: string;
|
|
210
|
+
};
|
|
211
|
+
|
|
212
|
+
declare function renderAbandonedCart(customerName: string | undefined, checkoutUrl: string): {
|
|
213
|
+
subject: string;
|
|
214
|
+
html: string;
|
|
215
|
+
text: string;
|
|
216
|
+
};
|
|
217
|
+
|
|
181
218
|
/**
|
|
182
219
|
* Returns complete EmailTemplates registry for EmailTransport
|
|
183
220
|
*/
|
|
@@ -222,6 +259,31 @@ declare function getEmailTemplates(): {
|
|
|
222
259
|
html: string;
|
|
223
260
|
text: string;
|
|
224
261
|
};
|
|
262
|
+
orderConfirmation: (orderId: string, customerName?: string, totalAmount?: string, trackingUrl?: string) => {
|
|
263
|
+
subject: string;
|
|
264
|
+
html: string;
|
|
265
|
+
text: string;
|
|
266
|
+
};
|
|
267
|
+
orderShipped: (orderId: string, customerName?: string, trackingNumber?: string, trackingUrl?: string) => {
|
|
268
|
+
subject: string;
|
|
269
|
+
html: string;
|
|
270
|
+
text: string;
|
|
271
|
+
};
|
|
272
|
+
orderDelivered: (orderId: string, customerName?: string, reviewUrl?: string) => {
|
|
273
|
+
subject: string;
|
|
274
|
+
html: string;
|
|
275
|
+
text: string;
|
|
276
|
+
};
|
|
277
|
+
orderRefunded: (orderId: string, customerName?: string, refundAmount?: string) => {
|
|
278
|
+
subject: string;
|
|
279
|
+
html: string;
|
|
280
|
+
text: string;
|
|
281
|
+
};
|
|
282
|
+
abandonedCart: (customerName?: string, checkoutUrl?: string) => {
|
|
283
|
+
subject: string;
|
|
284
|
+
html: string;
|
|
285
|
+
text: string;
|
|
286
|
+
};
|
|
225
287
|
};
|
|
226
288
|
|
|
227
289
|
declare class ConfigValidationError extends Error {
|
|
@@ -570,6 +632,41 @@ interface EmailTemplates {
|
|
|
570
632
|
html: string;
|
|
571
633
|
text: string;
|
|
572
634
|
};
|
|
635
|
+
magicLink: (link: string, code?: string, userName?: string) => {
|
|
636
|
+
subject: string;
|
|
637
|
+
html: string;
|
|
638
|
+
text: string;
|
|
639
|
+
};
|
|
640
|
+
userInvite: (inviteUrl: string, roleName?: string, inviterName?: string) => {
|
|
641
|
+
subject: string;
|
|
642
|
+
html: string;
|
|
643
|
+
text: string;
|
|
644
|
+
};
|
|
645
|
+
orderConfirmation: (orderId: string, customerName?: string, totalAmount?: string, trackingUrl?: string) => {
|
|
646
|
+
subject: string;
|
|
647
|
+
html: string;
|
|
648
|
+
text: string;
|
|
649
|
+
};
|
|
650
|
+
orderShipped: (orderId: string, customerName?: string, trackingNumber?: string, trackingUrl?: string) => {
|
|
651
|
+
subject: string;
|
|
652
|
+
html: string;
|
|
653
|
+
text: string;
|
|
654
|
+
};
|
|
655
|
+
orderDelivered: (orderId: string, customerName?: string, reviewUrl?: string) => {
|
|
656
|
+
subject: string;
|
|
657
|
+
html: string;
|
|
658
|
+
text: string;
|
|
659
|
+
};
|
|
660
|
+
orderRefunded: (orderId: string, customerName?: string, refundAmount?: string) => {
|
|
661
|
+
subject: string;
|
|
662
|
+
html: string;
|
|
663
|
+
text: string;
|
|
664
|
+
};
|
|
665
|
+
abandonedCart: (customerName?: string, checkoutUrl?: string) => {
|
|
666
|
+
subject: string;
|
|
667
|
+
html: string;
|
|
668
|
+
text: string;
|
|
669
|
+
};
|
|
573
670
|
}
|
|
574
671
|
declare class EmailTransport {
|
|
575
672
|
private transporter?;
|
|
@@ -798,6 +895,7 @@ declare class AuthRoutes {
|
|
|
798
895
|
private auditLogger?;
|
|
799
896
|
private baseUrl;
|
|
800
897
|
private emailVerificationRequired;
|
|
898
|
+
private jwtSecret;
|
|
801
899
|
constructor(config: AuthRoutesConfig);
|
|
802
900
|
private getBaseUrl;
|
|
803
901
|
register(req: Request): Promise<Response>;
|
|
@@ -819,6 +917,9 @@ declare class AuthRoutes {
|
|
|
819
917
|
refreshSession(req: Request): Promise<Response>;
|
|
820
918
|
private errorResponse;
|
|
821
919
|
private rateLimitResponse;
|
|
920
|
+
requestMagicLink(req: Request): Promise<Response>;
|
|
921
|
+
verifyMagicLink(req: Request): Promise<Response>;
|
|
922
|
+
inviteUser(req: Request): Promise<Response>;
|
|
822
923
|
}
|
|
823
924
|
|
|
824
925
|
type DatabaseType = "sqlite" | "postgres" | "mongodb" | "memory";
|
|
@@ -1549,4 +1650,4 @@ declare class Logger {
|
|
|
1549
1650
|
}
|
|
1550
1651
|
declare const logger: Logger;
|
|
1551
1652
|
|
|
1552
|
-
export { AbstractBaseAdapter, AccountLockout, type AdapterOptions, AuditLog, AuditLogFilter, AuditLogger, Auth, AuthAdapter, AuthResult, Session as AuthSession, AuthTokenConfig, AuthUser, BaseAdapter, type BaseEmailOptions, CollectionConfig, type CompareVersionsOptions, ConfigValidationError, CreateArgs, type CreateStorageResult, type CreateVersionOptions, type DatabaseConnectionOptions, type DatabaseType, type DatabaseType$1 as DbAdapterType, DeleteArgs, DeliveryOptions, DeliveryResult, Dialect, type DraftPublishConfig, type DrizzleAdapterOptions, EmailTransport, type EncryptionConfig, type Environment, Field, FindArgs, FindByIDArgs, FindResult, GlobalConfig, InMemoryAccountLockout, InMemoryAuditLogger, InMemoryAuthAdapter, InMemoryRateLimiter, JWTPayload, Kyro, type KyroActionOptions, type KyroAuthConfig, type KyroAuthMiddlewareOptions, KyroConfig, type KyroDevToolbarOptions, type KyroEnvSchemaOptions, type KyroLoaderOptions, KyroPubSub, KyroWSServer, LocalAdapter, type LogLevel, Logger, LoginCredentials, MediaService, type MongoDBAdapterOptions, NeonAdapter, type NeonAdapterOptions, PasswordPolicy, type PaymentConfig, PluginManager, type PublishVersionOptions, RateLimiter, RedisAuthAdapter, RegisterData, Registry, Request$1 as Request, SQLiteAuthAdapter, type SeoTagsOptions, Session, type SocialLink, type StorageAdapter, type StorageOptions, type StoreConfig, TursoAdapter, type TursoAdapterOptions, UpdateArgs, User, UserRole, type Version, type VersionAdapter, type VersionDiff, type VersionHistoryOptions, VersionManager, type VersionPublishSchedule, type VersionStatus, WebhookConfig, WebhookDelivery, WebhookPayload, WebhookService, applyCollectionOverrides, authConfig, autoBootstrap, bootstrapAdmin, bootstrapWithRetry, buildDeliveryRecord, collectionToCreateZod, collectionToUpdateZod, collectionToWhereZod, collectionToZod, createAuditContext, createAuth, createAuthConfig, createAuthStorage, createKyro, createLocalAdapter, createLocalStorage, createNeonAdapter, createStorage, createTestPayload, createTursoAdapter, createVersionManager, defineConfig, defineKyroConfig, deliverWebhook, deliverWithRetry, fieldToZod, generateAnalyticsTags, generateKyroAstroTypes, generateSeoTags, generateWebhookSecret, getAppSecret, getBootstrapFromEnv, getDefaultDraftPublishConfig, getEmailTemplates, getEncryptionKey, getPaymentConfig, getPaymentConfigFromSettings, getSessionConfig, getSocialLinks, getSocialLinksFromSettings, getStoreConfig, getStoreConfigFromSettings, globalToZod, isArchived, isDraft, isEdgeRuntime, isPublished, kyroAction, kyroAuthMiddleware, kyroDevToolbarIntegration, kyroEnvSchema, kyroLoader, loadSecrets, logger, renderAccountLocked, renderBaseLayout, renderMagicLink, renderPasswordChanged, renderResetPassword, renderUserInvite, renderVerifyEmail, renderWelcome, setDbAdapter, signPayload, validateCollection, validateConfig, validateFields, validateGlobal };
|
|
1653
|
+
export { AbstractBaseAdapter, AccountLockout, type AdapterOptions, AuditLog, AuditLogFilter, AuditLogger, Auth, AuthAdapter, AuthResult, Session as AuthSession, AuthTokenConfig, AuthUser, BaseAdapter, type BaseEmailOptions, CollectionConfig, type CompareVersionsOptions, ConfigValidationError, CreateArgs, type CreateStorageResult, type CreateVersionOptions, type DatabaseConnectionOptions, type DatabaseType, type DatabaseType$1 as DbAdapterType, DeleteArgs, DeliveryOptions, DeliveryResult, Dialect, type DraftPublishConfig, type DrizzleAdapterOptions, EmailTransport, type EncryptionConfig, type Environment, Field, FindArgs, FindByIDArgs, FindResult, GlobalConfig, InMemoryAccountLockout, InMemoryAuditLogger, InMemoryAuthAdapter, InMemoryRateLimiter, JWTPayload, Kyro, type KyroActionOptions, type KyroAuthConfig, type KyroAuthMiddlewareOptions, KyroConfig, type KyroDevToolbarOptions, type KyroEnvSchemaOptions, type KyroLoaderOptions, KyroPubSub, KyroWSServer, LocalAdapter, type LogLevel, Logger, LoginCredentials, MediaService, type MongoDBAdapterOptions, NeonAdapter, type NeonAdapterOptions, PasswordPolicy, type PaymentConfig, PluginManager, type PublishVersionOptions, RateLimiter, RedisAuthAdapter, RegisterData, Registry, Request$1 as Request, SQLiteAuthAdapter, type SeoTagsOptions, Session, type SocialLink, type StorageAdapter, type StorageOptions, type StoreConfig, TursoAdapter, type TursoAdapterOptions, UpdateArgs, User, UserRole, type Version, type VersionAdapter, type VersionDiff, type VersionHistoryOptions, VersionManager, type VersionPublishSchedule, type VersionStatus, WebhookConfig, WebhookDelivery, WebhookPayload, WebhookService, applyCollectionOverrides, authConfig, autoBootstrap, bootstrapAdmin, bootstrapWithRetry, buildDeliveryRecord, collectionToCreateZod, collectionToUpdateZod, collectionToWhereZod, collectionToZod, createAuditContext, createAuth, createAuthConfig, createAuthStorage, createKyro, createKyroHandler, createLocalAdapter, createLocalStorage, createNeonAdapter, createStorage, createTestPayload, createTursoAdapter, createVersionManager, defineConfig, defineKyroConfig, deliverWebhook, deliverWithRetry, fieldToZod, generateAnalyticsTags, generateKyroAstroTypes, generateSeoTags, generateWebhookSecret, getAppSecret, getBootstrapFromEnv, getDefaultDraftPublishConfig, getEmailTemplates, getEncryptionKey, getPaymentConfig, getPaymentConfigFromSettings, getSessionConfig, getSocialLinks, getSocialLinksFromSettings, getStoreConfig, getStoreConfigFromSettings, globalToZod, isArchived, isDraft, isEdgeRuntime, isPublished, kyroAction, kyroAuthMiddleware, kyroDevToolbarIntegration, kyroEnvSchema, kyroLoader, loadSecrets, logger, renderAbandonedCart, renderAccountLocked, renderBaseLayout, renderMagicLink, renderNewLogin, renderOrderConfirmation, renderOrderDelivered, renderOrderRefunded, renderOrderShipped, renderPasswordChanged, renderResetPassword, renderUserInvite, renderVerifyEmail, renderWelcome, setDbAdapter, signPayload, validateCollection, validateConfig, validateFields, validateGlobal };
|
package/dist/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
export{a as LocalAdapter,b as createLocalAdapter}from'./chunk-PRMILS4Y.js';export{a as RedisAuthAdapter}from'./chunk-M75VGFCI.js';import {a as a$5}from'./chunk-RPRGGGIW.js';export{k as allGlobalSettings,q as blogCollections,l as coreGlobalSettings,V as createTemplateConfig,r as ecommerceCollections,s as ecommerceGlobals,t as kitchenSinkCollections,v as mediaCollections,a as minimalCollections,U as templateCollections}from'./chunk-
|
|
2
|
-
g();g();g();g();async function He(n,e){let t=e.data;for(let r of n){let o=await r({...e,data:t});o!==void 0&&(t=o);}return t}async function Nr(n,e){return He(n,e)}g();g();g();var E=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 Fe(n){return new E(n)}g();var O=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(l=>({type:"text",value:String(l)}))}},{type:"close"}]})});if(!o.ok)return [];let i=(await o.json())?.results?.[0]?.response?.result;if(!i||!i.rows)return [];let c=i.cols.map(l=>l.name);return i.rows.map(l=>{let p={};return c.forEach((g,m)=>{p[g]=l[m]?.value??null;}),p})}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 Ke(n){return new O(n)}g();g();g();g();var $r={maxAttempts:5,lockDuration:9e5,notifyUser:true,notifyAdmin:true,adminNotifyAfter:3},R=class{redis;prefix;config;constructor(e,t={},r="kyro:lockout:"){this.redis=e,this.prefix=r,this.config={...$r,...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),s=r.lockedUntil?new Date(parseInt(r.lockedUntil,10)):void 0;return s&&s>new Date?{locked:true,attemptsRemaining:0,lockedUntil:s,totalAttempts:o}:s&&s<=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(),s=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),s>=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:s}}return {locked:false,attemptsRemaining:Math.max(0,this.config.maxAttempts-s),totalAttempts:s}}async lockAccount(e,t){let r=this.lockKey(e),o=Date.now(),s=t||this.config.lockDuration,i=new Date(o+s),c=this.redis.pipeline();c.hset(r,{attempts:this.config.maxAttempts.toString(),lockedAt:o.toString(),lockedUntil:i.getTime().toString()}),c.expire(r,Math.ceil(s/1e3)+3600),await c.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(s=>new Date(parseInt(s,10)))}async getLockoutStats(e){let t=this.historyKey(e),r=await this.redis.lrange(t,0,-1),o=r.filter((i,c)=>(c+1)%this.config.maxAttempts===0).length,s=await this.redis.hget(this.lockKey(e),"lockedAt");return {totalFailedAttempts:r.length,lockoutCount:o,lastLockout:s?new Date(parseInt(s,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};}};g();var zr={"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}},v=class{redis;prefix;limits;userLimits;constructor(e,t,r,o="kyro:ratelimit:"){this.redis=e,this.prefix=o,this.limits={...zr,...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),s=Date.now(),i=s-r.window,c=this.redis.pipeline();c.zremrangebyscore(o,0,i),c.zcard(o),c.zadd(o,s,`${s}:${Math.random()}`),c.expire(o,Math.ceil(r.window/1e3)+1);let p=(await c.exec())?.[1]?.[1]||0;if(p>=r.max){let g=await this.redis.zrange(o,0,0,"WITHSCORES"),m=g.length>1?parseInt(g[1],10)+r.window:s+r.window;return {allowed:false,remaining:0,resetAt:m,retryAfter:Math.ceil((m-s)/1e3)}}return {allowed:true,remaining:r.max-p-1,resetAt:s+r.window}}async checkUser(e,t,r){let o=this.userLimits[e]||this.userLimits["user:api"],s=this.getKey(`user:${e}:${t}`,r),i=Date.now(),c=i-o.window,l=this.redis.pipeline();l.zremrangebyscore(s,0,c),l.zcard(s),l.zadd(s,i,`${i}:${Math.random()}`),l.expire(s,Math.ceil(o.window/1e3)+1);let g=(await l.exec())?.[1]?.[1]||0;if(g>=o.max){let m=await this.redis.zrange(s,0,0,"WITHSCORES"),f=m.length>1?parseInt(m[1],10)+o.window:i+o.window;return {allowed:false,remaining:0,resetAt:f,retryAfter:Math.ceil((f-i)/1e3)}}return {allowed:true,remaining:o.max-g-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),s=Date.now(),i=s-r.window;await this.redis.zremrangebyscore(o,0,i);let c=await this.redis.zcard(o);return {count:c,limit:r.max,remaining:Math.max(0,r.max-c),resetAt:s+r.window}}setLimit(e,t){this.limits[e]=t;}setUserLimit(e,t){this.userLimits[e]=t;}};g();g();g();var D=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),s={id:t,email:e.email.toLowerCase(),passwordHash:o,role:e.role||"customer",tenantId:e.tenantId,createdAt:r,updatedAt:r};return this.users.set(t,s),this.emailToUserId.set(e.email.toLowerCase(),t),this.passwordHistory.set(t,[]),s}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-ZEEHSMAG.js')).default.hash(e,12)}async verifyPassword(e,t){let r=await this.findUserByEmail(e);return !r||!r.passwordHash?null:await(await import('./bcryptjs-ZEEHSMAG.js')).default.compare(t,r.passwordHash)?r:null}async createSession(e,t={}){let r=randomBytes(32).toString("hex"),o=randomBytes(32).toString("base64url"),s=randomBytes(32).toString("base64url"),i=new Date,c={id:r,userId:e,token:o,refreshToken:s,expiresAt:new Date(i.getTime()+86400*1e3).toISOString(),createdAt:i.toISOString(),ipAddress:t.ipAddress,userAgent:t.userAgent};return this.sessions.set(r,c),this.refreshTokens.set(s,r),c}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),s=(await import('./bcryptjs-ZEEHSMAG.js')).default;for(let i of o)if(await s.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(s=>s.userId===e.userId)),e.action&&(Array.isArray(e.action)?o=o.filter(s=>e.action.includes(String(s.action))):o=o.filter(s=>s.action===e.action)),e.resource&&(o=o.filter(s=>s.resource===e.resource)),e.success!==void 0&&(o=o.filter(s=>s.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}};g();var I=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:s}=r;return s!==null&&s>t?{locked:true,attemptsRemaining:0,lockedUntil:new Date(s),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 s=new Date(t+this.config.lockDuration);return r.lockedAt=t,r.lockedUntil=s.getTime(),this.storage.set(e,r),{locked:true,attemptsRemaining:0,lockedUntil:s,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,s=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=s.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),s=null,i=this.storage.get(e);i&&i.lockedAt!==null&&(s=new Date(i.lockedAt));let c=o>0?this.config.maxAttempts:0;return {totalFailedAttempts:r,lockoutCount:o,lastLockout:s,averageAttemptsBeforeLockout:c}}shouldNotifyAdmin(e){return this.config.notifyAdmin&&e>=this.config.adminNotifyAfter}getConfig(){return {...this.config}}setConfig(e){this.config={...this.config,...e};}};function b(n,e=""){return process.env[n]||e}function k(n,e=false){let t=process.env[n];return t?t.toLowerCase()==="true":e}function y(n,e=0){let t=process.env[n];return t?parseInt(t,10):e}function Be(){let n=process.env.KYRO_AUTH_DATABASE?.toLowerCase();if(n&&["sqlite","postgres","mongodb","memory"].includes(n))return n;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 qr(n){let e=process.cwd(),t=e.endsWith("admin")?join(e,".."):e,r=resolve(t,"data","auth.db");switch(n){case "sqlite":return new a$2({path:b("KYRO_AUTH_DB_PATH",r)});case "postgres":{let o=b("DATABASE_URL","");if(o){let s,i;try{s=(await import('./postgres-js-4CI7FMYS.js')).drizzle,i=await import('./src-QBADSZV4.js');}catch{a(["postgres","drizzle-orm"]),s=(await import('./postgres-js-4CI7FMYS.js')).drizzle,i=await import('./src-QBADSZV4.js');}let c=i.default(o,{onnotice:()=>{}}),l=s(c);return new a$3({db:l})}return new a$2({path:b("KYRO_AUTH_DB_PATH",r)})}case "mongodb":{let o=b("MONGODB_URI","");if(o){let s;try{let g=await import('./lib-XXYYUPMW.js');s=g.MongoClient??g.default?.MongoClient;}catch{a(["mongodb"]);let m=await import('./lib-XXYYUPMW.js');s=m.MongoClient??m.default?.MongoClient;}let i=new s(o);await i.connect();let l=new URL(o).pathname.replace(/^\//,"")||"kyro_cms",p=i.db(l);return new a$1({db:p})}return new a$2({path:b("KYRO_AUTH_DB_PATH",r)})}default:return new D}}async function G(n,e){let t=k("KYRO_DISTRIBUTED",false),r;if(t){let{RedisAuthAdapter:m}=await import('./redis-adapter-QPCTMF55.js'),f=b("REDIS_URL","redis://localhost:6379"),w=k("REDIS_TLS",false),h=new m({url:f,tls:w});await h.connect?.(),r=h;}else {let m=n||Be();r=await qr(m),r.connect&&await r.connect();}let o=e?await k$1.fromConfig(e).catch(()=>null)||k$1.fromEnv()||void 0:k$1.fromEnv()||void 0,s=new l({minLength:y("PASSWORD_MIN_LENGTH",12),requireUppercase:k("PASSWORD_REQUIRE_UPPERCASE",true),requireLowercase:k("PASSWORD_REQUIRE_LOWERCASE",true),requireNumbers:k("PASSWORD_REQUIRE_NUMBERS",true),requireSpecialChars:k("PASSWORD_REQUIRE_SPECIAL",true),preventReuse:y("PASSWORD_PREVENT_REUSE",5),maxLength:y("PASSWORD_MAX_LENGTH",128)}),i,c,l$1;if(t){let f=r.redis;i=new R(f,{maxAttempts:y("LOCKOUT_MAX_ATTEMPTS",5),lockDuration:y("LOCKOUT_DURATION_MINUTES",15)*60*1e3}),c=new v(f,{"auth:login":{window:y("RATE_LIMIT_AUTH_WINDOW_MS",9e5),max:y("RATE_LIMIT_AUTH_MAX_REQUESTS",10)},"api:general":{window:y("RATE_LIMIT_WINDOW_MS",6e4),max:y("RATE_LIMIT_MAX_REQUESTS",100)}}),l$1=new bb(f,y("AUDIT_LOG_RETENTION_DAYS",30));}else i=new I({maxAttempts:y("LOCKOUT_MAX_ATTEMPTS",5),lockDuration:y("LOCKOUT_DURATION_MINUTES",15)*60*1e3}),c=new ab({"auth:login":{window:y("RATE_LIMIT_AUTH_WINDOW_MS",9e5),max:y("RATE_LIMIT_AUTH_MAX_REQUESTS",10)},"api:general":{window:y("RATE_LIMIT_WINDOW_MS",6e4),max:y("RATE_LIMIT_MAX_REQUESTS",100)}}),l$1=k("AUDIT_LOG_ENABLED",true)?new db(y("AUDIT_LOG_RETENTION_DAYS",30)):void 0;let p=new eb({redis:r,email:o,jwtSecret:b("APP_SECRET","change-me"),jwtExpiresIn:b("JWT_EXPIRES_IN","24h"),jwtIssuer:b("JWT_ISSUER","kyro-cms"),jwtAudience:b("JWT_AUDIENCE","kyro-cms-client"),passwordPolicy:s,lockout:i,rateLimiter:c,auditLogger:l$1,baseUrl:b("EMAIL_BASE_URL","http://localhost:4321"),emailVerificationRequired:k("EMAIL_VERIFICATION_REQUIRED",true)}),g=t?"distributed":n||Be();return {authAdapter:r,databaseType:g,email:o,passwordPolicy:s,lockout:i,rateLimiter:c,auditLogger:l$1,routes:p}}var $e=G().catch(n=>(console.warn("[AuthConfig] Failed to initialize auth config:",n.message),null));var Gr=12,Qr="24h",Yr="7d",B=class{adapter;config;constructor(e,t){this.adapter=e,this.config={secret:t.secret,expiresIn:t.expiresIn??Qr,refreshExpiresIn:t.refreshExpiresIn??Yr,issuer:t.issuer??"kyro-cms",audience:t.audience??[],saltRounds:t.saltRounds??Gr};}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-OD67R5JS.js');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-OD67R5JS.js'),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-ZEEHSMAG.js');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 Jr(n,e){return new B(n,e)}g();g();function N(){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={...N(),...t};}async createVersion(e){let r=((await this.adapter.getLatestVersion(e.collection,e.documentId))?.version??0)+1,o={...e,version:r},s=await this.adapter.createVersion(o);return this.config.maxVersionsPerDocument>0&&await this.pruneOldVersions(e.collection,e.documentId),s}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 s=r.slice(this.config.maxVersionsPerDocument);for(let i of s)if(i.status!=="published"){await this.adapter.deleteVersions(e,t);break}}};function Xr(n,e){return new $(n,e)}function Zr(n){return n==="published"}function eo(n){return n==="draft"}function to(n){return n==="archived"}g();function ro(n){return n?Array.isArray(n)?n:Object.values(n):[]}function oo(n){return n?Array.isArray(n)?n:Object.values(n):[]}function ze(n){return {collections:ro(n.collections),globals:oo(n.globals),adapter:n.adapter,plugins:n.plugins,auth:n.auth,cors:n.cors,admin:n.admin,upload:n.upload,graphQL:n.graphQL,typescript:n.typescript,localization:n.localization,rateLimit:n.rateLimit,debug:n.debug}}var no=ze;g();function so(n){let{siteSettings:e,seoSettings:t,title:r,description:o,image:s,url:i}=n;if(!e)return "";let c=e.siteName||"",l=r||t?.defaultTitle||c,p=t?.titleTemplate,g=t?.separator||" | ",m=t?.siteNameInTitle!==false,f=p?p.replace(/\{\{title\}\}/g,l).replace(/\{\{siteName\}\}/g,m?c:"").replace(/\{\{separator\}\}/g,g).replace(/\s+/g," ").trim():l,w=o||t?.defaultDescription||e.siteDescription||"",h=s||e.siteOgImage?.url||"",V=i||e.siteUrl||"",A=`
|
|
1
|
+
export{a as LocalAdapter,b as createLocalAdapter}from'./chunk-PRMILS4Y.js';export{a as RedisAuthAdapter}from'./chunk-M75VGFCI.js';import {a as a$5}from'./chunk-RPRGGGIW.js';export{k as allGlobalSettings,q as blogCollections,l as coreGlobalSettings,V as createTemplateConfig,r as ecommerceCollections,s as ecommerceGlobals,t as kitchenSinkCollections,v as mediaCollections,a as minimalCollections,U as templateCollections}from'./chunk-G3B5RM2F.js';export{a as kyro}from'./chunk-SZT6BLUR.js';import {f}from'./chunk-EVCRNJBG.js';export{t as AnalyticsPlugin,u as CommentsPlugin,a as ConfigValidationError,z as Kyro,q as KyroPlugin,C as Logger,r as PluginManager,m as Registry,v as ReviewsPlugin,s as SEOPlugin,w as WishlistPlugin,y as applyCollectionOverrides,i as collectionToCreateZod,j as collectionToUpdateZod,k as collectionToWhereZod,h as collectionToZod,A as createKyro,B as createKyroHandler,p as createRegistry,g as fieldToZod,n as getRegistry,l as globalToZod,D as logger,x as presetPlugins,o as resetRegistry,b as validateCollection,e as validateConfig,d as validateFields,c as validateGlobal,f as z}from'./chunk-EVCRNJBG.js';export{e as autoBootstrap,a as bootstrapAdmin,f as bootstrapWithRetry,d as getBootstrapFromEnv}from'./chunk-VF6IW6WG.js';import'./chunk-LWM4WABU.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-7FXEXHK6.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-ZRIBWDYJ.js';import'./chunk-SQBTIMWF.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-PA4ZZREG.js';export{J as buildGraphQLSchema,K as createGraphQLSchema}from'./chunk-ZMG7Z3KF.js';import {bb,ab,db,eb}from'./chunk-HJXUDJC4.js';export{bb as AuditLogger,db as InMemoryAuditLogger,ab as InMemoryRateLimiter,hb as MediaService,cb as createAuditContext,ib as createHonoApp,_a as createLocalStorage,jb as createRESTAPI,gb as isEdgeRuntime,Za as resolveProvider}from'./chunk-HJXUDJC4.js';import {q,r}from'./chunk-Q63LWE6P.js';export{p as ConfigService,q as EmailTransport,r as PasswordPolicy,o as getEmailTemplates,n as renderAbandonedCart,g as renderAccountLocked,a as renderBaseLayout,f as renderMagicLink,i as renderNewLogin,j as renderOrderConfirmation,l as renderOrderDelivered,m as renderOrderRefunded,k as renderOrderShipped,e as renderPasswordChanged,c as renderResetPassword,h as renderUserInvite,b as renderVerifyEmail,d as renderWelcome}from'./chunk-Q63LWE6P.js';import'./chunk-OLRCZ6E3.js';import {a as a$2}from'./chunk-R25WLKX4.js';export{a as SQLiteAuthAdapter}from'./chunk-R25WLKX4.js';import {f as f$1}from'./chunk-6TPICJ2L.js';export{c as getAppSecret,d as getEncryptionKey,e as getSessionConfig,b as loadSecrets,a as setDbAdapter}from'./chunk-6TPICJ2L.js';import'./chunk-YENNL5HG.js';import'./chunk-W45TLOOT.js';import'./chunk-IKGVPXMK.js';import'./chunk-YUUXFD73.js';import'./chunk-LVBHOZZF.js';import'./chunk-OBYAIJVU.js';import'./chunk-JRUQ5ABB.js';import'./chunk-CIVA6SKW.js';import'./chunk-WPM6LFCY.js';import'./chunk-U6KFONKM.js';import'./chunk-TYQYKKWJ.js';import'./chunk-L2QXP26Q.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-YZEMLLD2.js';export{a as evaluateAccess,c as getWhereClause,b as mergeWhereClauses}from'./chunk-RTHJ6SS5.js';export{b as KyroPubSub,c as KyroWSServer,a as PubSub,d as createWSServer}from'./chunk-5M3FKE2V.js';import'./chunk-7MNDQU6K.js';import'./chunk-QDBGBDCT.js';export{c as DrizzleAdapter,b as collectionToDrizzleSchema,f as createDatabase,d as createDrizzleAdapter,a as fieldToDrizzleType,g as runMigrations,h as seedDefaultRoles}from'./chunk-BU6O3TP7.js';import {a as a$3}from'./chunk-ZWDBPEXL.js';export{a as PostgresAuthAdapter}from'./chunk-ZWDBPEXL.js';import'./chunk-47CXBWMA.js';import'./chunk-EML5FDUU.js';import'./chunk-OXGJOYEO.js';import'./chunk-FLMUMPDE.js';import'./chunk-2HA6EKXX.js';import'./chunk-JV4HJBXW.js';import'./chunk-N5POANYV.js';import'./chunk-HRAY65XH.js';import'./chunk-3NSZZCOJ.js';export{a as MongoDBAdapter,b as createMongoDBAdapter}from'./chunk-LELK3TYX.js';import {a as a$1}from'./chunk-UT7RGIYS.js';export{a as MongoDBAuthAdapter}from'./chunk-UT7RGIYS.js';import {a as a$4}from'./chunk-SLMIYECU.js';export{a as AbstractBaseAdapter}from'./chunk-SLMIYECU.js';import {a}from'./chunk-P6JITOFF.js';import'./chunk-7NH7H3WA.js';import'./chunk-VVVCCB6R.js';import'./chunk-TBHNE4VV.js';import {g}from'./chunk-Y2YAKDEQ.js';import ee,{randomBytes}from'crypto';import {readFileSync}from'fs';import Xe,{join,resolve}from'path';if (typeof window === "undefined") { const { createRequire } = await import(/* @vite-ignore */ 'module'); createRequire(import.meta.url); }
|
|
2
|
+
g();g();g();g();async function He(n,e){let t=e.data;for(let r of n){let o=await r({...e,data:t});o!==void 0&&(t=o);}return t}async function $r(n,e){return He(n,e)}g();g();g();var E=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 Fe(n){return new E(n)}g();var O=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(l=>({type:"text",value:String(l)}))}},{type:"close"}]})});if(!o.ok)return [];let i=(await o.json())?.results?.[0]?.response?.result;if(!i||!i.rows)return [];let c=i.cols.map(l=>l.name);return i.rows.map(l=>{let p={};return c.forEach((g,m)=>{p[g]=l[m]?.value??null;}),p})}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 Ke(n){return new O(n)}g();g();g();g();var zr={maxAttempts:5,lockDuration:9e5,notifyUser:true,notifyAdmin:true,adminNotifyAfter:3},R=class{redis;prefix;config;constructor(e,t={},r="kyro:lockout:"){this.redis=e,this.prefix=r,this.config={...zr,...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),s=r.lockedUntil?new Date(parseInt(r.lockedUntil,10)):void 0;return s&&s>new Date?{locked:true,attemptsRemaining:0,lockedUntil:s,totalAttempts:o}:s&&s<=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(),s=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),s>=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:s}}return {locked:false,attemptsRemaining:Math.max(0,this.config.maxAttempts-s),totalAttempts:s}}async lockAccount(e,t){let r=this.lockKey(e),o=Date.now(),s=t||this.config.lockDuration,i=new Date(o+s),c=this.redis.pipeline();c.hset(r,{attempts:this.config.maxAttempts.toString(),lockedAt:o.toString(),lockedUntil:i.getTime().toString()}),c.expire(r,Math.ceil(s/1e3)+3600),await c.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(s=>new Date(parseInt(s,10)))}async getLockoutStats(e){let t=this.historyKey(e),r=await this.redis.lrange(t,0,-1),o=r.filter((i,c)=>(c+1)%this.config.maxAttempts===0).length,s=await this.redis.hget(this.lockKey(e),"lockedAt");return {totalFailedAttempts:r.length,lockoutCount:o,lastLockout:s?new Date(parseInt(s,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};}};g();var jr={"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}},v=class{redis;prefix;limits;userLimits;constructor(e,t,r,o="kyro:ratelimit:"){this.redis=e,this.prefix=o,this.limits={...jr,...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),s=Date.now(),i=s-r.window,c=this.redis.pipeline();c.zremrangebyscore(o,0,i),c.zcard(o),c.zadd(o,s,`${s}:${Math.random()}`),c.expire(o,Math.ceil(r.window/1e3)+1);let p=(await c.exec())?.[1]?.[1]||0;if(p>=r.max){let g=await this.redis.zrange(o,0,0,"WITHSCORES"),m=g.length>1?parseInt(g[1],10)+r.window:s+r.window;return {allowed:false,remaining:0,resetAt:m,retryAfter:Math.ceil((m-s)/1e3)}}return {allowed:true,remaining:r.max-p-1,resetAt:s+r.window}}async checkUser(e,t,r){let o=this.userLimits[e]||this.userLimits["user:api"],s=this.getKey(`user:${e}:${t}`,r),i=Date.now(),c=i-o.window,l=this.redis.pipeline();l.zremrangebyscore(s,0,c),l.zcard(s),l.zadd(s,i,`${i}:${Math.random()}`),l.expire(s,Math.ceil(o.window/1e3)+1);let g=(await l.exec())?.[1]?.[1]||0;if(g>=o.max){let m=await this.redis.zrange(s,0,0,"WITHSCORES"),f=m.length>1?parseInt(m[1],10)+o.window:i+o.window;return {allowed:false,remaining:0,resetAt:f,retryAfter:Math.ceil((f-i)/1e3)}}return {allowed:true,remaining:o.max-g-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),s=Date.now(),i=s-r.window;await this.redis.zremrangebyscore(o,0,i);let c=await this.redis.zcard(o);return {count:c,limit:r.max,remaining:Math.max(0,r.max-c),resetAt:s+r.window}}setLimit(e,t){this.limits[e]=t;}setUserLimit(e,t){this.userLimits[e]=t;}};g();g();g();var D=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),s={id:t,email:e.email.toLowerCase(),passwordHash:o,role:e.role||"customer",tenantId:e.tenantId,createdAt:r,updatedAt:r};return this.users.set(t,s),this.emailToUserId.set(e.email.toLowerCase(),t),this.passwordHistory.set(t,[]),s}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-ZEEHSMAG.js')).default.hash(e,12)}async verifyPassword(e,t){let r=await this.findUserByEmail(e);return !r||!r.passwordHash?null:await(await import('./bcryptjs-ZEEHSMAG.js')).default.compare(t,r.passwordHash)?r:null}async createSession(e,t={}){let r=randomBytes(32).toString("hex"),o=randomBytes(32).toString("base64url"),s=randomBytes(32).toString("base64url"),i=new Date,c={id:r,userId:e,token:o,refreshToken:s,expiresAt:new Date(i.getTime()+86400*1e3).toISOString(),createdAt:i.toISOString(),ipAddress:t.ipAddress,userAgent:t.userAgent};return this.sessions.set(r,c),this.refreshTokens.set(s,r),c}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),s=(await import('./bcryptjs-ZEEHSMAG.js')).default;for(let i of o)if(await s.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(s=>s.userId===e.userId)),e.action&&(Array.isArray(e.action)?o=o.filter(s=>e.action.includes(String(s.action))):o=o.filter(s=>s.action===e.action)),e.resource&&(o=o.filter(s=>s.resource===e.resource)),e.success!==void 0&&(o=o.filter(s=>s.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}};g();var I=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:s}=r;return s!==null&&s>t?{locked:true,attemptsRemaining:0,lockedUntil:new Date(s),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 s=new Date(t+this.config.lockDuration);return r.lockedAt=t,r.lockedUntil=s.getTime(),this.storage.set(e,r),{locked:true,attemptsRemaining:0,lockedUntil:s,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,s=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=s.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),s=null,i=this.storage.get(e);i&&i.lockedAt!==null&&(s=new Date(i.lockedAt));let c=o>0?this.config.maxAttempts:0;return {totalFailedAttempts:r,lockoutCount:o,lastLockout:s,averageAttemptsBeforeLockout:c}}shouldNotifyAdmin(e){return this.config.notifyAdmin&&e>=this.config.adminNotifyAfter}getConfig(){return {...this.config}}setConfig(e){this.config={...this.config,...e};}};function b(n,e=""){return process.env[n]||e}function k(n,e=false){let t=process.env[n];return t?t.toLowerCase()==="true":e}function y(n,e=0){let t=process.env[n];return t?parseInt(t,10):e}function Be(){let n=process.env.KYRO_AUTH_DATABASE?.toLowerCase();if(n&&["sqlite","postgres","mongodb","memory"].includes(n))return n;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 Gr(n){let e=process.cwd(),t=e.endsWith("admin")?join(e,".."):e,r=resolve(t,"data","auth.db");switch(n){case "sqlite":return new a$2({path:b("KYRO_AUTH_DB_PATH",r)});case "postgres":{let o=b("DATABASE_URL","");if(o){let s,i;try{s=(await import('./postgres-js-4CI7FMYS.js')).drizzle,i=await import('./src-QBADSZV4.js');}catch{a(["postgres","drizzle-orm"]),s=(await import('./postgres-js-4CI7FMYS.js')).drizzle,i=await import('./src-QBADSZV4.js');}let c=i.default(o,{onnotice:()=>{}}),l=s(c);return new a$3({db:l})}return new a$2({path:b("KYRO_AUTH_DB_PATH",r)})}case "mongodb":{let o=b("MONGODB_URI","");if(o){let s;try{let g=await import('./lib-XXYYUPMW.js');s=g.MongoClient??g.default?.MongoClient;}catch{a(["mongodb"]);let m=await import('./lib-XXYYUPMW.js');s=m.MongoClient??m.default?.MongoClient;}let i=new s(o);await i.connect();let l=new URL(o).pathname.replace(/^\//,"")||"kyro_cms",p=i.db(l);return new a$1({db:p})}return new a$2({path:b("KYRO_AUTH_DB_PATH",r)})}default:return new D}}async function G(n,e){let t=k("KYRO_DISTRIBUTED",false),r$1;if(t){let{RedisAuthAdapter:m}=await import('./redis-adapter-QPCTMF55.js'),f=b("REDIS_URL","redis://localhost:6379"),w=k("REDIS_TLS",false),h=new m({url:f,tls:w});await h.connect?.(),r$1=h;}else {let m=n||Be();r$1=await Gr(m),r$1.connect&&await r$1.connect();}let o=e?await q.fromConfig(e).catch(()=>null)||q.fromEnv()||void 0:q.fromEnv()||void 0,s=new r({minLength:y("PASSWORD_MIN_LENGTH",12),requireUppercase:k("PASSWORD_REQUIRE_UPPERCASE",true),requireLowercase:k("PASSWORD_REQUIRE_LOWERCASE",true),requireNumbers:k("PASSWORD_REQUIRE_NUMBERS",true),requireSpecialChars:k("PASSWORD_REQUIRE_SPECIAL",true),preventReuse:y("PASSWORD_PREVENT_REUSE",5),maxLength:y("PASSWORD_MAX_LENGTH",128)}),i,c,l;if(t){let f=r$1.redis;i=new R(f,{maxAttempts:y("LOCKOUT_MAX_ATTEMPTS",5),lockDuration:y("LOCKOUT_DURATION_MINUTES",15)*60*1e3}),c=new v(f,{"auth:login":{window:y("RATE_LIMIT_AUTH_WINDOW_MS",9e5),max:y("RATE_LIMIT_AUTH_MAX_REQUESTS",10)},"api:general":{window:y("RATE_LIMIT_WINDOW_MS",6e4),max:y("RATE_LIMIT_MAX_REQUESTS",100)}}),l=new bb(f,y("AUDIT_LOG_RETENTION_DAYS",30));}else i=new I({maxAttempts:y("LOCKOUT_MAX_ATTEMPTS",5),lockDuration:y("LOCKOUT_DURATION_MINUTES",15)*60*1e3}),c=new ab({"auth:login":{window:y("RATE_LIMIT_AUTH_WINDOW_MS",9e5),max:y("RATE_LIMIT_AUTH_MAX_REQUESTS",10)},"api:general":{window:y("RATE_LIMIT_WINDOW_MS",6e4),max:y("RATE_LIMIT_MAX_REQUESTS",100)}}),l=k("AUDIT_LOG_ENABLED",true)?new db(y("AUDIT_LOG_RETENTION_DAYS",30)):void 0;let p=new eb({redis:r$1,email:o,jwtSecret:b("APP_SECRET","change-me"),jwtExpiresIn:b("JWT_EXPIRES_IN","24h"),jwtIssuer:b("JWT_ISSUER","kyro-cms"),jwtAudience:b("JWT_AUDIENCE","kyro-cms-client"),passwordPolicy:s,lockout:i,rateLimiter:c,auditLogger:l,baseUrl:b("EMAIL_BASE_URL","http://localhost:4321"),emailVerificationRequired:k("EMAIL_VERIFICATION_REQUIRED",true)}),g=t?"distributed":n||Be();return {authAdapter:r$1,databaseType:g,email:o,passwordPolicy:s,lockout:i,rateLimiter:c,auditLogger:l,routes:p}}var $e=G().catch(n=>(console.warn("[AuthConfig] Failed to initialize auth config:",n.message),null));var Qr=12,Yr="24h",Jr="7d",B=class{adapter;config;constructor(e,t){this.adapter=e,this.config={secret:t.secret,expiresIn:t.expiresIn??Yr,refreshExpiresIn:t.refreshExpiresIn??Jr,issuer:t.issuer??"kyro-cms",audience:t.audience??[],saltRounds:t.saltRounds??Qr};}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-OD67R5JS.js');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-OD67R5JS.js'),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-ZEEHSMAG.js');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 Xr(n,e){return new B(n,e)}g();g();function N(){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={...N(),...t};}async createVersion(e){let r=((await this.adapter.getLatestVersion(e.collection,e.documentId))?.version??0)+1,o={...e,version:r},s=await this.adapter.createVersion(o);return this.config.maxVersionsPerDocument>0&&await this.pruneOldVersions(e.collection,e.documentId),s}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 s=r.slice(this.config.maxVersionsPerDocument);for(let i of s)if(i.status!=="published"){await this.adapter.deleteVersions(e,t);break}}};function Zr(n,e){return new $(n,e)}function eo(n){return n==="published"}function to(n){return n==="draft"}function ro(n){return n==="archived"}g();function oo(n){return n?Array.isArray(n)?n:Object.values(n):[]}function no(n){return n?Array.isArray(n)?n:Object.values(n):[]}function ze(n){return {collections:oo(n.collections),globals:no(n.globals),adapter:n.adapter,plugins:n.plugins,auth:n.auth,cors:n.cors,admin:n.admin,upload:n.upload,graphQL:n.graphQL,typescript:n.typescript,localization:n.localization,rateLimit:n.rateLimit,debug:n.debug}}var so=ze;g();function io(n){let{siteSettings:e,seoSettings:t,title:r,description:o,image:s,url:i}=n;if(!e)return "";let c=e.siteName||"",l=r||t?.defaultTitle||c,p=t?.titleTemplate,g=t?.separator||" | ",m=t?.siteNameInTitle!==false,f=p?p.replace(/\{\{title\}\}/g,l).replace(/\{\{siteName\}\}/g,m?c:"").replace(/\{\{separator\}\}/g,g).replace(/\s+/g," ").trim():l,w=o||t?.defaultDescription||e.siteDescription||"",h=s||e.siteOgImage?.url||"",V=i||e.siteUrl||"",A=`
|
|
3
3
|
<title>${f}</title>
|
|
4
4
|
<meta name="description" content="${w}">
|
|
5
5
|
`;e.siteFavicon?.url&&(A+=`
|
|
@@ -20,7 +20,7 @@ g();g();g();g();async function He(n,e){let t=e.data;for(let r of n){let o=await
|
|
|
20
20
|
`,t?.social?.twitterHandle&&(A+=`
|
|
21
21
|
<meta name="twitter:site" content="${t.social.twitterHandle}">`),h&&(A+=`
|
|
22
22
|
<meta name="twitter:image" content="${h}">`),e.enableI18n&&e.i18n?.language&&(A+=`
|
|
23
|
-
<meta http-equiv="content-language" content="${e.i18n.language}">`),A}function
|
|
23
|
+
<meta http-equiv="content-language" content="${e.i18n.language}">`),A}function ao(n){if(!n||!n.analyticsEnabled||!n.analytics)return "";let{googleAnalyticsId:e,googleTagManagerId:t,plausibleDomain:r}=n.analytics,o="";return e&&(o+=`
|
|
24
24
|
<!-- Google Analytics -->
|
|
25
25
|
<script async src="https://www.googletagmanager.com/gtag/js?id=${e}"></script>
|
|
26
26
|
<script>
|
|
@@ -41,11 +41,11 @@ g();g();g();g();async function He(n,e){let t=e.data;for(let r of n){let o=await
|
|
|
41
41
|
`),r&&(o+=`
|
|
42
42
|
<!-- Plausible Analytics -->
|
|
43
43
|
<script defer data-domain="${r}" src="https://plausible.io/js/script.js"></script>
|
|
44
|
-
`),o}g();var
|
|
44
|
+
`),o}g();var co={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"}},lo=["facebook","twitter","instagram","linkedin","youtube","tiktok","pinterest","discord","twitch","github","mastodon"];function je(n){if(!n)return [];let e=n.showAll===true,t=[];for(let r of lo){let o=n[r];if(!o||["tiktok","pinterest","discord","twitch","github","mastodon"].includes(r)&&!e)continue;let i=co[r];t.push({platform:r,url:o,label:i?.label||r});}return t}async function uo(n,e){try{let t=await n.findOne({collection:"_globals_social-settings",where:{},draft:e?.draft??!1});return je(t)}catch{return []}}g();function We(n){return n?{storeName:n.storeName,storeEmail:n.storeEmail,storePhone:n.storePhone,address:n.address,currency:n.currency,tax:n.tax,shipping:n.shipping,orders:n.orders}:{}}async function po(n,e){try{let t=await n.findOne({collection:"_globals_store-settings",where:{},draft:e?.draft??!1});return We(t)}catch{return {}}}g();function qe(n){return n?{testMode:n.testMode,provider:n.provider,stripe:n.stripe,paypal:n.paypal,square:n.square,methods:n.methods,bankTransfer:n.bankTransfer}:{}}async function go(n,e){try{let t=await n.findOne({collection:"_globals_payment-settings",where:{},draft:e?.draft??!1});return qe(t)}catch{return {}}}g();g();g();g();g();function x(n){return new Promise((e,t)=>{n.oncomplete=n.onsuccess=()=>e(n.result),n.onabort=n.onerror=()=>t(n.error);})}function Y(n,e){let t,r=()=>{if(t)return t;let o=indexedDB.open(n);return o.onupgradeneeded=()=>o.result.createObjectStore(e),t=x(o),t.then(s=>{s.onclose=()=>t=void 0;},()=>{t=void 0;}),t};return (o,s)=>r().then(i=>s(i.transaction(e,o).objectStore(e)))}var Q;function U(){return Q||(Q=Y("keyval-store","keyval")),Q}function z(n,e=U()){return e("readonly",t=>x(t.get(n)))}function J(n,e,t=U()){return t("readwrite",r=>(r.put(e,n),x(r.transaction)))}function Ge(n,e=U()){return e("readwrite",t=>(t.delete(n),x(t.transaction)))}function Qe(n=U()){return n("readwrite",e=>(e.clear(),x(e.transaction)))}function mo(n,e){return n.openCursor().onsuccess=function(){this.result&&(e(this.result),this.result.continue());},x(n.transaction)}function Ye(n=U()){return n("readonly",e=>{if(e.getAllKeys)return x(e.getAllKeys());let t=[];return mo(e,r=>t.push(r.key)).then(()=>t)})}var fo="idb-keyval",Je=(n={})=>{let e=n.base&&n.base.length>0?`${n.base}:`:"",t=o=>e+o,r;return n.dbName&&n.storeName&&(r=Y(n.dbName,n.storeName)),{name:fo,options:n,async hasItem(o){return await z(t(o),r)!==void 0},async getItem(o){return await z(t(o),r)??null},async getItemRaw(o){return await z(t(o),r)??null},setItem(o,s){return J(t(o),s,r)},setItemRaw(o,s){return J(t(o),s,r)},removeItem(o){return Ge(t(o),r)},getKeys(){return Ye(r)},clear(){return Qe(r)}}};async function X(n={}){let{namespace:e="kyro",ttl:t}=n,r=f$1({driver:Je({dbName:"kyro-cms",storeName:e})}),o=e?`${e}:`:"";return {storage:{getItem:async i=>{let c=`${o}${i}`,l=await r.getItem(c);if(l==null)return null;try{let p=JSON.parse(l);return p.expiry&&Date.now()>p.expiry?(await r.removeItem(c),null):p.value}catch{return l}},setItem:async(i,c)=>{let l=`${o}${i}`,p=JSON.stringify(t?{value:c,expiry:Date.now()+t}:{value:c});await r.setItem(l,p);},removeItem:async i=>{await r.removeItem(`${o}${i}`);}},cleanup:async()=>{await r.dispose?.();}}}g();g();function Z(n){let e=n||process.env.APP_SECRET||process.env.AUTH_SECRET||"development-secret-key";return ee.createHash("sha256").update(e).digest("hex")}function ho(n,e){let t=ee.randomBytes(16),r=ee.createCipheriv("aes-256-gcm",Buffer.from(e,"hex").subarray(0,32),t),o=r.update(n,"utf8","hex");o+=r.final("hex");let s=r.getAuthTag().toString("hex");return `${t.toString("hex")}:${s}:${o}`}function Ao(n,e){let[t,r,o]=n.split(":"),s=Buffer.from(t,"hex"),i=Buffer.from(r,"hex"),c=ee.createDecipheriv("aes-256-gcm",Buffer.from(e,"hex").subarray(0,32),s);c.setAuthTag(i);let l=c.update(o,"hex","utf8");return l+=c.final("utf8"),l}async function te(n={}){let{namespace:e="kyro",ttl:t,encryption:r=true,secret:o,basePath:s}=n,i=s?Xe.join(s,".astro","kyro.json"):Xe.join(process.cwd(),".astro","kyro.json"),c=f$1({driver:a$5({base:i})}),l=r?Z(o):null,p=e?`${e}:`:"";return {storage:{getItem:async g=>{let m=`${p}${g}`,f=await c.getItem(m);if(f==null)return null;try{let w=l?Ao(f,l):f,h=JSON.parse(w);return h.expiry&&Date.now()>h.expiry?(await c.removeItem(m),null):h.value}catch{return f}},setItem:async(g,m)=>{let f=`${p}${g}`,w=JSON.stringify(t?{value:m,expiry:Date.now()+t}:{value:m});await c.setItem(f,l?ho(w,l):w);},removeItem:async g=>{await c.removeItem(`${p}${g}`);}},cleanup:async()=>{await c.dispose?.();}}}async function re(n){let{environment:e,adapter:t,connectionString:r,encryption:o}=n,s=process.env.APP_SECRET||process.env.AUTH_SECRET,i={enabled:o?.enabled??true,algorithm:o?.algorithm};return e==="browser"?X({namespace:"kyro"}):te({namespace:"kyro",encryption:i.enabled,secret:s})}async function Ze(n){let e={...n,encryption:{enabled:true,algorithm:n.encryption?.algorithm}};return re(e)}g();function wo(n){return {name:"kyro-loader",load:async e=>{let{store:t,logger:r,parseData:o}=e;r.info(`Loading Kyro CMS collection: "${n.collection}"`);try{let s=[];t.clear();for(let i of s){let c=String(i.id||i._id),l=await o({id:c,data:i});t.set({id:c,data:l,digest:JSON.stringify(l)});}r.info(`Successfully synced ${s.length} entries for "${n.collection}" into Astro store.`);}catch(s){r.error(`Failed to load Kyro collection "${n.collection}": ${s.message}`);}},schema:f.object({id:f.string(),createdAt:f.string().optional(),updatedAt:f.string().optional()}).passthrough()}}g();function bo(n){return {input:n.schema||f.object({}).passthrough(),handler:async(t,r)=>{try{return {success:!0,collection:n.collection,action:n.action,data:t,timestamp:new Date().toISOString()}}catch(o){return {success:false,error:o.message||"CMS Action Execution Failed"}}}}}g();function So(n={}){let e=n.protectedRoutes||[],t=n.loginPath||"/admin/login",r=n.cookieName||"kyro_session";return async(o,s)=>{let{request:i,cookies:c,redirect:l,locals:p}=o,g=new URL(i.url),m=c?.get?.(r)?.value||i.headers.get("authorization")?.replace("Bearer ",""),f=null;return m&&(f={id:"user_1",email:"admin@kyro-cms.com",role:"admin"}),p.kyroUser=f,e.some(h=>new RegExp("^"+h.replace(/\*/g,".*")+"$").test(g.pathname))&&!f?l(`${t}?redirect=${encodeURIComponent(g.pathname)}`):s()}}g();function ko(n){let e=n?.collections||[],t=`// Auto-generated by Kyro CMS
|
|
45
45
|
declare module 'kyro:collections' {
|
|
46
46
|
export interface KyroCollections {
|
|
47
47
|
`;for(let r of e){let o=r.name||r.slug;t+=` '${o}': Record<string, any>;
|
|
48
48
|
`;}return t+=` }
|
|
49
49
|
}
|
|
50
|
-
`,t}g();function
|
|
51
|
-
export{R as AccountLockout,B as Auth,I as InMemoryAccountLockout,D as InMemoryAuthAdapter,E as NeonAdapter,v as RateLimiter,O as TursoAdapter,$ as VersionManager,$e as authConfig,
|
|
50
|
+
`,t}g();function To(n={}){return {APP_SECRET:{context:"server",access:"secret",type:"string",optional:false},DATABASE_URL:{context:"server",access:"secret",type:"string",optional:!n.requireDatabase},PUBLIC_KYRO_URL:{context:"client",access:"public",type:"string",optional:true,default:"http://localhost:4321"}}}g();function xo(n={}){return {name:"kyro-dev-toolbar-integration",hooks:{"astro:config:setup":({addDevToolbarApp:e})=>{n.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"});}}}}
|
|
51
|
+
export{R as AccountLockout,B as Auth,I as InMemoryAccountLockout,D as InMemoryAuthAdapter,E as NeonAdapter,v as RateLimiter,O as TursoAdapter,$ as VersionManager,$e as authConfig,Xr as createAuth,G as createAuthConfig,Ze as createAuthStorage,Fe as createNeonAdapter,re as createStorage,Ke as createTursoAdapter,Zr as createVersionManager,ze as defineConfig,so as defineKyroConfig,ao as generateAnalyticsTags,ko as generateKyroAstroTypes,io as generateSeoTags,N as getDefaultDraftPublishConfig,go as getPaymentConfig,qe as getPaymentConfigFromSettings,uo as getSocialLinks,je as getSocialLinksFromSettings,po as getStoreConfig,We as getStoreConfigFromSettings,ro as isArchived,to as isDraft,eo as isPublished,bo as kyroAction,So as kyroAuthMiddleware,xo as kyroDevToolbarIntegration,To as kyroEnvSchema,wo as kyroLoader,$r as runFieldHooks,He as runHooks};
|
package/dist/rest/index.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
'use strict';var
|
|
1
|
+
'use strict';var chunkRYTA4NYP_cjs=require('../chunk-RYTA4NYP.cjs');require('../chunk-KBQTMHP3.cjs'),require('../chunk-HPYH7GTS.cjs'),require('../chunk-BHR7OAU4.cjs'),require('../chunk-O4YE57OS.cjs'),require('../chunk-MCIZG4A3.cjs'),require('../chunk-35PGCW3S.cjs'),require('../chunk-UNYXWPLZ.cjs'),require('../chunk-PITMDQYN.cjs'),require('../chunk-GIS6X43A.cjs'),require('../chunk-LEBM6ZSZ.cjs'),require('../chunk-GNEVCEJU.cjs'),require('../chunk-ZO3YB5DK.cjs'),require('../chunk-3VXEK5ZW.cjs'),require('../chunk-EZIDQBXI.cjs'),require('../chunk-LQ3YZTPU.cjs'),require('../chunk-MVX2PYJJ.cjs'),require('../chunk-AK754S3T.cjs'),require('../chunk-DUO523BH.cjs'),require('../chunk-6KUL2BSA.cjs'),require('../chunk-XBQ6HV3T.cjs'),require('../chunk-7JWQ2PZP.cjs'),require('../chunk-NGNJSUGL.cjs'),require('../chunk-KCHPADCH.cjs'),require('../chunk-BAVN7VDR.cjs'),require('../chunk-LY7N3UHH.cjs'),require('../chunk-7ACHOBWY.cjs'),require('../chunk-GNOSG3PK.cjs'),require('../chunk-BCEE4NBZ.cjs'),require('../chunk-VRZC4TTF.cjs'),require('../chunk-WJBQ2NBD.cjs'),require('../chunk-VQ53TFYA.cjs'),require('../chunk-F4ITQ6XQ.cjs'),require('../chunk-HTYVI2HK.cjs'),require('../chunk-ZOVH6QT5.cjs'),require('../chunk-7WMMKGEO.cjs'),require('../chunk-BUNLC3II.cjs');Object.defineProperty(exports,"createHonoApp",{enumerable:true,get:function(){return chunkRYTA4NYP_cjs.ib}});Object.defineProperty(exports,"createRESTAPI",{enumerable:true,get:function(){return chunkRYTA4NYP_cjs.jb}});
|
package/dist/rest/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export{ib as createHonoApp,jb as createRESTAPI}from'../chunk-
|
|
1
|
+
export{ib as createHonoApp,jb as createRESTAPI}from'../chunk-HJXUDJC4.js';import'../chunk-Q63LWE6P.js';import'../chunk-OLRCZ6E3.js';import'../chunk-R25WLKX4.js';import'../chunk-6TPICJ2L.js';import'../chunk-YENNL5HG.js';import'../chunk-W45TLOOT.js';import'../chunk-IKGVPXMK.js';import'../chunk-YUUXFD73.js';import'../chunk-LVBHOZZF.js';import'../chunk-OBYAIJVU.js';import'../chunk-JRUQ5ABB.js';import'../chunk-CIVA6SKW.js';import'../chunk-WPM6LFCY.js';import'../chunk-U6KFONKM.js';import'../chunk-TYQYKKWJ.js';import'../chunk-L2QXP26Q.js';import'../chunk-YZEMLLD2.js';import'../chunk-RTHJ6SS5.js';import'../chunk-BU6O3TP7.js';import'../chunk-ZWDBPEXL.js';import'../chunk-47CXBWMA.js';import'../chunk-EML5FDUU.js';import'../chunk-OXGJOYEO.js';import'../chunk-FLMUMPDE.js';import'../chunk-2HA6EKXX.js';import'../chunk-JV4HJBXW.js';import'../chunk-N5POANYV.js';import'../chunk-HRAY65XH.js';import'../chunk-3NSZZCOJ.js';import'../chunk-UT7RGIYS.js';import'../chunk-SLMIYECU.js';import'../chunk-P6JITOFF.js';import'../chunk-7NH7H3WA.js';import'../chunk-VVVCCB6R.js';import'../chunk-TBHNE4VV.js';import'../chunk-Y2YAKDEQ.js';if (typeof window === "undefined") { const { createRequire } = await import(/* @vite-ignore */ 'module'); createRequire(import.meta.url); }
|
package/dist/templates/index.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
'use strict';var
|
|
1
|
+
'use strict';var chunkEEBI65GB_cjs=require('../chunk-EEBI65GB.cjs'),chunk7GGZA5YU_cjs=require('../chunk-7GGZA5YU.cjs'),chunkZO3YB5DK_cjs=require('../chunk-ZO3YB5DK.cjs');require('../chunk-BUNLC3II.cjs');Object.defineProperty(exports,"accessSettingsGlobal",{enumerable:true,get:function(){return chunkEEBI65GB_cjs.g}});Object.defineProperty(exports,"allGlobalSettings",{enumerable:true,get:function(){return chunkEEBI65GB_cjs.k}});Object.defineProperty(exports,"blogCollections",{enumerable:true,get:function(){return chunkEEBI65GB_cjs.q}});Object.defineProperty(exports,"brandSettingsGlobal",{enumerable:true,get:function(){return chunkEEBI65GB_cjs.e}});Object.defineProperty(exports,"brandsCollection",{enumerable:true,get:function(){return chunkEEBI65GB_cjs.S}});Object.defineProperty(exports,"brandsCollections",{enumerable:true,get:function(){return chunkEEBI65GB_cjs.T}});Object.defineProperty(exports,"categoriesCollection",{enumerable:true,get:function(){return chunkEEBI65GB_cjs.A}});Object.defineProperty(exports,"categoriesCollections",{enumerable:true,get:function(){return chunkEEBI65GB_cjs.B}});Object.defineProperty(exports,"coreGlobalSettings",{enumerable:true,get:function(){return chunkEEBI65GB_cjs.l}});Object.defineProperty(exports,"couponsCollection",{enumerable:true,get:function(){return chunkEEBI65GB_cjs.K}});Object.defineProperty(exports,"couponsCollections",{enumerable:true,get:function(){return chunkEEBI65GB_cjs.L}});Object.defineProperty(exports,"createTemplateConfig",{enumerable:true,get:function(){return chunkEEBI65GB_cjs.V}});Object.defineProperty(exports,"customersCollection",{enumerable:true,get:function(){return chunkEEBI65GB_cjs.G}});Object.defineProperty(exports,"customersCollections",{enumerable:true,get:function(){return chunkEEBI65GB_cjs.H}});Object.defineProperty(exports,"ecommerceCollections",{enumerable:true,get:function(){return chunkEEBI65GB_cjs.r}});Object.defineProperty(exports,"ecommerceGlobals",{enumerable:true,get:function(){return chunkEEBI65GB_cjs.s}});Object.defineProperty(exports,"emailSettingsGlobal",{enumerable:true,get:function(){return chunkEEBI65GB_cjs.f}});Object.defineProperty(exports,"formEntriesCollection",{enumerable:true,get:function(){return chunkEEBI65GB_cjs.O}});Object.defineProperty(exports,"formEntriesCollections",{enumerable:true,get:function(){return chunkEEBI65GB_cjs.P}});Object.defineProperty(exports,"formsCollection",{enumerable:true,get:function(){return chunkEEBI65GB_cjs.M}});Object.defineProperty(exports,"formsCollections",{enumerable:true,get:function(){return chunkEEBI65GB_cjs.N}});Object.defineProperty(exports,"getSettingsForTemplate",{enumerable:true,get:function(){return chunkEEBI65GB_cjs.n}});Object.defineProperty(exports,"kitchenSinkCollections",{enumerable:true,get:function(){return chunkEEBI65GB_cjs.t}});Object.defineProperty(exports,"mediaCollection",{enumerable:true,get:function(){return chunkEEBI65GB_cjs.u}});Object.defineProperty(exports,"mediaCollections",{enumerable:true,get:function(){return chunkEEBI65GB_cjs.v}});Object.defineProperty(exports,"menuCollection",{enumerable:true,get:function(){return chunkEEBI65GB_cjs.w}});Object.defineProperty(exports,"menuCollections",{enumerable:true,get:function(){return chunkEEBI65GB_cjs.x}});Object.defineProperty(exports,"minimalCollections",{enumerable:true,get:function(){return chunkEEBI65GB_cjs.a}});Object.defineProperty(exports,"ordersCollection",{enumerable:true,get:function(){return chunkEEBI65GB_cjs.I}});Object.defineProperty(exports,"ordersCollections",{enumerable:true,get:function(){return chunkEEBI65GB_cjs.J}});Object.defineProperty(exports,"pageCollection",{enumerable:true,get:function(){return chunkEEBI65GB_cjs.y}});Object.defineProperty(exports,"pageCollections",{enumerable:true,get:function(){return chunkEEBI65GB_cjs.z}});Object.defineProperty(exports,"postsCollection",{enumerable:true,get:function(){return chunkEEBI65GB_cjs.o}});Object.defineProperty(exports,"postsCollections",{enumerable:true,get:function(){return chunkEEBI65GB_cjs.p}});Object.defineProperty(exports,"productCategoriesCollection",{enumerable:true,get:function(){return chunkEEBI65GB_cjs.C}});Object.defineProperty(exports,"productCategoriesCollections",{enumerable:true,get:function(){return chunkEEBI65GB_cjs.D}});Object.defineProperty(exports,"productsCollection",{enumerable:true,get:function(){return chunkEEBI65GB_cjs.E}});Object.defineProperty(exports,"productsCollections",{enumerable:true,get:function(){return chunkEEBI65GB_cjs.F}});Object.defineProperty(exports,"reviewsCollection",{enumerable:true,get:function(){return chunkEEBI65GB_cjs.Q}});Object.defineProperty(exports,"reviewsCollections",{enumerable:true,get:function(){return chunkEEBI65GB_cjs.R}});Object.defineProperty(exports,"seoSettingsGlobal",{enumerable:true,get:function(){return chunkEEBI65GB_cjs.d}});Object.defineProperty(exports,"settingsBySlug",{enumerable:true,get:function(){return chunkEEBI65GB_cjs.m}});Object.defineProperty(exports,"shippingSettingsGlobal",{enumerable:true,get:function(){return chunkEEBI65GB_cjs.i}});Object.defineProperty(exports,"siteSettingsGlobal",{enumerable:true,get:function(){return chunkEEBI65GB_cjs.c}});Object.defineProperty(exports,"starterCollections",{enumerable:true,get:function(){return chunkEEBI65GB_cjs.b}});Object.defineProperty(exports,"storeSettingsGlobal",{enumerable:true,get:function(){return chunkEEBI65GB_cjs.h}});Object.defineProperty(exports,"systemSettingsGlobal",{enumerable:true,get:function(){return chunkEEBI65GB_cjs.j}});Object.defineProperty(exports,"templateCollections",{enumerable:true,get:function(){return chunkEEBI65GB_cjs.U}});Object.defineProperty(exports,"storageSettingsGlobal",{enumerable:true,get:function(){return chunk7GGZA5YU_cjs.a}});Object.defineProperty(exports,"authCollections",{enumerable:true,get:function(){return chunkZO3YB5DK_cjs.b}});
|
package/dist/templates/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export{g as accessSettingsGlobal,k as allGlobalSettings,q as blogCollections,e as brandSettingsGlobal,S as brandsCollection,T as brandsCollections,A as categoriesCollection,B as categoriesCollections,l as coreGlobalSettings,K as couponsCollection,L as couponsCollections,V as createTemplateConfig,G as customersCollection,H as customersCollections,r as ecommerceCollections,s as ecommerceGlobals,f as emailSettingsGlobal,O as formEntriesCollection,P as formEntriesCollections,M as formsCollection,N as formsCollections,n as getSettingsForTemplate,t as kitchenSinkCollections,u as mediaCollection,v as mediaCollections,w as menuCollection,x as menuCollections,a as minimalCollections,I as ordersCollection,J as ordersCollections,y as pageCollection,z as pageCollections,o as postsCollection,p as postsCollections,C as productCategoriesCollection,D as productCategoriesCollections,E as productsCollection,F as productsCollections,Q as reviewsCollection,R as reviewsCollections,d as seoSettingsGlobal,m as settingsBySlug,i as shippingSettingsGlobal,c as siteSettingsGlobal,b as starterCollections,h as storeSettingsGlobal,j as systemSettingsGlobal,U as templateCollections}from'../chunk-
|
|
1
|
+
export{g as accessSettingsGlobal,k as allGlobalSettings,q as blogCollections,e as brandSettingsGlobal,S as brandsCollection,T as brandsCollections,A as categoriesCollection,B as categoriesCollections,l as coreGlobalSettings,K as couponsCollection,L as couponsCollections,V as createTemplateConfig,G as customersCollection,H as customersCollections,r as ecommerceCollections,s as ecommerceGlobals,f as emailSettingsGlobal,O as formEntriesCollection,P as formEntriesCollections,M as formsCollection,N as formsCollections,n as getSettingsForTemplate,t as kitchenSinkCollections,u as mediaCollection,v as mediaCollections,w as menuCollection,x as menuCollections,a as minimalCollections,I as ordersCollection,J as ordersCollections,y as pageCollection,z as pageCollections,o as postsCollection,p as postsCollections,C as productCategoriesCollection,D as productCategoriesCollections,E as productsCollection,F as productsCollections,Q as reviewsCollection,R as reviewsCollections,d as seoSettingsGlobal,m as settingsBySlug,i as shippingSettingsGlobal,c as siteSettingsGlobal,b as starterCollections,h as storeSettingsGlobal,j as systemSettingsGlobal,U as templateCollections}from'../chunk-G3B5RM2F.js';export{a as storageSettingsGlobal}from'../chunk-LWM4WABU.js';export{b as authCollections}from'../chunk-CIVA6SKW.js';import'../chunk-Y2YAKDEQ.js';if (typeof window === "undefined") { const { createRequire } = await import(/* @vite-ignore */ 'module'); createRequire(import.meta.url); }
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@kyro-cms/core",
|
|
3
|
-
"version": "0.12.
|
|
3
|
+
"version": "0.12.51",
|
|
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"
|
|
@@ -191,7 +191,7 @@
|
|
|
191
191
|
"ws": "^8.18.0",
|
|
192
192
|
"zod": "^3.24.0",
|
|
193
193
|
"zod-to-json-schema": "^3.25.2",
|
|
194
|
-
"@kyro-cms/ai": "0.12.
|
|
194
|
+
"@kyro-cms/ai": "0.12.51"
|
|
195
195
|
},
|
|
196
196
|
"devDependencies": {
|
|
197
197
|
"@tailwindcss/vite": "^4.0.0",
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
'use strict';var chunkHKNQVI76_cjs=require('./chunk-HKNQVI76.cjs');require('./chunk-YUER4JU3.cjs'),require('./chunk-HPYH7GTS.cjs'),require('./chunk-BHR7OAU4.cjs'),require('./chunk-VRZC4TTF.cjs'),require('./chunk-HTYVI2HK.cjs'),require('./chunk-BUNLC3II.cjs');Object.defineProperty(exports,"autoBootstrap",{enumerable:true,get:function(){return chunkHKNQVI76_cjs.e}});Object.defineProperty(exports,"bootstrapAdmin",{enumerable:true,get:function(){return chunkHKNQVI76_cjs.a}});Object.defineProperty(exports,"bootstrapWithRetry",{enumerable:true,get:function(){return chunkHKNQVI76_cjs.f}});Object.defineProperty(exports,"buildBootstrapConfig",{enumerable:true,get:function(){return chunkHKNQVI76_cjs.c}});Object.defineProperty(exports,"checkBootstrapRequired",{enumerable:true,get:function(){return chunkHKNQVI76_cjs.b}});Object.defineProperty(exports,"getBootstrapFromEnv",{enumerable:true,get:function(){return chunkHKNQVI76_cjs.d}});
|
package/dist/chunk-24L3UEJJ.js
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import {l,k}from'./chunk-PENOCINR.js';import {a}from'./chunk-R25WLKX4.js';import {g as g$1}from'./chunk-Y2YAKDEQ.js';if (typeof window === "undefined") { const { createRequire } = await import(/* @vite-ignore */ 'module'); createRequire(import.meta.url); }
|
|
2
|
-
g$1();async function g(t){let{adminEmail:e,adminPassword:r,adminRole:a$1="super_admin",tenantId:n,emailConfig:o,sendWelcomeEmail:c=false}=t,s=t.authAdapter||new a({path:t.authDbPath||"./data/auth.db"});try{await s.connect?.();}catch{return {success:false,error:"Failed to connect to auth storage"}}let u=new l().validate(r);if(!u.valid)return await s.disconnect?.(),{success:false,error:`Invalid password: ${u.errors.join(", ")}`};if(await s.findUserByEmail(e))return await s.disconnect?.(),{success:false,error:"Admin user already exists"};try{let i=await s.createUser({name:"Super Admin",email:e,password:r,role:a$1||"admin",tenantId:n});if(await s.updateUser?.(i.id,{emailVerified:!0}),c&&o){let l=new k(o),A=l.getTemplates().welcome(e.split("@")[0]);await l.send({to:e,...A});}return await s.disconnect?.(),{success:!0,user:i}}catch(i){return await s.disconnect?.(),{success:false,error:i instanceof Error?i.message:"Failed to create admin user"}}}async function M(t,e){return !await t.findUserByEmail(e)}function w(t){let e=t.KYRO_ADMIN_EMAIL,r=t.KYRO_ADMIN_PASSWORD;return !e||!r?null:{authDbPath:t.KYRO_AUTH_DB_PATH||"./data/auth.db",adminEmail:e,adminPassword:r,adminRole:t.KYRO_ADMIN_ROLE||"super_admin",tenantId:t.KYRO_ADMIN_TENANT_ID,emailConfig:t.SMTP_HOST?{provider:"smtp",smtp:{host:t.SMTP_HOST,port:parseInt(t.SMTP_PORT||"587",10),secure:t.SMTP_SECURE==="true",auth:{user:t.SMTP_USER||"",pass:t.SMTP_PASS||""}},from:t.SMTP_FROM||"noreply@example.com",fromName:t.SMTP_FROM_NAME}:void 0,sendWelcomeEmail:t.KYRO_ADMIN_SEND_WELCOME==="true"}}function h(){return w(process.env)}async function E(){try{let{env:t}=await import('cloudflare:workers');if(t){let e=w(t);if(e)return e}}catch{}return null}async function x(t){let e=h()||await E();if(!e)return null;t&&(e.authAdapter=t);try{if(await e.authAdapter?.connect?.(),await e.authAdapter?.findUserByEmail(e.adminEmail))return await e.authAdapter?.disconnect?.(),{success:!1,error:"Admin user already exists"}}catch{}let r=await g(e);return r.success||console.error(`Bootstrap failed: ${r.error}`),r}async function C(t,e=3,r=2e3){let a="";for(let n=0;n<e;n++){let o=await g(t);if(o.success||(a=o.error||"Unknown error",a.includes("already exists")))return o;n<e-1&&await new Promise(c=>setTimeout(c,r));}return {success:false,error:`Failed after ${e} retries: ${a}`}}export{g as a,M as b,w as c,h as d,x as e,C as f};
|