@kidecms/core 0.1.10 → 0.13.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 (182) 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 +84 -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 +625 -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 +26 -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.data.ts +7 -0
  90. package/internals/seed.ts +11 -0
  91. package/internals/upgrade.ts +776 -0
  92. package/{virtual.d.ts → internals/virtual.d.ts} +39 -5
  93. package/middleware/auth.ts +130 -17
  94. package/middleware/push.ts +121 -0
  95. package/package.json +55 -67
  96. package/platform/cloudflare/cf-env.ts +60 -0
  97. package/platform/cloudflare/database.ts +28 -0
  98. package/platform/cloudflare/globals.d.ts +5 -0
  99. package/platform/cloudflare/storage.ts +33 -0
  100. package/platform/cloudflare/uploads-route.ts +37 -0
  101. package/platform/node/database.ts +39 -0
  102. package/platform/node/storage.ts +52 -0
  103. package/routes/admin/[...path].astro +71 -0
  104. package/routes/{pages/admin → admin}/assets/[id].astro +25 -19
  105. package/routes/admin/assets/index.astro +90 -0
  106. package/routes/admin/forgot-password.astro +60 -0
  107. package/routes/{pages/admin → admin}/invite.astro +7 -6
  108. package/routes/admin/login.astro +103 -0
  109. package/routes/admin/reset-password.astro +73 -0
  110. package/routes/{pages/admin → admin}/setup.astro +32 -8
  111. package/routes/api/{cms/[collection] → [collection]}/[...path].ts +66 -14
  112. package/routes/api/admin/search.ts +89 -0
  113. package/routes/api/{cms/assets → assets}/[id].ts +24 -14
  114. package/routes/api/{cms/assets → assets}/index.ts +4 -2
  115. package/routes/api/assets/upload.ts +147 -0
  116. package/routes/api/auth/forgot-password.ts +77 -0
  117. package/routes/api/{cms/auth → auth}/invite.ts +41 -9
  118. package/routes/api/auth/login.ts +167 -0
  119. package/routes/api/{cms/auth → auth}/logout.ts +11 -2
  120. package/routes/api/auth/reset-password.ts +85 -0
  121. package/routes/api/auth/setup.ts +110 -0
  122. package/routes/api/auth/sso/[provider]/start.ts +34 -0
  123. package/routes/api/collaboration/index.ts +106 -0
  124. package/routes/api/cron/_authorize.ts +25 -0
  125. package/routes/api/{cms/cron → cron}/publish.ts +3 -9
  126. package/routes/api/cron/tasks.ts +33 -0
  127. package/routes/api/forms/submit/[slug].ts +143 -0
  128. package/routes/api/img/[...path].ts +65 -0
  129. package/routes/api/{cms/preview → preview}/render.ts +8 -3
  130. package/routes/api/{cms/references → references}/[collection]/[id].ts +31 -1
  131. package/routes/api/webhooks/[provider].ts +54 -0
  132. package/README.md +0 -28
  133. package/dist/admin.d.ts +0 -33
  134. package/dist/admin.js +0 -92
  135. package/dist/ai.d.ts +0 -15
  136. package/dist/ai.js +0 -70
  137. package/dist/api.d.ts +0 -14
  138. package/dist/api.js +0 -833
  139. package/dist/assets.d.ts +0 -51
  140. package/dist/assets.js +0 -163
  141. package/dist/auth.d.ts +0 -30
  142. package/dist/auth.js +0 -132
  143. package/dist/content.d.ts +0 -3
  144. package/dist/content.js +0 -29
  145. package/dist/create-admin.d.ts +0 -5
  146. package/dist/create-admin.js +0 -23
  147. package/dist/define.d.ts +0 -254
  148. package/dist/define.js +0 -36
  149. package/dist/generator.d.ts +0 -9
  150. package/dist/generator.js +0 -370
  151. package/dist/image.d.ts +0 -9
  152. package/dist/image.js +0 -69
  153. package/dist/index.d.ts +0 -28
  154. package/dist/index.js +0 -16
  155. package/dist/integration.d.ts +0 -14
  156. package/dist/integration.js +0 -327
  157. package/dist/locks.d.ts +0 -7
  158. package/dist/locks.js +0 -37
  159. package/dist/richtext.d.ts +0 -1
  160. package/dist/richtext.js +0 -1
  161. package/dist/runtime.d.ts +0 -24
  162. package/dist/runtime.js +0 -26
  163. package/dist/schema.d.ts +0 -17
  164. package/dist/schema.js +0 -13
  165. package/dist/seed.d.ts +0 -2
  166. package/dist/seed.js +0 -84
  167. package/dist/values.d.ts +0 -8
  168. package/dist/values.js +0 -102
  169. package/dist/webhooks.d.ts +0 -2
  170. package/dist/webhooks.js +0 -73
  171. package/routes/api/cms/assets/upload.ts +0 -112
  172. package/routes/api/cms/auth/login.ts +0 -124
  173. package/routes/api/cms/auth/setup.ts +0 -77
  174. package/routes/api/cms/img/[...path].ts +0 -24
  175. package/routes/pages/admin/[...path].astro +0 -1107
  176. package/routes/pages/admin/assets/index.astro +0 -63
  177. package/routes/pages/admin/login.astro +0 -57
  178. /package/routes/api/{cms/ai → ai}/alt-text.ts +0 -0
  179. /package/routes/api/{cms/ai → ai}/seo.ts +0 -0
  180. /package/routes/api/{cms/ai → ai}/translate.ts +0 -0
  181. /package/routes/api/{cms/assets → assets}/folders.ts +0 -0
  182. /package/routes/api/{cms/locks → locks}/[...path].ts +0 -0
@@ -0,0 +1,73 @@
1
+ ---
2
+ import "virtual:kide/admin-css";
3
+
4
+ import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "../../admin/components/ui/card";
5
+ import { Input } from "../../admin/components/ui/input";
6
+ import { Label } from "../../admin/components/ui/label";
7
+ import { buttonVariants } from "../../admin/components/ui/button";
8
+ import { resolveAdminAuth } from "../../core";
9
+ import config from "virtual:kide/config";
10
+
11
+ export const prerender = false;
12
+
13
+ const auth = resolveAdminAuth(config);
14
+ if (!auth.password.forgotPassword) return Astro.redirect("/admin/login");
15
+
16
+ const token = Astro.url.searchParams.get("token") ?? "";
17
+ const error = Astro.url.searchParams.get("error");
18
+ const errorMessage =
19
+ error === "missing"
20
+ ? "Password is required."
21
+ : error === "password"
22
+ ? "Passwords do not match."
23
+ : error === "short"
24
+ ? "Password must be at least 12 characters."
25
+ : error === "invalid"
26
+ ? "This reset link is invalid or expired."
27
+ : null;
28
+ ---
29
+
30
+ <!doctype html>
31
+ <html lang="en">
32
+ <head>
33
+ <meta charset="utf-8" />
34
+ <meta name="viewport" content="width=device-width" />
35
+ <link rel="icon" type="image/svg+xml" href="/favicon.svg" />
36
+ <link rel="icon" href="/favicon.ico" />
37
+ <title>Choose new password | Kide CMS</title>
38
+ </head>
39
+ <body class="bg-background text-foreground min-h-screen antialiased">
40
+ <div class="flex min-h-screen items-center justify-center px-4">
41
+ <div class="w-full max-w-sm space-y-6">
42
+ <h1 class="text-center text-xl font-semibold tracking-tight">Kide CMS</h1>
43
+ <Card>
44
+ <CardHeader>
45
+ <CardTitle>Choose new password</CardTitle>
46
+ <CardDescription>Set a new password for your account</CardDescription>
47
+ </CardHeader>
48
+ <CardContent>
49
+ {
50
+ errorMessage && (
51
+ <div class="border-destructive/50 bg-destructive/10 text-destructive mb-4 rounded-lg border px-3 py-2 text-sm">
52
+ {errorMessage}
53
+ </div>
54
+ )
55
+ }
56
+ <form method="post" action="/api/cms/auth/reset-password" class="grid gap-4">
57
+ <input type="hidden" name="token" value={token} />
58
+ <div class="grid gap-2">
59
+ <Label htmlFor="password">New password</Label>
60
+ <Input id="password" name="password" type="password" required autoFocus />
61
+ </div>
62
+ <div class="grid gap-2">
63
+ <Label htmlFor="confirmPassword">Confirm password</Label>
64
+ <Input id="confirmPassword" name="confirmPassword" type="password" required />
65
+ </div>
66
+ <button class={buttonVariants({ size: "lg", className: "w-full" })} type="submit">Reset password</button>
67
+ </form>
68
+ </CardContent>
69
+ </Card>
70
+ </div>
71
+ </div>
72
+ </body>
73
+ </html>
@@ -1,10 +1,10 @@
1
1
  ---
2
2
  import "virtual:kide/admin-css";
3
3
 
4
- import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@kidecms/core/admin/components/ui/card";
5
- import { Input } from "@kidecms/core/admin/components/ui/input";
6
- import { Label } from "@kidecms/core/admin/components/ui/label";
7
- import { buttonVariants } from "@kidecms/core/admin/components/ui/button";
4
+ import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "../../admin/components/ui/card";
5
+ import { Input } from "../../admin/components/ui/input";
6
+ import { Label } from "../../admin/components/ui/label";
7
+ import { buttonVariants } from "../../admin/components/ui/button";
8
8
  import { getDb } from "virtual:kide/db";
9
9
 
10
10
  export const prerender = false;
@@ -27,7 +27,7 @@ const errorMessage =
27
27
  : error === "password"
28
28
  ? "Passwords do not match."
29
29
  : error === "short"
30
- ? "Password must be at least 8 characters."
30
+ ? "Password must be at least 12 characters."
31
31
  : null;
32
32
  ---
33
33
 
@@ -43,6 +43,7 @@ const errorMessage =
43
43
  <body class="bg-background text-foreground min-h-screen antialiased">
44
44
  <div class="flex min-h-screen items-center justify-center px-4">
45
45
  <div class="w-full max-w-sm space-y-6">
46
+ <h1 class="text-center text-xl font-semibold tracking-tight">Kide CMS</h1>
46
47
  <Card>
47
48
  <CardHeader>
48
49
  <CardTitle>Create admin account</CardTitle>
@@ -59,15 +60,37 @@ const errorMessage =
59
60
  <form method="post" action="/api/cms/auth/setup" class="grid gap-4">
60
61
  <div class="grid gap-2">
61
62
  <Label htmlFor="name">Name</Label>
62
- <Input id="name" name="name" type="text" placeholder="Your name" required autoFocus />
63
+ <Input
64
+ id="name"
65
+ name="name"
66
+ type="text"
67
+ placeholder="Your name"
68
+ autoComplete="off"
69
+ required
70
+ autoFocus
71
+ />
63
72
  </div>
64
73
  <div class="grid gap-2">
65
74
  <Label htmlFor="email">Email</Label>
66
- <Input id="email" name="email" type="email" placeholder="admin@example.com" required />
75
+ <Input
76
+ id="email"
77
+ name="email"
78
+ type="email"
79
+ placeholder="admin@example.com"
80
+ autoComplete="off"
81
+ required
82
+ />
67
83
  </div>
68
84
  <div class="grid gap-2">
69
85
  <Label htmlFor="password">Password</Label>
70
- <Input id="password" name="password" type="password" placeholder="Min 8 characters" required />
86
+ <Input
87
+ id="password"
88
+ name="password"
89
+ type="password"
90
+ placeholder="Min 12 characters"
91
+ autoComplete="new-password"
92
+ required
93
+ />
71
94
  </div>
72
95
  <div class="grid gap-2">
73
96
  <Label htmlFor="confirmPassword">Confirm password</Label>
@@ -76,6 +99,7 @@ const errorMessage =
76
99
  name="confirmPassword"
77
100
  type="password"
78
101
  placeholder="Repeat password"
102
+ autoComplete="new-password"
79
103
  required
80
104
  />
81
105
  </div>
@@ -2,11 +2,28 @@ import type { APIRoute } from "astro";
2
2
 
3
3
  import config from "virtual:kide/config";
4
4
  import { cms } from "virtual:kide/api";
5
+ import { collaboration } from "virtual:kide/runtime";
6
+ import { isApprover, resolveCollaboration } from "../../../core";
7
+ import { loadSharedSectionUsageCounts } from "../../../admin/lib/edit-data";
5
8
 
6
9
  export const prerender = false;
7
10
 
8
11
  const cmsRuntime = cms as Record<string, any> & { meta: typeof cms.meta };
9
12
 
13
+ // Editorial gate: when the collection requires approval, publishing/scheduling a
14
+ // draft-enabled document is blocked until its review is approved. Approvers bypass.
15
+ const publishAllowed = async (
16
+ collection: { slug: string; drafts?: boolean },
17
+ documentId: string,
18
+ locals: App.Locals,
19
+ ): Promise<boolean> => {
20
+ const { enabled, requireApproval } = resolveCollaboration(config, collection.slug);
21
+ if (!enabled || !requireApproval || !collection.drafts) return true;
22
+ if (isApprover(config, locals.user?.role)) return true;
23
+ const { reviewState } = await collaboration.getState(collection.slug, documentId);
24
+ return reviewState === "approved";
25
+ };
26
+
10
27
  const getSegments = (path: string | undefined) => (path ?? "").split("/").filter(Boolean);
11
28
 
12
29
  const isFormRequest = (request: Request) => {
@@ -95,9 +112,11 @@ const handleHtmlMutation = async (
95
112
  try {
96
113
  if (action === "create") {
97
114
  const created = await collectionApi.create(data, ctx);
98
- if (collection.drafts && intent === "publish") {
115
+ const wantsGoLive = collection.drafts && (intent === "publish" || (intent === "schedule" && data._publishAt));
116
+ const blocked = wantsGoLive && !(await publishAllowed(collection, created._id, locals));
117
+ if (collection.drafts && intent === "publish" && !blocked) {
99
118
  await collectionApi.publish(created._id, ctx);
100
- } else if (collection.drafts && intent === "schedule" && data._publishAt) {
119
+ } else if (collection.drafts && intent === "schedule" && data._publishAt && !blocked) {
101
120
  await collectionApi.schedule(
102
121
  created._id,
103
122
  String(data._publishAt),
@@ -105,13 +124,14 @@ const handleHtmlMutation = async (
105
124
  ctx,
106
125
  );
107
126
  }
108
- const msg =
109
- intent === "publish"
127
+ const msg = blocked
128
+ ? `${name} saved as draft — needs review approval before publishing`
129
+ : intent === "publish"
110
130
  ? `${name} created and published`
111
131
  : intent === "schedule"
112
132
  ? `${name} scheduled`
113
133
  : `${name} created`;
114
- return redirect(`/admin/${collectionSlug}/${created._id}`, { status: "success", msg });
134
+ return redirect(`/admin/${collectionSlug}/${created._id}`, { status: blocked ? "error" : "success", msg });
115
135
  }
116
136
 
117
137
  if (!documentId) {
@@ -120,29 +140,38 @@ const handleHtmlMutation = async (
120
140
 
121
141
  if (action === "update") {
122
142
  await collectionApi.update(documentId, data, ctx);
123
- if (collection.drafts && intent === "publish") {
143
+ const wantsGoLive = collection.drafts && (intent === "publish" || (intent === "schedule" && data._publishAt));
144
+ const blocked = wantsGoLive && !(await publishAllowed(collection, documentId, locals));
145
+ if (collection.drafts && intent === "publish" && !blocked) {
124
146
  await collectionApi.publish(documentId, ctx);
125
147
  } else if (collection.drafts && intent === "unpublish") {
126
148
  await collectionApi.unpublish(documentId, ctx);
127
- } else if (collection.drafts && intent === "schedule" && data._publishAt) {
149
+ } else if (collection.drafts && intent === "schedule" && data._publishAt && !blocked) {
128
150
  await collectionApi.schedule(
129
151
  documentId,
130
152
  String(data._publishAt),
131
153
  data._unpublishAt ? String(data._unpublishAt) : null,
132
154
  ctx,
133
155
  );
156
+ } else if (intent === "submit-review" && resolveCollaboration(config, collectionSlug).enabled) {
157
+ // Save the draft (above) and move the review to "ready for review".
158
+ const actor = locals.user ? { id: locals.user.id, email: locals.user.email, role: locals.user.role } : null;
159
+ await collaboration.submitForReview(collectionSlug, documentId, actor);
134
160
  }
135
- const msg =
136
- intent === "publish"
161
+ const msg = blocked
162
+ ? `Saved — needs review approval before publishing`
163
+ : intent === "publish"
137
164
  ? `${name} published`
138
165
  : intent === "unpublish"
139
166
  ? `${name} unpublished`
140
167
  : intent === "schedule"
141
168
  ? `${name} scheduled`
142
- : collection.drafts
143
- ? `${name} saved as draft`
144
- : `${name} saved`;
145
- return redirect(redirectTo, { status: "success", msg });
169
+ : intent === "submit-review"
170
+ ? `Saved and submitted for review`
171
+ : collection.drafts
172
+ ? `${name} saved as draft`
173
+ : `${name} saved`;
174
+ return redirect(redirectTo, { status: blocked ? "error" : "success", msg });
146
175
  }
147
176
 
148
177
  if (action === "delete") {
@@ -151,6 +180,9 @@ const handleHtmlMutation = async (
151
180
  }
152
181
 
153
182
  if (action === "publish") {
183
+ if (!(await publishAllowed(collection, documentId, locals))) {
184
+ return redirect(redirectTo, { status: "error", msg: `${name} needs review approval before publishing` });
185
+ }
154
186
  await collectionApi.publish(documentId, ctx);
155
187
  return redirect(redirectTo, { status: "success", msg: `${name} published` });
156
188
  }
@@ -241,6 +273,20 @@ export const GET: APIRoute = async ({ params, url, locals }) => {
241
273
  cmsRuntime[collectionSlug].count({ where: findOptions.where, status: findOptions.status, locale, search }, ctx),
242
274
  ]);
243
275
 
276
+ if (collectionSlug === "shared-sections") {
277
+ const usageCounts = await loadSharedSectionUsageCounts(
278
+ docs.map((entry: Record<string, unknown>) => String(entry._id)),
279
+ config,
280
+ locals.user,
281
+ cmsRuntime,
282
+ config.locales?.default ?? "en",
283
+ ctx,
284
+ );
285
+ for (const entry of docs as Array<Record<string, unknown>>) {
286
+ entry.__usage = usageCounts[String(entry._id)] ?? 0;
287
+ }
288
+ }
289
+
244
290
  const page = Math.floor(offset / limit) + 1;
245
291
  const totalPages = Math.ceil(totalDocs / limit);
246
292
 
@@ -265,6 +311,9 @@ export const POST: APIRoute = async ({ params, request, locals, cache }) => {
265
311
  const collectionApi = cmsRuntime[collectionSlug];
266
312
 
267
313
  if (pathAction === "publish" && documentId) {
314
+ if (!(await publishAllowed(getCollection(collectionSlug), documentId, locals))) {
315
+ return Response.json({ error: "Needs review approval before publishing." }, { status: 403 });
316
+ }
268
317
  return Response.json(await collectionApi.publish(documentId, ctx));
269
318
  }
270
319
 
@@ -273,6 +322,9 @@ export const POST: APIRoute = async ({ params, request, locals, cache }) => {
273
322
  }
274
323
 
275
324
  if (pathAction === "schedule" && documentId) {
325
+ if (!(await publishAllowed(getCollection(collectionSlug), documentId, locals))) {
326
+ return Response.json({ error: "Needs review approval before scheduling." }, { status: 403 });
327
+ }
276
328
  const body = await request.json();
277
329
  return Response.json(await collectionApi.schedule(documentId, body.publishAt, body.unpublishAt ?? null, ctx));
278
330
  }
@@ -307,7 +359,7 @@ export const POST: APIRoute = async ({ params, request, locals, cache }) => {
307
359
  // Copy translations if the collection supports them
308
360
  if (collectionApi.getTranslations && collectionApi.upsertTranslation) {
309
361
  try {
310
- const translations = await collectionApi.getTranslations(documentId);
362
+ const translations = await collectionApi.getTranslations(documentId, ctx);
311
363
  if (translations && typeof translations === "object") {
312
364
  for (const [locale, translationData] of Object.entries(translations)) {
313
365
  if (!translationData || typeof translationData !== "object") continue;
@@ -0,0 +1,89 @@
1
+ import type { APIRoute } from "astro";
2
+
3
+ import { cms } from "virtual:kide/api";
4
+ import config from "virtual:kide/config";
5
+ import { getLabelField } from "../../../core";
6
+
7
+ export const prerender = false;
8
+
9
+ const HIDDEN_FROM_SEARCH = new Set(["form-submissions"]);
10
+ const PER_COLLECTION = 5;
11
+ const TOTAL_CAP = 30;
12
+
13
+ type SearchResult = {
14
+ collection: string;
15
+ collectionLabel: string;
16
+ docId: string;
17
+ title: string;
18
+ editUrl: string;
19
+ status: string | null;
20
+ };
21
+
22
+ export const GET: APIRoute = async ({ url, locals }) => {
23
+ if (!locals.user) {
24
+ return Response.json({ error: "Unauthorized" }, { status: 401 });
25
+ }
26
+
27
+ const q = (url.searchParams.get("q") ?? "").trim();
28
+ if (q.length < 2) return Response.json({ results: [] });
29
+
30
+ const cmsAny = cms as Record<string, any>;
31
+ const results: SearchResult[] = [];
32
+
33
+ const qLower = q.toLowerCase();
34
+
35
+ for (const collection of config.collections) {
36
+ if (HIDDEN_FROM_SEARCH.has(collection.slug)) continue;
37
+
38
+ const api = cmsAny[collection.slug];
39
+ if (!api?.find) continue;
40
+
41
+ // Singletons: there's exactly one doc, so we don't run a body search — instead match
42
+ // on the collection's singular label (which is what gets shown to admins). Body-search
43
+ // would fight UX: e.g. searching "front" for the "Front page" singleton must find it
44
+ // even if the singleton's body text says nothing about "front".
45
+ if (collection.singleton) {
46
+ if (!collection.labels.singular.toLowerCase().includes(qLower)) continue;
47
+ const docs = await api
48
+ .find({ status: "any", limit: 1 }, { user: locals.user })
49
+ .catch(() => null as Array<Record<string, unknown>> | null);
50
+ if (!docs || docs.length === 0) continue;
51
+ const doc = docs[0];
52
+ results.push({
53
+ collection: collection.slug,
54
+ // Match the sidebar grouping: every singleton lives under one "Singles" header.
55
+ collectionLabel: "Single",
56
+ docId: String(doc._id),
57
+ title: collection.labels.singular,
58
+ editUrl: `/admin/${collection.slug}/${doc._id}`,
59
+ status: typeof doc._status === "string" ? doc._status : null,
60
+ });
61
+ if (results.length >= TOTAL_CAP) break;
62
+ continue;
63
+ }
64
+
65
+ const docs = await api
66
+ .find({ search: q, status: "any", limit: PER_COLLECTION }, { user: locals.user })
67
+ .catch(() => null as Array<Record<string, unknown>> | null);
68
+
69
+ // access denied or runtime error — skip this collection silently
70
+ if (!docs) continue;
71
+
72
+ const labelField = getLabelField(collection);
73
+ for (const doc of docs) {
74
+ const title = String(doc[labelField] ?? doc.slug ?? doc._id);
75
+ results.push({
76
+ collection: collection.slug,
77
+ collectionLabel: collection.labels.singular,
78
+ docId: String(doc._id),
79
+ title,
80
+ editUrl: `/admin/${collection.slug}/${doc._id}`,
81
+ status: typeof doc._status === "string" ? doc._status : null,
82
+ });
83
+ if (results.length >= TOTAL_CAP) break;
84
+ }
85
+ if (results.length >= TOTAL_CAP) break;
86
+ }
87
+
88
+ return Response.json({ results });
89
+ };
@@ -13,7 +13,12 @@ export const GET: APIRoute = async ({ params }) => {
13
13
  return Response.json(asset);
14
14
  };
15
15
 
16
- export const PATCH: APIRoute = async ({ params, request }) => {
16
+ const getActor = (locals: App.Locals) => {
17
+ const user = locals.user;
18
+ return user ? { id: user.id, email: user.email, role: user.role } : null;
19
+ };
20
+
21
+ export const PATCH: APIRoute = async ({ params, request, locals }) => {
17
22
  const id = params.id;
18
23
  if (!id) return Response.json({ error: "Asset ID is required." }, { status: 400 });
19
24
 
@@ -31,47 +36,52 @@ export const PATCH: APIRoute = async ({ params, request }) => {
31
36
  if (body.focalX === null || typeof body.focalX === "number") data.focalX = body.focalX;
32
37
  if (body.focalY === null || typeof body.focalY === "number") data.focalY = body.focalY;
33
38
 
34
- const result = await assets.update(id, data);
39
+ const result = await assets.update(id, data, { actor: getActor(locals) });
35
40
  if (!result) return Response.json({ error: "Not found." }, { status: 404 });
36
41
 
37
42
  return Response.json(result);
38
43
  };
39
44
 
40
- export const DELETE: APIRoute = async ({ params }) => {
45
+ export const DELETE: APIRoute = async ({ params, locals }) => {
41
46
  const id = params.id;
42
47
  if (!id) return new Response(null, { status: 400 });
43
48
 
44
- await assets.delete(id);
49
+ await assets.delete(id, { actor: getActor(locals) });
45
50
  return new Response(null, { status: 204 });
46
51
  };
47
52
 
48
- export const POST: APIRoute = async ({ params, request }) => {
53
+ export const POST: APIRoute = async ({ params, request, locals }) => {
49
54
  const id = params.id;
50
55
  if (!id) return new Response(null, { status: 400 });
51
56
 
52
57
  const formData = new URLSearchParams(await request.text());
53
58
  const method = formData.get("_method");
59
+ const action = formData.get("_action");
60
+ const actor = getActor(locals);
54
61
 
55
- if (method === "DELETE") {
56
- await assets.delete(id);
62
+ if (method === "DELETE" || action === "delete") {
63
+ await assets.delete(id, { actor });
57
64
  return new Response(null, {
58
65
  status: 303,
59
66
  headers: { Location: "/admin/assets?_toast=success&_msg=Asset+deleted" },
60
67
  });
61
68
  }
62
69
 
63
- const action = formData.get("_action");
64
70
  if (action === "update") {
65
71
  const alt = formData.get("alt");
66
72
  const folder = formData.get("folder");
67
73
  const focalX = formData.get("focalX");
68
74
  const focalY = formData.get("focalY");
69
- await assets.update(id, {
70
- alt: alt !== null ? alt : undefined,
71
- folder: folder !== null ? (folder === "" ? null : folder) : undefined,
72
- focalX: focalX !== null ? (focalX === "" ? null : Number(focalX)) : undefined,
73
- focalY: focalY !== null ? (focalY === "" ? null : Number(focalY)) : undefined,
74
- });
75
+ await assets.update(
76
+ id,
77
+ {
78
+ alt: alt !== null ? alt : undefined,
79
+ folder: folder !== null ? (folder === "" ? null : folder) : undefined,
80
+ focalX: focalX !== null ? (focalX === "" ? null : Number(focalX)) : undefined,
81
+ focalY: focalY !== null ? (focalY === "" ? null : Number(focalY)) : undefined,
82
+ },
83
+ { actor },
84
+ );
75
85
  return new Response(null, {
76
86
  status: 303,
77
87
  headers: { Location: `/admin/assets/${id}?_toast=success&_msg=Asset+updated` },
@@ -14,10 +14,12 @@ export const GET: APIRoute = async ({ url }) => {
14
14
  const limit = url.searchParams.get("limit") ? Number(url.searchParams.get("limit")) : 50;
15
15
  const offset = url.searchParams.get("offset") ? Number(url.searchParams.get("offset")) : 0;
16
16
  const folderParam = url.searchParams.get("folder");
17
+ // folder scope: absent → undefined (every asset, unscoped) · "" → null (unfiled/root) · id → that folder
17
18
  const folder = folderParam !== null ? (folderParam === "" ? null : folderParam) : undefined;
19
+ const search = url.searchParams.get("q")?.trim() || undefined;
18
20
 
19
- const items = await assets.find({ limit, offset, folder });
20
- const total = await assets.count();
21
+ const items = await assets.find({ limit, offset, folder, search });
22
+ const total = await assets.count({ folder, search });
21
23
 
22
24
  return Response.json({ items, total });
23
25
  };
@@ -0,0 +1,147 @@
1
+ import type { APIRoute } from "astro";
2
+ import { assets } from "virtual:kide/runtime";
3
+ import config from "virtual:kide/config";
4
+ import { PayloadTooLargeError, readLimitedFormData } from "../../../core";
5
+
6
+ export const prerender = false;
7
+
8
+ // SVG is deliberately absent — it executes script when served inline from the admin's
9
+ // origin. Re-enable via `admin.uploads.allowedTypes` only behind a CSP or Content-Disposition.
10
+ const DEFAULT_ALLOWED_TYPES = [
11
+ "image/jpeg",
12
+ "image/png",
13
+ "image/gif",
14
+ "image/webp",
15
+ "image/avif",
16
+ "application/pdf",
17
+ "video/mp4",
18
+ "video/webm",
19
+ ];
20
+
21
+ const ALLOWED_TYPES = new Set(config.admin?.uploads?.allowedTypes ?? DEFAULT_ALLOWED_TYPES);
22
+ const MAX_FILE_SIZE = config.admin?.uploads?.maxFileSize ?? 50 * 1024 * 1024; // 50 MB
23
+ const MAX_FILES_PER_UPLOAD = 20;
24
+
25
+ // Magic number signatures for binary file type verification
26
+ const MAGIC_SIGNATURES: Array<{ type: string; bytes: number[]; offset?: number }> = [
27
+ { type: "image/jpeg", bytes: [0xff, 0xd8, 0xff] },
28
+ { type: "image/png", bytes: [0x89, 0x50, 0x4e, 0x47] },
29
+ { type: "image/gif", bytes: [0x47, 0x49, 0x46, 0x38] },
30
+ { type: "image/webp", bytes: [0x52, 0x49, 0x46, 0x46], offset: 0 }, // RIFF....WEBP
31
+ { type: "application/pdf", bytes: [0x25, 0x50, 0x44, 0x46] },
32
+ { type: "video/mp4", bytes: [0x66, 0x74, 0x79, 0x70], offset: 4 }, // ....ftyp
33
+ ];
34
+
35
+ function verifyMagicBytes(buffer: ArrayBuffer, declaredType: string): boolean {
36
+ // SVG and text-based formats can't be verified by magic bytes
37
+ if (declaredType === "image/svg+xml") {
38
+ const text = new TextDecoder().decode(buffer.slice(0, 256));
39
+ return text.includes("<svg") || text.trimStart().startsWith("<?xml");
40
+ }
41
+
42
+ const header = new Uint8Array(buffer.slice(0, 16));
43
+ for (const sig of MAGIC_SIGNATURES) {
44
+ if (sig.type !== declaredType) continue;
45
+ const offset = sig.offset ?? 0;
46
+ const match = sig.bytes.every((byte, i) => header[offset + i] === byte);
47
+ if (match) return true;
48
+ }
49
+
50
+ // AVIF is an ISOBMFF container — check for ftyp box with avif brand
51
+ if (declaredType === "image/avif") {
52
+ const offset4 = new Uint8Array(buffer.slice(4, 12));
53
+ const ftypStr = String.fromCharCode(...offset4);
54
+ return ftypStr.startsWith("ftyp") && ftypStr.includes("avif");
55
+ }
56
+
57
+ // video/webm starts with EBML header
58
+ if (declaredType === "video/webm") {
59
+ return header[0] === 0x1a && header[1] === 0x45 && header[2] === 0xdf && header[3] === 0xa3;
60
+ }
61
+
62
+ return false;
63
+ }
64
+
65
+ export const POST: APIRoute = async ({ request, locals }) => {
66
+ const contentType = request.headers.get("content-type") ?? "";
67
+
68
+ if (!contentType.includes("multipart/form-data")) {
69
+ return Response.json({ error: "Expected multipart/form-data." }, { status: 400 });
70
+ }
71
+
72
+ // Enforce the size cap on the raw byte stream — Content-Length is optional (absent on
73
+ // chunked requests) and checking `file.size` only after formData() already buffered
74
+ // everything is too late. A small overhead covers non-file fields + multipart framing.
75
+ let formData: FormData;
76
+ try {
77
+ formData = await readLimitedFormData(request, MAX_FILES_PER_UPLOAD * MAX_FILE_SIZE + 64 * 1024);
78
+ } catch (error) {
79
+ if (error instanceof PayloadTooLargeError) {
80
+ return Response.json({ error: "Upload exceeds the size limit." }, { status: 413 });
81
+ }
82
+ throw error;
83
+ }
84
+ const files = formData.getAll("file").filter((entry): entry is File => entry instanceof File);
85
+ const alt = formData.get("alt");
86
+ const folder = formData.get("folder");
87
+
88
+ if (files.length === 0) {
89
+ return Response.json({ error: "No file provided." }, { status: 400 });
90
+ }
91
+
92
+ if (files.length > MAX_FILES_PER_UPLOAD) {
93
+ return Response.json({ error: `Too many files (max ${MAX_FILES_PER_UPLOAD} per upload).` }, { status: 400 });
94
+ }
95
+
96
+ // Validate every file before storing any, so a bad file mid-batch never
97
+ // leaves a partial upload behind.
98
+ for (const file of files) {
99
+ if (!ALLOWED_TYPES.has(file.type)) {
100
+ return Response.json({ error: `File type "${file.type}" is not allowed.` }, { status: 400 });
101
+ }
102
+
103
+ if (file.size > MAX_FILE_SIZE) {
104
+ return Response.json(
105
+ { error: `"${file.name}" exceeds the ${MAX_FILE_SIZE / 1024 / 1024} MB size limit.` },
106
+ { status: 400 },
107
+ );
108
+ }
109
+
110
+ // Verify via the header only (slice leaves `file` unconsumed → assets.upload reads it once).
111
+ const header = await file.slice(0, 256).arrayBuffer();
112
+ if (!verifyMagicBytes(header, file.type)) {
113
+ return Response.json({ error: `"${file.name}" content does not match declared type.` }, { status: 400 });
114
+ }
115
+ }
116
+
117
+ const user = locals.user;
118
+ const actor = user ? { id: user.id, email: user.email, role: user.role } : null;
119
+ const uploaded = [];
120
+ for (const file of files) {
121
+ uploaded.push(
122
+ await assets.upload(
123
+ file,
124
+ {
125
+ // alt describes one file — never apply the same text to a whole batch
126
+ alt: alt && files.length === 1 ? String(alt) : undefined,
127
+ folder: folder ? String(folder) : undefined,
128
+ },
129
+ { actor },
130
+ ),
131
+ );
132
+ }
133
+
134
+ const redirectTo = formData.get("redirectTo");
135
+
136
+ if (redirectTo) {
137
+ // Delay so Vite's dev server picks up the new files before the redirect
138
+ await new Promise((r) => setTimeout(r, 1000));
139
+ const location =
140
+ uploaded.length === 1
141
+ ? `/admin/assets/${uploaded[0]._id}?_toast=success&_msg=Asset+uploaded`
142
+ : `/admin/assets?_toast=success&_msg=${uploaded.length}+assets+uploaded`;
143
+ return new Response(null, { status: 303, headers: { Location: location } });
144
+ }
145
+
146
+ return Response.json(uploaded.length === 1 ? uploaded[0] : uploaded, { status: 201 });
147
+ };