@kyro-cms/core 0.12.1 → 0.12.4
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/{WebhookService-DTNKXpXp.d.ts → WebhookService-B15DnDeH.d.cts} +3 -7
- package/dist/{WebhookService-DRQLv_jR.d.cts → WebhookService-DJ75IwdZ.d.ts} +3 -7
- package/dist/api-handler-graphql.cjs +1 -1
- package/dist/api-handler-graphql.js +1 -1
- package/dist/api-handler-trpc.cjs +1 -1
- package/dist/api-handler-trpc.js +1 -1
- package/dist/api-handler.cjs +1 -1
- package/dist/api-handler.js +1 -1
- package/dist/{base-Dk6eKGJJ.d.cts → base-CXZxchcr.d.cts} +1 -1
- package/dist/{base-BKGB0Y3W.d.ts → base-CjuIfzH2.d.ts} +1 -1
- package/dist/chunk-3YGGZ2VN.js +133 -0
- package/dist/{chunk-WRSQOKRF.js → chunk-EHLNY6BK.js} +1 -1
- package/dist/{chunk-FKTZLM2C.cjs → chunk-GZGP4THY.cjs} +1 -1
- package/dist/chunk-I67R6MR5.js +2 -0
- package/dist/{chunk-5BPMMIAQ.js → chunk-ISCIUG37.js} +1 -1
- package/dist/chunk-UTFLD5DC.cjs +86 -0
- package/dist/{chunk-HQND27DT.cjs → chunk-W7OSRADF.cjs} +2 -2
- package/dist/{chunk-ER2PUSHG.cjs → chunk-WMZEULS2.cjs} +1 -1
- package/dist/chunk-XSGRGUHP.js +86 -0
- package/dist/chunk-XUONID6O.cjs +2 -0
- package/dist/chunk-Z7CNY2UV.cjs +133 -0
- package/dist/{chunk-BRAWV32L.js → chunk-ZRSXM4BY.js} +1 -1
- package/dist/client.d.cts +1 -1
- package/dist/client.d.ts +1 -1
- package/dist/drizzle/index.cjs +1 -1
- package/dist/drizzle/index.d.cts +2 -2
- package/dist/drizzle/index.d.ts +2 -2
- package/dist/drizzle/index.js +1 -1
- package/dist/graphql/index.d.cts +2 -2
- package/dist/graphql/index.d.ts +2 -2
- package/dist/{index-yPGko8UV.d.cts → index-BCUSHYBf.d.cts} +1 -1
- package/dist/{index-cBgeiKp1.d.ts → index-C7FPi-Fj.d.ts} +1 -1
- package/dist/index.cjs +2 -2
- package/dist/index.d.cts +7 -7
- package/dist/index.d.ts +7 -7
- package/dist/index.js +1 -1
- package/dist/mongodb/index.d.cts +2 -2
- package/dist/mongodb/index.d.ts +2 -2
- package/dist/rest/index.cjs +1 -1
- package/dist/rest/index.d.cts +3 -3
- package/dist/rest/index.d.ts +3 -3
- package/dist/rest/index.js +1 -1
- package/dist/templates/index.d.cts +1 -1
- package/dist/templates/index.d.ts +1 -1
- package/dist/trpc/index.cjs +1 -1
- package/dist/trpc/index.d.cts +2 -2
- package/dist/trpc/index.d.ts +2 -2
- package/dist/trpc/index.js +1 -1
- package/dist/{types-BowAPGjD.d.cts → types-CqqoM3Dy.d.cts} +2 -1
- package/dist/{types-Bj3d_ys8.d.ts → types-L-qNugRL.d.ts} +2 -1
- package/package.json +1 -1
- package/dist/chunk-5KGQOTLK.cjs +0 -133
- package/dist/chunk-76RLJA6S.js +0 -133
- package/dist/chunk-APQOYPRT.cjs +0 -86
- package/dist/chunk-KG7V6O2Z.js +0 -2
- package/dist/chunk-QMPMY2WI.js +0 -86
- package/dist/chunk-WE46GGL4.cjs +0 -2
package/dist/index.d.ts
CHANGED
|
@@ -1,19 +1,19 @@
|
|
|
1
1
|
import * as hono from 'hono';
|
|
2
2
|
import * as hono_types from 'hono/types';
|
|
3
|
-
import { S as StorageProvider, R as Registry } from './index-
|
|
4
|
-
export { C as ConfigService, E as EmailConfig, a as StorageConfig, c as createRegistry, g as getRegistry, r as resetRegistry, b as resolveProvider } from './index-
|
|
5
|
-
import { B as BaseAdapter, K as KyroConfig, i as User, R as Request$1, C as CollectionConfig, G as GlobalConfig, F as FindArgs, b as FindResult, c as FindByIDArgs, d as CreateArgs, e as UpdateArgs, D as DeleteArgs, f as FindVersionsArgs, g as VersionRecord, h as CreateVersionArgs, H as Hook } from './types-
|
|
6
|
-
export { j as AccessArgs, k as AccessControl, l as AdapterConfig, A as AdminConfig, a as AuthConfig, m as CollectionAccess, n as CollectionHooks, o as CreateResult, p as FieldAccess, q as FieldHooks, r as GlobalAccess, s as GlobalHooks, t as HookArgs, I as ImageSize, P as PluginConfig, U as UploadConfig, V as VersionConfig, W as WhereClause, u as evaluateAccess, v as getWhereClause, w as mergeWhereClauses, x as runFieldHooks, y as runHooks } from './types-
|
|
3
|
+
import { S as StorageProvider, R as Registry } from './index-C7FPi-Fj.js';
|
|
4
|
+
export { C as ConfigService, E as EmailConfig, a as StorageConfig, c as createRegistry, g as getRegistry, r as resetRegistry, b as resolveProvider } from './index-C7FPi-Fj.js';
|
|
5
|
+
import { B as BaseAdapter, K as KyroConfig, i as User, R as Request$1, C as CollectionConfig, G as GlobalConfig, F as FindArgs, b as FindResult, c as FindByIDArgs, d as CreateArgs, e as UpdateArgs, D as DeleteArgs, f as FindVersionsArgs, g as VersionRecord, h as CreateVersionArgs, H as Hook } from './types-L-qNugRL.js';
|
|
6
|
+
export { j as AccessArgs, k as AccessControl, l as AdapterConfig, A as AdminConfig, a as AuthConfig, m as CollectionAccess, n as CollectionHooks, o as CreateResult, p as FieldAccess, q as FieldHooks, r as GlobalAccess, s as GlobalHooks, t as HookArgs, I as ImageSize, P as PluginConfig, U as UploadConfig, V as VersionConfig, W as WhereClause, u as evaluateAccess, v as getWhereClause, w as mergeWhereClauses, x as runFieldHooks, y as runHooks } from './types-L-qNugRL.js';
|
|
7
7
|
import { KyroPubSub, KyroWSServer } from './ws/index.js';
|
|
8
8
|
export { PubSub, createWSServer } from './ws/index.js';
|
|
9
|
-
import { W as WebhookPayload, D as DeliveryResult, a as WebhookDelivery, b as WebhookConfig, c as DeliveryOptions, d as WebhookService } from './WebhookService-
|
|
10
|
-
export { A as ALL_WEBHOOK_EVENTS, C as CreateWebhookData, U as UpdateWebhookData, e as WEBHOOK_COLLECTION, f as WEBHOOK_DELIVERY_COLLECTION, g as WEBHOOK_EVENTS, h as WebhookEvent, i as WebhookTriggerResult, j as createWebhookService } from './WebhookService-
|
|
9
|
+
import { W as WebhookPayload, D as DeliveryResult, a as WebhookDelivery, b as WebhookConfig, c as DeliveryOptions, d as WebhookService } from './WebhookService-DJ75IwdZ.js';
|
|
10
|
+
export { A as ALL_WEBHOOK_EVENTS, C as CreateWebhookData, U as UpdateWebhookData, e as WEBHOOK_COLLECTION, f as WEBHOOK_DELIVERY_COLLECTION, g as WEBHOOK_EVENTS, h as WebhookEvent, i as WebhookTriggerResult, j as createWebhookService } from './WebhookService-DJ75IwdZ.js';
|
|
11
11
|
import { F as Field } from './types-fvldOd92.js';
|
|
12
12
|
export { r as ALL_FIELD_TYPES, A as ArrayField, B as BaseField, a as Block, d as BlocksField, u as COMPLEX_FIELD_TYPES, C as CheckboxField, e as CodeField, f as CollapsibleField, g as ColorField, D as DateField, E as EmailField, i as FieldAdmin, j as FieldType, G as GroupField, I as ImageField, J as JSONField, L as LAYOUT_FIELD_TYPES, M as MarkdownField, N as NumberField, x as PRIMITIVE_FIELD_TYPES, P as PasswordField, y as RELATIONAL_FIELD_TYPES, R as RadioField, k as RelationshipField, l as RichTextBlock, m as RichTextField, n as RowField, o as SelectField, T as TabsField, p as TextField, q as TextareaField, U as UploadField, V as ValidateOptions, O as isArrayField, Q as isBlocksField, W as isGroupField, Y as isImageField, Z as isLayoutField, _ as isNumberField, $ as isRelationshipField, a0 as isRichTextField, a1 as isSelectField, a2 as isTextField, a3 as isUploadField } from './types-fvldOd92.js';
|
|
13
13
|
import { ZodTypeAny } from 'zod';
|
|
14
14
|
export { z } from 'zod';
|
|
15
15
|
export { n as normalizeRichTextValue, r as renderRichText, a as richTextStyles } from './richtext-DrhORshE.js';
|
|
16
|
-
import { A as AbstractBaseAdapter } from './base-
|
|
16
|
+
import { A as AbstractBaseAdapter } from './base-CjuIfzH2.js';
|
|
17
17
|
import { Dialect } from './drizzle/index.js';
|
|
18
18
|
export { DrizzleAdapter, PostgresAuthAdapter, collectionToDrizzleSchema, createDatabase, createDrizzleAdapter, fieldToDrizzleType, runMigrations, seedDefaultRoles } from './drizzle/index.js';
|
|
19
19
|
export { MongoDBAdapter, MongoDBAuthAdapter, createMongoDBAdapter } from './mongodb/index.js';
|
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export{a as RedisAuthAdapter}from'./chunk-AU6IWTBO.js';export{N as allSettingsGlobals,c as blogCollections,d as blogGlobals,O as coreSettingsGlobals,S as createTemplateConfig,e as ecommerceCollections,f as ecommerceGlobals,g as kitchenSinkCollections,i as mediaCollections,a as minimalCollections,R as templateCollections}from'./chunk-4RSGPSKQ.js';export{a as kyro}from'./chunk-PTS33SK5.js';export{a as ConfigValidationError,p as Kyro,r as LocalAdapter,l as Registry,h as collectionToCreateZod,i as collectionToUpdateZod,j as collectionToWhereZod,g as collectionToZod,q as createKyro,s as createLocalAdapter,o as createRegistry,f as fieldToZod,m as getRegistry,k as globalToZod,n as resetRegistry,b as validateCollection,e as validateConfig,d as validateFields,c as validateGlobal}from'./chunk-WRSQOKRF.js';export{d as autoBootstrap,a as bootstrapAdmin,e as bootstrapWithRetry,c as getBootstrapFromEnv}from'./chunk-FO3HLBC7.js';import'./chunk-NZ35PV5R.js';export{a as CSSGenerator,g as createAdminStyling,d as defaultDarkTheme,h as defaultFieldStyling,c as defaultLightTheme,e as ecommerce2026Theme,f as generateCSSVariables,b as generateTailwindConfig}from'./chunk-UHFDH3PG.js';export{q as ALL_FIELD_TYPES,n as COMPLEX_FIELD_TYPES,p as LAYOUT_FIELD_TYPES,m as PRIMITIVE_FIELD_TYPES,o as RELATIONAL_FIELD_TYPES,d as isArrayField,f as isBlocksField,e as isGroupField,h as isImageField,k as isLayoutField,b as isNumberField,c as isRelationshipField,i as isRichTextField,j as isSelectField,a as isTextField,g as isUploadField,t as normalizeRichTextValue,u as renderRichText,s as richTextStyles}from'./chunk-INB4LNA6.js';import'./chunk-5SEHX7ON.js';export{a as createContext,g as createCountProcedure,d as createCreateProcedure,f as createDeleteProcedure,h as createDynamicRouter,c as createFindByIDProcedure,b as createFindProcedure,i as createKyroServer,e as createUpdateProcedure}from'./chunk-5BPMMIAQ.js';export{c as buildGraphQLSchema,d as createGraphQLSchema}from'./chunk-PP7W5UKL.js';import {l,n,m,p as p$1,q}from'./chunk-QMPMY2WI.js';export{n as AuditLogger,p as InMemoryAuditLogger,m as InMemoryRateLimiter,r as MediaService,o as createAuditContext,s as createHonoApp,e as createLocalStorage,t as createRESTAPI,i as getAppSecret,j as getEncryptionKey,k as getSessionConfig,h as loadSecrets,d as resolveProvider,g as setDbAdapter}from'./chunk-QMPMY2WI.js';import {b as b$1,c}from'./chunk-7WOX27LK.js';export{a as ConfigService,b as EmailTransport,c as PasswordPolicy}from'./chunk-7WOX27LK.js';import'./chunk-K6WUOU6P.js';import'./chunk-AE6GXUT7.js';import {a as a$1}from'./chunk-2W4FK6CJ.js';export{a as SQLiteAuthAdapter}from'./chunk-2W4FK6CJ.js';import'./chunk-NRLIGDYF.js';export{e as ALL_WEBHOOK_EVENTS,f as WEBHOOK_COLLECTION,g as WEBHOOK_DELIVERY_COLLECTION,d as WEBHOOK_EVENTS,n as WebhookService,l as buildDeliveryRecord,m as createTestPayload,o as createWebhookService,j as deliverWebhook,k as deliverWithRetry,i as generateWebhookSecret,h as signPayload}from'./chunk-KG7V6O2Z.js';export{a as evaluateAccess,c as getWhereClause,b as mergeWhereClauses}from'./chunk-HLSB2MCK.js';export{b as KyroPubSub,c as KyroWSServer,a as PubSub,d as createWSServer}from'./chunk-GKYEJ2UF.js';import'./chunk-PP5S2UBV.js';export{c as DrizzleAdapter,b as collectionToDrizzleSchema,f as createDatabase,d as createDrizzleAdapter,a as fieldToDrizzleType,g as runMigrations,h as seedDefaultRoles}from'./chunk-76RLJA6S.js';import {a as a$2}from'./chunk-RHCWCG3O.js';export{a as PostgresAuthAdapter}from'./chunk-RHCWCG3O.js';import'./chunk-OG7CNQGU.js';import'./chunk-QRXDCV6K.js';export{a as MongoDBAdapter,b as createMongoDBAdapter}from'./chunk-YPDRUVWG.js';import {a}from'./chunk-P7CESLDJ.js';export{a as MongoDBAuthAdapter}from'./chunk-P7CESLDJ.js';export{a as AbstractBaseAdapter}from'./chunk-TQNM4C7H.js';import'./chunk-KDNYHLD2.js';import'./chunk-5J6HXUF6.js';import q$1,{randomBytes}from'crypto';import {readFileSync}from'fs';import Me,{join,resolve}from'path';export{z}from'zod';import {createStorage}from'unstorage';import $r from'unstorage/drivers/indexedb';import zr from'unstorage/drivers/fs';async function Ie(s,e){let t=e.data;for(let r of s){let o=await r({...e,data:t});o!==void 0&&(t=o);}return t}async function br(s,e){return Ie(s,e)}var b=class{name;version;description;hooks={};collections=[];globals=[];fields=[];extensions={collections:[],globals:[]};adminComponents={};adminStyles=[];serverMiddleware;clientMiddleware;constructor(e){this.name=e;}async init(e){}async beforeInit(e){}async afterInit(e){}getCollections(){return this.collections}getGlobals(){return this.globals}getHooks(){return this.hooks}},$=class{plugins=new Map;hooks=new Map;register(e){if(this.plugins.has(e.name))throw new Error(`Plugin "${e.name}" is already registered`);this.plugins.set(e.name,e);let t=e.getHooks?.()||{};for(let[r,o]of Object.entries(t))if(Array.isArray(o))for(let i of o)this.registerHook(r,i);}unregister(e){let t=this.plugins.get(e);if(!t)return;let r=t.getHooks?.()||{};for(let[o,i]of Object.entries(r))if(Array.isArray(i))for(let n of i)this.unregisterHook(o,n);this.plugins.delete(e);}get(e){return this.plugins.get(e)}getAll(){return Array.from(this.plugins.values())}has(e){return this.plugins.has(e)}registerHook(e,t){this.hooks.has(e)||this.hooks.set(e,[]),this.hooks.get(e).push(t);}unregisterHook(e,t){let r=this.hooks.get(e);if(r){let o=r.indexOf(t);o>-1&&r.splice(o,1);}}async executeHook(e,t){let r=this.hooks.get(e)||[],o=t;for(let i of r)try{let n=await i({...t,data:o});n!==void 0&&(o=n);}catch(n){console.error(`[PluginManager] Error in hook "${e}":`,n);}return o}getAllCollections(){let e=[];for(let t of this.plugins.values()){let r=t.getCollections?.()||[];e.push(...r);}return e}getAllGlobals(){let e=[];for(let t of this.plugins.values()){let r=t.getGlobals?.()||[];e.push(...r);}return e}getAllFields(){let e=[];for(let t of this.plugins.values())e.push(...t.fields);return e}getAdminComponents(){let e={};for(let t of this.plugins.values())Object.assign(e,t.adminComponents);return e}getAdminStyles(){let e=[];for(let t of this.plugins.values())e.push(...t.adminStyles);return e}},L=class extends b{constructor(){super("seo"),this.description="Advanced SEO features including sitemaps, robots.txt, and structured data",this.collections.push({slug:"seo-settings",label:"SEO Settings",fields:[{name:"sitemap",type:"checkbox",label:"Enable Sitemap",defaultValue:true},{name:"robotsTxt",type:"richtext",label:"robots.txt Content"},{name:"canonicalUrl",type:"text",variant:"url",label:"Canonical URL"},{name:"ogImage",type:"text",label:"Default OG Image URL"}]});}},E=class extends b{constructor(){super("analytics"),this.description="Analytics integration for tracking page views and events",this.collections.push({slug:"analytics-events",label:"Analytics Events",fields:[{name:"name",type:"text",required:true},{name:"properties",type:"json",label:"Event Properties"},{name:"timestamp",type:"date",required:true},{name:"userId",type:"text",label:"User ID"},{name:"sessionId",type:"text",label:"Session ID"}]}),this.adminComponents.AnalyticsDashboard={};}},U=class extends b{constructor(){super("comments"),this.description="Commenting system for products and posts",this.collections.push({slug:"comments",label:"Comments",fields:[{name:"content",type:"richtext",required:true},{name:"author",type:"text",required:true},{name:"email",type:"email"},{name:"approved",type:"checkbox",defaultValue:false},{name:"parent",type:"text",label:"Parent Comment ID"},{name:"resourceType",type:"text",required:true},{name:"resourceId",type:"text",required:true}]}),this.adminComponents.CommentModeration={};}},V=class extends b{constructor(){super("reviews"),this.description="Product reviews and ratings",this.collections.push({slug:"reviews",label:"Reviews",fields:[{name:"rating",type:"number",required:true,min:1,max:5},{name:"title",type:"text"},{name:"content",type:"richtext",required:true},{name:"author",type:"relationship",relationTo:"customers"},{name:"product",type:"relationship",relationTo:"products",required:true},{name:"approved",type:"checkbox",defaultValue:false},{name:"verified",type:"checkbox",label:"Verified Purchase"},{name:"helpful",type:"number",label:"Helpful Count",defaultValue:0}]}),this.adminComponents.ReviewModeration={};}},O=class extends b{constructor(){super("wishlist"),this.description="Customer wishlists",this.collections.push({slug:"wishlists",label:"Wishlists",fields:[{name:"customer",type:"relationship",relationTo:"customers",required:true},{name:"name",type:"text",label:"Wishlist Name",defaultValue:"My Wishlist"},{name:"items",type:"blocks",label:"Items",blocks:[{slug:"wishlist-item",label:"Item",fields:[{name:"product",type:"relationship",relationTo:"products"},{name:"quantity",type:"number",defaultValue:1},{name:"addedAt",type:"date"},{name:"priority",type:"select",options:[{label:"Low",value:"low"},{label:"Medium",value:"medium"},{label:"High",value:"high"}]}]}]}]});}},Ar={SEO:L,Analytics:E,Comments:U,Reviews:V,Wishlist:O};var wr={maxAttempts:5,lockDuration:9e5,notifyUser:true,notifyAdmin:true,adminNotifyAfter:3},x=class{redis;prefix;config;constructor(e,t={},r="kyro:lockout:"){this.redis=e,this.prefix=r,this.config={...wr,...t};}lockKey(e){return `${this.prefix}${e}`}historyKey(e){return `${this.prefix}${e}:history`}async checkLockout(e){let t=this.lockKey(e),r=await this.redis.hgetall(t);if(!r||Object.keys(r).length===0)return {locked:false,attemptsRemaining:this.config.maxAttempts,totalAttempts:0};let o=parseInt(r.attempts,10),i=r.lockedUntil?new Date(parseInt(r.lockedUntil,10)):void 0;return i&&i>new Date?{locked:true,attemptsRemaining:0,lockedUntil:i,totalAttempts:o}:i&&i<=new Date?(await this.unlockAccount(e),{locked:false,attemptsRemaining:this.config.maxAttempts,totalAttempts:0}):{locked:false,attemptsRemaining:Math.max(0,this.config.maxAttempts-o),totalAttempts:o}}async recordFailedAttempt(e){let t=this.lockKey(e),r=this.historyKey(e),o=Date.now(),i=await this.redis.hincrby(t,"attempts",1);if(await this.redis.hset(t,"lastAttempt",o.toString()),await this.redis.lpush(r,o.toString()),await this.redis.ltrim(r,0,99),i>=this.config.maxAttempts){let n=new Date(o+this.config.lockDuration);return await this.redis.hset(t,{lockedAt:o.toString(),lockedUntil:n.getTime().toString()}),await this.redis.expire(t,Math.ceil(this.config.lockDuration/1e3)+3600),{locked:true,attemptsRemaining:0,lockedUntil:n,totalAttempts:i}}return {locked:false,attemptsRemaining:Math.max(0,this.config.maxAttempts-i),totalAttempts:i}}async lockAccount(e,t){let r=this.lockKey(e),o=Date.now(),i=t||this.config.lockDuration,n=new Date(o+i),a=this.redis.pipeline();a.hset(r,{attempts:this.config.maxAttempts.toString(),lockedAt:o.toString(),lockedUntil:n.getTime().toString()}),a.expire(r,Math.ceil(i/1e3)+3600),await a.exec();}async unlockAccount(e){let t=this.lockKey(e);await this.redis.del(t);}async resetAttempts(e){let t=this.lockKey(e);(await this.redis.hgetall(t)).lockedAt?await this.redis.hset(t,{attempts:"0",lockedAt:"",lockedUntil:""}):await this.redis.del(t);}async getLockoutHistory(e,t=10){let r=this.historyKey(e);return (await this.redis.lrange(r,0,t-1)).map(i=>new Date(parseInt(i,10)))}async getLockoutStats(e){let t=this.historyKey(e),r=await this.redis.lrange(t,0,-1),o=r.filter((n,a)=>(a+1)%this.config.maxAttempts===0).length,i=await this.redis.hget(this.lockKey(e),"lockedAt");return {totalFailedAttempts:r.length,lockoutCount:o,lastLockout:i?new Date(parseInt(i,10)):null,averageAttemptsBeforeLockout:o>0?this.config.maxAttempts:0}}shouldNotifyAdmin(e){return this.config.notifyAdmin&&e>=this.config.adminNotifyAfter}getConfig(){return {...this.config}}setConfig(e){this.config={...this.config,...e};}};var kr={"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}},S=class{redis;prefix;limits;userLimits;constructor(e,t,r,o="kyro:ratelimit:"){this.redis=e,this.prefix=o,this.limits={...kr,...t},this.userLimits=r||{"user:api":{window:6e4,max:500},"user:write":{window:36e5,max:100}};}getKey(e,t){return `${this.prefix}${e}:${t}`}async check(e,t){let r=this.limits[e]||this.limits["api:general"],o=this.getKey(e,t),i=Date.now(),n=i-r.window,a=this.redis.pipeline();a.zremrangebyscore(o,0,n),a.zcard(o),a.zadd(o,i,`${i}:${Math.random()}`),a.expire(o,Math.ceil(r.window/1e3)+1);let c=(await a.exec())?.[1]?.[1]||0;if(c>=r.max){let g=await this.redis.zrange(o,0,0,"WITHSCORES"),d=g.length>1?parseInt(g[1],10)+r.window:i+r.window;return {allowed:false,remaining:0,resetAt:d,retryAfter:Math.ceil((d-i)/1e3)}}return {allowed:true,remaining:r.max-c-1,resetAt:i+r.window}}async checkUser(e,t,r){let o=this.userLimits[e]||this.userLimits["user:api"],i=this.getKey(`user:${e}:${t}`,r),n=Date.now(),a=n-o.window,l=this.redis.pipeline();l.zremrangebyscore(i,0,a),l.zcard(i),l.zadd(i,n,`${n}:${Math.random()}`),l.expire(i,Math.ceil(o.window/1e3)+1);let g=(await l.exec())?.[1]?.[1]||0;if(g>=o.max){let d=await this.redis.zrange(i,0,0,"WITHSCORES"),u=d.length>1?parseInt(d[1],10)+o.window:n+o.window;return {allowed:false,remaining:0,resetAt:u,retryAfter:Math.ceil((u-n)/1e3)}}return {allowed:true,remaining:o.max-g-1,resetAt:n+o.window}}async reset(e,t){let r=this.getKey(e,t);await this.redis.del(r);}async resetUser(e,t,r){let o=this.getKey(`user:${e}:${t}`,r);await this.redis.del(o);}async getStatus(e,t){let r=this.limits[e]||this.limits["api:general"],o=this.getKey(e,t),i=Date.now(),n=i-r.window;await this.redis.zremrangebyscore(o,0,n);let a=await this.redis.zcard(o);return {count:a,limit:r.max,remaining:Math.max(0,r.max-a),resetAt:i+r.window}}setLimit(e,t){this.limits[e]=t;}setUserLimit(e,t){this.userLimits[e]=t;}};var P=class{users=new Map;sessions=new Map;refreshTokens=new Map;emailToUserId=new Map;passwordHistory=new Map;emailVerificationTokens=new Map;passwordResetTokens=new Map;auditLogs=[];externalDb=false;constructor(){}async connect(){}async disconnect(){this.users.clear(),this.sessions.clear(),this.refreshTokens.clear(),this.emailToUserId.clear(),this.passwordHistory.clear();}async createUser(e){let t=randomBytes(16).toString("hex"),r=new Date().toISOString(),o=await this.hashPassword(e.password),i={id:t,email:e.email.toLowerCase(),passwordHash:o,role:e.role||"customer",tenantId:e.tenantId,createdAt:r,updatedAt:r};return this.users.set(t,i),this.emailToUserId.set(e.email.toLowerCase(),t),this.passwordHistory.set(t,[]),i}async findUserByEmail(e){let t=this.emailToUserId.get(e.toLowerCase());return t?this.findUserById(t):null}async findUserById(e){return this.users.get(e)||null}async updateUser(e,t){let r=await this.findUserById(e);if(!r)return null;let o={...r,...t,id:e,updatedAt:new Date().toISOString()};return t.email&&t.email!==r.email&&(this.emailToUserId.delete(r.email.toLowerCase()),this.emailToUserId.set(t.email.toLowerCase(),e)),this.users.set(e,o),o}async deleteUser(e){let t=await this.findUserById(e);return t?(this.users.delete(e),this.emailToUserId.delete(t.email.toLowerCase()),this.refreshTokens.forEach((r,o)=>{this.sessions.get(r)?.userId===e&&(this.refreshTokens.delete(o),this.sessions.delete(r));}),this.passwordHistory.delete(e),this.sessions.forEach((r,o)=>{r.userId===e&&this.sessions.delete(o);}),true):false}async hashPassword(e){return (await import('bcryptjs')).default.hash(e,12)}async verifyPassword(e,t){let r=await this.findUserByEmail(e);return !r||!r.passwordHash?null:await(await import('bcryptjs')).default.compare(t,r.passwordHash)?r:null}async createSession(e,t={}){let r=randomBytes(32).toString("hex"),o=randomBytes(32).toString("base64url"),i=randomBytes(32).toString("base64url"),n=new Date,a={id:r,userId:e,token:o,refreshToken:i,expiresAt:new Date(n.getTime()+86400*1e3).toISOString(),createdAt:n.toISOString(),ipAddress:t.ipAddress,userAgent:t.userAgent};return this.sessions.set(r,a),this.refreshTokens.set(i,r),a}async findSessionByToken(e){return this.sessions.get(e)||null}async findSessionByRefreshToken(e){let t=this.refreshTokens.get(e);return t&&this.sessions.get(t)||null}async deleteSession(e){let t=this.sessions.get(e);return t?(t.refreshToken&&this.refreshTokens.delete(t.refreshToken),this.sessions.delete(e),true):false}async deleteUserSessions(e){let t=0;return this.sessions.forEach((r,o)=>{r.userId===e&&(r.refreshToken&&this.refreshTokens.delete(r.refreshToken),this.sessions.delete(o),t++);}),t}async addPasswordToHistory(e,t){let r=this.passwordHistory.get(e)||[];r.push(t),r.length>5&&r.splice(0,r.length-5),this.passwordHistory.set(e,r);}async getPasswordHistory(e,t=5){return this.passwordHistory.get(e)||[]}async isPasswordInHistory(e,t,r=5){let o=await this.getPasswordHistory(t,r),i=(await import('bcryptjs')).default;for(let n of o)if(await i.compare(e,n))return true;return false}async createEmailVerificationToken(e){let t=randomBytes(32).toString("hex"),r=new Date(Date.now()+1440*60*1e3);return this.emailVerificationTokens.set(t,{userId:e,expiresAt:r}),{token:t,expiresAt:r}}async verifyEmailToken(e){let t=this.emailVerificationTokens.get(e);return !t||t.expiresAt<new Date?(this.emailVerificationTokens.delete(e),{success:false,error:"Invalid or expired token"}):(this.emailVerificationTokens.delete(e),{success:true,userId:t.userId})}async createPasswordResetToken(e){let t=await this.findUserByEmail(e);if(!t)return {token:"",expiresAt:new Date,error:"User not found"};let r=randomBytes(32).toString("hex"),o=new Date(Date.now()+3600*1e3);return this.passwordResetTokens.set(r,{userId:t.id,expiresAt:o}),{token:r,expiresAt:o}}async resetPasswordWithToken(e,t){let r=this.passwordResetTokens.get(e);if(!r||r.expiresAt<new Date)return this.passwordResetTokens.delete(e),{success:false,error:"Invalid or expired token"};let o=await this.hashPassword(t);return await this.updateUser(r.userId,{passwordHash:o}),this.passwordResetTokens.delete(e),{success:true}}async hasAnyUsers(){return this.users.size>0}async findAuditLogs(e){let{limit:t=50,offset:r=0}=e,o=this.auditLogs.slice().reverse();return e.userId&&(o=o.filter(i=>i.userId===e.userId)),e.action&&(Array.isArray(e.action)?o=o.filter(i=>e.action.includes(String(i.action))):o=o.filter(i=>i.action===e.action)),e.resource&&(o=o.filter(i=>i.resource===e.resource)),e.success!==void 0&&(o=o.filter(i=>i.success===e.success)),{logs:o.slice(r,r+t),total:o.length}}async createAuditLog(e){let t=randomBytes(16).toString("hex"),o={...e,id:t,timestamp:new Date};return this.auditLogs.push(o),o}};var C=class{storage=new Map;history=new Map;config;constructor(e={}){this.config={maxAttempts:5,lockDuration:9e5,notifyUser:true,notifyAdmin:true,adminNotifyAfter:3,...e};}async checkLockout(e){let t=Date.now(),r=this.storage.get(e);if(r&&r.lockedUntil!==null&&r.lockedUntil<=t)return await this.resetAttempts(e),{locked:false,attemptsRemaining:this.config.maxAttempts,totalAttempts:0};if(!r)return {locked:false,attemptsRemaining:this.config.maxAttempts,totalAttempts:0};let{attempts:o,lockedUntil:i}=r;return i!==null&&i>t?{locked:true,attemptsRemaining:0,lockedUntil:new Date(i),totalAttempts:o}:{locked:false,attemptsRemaining:Math.max(0,this.config.maxAttempts-o),totalAttempts:o}}async recordFailedAttempt(e){let t=Date.now(),r=this.storage.get(e)||{attempts:0,lastAttempt:null,lockedAt:null,lockedUntil:null};r.attempts+=1,r.lastAttempt=t;let o=this.history.get(e)||[];if(o.push(t),o.length>100&&o.splice(0,o.length-100),this.history.set(e,o),this.storage.set(e,r),r.attempts>=this.config.maxAttempts){let i=new Date(t+this.config.lockDuration);return r.lockedAt=t,r.lockedUntil=i.getTime(),this.storage.set(e,r),{locked:true,attemptsRemaining:0,lockedUntil:i,totalAttempts:r.attempts}}return {locked:false,attemptsRemaining:Math.max(0,this.config.maxAttempts-r.attempts),totalAttempts:r.attempts}}async lockAccount(e,t){let r=Date.now(),o=t||this.config.lockDuration,i=new Date(r+o),n=this.storage.get(e)||{attempts:0,lastAttempt:null,lockedAt:null,lockedUntil:null};n.attempts=this.config.maxAttempts,n.lockedAt=r,n.lockedUntil=i.getTime(),this.storage.set(e,n);}async unlockAccount(e){await this.resetAttempts(e);}async resetAttempts(e){let t=this.storage.get(e);t&&(t.attempts=0,t.lockedAt=null,t.lockedUntil=null,this.storage.set(e,t)),this.history.delete(e);}async getLockoutHistory(e,t=10){return (this.history.get(e)||[]).slice(-t).reverse().map(o=>new Date(o))}async getLockoutStats(e){let r=(this.history.get(e)||[]).length,o=Math.floor(r/this.config.maxAttempts),i=null,n=this.storage.get(e);n&&n.lockedAt!==null&&(i=new Date(n.lockedAt));let a=o>0?this.config.maxAttempts:0;return {totalFailedAttempts:r,lockoutCount:o,lastLockout:i,averageAttemptsBeforeLockout:a}}shouldNotifyAdmin(e){return this.config.notifyAdmin&&e>=this.config.adminNotifyAfter}getConfig(){return {...this.config}}setConfig(e){this.config={...this.config,...e};}};function h(s,e=""){return process.env[s]||e}function A(s,e=false){let t=process.env[s];return t?t.toLowerCase()==="true":e}function p(s,e=0){let t=process.env[s];return t?parseInt(t,10):e}function Le(){let s=process.env.KYRO_AUTH_DATABASE?.toLowerCase();if(s&&["sqlite","postgres","mongodb","memory"].includes(s))return s;try{let e=join(process.cwd(),"kyro.config.ts"),t=readFileSync(e,"utf8");if(t.includes("createLocalAdapter"))return "sqlite";if(t.includes("createDrizzleAdapter"))return t.includes("postgres")||t.includes("postgresql"),"postgres";if(t.includes("createMongoDBAdapter"))return "mongodb"}catch{}return "memory"}async function Pr(s){let e=process.cwd(),t=e.endsWith("admin")?join(e,".."):e,r=resolve(t,"data","auth.db");switch(s){case "sqlite":return new a$1({path:h("KYRO_AUTH_DB_PATH",r)});case "postgres":{try{let o=h("DATABASE_URL","");if(o){let{drizzle:i}=await import('drizzle-orm/postgres-js'),a=(await import('postgres')).default(o,{onnotice:()=>{}}),l=i(a);return new a$2({db:l})}}catch{console.warn("[Auth] Could not create PostgresAuthAdapter, falling back to SQLite auth adapter.");}return new a$1({path:h("KYRO_AUTH_DB_PATH",r)})}case "mongodb":{try{let o=h("MONGODB_URI","");if(o){let{MongoClient:i}=await import('mongodb'),n=new i(o);await n.connect();let l=new URL(o).pathname.replace(/^\//,"")||"kyro_cms",c=n.db(l);return new a({db:c})}}catch{console.warn("[Auth] Could not create MongoDBAuthAdapter, falling back to SQLite auth adapter.");}return new a$1({path:h("KYRO_AUTH_DB_PATH",r)})}default:return new P}}async function W(s,e){let t=A("KYRO_DISTRIBUTED",false),r;if(t){let{RedisAuthAdapter:d}=await import('./redis-adapter-VAXP43GR.js'),u=h("REDIS_URL","redis://localhost:6379"),y=A("REDIS_TLS",false),f=new d({url:u,tls:y});await f.connect?.(),r=f;}else {let d=s||Le();r=await Pr(d),r.connect&&await r.connect();}let o=e?await b$1.fromConfig(e).catch(()=>null)||b$1.fromEnv()||void 0:b$1.fromEnv()||void 0,i=new c({minLength:p("PASSWORD_MIN_LENGTH",12),requireUppercase:A("PASSWORD_REQUIRE_UPPERCASE",true),requireLowercase:A("PASSWORD_REQUIRE_LOWERCASE",true),requireNumbers:A("PASSWORD_REQUIRE_NUMBERS",true),requireSpecialChars:A("PASSWORD_REQUIRE_SPECIAL",true),preventReuse:p("PASSWORD_PREVENT_REUSE",5),maxLength:p("PASSWORD_MAX_LENGTH",128)}),n$1,a,l;if(t){let u=r.redis;n$1=new x(u,{maxAttempts:p("LOCKOUT_MAX_ATTEMPTS",5),lockDuration:p("LOCKOUT_DURATION_MINUTES",15)*60*1e3}),a=new S(u,{"auth:login":{window:p("RATE_LIMIT_AUTH_WINDOW_MS",9e5),max:p("RATE_LIMIT_AUTH_MAX_REQUESTS",10)},"api:general":{window:p("RATE_LIMIT_WINDOW_MS",6e4),max:p("RATE_LIMIT_MAX_REQUESTS",100)}}),l=new n(u,p("AUDIT_LOG_RETENTION_DAYS",30));}else n$1=new C({maxAttempts:p("LOCKOUT_MAX_ATTEMPTS",5),lockDuration:p("LOCKOUT_DURATION_MINUTES",15)*60*1e3}),a=new m({"auth:login":{window:p("RATE_LIMIT_AUTH_WINDOW_MS",9e5),max:p("RATE_LIMIT_AUTH_MAX_REQUESTS",10)},"api:general":{window:p("RATE_LIMIT_WINDOW_MS",6e4),max:p("RATE_LIMIT_MAX_REQUESTS",100)}}),l=A("AUDIT_LOG_ENABLED",true)?new p$1(p("AUDIT_LOG_RETENTION_DAYS",30)):void 0;let c$1=new q({redis:r,email:o,jwtSecret:h("APP_SECRET","change-me"),jwtExpiresIn:h("JWT_EXPIRES_IN","24h"),jwtIssuer:h("JWT_ISSUER","kyro-cms"),jwtAudience:h("JWT_AUDIENCE","kyro-cms-client"),passwordPolicy:i,lockout:n$1,rateLimiter:a,auditLogger:l,baseUrl:h("EMAIL_BASE_URL","http://localhost:4321"),emailVerificationRequired:A("EMAIL_VERIFICATION_REQUIRED",true)}),g=t?"distributed":s||Le();return {authAdapter:r,databaseType:g,email:o,passwordPolicy:i,lockout:n$1,rateLimiter:a,auditLogger:l,routes:c$1}}var Ue=W().catch(s=>(console.warn("[AuthConfig] Failed to initialize auth config:",s.message),null));var Cr=12,Tr="24h",vr="7d",H=class{adapter;config;constructor(e,t){this.adapter=e,this.config={secret:t.secret,expiresIn:t.expiresIn??Tr,refreshExpiresIn:t.refreshExpiresIn??vr,issuer:t.issuer??"kyro-cms",audience:t.audience??[],saltRounds:t.saltRounds??Cr};}async register(e){try{if(await this.adapter.findUserByEmail(e.email))return {success:!1,error:"Email already registered"};let r=await this.adapter.createUser({email:e.email,password:e.password,role:e.role??"customer",tenantId:e.tenantId});return this.createSessionForUser(r)}catch(t){return {success:false,error:String(t)}}}async login(e){try{let t=await this.adapter.verifyPassword(e.email,e.password);return t?this.createSessionForUser(t):{success:!1,error:"Invalid credentials"}}catch(t){return {success:false,error:String(t)}}}async logout(e){await this.adapter.deleteSession(e);}async refreshToken(e){try{let t=await this.adapter.findSessionByToken(e);if(!t||new Date(t.expiresAt)<new Date)return {success:!1,error:"Invalid or expired refresh token"};let r=await this.adapter.findUserById(t.userId);return r?(await this.adapter.deleteSession(e),this.createSessionForUser(r)):{success:!1,error:"User not found"}}catch(t){return {success:false,error:String(t)}}}async verifyToken(e){try{let{default:t}=await import('jsonwebtoken');return t.verify(e,this.config.secret,{issuer:this.config.issuer,audience:this.config.audience.length>0?this.config.audience[0]:void 0})}catch{return null}}async getUserFromToken(e){let t=await this.verifyToken(e);return t?this.adapter.findUserById(t.sub):null}async changePassword(e,t,r){try{let o=await this.adapter.findUserById(e);return o?await this.adapter.verifyPassword(o.email,t)?(await this.adapter.updateUser(e,{password:r}),await this.adapter.deleteUserSessions(e),{success:!0,user:o}):{success:!1,error:"Current password is incorrect"}:{success:!1,error:"User not found"}}catch(o){return {success:false,error:String(o)}}}async resetPassword(e,t){try{let r=await this.adapter.findUserByEmail(e);return r?(await this.adapter.updateUser(r.id,{password:t}),await this.adapter.deleteUserSessions(r.id),{success:!0,user:r}):{success:!1,error:"User not found"}}catch(r){return {success:false,error:String(r)}}}async sendEmailVerification(e){try{let{token:t,expiresAt:r}=await this.adapter.createEmailVerificationToken(e);return {success:!0}}catch(t){return {success:false,error:String(t)}}}async verifyEmail(e){try{return await this.adapter.verifyEmailToken(e)}catch(t){return {success:false,error:String(t)}}}async requestPasswordReset(e){try{let t=await this.adapter.createPasswordResetToken(e);return t.error?{success:!1,error:t.error}:{success:!0}}catch(t){return {success:false,error:String(t)}}}async resetPasswordWithToken(e,t){try{return await this.adapter.resetPasswordWithToken(e,t)}catch(r){return {success:false,error:String(r)}}}async deleteAccount(e){try{return await this.adapter.findUserById(e)?(await this.adapter.deleteUserSessions(e),await this.adapter.deleteUser(e),{success:!0}):{success:!1,error:"User not found"}}catch(t){return {success:false,error:String(t)}}}async createSessionForUser(e){let t=await this.generateToken(e),r=await this.adapter.createSession(e.id);return {success:true,user:e,session:r,token:t}}async generateToken(e){let{default:t}=await import('jsonwebtoken'),r={sub:e.id,email:e.email,role:e.role,tenantId:e.tenantId},o={expiresIn:this.parseExpiresIn(this.config.expiresIn)/1e3,issuer:this.config.issuer};return this.config.audience.length>0&&(o.audience=this.config.audience[0]),t.sign(r,this.config.secret,o)}async hashPassword(e){let{default:t}=await import('bcryptjs');return t.hash(e,this.config.saltRounds)}parseExpiresIn(e){if(typeof e=="number")return e;let t=e.match(/^(\d+)([smhd])$/);if(!t)return 864e5;let r=parseInt(t[1],10);switch(t[2]){case "s":return r*1e3;case "m":return r*6e4;case "h":return r*36e5;case "d":return r*864e5;default:return 864e5}}};function Rr(s,e){return new H(s,e)}function _(){return {enabled:true,draftsEnabled:true,publishEnabled:true,scheduleEnabled:false,versioningEnabled:true,maxVersionsPerDocument:50,autoPublish:false,requirePublishPermission:true}}var M=class{adapter;config;constructor(e,t){this.adapter=e,this.config={..._(),...t};}async createVersion(e){let r=((await this.adapter.getLatestVersion(e.collection,e.documentId))?.version??0)+1,o={...e,version:r},i=await this.adapter.createVersion(o);return this.config.maxVersionsPerDocument>0&&await this.pruneOldVersions(e.collection,e.documentId),i}async publishVersion(e){let t=await this.adapter.getVersion(e.collection,e.versionId);if(!t)throw new Error("Version not found");if(t.status==="published")throw new Error("Version is already published");await this.adapter.publishVersion(e);}async unpublishDocument(e,t){let r=await this.adapter.getVersions({collection:e,documentId:t,limit:1e3});for(let o of r)if(o.status==="published"){await this.createVersion({collection:e,documentId:t,data:o.data,status:"draft",createdBy:"system",changeDescription:"Unpublished document"});break}}async revertToVersion(e,t,r,o){if(!await this.adapter.getVersion(e,r))throw new Error("Version not found");return await this.adapter.revertToVersion({collection:e,documentId:t,versionId:r,userId:o})}async getVersionHistory(e,t,r=20,o=0){return this.adapter.getVersions({collection:e,documentId:t,limit:r,offset:o})}async compareTwoVersions(e,t,r,o){return this.adapter.compareVersions({collection:e,documentId:t,versionA:r,versionB:o})}async getLatestDraft(e,t){return this.adapter.getLatestVersion(e,t)}async getPublishedVersion(e,t){return this.adapter.getPublishedVersion(e,t)}async getVersion(e,t){return this.adapter.getVersion(e,t)}async schedulePublish(e,t,r,o){if(!this.config.scheduleEnabled)throw new Error("Scheduled publishing is not enabled");if(!await this.adapter.getVersion(e,r))throw new Error("Version not found")}async deleteVersionHistory(e,t){await this.adapter.deleteVersions(e,t);}async pruneOldVersions(e,t){let r=await this.adapter.getVersions({collection:e,documentId:t,limit:this.config.maxVersionsPerDocument+100});if(r.length<=this.config.maxVersionsPerDocument)return;r.slice(0,this.config.maxVersionsPerDocument);let i=r.slice(this.config.maxVersionsPerDocument);for(let n of i)if(n.status!=="published"){await this.adapter.deleteVersions(e,t);break}}};function Dr(s,e){return new M(s,e)}function Ir(s){return s==="published"}function Lr(s){return s==="draft"}function Er(s){return s==="archived"}function Ur(s){return s?Array.isArray(s)?s:Object.values(s):[]}function Vr(s){return s?Array.isArray(s)?s:Object.values(s):[]}function Ve(s){return {collections:Ur(s.collections),globals:Vr(s.globals),adapter:s.adapter,plugins:s.plugins,auth:s.auth,cors:s.cors,admin:s.admin,upload:s.upload,graphQL:s.graphQL,typescript:s.typescript,localization:s.localization,rateLimit:s.rateLimit,debug:s.debug}}var Or=Ve;function Hr(s){let{siteSettings:e,seoSettings:t,title:r,description:o,image:i,url:n}=s;if(!e)return "";let a=e.siteName||"",l=r||t?.defaultTitle||a,c=t?.titleTemplate,g=t?.separator||" | ",d=t?.siteNameInTitle!==false,u=c?c.replace(/\{\{title\}\}/g,l).replace(/\{\{siteName\}\}/g,d?a:"").replace(/\{\{separator\}\}/g,g).replace(/\s+/g," ").trim():l,y=o||t?.defaultDescription||e.siteDescription||"",f=i||e.siteOgImage?.url||"",F=n||e.siteUrl||"",m=`
|
|
1
|
+
export{a as RedisAuthAdapter}from'./chunk-AU6IWTBO.js';export{N as allSettingsGlobals,c as blogCollections,d as blogGlobals,O as coreSettingsGlobals,S as createTemplateConfig,e as ecommerceCollections,f as ecommerceGlobals,g as kitchenSinkCollections,i as mediaCollections,a as minimalCollections,R as templateCollections}from'./chunk-4RSGPSKQ.js';export{a as kyro}from'./chunk-PTS33SK5.js';export{a as ConfigValidationError,p as Kyro,r as LocalAdapter,l as Registry,h as collectionToCreateZod,i as collectionToUpdateZod,j as collectionToWhereZod,g as collectionToZod,q as createKyro,s as createLocalAdapter,o as createRegistry,f as fieldToZod,m as getRegistry,k as globalToZod,n as resetRegistry,b as validateCollection,e as validateConfig,d as validateFields,c as validateGlobal}from'./chunk-EHLNY6BK.js';export{d as autoBootstrap,a as bootstrapAdmin,e as bootstrapWithRetry,c as getBootstrapFromEnv}from'./chunk-FO3HLBC7.js';import'./chunk-NZ35PV5R.js';export{a as CSSGenerator,g as createAdminStyling,d as defaultDarkTheme,h as defaultFieldStyling,c as defaultLightTheme,e as ecommerce2026Theme,f as generateCSSVariables,b as generateTailwindConfig}from'./chunk-UHFDH3PG.js';export{q as ALL_FIELD_TYPES,n as COMPLEX_FIELD_TYPES,p as LAYOUT_FIELD_TYPES,m as PRIMITIVE_FIELD_TYPES,o as RELATIONAL_FIELD_TYPES,d as isArrayField,f as isBlocksField,e as isGroupField,h as isImageField,k as isLayoutField,b as isNumberField,c as isRelationshipField,i as isRichTextField,j as isSelectField,a as isTextField,g as isUploadField,t as normalizeRichTextValue,u as renderRichText,s as richTextStyles}from'./chunk-INB4LNA6.js';import'./chunk-5SEHX7ON.js';export{a as createContext,g as createCountProcedure,d as createCreateProcedure,f as createDeleteProcedure,h as createDynamicRouter,c as createFindByIDProcedure,b as createFindProcedure,i as createKyroServer,e as createUpdateProcedure}from'./chunk-ISCIUG37.js';export{c as buildGraphQLSchema,d as createGraphQLSchema}from'./chunk-PP7W5UKL.js';import {l,n,m,p as p$1,q}from'./chunk-XSGRGUHP.js';export{n as AuditLogger,p as InMemoryAuditLogger,m as InMemoryRateLimiter,r as MediaService,o as createAuditContext,s as createHonoApp,e as createLocalStorage,t as createRESTAPI,i as getAppSecret,j as getEncryptionKey,k as getSessionConfig,h as loadSecrets,d as resolveProvider,g as setDbAdapter}from'./chunk-XSGRGUHP.js';import {b as b$1,c}from'./chunk-7WOX27LK.js';export{a as ConfigService,b as EmailTransport,c as PasswordPolicy}from'./chunk-7WOX27LK.js';import'./chunk-K6WUOU6P.js';import'./chunk-AE6GXUT7.js';import {a as a$1}from'./chunk-2W4FK6CJ.js';export{a as SQLiteAuthAdapter}from'./chunk-2W4FK6CJ.js';import'./chunk-NRLIGDYF.js';export{e as ALL_WEBHOOK_EVENTS,f as WEBHOOK_COLLECTION,g as WEBHOOK_DELIVERY_COLLECTION,d as WEBHOOK_EVENTS,n as WebhookService,l as buildDeliveryRecord,m as createTestPayload,o as createWebhookService,j as deliverWebhook,k as deliverWithRetry,i as generateWebhookSecret,h as signPayload}from'./chunk-I67R6MR5.js';export{a as evaluateAccess,c as getWhereClause,b as mergeWhereClauses}from'./chunk-HLSB2MCK.js';export{b as KyroPubSub,c as KyroWSServer,a as PubSub,d as createWSServer}from'./chunk-GKYEJ2UF.js';import'./chunk-PP5S2UBV.js';export{c as DrizzleAdapter,b as collectionToDrizzleSchema,f as createDatabase,d as createDrizzleAdapter,a as fieldToDrizzleType,g as runMigrations,h as seedDefaultRoles}from'./chunk-3YGGZ2VN.js';import {a as a$2}from'./chunk-RHCWCG3O.js';export{a as PostgresAuthAdapter}from'./chunk-RHCWCG3O.js';import'./chunk-OG7CNQGU.js';import'./chunk-QRXDCV6K.js';export{a as MongoDBAdapter,b as createMongoDBAdapter}from'./chunk-YPDRUVWG.js';import {a}from'./chunk-P7CESLDJ.js';export{a as MongoDBAuthAdapter}from'./chunk-P7CESLDJ.js';export{a as AbstractBaseAdapter}from'./chunk-TQNM4C7H.js';import'./chunk-KDNYHLD2.js';import'./chunk-5J6HXUF6.js';import q$1,{randomBytes}from'crypto';import {readFileSync}from'fs';import Me,{join,resolve}from'path';export{z}from'zod';import {createStorage}from'unstorage';import $r from'unstorage/drivers/indexedb';import zr from'unstorage/drivers/fs';async function Ie(s,e){let t=e.data;for(let r of s){let o=await r({...e,data:t});o!==void 0&&(t=o);}return t}async function br(s,e){return Ie(s,e)}var b=class{name;version;description;hooks={};collections=[];globals=[];fields=[];extensions={collections:[],globals:[]};adminComponents={};adminStyles=[];serverMiddleware;clientMiddleware;constructor(e){this.name=e;}async init(e){}async beforeInit(e){}async afterInit(e){}getCollections(){return this.collections}getGlobals(){return this.globals}getHooks(){return this.hooks}},$=class{plugins=new Map;hooks=new Map;register(e){if(this.plugins.has(e.name))throw new Error(`Plugin "${e.name}" is already registered`);this.plugins.set(e.name,e);let t=e.getHooks?.()||{};for(let[r,o]of Object.entries(t))if(Array.isArray(o))for(let i of o)this.registerHook(r,i);}unregister(e){let t=this.plugins.get(e);if(!t)return;let r=t.getHooks?.()||{};for(let[o,i]of Object.entries(r))if(Array.isArray(i))for(let n of i)this.unregisterHook(o,n);this.plugins.delete(e);}get(e){return this.plugins.get(e)}getAll(){return Array.from(this.plugins.values())}has(e){return this.plugins.has(e)}registerHook(e,t){this.hooks.has(e)||this.hooks.set(e,[]),this.hooks.get(e).push(t);}unregisterHook(e,t){let r=this.hooks.get(e);if(r){let o=r.indexOf(t);o>-1&&r.splice(o,1);}}async executeHook(e,t){let r=this.hooks.get(e)||[],o=t;for(let i of r)try{let n=await i({...t,data:o});n!==void 0&&(o=n);}catch(n){console.error(`[PluginManager] Error in hook "${e}":`,n);}return o}getAllCollections(){let e=[];for(let t of this.plugins.values()){let r=t.getCollections?.()||[];e.push(...r);}return e}getAllGlobals(){let e=[];for(let t of this.plugins.values()){let r=t.getGlobals?.()||[];e.push(...r);}return e}getAllFields(){let e=[];for(let t of this.plugins.values())e.push(...t.fields);return e}getAdminComponents(){let e={};for(let t of this.plugins.values())Object.assign(e,t.adminComponents);return e}getAdminStyles(){let e=[];for(let t of this.plugins.values())e.push(...t.adminStyles);return e}},L=class extends b{constructor(){super("seo"),this.description="Advanced SEO features including sitemaps, robots.txt, and structured data",this.collections.push({slug:"seo-settings",label:"SEO Settings",fields:[{name:"sitemap",type:"checkbox",label:"Enable Sitemap",defaultValue:true},{name:"robotsTxt",type:"richtext",label:"robots.txt Content"},{name:"canonicalUrl",type:"text",variant:"url",label:"Canonical URL"},{name:"ogImage",type:"text",label:"Default OG Image URL"}]});}},E=class extends b{constructor(){super("analytics"),this.description="Analytics integration for tracking page views and events",this.collections.push({slug:"analytics-events",label:"Analytics Events",fields:[{name:"name",type:"text",required:true},{name:"properties",type:"json",label:"Event Properties"},{name:"timestamp",type:"date",required:true},{name:"userId",type:"text",label:"User ID"},{name:"sessionId",type:"text",label:"Session ID"}]}),this.adminComponents.AnalyticsDashboard={};}},U=class extends b{constructor(){super("comments"),this.description="Commenting system for products and posts",this.collections.push({slug:"comments",label:"Comments",fields:[{name:"content",type:"richtext",required:true},{name:"author",type:"text",required:true},{name:"email",type:"email"},{name:"approved",type:"checkbox",defaultValue:false},{name:"parent",type:"text",label:"Parent Comment ID"},{name:"resourceType",type:"text",required:true},{name:"resourceId",type:"text",required:true}]}),this.adminComponents.CommentModeration={};}},V=class extends b{constructor(){super("reviews"),this.description="Product reviews and ratings",this.collections.push({slug:"reviews",label:"Reviews",fields:[{name:"rating",type:"number",required:true,min:1,max:5},{name:"title",type:"text"},{name:"content",type:"richtext",required:true},{name:"author",type:"relationship",relationTo:"customers"},{name:"product",type:"relationship",relationTo:"products",required:true},{name:"approved",type:"checkbox",defaultValue:false},{name:"verified",type:"checkbox",label:"Verified Purchase"},{name:"helpful",type:"number",label:"Helpful Count",defaultValue:0}]}),this.adminComponents.ReviewModeration={};}},O=class extends b{constructor(){super("wishlist"),this.description="Customer wishlists",this.collections.push({slug:"wishlists",label:"Wishlists",fields:[{name:"customer",type:"relationship",relationTo:"customers",required:true},{name:"name",type:"text",label:"Wishlist Name",defaultValue:"My Wishlist"},{name:"items",type:"blocks",label:"Items",blocks:[{slug:"wishlist-item",label:"Item",fields:[{name:"product",type:"relationship",relationTo:"products"},{name:"quantity",type:"number",defaultValue:1},{name:"addedAt",type:"date"},{name:"priority",type:"select",options:[{label:"Low",value:"low"},{label:"Medium",value:"medium"},{label:"High",value:"high"}]}]}]}]});}},Ar={SEO:L,Analytics:E,Comments:U,Reviews:V,Wishlist:O};var wr={maxAttempts:5,lockDuration:9e5,notifyUser:true,notifyAdmin:true,adminNotifyAfter:3},x=class{redis;prefix;config;constructor(e,t={},r="kyro:lockout:"){this.redis=e,this.prefix=r,this.config={...wr,...t};}lockKey(e){return `${this.prefix}${e}`}historyKey(e){return `${this.prefix}${e}:history`}async checkLockout(e){let t=this.lockKey(e),r=await this.redis.hgetall(t);if(!r||Object.keys(r).length===0)return {locked:false,attemptsRemaining:this.config.maxAttempts,totalAttempts:0};let o=parseInt(r.attempts,10),i=r.lockedUntil?new Date(parseInt(r.lockedUntil,10)):void 0;return i&&i>new Date?{locked:true,attemptsRemaining:0,lockedUntil:i,totalAttempts:o}:i&&i<=new Date?(await this.unlockAccount(e),{locked:false,attemptsRemaining:this.config.maxAttempts,totalAttempts:0}):{locked:false,attemptsRemaining:Math.max(0,this.config.maxAttempts-o),totalAttempts:o}}async recordFailedAttempt(e){let t=this.lockKey(e),r=this.historyKey(e),o=Date.now(),i=await this.redis.hincrby(t,"attempts",1);if(await this.redis.hset(t,"lastAttempt",o.toString()),await this.redis.lpush(r,o.toString()),await this.redis.ltrim(r,0,99),i>=this.config.maxAttempts){let n=new Date(o+this.config.lockDuration);return await this.redis.hset(t,{lockedAt:o.toString(),lockedUntil:n.getTime().toString()}),await this.redis.expire(t,Math.ceil(this.config.lockDuration/1e3)+3600),{locked:true,attemptsRemaining:0,lockedUntil:n,totalAttempts:i}}return {locked:false,attemptsRemaining:Math.max(0,this.config.maxAttempts-i),totalAttempts:i}}async lockAccount(e,t){let r=this.lockKey(e),o=Date.now(),i=t||this.config.lockDuration,n=new Date(o+i),a=this.redis.pipeline();a.hset(r,{attempts:this.config.maxAttempts.toString(),lockedAt:o.toString(),lockedUntil:n.getTime().toString()}),a.expire(r,Math.ceil(i/1e3)+3600),await a.exec();}async unlockAccount(e){let t=this.lockKey(e);await this.redis.del(t);}async resetAttempts(e){let t=this.lockKey(e);(await this.redis.hgetall(t)).lockedAt?await this.redis.hset(t,{attempts:"0",lockedAt:"",lockedUntil:""}):await this.redis.del(t);}async getLockoutHistory(e,t=10){let r=this.historyKey(e);return (await this.redis.lrange(r,0,t-1)).map(i=>new Date(parseInt(i,10)))}async getLockoutStats(e){let t=this.historyKey(e),r=await this.redis.lrange(t,0,-1),o=r.filter((n,a)=>(a+1)%this.config.maxAttempts===0).length,i=await this.redis.hget(this.lockKey(e),"lockedAt");return {totalFailedAttempts:r.length,lockoutCount:o,lastLockout:i?new Date(parseInt(i,10)):null,averageAttemptsBeforeLockout:o>0?this.config.maxAttempts:0}}shouldNotifyAdmin(e){return this.config.notifyAdmin&&e>=this.config.adminNotifyAfter}getConfig(){return {...this.config}}setConfig(e){this.config={...this.config,...e};}};var kr={"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}},S=class{redis;prefix;limits;userLimits;constructor(e,t,r,o="kyro:ratelimit:"){this.redis=e,this.prefix=o,this.limits={...kr,...t},this.userLimits=r||{"user:api":{window:6e4,max:500},"user:write":{window:36e5,max:100}};}getKey(e,t){return `${this.prefix}${e}:${t}`}async check(e,t){let r=this.limits[e]||this.limits["api:general"],o=this.getKey(e,t),i=Date.now(),n=i-r.window,a=this.redis.pipeline();a.zremrangebyscore(o,0,n),a.zcard(o),a.zadd(o,i,`${i}:${Math.random()}`),a.expire(o,Math.ceil(r.window/1e3)+1);let c=(await a.exec())?.[1]?.[1]||0;if(c>=r.max){let g=await this.redis.zrange(o,0,0,"WITHSCORES"),d=g.length>1?parseInt(g[1],10)+r.window:i+r.window;return {allowed:false,remaining:0,resetAt:d,retryAfter:Math.ceil((d-i)/1e3)}}return {allowed:true,remaining:r.max-c-1,resetAt:i+r.window}}async checkUser(e,t,r){let o=this.userLimits[e]||this.userLimits["user:api"],i=this.getKey(`user:${e}:${t}`,r),n=Date.now(),a=n-o.window,l=this.redis.pipeline();l.zremrangebyscore(i,0,a),l.zcard(i),l.zadd(i,n,`${n}:${Math.random()}`),l.expire(i,Math.ceil(o.window/1e3)+1);let g=(await l.exec())?.[1]?.[1]||0;if(g>=o.max){let d=await this.redis.zrange(i,0,0,"WITHSCORES"),u=d.length>1?parseInt(d[1],10)+o.window:n+o.window;return {allowed:false,remaining:0,resetAt:u,retryAfter:Math.ceil((u-n)/1e3)}}return {allowed:true,remaining:o.max-g-1,resetAt:n+o.window}}async reset(e,t){let r=this.getKey(e,t);await this.redis.del(r);}async resetUser(e,t,r){let o=this.getKey(`user:${e}:${t}`,r);await this.redis.del(o);}async getStatus(e,t){let r=this.limits[e]||this.limits["api:general"],o=this.getKey(e,t),i=Date.now(),n=i-r.window;await this.redis.zremrangebyscore(o,0,n);let a=await this.redis.zcard(o);return {count:a,limit:r.max,remaining:Math.max(0,r.max-a),resetAt:i+r.window}}setLimit(e,t){this.limits[e]=t;}setUserLimit(e,t){this.userLimits[e]=t;}};var P=class{users=new Map;sessions=new Map;refreshTokens=new Map;emailToUserId=new Map;passwordHistory=new Map;emailVerificationTokens=new Map;passwordResetTokens=new Map;auditLogs=[];externalDb=false;constructor(){}async connect(){}async disconnect(){this.users.clear(),this.sessions.clear(),this.refreshTokens.clear(),this.emailToUserId.clear(),this.passwordHistory.clear();}async createUser(e){let t=randomBytes(16).toString("hex"),r=new Date().toISOString(),o=await this.hashPassword(e.password),i={id:t,email:e.email.toLowerCase(),passwordHash:o,role:e.role||"customer",tenantId:e.tenantId,createdAt:r,updatedAt:r};return this.users.set(t,i),this.emailToUserId.set(e.email.toLowerCase(),t),this.passwordHistory.set(t,[]),i}async findUserByEmail(e){let t=this.emailToUserId.get(e.toLowerCase());return t?this.findUserById(t):null}async findUserById(e){return this.users.get(e)||null}async updateUser(e,t){let r=await this.findUserById(e);if(!r)return null;let o={...r,...t,id:e,updatedAt:new Date().toISOString()};return t.email&&t.email!==r.email&&(this.emailToUserId.delete(r.email.toLowerCase()),this.emailToUserId.set(t.email.toLowerCase(),e)),this.users.set(e,o),o}async deleteUser(e){let t=await this.findUserById(e);return t?(this.users.delete(e),this.emailToUserId.delete(t.email.toLowerCase()),this.refreshTokens.forEach((r,o)=>{this.sessions.get(r)?.userId===e&&(this.refreshTokens.delete(o),this.sessions.delete(r));}),this.passwordHistory.delete(e),this.sessions.forEach((r,o)=>{r.userId===e&&this.sessions.delete(o);}),true):false}async hashPassword(e){return (await import('bcryptjs')).default.hash(e,12)}async verifyPassword(e,t){let r=await this.findUserByEmail(e);return !r||!r.passwordHash?null:await(await import('bcryptjs')).default.compare(t,r.passwordHash)?r:null}async createSession(e,t={}){let r=randomBytes(32).toString("hex"),o=randomBytes(32).toString("base64url"),i=randomBytes(32).toString("base64url"),n=new Date,a={id:r,userId:e,token:o,refreshToken:i,expiresAt:new Date(n.getTime()+86400*1e3).toISOString(),createdAt:n.toISOString(),ipAddress:t.ipAddress,userAgent:t.userAgent};return this.sessions.set(r,a),this.refreshTokens.set(i,r),a}async findSessionByToken(e){return this.sessions.get(e)||null}async findSessionByRefreshToken(e){let t=this.refreshTokens.get(e);return t&&this.sessions.get(t)||null}async deleteSession(e){let t=this.sessions.get(e);return t?(t.refreshToken&&this.refreshTokens.delete(t.refreshToken),this.sessions.delete(e),true):false}async deleteUserSessions(e){let t=0;return this.sessions.forEach((r,o)=>{r.userId===e&&(r.refreshToken&&this.refreshTokens.delete(r.refreshToken),this.sessions.delete(o),t++);}),t}async addPasswordToHistory(e,t){let r=this.passwordHistory.get(e)||[];r.push(t),r.length>5&&r.splice(0,r.length-5),this.passwordHistory.set(e,r);}async getPasswordHistory(e,t=5){return this.passwordHistory.get(e)||[]}async isPasswordInHistory(e,t,r=5){let o=await this.getPasswordHistory(t,r),i=(await import('bcryptjs')).default;for(let n of o)if(await i.compare(e,n))return true;return false}async createEmailVerificationToken(e){let t=randomBytes(32).toString("hex"),r=new Date(Date.now()+1440*60*1e3);return this.emailVerificationTokens.set(t,{userId:e,expiresAt:r}),{token:t,expiresAt:r}}async verifyEmailToken(e){let t=this.emailVerificationTokens.get(e);return !t||t.expiresAt<new Date?(this.emailVerificationTokens.delete(e),{success:false,error:"Invalid or expired token"}):(this.emailVerificationTokens.delete(e),{success:true,userId:t.userId})}async createPasswordResetToken(e){let t=await this.findUserByEmail(e);if(!t)return {token:"",expiresAt:new Date,error:"User not found"};let r=randomBytes(32).toString("hex"),o=new Date(Date.now()+3600*1e3);return this.passwordResetTokens.set(r,{userId:t.id,expiresAt:o}),{token:r,expiresAt:o}}async resetPasswordWithToken(e,t){let r=this.passwordResetTokens.get(e);if(!r||r.expiresAt<new Date)return this.passwordResetTokens.delete(e),{success:false,error:"Invalid or expired token"};let o=await this.hashPassword(t);return await this.updateUser(r.userId,{passwordHash:o}),this.passwordResetTokens.delete(e),{success:true}}async hasAnyUsers(){return this.users.size>0}async findAuditLogs(e){let{limit:t=50,offset:r=0}=e,o=this.auditLogs.slice().reverse();return e.userId&&(o=o.filter(i=>i.userId===e.userId)),e.action&&(Array.isArray(e.action)?o=o.filter(i=>e.action.includes(String(i.action))):o=o.filter(i=>i.action===e.action)),e.resource&&(o=o.filter(i=>i.resource===e.resource)),e.success!==void 0&&(o=o.filter(i=>i.success===e.success)),{logs:o.slice(r,r+t),total:o.length}}async createAuditLog(e){let t=randomBytes(16).toString("hex"),o={...e,id:t,timestamp:new Date};return this.auditLogs.push(o),o}};var C=class{storage=new Map;history=new Map;config;constructor(e={}){this.config={maxAttempts:5,lockDuration:9e5,notifyUser:true,notifyAdmin:true,adminNotifyAfter:3,...e};}async checkLockout(e){let t=Date.now(),r=this.storage.get(e);if(r&&r.lockedUntil!==null&&r.lockedUntil<=t)return await this.resetAttempts(e),{locked:false,attemptsRemaining:this.config.maxAttempts,totalAttempts:0};if(!r)return {locked:false,attemptsRemaining:this.config.maxAttempts,totalAttempts:0};let{attempts:o,lockedUntil:i}=r;return i!==null&&i>t?{locked:true,attemptsRemaining:0,lockedUntil:new Date(i),totalAttempts:o}:{locked:false,attemptsRemaining:Math.max(0,this.config.maxAttempts-o),totalAttempts:o}}async recordFailedAttempt(e){let t=Date.now(),r=this.storage.get(e)||{attempts:0,lastAttempt:null,lockedAt:null,lockedUntil:null};r.attempts+=1,r.lastAttempt=t;let o=this.history.get(e)||[];if(o.push(t),o.length>100&&o.splice(0,o.length-100),this.history.set(e,o),this.storage.set(e,r),r.attempts>=this.config.maxAttempts){let i=new Date(t+this.config.lockDuration);return r.lockedAt=t,r.lockedUntil=i.getTime(),this.storage.set(e,r),{locked:true,attemptsRemaining:0,lockedUntil:i,totalAttempts:r.attempts}}return {locked:false,attemptsRemaining:Math.max(0,this.config.maxAttempts-r.attempts),totalAttempts:r.attempts}}async lockAccount(e,t){let r=Date.now(),o=t||this.config.lockDuration,i=new Date(r+o),n=this.storage.get(e)||{attempts:0,lastAttempt:null,lockedAt:null,lockedUntil:null};n.attempts=this.config.maxAttempts,n.lockedAt=r,n.lockedUntil=i.getTime(),this.storage.set(e,n);}async unlockAccount(e){await this.resetAttempts(e);}async resetAttempts(e){let t=this.storage.get(e);t&&(t.attempts=0,t.lockedAt=null,t.lockedUntil=null,this.storage.set(e,t)),this.history.delete(e);}async getLockoutHistory(e,t=10){return (this.history.get(e)||[]).slice(-t).reverse().map(o=>new Date(o))}async getLockoutStats(e){let r=(this.history.get(e)||[]).length,o=Math.floor(r/this.config.maxAttempts),i=null,n=this.storage.get(e);n&&n.lockedAt!==null&&(i=new Date(n.lockedAt));let a=o>0?this.config.maxAttempts:0;return {totalFailedAttempts:r,lockoutCount:o,lastLockout:i,averageAttemptsBeforeLockout:a}}shouldNotifyAdmin(e){return this.config.notifyAdmin&&e>=this.config.adminNotifyAfter}getConfig(){return {...this.config}}setConfig(e){this.config={...this.config,...e};}};function h(s,e=""){return process.env[s]||e}function A(s,e=false){let t=process.env[s];return t?t.toLowerCase()==="true":e}function p(s,e=0){let t=process.env[s];return t?parseInt(t,10):e}function Le(){let s=process.env.KYRO_AUTH_DATABASE?.toLowerCase();if(s&&["sqlite","postgres","mongodb","memory"].includes(s))return s;try{let e=join(process.cwd(),"kyro.config.ts"),t=readFileSync(e,"utf8");if(t.includes("createLocalAdapter"))return "sqlite";if(t.includes("createDrizzleAdapter"))return t.includes("postgres")||t.includes("postgresql"),"postgres";if(t.includes("createMongoDBAdapter"))return "mongodb"}catch{}return "memory"}async function Pr(s){let e=process.cwd(),t=e.endsWith("admin")?join(e,".."):e,r=resolve(t,"data","auth.db");switch(s){case "sqlite":return new a$1({path:h("KYRO_AUTH_DB_PATH",r)});case "postgres":{try{let o=h("DATABASE_URL","");if(o){let{drizzle:i}=await import('drizzle-orm/postgres-js'),a=(await import('postgres')).default(o,{onnotice:()=>{}}),l=i(a);return new a$2({db:l})}}catch{console.warn("[Auth] Could not create PostgresAuthAdapter, falling back to SQLite auth adapter.");}return new a$1({path:h("KYRO_AUTH_DB_PATH",r)})}case "mongodb":{try{let o=h("MONGODB_URI","");if(o){let{MongoClient:i}=await import('mongodb'),n=new i(o);await n.connect();let l=new URL(o).pathname.replace(/^\//,"")||"kyro_cms",c=n.db(l);return new a({db:c})}}catch{console.warn("[Auth] Could not create MongoDBAuthAdapter, falling back to SQLite auth adapter.");}return new a$1({path:h("KYRO_AUTH_DB_PATH",r)})}default:return new P}}async function W(s,e){let t=A("KYRO_DISTRIBUTED",false),r;if(t){let{RedisAuthAdapter:d}=await import('./redis-adapter-VAXP43GR.js'),u=h("REDIS_URL","redis://localhost:6379"),y=A("REDIS_TLS",false),f=new d({url:u,tls:y});await f.connect?.(),r=f;}else {let d=s||Le();r=await Pr(d),r.connect&&await r.connect();}let o=e?await b$1.fromConfig(e).catch(()=>null)||b$1.fromEnv()||void 0:b$1.fromEnv()||void 0,i=new c({minLength:p("PASSWORD_MIN_LENGTH",12),requireUppercase:A("PASSWORD_REQUIRE_UPPERCASE",true),requireLowercase:A("PASSWORD_REQUIRE_LOWERCASE",true),requireNumbers:A("PASSWORD_REQUIRE_NUMBERS",true),requireSpecialChars:A("PASSWORD_REQUIRE_SPECIAL",true),preventReuse:p("PASSWORD_PREVENT_REUSE",5),maxLength:p("PASSWORD_MAX_LENGTH",128)}),n$1,a,l;if(t){let u=r.redis;n$1=new x(u,{maxAttempts:p("LOCKOUT_MAX_ATTEMPTS",5),lockDuration:p("LOCKOUT_DURATION_MINUTES",15)*60*1e3}),a=new S(u,{"auth:login":{window:p("RATE_LIMIT_AUTH_WINDOW_MS",9e5),max:p("RATE_LIMIT_AUTH_MAX_REQUESTS",10)},"api:general":{window:p("RATE_LIMIT_WINDOW_MS",6e4),max:p("RATE_LIMIT_MAX_REQUESTS",100)}}),l=new n(u,p("AUDIT_LOG_RETENTION_DAYS",30));}else n$1=new C({maxAttempts:p("LOCKOUT_MAX_ATTEMPTS",5),lockDuration:p("LOCKOUT_DURATION_MINUTES",15)*60*1e3}),a=new m({"auth:login":{window:p("RATE_LIMIT_AUTH_WINDOW_MS",9e5),max:p("RATE_LIMIT_AUTH_MAX_REQUESTS",10)},"api:general":{window:p("RATE_LIMIT_WINDOW_MS",6e4),max:p("RATE_LIMIT_MAX_REQUESTS",100)}}),l=A("AUDIT_LOG_ENABLED",true)?new p$1(p("AUDIT_LOG_RETENTION_DAYS",30)):void 0;let c$1=new q({redis:r,email:o,jwtSecret:h("APP_SECRET","change-me"),jwtExpiresIn:h("JWT_EXPIRES_IN","24h"),jwtIssuer:h("JWT_ISSUER","kyro-cms"),jwtAudience:h("JWT_AUDIENCE","kyro-cms-client"),passwordPolicy:i,lockout:n$1,rateLimiter:a,auditLogger:l,baseUrl:h("EMAIL_BASE_URL","http://localhost:4321"),emailVerificationRequired:A("EMAIL_VERIFICATION_REQUIRED",true)}),g=t?"distributed":s||Le();return {authAdapter:r,databaseType:g,email:o,passwordPolicy:i,lockout:n$1,rateLimiter:a,auditLogger:l,routes:c$1}}var Ue=W().catch(s=>(console.warn("[AuthConfig] Failed to initialize auth config:",s.message),null));var Cr=12,Tr="24h",vr="7d",H=class{adapter;config;constructor(e,t){this.adapter=e,this.config={secret:t.secret,expiresIn:t.expiresIn??Tr,refreshExpiresIn:t.refreshExpiresIn??vr,issuer:t.issuer??"kyro-cms",audience:t.audience??[],saltRounds:t.saltRounds??Cr};}async register(e){try{if(await this.adapter.findUserByEmail(e.email))return {success:!1,error:"Email already registered"};let r=await this.adapter.createUser({email:e.email,password:e.password,role:e.role??"customer",tenantId:e.tenantId});return this.createSessionForUser(r)}catch(t){return {success:false,error:String(t)}}}async login(e){try{let t=await this.adapter.verifyPassword(e.email,e.password);return t?this.createSessionForUser(t):{success:!1,error:"Invalid credentials"}}catch(t){return {success:false,error:String(t)}}}async logout(e){await this.adapter.deleteSession(e);}async refreshToken(e){try{let t=await this.adapter.findSessionByToken(e);if(!t||new Date(t.expiresAt)<new Date)return {success:!1,error:"Invalid or expired refresh token"};let r=await this.adapter.findUserById(t.userId);return r?(await this.adapter.deleteSession(e),this.createSessionForUser(r)):{success:!1,error:"User not found"}}catch(t){return {success:false,error:String(t)}}}async verifyToken(e){try{let{default:t}=await import('jsonwebtoken');return t.verify(e,this.config.secret,{issuer:this.config.issuer,audience:this.config.audience.length>0?this.config.audience[0]:void 0})}catch{return null}}async getUserFromToken(e){let t=await this.verifyToken(e);return t?this.adapter.findUserById(t.sub):null}async changePassword(e,t,r){try{let o=await this.adapter.findUserById(e);return o?await this.adapter.verifyPassword(o.email,t)?(await this.adapter.updateUser(e,{password:r}),await this.adapter.deleteUserSessions(e),{success:!0,user:o}):{success:!1,error:"Current password is incorrect"}:{success:!1,error:"User not found"}}catch(o){return {success:false,error:String(o)}}}async resetPassword(e,t){try{let r=await this.adapter.findUserByEmail(e);return r?(await this.adapter.updateUser(r.id,{password:t}),await this.adapter.deleteUserSessions(r.id),{success:!0,user:r}):{success:!1,error:"User not found"}}catch(r){return {success:false,error:String(r)}}}async sendEmailVerification(e){try{let{token:t,expiresAt:r}=await this.adapter.createEmailVerificationToken(e);return {success:!0}}catch(t){return {success:false,error:String(t)}}}async verifyEmail(e){try{return await this.adapter.verifyEmailToken(e)}catch(t){return {success:false,error:String(t)}}}async requestPasswordReset(e){try{let t=await this.adapter.createPasswordResetToken(e);return t.error?{success:!1,error:t.error}:{success:!0}}catch(t){return {success:false,error:String(t)}}}async resetPasswordWithToken(e,t){try{return await this.adapter.resetPasswordWithToken(e,t)}catch(r){return {success:false,error:String(r)}}}async deleteAccount(e){try{return await this.adapter.findUserById(e)?(await this.adapter.deleteUserSessions(e),await this.adapter.deleteUser(e),{success:!0}):{success:!1,error:"User not found"}}catch(t){return {success:false,error:String(t)}}}async createSessionForUser(e){let t=await this.generateToken(e),r=await this.adapter.createSession(e.id);return {success:true,user:e,session:r,token:t}}async generateToken(e){let{default:t}=await import('jsonwebtoken'),r={sub:e.id,email:e.email,role:e.role,tenantId:e.tenantId},o={expiresIn:this.parseExpiresIn(this.config.expiresIn)/1e3,issuer:this.config.issuer};return this.config.audience.length>0&&(o.audience=this.config.audience[0]),t.sign(r,this.config.secret,o)}async hashPassword(e){let{default:t}=await import('bcryptjs');return t.hash(e,this.config.saltRounds)}parseExpiresIn(e){if(typeof e=="number")return e;let t=e.match(/^(\d+)([smhd])$/);if(!t)return 864e5;let r=parseInt(t[1],10);switch(t[2]){case "s":return r*1e3;case "m":return r*6e4;case "h":return r*36e5;case "d":return r*864e5;default:return 864e5}}};function Rr(s,e){return new H(s,e)}function _(){return {enabled:true,draftsEnabled:true,publishEnabled:true,scheduleEnabled:false,versioningEnabled:true,maxVersionsPerDocument:50,autoPublish:false,requirePublishPermission:true}}var M=class{adapter;config;constructor(e,t){this.adapter=e,this.config={..._(),...t};}async createVersion(e){let r=((await this.adapter.getLatestVersion(e.collection,e.documentId))?.version??0)+1,o={...e,version:r},i=await this.adapter.createVersion(o);return this.config.maxVersionsPerDocument>0&&await this.pruneOldVersions(e.collection,e.documentId),i}async publishVersion(e){let t=await this.adapter.getVersion(e.collection,e.versionId);if(!t)throw new Error("Version not found");if(t.status==="published")throw new Error("Version is already published");await this.adapter.publishVersion(e);}async unpublishDocument(e,t){let r=await this.adapter.getVersions({collection:e,documentId:t,limit:1e3});for(let o of r)if(o.status==="published"){await this.createVersion({collection:e,documentId:t,data:o.data,status:"draft",createdBy:"system",changeDescription:"Unpublished document"});break}}async revertToVersion(e,t,r,o){if(!await this.adapter.getVersion(e,r))throw new Error("Version not found");return await this.adapter.revertToVersion({collection:e,documentId:t,versionId:r,userId:o})}async getVersionHistory(e,t,r=20,o=0){return this.adapter.getVersions({collection:e,documentId:t,limit:r,offset:o})}async compareTwoVersions(e,t,r,o){return this.adapter.compareVersions({collection:e,documentId:t,versionA:r,versionB:o})}async getLatestDraft(e,t){return this.adapter.getLatestVersion(e,t)}async getPublishedVersion(e,t){return this.adapter.getPublishedVersion(e,t)}async getVersion(e,t){return this.adapter.getVersion(e,t)}async schedulePublish(e,t,r,o){if(!this.config.scheduleEnabled)throw new Error("Scheduled publishing is not enabled");if(!await this.adapter.getVersion(e,r))throw new Error("Version not found")}async deleteVersionHistory(e,t){await this.adapter.deleteVersions(e,t);}async pruneOldVersions(e,t){let r=await this.adapter.getVersions({collection:e,documentId:t,limit:this.config.maxVersionsPerDocument+100});if(r.length<=this.config.maxVersionsPerDocument)return;r.slice(0,this.config.maxVersionsPerDocument);let i=r.slice(this.config.maxVersionsPerDocument);for(let n of i)if(n.status!=="published"){await this.adapter.deleteVersions(e,t);break}}};function Dr(s,e){return new M(s,e)}function Ir(s){return s==="published"}function Lr(s){return s==="draft"}function Er(s){return s==="archived"}function Ur(s){return s?Array.isArray(s)?s:Object.values(s):[]}function Vr(s){return s?Array.isArray(s)?s:Object.values(s):[]}function Ve(s){return {collections:Ur(s.collections),globals:Vr(s.globals),adapter:s.adapter,plugins:s.plugins,auth:s.auth,cors:s.cors,admin:s.admin,upload:s.upload,graphQL:s.graphQL,typescript:s.typescript,localization:s.localization,rateLimit:s.rateLimit,debug:s.debug}}var Or=Ve;function Hr(s){let{siteSettings:e,seoSettings:t,title:r,description:o,image:i,url:n}=s;if(!e)return "";let a=e.siteName||"",l=r||t?.defaultTitle||a,c=t?.titleTemplate,g=t?.separator||" | ",d=t?.siteNameInTitle!==false,u=c?c.replace(/\{\{title\}\}/g,l).replace(/\{\{siteName\}\}/g,d?a:"").replace(/\{\{separator\}\}/g,g).replace(/\s+/g," ").trim():l,y=o||t?.defaultDescription||e.siteDescription||"",f=i||e.siteOgImage?.url||"",F=n||e.siteUrl||"",m=`
|
|
2
2
|
<title>${u}</title>
|
|
3
3
|
<meta name="description" content="${y}">
|
|
4
4
|
`;e.siteFavicon?.url&&(m+=`
|
package/dist/mongodb/index.d.cts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { A as AbstractBaseAdapter } from '../base-
|
|
2
|
-
import { F as FindArgs, b as FindResult, c as FindByIDArgs, d as CreateArgs, e as UpdateArgs, D as DeleteArgs, f as FindVersionsArgs, g as VersionRecord, h as CreateVersionArgs } from '../types-
|
|
1
|
+
import { A as AbstractBaseAdapter } from '../base-CXZxchcr.cjs';
|
|
2
|
+
import { F as FindArgs, b as FindResult, c as FindByIDArgs, d as CreateArgs, e as UpdateArgs, D as DeleteArgs, f as FindVersionsArgs, g as VersionRecord, h as CreateVersionArgs } from '../types-CqqoM3Dy.cjs';
|
|
3
3
|
import { A as AuthAdapter, U as UserRole, c as AuthUser, S as Session, e as AuditLogFilter, d as AuditLog } from '../types-CpjuXbe7.cjs';
|
|
4
4
|
import '../types-fvldOd92.cjs';
|
|
5
5
|
|
package/dist/mongodb/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { A as AbstractBaseAdapter } from '../base-
|
|
2
|
-
import { F as FindArgs, b as FindResult, c as FindByIDArgs, d as CreateArgs, e as UpdateArgs, D as DeleteArgs, f as FindVersionsArgs, g as VersionRecord, h as CreateVersionArgs } from '../types-
|
|
1
|
+
import { A as AbstractBaseAdapter } from '../base-CjuIfzH2.js';
|
|
2
|
+
import { F as FindArgs, b as FindResult, c as FindByIDArgs, d as CreateArgs, e as UpdateArgs, D as DeleteArgs, f as FindVersionsArgs, g as VersionRecord, h as CreateVersionArgs } from '../types-L-qNugRL.js';
|
|
3
3
|
import { A as AuthAdapter, U as UserRole, c as AuthUser, S as Session, e as AuditLogFilter, d as AuditLog } from '../types-CpjuXbe7.js';
|
|
4
4
|
import '../types-fvldOd92.js';
|
|
5
5
|
|
package/dist/rest/index.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
'use strict';var
|
|
1
|
+
'use strict';var chunkUTFLD5DC_cjs=require('../chunk-UTFLD5DC.cjs');require('../chunk-AJAZ7D3W.cjs'),require('../chunk-WIZ6C5QZ.cjs'),require('../chunk-GFU7AOI3.cjs'),require('../chunk-ET6NN2V2.cjs'),require('../chunk-HVXO3OFB.cjs'),require('../chunk-XUONID6O.cjs'),require('../chunk-NY47CFVP.cjs'),require('../chunk-Z7CNY2UV.cjs'),require('../chunk-GYQMNXXW.cjs'),require('../chunk-MIOMMB23.cjs'),require('../chunk-UCCFT5OO.cjs'),require('../chunk-ATLSIYRH.cjs'),require('../chunk-EJDIR56C.cjs'),require('../chunk-Q3Q7BJVQ.cjs'),require('../chunk-AHSFSERC.cjs');Object.defineProperty(exports,"createHonoApp",{enumerable:true,get:function(){return chunkUTFLD5DC_cjs.s}});Object.defineProperty(exports,"createRESTAPI",{enumerable:true,get:function(){return chunkUTFLD5DC_cjs.t}});
|
package/dist/rest/index.d.cts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { Hono } from 'hono';
|
|
2
|
-
import { B as BaseAdapter, i as User } from '../types-
|
|
3
|
-
import { R as Registry } from '../index-
|
|
4
|
-
import { j as createWebhookService } from '../WebhookService-
|
|
2
|
+
import { B as BaseAdapter, i as User } from '../types-CqqoM3Dy.cjs';
|
|
3
|
+
import { R as Registry } from '../index-BCUSHYBf.cjs';
|
|
4
|
+
import { j as createWebhookService } from '../WebhookService-B15DnDeH.cjs';
|
|
5
5
|
import '../types-fvldOd92.cjs';
|
|
6
6
|
import 'zod';
|
|
7
7
|
|
package/dist/rest/index.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { Hono } from 'hono';
|
|
2
|
-
import { B as BaseAdapter, i as User } from '../types-
|
|
3
|
-
import { R as Registry } from '../index-
|
|
4
|
-
import { j as createWebhookService } from '../WebhookService-
|
|
2
|
+
import { B as BaseAdapter, i as User } from '../types-L-qNugRL.js';
|
|
3
|
+
import { R as Registry } from '../index-C7FPi-Fj.js';
|
|
4
|
+
import { j as createWebhookService } from '../WebhookService-DJ75IwdZ.js';
|
|
5
5
|
import '../types-fvldOd92.js';
|
|
6
6
|
import 'zod';
|
|
7
7
|
|
package/dist/rest/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export{s as createHonoApp,t as createRESTAPI}from'../chunk-
|
|
1
|
+
export{s as createHonoApp,t as createRESTAPI}from'../chunk-XSGRGUHP.js';import'../chunk-7WOX27LK.js';import'../chunk-K6WUOU6P.js';import'../chunk-AE6GXUT7.js';import'../chunk-2W4FK6CJ.js';import'../chunk-NRLIGDYF.js';import'../chunk-I67R6MR5.js';import'../chunk-HLSB2MCK.js';import'../chunk-3YGGZ2VN.js';import'../chunk-RHCWCG3O.js';import'../chunk-OG7CNQGU.js';import'../chunk-YPDRUVWG.js';import'../chunk-P7CESLDJ.js';import'../chunk-TQNM4C7H.js';import'../chunk-KDNYHLD2.js';import'../chunk-5J6HXUF6.js';
|
package/dist/trpc/index.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
'use strict';var
|
|
1
|
+
'use strict';var chunkWMZEULS2_cjs=require('../chunk-WMZEULS2.cjs');require('../chunk-XUONID6O.cjs'),require('../chunk-NY47CFVP.cjs'),require('../chunk-Q3Q7BJVQ.cjs'),require('../chunk-AHSFSERC.cjs');Object.defineProperty(exports,"createContext",{enumerable:true,get:function(){return chunkWMZEULS2_cjs.a}});Object.defineProperty(exports,"createCountProcedure",{enumerable:true,get:function(){return chunkWMZEULS2_cjs.g}});Object.defineProperty(exports,"createCreateProcedure",{enumerable:true,get:function(){return chunkWMZEULS2_cjs.d}});Object.defineProperty(exports,"createDeleteProcedure",{enumerable:true,get:function(){return chunkWMZEULS2_cjs.f}});Object.defineProperty(exports,"createDynamicRouter",{enumerable:true,get:function(){return chunkWMZEULS2_cjs.h}});Object.defineProperty(exports,"createFindByIDProcedure",{enumerable:true,get:function(){return chunkWMZEULS2_cjs.c}});Object.defineProperty(exports,"createFindProcedure",{enumerable:true,get:function(){return chunkWMZEULS2_cjs.b}});Object.defineProperty(exports,"createKyroServer",{enumerable:true,get:function(){return chunkWMZEULS2_cjs.i}});Object.defineProperty(exports,"createUpdateProcedure",{enumerable:true,get:function(){return chunkWMZEULS2_cjs.e}});
|
package/dist/trpc/index.d.cts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { B as BaseAdapter, R as Request, i as User, b as FindResult } from '../types-
|
|
2
|
-
import { j as createWebhookService } from '../WebhookService-
|
|
1
|
+
import { B as BaseAdapter, R as Request, i as User, b as FindResult } from '../types-CqqoM3Dy.cjs';
|
|
2
|
+
import { j as createWebhookService } from '../WebhookService-B15DnDeH.cjs';
|
|
3
3
|
import '../types-fvldOd92.cjs';
|
|
4
4
|
|
|
5
5
|
interface ApiKeyContext {
|
package/dist/trpc/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { B as BaseAdapter, R as Request, i as User, b as FindResult } from '../types-
|
|
2
|
-
import { j as createWebhookService } from '../WebhookService-
|
|
1
|
+
import { B as BaseAdapter, R as Request, i as User, b as FindResult } from '../types-L-qNugRL.js';
|
|
2
|
+
import { j as createWebhookService } from '../WebhookService-DJ75IwdZ.js';
|
|
3
3
|
import '../types-fvldOd92.js';
|
|
4
4
|
|
|
5
5
|
interface ApiKeyContext {
|
package/dist/trpc/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
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-
|
|
1
|
+
export{a as createContext,g as createCountProcedure,d as createCreateProcedure,f as createDeleteProcedure,h as createDynamicRouter,c as createFindByIDProcedure,b as createFindProcedure,i as createKyroServer,e as createUpdateProcedure}from'../chunk-ISCIUG37.js';import'../chunk-I67R6MR5.js';import'../chunk-HLSB2MCK.js';import'../chunk-KDNYHLD2.js';import'../chunk-5J6HXUF6.js';
|
|
@@ -116,7 +116,8 @@ interface AdminConfig {
|
|
|
116
116
|
icon?: string;
|
|
117
117
|
preview?: (doc: Record<string, unknown>, options: {
|
|
118
118
|
req: unknown;
|
|
119
|
-
|
|
119
|
+
token?: string;
|
|
120
|
+
}) => string | Promise<string>;
|
|
120
121
|
disableDuplicate?: boolean;
|
|
121
122
|
pagination?: {
|
|
122
123
|
defaultLimit?: number;
|
|
@@ -116,7 +116,8 @@ interface AdminConfig {
|
|
|
116
116
|
icon?: string;
|
|
117
117
|
preview?: (doc: Record<string, unknown>, options: {
|
|
118
118
|
req: unknown;
|
|
119
|
-
|
|
119
|
+
token?: string;
|
|
120
|
+
}) => string | Promise<string>;
|
|
120
121
|
disableDuplicate?: boolean;
|
|
121
122
|
pagination?: {
|
|
122
123
|
defaultLimit?: number;
|
package/package.json
CHANGED
package/dist/chunk-5KGQOTLK.cjs
DELETED
|
@@ -1,133 +0,0 @@
|
|
|
1
|
-
'use strict';var chunkEJDIR56C_cjs=require('./chunk-EJDIR56C.cjs'),drizzleOrm=require('drizzle-orm'),pgCore=require('drizzle-orm/pg-core'),sqliteCore=require('drizzle-orm/sqlite-core'),postgresJs=require('drizzle-orm/postgres-js'),re=require('postgres'),crypto=require('crypto'),promises=require('fs/promises'),path=require('path'),module$1=require('module');var _documentCurrentScript=typeof document!=='undefined'?document.currentScript:null;function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var re__default=/*#__PURE__*/_interopDefault(re);var M=false;function L(f,s="postgres"){switch(f.type){case "text":case "email":case "password":case "color":case "icon":return s==="sqlite"?"text":"varchar";case "textarea":case "code":case "markdown":case "secret":return "text";case "number":return f.integer?"integer":"decimal";case "checkbox":return "boolean";case "date":return "timestamp";case "select":case "radio":return s==="sqlite"?"text":"varchar";case "richtext":case "json":case "array":case "group":case "blocks":case "row":case "collapsible":case "tabs":return "jsonb";case "relationship":return s==="sqlite"?"text":"varchar";case "upload":return "jsonb";default:return "jsonb"}}function Le(f,s="postgres"){let n=f.slug.replace(/-/g,"_"),e=[];e.push(`export const ${n} = pgTable('${n}', {`),e.push(" id: uuid('id').primaryKey().defaultRandom(),");for(let t of f.fields){if(t.name==="id")continue;let i=L(t,s),r=t.required,a=` ${t.name}: pg.${i}('${t.name}')`;t.unique&&(a+=".unique()"),r||(a+=".nullable()"),t.defaultValue!==void 0&&(typeof t.defaultValue=="string"?a+=`.default('${t.defaultValue}')`:typeof t.defaultValue=="boolean"?a+=`.default(${t.defaultValue})`:a+=`.default(sql\`${JSON.stringify(t.defaultValue)}\`)`),a+=",",e.push(a);}return f.timestamps&&(e.push(" createdAt: pg.timestamp('created_at').defaultNow(),"),e.push(" updatedAt: pg.timestamp('updated_at').defaultNow(),")),e.push(` status: ${s==="sqlite"?"sqlite":"pg"}.varchar('status').default('draft'),`),e.push(` hasDraft: ${s==="sqlite"?"sqlite":"pg"}.boolean('hasDraft').default(false),`),e.push("});"),e.join(`
|
|
2
|
-
`)}function P(f,s){return Array.isArray(f)?f.map(n=>{if(!n||typeof n!="object")return n;let e=n.data?{...n.data}:void 0;if(!e)return n;let t=s.find(i=>i.slug===n.type||i.slug===n.slug);if(!t||!Array.isArray(t.fields))return n;for(let i of t.fields){if(i.name&&(i.type==="upload"||i.type==="image")&&e[i.name]){let r=e[i.name];Array.isArray(r)?e[i.name]=r.map(a=>typeof a=="string"?{id:a}:a):typeof r=="string"&&(e[i.name]={id:r});}if(i.type==="blocks"&&i.name&&e[i.name]){let r=i.blocks||[];e[i.name]=P(e[i.name],r);}}return {...n,data:e}}):f}var S=class extends chunkEJDIR56C_cjs.a{client;schema;dialect;connectionString;versionsTableReady=false;constructor(s){if(super(),this.schema=s.schema||{},s.connectionString){this.connectionString=s.connectionString;let n=s.connectionString.toLowerCase();n.startsWith("postgres://")||n.startsWith("postgresql://")?this.dialect="postgres":n.includes(".db")||n.includes("sqlite")||n.includes("file:")?this.dialect="sqlite":this.dialect=s.type||"postgres";}else this.client=s.client,this.dialect=s.type||"sqlite";}prepareData(s,n){let e=super.prepareData(s,n);e.createdAt&&typeof e.createdAt=="string"&&(e.createdAt=new Date(e.createdAt)),e.updatedAt&&typeof e.updatedAt=="string"&&(e.updatedAt=new Date(e.updatedAt));for(let t of n.fields)if(t.type==="date"&&t.name){let i=e[t.name];i&&typeof i=="string"&&(e[t.name]=new Date(i));}for(let t of n.fields){let r=L(t,this.dialect)==="jsonb";if(t.type==="tabs"&&"tabs"in t&&t.name){let a=s[t.name];if(a&&typeof a=="object"){let o={};for(let[c,u]of Object.entries(a)){let d=t.tabs.flatMap(m=>m.fields).find(m=>m.name===c);(d?.type==="upload"||d?.type==="image"||d?.type==="list"||d?.type==="relationship-block")&&u?o[c]=Array.isArray(u)||typeof u=="object"?JSON.stringify(u):u:o[c]=u;}e[t.name]=this.dialect==="sqlite"||!r?JSON.stringify(o):o;}}else if(r&&t.name&&s[t.name]!==void 0&&s[t.name]!==null)e[t.name]=this.dialect==="sqlite"?JSON.stringify(s[t.name]):s[t.name];else if((t.type==="upload"||t.type==="image"||t.type==="list"||t.type==="relationship-block")&&t.name){let a=s[t.name];a!=null&&(e[t.name]=this.dialect==="sqlite"||!r?typeof a=="string"?a:JSON.stringify(a):a);}}for(let t of n.fields)if(t.name&&e[t.name]===""){let i=L(t,this.dialect);(i==="timestamp"||i==="jsonb"||i==="decimal"||i==="integer"||i==="numeric"||i==="boolean")&&(e[t.name]=null);}return e}async connect(){if(this.connectionString&&!this.client){if(this.dialect==="postgres"){let{default:s}=await import('postgres'),{drizzle:n}=await import('drizzle-orm/postgres-js'),e=s(this.connectionString,{onnotice:()=>{}});this.client=n(e,{schema:this.schema});}else if(this.dialect==="sqlite"){let{default:s}=await import('better-sqlite3'),{drizzle:n}=await import('drizzle-orm/better-sqlite3'),e=new s(this.connectionString.replace("file:",""));this.client=n(e,{schema:this.schema});}}this.connected=true;}async init(s,n=[]){if(await super.init(s,n),this.connectionString&&!this.client&&await this.connect(),this.client&&!M){for(let t of s){let i=this.getTableName(t.slug);this.schema[i]||(this.schema[i]=this.createTableFromConfig(t));}await this.ensureCollectionTables(s);let e=n.map(t=>({slug:`_globals_${t.slug}`,fields:t.fields,label:t.label}));for(let t of e){let i=this.getTableName(t.slug);this.schema[i]||(this.schema[i]=this.createTableFromConfig(t,true)),this.collections.has(t.slug)||this.collections.set(t.slug,t);}await this.ensureCollectionTables(e),M=true;}}createTableFromConfig(s,n=false){let e=this.getTableName(s.slug),t={id:n?pgCore.text("id").primaryKey():pgCore.uuid("id").primaryKey().defaultRandom()};for(let i of s.fields){if(!i.name||i.name==="id")continue;let r=L(i,this.dialect),a=i.name.replace(/-/g,"_"),o=a.replace(/([A-Z])/g,"_$1").toLowerCase(),c;if(this.dialect==="sqlite")switch(r){case "varchar":case "text":c=sqliteCore.text(o);break;case "integer":c=sqliteCore.integer(o);break;case "decimal":case "numeric":c=sqliteCore.numeric(o);break;case "boolean":c=sqliteCore.integer(o,{mode:"boolean"});break;case "timestamp":c=sqliteCore.text(o);break;case "jsonb":c=sqliteCore.text(o);break;default:c=sqliteCore.text(o);}else switch(r){case "varchar":c=pgCore.varchar(o,{length:255});break;case "integer":c=pgCore.integer(o);break;case "decimal":c=pgCore.decimal(o);break;case "boolean":c=pgCore.boolean(o);break;case "timestamp":c=pgCore.timestamp(o);break;case "jsonb":c=pgCore.jsonb(o);break;default:c=pgCore.text(o);}i.required||(c=c.default(null)),t[a]=c;}return t.createdAt||(t.createdAt=this.dialect==="sqlite"?sqliteCore.text("created_at").default(new Date().toISOString()):pgCore.timestamp("created_at").defaultNow()),t.updatedAt||(t.updatedAt=this.dialect==="sqlite"?sqliteCore.text("updated_at").default(new Date().toISOString()):pgCore.timestamp("updated_at").defaultNow()),e!=="users"&&e!=="audit_logs"&&(t.status||(t.status=this.dialect==="sqlite"?sqliteCore.text("status").default("draft"):pgCore.varchar("status",{length:20}).default("draft")),t.hasDraft||(t.hasDraft=this.dialect==="sqlite"?sqliteCore.integer("hasDraft",{mode:"boolean"}).default(false):pgCore.boolean("hasDraft").default(false))),this.dialect==="sqlite"?sqliteCore.sqliteTable(e,t):pgCore.pgTable(e,t)}async ensureCollectionTables(s){let n=[];for(let e of s){let t=e.slug.startsWith("_globals_"),i=this.getTableName(e.slug),r=this.generateCreateColumns(e),a=e.fields.some(d=>d.name==="createdAt"),o=e.fields.some(d=>d.name==="updatedAt"),c=e.fields.some(d=>d.name==="status"),u=e.fields.some(d=>d.name==="hasDraft");if(this.dialect==="postgres"){let d=t?'"id" TEXT PRIMARY KEY':'"id" UUID PRIMARY KEY DEFAULT gen_random_uuid()';n.push(`
|
|
3
|
-
CREATE TABLE IF NOT EXISTS "${i}" (
|
|
4
|
-
${d},
|
|
5
|
-
${r}
|
|
6
|
-
${a?"":'"created_at" TIMESTAMP NOT NULL DEFAULT NOW(),'}
|
|
7
|
-
${o?"":'"updated_at" TIMESTAMP NOT NULL DEFAULT NOW(),'}
|
|
8
|
-
${c?"":`"status" VARCHAR(20) DEFAULT 'draft',`}
|
|
9
|
-
${u?"":'"hasDraft" BOOLEAN DEFAULT false'}
|
|
10
|
-
)
|
|
11
|
-
`);}else n.push(`
|
|
12
|
-
CREATE TABLE IF NOT EXISTS "${i}" (
|
|
13
|
-
"id" TEXT PRIMARY KEY,
|
|
14
|
-
${r}
|
|
15
|
-
${a?"":`"created_at" TEXT NOT NULL DEFAULT (datetime('now')),`}
|
|
16
|
-
${o?"":`"updated_at" TEXT NOT NULL DEFAULT (datetime('now')),`}
|
|
17
|
-
${c?"":`"status" TEXT DEFAULT 'draft',`}
|
|
18
|
-
${u?"":'"hasDraft" INTEGER DEFAULT 0'}
|
|
19
|
-
)
|
|
20
|
-
`);}if(n.length>0)if(this.dialect==="postgres")await this.client.execute(drizzleOrm.sql.raw(n.join(`;
|
|
21
|
-
`)));else for(let e of n)await this.client.execute(drizzleOrm.sql.raw(e));for(let e of s){let t=this.getTableName(e.slug);t==="users"||t==="audit_logs"||await this.syncTableColumns(e,t);}}getColumnSqlDefinition(s,n){let e=L(s,n),t=s.name.replace(/-/g,"_").replace(/([A-Z])/g,"_$1").toLowerCase(),i=this.columnSqlType(e,n);return `"${t}" ${i} DEFAULT NULL`}columnSqlType(s,n){if(n==="sqlite")switch(s){case "varchar":return "TEXT";case "text":return "TEXT";case "integer":return "INTEGER";case "decimal":case "numeric":return "NUMERIC";case "boolean":return "INTEGER";case "timestamp":return "TEXT";case "jsonb":return "TEXT";default:return "TEXT"}switch(s){case "varchar":return "VARCHAR(255)";case "text":return "TEXT";case "integer":return "INTEGER";case "decimal":case "numeric":return "DECIMAL";case "boolean":return "BOOLEAN";case "timestamp":return "TIMESTAMP";case "jsonb":return "JSONB";default:return "TEXT"}}getExpectedColumnDefs(s,n){let e={},t=s.slug.startsWith("_globals_"),i=s.fields.some(c=>c.name==="createdAt"),r=s.fields.some(c=>c.name==="updatedAt"),a=s.fields.some(c=>c.name==="status"),o=s.fields.some(c=>c.name==="hasDraft");this.dialect==="postgres"?(e.id=t?'"id" TEXT PRIMARY KEY':'"id" UUID PRIMARY KEY DEFAULT gen_random_uuid()',i||(e.created_at='"created_at" TIMESTAMP DEFAULT NULL'),r||(e.updated_at='"updated_at" TIMESTAMP DEFAULT NULL'),a||(e.status='"status" VARCHAR(20) DEFAULT NULL'),o||(e.hasDraft='"hasDraft" BOOLEAN DEFAULT NULL')):(e.id='"id" TEXT PRIMARY KEY',i||(e.created_at='"created_at" TEXT DEFAULT NULL'),r||(e.updated_at='"updated_at" TEXT DEFAULT NULL'),a||(e.status='"status" TEXT DEFAULT NULL'),o||(e.hasDraft='"hasDraft" INTEGER DEFAULT NULL'));for(let c of s.fields){if(!c.name||c.name==="id")continue;let u=this.getColumnSqlDefinition(c,this.dialect),d=c.name.replace(/-/g,"_").replace(/([A-Z])/g,"_$1").toLowerCase();e[d]=u;}return e}async syncTableColumns(s,n){let e;try{if(this.dialect==="postgres"){let r=await this.client.execute(drizzleOrm.sql`SELECT column_name, data_type, character_maximum_length FROM information_schema.columns WHERE table_name = ${n}`);e=new Map(r.map(a=>[a.column_name,{type:a.data_type,maxLen:a.character_maximum_length}]));}else {let r=await this.client.execute(drizzleOrm.sql`PRAGMA table_info("${drizzleOrm.sql.raw(n)}")`);e=new Map(r.map(a=>[a.name,{type:a.type,maxLen:null}]));}}catch{return}let t=this.getExpectedColumnDefs(s,n),i=Object.keys(t).filter(r=>!e.has(r));if(i.length>0){let r=i.map(a=>`ALTER TABLE "${n}" ADD COLUMN ${t[a]}`);await this.executeRaw(drizzleOrm.sql.raw(r.join(`;
|
|
22
|
-
`)));}if(this.dialect==="postgres")for(let r of s.fields){if(!r.name||r.name==="id")continue;let a=L(r,this.dialect),o=r.name.replace(/-/g,"_").replace(/([A-Z])/g,"_$1").toLowerCase(),c=e.get(o);!c||c.type!=="character varying"||(a==="text"?await this.executeRaw(drizzleOrm.sql.raw(`ALTER TABLE "${n}" ALTER COLUMN "${o}" TYPE TEXT`)):a==="jsonb"&&(await this.executeRaw(drizzleOrm.sql.raw(`ALTER TABLE "${n}" ALTER COLUMN "${o}" DROP DEFAULT`)),await this.executeRaw(drizzleOrm.sql.raw(`ALTER TABLE "${n}" ALTER COLUMN "${o}" TYPE JSONB USING (CASE WHEN "${o}" IS NULL THEN NULL WHEN "${o}"::text ~ '^\\s*\\{' THEN "${o}"::jsonb ELSE jsonb_build_object('id', "${o}"::text) END)`))));}}generateCreateColumns(s){let n=[];for(let e of s.fields){if(!e.name||e.name==="id")continue;let t=L(e,this.dialect),i=e.name.replace(/-/g,"_").replace(/([A-Z])/g,"_$1").toLowerCase(),r=e.required?"NOT NULL":"DEFAULT NULL",a;if(this.dialect==="sqlite")switch(t){case "varchar":case "text":a=`TEXT ${r}`;break;case "integer":a=`INTEGER ${r}`;break;case "decimal":case "numeric":a=`NUMERIC ${r}`;break;case "boolean":a=`INTEGER ${r}`;break;case "timestamp":a=`TEXT ${r}`;break;case "jsonb":a=`TEXT ${r}`;break;default:a=`TEXT ${r}`;}else switch(t){case "varchar":a=`VARCHAR(255) ${r}`;break;case "integer":a=`INTEGER ${r}`;break;case "decimal":a=`DECIMAL ${r}`;break;case "boolean":a=`BOOLEAN ${r}`;break;case "timestamp":a=`TIMESTAMP ${r}`;break;case "jsonb":a=`JSONB ${r}`;break;default:a=`TEXT ${r}`;}n.push(`"${i}" ${a}`);}return n.join(`,
|
|
23
|
-
`)+(n.length>0?",":"")}async disconnect(){this.connected=false;}async find(s){let{collection:n,where:e={},sort:t,limit:i=10,page:r=1,tenantId:a,select:o,draft:c}=s,u=this.getCollection(n),d=this.getTable(n),T={...e};this.tenantContext&&u.tenantScoped&&(T=chunkEJDIR56C_cjs.c({where:T},n,this.tenantContext,chunkEJDIR56C_cjs.b).where||{});let m=this.buildWhereClause(T,u,d,a),h=u.fields.find(p=>p.name==="status"),y=h?.type==="select"&&Array.isArray(h.options)&&h.options.some(p=>p.value==="published");!c&&d.status&&y&&m.push(drizzleOrm.eq(d.status,"published"));let A=this.parseSort(t),R=!c&&d.status&&y?{...T,status:"published"}:T,B=await this.count({collection:n,where:R,tenantId:a}),X=(r-1)*i,v=[];try{let p=d[A.field]||d.createdAt||d.id,N=A.direction==="asc"?p:drizzleOrm.desc(p),E=this.client.select().from(d);m.length>0&&(E=E.where(drizzleOrm.and(...m))),v=await E.orderBy(N).limit(i).offset(X);}catch(p){console.error("[DrizzleAdapter] Query error:",p);}let _=v.map(p=>this.processResult(p,u));return this.tenantContext&&!this.tenantContext.isSuperAdmin&&(_=_.filter(p=>chunkEJDIR56C_cjs.d(p,n,this.tenantContext,chunkEJDIR56C_cjs.b))),c&&(_=await Promise.all(_.map(async p=>{let N=await this.executeRaw(drizzleOrm.sql`
|
|
24
|
-
SELECT * FROM kyro_versions
|
|
25
|
-
WHERE collection_slug = ${n}
|
|
26
|
-
AND document_id = ${p.id}
|
|
27
|
-
ORDER BY created_at DESC
|
|
28
|
-
LIMIT 1
|
|
29
|
-
`);if(N.length>0){let E=N[0],W=typeof E.data=="string"?JSON.parse(E.data):E.data;return {...p,...W,status:p.status}}return p}))),{docs:_,...this.calculatePagination(r,i,B)}}async findByID(s){let{collection:n,id:e,tenantId:t,draft:i}=s,r=this.getCollection(n),a=this.getTable(n);if(this.tenantContext&&r.tenantScoped){let h={id:e,tenantId:this.tenantContext.tenantId};if(!chunkEJDIR56C_cjs.d(h,n,this.tenantContext,chunkEJDIR56C_cjs.b))return null}let o=[drizzleOrm.eq(a.id,e)];t&&a.tenantId&&o.push(drizzleOrm.eq(a.tenantId,t));let c=r.fields.find(h=>h.name==="status"),u=c?.type==="select"&&Array.isArray(c.options)&&c.options.some(h=>h.value==="published");!i&&a.status&&u&&o.push(drizzleOrm.eq(a.status,"published"));let d=o.length>1?drizzleOrm.and(...o):o[0],T=await this.client.select().from(a).where(d);if(T.length===0)return null;let m=this.processResult(T[0],r);if(i){let h=await this.executeRaw(drizzleOrm.sql`
|
|
30
|
-
SELECT * FROM kyro_versions
|
|
31
|
-
WHERE collection_slug = ${n}
|
|
32
|
-
AND document_id = ${m.id}
|
|
33
|
-
ORDER BY created_at DESC
|
|
34
|
-
LIMIT 1
|
|
35
|
-
`);if(h.length>0){let y=h[0],A=typeof y.data=="string"?JSON.parse(y.data):y.data;m={...m,...A,status:m.status};}}return m}async create(s){let{collection:n,data:e,tenantId:t}=s,i=this.getCollection(n),r=this.getTable(n),a=this.prepareData(e,i);t&&(a.tenantId=t);let o=await this.client.insert(r).values(a).returning();return this.processResult(o[0],i)}async update(s){let{collection:n,id:e,data:t,tenantId:i}=s,r=this.getCollection(n),a=this.getTable(n),o=this.prepareData(t,r);delete o.id;let c=[drizzleOrm.eq(a.id,e)];i&&a.tenantId&&c.push(drizzleOrm.eq(a.tenantId,i));let u=await this.client.update(a).set(o).where(drizzleOrm.and(...c)).returning();if(u.length===0)throw new Error(`Document not found: ${n}/${e}`);return this.processResult(u[0],r)}async delete(s){let{collection:n,id:e,tenantId:t}=s,i=this.getCollection(n),r=this.getTable(n),a=[drizzleOrm.eq(r.id,e)];t&&r.tenantId&&a.push(drizzleOrm.eq(r.tenantId,t));let o=await this.client.delete(r).where(drizzleOrm.and(...a)).returning();if(o.length===0)throw new Error(`Document not found: ${n}/${e}`);return this.processResult(o[0],i)}async count(s){let{collection:n,where:e={},tenantId:t}=s,i=this.getCollection(n),r=this.getTable(n),a=this.buildWhereClause(e,i,r,t);try{let o=this.client.select({count:drizzleOrm.sql`count(*)`}).from(r);a.length>0&&(o=o.where(drizzleOrm.and(...a)));let c=await o;return Number(c[0]?.count||0)}catch{return 0}}async findOne(s){let{collection:n,where:e={},tenantId:t,draft:i}=s;if(n.startsWith("_globals_")){let a=n.replace("_globals_",""),o=this.globals.get(a);if(!o)throw new Error(`Global "${a}" not found`);let c=this.getTable(n),u=this.client.select().from(c),d=o.fields.find(y=>y.name==="status"),T=d?.type==="select"&&Array.isArray(d.options)&&d.options.some(y=>y.value==="published");!i&&c.status&&T&&(u=u.where(drizzleOrm.eq(c.status,"published")));let m=await u.limit(1);if(m.length===0)return null;let h=this.processResult(m[0],o);if(i){let y=await this.executeRaw(drizzleOrm.sql`
|
|
36
|
-
SELECT * FROM kyro_versions
|
|
37
|
-
WHERE collection_slug = ${n}
|
|
38
|
-
AND document_id = ${a}
|
|
39
|
-
ORDER BY created_at DESC
|
|
40
|
-
LIMIT 1
|
|
41
|
-
`);if(y.length>0){let A=y[0],R=typeof A.data=="string"?JSON.parse(A.data):A.data;h={...h,...R,status:h.status};}}return h}return (await this.find({...s,limit:1})).docs[0]||null}async findVersions(s){await this.ensureVersionsTable();let{collection:n,documentId:e,limit:t=10,page:i=1,tenantId:r}=s,a=(i-1)*t,o=await this.executeRaw(drizzleOrm.sql`
|
|
42
|
-
SELECT count(*) as count
|
|
43
|
-
FROM kyro_versions
|
|
44
|
-
WHERE collection_slug = ${n}
|
|
45
|
-
AND document_id = ${e}
|
|
46
|
-
AND autosave = 0
|
|
47
|
-
${r?drizzleOrm.sql`AND tenant_id = ${r}`:drizzleOrm.sql``}
|
|
48
|
-
`),c=parseInt(o[0]?.count||"0");return {docs:(await this.executeRaw(drizzleOrm.sql`
|
|
49
|
-
SELECT *
|
|
50
|
-
FROM kyro_versions
|
|
51
|
-
WHERE collection_slug = ${n}
|
|
52
|
-
AND document_id = ${e}
|
|
53
|
-
AND autosave = 0
|
|
54
|
-
${r?drizzleOrm.sql`AND tenant_id = ${r}`:drizzleOrm.sql``}
|
|
55
|
-
ORDER BY created_at DESC
|
|
56
|
-
LIMIT ${t}
|
|
57
|
-
OFFSET ${a}
|
|
58
|
-
`)).map(d=>({...d,data:typeof d.data=="string"?JSON.parse(d.data):d.data})),...this.calculatePagination(i,t,c)}}async findVersionByID(s){await this.ensureVersionsTable();let n=await this.executeRaw(drizzleOrm.sql`
|
|
59
|
-
SELECT * FROM kyro_versions
|
|
60
|
-
WHERE id = ${s.versionId}
|
|
61
|
-
AND collection_slug = ${s.collection}
|
|
62
|
-
${s.tenantId?drizzleOrm.sql`AND tenant_id = ${s.tenantId}`:drizzleOrm.sql``}
|
|
63
|
-
LIMIT 1
|
|
64
|
-
`);if(n.length===0)return null;let e=n[0];return {...e,data:typeof e.data=="string"?JSON.parse(e.data):e.data}}async createVersion(s){await this.ensureVersionsTable();let n=new Date().toISOString();if(s.autosave){let t=await this.executeRaw(drizzleOrm.sql`
|
|
65
|
-
SELECT * FROM kyro_versions
|
|
66
|
-
WHERE collection_slug = ${s.collection}
|
|
67
|
-
AND document_id = ${s.documentId}
|
|
68
|
-
AND autosave = 1
|
|
69
|
-
${s.tenantId?drizzleOrm.sql`AND tenant_id = ${s.tenantId}`:drizzleOrm.sql``}
|
|
70
|
-
LIMIT 1
|
|
71
|
-
`);if(t.length>0)return await this.executeRaw(drizzleOrm.sql`
|
|
72
|
-
UPDATE kyro_versions
|
|
73
|
-
SET data = ${JSON.stringify(s.data)},
|
|
74
|
-
status = ${s.status},
|
|
75
|
-
updated_at = ${n}
|
|
76
|
-
WHERE id = ${t[0].id}
|
|
77
|
-
`),this.findVersionByID({collection:s.collection,versionId:t[0].id,tenantId:s.tenantId})}let e=Math.random().toString(36).substring(2,15);if(await this.executeRaw(drizzleOrm.sql`
|
|
78
|
-
INSERT INTO kyro_versions (
|
|
79
|
-
id, collection_slug, document_id, tenant_id, data, status, autosave, created_by, change_description, created_at, updated_at
|
|
80
|
-
) VALUES (
|
|
81
|
-
${e}, ${s.collection}, ${s.documentId}, ${s.tenantId||null},
|
|
82
|
-
${JSON.stringify(s.data)}, ${s.status}, ${s.autosave?1:0}, ${s.createdBy||null},
|
|
83
|
-
${s.changeDescription||null}, ${n}, ${n}
|
|
84
|
-
)
|
|
85
|
-
`),!s.autosave){let t=this.getCollection(s.collection);t.versions?.maxPerDoc&&await this.deleteVersions({collection:s.collection,documentId:s.documentId,keepLatest:t.versions.maxPerDoc,tenantId:s.tenantId});}return this.findVersionByID({collection:s.collection,versionId:e,tenantId:s.tenantId})}async updateLatestVersion(s){return this.createVersion({...s,autosave:true})}async deleteVersions(s){if(await this.ensureVersionsTable(),s.keepLatest){let e=(await this.executeRaw(drizzleOrm.sql`
|
|
86
|
-
SELECT id FROM kyro_versions
|
|
87
|
-
WHERE collection_slug = ${s.collection}
|
|
88
|
-
AND document_id = ${s.documentId}
|
|
89
|
-
AND autosave = 0
|
|
90
|
-
${s.tenantId?drizzleOrm.sql`AND tenant_id = ${s.tenantId}`:drizzleOrm.sql``}
|
|
91
|
-
ORDER BY created_at DESC
|
|
92
|
-
LIMIT ${s.keepLatest}
|
|
93
|
-
`)).map(t=>t.id);e.length>0&&await this.executeRaw(drizzleOrm.sql`
|
|
94
|
-
DELETE FROM kyro_versions
|
|
95
|
-
WHERE collection_slug = ${s.collection}
|
|
96
|
-
AND document_id = ${s.documentId}
|
|
97
|
-
AND autosave = 0
|
|
98
|
-
AND id NOT IN (${drizzleOrm.sql.join(e.map(t=>drizzleOrm.sql`${t}`),drizzleOrm.sql`, `)})
|
|
99
|
-
`);}else await this.executeRaw(drizzleOrm.sql`
|
|
100
|
-
DELETE FROM kyro_versions
|
|
101
|
-
WHERE collection_slug = ${s.collection}
|
|
102
|
-
AND document_id = ${s.documentId}
|
|
103
|
-
${s.tenantId?drizzleOrm.sql`AND tenant_id = ${s.tenantId}`:drizzleOrm.sql``}
|
|
104
|
-
`);}getTable(s){let n=this.getTableName(s),e=this.schema[n];if(!e)throw new Error(`Table "${n}" not found in schema`);return e}buildWhereClause(s,n,e,t){let i=[];t&&n.tenantScoped&&e.tenantId&&i.push(drizzleOrm.eq(e.tenantId,t));for(let[r,a]of Object.entries(s))if(r==="AND"&&Array.isArray(a)){let o=a.map(c=>this.buildWhereClause(c,n,e)).flat().filter(Boolean);o.length>0&&i.push(drizzleOrm.and(...o));}else if(r==="OR"&&Array.isArray(a)){let o=a.map(c=>this.buildWhereClause(c,n,e)).flat().filter(Boolean);o.length>0&&i.push(drizzleOrm.or(...o));}else if(typeof a=="object"&&a!==null&&!Array.isArray(a)){let o=e[r];if(!o)continue;a.equals!==void 0&&i.push(drizzleOrm.eq(o,a.equals)),a.not_equals!==void 0&&i.push(drizzleOrm.ne(o,a.not_equals)),a.in&&Array.isArray(a.in)&&i.push(drizzleOrm.inArray(o,a.in)),a.like!==void 0&&i.push(drizzleOrm.like(o,a.like)),a.contains!==void 0&&i.push(drizzleOrm.like(o,`%${a.contains}%`)),a.greater_than!==void 0&&i.push(drizzleOrm.gt(o,a.greater_than)),a.greater_than_equal!==void 0&&i.push(drizzleOrm.gte(o,a.greater_than_equal)),a.less_than!==void 0&&i.push(drizzleOrm.lt(o,a.less_than)),a.less_than_equal!==void 0&&i.push(drizzleOrm.lte(o,a.less_than_equal));}else {let o=e[r];o&&i.push(drizzleOrm.eq(o,a));}return i}processResult(s,n){if(!s)return null;let e={...s};s.id&&(e.id=String(s.id));for(let t of n.fields){if(!t.name)continue;let i=t.name.replace(/-/g,"_").replace(/([A-Z])/g,"_$1").toLowerCase();i!==t.name&&e[i]!==void 0&&e[t.name]===void 0&&(e[t.name]=e[i],delete e[i]);}for(let t of n.fields){if(["json","richtext","array","group","blocks","upload","image","list","relationship-block"].includes(t.type)){let i=t;if(e[i.name]&&typeof e[i.name]=="string")try{let r=JSON.parse(e[i.name]);e[i.name]=r;}catch{}if(t.type==="blocks"&&e[i.name]&&Array.isArray(e[i.name])){let r=i.blocks||[];e[i.name]=P(e[i.name],r);}}if(t.type==="tabs"&&"tabs"in t&&t.name){if(typeof e[t.name]=="object"&&e[t.name]!==null&&!Array.isArray(e[t.name])){for(let r of t.tabs)for(let a of r.fields)if((a.type==="upload"||a.type==="image")&&a.name){let o=e[t.name][a.name];if(typeof o=="string")try{let c=JSON.parse(o);e[t.name][a.name]=Array.isArray(c)?c.map(u=>u&&typeof u=="object"&&typeof u.id=="string"?u.id:String(u||"")):typeof c.id=="string"?c.id:String(c.id||"");}catch{}else o&&typeof o=="object"&&(e[t.name][a.name]=Array.isArray(o)?o.map(c=>c&&typeof c=="object"&&typeof c.id=="string"?c.id:String(c||"")):typeof o.id=="string"?o.id:String(o.id||""));}continue}if(typeof e[t.name]=="string")try{let r=JSON.parse(e[t.name]);if(typeof r=="object"&&r!==null){e[t.name]=r;continue}}catch{}let i={};for(let r of t.tabs)for(let a of r.fields)if(a.name&&e[a.name]!==void 0){let o=e[a.name];if(["json","richtext","array","group","blocks","upload","image","list","relationship-block"].includes(a.type)){if(o&&typeof o=="string")try{o=JSON.parse(o);}catch{}(a.type==="upload"||a.type==="image")&&o&&typeof o=="object"&&(o=Array.isArray(o)?o.map(c=>c&&typeof c=="object"&&typeof c.id=="string"?c.id:String(c||"")):typeof o.id=="string"?o.id:String(o.id||""));}i[a.name]=o,delete e[a.name];}e[t.name]=i;}}return e.createdAt&&(e.createdAt=new Date(e.createdAt).toISOString()),e.updatedAt&&(e.updatedAt=new Date(e.updatedAt).toISOString()),e}async ensureVersionsTable(){if(this.versionsTableReady)return;let s;this.dialect==="sqlite"?s=`
|
|
105
|
-
CREATE TABLE IF NOT EXISTS kyro_versions (
|
|
106
|
-
id text PRIMARY KEY,
|
|
107
|
-
collection_slug text NOT NULL,
|
|
108
|
-
document_id text NOT NULL,
|
|
109
|
-
tenant_id text,
|
|
110
|
-
data text NOT NULL,
|
|
111
|
-
status text NOT NULL DEFAULT 'draft',
|
|
112
|
-
autosave integer NOT NULL DEFAULT 0,
|
|
113
|
-
created_by text,
|
|
114
|
-
change_description text,
|
|
115
|
-
created_at text DEFAULT (datetime('now')),
|
|
116
|
-
updated_at text DEFAULT (datetime('now'))
|
|
117
|
-
)
|
|
118
|
-
`:s=`
|
|
119
|
-
CREATE TABLE IF NOT EXISTS kyro_versions (
|
|
120
|
-
id text PRIMARY KEY,
|
|
121
|
-
collection_slug text NOT NULL,
|
|
122
|
-
document_id text NOT NULL,
|
|
123
|
-
tenant_id text,
|
|
124
|
-
data text NOT NULL,
|
|
125
|
-
status text NOT NULL,
|
|
126
|
-
autosave integer NOT NULL DEFAULT 0,
|
|
127
|
-
created_by text,
|
|
128
|
-
change_description text,
|
|
129
|
-
created_at text NOT NULL,
|
|
130
|
-
updated_at text NOT NULL
|
|
131
|
-
)
|
|
132
|
-
`,await this.executeRaw(drizzleOrm.sql.raw(s));try{this.dialect==="postgres"?await this.executeRaw(drizzleOrm.sql.raw("ALTER TABLE kyro_versions ADD COLUMN IF NOT EXISTS autosave integer NOT NULL DEFAULT 0")):await this.executeRaw(drizzleOrm.sql.raw("ALTER TABLE kyro_versions ADD COLUMN autosave integer NOT NULL DEFAULT 0"));}catch{}this.versionsTableReady=true;}async executeRaw(s){let n=await this.client.execute(s);return Array.isArray(n)?n:Array.isArray(n?.rows)?n.rows:Array.isArray(n?.[0])?n[0]:[]}};function De(f){return new S(f)}var pe=module$1.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('chunk-5KGQOTLK.cjs', document.baseURI).href))),he="node:sqlite",{DatabaseSync:me}=pe(he);function ye(){return process.env.DB_TYPE==="postgres"?"postgres":"sqlite"}function j(){return crypto.randomBytes(16).toString("hex")}async function Se(){let f=ye();if(f==="sqlite"){let r=path.resolve(process.cwd(),"data","kyro.db");await promises.mkdir(path.dirname(r),{recursive:true});let a=new me(r);return a.exec("PRAGMA journal_mode = WAL"),{db:a,dialect:f,genId:j}}let s=process.env.DATABASE_URL||"postgresql://postgres:postgres@localhost:5432/kyro_cms",n=parseInt(process.env.DB_POOL_MAX||"10",10),e=process.env.DB_SSL==="true",t=re__default.default(s,{max:n,ssl:e?"require":false,onnotice:()=>{}});return {db:postgresJs.drizzle(t),dialect:f,genId:j}}async function ve(f,s){}async function xe(f){let{roles:s}=await import('./schema-HIUSHSUI.cjs');await f.insert(s).values({name:"super_admin",level:100,inherits:[],description:"Full system access across all tenants",isSystem:true}).onConflictDoNothing();}
|
|
133
|
-
exports.a=L;exports.b=Le;exports.c=S;exports.d=De;exports.e=j;exports.f=Se;exports.g=ve;exports.h=xe;
|