@kidecms/core 0.1.11 → 0.14.0

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.
Files changed (180) hide show
  1. package/LICENSE +21 -0
  2. package/admin/components/AssetsGrid.tsx +366 -173
  3. package/admin/components/BlockEditor.tsx +260 -679
  4. package/admin/components/CheckboxField.tsx +2 -2
  5. package/admin/components/CollaborationReviewBar.tsx +384 -0
  6. package/admin/components/ColorField.tsx +87 -0
  7. package/admin/components/CommandPalette.tsx +169 -0
  8. package/admin/components/ContentEditor.tsx +687 -0
  9. package/admin/components/DocumentActions.tsx +4 -2
  10. package/admin/components/DocumentsDataTable.tsx +91 -10
  11. package/admin/components/FieldControl.astro +151 -26
  12. package/admin/components/FocalPointSelector.tsx +27 -1
  13. package/admin/components/InternalLinkPicker.tsx +4 -3
  14. package/admin/components/LinkField.tsx +126 -0
  15. package/admin/components/RelationField.tsx +105 -26
  16. package/admin/components/RepeaterInput.tsx +46 -0
  17. package/admin/components/RichTextEditor.tsx +44 -9
  18. package/admin/components/SharedSectionBlockField.tsx +93 -0
  19. package/admin/components/SidebarUserMenu.tsx +1 -1
  20. package/admin/components/Toast.astro +1 -1
  21. package/admin/components/TreeItemsEditor.tsx +20 -19
  22. package/admin/components/TreeSelect.tsx +2 -2
  23. package/admin/components/YoutubeField.tsx +48 -0
  24. package/admin/components/block-fields.tsx +777 -0
  25. package/admin/components/content-block-spec.ts +114 -0
  26. package/admin/components/slash-command.tsx +242 -0
  27. package/admin/components/tree-utils.ts +14 -2
  28. package/admin/components/ui/badge.tsx +2 -3
  29. package/admin/components/ui/button.tsx +5 -4
  30. package/admin/components/ui/checkbox.tsx +1 -1
  31. package/admin/components/ui/input.tsx +1 -1
  32. package/admin/components/ui/select.tsx +1 -1
  33. package/admin/components/ui/table.tsx +1 -1
  34. package/admin/components/ui/textarea.tsx +1 -1
  35. package/admin/layouts/AdminLayout.astro +323 -123
  36. package/admin/lib/access.ts +54 -0
  37. package/admin/lib/collaboration.ts +178 -0
  38. package/admin/lib/edit-data.ts +448 -0
  39. package/admin/views/AccessDeniedView.astro +8 -0
  40. package/admin/views/EditView.astro +706 -0
  41. package/admin/views/ListView.astro +202 -0
  42. package/admin/views/RecentView.astro +76 -0
  43. package/admin/views/SinglesView.astro +65 -0
  44. package/admin/views/edit/EditScripts.astro +145 -0
  45. package/admin/views/edit/ReverseReferencesList.astro +68 -0
  46. package/core/admin.ts +193 -0
  47. package/core/ai.ts +87 -0
  48. package/core/api.ts +1392 -0
  49. package/core/assets.ts +336 -0
  50. package/core/audit.ts +86 -0
  51. package/core/auth-config.ts +44 -0
  52. package/core/auth.ts +303 -0
  53. package/core/collaboration.ts +276 -0
  54. package/core/content.ts +27 -0
  55. package/core/create-admin.ts +28 -0
  56. package/core/define.ts +623 -0
  57. package/core/field-model.ts +172 -0
  58. package/core/generator.ts +519 -0
  59. package/core/http.ts +42 -0
  60. package/core/image.ts +219 -0
  61. package/core/index.ts +211 -0
  62. package/core/locks.ts +52 -0
  63. package/core/log.ts +37 -0
  64. package/core/migrate.ts +278 -0
  65. package/core/rate-limit.ts +110 -0
  66. package/core/request-scope.ts +33 -0
  67. package/core/richtext.ts +1 -0
  68. package/core/runtime.ts +63 -0
  69. package/core/schema.ts +32 -0
  70. package/core/search.ts +489 -0
  71. package/core/seed.ts +101 -0
  72. package/core/shared-sections.ts +96 -0
  73. package/core/tasks.ts +176 -0
  74. package/core/values.ts +433 -0
  75. package/core/webhooks.ts +85 -0
  76. package/core/youtube.ts +39 -0
  77. package/internals/cli.mjs +34 -0
  78. package/internals/context.ts +67 -0
  79. package/internals/create-admin.ts +40 -0
  80. package/internals/describe.ts +25 -0
  81. package/internals/eject.ts +144 -0
  82. package/internals/generator.ts +11 -0
  83. package/internals/integration.ts +481 -0
  84. package/internals/mcp.ts +397 -0
  85. package/internals/project.ts +31 -0
  86. package/internals/push.ts +160 -0
  87. package/internals/reindex.ts +11 -0
  88. package/internals/restore.ts +257 -0
  89. package/internals/seed.ts +15 -0
  90. package/internals/upgrade.ts +785 -0
  91. package/{virtual.d.ts → internals/virtual.d.ts} +39 -5
  92. package/middleware/auth.ts +130 -17
  93. package/middleware/push.ts +121 -0
  94. package/package.json +55 -67
  95. package/platform/cloudflare/cf-env.ts +60 -0
  96. package/platform/cloudflare/database.ts +28 -0
  97. package/platform/cloudflare/globals.d.ts +5 -0
  98. package/platform/cloudflare/storage.ts +33 -0
  99. package/platform/cloudflare/uploads-route.ts +37 -0
  100. package/platform/node/database.ts +39 -0
  101. package/platform/node/storage.ts +52 -0
  102. package/routes/admin/[...path].astro +71 -0
  103. package/routes/{pages/admin → admin}/assets/[id].astro +25 -19
  104. package/routes/admin/assets/index.astro +90 -0
  105. package/routes/{pages/admin/login.astro → admin/forgot-password.astro} +21 -19
  106. package/routes/{pages/admin → admin}/invite.astro +13 -6
  107. package/routes/admin/login.astro +103 -0
  108. package/routes/admin/reset-password.astro +73 -0
  109. package/routes/{pages/admin → admin}/setup.astro +32 -8
  110. package/routes/api/{cms/[collection] → [collection]}/[...path].ts +67 -15
  111. package/routes/api/admin/search.ts +89 -0
  112. package/routes/api/{cms/assets → assets}/[id].ts +24 -14
  113. package/routes/api/{cms/assets → assets}/index.ts +4 -2
  114. package/routes/api/assets/upload.ts +147 -0
  115. package/routes/api/auth/forgot-password.ts +77 -0
  116. package/routes/api/{cms/auth → auth}/invite.ts +41 -9
  117. package/routes/api/auth/login.ts +167 -0
  118. package/routes/api/{cms/auth → auth}/logout.ts +11 -2
  119. package/routes/api/auth/reset-password.ts +85 -0
  120. package/routes/api/auth/setup.ts +110 -0
  121. package/routes/api/auth/sso/[provider]/start.ts +34 -0
  122. package/routes/api/collaboration/index.ts +106 -0
  123. package/routes/api/cron/_authorize.ts +25 -0
  124. package/routes/api/{cms/cron → cron}/publish.ts +3 -9
  125. package/routes/api/cron/tasks.ts +34 -0
  126. package/routes/api/forms/submit/[slug].ts +143 -0
  127. package/routes/api/img/[...path].ts +65 -0
  128. package/routes/api/{cms/preview → preview}/render.ts +8 -3
  129. package/routes/api/{cms/references → references}/[collection]/[id].ts +31 -1
  130. package/routes/api/webhooks/[provider].ts +54 -0
  131. package/README.md +0 -28
  132. package/dist/admin.d.ts +0 -33
  133. package/dist/admin.js +0 -92
  134. package/dist/ai.d.ts +0 -15
  135. package/dist/ai.js +0 -70
  136. package/dist/api.d.ts +0 -14
  137. package/dist/api.js +0 -833
  138. package/dist/assets.d.ts +0 -51
  139. package/dist/assets.js +0 -163
  140. package/dist/auth.d.ts +0 -30
  141. package/dist/auth.js +0 -132
  142. package/dist/content.d.ts +0 -3
  143. package/dist/content.js +0 -29
  144. package/dist/create-admin.d.ts +0 -5
  145. package/dist/create-admin.js +0 -23
  146. package/dist/define.d.ts +0 -254
  147. package/dist/define.js +0 -36
  148. package/dist/generator.d.ts +0 -9
  149. package/dist/generator.js +0 -370
  150. package/dist/image.d.ts +0 -9
  151. package/dist/image.js +0 -69
  152. package/dist/index.d.ts +0 -28
  153. package/dist/index.js +0 -16
  154. package/dist/integration.d.ts +0 -14
  155. package/dist/integration.js +0 -327
  156. package/dist/locks.d.ts +0 -7
  157. package/dist/locks.js +0 -37
  158. package/dist/richtext.d.ts +0 -1
  159. package/dist/richtext.js +0 -1
  160. package/dist/runtime.d.ts +0 -24
  161. package/dist/runtime.js +0 -26
  162. package/dist/schema.d.ts +0 -17
  163. package/dist/schema.js +0 -13
  164. package/dist/seed.d.ts +0 -2
  165. package/dist/seed.js +0 -84
  166. package/dist/values.d.ts +0 -8
  167. package/dist/values.js +0 -102
  168. package/dist/webhooks.d.ts +0 -2
  169. package/dist/webhooks.js +0 -73
  170. package/routes/api/cms/assets/upload.ts +0 -112
  171. package/routes/api/cms/auth/login.ts +0 -124
  172. package/routes/api/cms/auth/setup.ts +0 -77
  173. package/routes/api/cms/img/[...path].ts +0 -24
  174. package/routes/pages/admin/[...path].astro +0 -1107
  175. package/routes/pages/admin/assets/index.astro +0 -63
  176. /package/routes/api/{cms/ai → ai}/alt-text.ts +0 -0
  177. /package/routes/api/{cms/ai → ai}/seo.ts +0 -0
  178. /package/routes/api/{cms/ai → ai}/translate.ts +0 -0
  179. /package/routes/api/{cms/assets → assets}/folders.ts +0 -0
  180. /package/routes/api/{cms/locks → locks}/[...path].ts +0 -0
@@ -3,18 +3,20 @@ declare module "virtual:kide/custom-fields" {
3
3
  }
4
4
 
5
5
  declare module "virtual:kide/config" {
6
- import type { CmsConfig } from "@kidecms/core";
7
- const config: CmsConfig;
6
+ const config: import("../core").CMSConfig;
8
7
  export default config;
9
8
  }
10
9
 
11
10
  declare module "virtual:kide/api" {
12
- const cms: Record<string, any> & { meta: any };
11
+ const cms: Record<string, any> & { meta: any; scheduled: any; tasks: any };
13
12
  export { cms };
14
13
  }
15
14
 
16
15
  declare module "virtual:kide/schema" {
17
16
  const cmsTables: Record<string, { main: any; translations?: any }>;
17
+ export const cmsSessions: any;
18
+ export const cmsPasswordResets: any;
19
+ export const cmsRateLimits: any;
18
20
  export { cmsTables };
19
21
  }
20
22
 
@@ -25,6 +27,7 @@ declare module "virtual:kide/runtime" {
25
27
  destroySession,
26
28
  clearSessionCookie,
27
29
  verifyPassword,
30
+ hashToken,
28
31
  hashPassword,
29
32
  createSession,
30
33
  setSessionCookie,
@@ -32,6 +35,9 @@ declare module "virtual:kide/runtime" {
32
35
  createInvite,
33
36
  validateInvite,
34
37
  consumeInvite,
38
+ createPasswordReset,
39
+ validatePasswordReset,
40
+ consumePasswordReset,
35
41
  SESSION_COOKIE_NAME,
36
42
  acquireLock,
37
43
  releaseLock,
@@ -43,7 +49,24 @@ declare module "virtual:kide/runtime" {
43
49
  assets,
44
50
  folders,
45
51
  createCms,
46
- } from "@kidecms/core";
52
+ recordAudit,
53
+ logAudit,
54
+ pruneAuditLog,
55
+ auditRequestMeta,
56
+ tokenReference,
57
+ collaboration,
58
+ search,
59
+ indexDocument,
60
+ removeDocument,
61
+ reindexAll,
62
+ readEnv,
63
+ peekRateLimit,
64
+ hitRateLimit,
65
+ recordRateLimit,
66
+ clearRateLimit,
67
+ pruneRateLimits,
68
+ getEmail,
69
+ } from "../core";
47
70
  }
48
71
 
49
72
  declare module "virtual:kide/block-renderer" {
@@ -51,11 +74,22 @@ declare module "virtual:kide/block-renderer" {
51
74
  export default BlockRenderer;
52
75
  }
53
76
 
77
+ declare module "virtual:kide/content-renderer" {
78
+ const ContentRenderer: any;
79
+ export default ContentRenderer;
80
+ }
81
+
54
82
  declare module "virtual:kide/db" {
55
83
  export function getDb(): Promise<any>;
56
84
  }
57
85
 
58
86
  declare module "virtual:kide/email" {
59
- export function sendInviteEmail(options: { to: string; inviteUrl: string }): Promise<void>;
87
+ export function sendInviteEmail(to: string, inviteUrl: string): Promise<boolean>;
88
+ export function sendPasswordResetEmail(to: string, resetUrl: string): Promise<boolean>;
89
+ export function sendFormSubmissionEmail(
90
+ to: string,
91
+ formTitle: string,
92
+ data: Record<string, unknown>,
93
+ ): Promise<boolean>;
60
94
  export function isEmailConfigured(): boolean;
61
95
  }
@@ -1,4 +1,8 @@
1
1
  import { defineMiddleware } from "astro:middleware";
2
+ import type { APIContext, MiddlewareNext } from "astro";
3
+ import { readEnv, resolveAdminAuth, runWithRequestScope } from "../core";
4
+ import type { RequestScope, SessionUser } from "../core";
5
+ import config from "virtual:kide/config";
2
6
  import { getSessionUser } from "virtual:kide/runtime";
3
7
  import { getDb } from "virtual:kide/db";
4
8
 
@@ -8,36 +12,120 @@ export const resetUserCache = () => {
8
12
  hasUsers = null;
9
13
  };
10
14
 
15
+ const normalizeCustomUser = (value: Record<string, unknown> | null): SessionUser | null => {
16
+ if (!value || typeof value.id !== "string" || typeof value.email !== "string") return null;
17
+ return {
18
+ ...value,
19
+ id: value.id,
20
+ email: value.email,
21
+ name: typeof value.name === "string" ? value.name : value.email,
22
+ role: typeof value.role === "string" ? value.role : "editor",
23
+ };
24
+ };
25
+
11
26
  export const onRequest = defineMiddleware(async (context, next) => {
27
+ // Establish a per-request scope for EVERY request (including public pages and custom public
28
+ // API routes) so deferred work (audit/search/webhook-enqueue) is kept alive only for THIS
29
+ // request — never routed to the module-level script fallback, whose promises aren't attached
30
+ // to any waitUntil on Cloudflare. On Cloudflare defer = cfContext.waitUntil (locals.runtime.ctx
31
+ // throws on Astro 7); on Node it's a no-op (the process stays alive regardless).
32
+ const cfContext = (context.locals as { cfContext?: { waitUntil?: (p: Promise<unknown>) => void } }).cfContext;
33
+ const scope: RequestScope = cfContext?.waitUntil
34
+ ? { defer: (task) => cfContext.waitUntil!(task) }
35
+ : { defer: () => {} };
36
+ return runWithRequestScope(scope, () => handle(context, next));
37
+ });
38
+
39
+ const handle = async (context: APIContext, next: MiddlewareNext) => {
12
40
  const { pathname } = context.url;
13
41
 
42
+ // `?preview` exposes draft content on public pages; require a session (unauth → strip it).
43
+ if (context.url.searchParams.has("preview")) {
44
+ const previewUser = await getSessionUser(context.request);
45
+ if (!previewUser) {
46
+ const clean = new URL(context.url);
47
+ clean.searchParams.delete("preview");
48
+ return context.redirect(`${clean.pathname}${clean.search}`);
49
+ }
50
+ }
51
+
14
52
  // Skip auth for public pages and static assets
15
53
  const isAdminRoute = pathname.startsWith("/admin");
16
54
  const isAdminApiRoute = pathname.startsWith("/api/cms");
17
55
  const isLoginPage = pathname === "/admin/login";
18
56
  const isLoginApi = pathname === "/api/cms/auth/login";
57
+ const isForgotPasswordPage = pathname === "/admin/forgot-password";
58
+ const isForgotPasswordApi = pathname === "/api/cms/auth/forgot-password";
59
+ const isResetPasswordPage = pathname === "/admin/reset-password";
60
+ const isResetPasswordApi = pathname === "/api/cms/auth/reset-password";
61
+ const isSsoAuthApi = pathname.startsWith("/api/cms/auth/sso/");
19
62
  const isSetupPage = pathname === "/admin/setup";
20
63
  const isSetupApi = pathname === "/api/cms/auth/setup";
21
64
  const isInvitePage = pathname === "/admin/invite";
22
65
  const isInviteApi = pathname === "/api/cms/auth/invite";
23
66
 
24
- if (!isAdminRoute && !isAdminApiRoute) {
67
+ // Public despite the /api/cms prefix: cmsImage() puts these URLs on public pages.
68
+ // Only reads files under public/, which are served unauthenticated anyway.
69
+ const isPublicImageApi = pathname.startsWith("/api/cms/img/");
70
+
71
+ if ((!isAdminRoute && !isAdminApiRoute) || isPublicImageApi) {
25
72
  return next();
26
73
  }
27
74
 
28
75
  // Security headers for all admin routes
76
+ const isAuthPath =
77
+ pathname.startsWith("/api/cms/auth/") ||
78
+ isLoginPage ||
79
+ isSetupPage ||
80
+ isInvitePage ||
81
+ isForgotPasswordPage ||
82
+ isResetPasswordPage;
29
83
  const addSecurityHeaders = (response: Response) => {
30
84
  response.headers.set("X-Content-Type-Options", "nosniff");
31
- response.headers.set("X-Frame-Options", "DENY");
85
+ response.headers.set("X-Frame-Options", "SAMEORIGIN");
86
+ response.headers.set("Referrer-Policy", "strict-origin-when-cross-origin");
87
+ // Keep credentials and reset/invite tokens out of shared/browser caches.
88
+ if (isAuthPath) response.headers.set("Cache-Control", "no-store");
32
89
  return response;
33
90
  };
34
91
 
35
- // CSRF protection: verify Origin on state-changing requests
36
- if (context.request.method !== "GET" && context.request.method !== "HEAD") {
92
+ // The request scope is already established by onRequest (wraps this whole function).
93
+ const serve = async () => addSecurityHeaders(await next());
94
+
95
+ // CSRF: positive same-origin assertion on state-changing requests. Machine endpoints
96
+ // authenticate independently (cron bearer, webhook HMAC) or are intentionally public
97
+ // (form submit) and legitimately have no browser Origin, so they're exempt here;
98
+ // everything else (login/setup/invite/reset included) must prove same-origin.
99
+ const method = context.request.method;
100
+ const isMachineEndpoint =
101
+ pathname === "/api/cms/cron/publish" ||
102
+ pathname === "/api/cms/cron/tasks" ||
103
+ pathname.startsWith("/api/cms/webhooks/") ||
104
+ pathname.startsWith("/api/cms/forms/submit/");
105
+ if (method !== "GET" && method !== "HEAD" && method !== "OPTIONS" && !isMachineEndpoint) {
106
+ // Compare against an explicitly configured origin when set (robust behind a proxy that
107
+ // may rewrite Host); otherwise fall back to the request's own origin.
108
+ const host = readEnv("CMS_TRUSTED_ORIGIN") ?? context.url.origin;
37
109
  const origin = context.request.headers.get("origin");
38
- const host = context.url.origin;
39
- if (origin && origin !== host) {
40
- return new Response(JSON.stringify({ error: "Forbidden" }), { status: 403 });
110
+ const referer = context.request.headers.get("referer");
111
+ const secFetchSite = context.request.headers.get("sec-fetch-site");
112
+
113
+ let refererOk = false;
114
+ if (!origin && referer) {
115
+ try {
116
+ refererOk = new URL(referer).origin === host;
117
+ } catch {
118
+ refererOk = false;
119
+ }
120
+ }
121
+ const originOk = origin === host;
122
+ // Reject an explicit cross-site Fetch-Metadata signal, or the absence of any
123
+ // trustworthy same-origin signal (the hole the old `if (origin && ...)` left open).
124
+ if (secFetchSite === "cross-site" || !(originOk || refererOk)) {
125
+ return new Response(JSON.stringify({ error: "Forbidden" }), {
126
+ status: 403,
127
+ headers: { "Content-Type": "application/json" },
128
+ });
41
129
  }
42
130
  }
43
131
 
@@ -53,15 +141,18 @@ export const onRequest = defineMiddleware(async (context, next) => {
53
141
  } else {
54
142
  hasUsers = true;
55
143
  }
56
- } catch {
57
- // Tables may not exist yet (first run, schema not pushed)
144
+ } catch (error) {
145
+ // Only a missing users table means first run (schema not pushed yet) — anything else
146
+ // (corruption, I/O) must surface, not funnel visitors to /admin/setup.
147
+ const message = error instanceof Error ? error.message : String(error);
148
+ if (!/no such table: cms_users/i.test(message)) throw error;
58
149
  hasUsers = false;
59
150
  }
60
151
  }
61
152
 
62
153
  // No users yet — redirect to setup
63
154
  if (!hasUsers) {
64
- if (isSetupPage || isSetupApi) return addSecurityHeaders(await next());
155
+ if (isSetupPage || isSetupApi) return serve();
65
156
  if (isAdminApiRoute) {
66
157
  return new Response(JSON.stringify({ error: "Setup required" }), { status: 403 });
67
158
  }
@@ -73,13 +164,35 @@ export const onRequest = defineMiddleware(async (context, next) => {
73
164
  return context.redirect("/admin/login");
74
165
  }
75
166
 
76
- // Always allow login page, login API, and cron endpoint (has its own auth)
77
- const isCronApi = pathname === "/api/cms/cron/publish";
78
- if (isLoginPage || isLoginApi || isSetupApi || isCronApi || isInvitePage || isInviteApi) {
79
- return addSecurityHeaders(await next());
167
+ // Always allow login page, login API, and cron/webhook endpoints (they have
168
+ // their own auth: bearer secret for cron, HMAC signature for webhooks)
169
+ const isCronApi = pathname === "/api/cms/cron/publish" || pathname === "/api/cms/cron/tasks";
170
+ const isWebhookApi = pathname.startsWith("/api/cms/webhooks/");
171
+ const isFormSubmit = pathname.startsWith("/api/cms/forms/submit/");
172
+ if (
173
+ isLoginPage ||
174
+ isLoginApi ||
175
+ isForgotPasswordPage ||
176
+ isForgotPasswordApi ||
177
+ isResetPasswordPage ||
178
+ isResetPasswordApi ||
179
+ isSsoAuthApi ||
180
+ isSetupApi ||
181
+ isCronApi ||
182
+ isWebhookApi ||
183
+ isInvitePage ||
184
+ isInviteApi ||
185
+ isFormSubmit
186
+ ) {
187
+ return serve();
80
188
  }
81
189
 
82
- const user = await getSessionUser(context.request);
190
+ const auth = resolveAdminAuth(config);
191
+ const customProvider = config.admin?.auth?.provider;
192
+ const user =
193
+ auth.provider === "custom" && typeof customProvider === "object"
194
+ ? normalizeCustomUser(await customProvider.getSession(context.request))
195
+ : await getSessionUser(context.request);
83
196
 
84
197
  if (!user) {
85
198
  // API routes → 401
@@ -96,5 +209,5 @@ export const onRequest = defineMiddleware(async (context, next) => {
96
209
  // Attach user to locals for downstream use
97
210
  context.locals.user = user;
98
211
 
99
- return addSecurityHeaders(await next());
100
- });
212
+ return serve();
213
+ };
@@ -0,0 +1,121 @@
1
+ /**
2
+ * Schema sync for the local SQLite dev database, runnable from scripts/CI.
3
+ *
4
+ * Applies the generated Drizzle schema (`.generated/schema.ts`) for **additive**
5
+ * changes (new tables / new columns) and FTS-safe diffs without a TTY — unlike
6
+ * `drizzle-kit push`, which the dev server shells out to and which needs a
7
+ * terminal. NOTE: a column **rename or drop** is ambiguous and drizzle-kit's
8
+ * resolver still requires a TTY (we surface a clear error below). For those,
9
+ * either DROP the affected table first (data loss — fine for a dev DB you're
10
+ * about to repopulate) and re-run, or hand-write a migration to preserve data.
11
+ *
12
+ * pnpm cms:push # sync ./data/cms.db (or CMS_DATABASE_URL)
13
+ * pnpm cms:generate && pnpm cms:push # after editing collections
14
+ *
15
+ * For Cloudflare D1 projects, keep using `drizzle-kit push` / wrangler — this
16
+ * script targets local better-sqlite3 only.
17
+ */
18
+ import { mkdirSync } from "node:fs";
19
+ import path from "node:path";
20
+ import Database from "better-sqlite3";
21
+ import { drizzle } from "drizzle-orm/better-sqlite3";
22
+ import { pushSQLiteSchema } from "drizzle-kit/api";
23
+
24
+ import * as schema from "../.generated/schema";
25
+
26
+ const dbPath = process.env.CMS_DATABASE_URL ?? path.join(process.cwd(), "data", "cms.db");
27
+
28
+ // The FTS5 search tables are created lazily at runtime (ensureSearchSchema) and
29
+ // are not part of the Drizzle schema, so the diff always wants to drop them.
30
+ // Mirror drizzle.config's `tablesFilter: ["!cms_search_index*"]` and skip those.
31
+ const isSearchIndexStatement = (stmt: string) => /\bcms_search_index/i.test(stmt);
32
+
33
+ // Tables to drop before pushing, so a column rename/drop becomes a non-interactive
34
+ // CREATE (data loss — intended for a dev DB you're repopulating). Accepts a comma
35
+ // list of collection slugs or table names; expands to the collection's
36
+ // _translations/_versions tables too.
37
+ // RECREATE=pages,posts pnpm cms:push (or --recreate=pages,posts)
38
+ const parseRecreate = (): string[] => {
39
+ const arg = process.argv.find((a) => a.startsWith("--recreate="))?.slice("--recreate=".length);
40
+ const raw = process.env.RECREATE ?? arg ?? "";
41
+ const tables = new Set<string>();
42
+ for (const name of raw
43
+ .split(",")
44
+ .map((s) => s.trim())
45
+ .filter(Boolean)) {
46
+ const base = name.startsWith("cms_") ? name : `cms_${name}`;
47
+ tables.add(base);
48
+ tables.add(`${base}_translations`);
49
+ tables.add(`${base}_versions`);
50
+ }
51
+ return [...tables];
52
+ };
53
+
54
+ async function main() {
55
+ if (dbPath !== ":memory:") mkdirSync(path.dirname(path.resolve(dbPath)), { recursive: true });
56
+
57
+ const sqlite = new Database(dbPath);
58
+ sqlite.pragma("foreign_keys = OFF"); // allow dropping referenced tables for --recreate
59
+ const db = drizzle(sqlite);
60
+
61
+ const recreate = parseRecreate();
62
+ if (recreate.length) {
63
+ for (const t of recreate) sqlite.exec(`DROP TABLE IF EXISTS ${t}`);
64
+ console.log(`[cms:push] dropped for recreate: ${recreate.join(", ")}`);
65
+ }
66
+
67
+ // pushSQLiteSchema().apply() assumes a libsql driver (calls .all() on DDL), so
68
+ // execute the diff statements directly against better-sqlite3 instead.
69
+ const isTtyPromptError = (error: unknown) => /TTY|Interactive prompts/i.test((error as Error).message);
70
+ let diff;
71
+ try {
72
+ diff = await pushSQLiteSchema({ ...schema }, db as never);
73
+ } catch (error) {
74
+ if (!isTtyPromptError(error)) {
75
+ sqlite.close();
76
+ throw error;
77
+ }
78
+ // The programmatic API has no tablesFilter, so when the schema CREATEs a new
79
+ // table, drizzle-kit sees the runtime-created FTS tables as deletion
80
+ // candidates and wants to ask "renamed?" interactively. Drop them (they're
81
+ // rebuilt lazily; search needs a reindex) and retry before giving up.
82
+ const ftsTables = sqlite
83
+ .prepare("SELECT name FROM sqlite_master WHERE type='table' AND name LIKE 'cms_search_index%'")
84
+ .all() as Array<{ name: string }>;
85
+ for (const { name } of ftsTables) sqlite.exec(`DROP TABLE IF EXISTS ${name}`);
86
+ if (ftsTables.length) {
87
+ console.log("[cms:push] Dropped runtime search-index tables to disambiguate the diff —");
88
+ console.log(" run `pnpm cms:reindex` afterwards to rebuild search.");
89
+ }
90
+ try {
91
+ diff = await pushSQLiteSchema({ ...schema }, db as never);
92
+ } catch (retryError) {
93
+ sqlite.close();
94
+ if (isTtyPromptError(retryError)) {
95
+ console.error(
96
+ "[cms:push] This change includes an ambiguous column rename/drop that drizzle-kit\n" +
97
+ " can only resolve interactively (no TTY here). Either DROP the affected\n" +
98
+ " table (data loss — fine for a dev DB you're repopulating) and re-run,\n" +
99
+ " or hand-write a migration to preserve the data.",
100
+ );
101
+ process.exit(1);
102
+ }
103
+ throw retryError;
104
+ }
105
+ }
106
+ const { statementsToExecute, hasDataLoss } = diff;
107
+ const statements = statementsToExecute.filter((stmt) => !isSearchIndexStatement(stmt));
108
+
109
+ if (statements.length === 0) {
110
+ console.log("[cms:push] Schema already in sync.");
111
+ } else {
112
+ for (const statement of statements) sqlite.exec(statement);
113
+ console.log(`[cms:push] Applied ${statements.length} statement(s)${hasDataLoss ? " (includes data loss)" : ""}.`);
114
+ if (hasDataLoss)
115
+ console.log("[cms:push] Tip: run `pnpm cms:reindex` to rebuild the search index if columns changed.");
116
+ }
117
+
118
+ sqlite.close();
119
+ }
120
+
121
+ await main();
package/package.json CHANGED
@@ -1,103 +1,91 @@
1
1
  {
2
2
  "name": "@kidecms/core",
3
- "version": "0.1.11",
4
- "description": "Code-first CMS framework built for Astro.",
5
- "author": "Matti Hernesniemi",
6
- "license": "MIT",
3
+ "version": "0.14.0",
4
+ "description": "Kide CMS runtime — core library, admin UI, routes, and middleware for Astro. Shipped as TypeScript source.",
7
5
  "type": "module",
8
- "main": "./dist/index.js",
9
- "types": "./dist/index.d.ts",
6
+ "license": "MIT",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "https://github.com/mhernesniemi/kide-cms.git"
10
+ },
11
+ "engines": {
12
+ "node": ">=22.12.0"
13
+ },
14
+ "bin": {
15
+ "kide": "./internals/cli.mjs"
16
+ },
10
17
  "exports": {
11
- ".": {
12
- "types": "./dist/index.d.ts",
13
- "import": "./dist/index.js"
14
- },
15
- "./integration": {
16
- "import": "./dist/integration.js"
17
- },
18
- "./admin/*": "./admin/*",
19
- "./routes/*": "./routes/*",
20
- "./middleware/*": "./middleware/*"
18
+ ".": "./core/index.ts",
19
+ "./astro": "./internals/integration.ts",
20
+ "./context": "./internals/context.ts",
21
+ "./youtube": "./core/youtube.ts",
22
+ "./client/preview": "./client/preview.ts",
23
+ "./platform/*": "./platform/*.ts",
24
+ "./package.json": "./package.json",
25
+ "./*": "./*"
21
26
  },
22
27
  "files": [
23
- "dist",
24
28
  "admin",
25
29
  "client",
26
- "routes",
30
+ "core",
31
+ "internals",
27
32
  "middleware",
28
- "virtual.d.ts"
33
+ "platform",
34
+ "routes",
35
+ "!**/__tests__",
36
+ "!**/__snapshots__",
37
+ "!**/*.test.ts",
38
+ "!**/*.workers.test.ts"
29
39
  ],
30
- "scripts": {
31
- "build": "tsc -p tsconfig.json"
32
- },
33
- "engines": {
34
- "node": ">=22.12.0"
40
+ "publishConfig": {
41
+ "access": "public"
35
42
  },
36
43
  "dependencies": {
44
+ "@ai-sdk/openai": "^3.0.41",
37
45
  "@base-ui/react": "^1.3.0",
38
46
  "@dnd-kit/core": "^6.3.1",
39
47
  "@dnd-kit/sortable": "^10.0.0",
40
48
  "@dnd-kit/utilities": "^3.2.2",
49
+ "@modelcontextprotocol/sdk": "^1.29.0",
41
50
  "@radix-ui/react-dropdown-menu": "^2.1.16",
42
51
  "@radix-ui/react-popover": "^1.1.15",
43
52
  "@tanstack/react-table": "^8.21.3",
44
- "@tiptap/core": "^3.22.3",
45
- "@tiptap/extension-image": "^3.22.3",
46
- "@tiptap/extension-link": "^3.22.3",
47
- "@tiptap/markdown": "^3.22.3",
48
- "@tiptap/pm": "^3.22.3",
49
- "@tiptap/react": "^3.22.3",
50
- "@tiptap/starter-kit": "^3.22.3",
53
+ "@tiptap/core": "3.22.4",
54
+ "@tiptap/extension-image": "3.22.4",
55
+ "@tiptap/extension-link": "3.22.4",
56
+ "@tiptap/extension-placeholder": "3.22.4",
57
+ "@tiptap/markdown": "3.22.4",
58
+ "@tiptap/pm": "3.22.4",
59
+ "@tiptap/react": "3.22.4",
60
+ "@tiptap/starter-kit": "3.22.4",
61
+ "@tiptap/suggestion": "3.22.4",
62
+ "ai": "^6.0.116",
51
63
  "class-variance-authority": "^0.7.1",
52
64
  "clsx": "^2.1.1",
53
65
  "cmdk": "^1.1.1",
54
- "drizzle-orm": "^0.45.0",
66
+ "drizzle-kit": "^0.31.9",
55
67
  "lucide-react": "^0.577.0",
56
- "nanoid": "^5.1.6",
68
+ "nanoid": "^6.0.1",
57
69
  "tailwind-merge": "^3.5.0",
58
- "tw-animate-css": "^1.4.0",
59
- "zod": "^4.3.6"
70
+ "tsx": "^4.21.0",
71
+ "tw-animate-css": "^1.4.0"
60
72
  },
61
73
  "peerDependencies": {
62
- "@ai-sdk/openai": "^3.0.0",
63
- "@astrojs/react": "^5.0.0",
64
- "ai": "^6.0.0",
65
- "astro": "^6.0.0",
74
+ "astro": "^7.0.0",
75
+ "better-sqlite3": "^12.0.0",
76
+ "drizzle-orm": "^0.45.1",
66
77
  "react": "^19.0.0",
67
78
  "react-dom": "^19.0.0",
68
- "sharp": "^0.34.0",
69
- "tailwindcss": "^4.0.0"
79
+ "sharp": "^0.35.0",
80
+ "tailwindcss": "^4.0.0",
81
+ "zod": "^4.0.0"
70
82
  },
71
83
  "peerDependenciesMeta": {
72
- "@ai-sdk/openai": {
73
- "optional": true
74
- },
75
- "@astrojs/react": {
76
- "optional": true
77
- },
78
- "react": {
79
- "optional": true
80
- },
81
- "react-dom": {
84
+ "better-sqlite3": {
82
85
  "optional": true
83
86
  },
84
87
  "sharp": {
85
88
  "optional": true
86
- },
87
- "ai": {
88
- "optional": true
89
- },
90
- "astro": {
91
- "optional": true
92
- },
93
- "tailwindcss": {
94
- "optional": true
95
89
  }
96
- },
97
- "devDependencies": {
98
- "@types/node": "^24.0.0",
99
- "@types/react": "^19.2.14",
100
- "@types/react-dom": "^19.2.3",
101
- "typescript": "^5.9.3"
102
90
  }
103
- }
91
+ }
@@ -0,0 +1,60 @@
1
+ /**
2
+ * Resolves the Cloudflare bindings (CMS_DB, CMS_ASSETS, …) in both runtimes the
3
+ * CMS runs in:
4
+ *
5
+ * - Worker (`astro dev`, and the deployed Worker): bindings come from the
6
+ * `cloudflare:workers` module.
7
+ * - Plain Node (`cms:seed`, `cms:admin`, `cms:reindex`, and your own import /
8
+ * migration scripts run with `node --import tsx`): that module doesn't
9
+ * exist, so we fall back to wrangler's getPlatformProxy(), which exposes the
10
+ * SAME local D1/R2 that `astro dev` uses (from .wrangler/state).
11
+ *
12
+ * This is what lets the cms:* scripts (and custom scripts) talk to the local
13
+ * database/storage from Node without being run inside the Worker.
14
+ */
15
+
16
+ // The bindings Kide's own Cloudflare profile reads — kept in sync with wrangler.toml's
17
+ // [[d1_databases]] and [[r2_buckets]]. Catches a binding-name typo at typecheck time.
18
+ export type CfEnv = { CMS_DB?: D1Database; CMS_ASSETS?: R2Bucket } & Record<string, unknown>;
19
+
20
+ type CfProxy = { env: CfEnv; dispose: () => Promise<void> };
21
+
22
+ let envPromise: Promise<CfEnv> | undefined;
23
+ let proxy: CfProxy | null = null;
24
+
25
+ const isWorker = () => typeof navigator !== "undefined" && navigator.userAgent === "Cloudflare-Workers";
26
+
27
+ export function getCfEnv(): Promise<CfEnv> {
28
+ envPromise ??= (async () => {
29
+ if (isWorker()) {
30
+ return (await import("cloudflare:workers")).env as CfEnv;
31
+ }
32
+ // Node: connect to the local miniflare state via wrangler. The specifier is
33
+ // kept off the static graph (variable + @vite-ignore) so wrangler is never
34
+ // pulled into the Worker bundle — this branch only runs in Node.
35
+ const wranglerSpecifier = "wrangler";
36
+ const { getPlatformProxy } = await import(/* @vite-ignore */ wranglerSpecifier);
37
+ proxy = (await getPlatformProxy()) as CfProxy;
38
+ return proxy.env;
39
+ })();
40
+ return envPromise;
41
+ }
42
+
43
+ /**
44
+ * Tear down the local platform proxy (Node only) so a one-shot script can exit.
45
+ * No-op inside the Worker. Safe to call multiple times. Flushes pending
46
+ * background writes (audit/search) first so they don't hit a disposed proxy.
47
+ */
48
+ export async function disposeCfEnv(): Promise<void> {
49
+ const p = proxy;
50
+ proxy = null;
51
+ envPromise = undefined;
52
+ if (!p) return;
53
+ try {
54
+ const { flushTasks } = await import("../../core");
55
+ await flushTasks();
56
+ } catch {
57
+ // core not loaded / nothing to flush
58
+ }
59
+ await p.dispose();
60
+ }
@@ -0,0 +1,28 @@
1
+ import { drizzle } from "drizzle-orm/d1";
2
+
3
+ import { disposeCfEnv, getCfEnv } from "./cf-env";
4
+
5
+ let dbInstance: ReturnType<typeof drizzle> | null = null;
6
+
7
+ // D1 migrations are applied out of band via `wrangler d1 migrations apply` —
8
+ // no boot-time schema work here, matching the Node profile.
9
+
10
+ export const getDb = async () => {
11
+ if (dbInstance) return dbInstance;
12
+
13
+ const env = await getCfEnv();
14
+ const db = env.CMS_DB;
15
+ if (!db) {
16
+ throw new Error("D1 database binding CMS_DB not found. Check wrangler.toml.");
17
+ }
18
+
19
+ dbInstance = drizzle(db);
20
+ return dbInstance;
21
+ };
22
+
23
+ // Returns a promise on the Cloudflare target — disposing the local platform
24
+ // proxy in Node so one-shot scripts can exit. A no-op inside the Worker.
25
+ export const closeDb = () => {
26
+ dbInstance = null;
27
+ return disposeCfEnv();
28
+ };
@@ -0,0 +1,5 @@
1
+ // Runtime module provided by the Workers runtime (nodejs_compat). Declared here so the
2
+ // Cloudflare profile type-checks under tsconfig.cloudflare.json without the full runtime.
3
+ declare module "cloudflare:workers" {
4
+ export const env: import("./cf-env").CfEnv;
5
+ }