@kyro-cms/core 0.12.18 → 0.12.21
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/api-handler-graphql.cjs +1 -1
- package/dist/api-handler-graphql.js +1 -1
- package/dist/api-handler-trpc.cjs +1 -1
- package/dist/api-handler-trpc.js +1 -1
- package/dist/api-handler.cjs +1 -1
- package/dist/api-handler.js +1 -1
- package/dist/bootstrap-4WXRKXMO.cjs +1 -0
- package/dist/{bootstrap-A3OBR3YI.js → bootstrap-KFGRTJSD.js} +1 -1
- package/dist/{chunk-CPGTIDGM.js → chunk-3NC7GXD5.js} +3 -3
- package/dist/{chunk-7USZ4YRI.js → chunk-4D6FG2J6.js} +1 -1
- package/dist/chunk-5K4YG5DA.cjs +300 -0
- package/dist/chunk-6J27P5D6.js +300 -0
- package/dist/{chunk-QMQXKCCQ.cjs → chunk-KJT6VTTN.cjs} +1 -1
- package/dist/chunk-O3OYZQN7.cjs +21 -0
- package/dist/chunk-OOQGI3T7.js +1 -0
- package/dist/chunk-QJZQOLRN.js +21 -0
- package/dist/{chunk-RNCVLIKD.cjs → chunk-SFAD6WPC.cjs} +3 -3
- package/dist/{chunk-JAJ6ZWAQ.cjs → chunk-XALG5H27.cjs} +1 -1
- package/dist/chunk-XTRY75KC.cjs +210 -0
- package/dist/chunk-YVM5BDRD.js +210 -0
- package/dist/cli/index.cjs +1 -1
- package/dist/cli/index.js +1 -1
- package/dist/index.cjs +3 -3
- package/dist/index.d.cts +105 -1
- package/dist/index.d.ts +105 -1
- package/dist/index.js +1 -1
- package/dist/rest/index.cjs +1 -1
- package/dist/rest/index.js +1 -1
- package/dist/templates/index.cjs +1 -1
- package/dist/templates/index.js +1 -1
- package/package.json +1 -1
- package/dist/bootstrap-YLGVKTQS.cjs +0 -1
- package/dist/chunk-6NGUY76Y.js +0 -259
- package/dist/chunk-EQIAXBR4.cjs +0 -86
- package/dist/chunk-GCQTSPX6.cjs +0 -259
- package/dist/chunk-HRNAHWDS.js +0 -21
- package/dist/chunk-O62KJ2J7.js +0 -1
- package/dist/chunk-ODPUHZUA.js +0 -86
- package/dist/chunk-RDKCMKBE.cjs +0 -21
|
@@ -0,0 +1,300 @@
|
|
|
1
|
+
import {a}from'./chunk-K6WUOU6P.js';function l(i){let{title:e,previewText:t=e,badgeText:r="Security Notification",badgeType:s="info",bodyHtml:o,ctaText:a,ctaUrl:n,secondaryCtaText:c,secondaryCtaUrl:g}=i,d="#eff6ff",p="#bfdbfe",m="#1d4ed8";return s==="success"?(d="#ecfdf5",p="#a7f3d0",m="#047857"):s==="warning"?(d="#fffbeb",p="#fde68a",m="#b45309"):s==="error"&&(d="#fef2f2",p="#fecaca",m="#b91c1c"),`<!DOCTYPE html>
|
|
2
|
+
<html lang="en">
|
|
3
|
+
<head>
|
|
4
|
+
<meta charset="UTF-8">
|
|
5
|
+
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
|
6
|
+
<meta name="color-scheme" content="light dark">
|
|
7
|
+
<meta name="supported-color-schemes" content="light dark">
|
|
8
|
+
<title>${e}</title>
|
|
9
|
+
<style>
|
|
10
|
+
:root {
|
|
11
|
+
color-scheme: light dark;
|
|
12
|
+
supported-color-schemes: light dark;
|
|
13
|
+
}
|
|
14
|
+
@media (prefers-color-scheme: dark) {
|
|
15
|
+
.email-body { background-color: #09090b !important; color: #f4f4f5 !important; }
|
|
16
|
+
.email-card { background-color: #121215 !important; border-color: #27272a !important; box-shadow: none !important; }
|
|
17
|
+
.email-header { background-color: #18181b !important; border-color: #27272a !important; }
|
|
18
|
+
.email-brand-text { color: #ffffff !important; }
|
|
19
|
+
.email-title { color: #ffffff !important; }
|
|
20
|
+
.email-text { color: #a1a1aa !important; }
|
|
21
|
+
.email-strong { color: #ffffff !important; }
|
|
22
|
+
.email-table { background-color: #18181b !important; border-color: #27272a !important; }
|
|
23
|
+
.email-td-border { border-color: #27272a !important; }
|
|
24
|
+
.email-label { color: #a1a1aa !important; }
|
|
25
|
+
.email-value { color: #f4f4f5 !important; }
|
|
26
|
+
.email-code-box { background-color: #18181b !important; border-color: #27272a !important; color: #ffffff !important; }
|
|
27
|
+
.email-btn-primary { background-color: #ffffff !important; color: #09090b !important; }
|
|
28
|
+
.email-btn-secondary { background-color: #18181b !important; border-color: #27272a !important; color: #f4f4f5 !important; }
|
|
29
|
+
.email-footer { background-color: #09090b !important; border-color: #27272a !important; }
|
|
30
|
+
.email-footer-text { color: #71717a !important; }
|
|
31
|
+
.email-footer-link { color: #a1a1aa !important; }
|
|
32
|
+
.logo-light { display: none !important; }
|
|
33
|
+
.logo-dark { display: inline-block !important; }
|
|
34
|
+
}
|
|
35
|
+
</style>
|
|
36
|
+
</head>
|
|
37
|
+
<body class="email-body" style="margin: 0; padding: 36px 16px; background-color: #f4f4f5; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif; color: #09090b; -webkit-font-smoothing: antialiased;">
|
|
38
|
+
<!-- Preview Text -->
|
|
39
|
+
<div style="display: none; max-height: 0; overflow: hidden;">${t}</div>
|
|
40
|
+
|
|
41
|
+
<table role="presentation" width="100%" border="0" cellspacing="0" cellpadding="0" class="email-card" style="max-width: 540px; margin: 0 auto; background-color: #ffffff; border: 1px solid #e4e4e7; border-radius: 12px; overflow: hidden; box-shadow: 0 4px 12px rgba(0, 0, 0, 0.03);">
|
|
42
|
+
<!-- Header Bar -->
|
|
43
|
+
<tr>
|
|
44
|
+
<td class="email-header" style="padding: 22px 28px; border-bottom: 1px solid #f4f4f5; background-color: #ffffff;">
|
|
45
|
+
<table role="presentation" width="100%" border="0" cellspacing="0" cellpadding="0">
|
|
46
|
+
<tr>
|
|
47
|
+
<td align="left" valign="middle">
|
|
48
|
+
<a href="https://kyro-cms.com" target="_blank" style="text-decoration: none; display: inline-flex; align-items: center; gap: 10px;">
|
|
49
|
+
<!-- Light Mode Logo -->
|
|
50
|
+
<img src="https://kyro-cms.com/logo.svg" alt="Kyro Logo" class="logo-light" height="24" style="display: inline-block; border: 0; max-height: 24px; vertical-align: middle;" />
|
|
51
|
+
<!-- Dark Mode Logo -->
|
|
52
|
+
<img src="https://kyro-cms.com/logo-white.svg" alt="Kyro Logo" class="logo-dark" height="24" style="display: none; border: 0; max-height: 24px; vertical-align: middle;" />
|
|
53
|
+
<span class="email-brand-text" style="font-size: 16px; font-weight: 700; color: #09090b; letter-spacing: -0.3px; vertical-align: middle;">Kyro CMS</span>
|
|
54
|
+
</a>
|
|
55
|
+
</td>
|
|
56
|
+
<td align="right" valign="middle">
|
|
57
|
+
<span class="badge-status" style="display: inline-block; padding: 4px 10px; background-color: ${d}; border: 1px solid ${p}; border-radius: 9999px; font-size: 11px; font-weight: 500; color: ${m};">
|
|
58
|
+
${r}
|
|
59
|
+
</span>
|
|
60
|
+
</td>
|
|
61
|
+
</tr>
|
|
62
|
+
</table>
|
|
63
|
+
</td>
|
|
64
|
+
</tr>
|
|
65
|
+
|
|
66
|
+
<!-- Body Section -->
|
|
67
|
+
<tr>
|
|
68
|
+
<td style="padding: 28px;">
|
|
69
|
+
<h1 class="email-title" style="margin: 0 0 12px; font-size: 20px; font-weight: 600; color: #09090b; letter-spacing: -0.3px;">
|
|
70
|
+
${e}
|
|
71
|
+
</h1>
|
|
72
|
+
|
|
73
|
+
${o}
|
|
74
|
+
|
|
75
|
+
${a&&n?`
|
|
76
|
+
<!-- Action Buttons -->
|
|
77
|
+
<table role="presentation" width="100%" border="0" cellspacing="0" cellpadding="0" style="margin-top: 24px;">
|
|
78
|
+
<tr>
|
|
79
|
+
<td align="left">
|
|
80
|
+
<a href="${n}" target="_blank" class="email-btn-primary" style="display: inline-block; padding: 11px 20px; background-color: #09090b; color: #ffffff; font-size: 13px; font-weight: 500; text-decoration: none; border-radius: 6px;">
|
|
81
|
+
${a} \u2192
|
|
82
|
+
</a>
|
|
83
|
+
${c&&g?`<a href="${g}" target="_blank" class="email-btn-secondary" style="display: inline-block; padding: 11px 16px; margin-left: 8px; background-color: #ffffff; border: 1px solid #e4e4e7; color: #09090b; font-size: 13px; font-weight: 500; text-decoration: none; border-radius: 6px;">
|
|
84
|
+
${c}
|
|
85
|
+
</a>`:""}
|
|
86
|
+
</td>
|
|
87
|
+
</tr>
|
|
88
|
+
</table>`:""}
|
|
89
|
+
</td>
|
|
90
|
+
</tr>
|
|
91
|
+
|
|
92
|
+
<!-- Footer -->
|
|
93
|
+
<tr>
|
|
94
|
+
<td class="email-footer" style="padding: 18px 28px; border-top: 1px solid #f4f4f5; background-color: #fafafa; text-align: center;">
|
|
95
|
+
<p class="email-footer-text" style="margin: 0 0 8px; font-size: 12px; color: #71717a;">
|
|
96
|
+
Sent securely via <strong>Kyro CMS Authentication Engine</strong>.
|
|
97
|
+
</p>
|
|
98
|
+
<p style="margin: 0; font-size: 12px; color: #71717a;">
|
|
99
|
+
<a href="https://kyro-cms.com" target="_blank" class="email-footer-link" style="color: #09090b; text-decoration: none; font-weight: 500;">kyro-cms.com</a> \u2022
|
|
100
|
+
<a href="https://kyro-cms.com/docs" target="_blank" class="email-footer-link" style="color: #09090b; text-decoration: none; font-weight: 500;">Docs</a> \u2022
|
|
101
|
+
<a href="https://github.com/danielDozie/kyro-cms" target="_blank" class="email-footer-link" style="color: #09090b; text-decoration: none; font-weight: 500;">GitHub</a>
|
|
102
|
+
</p>
|
|
103
|
+
</td>
|
|
104
|
+
</tr>
|
|
105
|
+
</table>
|
|
106
|
+
</body>
|
|
107
|
+
</html>`}function h(i,e="User"){let t="Confirm your email address \u2014 Kyro CMS",r=`
|
|
108
|
+
<p class="email-text" style="margin: 0 0 16px; font-size: 14px; line-height: 1.6; color: #52525b;">
|
|
109
|
+
Hello <strong class="email-strong" style="color: #09090b;">${e}</strong>,
|
|
110
|
+
</p>
|
|
111
|
+
<p class="email-text" style="margin: 0 0 20px; font-size: 14px; line-height: 1.6; color: #52525b;">
|
|
112
|
+
Thank you for registering. Please confirm your email address by clicking the verification button below to activate your account.
|
|
113
|
+
</p>
|
|
114
|
+
|
|
115
|
+
<!-- Verification Token Link Card -->
|
|
116
|
+
<table role="presentation" width="100%" border="0" cellspacing="0" cellpadding="0" class="email-table" style="background-color: #fafafa; border: 1px solid #e4e4e7; border-radius: 8px; margin-bottom: 20px; padding: 14px; border-collapse: separate;">
|
|
117
|
+
<tr>
|
|
118
|
+
<td style="font-size: 12px; color: #71717a; line-height: 1.5; word-break: break-all;">
|
|
119
|
+
<strong>Direct link:</strong><br />
|
|
120
|
+
<a href="${i}" style="color: #09090b; text-decoration: underline;" class="email-value">${i}</a>
|
|
121
|
+
</td>
|
|
122
|
+
</tr>
|
|
123
|
+
</table>
|
|
124
|
+
|
|
125
|
+
<p class="email-text" style="margin: 0 0 8px; font-size: 12px; color: #71717a;">
|
|
126
|
+
This verification link will expire in 24 hours. If you did not create an account, you can safely ignore this email.
|
|
127
|
+
</p>
|
|
128
|
+
`,s=l({title:"Confirm Your Email Address",previewText:"Please confirm your email address to activate your Kyro CMS account.",badgeText:"Action Required",badgeType:"warning",bodyHtml:r,ctaText:"Confirm Email Address",ctaUrl:i,secondaryCtaText:"Documentation",secondaryCtaUrl:"https://kyro-cms.com/docs"}),o=`Welcome, ${e}!
|
|
129
|
+
|
|
130
|
+
Please verify your email address by visiting:
|
|
131
|
+
${i}
|
|
132
|
+
|
|
133
|
+
This link expires in 24 hours.
|
|
134
|
+
|
|
135
|
+
Kyro CMS \u2014 https://kyro-cms.com`;return {subject:t,html:s,text:o}}function y(i,e="User"){let t="Reset your password \u2014 Kyro CMS",r=`
|
|
136
|
+
<p class="email-text" style="margin: 0 0 16px; font-size: 14px; line-height: 1.6; color: #52525b;">
|
|
137
|
+
Hello <strong class="email-strong" style="color: #09090b;">${e}</strong>,
|
|
138
|
+
</p>
|
|
139
|
+
<p class="email-text" style="margin: 0 0 20px; font-size: 14px; line-height: 1.6; color: #52525b;">
|
|
140
|
+
We received a request to reset the password for your account. Click the button below to choose a new password.
|
|
141
|
+
</p>
|
|
142
|
+
|
|
143
|
+
<!-- Reset Link Box -->
|
|
144
|
+
<table role="presentation" width="100%" border="0" cellspacing="0" cellpadding="0" class="email-table" style="background-color: #fafafa; border: 1px solid #e4e4e7; border-radius: 8px; margin-bottom: 20px; padding: 14px; border-collapse: separate;">
|
|
145
|
+
<tr>
|
|
146
|
+
<td style="font-size: 12px; color: #71717a; line-height: 1.5; word-break: break-all;">
|
|
147
|
+
<strong>Reset URL:</strong><br />
|
|
148
|
+
<a href="${i}" style="color: #09090b; text-decoration: underline;" class="email-value">${i}</a>
|
|
149
|
+
</td>
|
|
150
|
+
</tr>
|
|
151
|
+
</table>
|
|
152
|
+
|
|
153
|
+
<p class="email-text" style="margin: 0 0 8px; font-size: 12px; color: #71717a;">
|
|
154
|
+
For security reasons, this link will expire in 1 hour. If you did not request a password reset, no further action is required.
|
|
155
|
+
</p>
|
|
156
|
+
`,s=l({title:"Reset Your Password",previewText:"Use this secure link to reset your Kyro CMS password.",badgeText:"Security Action",badgeType:"warning",bodyHtml:r,ctaText:"Reset Password",ctaUrl:i}),o=`Hello ${e},
|
|
157
|
+
|
|
158
|
+
Reset your password using the following link:
|
|
159
|
+
${i}
|
|
160
|
+
|
|
161
|
+
This link will expire in 1 hour.
|
|
162
|
+
|
|
163
|
+
Kyro CMS \u2014 https://kyro-cms.com`;return {subject:t,html:s,text:o}}function b(i="User",e="https://kyro-cms.com"){let t="Welcome to Kyro CMS!",r=`
|
|
164
|
+
<p class="email-text" style="margin: 0 0 16px; font-size: 14px; line-height: 1.6; color: #52525b;">
|
|
165
|
+
Welcome <strong class="email-strong" style="color: #09090b;">${i}</strong>,
|
|
166
|
+
</p>
|
|
167
|
+
<p class="email-text" style="margin: 0 0 20px; font-size: 14px; line-height: 1.6; color: #52525b;">
|
|
168
|
+
Your Kyro CMS account is now set up and ready to go. You can access your admin dashboard, build content collections, and manage schema endpoints.
|
|
169
|
+
</p>
|
|
170
|
+
|
|
171
|
+
<!-- Key Capabilities List -->
|
|
172
|
+
<table role="presentation" width="100%" border="0" cellspacing="0" cellpadding="0" class="email-table" style="background-color: #fafafa; border: 1px solid #e4e4e7; border-radius: 8px; margin-bottom: 24px; padding: 16px; border-collapse: separate;">
|
|
173
|
+
<tr>
|
|
174
|
+
<td style="font-size: 13px; color: #09090b; line-height: 1.6;" class="email-value">
|
|
175
|
+
\u{1F680} <strong>What you can do next:</strong>
|
|
176
|
+
<ul style="margin: 8px 0 0; padding-left: 20px; color: #52525b;">
|
|
177
|
+
<li>Define collections & custom field schemas in <code style="font-family: monospace;">kyro.config.ts</code></li>
|
|
178
|
+
<li>Explore auto-generated REST, GraphQL, tRPC & WebSocket endpoints</li>
|
|
179
|
+
<li>Customize your visual Admin dashboard & branding settings</li>
|
|
180
|
+
</ul>
|
|
181
|
+
</td>
|
|
182
|
+
</tr>
|
|
183
|
+
</table>
|
|
184
|
+
`,s=l({title:"Welcome to Kyro CMS",previewText:"Your account is verified and ready. Start building content applications.",badgeText:"Account Ready",badgeType:"success",bodyHtml:r,ctaText:"Open Dashboard",ctaUrl:e,secondaryCtaText:"Documentation",secondaryCtaUrl:"https://kyro-cms.com/docs"}),o=`Welcome to Kyro CMS, ${i}!
|
|
185
|
+
|
|
186
|
+
Your account is active. Log in at ${e} to start building.
|
|
187
|
+
|
|
188
|
+
Documentation: https://kyro-cms.com/docs`;return {subject:t,html:s,text:o}}function x(i="User"){let e="Security Alert: Password Changed \u2014 Kyro CMS",t=new Date().toUTCString(),r=`
|
|
189
|
+
<p class="email-text" style="margin: 0 0 16px; font-size: 14px; line-height: 1.6; color: #52525b;">
|
|
190
|
+
Hello <strong class="email-strong" style="color: #09090b;">${i}</strong>,
|
|
191
|
+
</p>
|
|
192
|
+
<p class="email-text" style="margin: 0 0 20px; font-size: 14px; line-height: 1.6; color: #52525b;">
|
|
193
|
+
This email confirms that the password for your Kyro CMS account was successfully updated on <strong>${t}</strong>.
|
|
194
|
+
</p>
|
|
195
|
+
|
|
196
|
+
<!-- Security Warning Card -->
|
|
197
|
+
<table role="presentation" width="100%" border="0" cellspacing="0" cellpadding="0" class="email-table" style="background-color: #fef2f2; border: 1px solid #fecaca; border-radius: 8px; margin-bottom: 20px; padding: 14px; border-collapse: separate;">
|
|
198
|
+
<tr>
|
|
199
|
+
<td style="font-size: 13px; color: #991b1b; line-height: 1.5;">
|
|
200
|
+
\u26A0\uFE0F <strong>Did not request this change?</strong><br />
|
|
201
|
+
If you did not initiate this change, your account may be compromised. Reset your password immediately and contact an administrator.
|
|
202
|
+
</td>
|
|
203
|
+
</tr>
|
|
204
|
+
</table>
|
|
205
|
+
`,s=l({title:"Password Updated",previewText:"Your Kyro CMS account password was updated.",badgeText:"Security Alert",badgeType:"warning",bodyHtml:r,ctaText:"Account Security",ctaUrl:"https://kyro-cms.com"}),o=`Security Alert: Your Kyro CMS password was updated at ${t}.
|
|
206
|
+
|
|
207
|
+
If you did not make this change, please reset your password immediately.
|
|
208
|
+
|
|
209
|
+
Kyro CMS \u2014 https://kyro-cms.com`;return {subject:e,html:s,text:o}}function _(i,e,t="User"){let r="Your one-time login link \u2014 Kyro CMS",s=`
|
|
210
|
+
<p class="email-text" style="margin: 0 0 16px; font-size: 14px; line-height: 1.6; color: #52525b;">
|
|
211
|
+
Hello <strong class="email-strong" style="color: #09090b;">${t}</strong>,
|
|
212
|
+
</p>
|
|
213
|
+
<p class="email-text" style="margin: 0 0 20px; font-size: 14px; line-height: 1.6; color: #52525b;">
|
|
214
|
+
Click the button below to sign in to your Kyro CMS account without entering a password.
|
|
215
|
+
</p>
|
|
216
|
+
|
|
217
|
+
${e?`
|
|
218
|
+
<!-- One-Time Passcode Box -->
|
|
219
|
+
<table role="presentation" width="100%" border="0" cellspacing="0" cellpadding="0" class="email-table" style="background-color: #fafafa; border: 1px solid #e4e4e7; border-radius: 8px; margin-bottom: 20px; padding: 16px; text-align: center;">
|
|
220
|
+
<tr>
|
|
221
|
+
<td style="font-size: 12px; color: #71717a; text-transform: uppercase; letter-spacing: 0.5px; margin-bottom: 6px;">
|
|
222
|
+
One-Time Passcode
|
|
223
|
+
</td>
|
|
224
|
+
</tr>
|
|
225
|
+
<tr>
|
|
226
|
+
<td style="font-size: 28px; font-weight: 800; font-family: monospace; color: #09090b; letter-spacing: 4px;" class="email-code-box">
|
|
227
|
+
${e}
|
|
228
|
+
</td>
|
|
229
|
+
</tr>
|
|
230
|
+
</table>`:""}
|
|
231
|
+
|
|
232
|
+
<p class="email-text" style="margin: 0 0 8px; font-size: 12px; color: #71717a;">
|
|
233
|
+
This single-use link will expire in 10 minutes. Never share authentication links with anyone.
|
|
234
|
+
</p>
|
|
235
|
+
`,o=l({title:"Sign in to Kyro CMS",previewText:"Your secure magic login link for Kyro CMS.",badgeText:"Instant Login",badgeType:"info",bodyHtml:s,ctaText:"Sign In Now",ctaUrl:i}),a=`Hello ${t},
|
|
236
|
+
|
|
237
|
+
Sign in to Kyro CMS using the link below:
|
|
238
|
+
${i}${e?`
|
|
239
|
+
|
|
240
|
+
Or enter code: ${e}`:""}
|
|
241
|
+
|
|
242
|
+
This link expires in 10 minutes.
|
|
243
|
+
|
|
244
|
+
Kyro CMS \u2014 https://kyro-cms.com`;return {subject:r,html:o,text:a}}function S(i,e,t="User"){let r="Security Alert: Account Temporarily Locked \u2014 Kyro CMS",s=`
|
|
245
|
+
<p class="email-text" style="margin: 0 0 16px; font-size: 14px; line-height: 1.6; color: #52525b;">
|
|
246
|
+
Hello <strong class="email-strong" style="color: #09090b;">${t}</strong>,
|
|
247
|
+
</p>
|
|
248
|
+
<p class="email-text" style="margin: 0 0 20px; font-size: 14px; line-height: 1.6; color: #52525b;">
|
|
249
|
+
Your Kyro CMS account was temporarily locked after <strong>${i} failed login attempts</strong>.
|
|
250
|
+
</p>
|
|
251
|
+
|
|
252
|
+
<!-- Lockout Notice Card -->
|
|
253
|
+
<table role="presentation" width="100%" border="0" cellspacing="0" cellpadding="0" class="email-table" style="background-color: #fffbeb; border: 1px solid #fde68a; border-radius: 8px; margin-bottom: 20px; padding: 14px; border-collapse: separate;">
|
|
254
|
+
<tr>
|
|
255
|
+
<td style="font-size: 13px; color: #b45309; line-height: 1.5;">
|
|
256
|
+
\u{1F512} <strong>Lockout duration:</strong> ${e} minutes.<br />
|
|
257
|
+
You may try logging in again after the cooling-off period expires.
|
|
258
|
+
</td>
|
|
259
|
+
</tr>
|
|
260
|
+
</table>
|
|
261
|
+
`,o=l({title:"Account Temporarily Locked",previewText:"Your Kyro CMS account was locked due to multiple failed login attempts.",badgeText:"Security Lockout",badgeType:"warning",bodyHtml:s,ctaText:"Unlock Instructions",ctaUrl:"https://kyro-cms.com/docs"}),a=`Security Alert: Account temporarily locked for ${t} after ${i} failed login attempts. Unlocks in ${e} minutes.
|
|
262
|
+
|
|
263
|
+
Kyro CMS \u2014 https://kyro-cms.com`;return {subject:r,html:o,text:a}}function T(i,e="Editor",t="An Administrator"){let r="You're invited to join Kyro CMS",s=`
|
|
264
|
+
<p class="email-text" style="margin: 0 0 16px; font-size: 14px; line-height: 1.6; color: #52525b;">
|
|
265
|
+
Hello,
|
|
266
|
+
</p>
|
|
267
|
+
<p class="email-text" style="margin: 0 0 20px; font-size: 14px; line-height: 1.6; color: #52525b;">
|
|
268
|
+
<strong class="email-strong" style="color: #09090b;">${t}</strong> has invited you to join their team workspace as an <strong>${e}</strong> in Kyro CMS.
|
|
269
|
+
</p>
|
|
270
|
+
|
|
271
|
+
<!-- Invite Details Card -->
|
|
272
|
+
<table role="presentation" width="100%" border="0" cellspacing="0" cellpadding="0" class="email-table" style="background-color: #fafafa; border: 1px solid #e4e4e7; border-radius: 8px; margin-bottom: 20px; padding: 14px; border-collapse: separate;">
|
|
273
|
+
<tr>
|
|
274
|
+
<td style="font-size: 13px; color: #09090b; line-height: 1.6;" class="email-value">
|
|
275
|
+
<strong>Assigned Role:</strong> ${e}<br />
|
|
276
|
+
<strong>Invited By:</strong> ${t}
|
|
277
|
+
</td>
|
|
278
|
+
</tr>
|
|
279
|
+
</table>
|
|
280
|
+
`,o=l({title:"Workspace Invitation",previewText:`You have been invited to join Kyro CMS as an ${e}.`,badgeText:"Team Invite",badgeType:"info",bodyHtml:s,ctaText:"Accept Invitation",ctaUrl:i,secondaryCtaText:"Documentation",secondaryCtaUrl:"https://kyro-cms.com/docs"}),a=`You're invited to join Kyro CMS as an ${e} by ${t}.
|
|
281
|
+
|
|
282
|
+
Accept your invitation here:
|
|
283
|
+
${i}
|
|
284
|
+
|
|
285
|
+
Kyro CMS \u2014 https://kyro-cms.com`;return {subject:r,html:o,text:a}}function w(){return {verifyEmail:(i,e)=>h(i,e),resetPassword:(i,e)=>y(i,e),welcome:(i,e)=>b(i,e),passwordChanged:i=>x(i),magicLink:(i,e,t)=>_(i,e,t),accountLocked:(i,e,t)=>S(i,e,t),newLogin:(i,e,t="User")=>{let r="Security Alert: New Sign-in to Kyro CMS",s=`New login detected for ${t} at ${e} from ${i}.`,o=`<p>${s}</p>`;return {subject:r,html:o,text:s}},userInvite:(i,e,t)=>T(i,e,t)}}var C=false,u=class i{db;cache={};loaded=false;static SENSITIVE_KEYS=["storage.s3.secret_access_key","storage.r2.secret_access_key","storage.gcs.private_key","storage.backblaze.application_key","storage.wasabi.secret_access_key","storage.ftp.password","storage.bunny.api_key","storage.cloudinary.api_secret","storage.imgix.sign_key","email.smtp.pass","auth.jwt_secret","auth.github_secret","auth.google_secret","auth.app_secret","database.url","redis.url","auth.admin_password"];constructor(e){this.db=e;}async load(){if(!this.loaded){await this.ensureSettingsTable();try{if(typeof this.db?.select=="function"){let e=await this.db.select().from(a);this.cache=e.reduce((t,r)=>(t[r.key]=r.value,t),{});}await this.loadFromGlobals();}catch{console.warn("ConfigService: Could not load settings from database, using environment fallbacks.");}this.loaded=true;}}async ensureSettingsTable(){if(!C)try{if(typeof this.db?.execute=="function"){let{sql:e}=await import('drizzle-orm');await this.db.execute(e`
|
|
286
|
+
CREATE TABLE IF NOT EXISTS "settings" (
|
|
287
|
+
"key" VARCHAR(255) PRIMARY KEY,
|
|
288
|
+
"value" TEXT NOT NULL,
|
|
289
|
+
"description" TEXT,
|
|
290
|
+
"updated_at" TIMESTAMP DEFAULT NOW()
|
|
291
|
+
)
|
|
292
|
+
`),C=!0;}else typeof this.db?.exec=="function"&&(this.db.exec(`
|
|
293
|
+
CREATE TABLE IF NOT EXISTS settings (
|
|
294
|
+
key TEXT PRIMARY KEY,
|
|
295
|
+
value TEXT NOT NULL,
|
|
296
|
+
description TEXT,
|
|
297
|
+
updated_at TEXT
|
|
298
|
+
)
|
|
299
|
+
`),C=!0);}catch{}}async loadFromGlobals(){try{let e=null;if(typeof this.db?.findOne=="function")try{let s=await this.db.findOne({collection:"_globals_storage-settings",where:{},draft:!0});s&&(e=s);}catch{}if(!e&&typeof this.db?.execute=="function"){let{sql:s}=await import('drizzle-orm'),o=['"_globals_storage-settings"','"_globals_storage_settings"','"global_storage_settings"'];for(let a of o)try{let n=await this.db.execute(s`SELECT * FROM ${s.raw(a)} LIMIT 1`);if(e=Array.isArray(n)?n[0]:n?.rows?n.rows[0]:null,e)break}catch{}}else if(!e&&typeof this.db?.prepare=="function"){let s=['"_globals_storage-settings"','"_globals_storage_settings"','"global_storage_settings"'];for(let o of s)try{if(e=this.db.prepare(`SELECT * FROM ${o} LIMIT 1`).get(),e)break}catch{}}if(!e)return;let t=s=>{if(!s)return null;if(typeof s=="string")try{return JSON.parse(s)}catch{return null}return s},r=e.provider||"local";if(this.cache["storage.type"]=r,r==="local"){let s=t(e.local);this.cache["storage.local.dir"]=s?.uploadDir||"./public/uploads",this.cache["storage.local.url"]=s?.baseUrl||"/uploads";}if(r==="aws"){let s=t(e.aws);this.cache["storage.s3.bucket"]=s?.bucket||"",this.cache["storage.s3.region"]=s?.region||"us-east-1",this.cache["storage.s3.access_key_id"]=s?.accessKeyId||"",this.cache["storage.s3.secret_access_key"]=s?.secretAccessKey||"",this.cache["storage.s3.endpoint"]=s?.endpoint||"",this.cache["storage.s3.cdn_url"]=s?.cdnUrl||"",this.cache["storage.s3.prefix"]=s?.prefix||"";}if(r==="r2"){let s=t(e.r2);this.cache["storage.r2.account_id"]=s?.accountId||"",this.cache["storage.r2.access_key_id"]=s?.accessKeyId||"",this.cache["storage.r2.secret_access_key"]=s?.secretAccessKey||"",this.cache["storage.r2.bucket"]=s?.bucket||"",this.cache["storage.r2.cdn_url"]=s?.cdnUrl||"",this.cache["storage.r2.prefix"]=s?.prefix||"";}if(r==="cloudinary"){let s=t(e.cloudinary);this.cache["storage.cloudinary.cloud_name"]=s?.cloudName||"",this.cache["storage.cloudinary.api_key"]=s?.apiKey||"",this.cache["storage.cloudinary.api_secret"]=s?.apiSecret||"",this.cache["storage.cloudinary.folder"]=s?.folder||"";}if(r==="ftp"){let s=t(e.ftp);this.cache["storage.ftp.host"]=s?.host||"",this.cache["storage.ftp.port"]=String(s?.port||"21"),this.cache["storage.ftp.user"]=s?.user||"",this.cache["storage.ftp.password"]=s?.password||"",this.cache["storage.ftp.secure"]=s?.secure?"true":"false",this.cache["storage.ftp.base_url"]=s?.baseUrl||"",this.cache["storage.ftp.prefix"]=s?.prefix||"";}}catch(e){console.warn("ConfigService: Could not load storage settings from globals table:",e);}try{let e=null;if(typeof this.db?.findOne=="function")try{let t=await this.db.findOne({collection:"_globals_email-settings",where:{},draft:!0});t&&(e=t);}catch{}if(!e&&typeof this.db?.execute=="function"){let{sql:t}=await import('drizzle-orm'),r=['"_globals_email-settings"','"_globals_email_settings"','"global_email_settings"'];for(let s of r)try{let o=await this.db.execute(t`SELECT * FROM ${t.raw(s)} LIMIT 1`);if(e=Array.isArray(o)?o[0]:o?.rows?o.rows[0]:null,e)break}catch{}}else if(!e&&typeof this.db?.prepare=="function"){let t=['"_globals_email-settings"','"_globals_email_settings"','"global_email_settings"'];for(let r of t)try{if(e=this.db.prepare(`SELECT * FROM ${r} LIMIT 1`).get(),e)break}catch{}}if(e){let t=r=>{if(!r)return null;if(typeof r=="string")try{return JSON.parse(r)}catch{return null}return r};if(this.cache["email.provider"]=e.provider||"smtp",this.cache["email.smtp.from"]=e.fromEmail||"",this.cache["email.smtp.from_name"]=e.fromName||"",this.cache["email.smtp.reply_to"]=e.replyTo||"",e.provider==="smtp"){let r=t(e.smtp);this.cache["email.smtp.host"]=r?.host||"",this.cache["email.smtp.port"]=String(r?.port||"587"),this.cache["email.smtp.user"]=r?.username||"",this.cache["email.smtp.pass"]=r?.password||"",this.cache["email.smtp.secure"]=r?.secure?"true":"false";}else if(e.provider==="resend"){let r=t(e.resend);this.cache["email.smtp.pass"]=r?.apiKey||"";}else if(e.provider==="sendgrid"){let r=t(e.sendgrid);this.cache["email.smtp.pass"]=r?.apiKey||"";}else if(e.provider==="mailgun"){let r=t(e.mailgun);this.cache["email.smtp.pass"]=r?.apiKey||"";}else if(e.provider==="ses"){let r=t(e.ses);this.cache["email.smtp.user"]=r?.accessKeyId||"",this.cache["email.smtp.pass"]=r?.secretAccessKey||"";}}}catch(e){console.warn("ConfigService: Could not load email settings from globals table:",e);}}get(e,t,r){return this.cache[e]?this.cache[e]:t&&process.env[t]?process.env[t]:r}getStorageConfig(){return {type:this.get("storage.type","STORAGE_TYPE","local"),s3:{bucket:this.get("storage.s3.bucket","STORAGE_BUCKET"),region:this.get("storage.s3.region","STORAGE_REGION","us-east-1"),accessKeyId:this.get("storage.s3.access_key_id","STORAGE_ACCESS_KEY_ID"),secretAccessKey:this.get("storage.s3.secret_access_key","STORAGE_SECRET_ACCESS_KEY"),endpoint:this.get("storage.s3.endpoint","STORAGE_ENDPOINT"),cdnUrl:this.get("storage.s3.cdn_url","STORAGE_CDN_URL"),prefix:this.get("storage.s3.prefix","STORAGE_PREFIX")},r2:{accountId:this.get("storage.r2.account_id","R2_ACCOUNT_ID"),accessKeyId:this.get("storage.r2.access_key_id","R2_ACCESS_KEY_ID"),secretAccessKey:this.get("storage.r2.secret_access_key","R2_SECRET_ACCESS_KEY"),bucket:this.get("storage.r2.bucket","R2_BUCKET"),cdnUrl:this.get("storage.r2.cdn_url","R2_CDN_URL"),prefix:this.get("storage.r2.prefix","R2_PREFIX")},gcs:{bucket:this.get("storage.gcs.bucket","GCS_BUCKET"),projectId:this.get("storage.gcs.project_id","GCS_PROJECT_ID"),clientEmail:this.get("storage.gcs.client_email","GCS_CLIENT_EMAIL"),privateKey:this.get("storage.gcs.private_key","GCS_PRIVATE_KEY"),cdnUrl:this.get("storage.gcs.cdn_url","GCS_CDN_URL"),prefix:this.get("storage.gcs.prefix","GCS_PREFIX")},digitalocean:{bucket:this.get("storage.digitalocean.bucket","DO_BUCKET"),region:this.get("storage.digitalocean.region","DO_REGION","nyc3"),accessKeyId:this.get("storage.digitalocean.access_key_id","DO_ACCESS_KEY_ID"),secretAccessKey:this.get("storage.digitalocean.secret_access_key","DO_SECRET_ACCESS_KEY"),cdnUrl:this.get("storage.digitalocean.cdn_url","DO_CDN_URL"),prefix:this.get("storage.digitalocean.prefix","DO_PREFIX")},backblaze:{bucket:this.get("storage.backblaze.bucket","BB_BUCKET"),accountId:this.get("storage.backblaze.account_id","BB_ACCOUNT_ID"),applicationKeyId:this.get("storage.backblaze.application_key_id","BB_APPLICATION_KEY_ID"),applicationKey:this.get("storage.backblaze.application_key","BB_APPLICATION_KEY"),cdnUrl:this.get("storage.backblaze.cdn_url","BB_CDN_URL"),prefix:this.get("storage.backblaze.prefix","BB_PREFIX")},wasabi:{bucket:this.get("storage.wasabi.bucket","WASABI_BUCKET"),region:this.get("storage.wasabi.region","WASABI_REGION","us-east-1"),accessKeyId:this.get("storage.wasabi.access_key_id","WASABI_ACCESS_KEY_ID"),secretAccessKey:this.get("storage.wasabi.secret_access_key","WASABI_SECRET_ACCESS_KEY"),cdnUrl:this.get("storage.wasabi.cdn_url","WASABI_CDN_URL"),prefix:this.get("storage.wasabi.prefix","WASABI_PREFIX")},bunny:{storageZone:this.get("storage.bunny.storage_zone","BUNNY_STORAGE_ZONE"),apiKey:this.get("storage.bunny.api_key","BUNNY_API_KEY"),cdnUrl:this.get("storage.bunny.cdn_url","BUNNY_CDN_URL"),prefix:this.get("storage.bunny.prefix","BUNNY_PREFIX")},ftp:{host:this.get("storage.ftp.host","FTP_HOST"),port:parseInt(this.get("storage.ftp.port","FTP_PORT","21"),10),user:this.get("storage.ftp.user","FTP_USER"),password:this.get("storage.ftp.password","FTP_PASSWORD"),secure:this.get("storage.ftp.secure","FTP_SECURE")==="true",baseUrl:this.get("storage.ftp.base_url","FTP_BASE_URL"),prefix:this.get("storage.ftp.prefix","FTP_PREFIX")},cloudinary:{cloudName:this.get("storage.cloudinary.cloud_name","CLOUDINARY_CLOUD_NAME"),apiKey:this.get("storage.cloudinary.api_key","CLOUDINARY_API_KEY"),apiSecret:this.get("storage.cloudinary.api_secret","CLOUDINARY_API_SECRET"),folder:this.get("storage.cloudinary.folder","CLOUDINARY_FOLDER")},imgix:{domain:this.get("storage.imgix.domain","IMGIX_DOMAIN"),signKey:this.get("storage.imgix.sign_key","IMGIX_SIGN_KEY")},local:{uploadDir:this.get("storage.local.dir","STORAGE_LOCAL_DIR","./public/uploads"),baseUrl:this.get("storage.local.url","STORAGE_LOCAL_URL","/uploads")}}}getEmailConfig(){return {provider:this.get("email.provider","EMAIL_PROVIDER","smtp"),host:this.get("email.smtp.host","SMTP_HOST"),port:parseInt(this.get("email.smtp.port","SMTP_PORT","587"),10),secure:this.get("email.smtp.secure","SMTP_SECURE")==="true",user:this.get("email.smtp.user","SMTP_USER"),pass:this.get("email.smtp.pass","SMTP_PASS"),from:this.get("email.smtp.from","SMTP_FROM","noreply@example.com"),fromName:this.get("email.smtp.from_name","SMTP_FROM_NAME","Kyro CMS"),replyTo:this.get("email.smtp.reply_to","SMTP_REPLY_TO")}}maskSensitive(e,t){return t&&(i.SENSITIVE_KEYS.includes(e)?"********":t)}async set(e,t,r){await this.db.insert(a).values({key:e,value:t,description:r,updatedAt:new Date}).onConflictDoUpdate({target:[a.key],set:{value:t,description:r,updatedAt:new Date}}),this.cache[e]=t;}};var E=class i{transporter;config;templates;transporterInitialized=false;constructor(e,t){this.config=e,this.templates={...w(),...t};}async ensureTransporter(){if(this.transporterInitialized)return this.transporter;let{default:e}=await import('nodemailer');return this.config.provider==="smtp"&&this.config.smtp?this.transporter=e.createTransport({host:this.config.smtp.host,port:this.config.smtp.port,secure:this.config.smtp.secure,auth:this.config.smtp.auth}):this.config.provider==="ses"&&this.config.ses&&(this.transporter=e.createTransport({host:`email-smtp.${this.config.ses.region}.amazonaws.com`,port:587,secure:false,auth:{user:this.config.ses.accessKeyId,pass:this.config.ses.secretAccessKey}})),this.transporterInitialized=true,this.transporter}async send(e){let{provider:t,from:r,fromName:s,replyTo:o}=this.config,a=`"${s||"Kyro CMS"}" <${r}>`,n=e.replyTo||o;try{let c;switch(t){case "smtp":case "ses":{let g=await this.ensureTransporter();if(!g)throw new Error(`${t} transporter not initialized`);c=await g.sendMail({from:a,to:Array.isArray(e.to)?e.to.join(", "):e.to,subject:e.subject,html:e.html,text:e.text,replyTo:n});}break;case "resend":c=await this.sendViaResend(a,e,n);break;case "sendgrid":c=await this.sendViaSendGrid(a,e,n);break;case "mailgun":c=await this.sendViaMailgun(a,e,n);break;default:throw new Error(`Unsupported email provider: ${t}`)}return c}catch(c){throw console.error("[EmailTransport] FAILED to send email:",c.message),c.response&&console.error("[EmailTransport] Provider Error Detail:",JSON.stringify(c.response,null,2)),c}}async sendViaResend(e,t,r){let s=this.config.resend?.apiKey;if(!s)throw new Error("Resend API Key missing");let o={from:e,to:t.to,subject:t.subject,html:t.html,text:t.text,reply_to:r},a=await fetch("https://api.resend.com/emails",{method:"POST",headers:{Authorization:`Bearer ${s}`,"Content-Type":"application/json"},body:JSON.stringify(o)});if(!a.ok){let n=await a.json();throw new Error(`Resend Error: ${JSON.stringify(n)}`)}return a.json()}async sendViaSendGrid(e,t,r){let s=this.config.sendgrid?.apiKey;if(!s)throw new Error("SendGrid API Key missing");let o={personalizations:[{to:Array.isArray(t.to)?t.to.map(n=>({email:n})):[{email:t.to}]}],from:{email:e.match(/<(.+)>/)?.[1]||e,name:e.match(/"(.+)"/)?.[1]},subject:t.subject,content:[{type:"text/plain",value:t.text||""},{type:"text/html",value:t.html}],reply_to:r?{email:r}:void 0},a=await fetch("https://api.sendgrid.com/v3/mail/send",{method:"POST",headers:{Authorization:`Bearer ${s}`,"Content-Type":"application/json"},body:JSON.stringify(o)});if(!a.ok){let n=await a.json();throw new Error(`SendGrid Error: ${JSON.stringify(n)}`)}return {success:true}}async sendViaMailgun(e,t,r){let{apiKey:s,domain:o,region:a}=this.config.mailgun||{};if(!s||!o)throw new Error("Mailgun config missing");let n=a==="eu"?"api.eu.mailgun.net":"api.mailgun.net",c=btoa(`api:${s}`),g=new URLSearchParams;g.append("from",e);let d=Array.isArray(t.to)?t.to.join(", "):t.to;g.append("to",d),g.append("subject",t.subject),g.append("html",t.html),t.text&&g.append("text",t.text),r&&g.append("h:Reply-To",r);let p=await fetch(`https://${n}/v3/${o}/messages`,{method:"POST",headers:{Authorization:`Basic ${c}`,"Content-Type":"application/x-www-form-urlencoded"},body:g});if(!p.ok){let m=await p.json();throw new Error(`Mailgun Error: ${JSON.stringify(m)}`)}return p.json()}getTemplates(){return this.templates}async verifyConnection(){if(this.config.provider==="smtp"||this.config.provider==="ses")try{let e=await this.ensureTransporter();if(e)return await e.verify(),!0}catch{return false}return !!(this.config.resend?.apiKey||this.config.sendgrid?.apiKey||this.config.mailgun?.apiKey)}static async fromConfig(e){let t=new u(e);await t.load();let r=t.getEmailConfig();if(!r.provider)return this.fromEnv();let s={provider:r.provider||"smtp",from:r.from||"noreply@example.com",fromName:r.fromName,replyTo:r.replyTo,smtp:r.provider==="smtp"?{host:r.host||"",port:r.port||587,secure:r.secure||false,auth:{user:r.user||"",pass:r.pass||""}}:void 0,resend:r.provider==="resend"?{apiKey:r.pass||""}:void 0,sendgrid:r.provider==="sendgrid"?{apiKey:r.pass||""}:void 0,mailgun:r.provider==="mailgun"?{apiKey:r.pass||"",domain:r.host||"",region:r.secure?"eu":"us"}:void 0,ses:r.provider==="ses"?{accessKeyId:r.user||"",secretAccessKey:r.pass||"",region:r.host||"us-east-1"}:void 0};return new i(s)}static fromEnv(){let e=process.env.EMAIL_PROVIDER||"smtp",t=process.env.SMTP_FROM||process.env.DEFAULT_FROM||"noreply@example.com",r=process.env.SMTP_FROM_NAME||"Kyro CMS",s=process.env.SMTP_REPLY_TO;if(e==="smtp"){let o=process.env.SMTP_HOST,a=process.env.SMTP_USER,n=process.env.SMTP_PASS;return !o||!a||!n?null:new i({provider:"smtp",from:t,fromName:r,replyTo:s,smtp:{host:o,port:parseInt(process.env.SMTP_PORT||"587",10),secure:process.env.SMTP_SECURE==="true",auth:{user:a,pass:n}}})}if(e==="resend"){let o=process.env.RESEND_API_KEY||process.env.SMTP_PASS;return o?new i({provider:"resend",from:t,fromName:r,replyTo:s,resend:{apiKey:o}}):null}if(e==="sendgrid"){let o=process.env.SENDGRID_API_KEY||process.env.SMTP_PASS;return o?new i({provider:"sendgrid",from:t,fromName:r,replyTo:s,sendgrid:{apiKey:o}}):null}if(e==="mailgun"){let o=process.env.MAILGUN_API_KEY||process.env.SMTP_PASS,a=process.env.MAILGUN_DOMAIN||process.env.SMTP_HOST;return !o||!a?null:new i({provider:"mailgun",from:t,fromName:r,replyTo:s,mailgun:{apiKey:o,domain:a,region:process.env.MAILGUN_REGION||(process.env.SMTP_SECURE==="true"?"eu":"us")}})}if(e==="ses"){let o=process.env.AWS_ACCESS_KEY_ID||process.env.SMTP_USER,a=process.env.AWS_SECRET_ACCESS_KEY||process.env.SMTP_PASS,n=process.env.AWS_REGION||process.env.SMTP_HOST||"us-east-1";return !o||!a?null:new i({provider:"ses",from:t,fromName:r,replyTo:s,ses:{accessKeyId:o,secretAccessKey:a,region:n}})}return null}};var v={minLength:12,requireUppercase:true,requireLowercase:true,requireNumbers:true,requireSpecialChars:true,preventReuse:5,maxLength:128},k=class{config;constructor(e={}){this.config={...v,...e};}validate(e){let t=[];return this.config.maxLength&&e.length>this.config.maxLength&&t.push(`Password must not exceed ${this.config.maxLength} characters`),e.length<this.config.minLength&&t.push(`Password must be at least ${this.config.minLength} characters`),this.config.requireUppercase&&!/[A-Z]/.test(e)&&t.push("Password must contain at least one uppercase letter"),this.config.requireLowercase&&!/[a-z]/.test(e)&&t.push("Password must contain at least one lowercase letter"),this.config.requireNumbers&&!/[0-9]/.test(e)&&t.push("Password must contain at least one number"),this.config.requireSpecialChars&&!/[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]/.test(e)&&t.push("Password must contain at least one special character"),["password","123456","12345678","qwerty","abc123","monkey","1234567","letmein","trustno1","dragon","baseball","iloveyou","master","sunshine","ashley","football","password1","shadow","123123","654321"].includes(e.toLowerCase())&&t.push("This password is too common. Please choose a more secure password"),(/^[a-zA-Z]+$/.test(e)||/^[0-9]+$/.test(e))&&t.push("Password must contain a mix of letters, numbers, and/or special characters"),/(.)\1{2,}/.test(e)&&t.push("Password must not contain more than 2 consecutive identical characters"),/^(012|123|234|345|456|567|678|789|890|098|987|876|765|654|543|432|321|210)+$/i.test(e)&&t.push("Password must not contain sequential numbers or letters"),{valid:t.length===0,errors:t}}async checkReuse(e,t,r){return {valid:true,errors:[]}}async isInHistory(e,t,r){for(let s of t)if(await r(e,s))return true;return false}generatePassword(e=16){let t="ABCDEFGHIJKLMNOPQRSTUVWXYZ",r="abcdefghijklmnopqrstuvwxyz",s="0123456789",o="!@#$%^&*()_+-=[]{}|;:,.<>?",a="";a+=t[Math.floor(Math.random()*t.length)],a+=r[Math.floor(Math.random()*r.length)],a+=s[Math.floor(Math.random()*s.length)],a+=o[Math.floor(Math.random()*o.length)];let n=t+r+s+o;for(let c=a.length;c<e;c++)a+=n[Math.floor(Math.random()*n.length)];return a.split("").sort(()=>Math.random()-.5).join("")}getStrength(e){let t=0,r=[];e.length>=8&&(t+=1),e.length>=12&&(t+=1),e.length>=16&&(t+=1),/[a-z]/.test(e)&&(t+=1),/[A-Z]/.test(e)&&(t+=1),/[0-9]/.test(e)&&(t+=1),/[!@#$%^&*()_+\-=\[\]{}|;:,.<>?]/.test(e)&&(t+=1),e.length>8&&(t+=1),e.length>12&&(t+=1);let s=new Set(e).size;s>6&&(t+=1),s>10&&(t+=1);let o;return t<=3?(o="Weak",r.push("Add more characters"),r.push("Include uppercase and lowercase letters")):t<=5?(o="Fair",r.push("Add special characters"),r.push("Consider making it longer")):t<=7?(o="Good",r.push("Consider making it longer for extra security")):o="Strong",{score:t,label:o,feedback:r}}setConfig(e){this.config={...this.config,...e};}getConfig(){return {...this.config}}};
|
|
300
|
+
export{l as a,h as b,y as c,b as d,x as e,_ as f,S as g,T as h,w as i,u as j,E as k,k as l};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
'use strict';var
|
|
1
|
+
'use strict';var chunk5K4YG5DA_cjs=require('./chunk-5K4YG5DA.cjs'),chunkHOP4D5XZ_cjs=require('./chunk-HOP4D5XZ.cjs');async function f(t){let{adminEmail:e,adminPassword:r,adminRole:o="super_admin",tenantId:n,emailConfig:s,sendWelcomeEmail:c=false}=t,a=t.authAdapter||new chunkHOP4D5XZ_cjs.a({path:t.authDbPath||"./data/auth.db"});try{await a.connect?.();}catch{return {success:false,error:"Failed to connect to auth storage"}}let l=new chunk5K4YG5DA_cjs.l().validate(r);if(!l.valid)return await a.disconnect?.(),{success:false,error:`Invalid password: ${l.errors.join(", ")}`};if(await a.findUserByEmail(e))return await a.disconnect?.(),{success:false,error:"Admin user already exists"};try{let i=await a.createUser({email:e,password:r,role:o||"admin",tenantId:n});if(c&&s){let u=new chunk5K4YG5DA_cjs.k(s),A=u.getTemplates().welcome(e.split("@")[0]);await u.send({to:e,...A});}return await a.disconnect?.(),{success:!0,user:i}}catch(i){return await a.disconnect?.(),{success:false,error:i instanceof Error?i.message:"Failed to create admin user"}}}async function y(t,e){return !await t.findUserByEmail(e)}function w(){let t=process.env.KYRO_ADMIN_EMAIL,e=process.env.KYRO_ADMIN_PASSWORD;return !t||!e?null:{authDbPath:process.env.KYRO_AUTH_DB_PATH||"./data/auth.db",adminEmail:t,adminPassword:e,adminRole:process.env.KYRO_ADMIN_ROLE||"super_admin",tenantId:process.env.KYRO_ADMIN_TENANT_ID,emailConfig:process.env.SMTP_HOST?{provider:"smtp",smtp:{host:process.env.SMTP_HOST,port:parseInt(process.env.SMTP_PORT||"587",10),secure:process.env.SMTP_SECURE==="true",auth:{user:process.env.SMTP_USER||"",pass:process.env.SMTP_PASS||""}},from:process.env.SMTP_FROM||"noreply@example.com",fromName:process.env.SMTP_FROM_NAME}:void 0,sendWelcomeEmail:process.env.KYRO_ADMIN_SEND_WELCOME==="true"}}async function T(t){let e=w();if(!e)return null;t&&(e.authAdapter=t);try{if(await e.authAdapter?.connect?.(),await e.authAdapter?.findUserByEmail(e.adminEmail))return await e.authAdapter?.disconnect?.(),{success:!1,error:"Admin user already exists"}}catch{}let r=await f(e);return r.success||console.error(`Bootstrap failed: ${r.error}`),r}async function v(t,e=3,r=2e3){let o="";for(let n=0;n<e;n++){let s=await f(t);if(s.success||(o=s.error||"Unknown error",o.includes("already exists")))return s;n<e-1&&await new Promise(c=>setTimeout(c,r));}return {success:false,error:`Failed after ${e} retries: ${o}`}}exports.a=f;exports.b=y;exports.c=w;exports.d=T;exports.e=v;
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
'use strict';var chunk65G73T7Z_cjs=require('./chunk-65G73T7Z.cjs'),chunkKD7LUCFY_cjs=require('./chunk-KD7LUCFY.cjs'),chunkZUVP4UK7_cjs=require('./chunk-ZUVP4UK7.cjs'),chunkHS2KNFAB_cjs=require('./chunk-HS2KNFAB.cjs'),chunkXTRY75KC_cjs=require('./chunk-XTRY75KC.cjs'),chunkILEZ3NYX_cjs=require('./chunk-ILEZ3NYX.cjs'),chunkNY47CFVP_cjs=require('./chunk-NY47CFVP.cjs'),chunkG3J2EU5D_cjs=require('./chunk-G3J2EU5D.cjs'),chunkWG3UQEV7_cjs=require('./chunk-WG3UQEV7.cjs'),chunkMIOMMB23_cjs=require('./chunk-MIOMMB23.cjs'),chunkFHJJKFAU_cjs=require('./chunk-FHJJKFAU.cjs'),chunkG7SSHELM_cjs=require('./chunk-G7SSHELM.cjs'),zod=require('zod'),graphqlYoga=require('graphql-yoga'),module$1=require('module'),crypto=require('crypto');var _documentCurrentScript=typeof document!=='undefined'?document.currentScript:null;function L(n,e){for(let t of n){if(t.name===e)return true;if("tabs"in t&&t.tabs){for(let s of t.tabs)if(L(s.fields,e))return true}if("fields"in t&&t.fields&&L(t.fields,e))return true}return false}var z=class extends Error{errors;constructor(e){super(`Configuration validation failed:
|
|
2
|
+
${e.join(`
|
|
3
|
+
`)}`),this.name="ConfigValidationError",this.errors=e;}};function X(n){let e=[];if(n.slug?/^[a-z][a-z0-9_-]*$/.test(n.slug)||e.push(`Collection slug "${n.slug}" must be lowercase alphanumeric with dashes`):e.push('Collection is missing a "slug" property'),!n.fields||n.fields.length===0)e.push(`Collection "${n.slug}" has no fields defined`);else {let t=R(n.fields,n.slug);e.push(...t);}if(n.access)for(let[t,s]of Object.entries(n.access))typeof s!="boolean"&&typeof s!="function"&&e.push(`Collection "${n.slug}" has invalid access.${t} (must be boolean or function)`);if(n.admin?.useAsTitle&&(L(n.fields,n.admin.useAsTitle)||e.push(`Collection "${n.slug}" admin.useAsTitle references unknown field "${n.admin.useAsTitle}"`)),n.admin?.defaultColumns)for(let t of n.admin.defaultColumns)L(n.fields,t)||e.push(`Collection "${n.slug}" admin.defaultColumns references unknown field "${t}"`);if(n.upload&&n.upload.fileSize&&n.upload.fileSize<=0&&e.push(`Collection "${n.slug}" upload.fileSize must be positive`),n.versions&&n.versions.maxPerDoc&&n.versions.maxPerDoc<=0&&e.push(`Collection "${n.slug}" versions.maxPerDoc must be positive`),n.auth){let t=n.fields.some(i=>i.name==="email"),s=n.fields.some(i=>i.name==="password");t||e.push(`Collection "${n.slug}" with auth enabled requires an "email" field`),s||e.push(`Collection "${n.slug}" with auth enabled requires a "password" field`);}return e}function J(n){let e=[];if(n.slug?/^[a-z][a-z0-9_-]*$/.test(n.slug)||e.push(`Global slug "${n.slug}" must be lowercase alphanumeric with dashes`):e.push('Global is missing a "slug" property'),!n.fields||n.fields.length===0)e.push(`Global "${n.slug}" has no fields defined`);else {let t=R(n.fields,`global:${n.slug}`);e.push(...t);}return e}function R(n,e){let t=[],s=new Set;for(let i=0;i<n.length;i++){let a=n[i];if(a.type==="row"||a.type==="collapsible"||a.type==="tabs"){if("fields"in a&&a.fields){let r=R(a.fields,e);t.push(...r);}else if("tabs"in a)for(let r of a.tabs){let c=R(r.fields,e);t.push(...c);}continue}let o=a.name;if(!o){t.push(`${e}: Field at index ${i} is missing a "name" property`);continue}if(s.has(o)&&t.push(`${e}: Duplicate field name "${o}"`),s.add(o),/^[a-zA-Z][a-zA-Z0-9_]*$/.test(o)||t.push(`${e}: Field name "${o}" must be alphanumeric with underscores`),!a.type){t.push(`${e}: Field "${o}" is missing a "type" property`);continue}switch(a.type){case "relationship":a.relationTo||t.push(`${e}: Relationship field "${o}" is missing "relationTo"`);break;case "array":if(!a.fields||a.fields.length===0)t.push(`${e}: Array field "${o}" has no fields defined`);else {let r=R(a.fields,`${e}.${o}`);t.push(...r);}break;case "group":if(!a.fields||a.fields.length===0)t.push(`${e}: Group field "${o}" has no fields defined`);else {let r=R(a.fields,`${e}.${o}`);t.push(...r);}break;case "blocks":if(!a.blocks||a.blocks.length===0)t.push(`${e}: Blocks field "${o}" has no blocks defined`);else {let r=Ke(a.blocks,`${e}.${o}`);t.push(...r);}break;case "select":case "radio":if(typeof a.options=="function")break;if((!a.options||a.options.length===0)&&!a.dynamicOptions)t.push(`${e}: ${a.type} field "${o}" has no options defined`);else if(Array.isArray(a.options)){let r=a.options.map(d=>d.value),c=new Set(r);r.length!==c.size&&t.push(`${e}: ${a.type} field "${o}" has duplicate option values`);}break;case "upload":a.relationTo||t.push(`${e}: Upload field "${o}" is missing "relationTo"`);break}"min"in a&&"max"in a&&a.min>a.max&&t.push(`${e}: Field "${o}" has min greater than max`),"minLength"in a&&"maxLength"in a&&a.minLength>a.maxLength&&t.push(`${e}: Field "${o}" has minLength greater than maxLength`),"minRows"in a&&"maxRows"in a&&a.minRows>a.maxRows&&t.push(`${e}: Field "${o}" has minRows greater than maxRows`);}return t}function Ke(n,e){let t=[],s=new Set;for(let i of n){if(!i.slug){t.push(`${e}: Block is missing a "slug" property`);continue}if(s.has(i.slug)&&t.push(`${e}: Duplicate block slug "${i.slug}"`),s.add(i.slug),i.label||t.push(`${e}: Block "${i.slug}" is missing a "label" property`),!i.fields||i.fields.length===0)t.push(`${e}: Block "${i.slug}" has no fields defined`);else {let a=R(i.fields,`${e}.${i.slug}`);t.push(...a);}}return t}function we(n,e=[]){let t=[],s=new Set;for(let i of n)s.has(i.slug)&&t.push(`Duplicate collection slug "${i.slug}"`),s.add(i.slug);for(let i of e)s.has(i.slug)&&t.push(`Duplicate global slug "${i.slug}"`),s.add(i.slug);for(let i of n){let a=X(i);t.push(...a);}for(let i of e){let a=J(i);t.push(...a);}for(let i of n){let a=_(i.fields,n);t.push(...a);}if(t.length>0)throw new z(t)}function _(n,e){let t=[],s=new Set(e.map(i=>i.slug));for(let i of n){if(i.type==="relationship"){let a=Array.isArray(i.relationTo)?i.relationTo:[i.relationTo];for(let o of a)o!=="*"&&!s.has(o)&&console.warn(`[Kyro Config Warning]: Relationship field "${i.name}" references unknown collection "${o}". Select options will not be available until this collection is registered.`);}if(i.type==="upload"){let a=Array.isArray(i.relationTo)?i.relationTo:[i.relationTo];for(let o of a)s.has(o)||t.push(`Upload field "${i.name}" references unknown collection "${o}"`);}if("fields"in i&&i.fields){let a=_(i.fields,e);t.push(...a);}if("tabs"in i)for(let a of i.tabs){let o=_(a.fields,e);t.push(...o);}if("blocks"in i)for(let a of i.blocks){let o=_(a.fields,e);t.push(...o);}}return t}function A(n){switch(n.type){case "text":return Me(n);case "number":return Ve(n);case "checkbox":return Be(n);case "date":return He(n);case "email":return We(n);case "password":return ze(n);case "textarea":return Xe(n);case "select":return Je(n);case "radio":return Ye(n);case "color":return Qe(n);case "richtext":return et(n);case "json":return tt(n);case "code":return st(n);case "upload":return Re(n);case "image":return Re(n);case "markdown":return nt(n);case "relationship":return Ne(n);case "relationship-block":return Ne(n);case "array":return it(n);case "list":return at(n);case "group":return ot(n);case "blocks":return rt(n);case "row":return lt(n);case "collapsible":return ct(n);case "tabs":return dt(n);default:return zod.z.any()}}function Me(n){let e=zod.z.string();return n.minLength&&(e=e.min(n.minLength)),n.maxLength&&(e=e.max(n.maxLength)),n.pattern&&(e=e.regex(new RegExp(n.pattern))),n.variant==="email"&&(e=e.email()),n.variant==="url"&&(e=e.url()),n.hasMany&&(e=zod.z.array(e)),n.required||(e=e.optional().nullable()),n.validate&&(e=T(e,n.validate)),e}function Ve(n){let e=n.integer?zod.z.coerce.number().int():zod.z.coerce.number();return n.min!==void 0&&(e=e.min(n.min)),n.max!==void 0&&(e=e.max(n.max)),n.step&&(e=e.refine(t=>Number.isInteger(t/n.step),`Value must be divisible by ${n.step}`)),n.hasMany&&(e=zod.z.array(e)),n.required||(e=e.optional().nullable()),n.validate&&(e=T(e,n.validate)),e}function Be(n){let e=zod.z.boolean();return n.required||(e=e.optional().nullable()),n.validate&&(e=T(e,n.validate)),e}function He(n){let e=zod.z.string().refine(t=>!isNaN(Date.parse(t)),"Invalid date format");return n.minDate&&(e=e.refine(t=>new Date(t)>=new Date(n.minDate),`Date must be after ${n.minDate}`)),n.maxDate&&(e=e.refine(t=>new Date(t)<=new Date(n.maxDate),`Date must be before ${n.maxDate}`)),n.required||(e=e.optional().nullable()),n.validate&&(e=T(e,n.validate)),e}function We(n){let e=zod.z.string().email("Invalid email");return n.required||(e=e.optional().nullable()),n.validate&&(e=T(e,n.validate)),e}function ze(n){let e=zod.z.string().min(6,"Password must be at least 6 characters");return n.required||(e=e.optional().nullable()),n.validate&&(e=T(e,n.validate)),e}function Xe(n){let e=zod.z.string();return n.minLength&&(e=e.min(n.minLength)),n.maxLength&&(e=e.max(n.maxLength)),n.required||(e=e.optional().nullable()),n.validate&&(e=T(e,n.validate)),e}function Je(n){let e;if(Array.isArray(n.options)&&n.options.length>0){let t=n.options.map(s=>s.value);n.hasMany?e=zod.z.array(zod.z.enum(t)):e=zod.z.enum(t);}else e=n.hasMany?zod.z.array(zod.z.string()):zod.z.string();return n.required||(e=e.optional().nullable()),n.validate&&(e=T(e,n.validate)),e}function Ye(n){let e;if(Array.isArray(n.options)&&n.options.length>0){let t=n.options.map(s=>s.value);e=zod.z.enum(t);}else e=zod.z.string();return n.required||(e=e.optional().nullable()),n.validate&&(e=T(e,n.validate)),e}function Qe(n){let e=zod.z.string();return n.format==="hex"&&(e=e.regex(/^#[0-9A-Fa-f]{6}$/)),n.format==="rgb"&&(e=e.regex(/^rgb\(\s*\d{1,3}\s*,\s*\d{1,3}\s*,\s*\d{1,3}\s*\)$/)),n.format==="hsl"&&(e=e.regex(/^hsl\(\s*\d{1,3}\s*,\s*\d{1,3}%\s*,\s*\d{1,3}%\s*\)$/)),n.required||(e=e.optional().nullable()),n.validate&&(e=T(e,n.validate)),e}function et(n){let e=zod.z.array(zod.z.record(zod.z.any()));return n.required||(e=e.optional().nullable()),n.validate&&(e=T(e,n.validate)),e}function tt(n){let e=zod.z.union([zod.z.record(zod.z.any()),zod.z.array(zod.z.any())]);return n.required||(e=e.optional().nullable()),n.validate&&(e=T(e,n.validate)),e}function st(n){let e=zod.z.string();return n.required||(e=e.optional().nullable()),n.validate&&(e=T(e,n.validate)),e}function Re(n){let e;if(n.relationTo){let t=zod.z.object({id:zod.z.string(),url:zod.z.string().optional(),filename:zod.z.string().optional(),mimeType:zod.z.string().optional()});e=zod.z.union([zod.z.string(),t]);}else e=zod.z.string();return n.hasMany&&(e=zod.z.array(e)),n.required||(e=e.optional().nullable()),n.validate&&(e=T(e,n.validate)),e}function nt(n){let e=zod.z.string();return n.required||(e=e.optional().nullable()),n.validate&&(e=T(e,n.validate)),e}function Ne(n){let e;return Array.isArray(n.relationTo)?e=zod.z.object({relationTo:zod.z.enum(n.relationTo),value:zod.z.string()}):e=zod.z.union([zod.z.string(),zod.z.object({relationTo:zod.z.string(),value:zod.z.string()})]),n.hasMany&&(e=zod.z.array(e)),n.required||(e=e.optional().nullable()),n.validate&&(e=T(e,n.validate)),e}function it(n){let e=zod.z.object(Object.fromEntries(n.fields.filter(s=>s.name).map(s=>[s.name,A(s)]))).passthrough(),t=zod.z.array(e);return n.minRows&&(t=t.min(n.minRows)),n.maxRows&&(t=t.max(n.maxRows)),n.required||(t=t.optional().nullable()),n.validate&&(t=T(t,n.validate)),t}function at(n){let e=zod.z.array(zod.z.string());return n.required||(e=e.optional().nullable()),e}function ot(n){let e=zod.z.object(Object.fromEntries(n.fields.filter(t=>t.name).map(t=>[t.name,A(t)])));return n.required?e:e.optional().nullable()}function rt(n){let e=n.blocks||[];e.map(a=>zod.z.object({blockType:zod.z.literal(a.slug),...Object.fromEntries(a.fields.filter(o=>o.name).map(o=>[o.name,A(o)]))}));let s=e.map(a=>a.slug),i;if(s.length>0){let a=zod.z.object({blockType:zod.z.enum(s)}).catchall(zod.z.any()),o=zod.z.object({blockType:zod.z.string()}).catchall(zod.z.any());i=zod.z.array(zod.z.union([a,o,zod.z.record(zod.z.any())]));}else i=zod.z.array(zod.z.union([zod.z.object({blockType:zod.z.string()}).catchall(zod.z.any()),zod.z.record(zod.z.any())]));return n.minRows&&(i=i.min(n.minRows)),n.maxRows&&(i=i.max(n.maxRows)),n.required||(i=i.optional().nullable()),n.validate&&(i=T(i,n.validate)),i}function lt(n){return zod.z.object(Object.fromEntries(n.fields.filter(t=>t.name).map(t=>[t.name,A(t)])))}function ct(n){return zod.z.object(Object.fromEntries(n.fields.filter(t=>t.name).map(t=>[t.name,A(t)])))}function dt(n){let e={};for(let t of n.tabs)for(let s of t.fields)s.name&&(e[s.name]=A(s));return zod.z.object(e).passthrough().optional()}function T(n,e){return n.refine(async t=>await e(t,{required:false})===true,{message:"Custom validation failed"})}function F(n){let e={};for(let t of n)if(t.type==="tabs"&&"tabs"in t){let s={};for(let i of t.tabs){let a=F(i.fields);Object.assign(s,a);}t.name?e[t.name]=zod.z.object(s).passthrough().optional():Object.assign(e,s);}else if(t.type==="row"&&"fields"in t){let s=F(t.fields);t.name?e[t.name]=zod.z.object(s).passthrough().optional():Object.assign(e,s);}else if(t.type==="collapsible"&&"fields"in t){let s=F(t.fields);t.name?e[t.name]=zod.z.object(s).passthrough().optional():Object.assign(e,s);}else {if(!t.name)continue;e[t.name]=A(t);}return e}function v(n){let e={};for(let t of n)if(t.type==="tabs"&&"tabs"in t){let s={};for(let i of t.tabs){let a=v(i.fields);Object.assign(s,a);}t.name?e[t.name]=zod.z.object(s).passthrough().optional().nullable():Object.assign(e,s);}else if(t.type==="row"&&"fields"in t){let s=v(t.fields);t.name?e[t.name]=zod.z.object(s).passthrough().optional().nullable():Object.assign(e,s);}else if(t.type==="collapsible"&&"fields"in t){let s=v(t.fields);t.name?e[t.name]=zod.z.object(s).passthrough().optional().nullable():Object.assign(e,s);}else if(t.type==="group"&&"fields"in t)t.name?e[t.name]=zod.z.object(v(t.fields)).passthrough().optional().nullable():Object.assign(e,v(t.fields));else {if(!t.name)continue;e[t.name]=A(t).optional().nullable();}return e}function De(n){let e=F(n.fields);return n.timestamps&&(e.createdAt=zod.z.string().optional(),e.updatedAt=zod.z.string().optional()),n.tenantScoped&&(e.tenantId=zod.z.string().optional()),e.id=zod.z.string().optional(),zod.z.object(e).passthrough()}function Fe(n){let e=F(n.fields);return zod.z.object(e).passthrough()}function ke(n){let e={};for(let t of n.fields)if(t.name)if(t.type==="tabs"&&"tabs"in t){let s={};for(let i of t.tabs)for(let a of i.fields)a.name&&(s[a.name]=A(a).optional().nullable());e[t.name]=zod.z.object(s).optional().nullable();}else if(t.type==="row"&&"fields"in t){let s={};for(let i of t.fields)i.name&&(s[i.name]=A(i).optional().nullable());Object.assign(e,s);}else t.type==="collapsible"&&"fields"in t?e[t.name]=zod.z.object(v(t.fields)).optional().nullable():t.type==="group"&&"fields"in t?e[t.name]=zod.z.object(v(t.fields)).optional().nullable():e[t.name]=A(t).optional().nullable();return zod.z.object(e).passthrough()}function Ie(n){let e={};for(let t of n.fields)t.name&&(e[t.name]=zod.z.object({equals:zod.z.any().optional(),not_equals:zod.z.any().optional(),in:zod.z.array(zod.z.any()).optional(),not_in:zod.z.array(zod.z.any()).optional(),greater_than:zod.z.number().optional(),greater_than_equal:zod.z.number().optional(),less_than:zod.z.number().optional(),less_than_equal:zod.z.number().optional(),like:zod.z.string().optional(),not_like:zod.z.string().optional(),contains:zod.z.string().optional(),exists:zod.z.boolean().optional()}).optional());return e.AND=zod.z.array(zod.z.lazy(()=>zod.z.object(e))).optional(),e.OR=zod.z.array(zod.z.lazy(()=>zod.z.object(e))).optional(),zod.z.object(e).optional()}function Pe(n){let e=F(n.fields);return e.id=zod.z.string().optional(),zod.z.object(e).passthrough()}function Oe(n){let e={};for(let t of n.fields)if(t.name)if(t.type==="tabs"&&"tabs"in t){let s={};for(let i of t.tabs)for(let a of i.fields)a.name&&(s[a.name]=A(a).optional().nullable());e[t.name]=zod.z.object(s).optional().nullable();}else t.type==="collapsible"&&"fields"in t?e[t.name]=zod.z.object(v(t.fields)).optional().nullable():t.type==="group"&&"fields"in t?e[t.name]=zod.z.object(v(t.fields)).optional().nullable():e[t.name]=A(t).optional().nullable();return zod.z.object(e).passthrough()}var I=class{storageProviders=chunkXTRY75KC_cjs.f();collections=new Map;globals=new Map;plugins=[];schemaCache=new Map;initialized=false;addCollection(e){if(this.initialized)throw new Error("Cannot add collections after Registry has been initialized");if(this.collections.has(e.slug)){console.warn(`[Registry] Duplicate collection slug "${e.slug}" \u2014 skipping`);return}let t={...e,fields:[...e.fields]};for(let i of this.plugins){let a=i.extensions?.collections?.find(o=>o.slug===t.slug);a&&(t={...t,...a.config,fields:[...t.fields,...a.config.fields||[]]});}if(t.seo){let i=chunkKD7LUCFY_cjs.a(),a=t.fields.findIndex(o=>o.type==="tabs");if(a!==-1){let o=t.fields[a];t.fields[a]={...o,tabs:[...o.tabs,{label:"SEO Settings",fields:i.fields}]};}else t.fields.push(i);}t.fields=this.applyFieldDefaults(t);let s=X(t);if(s.length>0)throw new Error(`Invalid collection config: ${s.join(", ")}`);this.collections.set(t.slug,t),this.clearSchemaCache(t.slug);}addCollections(e){for(let t of e)this.addCollection(t);}getCollection(e){return this.collections.get(e)}getCollections(){return Array.from(this.collections.values())}getCollectionSlugs(){return Array.from(this.collections.keys())}hasCollection(e){return this.collections.has(e)}removeCollection(e){if(this.initialized)throw new Error("Cannot remove collections after Registry has been initialized");return this.clearSchemaCache(e),this.collections.delete(e)}addGlobal(e){if(this.initialized)throw new Error("Cannot add globals after Registry has been initialized");this._addGlobalUnsafe(e);}addGlobalPostInit(e){this.globals.has(e.slug)&&this.globals.delete(e.slug),this._addGlobalUnsafe(e);}_addGlobalUnsafe(e){if(this.globals.has(e.slug)){console.warn(`[Registry] Duplicate global slug "${e.slug}" \u2014 skipping`);return}let t=J(e);if(t.length>0)throw new Error(`Invalid global config: ${t.join(", ")}`);let s={...e};for(let i of this.plugins){let a=i.extensions?.globals?.find(o=>o.slug===s.slug);a&&(s={...s,...a.config,fields:[...s.fields||[],...a.config.fields||[]]});}this.globals.set(s.slug,s),this.clearSchemaCache(`global:${s.slug}`);}addGlobals(e){for(let t of e)this.addGlobal(t);}getGlobal(e){return this.globals.get(e)}getGlobals(){return Array.from(this.globals.values())}getGlobalSlugs(){return Array.from(this.globals.keys())}hasGlobal(e){return this.globals.has(e)}removeGlobal(e){if(this.initialized)throw new Error("Cannot remove globals after Registry has been initialized");return this.clearSchemaCache(`global:${e}`),this.globals.delete(e)}addPlugin(e){if(this.initialized)throw new Error("Cannot add plugins after Registry has been initialized");this.plugins.push(e);}getPlugins(){return [...this.plugins]}getZodSchema(e){let t=this.schemaCache.get(e);if(t)return t;let s=this.collections.get(e);if(s){let a=De(s);return this.schemaCache.set(e,a),a}let i=this.globals.get(e);if(i){let a=Pe(i);return this.schemaCache.set(`global:${e}`,a),a}throw new Error(`No collection or global found with slug "${e}"`)}getCreateZodSchema(e){let t=`${e}:create`,s=this.schemaCache.get(t);if(s)return s;let i=this.collections.get(e);if(i){let a=Fe(i);return this.schemaCache.set(t,a),a}throw new Error(`No collection found with slug "${e}"`)}getUpdateZodSchema(e){let t=`${e}:update`,s=this.schemaCache.get(t);if(s)return s;let i=this.collections.get(e);if(i){let o=ke(i);return this.schemaCache.set(t,o),o}let a=this.globals.get(e);if(a){let o=Oe(a);return this.schemaCache.set(`global:${e}:update`,o),o}throw new Error(`No collection or global found with slug "${e}"`)}getWhereZodSchema(e){let t=`${e}:where`,s=this.schemaCache.get(t);if(s)return s;let i=this.collections.get(e);if(i){let a=Ie(i);return this.schemaCache.set(t,a),a}throw new Error(`No collection found with slug "${e}"`)}getFieldZodSchema(e){return A(e)}clearSchemaCache(e){this.schemaCache.delete(e),this.schemaCache.delete(`${e}:create`),this.schemaCache.delete(`${e}:update`),this.schemaCache.delete(`${e}:where`);}applyFieldDefaults(e){let t=[...e.fields];return t.some(s=>s.name==="id")||t.unshift({name:"id",type:"text",admin:{readOnly:true,hidden:true}}),e.tenantScoped&&!t.some(s=>s.name==="tenantId")&&t.push({name:"tenantId",type:"text",required:true,admin:{readOnly:true,hidden:true}}),e.timestamps&&!t.some(s=>s.name==="createdAt")&&(t.push({name:"createdAt",type:"date",admin:{readOnly:true,hidden:true}}),t.push({name:"updatedAt",type:"date",admin:{readOnly:true,hidden:true}})),e.versions?.drafts&&!t.some(s=>s.name==="status")&&t.push({name:"status",type:"select",options:[{value:"draft",label:"Draft"},{value:"published",label:"Published"}],admin:{readOnly:true,hidden:true}}),e.auth&&!t.some(s=>s.name==="password")&&t.push({name:"password",type:"password",required:true,admin:{hidden:true}}),t}getFields(e){let t=this.collections.get(e);if(t)return t.fields;let s=this.globals.get(e);if(s)return s.fields;throw new Error(`No collection or global found with slug "${e}"`)}getFieldMap(e){let t=this.getFields(e),s=new Map,i=a=>{for(let o of a){if(o.name&&s.set(o.name,o),"fields"in o&&o.fields&&i(o.fields),"tabs"in o)for(let r of o.tabs)i(r.fields);if("blocks"in o)for(let r of o.blocks)i(r.fields);}};return i(t),s}getVisibleFields(e){return this.getFields(e).filter(s=>!s.admin?.hidden)}validate(){let e=this.getCollections(),t=this.getGlobals();we(e,t);}async init(e){this.validate();for(let t of this.plugins){t.init&&await t.init(e||this);let s=t.collections||[];for(let a of s)a.slug&&!this.hasCollection(a.slug)&&this.addCollection(a);let i=t.globals||[];for(let a of i)a.slug&&!this.hasGlobal(a.slug)&&this.addGlobal(a);}this.initialized=true;}isInitialized(){return this.initialized}getPaginationDefaults(e){let t=this.collections.get(e);return {defaultLimit:t?.admin?.pagination?.defaultLimit||10,limits:t?.admin?.pagination?.limits||[10,25,50,100]}}getDefaultSort(e){let s=this.collections.get(e)?.admin?.useAsTitle;return s||"createdAt"}getDefaultColumns(e){let t=this.collections.get(e);return t?.admin?.defaultColumns?t.admin.defaultColumns:this.getVisibleFields(e).slice(0,4).map(i=>i.name)}getAdminTitle(e){let t=this.collections.get(e);return t?.label||t?.admin?.description||e}getAdminLabel(e){let t=this.collections.get(e);return t?.singularLabel||t?.label||e}getAdminGroup(e){return this.collections.get(e)?.admin?.group}getStats(){let e=0;for(let t of this.collections.values())e+=t.fields.length;for(let t of this.globals.values())e+=t.fields.length;return {collections:this.collections.size,globals:this.globals.size,plugins:this.plugins.length,fields:e}}toJSON(){return {collections:this.getCollections(),globals:this.getGlobals()}}},k=null;function ut(){return k||(k=new I),k}function pt(){k=null;}function Y(){return k=new I,k}var x=class{name;displayName;adminEntry;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}},j=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[s,i]of Object.entries(t))if(Array.isArray(i))for(let a of i)this.registerHook(s,a);}unregister(e){let t=this.plugins.get(e);if(!t)return;let s=t.getHooks?.()||{};for(let[i,a]of Object.entries(s))if(Array.isArray(a))for(let o of a)this.unregisterHook(i,o);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 s=this.hooks.get(e);if(s){let i=s.indexOf(t);i>-1&&s.splice(i,1);}}async executeHook(e,t){let s=this.hooks.get(e)||[],i=t;for(let a of s)try{let o=await a({...t,data:i});o!==void 0&&(i=o);}catch(o){console.error(`[PluginManager] Error in hook "${e}":`,o);}return i}getAllCollections(){let e=[];for(let t of this.plugins.values()){let s=t.getCollections?.()||[];e.push(...s);}return e}getAllGlobals(){let e=[];for(let t of this.plugins.values()){let s=t.getGlobals?.()||[];e.push(...s);}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}},Q=class extends x{constructor(){super("seo"),this.displayName="Core SEO",this.description="Advanced SEO features including sitemaps, robots.txt, and structured data",this.adminEntry="@kyro-cms/admin/plugins/seo-admin",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"}]});}},ee=class extends x{constructor(){super("analytics"),this.displayName="Core Analytics",this.description="Built-in privacy-friendly analytics and dashboards",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={};}},te=class extends x{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={};}},se=class extends x{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={};}},ne=class extends x{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"}]}]}]}]});}},_t={SEO:Q,Analytics:ee,Comments:te,Reviews:se,Wishlist:ne};var ft={aws:{type:"aws",configKey:"s3",displayName:"S3 Compatible (AWS, Backblaze, Wasabi, etc.)",configFields:[{name:"bucket",type:"text",label:"Bucket Name",required:true},{name:"region",type:"text",label:"Region",defaultValue:"us-east-1",admin:{placeholder:"us-east-1"}},{name:"accessKeyId",type:"text",label:"Access Key ID",required:true},{name:"secretAccessKey",type:"password",label:"Secret Access Key",required:true},{name:"endpoint",type:"text",label:"Endpoint URL",admin:{placeholder:"https://s3.custom.com"}},{name:"cdnUrl",type:"text",label:"CDN URL",admin:{placeholder:"https://cdn.example.com"}},{name:"prefix",type:"text",label:"Path Prefix",admin:{placeholder:"uploads"}}]},r2:{type:"r2",configKey:"r2",displayName:"Cloudflare R2",configFields:[{name:"accountId",type:"text",label:"Account ID",required:true,admin:{placeholder:"Your Cloudflare Account ID"}},{name:"accessKeyId",type:"text",label:"Access Key ID",required:true},{name:"secretAccessKey",type:"password",label:"Secret Access Key",required:true},{name:"bucket",type:"text",label:"Bucket Name",required:true},{name:"publicDevUrl",type:"text",label:"Public Dev URL ID",admin:{placeholder:"pub-xxxxxxxxxxxxxxxx",description:"Enter ONLY the ID (e.g., pub-b8d8c4cc8bcf4d868ddd95efc1b305aa). Do NOT include https:// or the full URL. Found in R2 Dashboard \u2192 Public Dev URL."}},{name:"cdnUrl",type:"text",label:"Custom CDN URL",admin:{placeholder:"https://assets.example.com (optional)"}},{name:"prefix",type:"text",label:"Path Prefix",admin:{placeholder:"uploads (optional)",description:"Optional prefix for all object keys. Do not use '/' as prefix."}}]},gcs:{type:"gcs",configKey:"gcs",displayName:"Google Cloud Storage",configFields:[{name:"bucket",type:"text",label:"Bucket Name",required:true},{name:"projectId",type:"text",label:"Project ID"},{name:"clientEmail",type:"text",label:"Client Email"},{name:"privateKey",type:"password",label:"Private Key"},{name:"cdnUrl",type:"text",label:"CDN URL"},{name:"prefix",type:"text",label:"Path Prefix"}]},digitalocean:{type:"digitalocean",configKey:"digitalocean",displayName:"DigitalOcean Spaces",configFields:[{name:"bucket",type:"text",label:"Bucket Name",required:true},{name:"region",type:"text",label:"Region",defaultValue:"nyc3"},{name:"accessKeyId",type:"text",label:"Access Key ID",required:true},{name:"secretAccessKey",type:"password",label:"Secret Access Key",required:true},{name:"cdnUrl",type:"text",label:"CDN URL"},{name:"prefix",type:"text",label:"Path Prefix"}]},backblaze:{type:"backblaze",configKey:"backblaze",displayName:"Backblaze B2",configFields:[{name:"bucket",type:"text",label:"Bucket Name",required:true},{name:"accountId",type:"text",label:"Account ID"},{name:"applicationKeyId",type:"text",label:"Application Key ID",required:true},{name:"applicationKey",type:"password",label:"Application Key",required:true},{name:"cdnUrl",type:"text",label:"CDN URL"},{name:"prefix",type:"text",label:"Path Prefix"}]},wasabi:{type:"wasabi",configKey:"wasabi",displayName:"Wasabi",configFields:[{name:"bucket",type:"text",label:"Bucket Name",required:true},{name:"region",type:"text",label:"Region",defaultValue:"us-east-1"},{name:"accessKeyId",type:"text",label:"Access Key ID",required:true},{name:"secretAccessKey",type:"password",label:"Secret Access Key",required:true},{name:"cdnUrl",type:"text",label:"CDN URL"},{name:"prefix",type:"text",label:"Path Prefix"}]}};function yt(n,e){switch(n){case "r2":return e?.endpoint||`https://${e?.accountId||""}.r2.cloudflarestorage.com`;case "digitalocean":return e?.endpoint||`https://${e?.region||"nyc3"}.digitaloceanspaces.com`;case "backblaze":return e?.endpoint||"https://s3.backblazeb2.com";case "wasabi":return e?.endpoint||`https://s3.${e?.region||"us-east-1"}.wasabisys.com`;default:return e?.endpoint}}function $e(n,e){return {provider:n,bucket:e?.bucket||"",region:e?.region||"us-east-1",accessKeyId:e?.accessKeyId||e?.clientEmail||e?.applicationKeyId||"",secretAccessKey:e?.secretAccessKey||e?.privateKey||e?.applicationKey||"",endpoint:yt(n,e),cdnUrl:e?.cdnUrl,prefix:e?.prefix,accountId:e?.accountId,publicDevUrl:e?.publicDevUrl}}function gt(n,e,t){let s=t[e.configKey]||{};return $e(n,s)}function ht(n,e,t){let s=t?.[e.configKey]||t;return $e(n,s)}var ie=class extends x{constructor(){super("@kyro-cms/storage-s3"),this.version="1.0.0",this.description="S3-compatible storage (AWS R2 GCS DigitalOcean Backblaze Wasabi)";}async init(e){let t=e.registry?.storageProviders;if(!t)return;let s=this.name;for(let i of Object.values(ft))t.register({type:i.type,displayName:i.displayName,pluginName:s,configKey:i.configKey,configFields:i.configFields,extractConfig:a=>gt(i.type,i,a),extractRawConfig:a=>ht(i.type,i,a),factory:a=>chunkXTRY75KC_cjs.a(a)});}},_e=new ie;var ae=class extends x{constructor(){super("@kyro-cms/storage-cloudinary"),this.version="1.0.0",this.description="Cloudinary image and video storage";}async init(e){let t=e.registry?.storageProviders;t&&t.register({type:"cloudinary",displayName:"Cloudinary",pluginName:this.name,configKey:"cloudinary",configFields:[{name:"cloudName",type:"text",label:"Cloud Name",required:true},{name:"apiKey",type:"text",label:"API Key",required:true},{name:"apiSecret",type:"password",label:"API Secret",required:true},{name:"folder",type:"text",label:"Folder",admin:{placeholder:"Optional folder path"}},{name:"uploadPreset",type:"text",label:"Upload Preset (optional)",admin:{placeholder:"Leave empty for signed uploads",description:"If not set, uploads will be signed with API Secret"}}],extractConfig:s=>({cloudName:s.cloudinary?.cloudName||"",apiKey:s.cloudinary?.apiKey||"",apiSecret:s.cloudinary?.apiSecret||"",folder:s.cloudinary?.folder,uploadPreset:s.cloudinary?.uploadPreset}),extractRawConfig:s=>{let i=s?.cloudinary||s;return {cloudName:i?.cloudName||"",apiKey:i?.apiKey||"",apiSecret:i?.apiSecret||"",folder:i?.folder,uploadPreset:i?.uploadPreset}},factory:s=>chunkXTRY75KC_cjs.b(s)});}},Le=new ae;var oe=class extends x{constructor(){super("@kyro-cms/storage-ftp"),this.version="1.0.0",this.description="FTP/SFTP storage provider";}async init(e){let t=e.registry?.storageProviders;t&&t.register({type:"ftp",displayName:"FTP",pluginName:this.name,configKey:"ftp",configFields:[{name:"host",type:"text",label:"Host",required:true,admin:{placeholder:"ftp.example.com"}},{name:"port",type:"number",label:"Port",defaultValue:21,admin:{placeholder:"21 for FTP"}},{name:"user",type:"text",label:"Username",required:true},{name:"password",type:"password",label:"Password",required:true},{name:"secure",type:"checkbox",label:"Use TLS/SSL",defaultValue:false,admin:{description:"Enable TLS/SSL for secure connections (FTP only)"}},{name:"baseUrl",type:"text",label:"Base URL",required:true,admin:{placeholder:"https://files.example.com"}},{name:"prefix",type:"text",label:"Path Prefix",admin:{placeholder:"uploads"}}],extractConfig:s=>({host:s.ftp?.host||"",port:s.ftp?.port||21,user:s.ftp?.user||"",password:s.ftp?.password||"",secure:s.ftp?.secure||false,baseUrl:s.ftp?.baseUrl||"",prefix:s.ftp?.prefix,type:"ftp"}),extractRawConfig:s=>{let i=s?.ftp||s;return {host:i?.host||"",port:i?.port||21,user:i?.user||"",password:i?.password||"",secure:i?.secure||false,baseUrl:i?.baseUrl||"",prefix:i?.prefix,type:"ftp"}},factory:s=>chunkXTRY75KC_cjs.c(s)});}},je=new oe;var bt=[_e,Le,je];function N(n,e,t){let s=e.split(".");if(s.length===0)return false;let i=s[0],a=s.slice(1).join(".");for(let o of n)if(o.name===i)if(a){if(o.fields&&Array.isArray(o.fields))return N(o.fields,a,t);if(o.type==="tabs"&&o.tabs&&Array.isArray(o.tabs)){for(let r of o.tabs)if(r.fields&&Array.isArray(r.fields)&&N(r.fields,a,t))return true;return false}if(o.type==="blocks"&&o.blocks&&Array.isArray(o.blocks)){let r=a.split(".")[0],c=a.split(".").slice(1).join(".");if(!c)return false;for(let d of o.blocks)if(d.slug===r&&d.fields&&Array.isArray(d.fields))return N(d.fields,c,t);return false}return o.type==="array"&&o.fields&&Array.isArray(o.fields)?N(o.fields,a,t):false}else return Object.assign(o,t),true;for(let o of n)if(!o.name||o.type==="tabs"||o.type==="row"||o.type==="collapsible"){if(o.fields&&Array.isArray(o.fields)&&N(o.fields,e,t))return true;if(o.type==="tabs"&&o.tabs&&Array.isArray(o.tabs)){for(let c of o.tabs)if(c.fields&&Array.isArray(c.fields)&&N(c.fields,e,t))return true}}return a?false:(n.push({name:i,...t}),true)}function Tt(n,e){if(e)for(let t of n){let s=e[t.slug];if(s){let{fields:i,...a}=s;if(t.admin={...t.admin,...a},i&&t.fields&&Array.isArray(t.fields))for(let[o,r]of Object.entries(i))N(t.fields,o,r);}}}var re=class{registry;db;pubsub;webhookService;settings;pluginManager;wsServer;config;constructor(e){this.config=e,this.registry=Y(),this.db=e.adapter,this.pubsub=new chunkG3J2EU5D_cjs.b(this.registry),this.webhookService=chunkILEZ3NYX_cjs.o(this.db),this.pluginManager=new j;for(let t of bt)this.pluginManager.register(t),this.registry.addPlugin(t);if(e.plugins)for(let t of e.plugins)this.pluginManager.register(t),this.registry.addPlugin(t);e.collections&&e.admin?.collectionOverrides&&Tt(e.collections,e.admin.collectionOverrides),e.collections&&this.registry.addCollections(e.collections),e.globals&&this.registry.addGlobals(e.globals);}async init(){await this.pluginManager.executeHook("beforeInit",{kyro:this}),await this.registry.init(this),await this.pluginManager.executeHook("afterInit",{kyro:this}),this.registry.addGlobalPostInit(chunk65G73T7Z_cjs.a);let e={slug:"plugin-settings",admin:{hidden:true},fields:[{name:"states",type:"json"}]};if(this.registry.addGlobalPostInit(e),!this.db)throw new Error("Database adapter is null \u2014 failed to load at startup. Check the server console for the exact error.");let t={slug:chunkNY47CFVP_cjs.d,fields:[{name:"userId",type:"text",required:true},{name:"name",type:"text",required:true},{name:"key",type:"text",required:true},{name:"keyPrefix",type:"text",required:true},{name:"permissions",type:"json"},{name:"lastUsedAt",type:"date"},{name:"expiresAt",type:"date"}]},s={slug:chunkILEZ3NYX_cjs.f,fields:[{name:"name",type:"text",required:true},{name:"url",type:"text",required:true},{name:"events",type:"json",required:true},{name:"collections",type:"json"},{name:"status",type:"text",required:true},{name:"secret",type:"text"},{name:"headers",type:"json"},{name:"action",type:"text"},{name:"config",type:"json"},{name:"lastTriggered",type:"date"},{name:"lastError",type:"text"}]},i={slug:chunkILEZ3NYX_cjs.g,fields:[{name:"webhookId",type:"text",required:true},{name:"event",type:"text",required:true},{name:"payload",type:"json",required:true},{name:"attempt",type:"number",required:true},{name:"status",type:"text",required:true},{name:"responseStatus",type:"number"},{name:"responseBody",type:"text"},{name:"error",type:"text"},{name:"duration",type:"number"},{name:"deliveredAt",type:"date"},{name:"nextRetryAt",type:"date"}]},a=this.registry.getGlobals();if(this.db instanceof chunkWG3UQEV7_cjs.c&&this.db.dialect==="postgres"){let o=this.db,r=chunkNY47CFVP_cjs.d.replace(/-/g,"_");o.schema[r]||(o.schema[r]=chunkMIOMMB23_cjs.g);}await this.db.init([...this.registry.getCollections(),t,s,i],a),await this.loadPluginState(),this.pubsub.autoRegisterHooks();}async loadSettings(){if(this.settings)return this.settings;try{let e=await this.db.findOne({collection:"_globals_access-settings",where:{},draft:!0});e&&(this.settings={access:e});}catch{}return this.settings||{}}async loadPluginState(){let e=this.registry.storageProviders,t=e.getAllPluginNames(),s={};try{let i=await this.db.findOne({collection:"_globals_plugin-settings",where:{},draft:!0});i&&i.states&&(s=i.states);}catch{}for(let i of t)s[i]!==void 0&&e.setPluginEnabled(i,s[i]);}getREST(e){let t=typeof this.config.auth=="object"?this.config.auth:null,s=t?.secret,i=t?.checkSession!==false;return chunkXTRY75KC_cjs.t({registry:this.registry,db:this.db,authSecret:s,authAdapter:this.config.authAdapter,checkSession:i,...e,cors:this.config.cors,webhookService:this.webhookService,settings:this.settings})}getGraphQL(e){let t=chunkHS2KNFAB_cjs.c({registry:this.registry,db:this.db,settings:this.settings});return {fetch:graphqlYoga.createYoga({schema:t,context:async({request:i})=>{let a=chunkNY47CFVP_cjs.f(i),o,r;if(a&&this.db){let d=await chunkNY47CFVP_cjs.e(a,this.db);d.user&&(o=d.user,r=chunkNY47CFVP_cjs.g(d));}let c=e?.tenantId;return {db:this.db,registry:this.registry,user:o,req:i,tenantId:c,apiKey:r,relationLoader:new chunkHS2KNFAB_cjs.a({db:this.db,tenantId:c,user:o})}},graphiql:this.config.graphQL?.disablePlayground!==true,plugins:[]}).fetch,schema:t}}getTRPC(e){return {fetch:async(t,s)=>{let a=new URL(t.url).pathname.replace(/^\/api\/trpc\//,""),[o,...r]=a.split("."),c=r.join(".");if(c=c.replace(/\.(query|mutate|subscribe)$/,""),!o||!c)return new Response(JSON.stringify({error:{message:"Invalid tRPC path",code:-32600,data:{code:"BAD_REQUEST",httpStatus:400}}}),{status:400,headers:{"Content-Type":"application/json"}});let d=await chunkZUVP4UK7_cjs.a({db:this.db,registry:this.registry,req:t,user:e?.user,tenantId:e?.tenantId,settings:this.settings}),p=chunkZUVP4UK7_cjs.i(d)[o];if(!p)return new Response(JSON.stringify({error:{message:`Collection '${o}' not found`,code:-32601,data:{code:"NOT_FOUND",httpStatus:404}}}),{status:404,headers:{"Content-Type":"application/json"}});let m=p[c];if(typeof m!="function")return new Response(JSON.stringify({error:{message:`Procedure '${c}' not found`,code:-32601,data:{code:"NOT_FOUND",httpStatus:404}}}),{status:404,headers:{"Content-Type":"application/json"}});try{let y={};if(t.method==="POST"||t.method==="PATCH")y=await t.json().catch(()=>({}));else {let C=new URL(t.url).searchParams.get("input");if(C)try{y=JSON.parse(decodeURIComponent(C));}catch{}}let g=y?.["0"]??y,f=await m({...g,collection:o});return new Response(JSON.stringify({result:{data:f}}),{status:200,headers:{"Content-Type":"application/json"}})}catch(y){let g=y.message||"Internal error",f=g.includes("not found")?404:g.includes("denied")||g.includes("authentication required")?403:g.includes("conflict")?409:500,C=f===404?-32601:f===403?-32001:f===409?-32002:-32603;return new Response(JSON.stringify({error:{message:g,code:C,data:{code:"INTERNAL_SERVER_ERROR",httpStatus:f}}}),{status:f,headers:{"Content-Type":"application/json"}})}},router:null}}getWS(){return this.wsServer}async startWebSocket(e){let t=this.settings?.access?.apiAccess;if(t?.wsEnabled===false)return null;let s=async a=>{let o=await chunkNY47CFVP_cjs.e(a,this.db);if(!o.valid)throw new Error(o.error||"Invalid API key");if(!o.user)throw new Error("API key has no associated user");return o.user},i=e?.port||8080;if(globalThis.__KYRO_WS_SERVER__)try{await globalThis.__KYRO_WS_SERVER__.close();}catch{}return this.wsServer=chunkG3J2EU5D_cjs.d({pubsub:this.pubsub,port:i,requireAuth:e?.requireAuth??t?.requireAuth,verifyToken:e?.verifyToken||s}),globalThis.__KYRO_WS_SERVER__=this.wsServer,this.wsServer}async shutdown(){await this.pluginManager.executeHook("beforeServerStop",{kyro:this}),this.wsServer&&await this.wsServer.close(),await this.db.disconnect(),await this.pluginManager.executeHook("afterServerStop",{kyro:this});}};function gs(n){return new re(n)}var At=module$1.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('chunk-O3OYZQN7.cjs', document.baseURI).href))),St="node:sqlite",{DatabaseSync:xt}=At(St);function E(n){let e=[];for(let t of n)if(t.type==="tabs"&&"tabs"in t)for(let s of t.tabs)e.push(...E(s.fields));else t.type==="row"&&"fields"in t?e.push(...E(t.fields)):t.type==="collapsible"&&"fields"in t?e.push(...E(t.fields)):e.push(t);return e}function Et(n,e){let t=e,s=n[t.name];if(t.type==="json"||t.type==="richtext"||t.type==="array"||t.type==="group"||t.type==="blocks"||t.type==="list"||t.type==="relationship-block")try{s=s?JSON.parse(s):null;}catch{s=null;}if(t.type==="checkbox"&&(s=!!s),t.type==="date"&&s)try{let i=new Date(s);isNaN(i.getTime())?s=null:s=i.toISOString();}catch{s=null;}if((t.type==="upload"||t.type==="image")&&s)try{let i=JSON.parse(s);Array.isArray(i)?s=i.map(a=>typeof a=="object"&&a!==null?a:{id:a}):s=typeof i=="object"?i:{id:i};}catch{s={id:s};}if(t.type==="relationship"&&s)try{let i=JSON.parse(s);Array.isArray(i),s=i;}catch{s={relationTo:Array.isArray(t.relationTo)?t.relationTo[0]:t.relationTo,value:s};}if(t.type==="list"&&s)try{let i=JSON.parse(s);s=Array.isArray(i)?i:[];}catch{s=[];}if(t.type==="relationship-block"&&s)try{let i=JSON.parse(s);s=Array.isArray(i)?i:[];}catch{s=[];}return s}function qe(n,e){return Array.isArray(n)?n.map(t=>{if(!t||typeof t!="object")return t;let s=t.data?{...t.data}:void 0;if(!s)return t;let i=e.find(a=>a.slug===t.type||a.slug===t.slug);if(!i||!Array.isArray(i.fields))return t;for(let a of i.fields){if(a.name&&(a.type==="upload"||a.type==="image")&&s[a.name]){let o=s[a.name];Array.isArray(o)?s[a.name]=o.map(r=>typeof r=="string"?{id:r}:r):typeof o=="string"&&(s[a.name]={id:o});}if(a.type==="blocks"&&a.name&&s[a.name]){let o=a.blocks||[];s[a.name]=qe(s[a.name],o);}}return {...t,data:s}}):n}function q(n,e){try{return n.prepare(`PRAGMA table_info(${e})`).all().map(s=>s.name)}catch{return []}}var le=class extends chunkFHJJKFAU_cjs.a{db;path;migrations=new Map;versionsTableName="kyro_versions";constructor(e){super(),this.path=e.path,e.db?this.db=e.db:this.db=null;}async connect(){if(this.db||(this.db=new xt(this.path||":memory:")),this.db&&typeof this.db.prepare=="function"&&!this.db.prepare.__wrapped){let e=this.db.prepare.bind(this.db),t=s=>{let i=e(s),a=o=>typeof o=="boolean"?o?1:0:o===void 0?null:o;return new Proxy(i,{get(o,r,c){if(r==="all")return (...u)=>o.all(...u.map(a));if(r==="get")return (...u)=>o.get(...u.map(a));if(r==="run")return (...u)=>o.run(...u.map(a));let d=Reflect.get(o,r,c);return typeof d=="function"?d.bind(o):d}})};t.__wrapped=true,this.db.prepare=t;}this.db.exec("PRAGMA journal_mode = WAL"),this.db.exec("PRAGMA foreign_keys = ON"),this.connected=true;}async disconnect(){this.db&&this.db.close(),this.connected=false;}ensureTable(e,t){let s=t||this.getTableNameFor(e.slug),i=["id TEXT PRIMARY KEY"];for(let r of E(e.fields)){if(!r.name||r.name==="id")continue;let c=this.fieldToSQL(r);c&&i.push(c);}let a=E(e.fields);a.some(r=>r.name==="createdAt")||i.push(`${this.col("createdAt")} TEXT DEFAULT (datetime('now'))`),a.some(r=>r.name==="updatedAt")||i.push(`${this.col("updatedAt")} TEXT DEFAULT (datetime('now'))`),a.some(r=>r.name==="status")||i.push("status TEXT DEFAULT 'draft'"),a.some(r=>r.name==="hasDraft")||i.push("hasDraft INTEGER DEFAULT 0"),e.tenantScoped&&i.push("tenant_id TEXT NOT NULL");let o=q(this.db,s);if(o.length===0){let r=`CREATE TABLE IF NOT EXISTS ${s} (${i.join(", ")})`;this.db.exec(r),this.db.exec(`CREATE INDEX IF NOT EXISTS idx_${s}_status ON ${s}(status)`);for(let c of E(e.fields))c.name&&c.indexed&&this.db.exec(`CREATE INDEX IF NOT EXISTS idx_${s}_${c.name} ON ${s}(${this.col(c.name)})`),c.name&&c.unique&&this.db.exec(`CREATE UNIQUE INDEX IF NOT EXISTS idx_${s}_${c.name}_unique ON ${s}(${this.col(c.name)})`);}else {let r=new Set(o);for(let c of i){let d=c.split(" ")[0].replace(/^"/,"").replace(/"$/,"");if(!r.has(d)&&d!=="id")try{d==="status"?this.db.exec(`ALTER TABLE ${s} ADD COLUMN ${this.col(d)} TEXT DEFAULT 'published'`):d==="hasDraft"?this.db.exec(`ALTER TABLE ${s} ADD COLUMN ${this.col(d)} INTEGER DEFAULT 0`):this.db.exec(`ALTER TABLE ${s} ADD COLUMN ${this.col(d)} TEXT`);}catch{}}}this.migrations.set(s,true);}ensureVersionsTable(){this.db.exec(`
|
|
4
|
+
CREATE TABLE IF NOT EXISTS ${this.versionsTableName} (
|
|
5
|
+
id TEXT PRIMARY KEY,
|
|
6
|
+
collection_slug TEXT NOT NULL,
|
|
7
|
+
document_id TEXT NOT NULL,
|
|
8
|
+
tenant_id TEXT,
|
|
9
|
+
version INTEGER NOT NULL,
|
|
10
|
+
status TEXT NOT NULL DEFAULT 'draft',
|
|
11
|
+
autosave INTEGER NOT NULL DEFAULT 0,
|
|
12
|
+
data TEXT NOT NULL,
|
|
13
|
+
created_by TEXT,
|
|
14
|
+
change_description TEXT,
|
|
15
|
+
published_at TEXT,
|
|
16
|
+
created_at TEXT DEFAULT (datetime('now')),
|
|
17
|
+
updated_at TEXT DEFAULT (datetime('now'))
|
|
18
|
+
)
|
|
19
|
+
`);try{this.db.exec(`ALTER TABLE ${this.versionsTableName} ADD COLUMN autosave INTEGER NOT NULL DEFAULT 0`);}catch{}this.db.exec(`CREATE INDEX IF NOT EXISTS idx_${this.versionsTableName}_doc ON ${this.versionsTableName}(collection_slug, document_id)`),this.db.exec(`CREATE INDEX IF NOT EXISTS idx_${this.versionsTableName}_status ON ${this.versionsTableName}(status)`),this.db.exec(`CREATE INDEX IF NOT EXISTS idx_${this.versionsTableName}_autosave ON ${this.versionsTableName}(autosave)`);}resolveCol(e,t){let s=t.replace(/^-/,""),i=q(this.db,e);if(!i.includes(s)){if(s==="created_at"&&i.includes("createdAt"))return '"createdAt"';if(s==="createdAt"&&i.includes("created_at"))return '"created_at"';if(s==="updated_at"&&i.includes("updatedAt"))return '"updatedAt"';if(s==="updatedAt"&&i.includes("updated_at"))return '"updated_at"'}return this.col(s)}col(e){return `"${e}"`}fieldToSQL(e){switch(e.type){case "text":case "email":case "password":case "textarea":case "color":case "icon":case "code":case "markdown":case "url":return this.col(e.name)+" TEXT";case "number":return this.col(e.name)+" REAL";case "checkbox":return this.col(e.name)+" INTEGER DEFAULT 0";case "date":return this.col(e.name)+" TEXT";case "select":case "radio":return this.col(e.name)+" TEXT";case "relationship":case "upload":return this.col(e.name)+" TEXT";case "json":case "richtext":case "array":case "group":case "blocks":return this.col(e.name)+" TEXT";default:return null}}parseGlobalsSlug(e){if(e.startsWith("_globals_")){let t=e.replace("_globals_","");return {isGlobal:true,globalSlug:t,tableName:`global_${t.replace(/-/g,"_")}`}}return {isGlobal:false,globalSlug:"",tableName:this.getTableNameFor(e)}}async find(e){let{collection:t,where:s={},sort:i,limit:a=10,page:o=1,tenantId:r,draft:c=false}=e,d=this.parseGlobalsSlug(t),u=d.isGlobal?this.globals.get(d.globalSlug):this.getCollection(t);this.ensureTable(u,d.tableName);let p=d.tableName,m=`SELECT * FROM ${p}`,y=[],g=[],f={...s};this.tenantContext&&u.tenantScoped&&(f=chunkFHJJKFAU_cjs.c({where:f},t,this.tenantContext,chunkFHJJKFAU_cjs.b).where||{});let C=u.fields.find(b=>b.name==="status"),h=C?.type==="select"&&Array.isArray(C.options)&&C.options.some(b=>b.value==="published");!c&&h&&(g.push("status = ?"),y.push("published")),r&&u.tenantScoped&&(g.push("tenant_id = ?"),y.push(r));for(let[b,S]of Object.entries(f)){if(b==="AND"||b==="OR")continue;let D=this.resolveCol(p,b);typeof S=="object"&&S!==null?(S.equals!==void 0&&(g.push(`${D} = ?`),y.push(S.equals)),S.in!==void 0&&(g.push(`${D} IN (${S.in.map(()=>"?").join(", ")})`),y.push(...S.in)),S.not_equals!==void 0&&(g.push(`${D} != ?`),y.push(S.not_equals))):(g.push(`${D} = ?`),y.push(S));}g.length>0&&(m+=` WHERE ${g.join(" AND ")}`);let ce=i||"-createdAt",Ze=this.resolveCol(p,ce),Ge=ce.startsWith("-")?"DESC":"ASC";m+=` ORDER BY ${Ze} ${Ge}`;let Ue=m.replace("SELECT *","SELECT COUNT(*) as count"),P=this.db.prepare(Ue).get(...y)?.count||0;m+=" LIMIT ? OFFSET ?",y.push(a,(o-1)*a);let w=this.db.prepare(m).all(...y).map(b=>this.rowToDoc(b,u));return this.tenantContext&&!this.tenantContext.isSuperAdmin&&(w=w.filter(b=>chunkFHJJKFAU_cjs.d(b,t,this.tenantContext,chunkFHJJKFAU_cjs.b))),c&&(w=await Promise.all(w.map(async b=>{let S=this.db.prepare(`SELECT * FROM ${this.versionsTableName} WHERE collection_slug = ? AND document_id = ? AND tenant_id IS NULL ORDER BY version DESC LIMIT 1`).get(t,b.id);if(S){let D=S.data?JSON.parse(S.data):{};return chunkG7SSHELM_cjs.a({...b,...D,status:b.status})}return b}))),w=w.map(b=>chunkG7SSHELM_cjs.a(b)),{docs:w,totalDocs:P,limit:a,totalPages:Math.ceil(P/a),page:o,pagingCounter:(o-1)*a+1,hasPrevPage:o>1,hasNextPage:o<Math.ceil(P/a),prevPage:o>1?o-1:null,nextPage:o<Math.ceil(P/a)?o+1:null}}async findByID(e){let{collection:t,id:s,tenantId:i,draft:a=false}=e,o=this.parseGlobalsSlug(t),r=o.isGlobal?this.globals.get(o.globalSlug):this.getCollection(t);this.ensureTable(r,o.tableName);let d=`SELECT * FROM ${o.tableName} WHERE id = ?`,u=[s];if(this.tenantContext&&r.tenantScoped){let f={id:s,tenant_id:this.tenantContext.tenantId};if(!chunkFHJJKFAU_cjs.d(f,t,this.tenantContext,chunkFHJJKFAU_cjs.b))return null}let p=r.fields.find(f=>f.name==="status"),m=p?.type==="select"&&Array.isArray(p.options)&&p.options.some(f=>f.value==="published");!a&&m&&(d+=" AND status = ?",u.push("published")),i&&r.tenantScoped&&(d+=" AND tenant_id = ?",u.push(i));let y=this.db.prepare(d).get(...u);if(!y)return null;let g=this.rowToDoc(y,r);if(a){let f=this.db.prepare(`SELECT * FROM ${this.versionsTableName} WHERE collection_slug = ? AND document_id = ? AND tenant_id IS NULL ORDER BY version DESC LIMIT 1`).get(t,g.id);if(f){let C=f.data?JSON.parse(f.data):{};g={...g,...C,status:g.status};}}return chunkG7SSHELM_cjs.a(g)}async create(e){let{collection:t,data:s,tenantId:i}=e,a=this.parseGlobalsSlug(t),o=a.isGlobal?this.globals.get(a.globalSlug):this.getCollection(t);this.ensureTable(o,a.tableName);let r=a.tableName,c=a.isGlobal?a.globalSlug:s.id||this.generateId(),d=this.prepareData(s,o);d.id=c,d.created_at=new Date().toISOString(),d.updated_at=new Date().toISOString(),i&&o.tenantScoped&&(d.tenant_id=i);let u=Object.keys(d),p=q(this.db,r),m={};for(let h of u)p.includes(h)&&(m[h]=d[h]);let y=Object.keys(m),g=y.map(h=>this.col(h)),f=y.map(()=>"?").join(", "),C=Object.values(m).map(h=>h!==null&&typeof h=="object"?JSON.stringify(h):h);return this.db.prepare(`INSERT OR REPLACE INTO ${r} (${g.join(", ")}) VALUES (${f})`).run(...C),this.ensureVersionsTable(),this.findByID({collection:t,id:c,tenantId:i,draft:true})}async update(e){let{collection:t,id:s,data:i,tenantId:a}=e,o=this.parseGlobalsSlug(t),r=o.isGlobal?this.globals.get(o.globalSlug):this.getCollection(t);this.ensureTable(r,o.tableName);let c=o.tableName,d=this.prepareData(i,r);d.updated_at=new Date().toISOString();let u=q(this.db,c),p={};for(let h of Object.keys(d))u.includes(h)&&(p[h]=d[h]);let y=Object.keys(p).map(h=>`${this.col(h)} = ?`).join(", "),g=Object.values(p).map(h=>h!==null&&typeof h=="object"?JSON.stringify(h):h),f=`UPDATE ${c} SET ${y} WHERE id = ?`,C=[...g,s];return a&&r.tenantScoped&&(f+=" AND tenant_id = ?",C.push(a)),this.db.prepare(f).run(...C),this.ensureVersionsTable(),this.findByID({collection:t,id:s,tenantId:a,draft:true})}async delete(e){let{collection:t,id:s,tenantId:i}=e,a=this.parseGlobalsSlug(t),o=a.isGlobal?this.globals.get(a.globalSlug):this.getCollection(t);this.ensureTable(o,a.tableName),this.ensureVersionsTable();let r=await this.findByID({collection:t,id:s,tenantId:i,draft:true});if(!r)throw new Error(`Document not found: ${t}/${s}`);let d=`DELETE FROM ${a.tableName} WHERE id = ?`,u=[s];return i&&o.tenantScoped&&(d+=" AND tenant_id = ?",u.push(i)),this.db.prepare(d).run(...u),r}async count(e){let{collection:t,tenantId:s}=e,i=this.parseGlobalsSlug(t),a=i.isGlobal?this.globals.get(i.globalSlug):this.getCollection(t);this.ensureTable(a,i.tableName);let r=`SELECT COUNT(*) as count FROM ${i.tableName}`,c=[];return s&&a.tenantScoped&&(r+=" WHERE tenant_id = ?",c.push(s)),this.db.prepare(r).get(...c)?.count||0}async findOne(e){let t=this.parseGlobalsSlug(e.collection);if(t.isGlobal){let i=this.globals.get(t.globalSlug);if(!i)throw new Error(`Global "${t.globalSlug}" not found in adapter`);this.ensureTable(i,t.tableName);let a=`SELECT * FROM ${t.tableName}`,o=[],r=[],c=i.fields.find(p=>p.name==="status"),d=c?.type==="select"&&Array.isArray(c.options)&&c.options.some(p=>p.value==="published");!e.draft&&i.versions&&d&&o.push("status = 'published'"),o.length>0&&(a+=` WHERE ${o.join(" AND ")}`),a+=" LIMIT 1";let u=this.db.prepare(a).get(...r);if(u){let p=this.rowToDoc(u,i);if(e.draft){let m=this.db.prepare(`SELECT * FROM ${this.versionsTableName} WHERE collection_slug = ? AND document_id = ? AND tenant_id IS NULL ORDER BY version DESC LIMIT 1`).get(e.collection,t.globalSlug);if(m){let y=m.data?JSON.parse(m.data):{};p={...p,...y,status:p.status};}}return p}return null}return (await this.find({...e,limit:1})).docs[0]||null}async findVersions(e){this.ensureVersionsTable();let{collection:t,documentId:s,tenantId:i,limit:a=20,page:o=1}=e,r=["collection_slug = ?","document_id = ?","autosave = 0"],c=[t,s];i?(r.push("tenant_id = ?"),c.push(i)):r.push("tenant_id IS NULL");let d=`WHERE ${r.join(" AND ")}`,p=this.db.prepare(`SELECT COUNT(*) as count FROM ${this.versionsTableName} ${d}`).get(...c)?.count||0,m=(o-1)*a;return {docs:this.db.prepare(`SELECT * FROM ${this.versionsTableName} ${d} ORDER BY version DESC LIMIT ? OFFSET ?`).all(...c,a,m).map(f=>this.rowToVersion(f)),totalDocs:p,limit:a,totalPages:Math.ceil(p/a),page:o,pagingCounter:(o-1)*a+1,hasPrevPage:o>1,hasNextPage:o<Math.ceil(p/a),prevPage:o>1?o-1:null,nextPage:o<Math.ceil(p/a)?o+1:null}}async findVersionByID(e){this.ensureVersionsTable();let t=this.db.prepare(`SELECT * FROM ${this.versionsTableName} WHERE id = ? AND collection_slug = ? LIMIT 1`).get(e.versionId,e.collection);return t?this.rowToVersion(t):null}async createVersion(e){this.ensureVersionsTable();let t=new Date().toISOString();if(e.autosave){let r=`SELECT * FROM ${this.versionsTableName} WHERE collection_slug = ? AND document_id = ? AND autosave = 1`,c=[e.collection,e.documentId];e.tenantId?(r+=" AND tenant_id = ?",c.push(e.tenantId)):r+=" AND tenant_id IS NULL",r+=" LIMIT 1";let d=this.db.prepare(r).get(...c);if(d){this.db.prepare(`UPDATE ${this.versionsTableName} SET data = ?, status = ?, updated_at = ? WHERE id = ?`).run(JSON.stringify(e.data),e.status,t,d.id);let u=await this.findVersionByID({collection:e.collection,versionId:d.id});if(u)return u}}let s=this.generateId(),a=(this.db.prepare(`SELECT version FROM ${this.versionsTableName} WHERE collection_slug = ? AND document_id = ? AND autosave = 0 ORDER BY version DESC LIMIT 1`).get(e.collection,e.documentId)?.version??0)+1;if(this.db.prepare(`INSERT INTO ${this.versionsTableName} (
|
|
20
|
+
id, collection_slug, document_id, tenant_id, version, status, autosave, data, created_by, change_description, published_at, created_at, updated_at
|
|
21
|
+
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(s,e.collection,e.documentId,e.tenantId??null,a,e.status,e.autosave?1:0,JSON.stringify(e.data),e.createdBy??null,e.changeDescription??null,e.status==="published"?t:null,t,t),!e.autosave){let c=this.collections.get(e.collection)?.versions?.maxPerDoc;c&&c>0&&await this.deleteVersions({collection:e.collection,documentId:e.documentId,keepLatest:c,tenantId:e.tenantId});}return await this.findVersionByID({collection:e.collection,versionId:s})}async updateLatestVersion(e){return this.createVersion({...e,autosave:true})}async deleteVersions(e){this.ensureVersionsTable();let{collection:t,documentId:s,keepLatest:i,tenantId:a}=e;if(i&&i>0){let o=this.db.prepare(`SELECT id, status, autosave FROM ${this.versionsTableName} WHERE collection_slug = ? AND document_id = ? ORDER BY version DESC`).all(t,s),r=0,c=[];for(let d of o)d.status==="published"||d.autosave===1||(r++,r>i&&c.push(d.id));for(let d of c)this.db.prepare(`DELETE FROM ${this.versionsTableName} WHERE id = ?`).run(d);}else {let o=`DELETE FROM ${this.versionsTableName} WHERE collection_slug = ? AND document_id = ?`,r=[t,s];a&&(o+=" AND tenant_id = ?",r.push(a)),this.db.prepare(o).run(...r);}}rowToVersion(e){return {id:String(e.id),collection:e.collection_slug,documentId:e.document_id,version:e.version,status:e.status,data:e.data?JSON.parse(e.data):{},createdBy:e.created_by??void 0,changeDescription:e.change_description??void 0,publishedAt:e.published_at??null,createdAt:e.created_at,updatedAt:e.updated_at}}prepareData(e,t){let s={},i=E(t.fields),a=(o,r)=>{let c=o;if(c.type==="json"||c.type==="richtext"||c.type==="array"||c.type==="group"||c.type==="blocks"||c.type==="list"||c.type==="relationship-block")return r!=null?JSON.stringify(r):null;if(c.type==="checkbox")return r?1:0;if(c.type==="number")return r!==null&&r!==""?Number(r):null;if(c.type==="upload"||c.type==="image"){if(r==null)return null;if(Array.isArray(r)){let d=r.map(u=>typeof u=="string"?u:typeof u=="object"?u.id||u._id||u:String(u));return JSON.stringify(d)}return typeof r=="string"?r:typeof r=="object"?JSON.stringify(r):String(r)}else if(o.type==="relationship"){if(r==null)return null;if(Array.isArray(r)){let d=r.map(u=>typeof u=="string"?u:typeof u=="object"?JSON.stringify({relationTo:o.relationTo,value:u.id||u}):String(u));return JSON.stringify(d)}return typeof r=="string"?r:typeof r=="object"?JSON.stringify({relationTo:o.relationTo,value:r.id||r}):String(r)}return r};for(let o of i){if(!o.name||o.name==="id"||t.fields.some(d=>d.type==="tabs"&&d.name&&"tabs"in d&&d.tabs.some(u=>u.fields.some(p=>p.name===o.name))))continue;let c=e[o.name];c!==void 0&&(s[o.name]=a(o,c));}for(let o of t.fields)if(o.type==="tabs"&&"tabs"in o&&o.name){let r=e[o.name];if(r&&typeof r=="object"){for(let c of o.tabs)for(let d of c.fields)if(d.name&&d.name!=="id"){let u=r[d.name];u!==void 0&&(s[d.name]=a(d,u));}}}return s}rowToDoc(e,t){let s={id:e.id};for(let i of E(t.fields)){if(!i.name||i.name==="id")continue;let a=i,o=e[a.name];if(a.type==="json"||a.type==="richtext"||a.type==="array"||a.type==="group"||a.type==="blocks"||a.type==="list"||a.type==="relationship-block")try{o=o?JSON.parse(o):null;}catch{o=null;}if(a.type==="blocks"&&o&&Array.isArray(o)){let r=a.blocks||[];o=qe(o,r);}if(i.type==="checkbox"&&(o=!!o),i.type==="date"&&o)try{let r=new Date(o);isNaN(r.getTime())?(console.warn(`[LocalAdapter] Invalid date value for field "${i.name}":`,o),o=null):o=r.toISOString();}catch{o=null;}if((i.type==="upload"||i.type==="image")&&o)try{let r=JSON.parse(o);Array.isArray(r)?o=r.map(c=>typeof c=="object"&&c!==null?c:{id:c}):o=typeof r=="object"?r:{id:r};}catch{o={id:o};}if(i.type==="relationship"&&o)try{let r=JSON.parse(o);Array.isArray(r),o=r;}catch{o={relationTo:Array.isArray(i.relationTo)?i.relationTo[0]:i.relationTo,value:o};}s[i.name]=o;}for(let i of t.fields)if(!(!i.name||i.name==="id"||i.name==="row"||i.name==="collapsible")&&i.type==="tabs"&&"tabs"in i){let a={};for(let o of i.tabs)for(let r of o.fields)r.name&&r.name!=="id"&&(a[r.name]=Et(e,r));s[i.name]=a;}if(t.timestamps){let i=e.createdAt||e.created_at,a=e.updatedAt||e.updated_at;if(i)try{let o=new Date(i);isNaN(o.getTime())||(s.createdAt=o.toISOString());}catch{}if(a)try{let o=new Date(a);isNaN(o.getTime())||(s.updatedAt=o.toISOString());}catch{}}t.tenantScoped&&(s.tenantId=e.tenant_id),s.status=e.status??"published",s.hasDraft=e.hasDraft?!!e.hasDraft:false;for(let i of Object.keys(s))/^\d+$/.test(i)&&delete s[i];return s}generateId(){let e=Date.now().toString(16).padStart(12,"0"),t=crypto.randomBytes(6).toString("hex");return e+t}getMediaById(e){try{let t=this.getTableNameFor("media"),s=this.db.prepare(`SELECT id, url, thumbnail_url FROM ${t} WHERE id = ?`).get(e);if(s)return {id:s.id,url:s.url,thumbnailUrl:s.thumbnail_url||s.url}}catch{}return null}getTableNameFor(e){return e.replace(/-/g,"_")}async migrate(){for(let e of this.collections.values())this.ensureTable(e);}async rollback(){}async transaction(e){return new Promise((t,s)=>{let i=this.db.transaction(async()=>e({db:this.db}));try{let a=i();t(a);}catch(a){s(a);}})}getDatabase(){return this.db}exec(e){this.db.exec(e);}prepare(e){return this.db.prepare(e)}};function ks(n){return new le(n||{})}exports.A=le;exports.B=ks;exports.a=z;exports.b=X;exports.c=J;exports.d=R;exports.e=we;exports.f=A;exports.g=De;exports.h=Fe;exports.i=ke;exports.j=Ie;exports.k=Pe;exports.l=I;exports.m=ut;exports.n=pt;exports.o=Y;exports.p=x;exports.q=j;exports.r=Q;exports.s=ee;exports.t=te;exports.u=se;exports.v=ne;exports.w=_t;exports.x=Tt;exports.y=re;exports.z=gs;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import {l,k}from'./chunk-6J27P5D6.js';import {a}from'./chunk-IKOXCJYO.js';async function f(t){let{adminEmail:e,adminPassword:r,adminRole:o="super_admin",tenantId:n,emailConfig:s,sendWelcomeEmail:c=false}=t,a$1=t.authAdapter||new a({path:t.authDbPath||"./data/auth.db"});try{await a$1.connect?.();}catch{return {success:false,error:"Failed to connect to auth storage"}}let l$1=new l().validate(r);if(!l$1.valid)return await a$1.disconnect?.(),{success:false,error:`Invalid password: ${l$1.errors.join(", ")}`};if(await a$1.findUserByEmail(e))return await a$1.disconnect?.(),{success:false,error:"Admin user already exists"};try{let i=await a$1.createUser({email:e,password:r,role:o||"admin",tenantId:n});if(c&&s){let u=new k(s),A=u.getTemplates().welcome(e.split("@")[0]);await u.send({to:e,...A});}return await a$1.disconnect?.(),{success:!0,user:i}}catch(i){return await a$1.disconnect?.(),{success:false,error:i instanceof Error?i.message:"Failed to create admin user"}}}async function y(t,e){return !await t.findUserByEmail(e)}function w(){let t=process.env.KYRO_ADMIN_EMAIL,e=process.env.KYRO_ADMIN_PASSWORD;return !t||!e?null:{authDbPath:process.env.KYRO_AUTH_DB_PATH||"./data/auth.db",adminEmail:t,adminPassword:e,adminRole:process.env.KYRO_ADMIN_ROLE||"super_admin",tenantId:process.env.KYRO_ADMIN_TENANT_ID,emailConfig:process.env.SMTP_HOST?{provider:"smtp",smtp:{host:process.env.SMTP_HOST,port:parseInt(process.env.SMTP_PORT||"587",10),secure:process.env.SMTP_SECURE==="true",auth:{user:process.env.SMTP_USER||"",pass:process.env.SMTP_PASS||""}},from:process.env.SMTP_FROM||"noreply@example.com",fromName:process.env.SMTP_FROM_NAME}:void 0,sendWelcomeEmail:process.env.KYRO_ADMIN_SEND_WELCOME==="true"}}async function T(t){let e=w();if(!e)return null;t&&(e.authAdapter=t);try{if(await e.authAdapter?.connect?.(),await e.authAdapter?.findUserByEmail(e.adminEmail))return await e.authAdapter?.disconnect?.(),{success:!1,error:"Admin user already exists"}}catch{}let r=await f(e);return r.success||console.error(`Bootstrap failed: ${r.error}`),r}async function v(t,e=3,r=2e3){let o="";for(let n=0;n<e;n++){let s=await f(t);if(s.success||(o=s.error||"Unknown error",o.includes("already exists")))return s;n<e-1&&await new Promise(c=>setTimeout(c,r));}return {success:false,error:`Failed after ${e} retries: ${o}`}}export{f as a,y as b,w as c,T as d,v as e};
|