@kidecms/core 0.15.0 → 0.16.1

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.
@@ -806,7 +806,7 @@ export default function AssetsGrid({
806
806
 
807
807
  {/* Selection toolbar */}
808
808
  {selectedIds.size > 0 && (
809
- <div className="bg-muted/40 flex items-center justify-between gap-3 rounded-lg border px-3 py-2">
809
+ <div className="bg-background sticky top-4 z-20 flex items-center justify-between gap-3 rounded-lg border px-3 py-2 shadow-sm">
810
810
  <span className="text-sm font-medium">{selectedIds.size} selected</span>
811
811
  <div className="flex items-center gap-2">
812
812
  <Button
@@ -20,7 +20,7 @@ const buttonVariants = cva(
20
20
  ghost:
21
21
  "border-transparent hover:bg-foreground/8 hover:text-foreground aria-expanded:bg-foreground/8 aria-expanded:text-foreground dark:hover:bg-foreground/15 dark:aria-expanded:bg-foreground/15",
22
22
  destructive:
23
- "border-transparent bg-destructive/10 text-destructive hover:bg-destructive/20 dark:bg-destructive/20 dark:hover:bg-destructive/30",
23
+ "bg-red-100 hover:bg-red-200/70 text-red-800 border-red-300 dark:bg-red-500/20 dark:hover:bg-red-500/30 dark:border-red-900 dark:text-red-200",
24
24
  link: "border-transparent text-primary underline-offset-4 hover:underline",
25
25
  },
26
26
  size: {
@@ -11,6 +11,7 @@ import {
11
11
  formatDate,
12
12
  formatFieldValue,
13
13
  formatPagePath,
14
+ getPageHref,
14
15
  getLabelField,
15
16
  getListColumns,
16
17
  getTranslatableFieldNames,
@@ -175,7 +176,7 @@ const tableRows = docs.map((entry: Record<string, unknown>) => {
175
176
  : []),
176
177
  ],
177
178
  searchText: String(entry[getLabelField(collection)] ?? entry.slug ?? entry._id ?? ""),
178
- pageHref: pagePath ? `${pagePath}?preview=true` : undefined,
179
+ pageHref: pagePath ? getPageHref(pagePath, !collection.drafts || entry._status === "published") : undefined,
179
180
  values: Object.fromEntries(displayColumns.map((column) => [column, formatColumnValue(column, entry, pagePath)])),
180
181
  };
181
182
  });
@@ -2,7 +2,7 @@
2
2
  import DocumentsDataTable from "../components/DocumentsDataTable";
3
3
  import config from "virtual:kide/config";
4
4
  import { cms } from "virtual:kide/api";
5
- import { formatDate, formatPagePath, getTranslatableFieldNames } from "../../core";
5
+ import { formatDate, formatPagePath, getPageHref, getTranslatableFieldNames } from "../../core";
6
6
  import { canRead } from "../lib/access";
7
7
 
8
8
  const user = Astro.locals.user;
@@ -46,7 +46,9 @@ const singletonsData = await Promise.all(
46
46
  updatedAt: singleDoc ? formatDate(singleDoc._updatedAt) : "—",
47
47
  editHref: `/admin/${sc.slug}`,
48
48
  page: pagePath,
49
- pageHref: pagePath ? `${pagePath}?preview=true` : null,
49
+ pageHref: pagePath
50
+ ? getPageHref(pagePath, !!singleDoc && (!sc.drafts || singleDoc._status === "published"))
51
+ : null,
50
52
  };
51
53
  }),
52
54
  );
package/client/preview.ts CHANGED
@@ -33,3 +33,58 @@ if (new URLSearchParams(location.search).has("preview")) {
33
33
  }
34
34
  };
35
35
  }
36
+
37
+ // --- Edit bar: "Edit this page" chip on public pages for logged-in editors ---
38
+ // Zero-cost for anonymous visitors: only acts when the non-httpOnly `kide-editor`
39
+ // hint cookie (set by the auth middleware on admin visits) is present, and only
40
+ // then verifies the real session via the edit-bar endpoint. Renders into a shadow
41
+ // root so site CSS can't leak in. Skipped in preview mode (the editor is already
42
+ // editing in another tab) and on admin pages.
43
+ if (
44
+ !new URLSearchParams(location.search).has("preview") &&
45
+ !location.pathname.startsWith("/admin") &&
46
+ document.cookie.split("; ").includes("kide-editor=1")
47
+ ) {
48
+ const marker = document.querySelector("[data-cms-doc]");
49
+ const ref = marker?.getAttribute("data-cms-doc");
50
+ if (ref) {
51
+ fetch(`/api/cms/edit-bar?doc=${encodeURIComponent(ref)}`)
52
+ .then((r) => {
53
+ if (r.status === 401) {
54
+ // Session gone — drop the hint so future page views stay request-free.
55
+ document.cookie = "kide-editor=; Path=/; Max-Age=0";
56
+ return null;
57
+ }
58
+ return r.ok ? r.json() : null;
59
+ })
60
+ .then((data: { editUrl: string; status: string | null } | null) => {
61
+ if (!data) return;
62
+ const host = document.createElement("div");
63
+ const shadow = host.attachShadow({ mode: "open" });
64
+ // Static markup only — editUrl embeds a caller-suppliable document id, so
65
+ // it goes through setAttribute, never into an HTML string.
66
+ shadow.innerHTML = `
67
+ <style>
68
+ a {
69
+ position: fixed; right: 16px; bottom: 16px; z-index: 2147483647;
70
+ display: inline-flex; align-items: center; gap: 8px;
71
+ padding: 8px 14px; border-radius: 999px;
72
+ background: #18181b; color: #fafafa;
73
+ font: 500 13px/1 system-ui, sans-serif; text-decoration: none;
74
+ box-shadow: 0 2px 12px rgba(0, 0, 0, 0.25);
75
+ }
76
+ a:hover { background: #303036; }
77
+ svg { width: 13px; height: 13px; }
78
+ </style>
79
+ <a>
80
+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
81
+ <path d="M17 3a2.85 2.83 0 1 1 4 4L7.5 20.5 2 22l1.5-5.5Z" />
82
+ </svg>
83
+ Edit this page
84
+ </a>`;
85
+ shadow.querySelector("a")!.setAttribute("href", data.editUrl);
86
+ document.body.appendChild(host);
87
+ })
88
+ .catch(() => {});
89
+ }
90
+ }
package/core/admin.ts CHANGED
@@ -106,6 +106,9 @@ export const resolveAdminRoute = (path: string | undefined): AdminRoute => {
106
106
  /** Display text for a document's public URL in list tables — the bare root path reads as "Homepage" instead of "/". */
107
107
  export const formatPagePath = (path: string | null | undefined) => (path === "/" ? "Homepage" : (path ?? "—"));
108
108
 
109
+ /** Link target for the URL column: live documents open the real page; never-published drafts only exist behind ?preview. */
110
+ export const getPageHref = (pagePath: string, isLive: boolean) => (isLive ? pagePath : `${pagePath}?preview=true`);
111
+
109
112
  export const humanize = (value: string) =>
110
113
  value
111
114
  .replace(/^_+/, "")
package/core/define.ts CHANGED
@@ -382,6 +382,8 @@ export type AdminConfig = {
382
382
  */
383
383
  dateTimePattern?: string;
384
384
  nav?: AdminNavItem[];
385
+ /** "Edit this page" chip on public pages for logged-in editors (default: true). */
386
+ editBar?: boolean;
385
387
  uploads?: AdminUploadConfig;
386
388
  rateLimit?: AdminRateLimitConfig;
387
389
  auth?: AdminAuthConfig;
package/core/index.ts CHANGED
@@ -180,6 +180,7 @@ export {
180
180
  humanize,
181
181
  formatFieldValue,
182
182
  formatPagePath,
183
+ getPageHref,
183
184
  getListColumns,
184
185
  getFieldGroups,
185
186
  getFieldSets,
package/core/runtime.ts CHANGED
@@ -2,6 +2,8 @@ export type CmsStorageAdapter = {
2
2
  putFile: (storagePath: string, data: ArrayBuffer | Uint8Array) => Promise<void>;
3
3
  getFile: (storagePath: string) => Promise<ArrayBuffer | null>;
4
4
  deleteFile: (storagePath: string) => Promise<void>;
5
+ /** Optional streaming read — the /uploads route buffers via getFile when absent. */
6
+ getFileStream?: (storagePath: string) => Promise<{ body: ReadableStream; size: number } | null>;
5
7
  };
6
8
 
7
9
  export type CmsEmailAdapter = {
@@ -107,7 +107,8 @@ export default function cmsIntegration(options?: CmsIntegrationOptions): AstroIn
107
107
  const generatedPath = options?.generatedPath ?? "src/cms/.generated";
108
108
  const adaptersPath = options?.adaptersPath ?? "src/cms/adapters";
109
109
  const generatorPath = options?.generatorPath ?? packagePath("internals", "generator.ts");
110
- const platform = options?.platform ?? "node";
110
+ // options.platform stays accepted for compat (CF configs pass it) but nothing
111
+ // branches on it anymore — the /uploads route now serves both platforms.
111
112
 
112
113
  return {
113
114
  name: "kide-cms",
@@ -255,13 +256,13 @@ export default function cmsIntegration(options?: CmsIntegrationOptions): AstroIn
255
256
  entrypoint: new URL("../routes/admin/[...path].astro", import.meta.url),
256
257
  });
257
258
 
258
- // Cloudflare serves /uploads/* from R2 through a route (Node uses static files).
259
- if (platform === "cloudflare") {
260
- injectRoute({
261
- pattern: "/uploads/[...path]",
262
- entrypoint: new URL("../platform/cloudflare/uploads-route.ts", import.meta.url),
263
- });
264
- }
259
+ // /uploads/* streams from the storage adapter (Node: uploads dir, CF: R2).
260
+ // Both platforms need it: Node's static layer only serves files that
261
+ // existed at build time, so runtime uploads 404 in production without it.
262
+ injectRoute({
263
+ pattern: "/uploads/[...path]",
264
+ entrypoint: new URL("../routes/uploads/[...path].ts", import.meta.url),
265
+ });
265
266
 
266
267
  // Inject API routes
267
268
  injectRoute({
@@ -312,6 +313,10 @@ export default function cmsIntegration(options?: CmsIntegrationOptions): AstroIn
312
313
  pattern: "/api/cms/collaboration",
313
314
  entrypoint: new URL("../routes/api/collaboration/index.ts", import.meta.url),
314
315
  });
316
+ injectRoute({
317
+ pattern: "/api/cms/edit-bar",
318
+ entrypoint: new URL("../routes/api/edit-bar.ts", import.meta.url),
319
+ });
315
320
  injectRoute({
316
321
  pattern: "/api/cms/ai/alt-text",
317
322
  entrypoint: new URL("../routes/api/ai/alt-text.ts", import.meta.url),
@@ -148,11 +148,18 @@ const handle = async (context: APIContext, next: MiddlewareNext) => {
148
148
  hasUsers = true;
149
149
  }
150
150
  } catch (error) {
151
- // Only a missing users table means first run (schema not pushed yet) — anything else
152
- // (corruption, I/O) must surface, not funnel visitors to /admin/setup.
151
+ // Anything but a missing users table (corruption, I/O) must surface.
153
152
  const message = error instanceof Error ? error.message : String(error);
154
153
  if (!/no such table: cms_users/i.test(message)) throw error;
155
- hasUsers = false;
154
+ // Schema not pushed. Setup can't succeed against a table-less database
155
+ // (its INSERT would fail too), so say what's actually wrong instead of
156
+ // redirecting there. Typical cause: `pnpm build && pnpm preview` without
157
+ // a prior `pnpm cms:push` (dev pushes on boot, production never does).
158
+ // hasUsers stays unset so the check re-runs once the schema exists.
159
+ return new Response(
160
+ "Database schema is not initialized. Run `pnpm cms:push` against this environment's database (Cloudflare D1: apply your migrations), then reload.",
161
+ { status: 503, headers: { "Content-Type": "text/plain", "Cache-Control": "no-store" } },
162
+ );
156
163
  }
157
164
  }
158
165
 
@@ -200,6 +207,22 @@ const handle = async (context: APIContext, next: MiddlewareNext) => {
200
207
  ? normalizeCustomUser(await customProvider.getSession(context.request))
201
208
  : await getSessionUser(context.request);
202
209
 
210
+ // Non-httpOnly hint for the public-site edit bar: lets the injected client skip
211
+ // the session check entirely for anonymous visitors. Carries no auth value — the
212
+ // edit-bar endpoint verifies the real session. Only ever set/cleared on /admin
213
+ // responses, which are never cached, so it can't poison the shared cache.
214
+ const hasEditorHint = (context.request.headers.get("cookie") ?? "").split(/;\s*/).includes("kide-editor=1");
215
+ const editBarEnabled = config.admin?.editBar !== false;
216
+ const secure = process.env.NODE_ENV === "production" ? "; Secure" : "";
217
+ const withEditorHint = (response: Response, loggedIn: boolean) => {
218
+ if (loggedIn && editBarEnabled && !hasEditorHint) {
219
+ response.headers.append("Set-Cookie", `kide-editor=1; Path=/; SameSite=Strict${secure}; Max-Age=2592000`);
220
+ } else if (hasEditorHint && (!loggedIn || !editBarEnabled)) {
221
+ response.headers.append("Set-Cookie", `kide-editor=; Path=/; SameSite=Strict${secure}; Max-Age=0`);
222
+ }
223
+ return response;
224
+ };
225
+
203
226
  if (!user) {
204
227
  // API routes → 401
205
228
  if (isAdminApiRoute) {
@@ -209,11 +232,11 @@ const handle = async (context: APIContext, next: MiddlewareNext) => {
209
232
  });
210
233
  }
211
234
  // Admin pages → redirect to login
212
- return context.redirect("/admin/login");
235
+ return withEditorHint(context.redirect("/admin/login"), false);
213
236
  }
214
237
 
215
238
  // Attach user to locals for downstream use
216
239
  context.locals.user = user;
217
240
 
218
- return serve();
241
+ return withEditorHint(await serve(), true);
219
242
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kidecms/core",
3
- "version": "0.15.0",
3
+ "version": "0.16.1",
4
4
  "description": "Kide CMS runtime — core library, admin UI, routes, and middleware for Astro. Shipped as TypeScript source.",
5
5
  "keywords": [
6
6
  "cms",
@@ -3,7 +3,7 @@ import type { APIRoute } from "astro";
3
3
  import config from "virtual:kide/config";
4
4
  import { cms } from "virtual:kide/api";
5
5
  import { collaboration } from "virtual:kide/runtime";
6
- import { formatPagePath, isApprover, resolveCollaboration } from "../../../core";
6
+ import { formatPagePath, getPageHref, isApprover, resolveCollaboration } from "../../../core";
7
7
  import { loadSharedSectionUsageCounts } from "../../../admin/lib/edit-data";
8
8
 
9
9
  export const prerender = false;
@@ -295,7 +295,9 @@ export const GET: APIRoute = async ({ params, url, locals }) => {
295
295
  ? collection.preview
296
296
  : cmsRuntime.meta.getRouteForDocument(collectionSlug, entry)
297
297
  : null;
298
- if (pagePath) entry._pageHref = `${pagePath}?preview=true`;
298
+ if (pagePath) {
299
+ entry._pageHref = getPageHref(pagePath, !collection.drafts || entry._status === "published");
300
+ }
299
301
  entry.__page = formatPagePath(pagePath);
300
302
  }
301
303
  }
@@ -0,0 +1,46 @@
1
+ import type { APIRoute } from "astro";
2
+ import config from "virtual:kide/config";
3
+ import { cms } from "virtual:kide/api";
4
+ import { canRead, getVisualStatus } from "../../admin/lib/access";
5
+
6
+ export const prerender = false;
7
+
8
+ const cmsRuntime = cms as Record<string, any>;
9
+
10
+ // Resolves a public page's `data-cms-doc="<collection>:<id>"` marker into an admin
11
+ // edit URL for the edit-bar chip. Auth is enforced by the middleware (401 without a
12
+ // session); this only decides whether THIS user may see a link to THIS document.
13
+ export const GET: APIRoute = async ({ url, locals }) => {
14
+ if (config.admin?.editBar === false) {
15
+ return Response.json({ error: "Not found" }, { status: 404 });
16
+ }
17
+
18
+ const ref = url.searchParams.get("doc") ?? "";
19
+ const separator = ref.indexOf(":");
20
+ const collectionSlug = separator === -1 ? ref : ref.slice(0, separator);
21
+ const documentId = separator === -1 ? "" : ref.slice(separator + 1);
22
+
23
+ const collection = config.collections.find((c) => c.slug === collectionSlug);
24
+ const user = locals.user;
25
+ if (!collection || collection.auth || !documentId || !user || !canRead(config, user, collectionSlug)) {
26
+ return Response.json({ error: "Not found" }, { status: 404, headers: { "Cache-Control": "no-store" } });
27
+ }
28
+
29
+ let doc: Record<string, unknown> | null;
30
+ try {
31
+ doc = await cmsRuntime[collectionSlug].findById(documentId, { status: "any" }, { user });
32
+ } catch {
33
+ doc = null;
34
+ }
35
+ if (!doc) {
36
+ return Response.json({ error: "Not found" }, { status: 404, headers: { "Cache-Control": "no-store" } });
37
+ }
38
+
39
+ return Response.json(
40
+ {
41
+ editUrl: collection.singleton ? `/admin/${collectionSlug}` : `/admin/${collectionSlug}/${documentId}`,
42
+ status: collection.drafts ? getVisualStatus(doc) : null,
43
+ },
44
+ { headers: { "Cache-Control": "no-store" } },
45
+ );
46
+ };
@@ -0,0 +1,61 @@
1
+ import type { APIRoute } from "astro";
2
+ // Narrow import (not the core barrel): this route compiles in the Cloudflare
3
+ // profile too, and the barrel drags in Node-only modules.
4
+ import { getStorage } from "../../core/runtime";
5
+
6
+ export const prerender = false;
7
+
8
+ const MIME_TYPES: Record<string, string> = {
9
+ ".jpg": "image/jpeg",
10
+ ".jpeg": "image/jpeg",
11
+ ".png": "image/png",
12
+ ".gif": "image/gif",
13
+ ".webp": "image/webp",
14
+ ".avif": "image/avif",
15
+ ".svg": "image/svg+xml",
16
+ ".pdf": "application/pdf",
17
+ ".mp4": "video/mp4",
18
+ ".webm": "video/webm",
19
+ };
20
+
21
+ // Serves runtime-uploaded files through the storage adapter (Node: uploads dir,
22
+ // Cloudflare: R2). Node's static layer only knows files present at build time,
23
+ // so anything uploaded after `astro build` is invisible to it; this route is the
24
+ // fallback that makes production uploads servable. Static files win when both
25
+ // exist — same bytes either way.
26
+ export const GET: APIRoute = async ({ params }) => {
27
+ const storagePath = `/uploads/${params.path}`;
28
+ const storage = getStorage();
29
+
30
+ let body: ReadableStream | ArrayBuffer | null;
31
+ let size: number;
32
+ try {
33
+ if (storage.getFileStream) {
34
+ const file = await storage.getFileStream(storagePath);
35
+ body = file?.body ?? null;
36
+ size = file?.size ?? 0;
37
+ } else {
38
+ // Custom adapters implement only the three-method contract — buffer instead.
39
+ body = await storage.getFile(storagePath);
40
+ size = body instanceof ArrayBuffer ? body.byteLength : 0;
41
+ }
42
+ } catch {
43
+ body = null; // traversal attempt or adapter error — same 404 as a missing file
44
+ size = 0;
45
+ }
46
+
47
+ if (!body) {
48
+ return new Response("Not found", { status: 404 });
49
+ }
50
+
51
+ const ext = storagePath.substring(storagePath.lastIndexOf(".")).toLowerCase();
52
+ const contentType = MIME_TYPES[ext] || "application/octet-stream";
53
+
54
+ return new Response(body, {
55
+ headers: {
56
+ "Content-Type": contentType,
57
+ "Content-Length": String(size),
58
+ "Cache-Control": "public, max-age=31536000, immutable",
59
+ },
60
+ });
61
+ };
@@ -1,37 +0,0 @@
1
- import type { APIRoute } from "astro";
2
- import { getFileStream } from "./storage";
3
-
4
- export const prerender = false;
5
-
6
- const MIME_TYPES: Record<string, string> = {
7
- ".jpg": "image/jpeg",
8
- ".jpeg": "image/jpeg",
9
- ".png": "image/png",
10
- ".gif": "image/gif",
11
- ".webp": "image/webp",
12
- ".avif": "image/avif",
13
- ".svg": "image/svg+xml",
14
- ".pdf": "application/pdf",
15
- ".mp4": "video/mp4",
16
- ".webm": "video/webm",
17
- };
18
-
19
- export const GET: APIRoute = async ({ params }) => {
20
- const filePath = `/uploads/${params.path}`;
21
- const file = await getFileStream(filePath);
22
-
23
- if (!file) {
24
- return new Response("Not found", { status: 404 });
25
- }
26
-
27
- const ext = filePath.substring(filePath.lastIndexOf(".")).toLowerCase();
28
- const contentType = MIME_TYPES[ext] || "application/octet-stream";
29
-
30
- return new Response(file.body, {
31
- headers: {
32
- "Content-Type": contentType,
33
- "Content-Length": String(file.size),
34
- "Cache-Control": "public, max-age=31536000, immutable",
35
- },
36
- });
37
- };