@basicbenframework/cms 0.7.2 → 0.8.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 (40) hide show
  1. package/db/migrations/043_add_private_content.js +32 -0
  2. package/db/migrations/044_add_post_autosave_key.js +20 -0
  3. package/lib/client/components/admin/MediaPicker.js +3 -1
  4. package/lib/client/components/admin/SnippetPicker.js +3 -1
  5. package/lib/client/components/admin/SocialImageField.d.ts +24 -0
  6. package/lib/client/components/admin/SocialImageField.js +70 -0
  7. package/lib/client/i18n/locales/es/content.js +2 -0
  8. package/lib/client/i18n/locales/es/editor.js +18 -1
  9. package/lib/client/pages/admin/Pages.js +2 -2
  10. package/lib/client/pages/admin/PostEditor.js +103 -9
  11. package/lib/client/pages/admin/Posts.js +2 -2
  12. package/lib/controllers/FeedController.js +2 -2
  13. package/lib/controllers/MediaController.js +18 -1
  14. package/lib/controllers/PageController.js +5 -1
  15. package/lib/controllers/PostController.d.ts +14 -0
  16. package/lib/controllers/PostController.js +83 -1
  17. package/lib/features/theme/ThemeController.js +7 -1
  18. package/lib/features/theme/templates.d.ts +6 -1
  19. package/lib/features/theme/templates.js +13 -2
  20. package/lib/helpers/autosave.d.ts +13 -0
  21. package/lib/helpers/autosave.js +19 -0
  22. package/lib/helpers/comment-mail.js +8 -3
  23. package/lib/helpers/redirects.d.ts +7 -1
  24. package/lib/helpers/redirects.js +7 -1
  25. package/lib/helpers/seo-fields.d.ts +7 -0
  26. package/lib/helpers/seo-fields.js +9 -0
  27. package/lib/models/Media.d.ts +4 -1
  28. package/lib/models/Media.js +18 -1
  29. package/lib/models/Menu.js +4 -4
  30. package/lib/models/Page.d.ts +2 -0
  31. package/lib/models/Page.js +6 -3
  32. package/lib/models/Post.d.ts +16 -0
  33. package/lib/models/Post.js +21 -1
  34. package/lib/models/PublicContent.d.ts +1 -1
  35. package/lib/models/PublicContent.js +5 -5
  36. package/lib/models/visibility.d.ts +9 -0
  37. package/lib/models/visibility.js +15 -1
  38. package/lib/routes/api/posts.js +3 -0
  39. package/lib/types/index.d.ts +4 -0
  40. package/package.json +1 -1
@@ -4,7 +4,8 @@ import { can } from '@basicbenframework/core/auth/permissions';
4
4
  import { Post } from "../models/Post.js";
5
5
  import { paginationFrom, meta } from "../models/pagination.js";
6
6
  import { PostRevision } from "../models/PostRevision.js";
7
- import { seoFields } from "../helpers/seo-fields.js";
7
+ import { seoFields, privateFlag } from "../helpers/seo-fields.js";
8
+ import { worthAutosaving, validAutosaveKey } from "../helpers/autosave.js";
8
9
  import { LISTING_FILTERS } from "../models/Post.js";
9
10
  import { POST_STATUSES, toStoredTimestamp } from "../models/visibility.js";
10
11
  import { lockConflict } from "./PostLockController.js";
@@ -322,6 +323,83 @@ export const PostController = {
322
323
  });
323
324
  res.json({ autosave: { id: saved?.id, created_at: saved?.created_at } });
324
325
  },
326
+ /**
327
+ * The first autosave of a post that has never been saved.
328
+ *
329
+ * Autosave needs a post to hang its copy on, so a new post had none: a tab
330
+ * closed before the first Save lost everything typed into it. The editor
331
+ * calls this once, on the first title or body worth keeping, and gets a
332
+ * draft back; from then on it autosaves against that id like any other post.
333
+ *
334
+ * Always a draft, whatever is sent — this never publishes, schedules or makes
335
+ * anything public — and only the text is taken. The rules a real save
336
+ * enforces on a title and body (three and ten characters) wait for that
337
+ * save: a draft is allowed to be the first few words of itself.
338
+ */
339
+ async autosaveNew(req, res) {
340
+ const { title, content, excerpt, post_type, autosave_key } = (req.body ?? {});
341
+ if (typeof title !== 'string' || typeof content !== 'string') {
342
+ return res.json({ error: 'title and content are required' }, 422);
343
+ }
344
+ // A stray keystroke is not a draft: see helpers/autosave.ts.
345
+ if (!worthAutosaving(title, content)) {
346
+ return res.json({ error: 'Nothing to save yet' }, 422);
347
+ }
348
+ // The editor's key for this screen. A repeat — its earlier response lost
349
+ // after the row was written — gets the draft that request made, not a
350
+ // second one.
351
+ const key = validAutosaveKey(autosave_key) ? autosave_key : null;
352
+ if (autosave_key !== undefined && !key)
353
+ return res.json({ errors: { autosave_key: ['Invalid key'] } }, 422);
354
+ if (key) {
355
+ const earlier = await Post.findByAutosaveKey(req.userId, key);
356
+ if (earlier)
357
+ return res.json({ post: earlier });
358
+ }
359
+ const typed = await typeAndFields(post_type === undefined ? {} : { post_type }, null);
360
+ if ('errors' in typed)
361
+ return res.json({ errors: typed.errors }, 422);
362
+ const creating = await guardWrite(HOOKS.POST_CREATING, {
363
+ user_id: req.userId,
364
+ title: title.slice(0, 200),
365
+ content,
366
+ ...(typeof excerpt === 'string' ? { excerpt } : {}),
367
+ ...typed.values,
368
+ status: 'draft',
369
+ published: 0
370
+ }, { req }, { refused: 'Post rejected.' });
371
+ if (!creating.ok)
372
+ return res.json({ error: creating.error }, creating.status);
373
+ // A listener may adjust the text, not the state: what comes out of here is
374
+ // a draft of the signed-in user's, whatever the filter returned.
375
+ const value = creating.value;
376
+ let post;
377
+ try {
378
+ post = await Post.create({
379
+ title: String(value.title ?? ''),
380
+ content: String(value.content ?? ''),
381
+ ...(typeof value.excerpt === 'string' ? { excerpt: value.excerpt } : {}),
382
+ ...(typeof value.post_type === 'string' ? { post_type: value.post_type } : {}),
383
+ ...(key ? { autosave_key: key } : {}),
384
+ user_id: req.userId,
385
+ status: 'draft',
386
+ published: false
387
+ });
388
+ }
389
+ catch (error) {
390
+ // Two requests with one key raced, and the unique index let one in.
391
+ const earlier = key ? await Post.findByAutosaveKey(req.userId, key) : undefined;
392
+ if (earlier)
393
+ return res.json({ post: earlier });
394
+ throw error;
395
+ }
396
+ // Its address is chosen on the first real save, from the title it has by
397
+ // then, not from the first few letters typed.
398
+ await Post.forgetSlug(post.id);
399
+ post.slug = null;
400
+ await hooks.fire(HOOKS.POST_CREATED, { post, userId: req.userId });
401
+ res.json({ post }, 201);
402
+ },
325
403
  async feed(req, res) {
326
404
  // The built-in blog's feed. Restricted bodies are withheld unless the
327
405
  // access policy lets this reader have them — see helpers/gating.ts.
@@ -395,6 +473,10 @@ function editableFields(body, existing) {
395
473
  Object.assign(errors, seo.errors);
396
474
  else
397
475
  Object.assign(fields, seo.values);
476
+ // Private: published for the people who can edit it, hidden from every
477
+ // public surface. See migration 043 and `livePost`.
478
+ if ('is_private' in payload)
479
+ fields.is_private = privateFlag(payload.is_private);
398
480
  // Who may read the body: `public` or a level the access policy offers. The
399
481
  // level the post already has is always accepted, so a post saved under a
400
482
  // feature that has since been removed can still be edited without being
@@ -8,7 +8,7 @@ import { Taxonomy } from "../../models/Taxonomy.js";
8
8
  import { Menu } from "../../models/Menu.js";
9
9
  import { Redirect } from "../../models/Redirect.js";
10
10
  import { normalizeRedirectSource, RESERVED_ROUTE_SEGMENTS, POST_ROUTE_BASE } from "../../helpers/content-paths.js";
11
- import { renderListing, renderEntry, renderPage, renderNotFound, pathOf } from "./templates.js";
11
+ import { renderListing, renderEntry, renderPage, renderNotFound, pathOf, listingPath } from "./templates.js";
12
12
  /**
13
13
  * The reference public site, rendered on the server.
14
14
  *
@@ -184,6 +184,10 @@ function themed(handler) {
184
184
  }
185
185
  export const ThemeController = {
186
186
  home: themed(async (req, res, ctx) => {
187
+ // One address per page: `/?page=2` is `/page/2`, the one the pager links.
188
+ const page = pageNumber(req);
189
+ if (page > 1)
190
+ return res.redirect(listingPath('/', page), 301);
187
191
  await listing(req, res, { title: ctx.site.name, intro: ctx.site.description, basePath: '/', heading: false }, ctx);
188
192
  }),
189
193
  /** `/blog/:slug` — a blog post. */
@@ -217,6 +221,8 @@ export const ThemeController = {
217
221
  }),
218
222
  /** `/page/:page` — the home page, paginated the WordPress way. */
219
223
  homePage: themed(async (req, res, ctx) => {
224
+ if (pageNumber(req) <= 1)
225
+ return res.redirect('/', 301);
220
226
  await listing(req, res, { title: ctx.site.name, intro: ctx.site.description, basePath: '/', heading: false }, ctx);
221
227
  }),
222
228
  category: themed(async (req, res, ctx) => {
@@ -76,6 +76,11 @@ export declare function responsiveImg(image: ResponsiveImage | null, options?: {
76
76
  }): SafeHtml | '';
77
77
  /** One entry in a listing. */
78
78
  export declare function card(ctx: ThemeContext, post: PublicPost): SafeHtml;
79
+ /**
80
+ * Page `n` of a listing. The home page pages the WordPress way, `/page/2`,
81
+ * the route it has; an archive adds `?page=2` to its own path.
82
+ */
83
+ export declare function listingPath(base: string, n: number): string;
79
84
  /** Everything in <head> a browser, a crawler or a link preview reads. */
80
85
  export declare function renderHead(ctx: ThemeContext, meta: HeadMeta): SafeHtml;
81
86
  /** The whole page around a body. */
@@ -87,7 +92,7 @@ export interface ListingView {
87
92
  posts: PublicPost[];
88
93
  page: number;
89
94
  totalPages: number;
90
- /** The listing's own path, without `?page=`. */
95
+ /** The listing's own path, without its page number. */
91
96
  basePath: string;
92
97
  /** The home page and a type archive are the site; archives are collections. */
93
98
  heading?: boolean;
@@ -67,10 +67,21 @@ export function card(ctx, post) {
67
67
  </div>
68
68
  </article>`;
69
69
  }
70
+ /**
71
+ * Page `n` of a listing. The home page pages the WordPress way, `/page/2`,
72
+ * the route it has; an archive adds `?page=2` to its own path.
73
+ */
74
+ export function listingPath(base, n) {
75
+ if (n <= 1)
76
+ return base;
77
+ if (base === '/')
78
+ return `/page/${n}`;
79
+ return `${base}${base.includes('?') ? '&' : '?'}page=${n}`;
80
+ }
70
81
  function pager(page, totalPages, base) {
71
82
  if (totalPages <= 1)
72
83
  return '';
73
- const link = (n) => (n <= 1 ? base : `${base}${base.includes('?') ? '&' : '?'}page=${n}`);
84
+ const link = (n) => listingPath(base, n);
74
85
  return html `<nav class="pager" aria-label="Pagination">
75
86
  ${page > 1 ? html `<a rel="prev" href="${link(page - 1)}">← Newer</a>` : html `<span></span>`}
76
87
  <span>Page ${page} of ${totalPages}</span>
@@ -199,7 +210,7 @@ ${raw(site.code_injection.foot)}
199
210
  }
200
211
  /** The home page, a type archive, or a category/tag/author/term archive. */
201
212
  export function renderListing(ctx, view) {
202
- const pageUrl = (n) => absolute(ctx, n <= 1 ? view.basePath : `${view.basePath}?page=${n}`);
213
+ const pageUrl = (n) => absolute(ctx, listingPath(view.basePath, n));
203
214
  const isHome = view.basePath === '/';
204
215
  const body = html `
205
216
  ${view.heading === false ? '' : html `<header>
@@ -0,0 +1,13 @@
1
+ /**
2
+ * When a new post has enough in it to be saved as a draft.
3
+ *
4
+ * Shared by the editor, which waits for it before its first autosave, and the
5
+ * server, which refuses anything less — so a stray keystroke on New post and a
6
+ * closed tab leave nothing behind. The same lengths a real save asks of a
7
+ * title and a body; either one is enough.
8
+ */
9
+ export declare const AUTOSAVE_MIN_TITLE = 3;
10
+ export declare const AUTOSAVE_MIN_CONTENT = 10;
11
+ export declare function worthAutosaving(title: unknown, content: unknown): boolean;
12
+ /** The shape of the editor's idempotency key: short, URL-safe, its own. */
13
+ export declare function validAutosaveKey(value: unknown): value is string;
@@ -0,0 +1,19 @@
1
+ /**
2
+ * When a new post has enough in it to be saved as a draft.
3
+ *
4
+ * Shared by the editor, which waits for it before its first autosave, and the
5
+ * server, which refuses anything less — so a stray keystroke on New post and a
6
+ * closed tab leave nothing behind. The same lengths a real save asks of a
7
+ * title and a body; either one is enough.
8
+ */
9
+ export const AUTOSAVE_MIN_TITLE = 3;
10
+ export const AUTOSAVE_MIN_CONTENT = 10;
11
+ export function worthAutosaving(title, content) {
12
+ const t = typeof title === 'string' ? title.trim().length : 0;
13
+ const c = typeof content === 'string' ? content.trim().length : 0;
14
+ return t >= AUTOSAVE_MIN_TITLE || c >= AUTOSAVE_MIN_CONTENT;
15
+ }
16
+ /** The shape of the editor's idempotency key: short, URL-safe, its own. */
17
+ export function validAutosaveKey(value) {
18
+ return typeof value === 'string' && /^[A-Za-z0-9_-]{8,64}$/.test(value);
19
+ }
@@ -25,6 +25,7 @@ import { renderMail } from "./mail-templates.js";
25
25
  import { capabilitiesFor, ROLES } from '@basicbenframework/core/auth/permissions';
26
26
  import { getDb } from '@basicbenframework/core/db';
27
27
  import { Comment } from "../models/Comment.js";
28
+ import { livePost } from "../models/visibility.js";
28
29
  import { Settings } from "../models/Settings.js";
29
30
  import { issueUnsubscribeToken } from "./comment-guard.js";
30
31
  const appUrl = () => process.env.APP_URL || 'http://localhost:3000';
@@ -156,12 +157,16 @@ export async function notifyParentOfReply(replyId) {
156
157
  const sameAccount = reply.user_id && parent.user_id && Number(reply.user_id) === Number(parent.user_id);
157
158
  if (sameAccount || (replyEmail && replyEmail === to.toLowerCase()))
158
159
  return;
159
- if (!(await Comment.claimReplyNotification(Number(reply.id))))
160
- return;
160
+ // Only for a post readers can see. One made private (or unpublished, or
161
+ // trashed) since the comment was left must not be named, or linked, in a
162
+ // mail to someone who cannot open it. Checked before the claim, so nothing
163
+ // is marked sent that was not.
161
164
  const db = await getDb();
162
- const post = await db.get('SELECT id, title FROM posts WHERE id = ?', [reply.post_id]);
165
+ const post = await db.get(`SELECT id, title FROM posts WHERE id = ? AND ${livePost('posts')}`, [reply.post_id]);
163
166
  if (!post)
164
167
  return;
168
+ if (!(await Comment.claimReplyNotification(Number(reply.id))))
169
+ return;
165
170
  const unsubscribeUrl = `${appUrl()}/api/comments/unsubscribe?token=${encodeURIComponent(issueUnsubscribeToken(Number(parent.id)))}`;
166
171
  const replyUrl = `${appUrl()}/feed/${post.id}#comment-${reply.id}`;
167
172
  const name = parent.user_name || parent.author_name || 'there';
@@ -24,6 +24,8 @@ interface Movable {
24
24
  slug?: string | null;
25
25
  published?: boolean | number | null;
26
26
  deleted_at?: string | null;
27
+ /** Private (migration 043): published, but not public. */
28
+ is_private?: boolean | number | null;
27
29
  /** The post's content type key; absent or `post` means `/blog`. */
28
30
  post_type?: string | null;
29
31
  }
@@ -33,7 +35,11 @@ interface Movable {
33
35
  *
34
36
  * Only content that was public before the save: a draft's slug was never a
35
37
  * URL anyone could have linked to, so redirecting from it would only litter
36
- * the table. A post without a slug answered to its id, and still does — the
38
+ * the table. Nor a private one, on either side of the save: its slugs were
39
+ * never public, and `/api/v1/redirects` lists every redirect to anyone, so
40
+ * recording one would publish the old address and the new.
41
+ *
42
+ * A post without a slug answered to its id, and still does — the
37
43
  * content API accepts an id wherever it accepts a slug — so it needs nothing.
38
44
  */
39
45
  export declare function redirectIfSlugChanged(kind: 'post' | 'page', before: Movable, after: Movable | null | undefined, routeBases?: {
@@ -53,7 +53,11 @@ async function baseFor(type) {
53
53
  *
54
54
  * Only content that was public before the save: a draft's slug was never a
55
55
  * URL anyone could have linked to, so redirecting from it would only litter
56
- * the table. A post without a slug answered to its id, and still does — the
56
+ * the table. Nor a private one, on either side of the save: its slugs were
57
+ * never public, and `/api/v1/redirects` lists every redirect to anyone, so
58
+ * recording one would publish the old address and the new.
59
+ *
60
+ * A post without a slug answered to its id, and still does — the
57
61
  * content API accepts an id wherever it accepts a slug — so it needs nothing.
58
62
  */
59
63
  export async function redirectIfSlugChanged(kind, before, after,
@@ -65,6 +69,8 @@ routeBases = {}) {
65
69
  return;
66
70
  if (!before.published || before.deleted_at)
67
71
  return;
72
+ if (Number(before.is_private) || Number(after.is_private))
73
+ return;
68
74
  // Looked up from the rows themselves when the caller did not say, so the
69
75
  // controller's one-line call covers custom types without knowing about them.
70
76
  // A plain post never touches the database here.
@@ -11,3 +11,10 @@ export declare function seoFields(body: unknown): {
11
11
  errors: Record<string, string[]>;
12
12
  };
13
13
  export declare const SEO_COLUMNS: string[];
14
+ /**
15
+ * The private flag (migration 043) as stored: 1 or 0.
16
+ *
17
+ * A checkbox arrives as true, "true", "on" or "1" depending on the client, and
18
+ * anything else — including absent-but-present-as-null — is public.
19
+ */
20
+ export declare function privateFlag(value: unknown): 0 | 1;
@@ -50,3 +50,12 @@ export const SEO_COLUMNS = [
50
50
  'og_title', 'og_description', 'og_image', 'twitter_title', 'twitter_description',
51
51
  'twitter_image', 'canonical_url', 'noindex'
52
52
  ];
53
+ /**
54
+ * The private flag (migration 043) as stored: 1 or 0.
55
+ *
56
+ * A checkbox arrives as true, "true", "on" or "1" depending on the client, and
57
+ * anything else — including absent-but-present-as-null — is public.
58
+ */
59
+ export function privateFlag(value) {
60
+ return [true, 1, '1', 'true', 'on'].includes(value) ? 1 : 0;
61
+ }
@@ -25,11 +25,14 @@ export declare const Media: {
25
25
  * @param perPage
26
26
  * @param filters - `search` matches the original filename; `type` is a mime
27
27
  * prefix such as 'image', or 'other' for anything that is not image, video
28
- * or audio.
28
+ * or audio. `servedAt` is the path of a URL the file is served from: it
29
+ * matches the item whose storage key that path ends with, which is how a
30
+ * pasted URL is turned back into the library item it points at.
29
31
  */
30
32
  all(page?: number, perPage?: number, filters?: {
31
33
  search?: string;
32
34
  type?: string;
35
+ servedAt?: string;
33
36
  }): Promise<{
34
37
  items: MediaType[];
35
38
  total: number;
@@ -11,7 +11,9 @@ export const Media = {
11
11
  * @param perPage
12
12
  * @param filters - `search` matches the original filename; `type` is a mime
13
13
  * prefix such as 'image', or 'other' for anything that is not image, video
14
- * or audio.
14
+ * or audio. `servedAt` is the path of a URL the file is served from: it
15
+ * matches the item whose storage key that path ends with, which is how a
16
+ * pasted URL is turned back into the library item it points at.
15
17
  */
16
18
  async all(page = 1, perPage = 20, filters = {}) {
17
19
  const db = await getDb();
@@ -22,6 +24,21 @@ export const Media = {
22
24
  where.push('m.original_name LIKE ?');
23
25
  params.push(`%${filters.search}%`);
24
26
  }
27
+ if (filters.servedAt) {
28
+ // Every storage driver serves a key at a URL ending in that key, after
29
+ // whatever prefix its bucket, CDN or local route adds. So the key is one
30
+ // of the path's whole-segment suffixes: compared exactly, because a
31
+ // stored key used as a LIKE pattern would make `_` and `%` wildcards.
32
+ const segments = filters.servedAt.split('/').filter(Boolean).slice(-20);
33
+ const suffixes = segments.map((_, i) => segments.slice(i).join('/'));
34
+ if (suffixes.length) {
35
+ where.push(`m.path IN (${suffixes.map(() => '?').join(', ')})`);
36
+ params.push(...suffixes);
37
+ }
38
+ else {
39
+ where.push('1 = 0');
40
+ }
41
+ }
25
42
  if (filters.type === 'other') {
26
43
  where.push("COALESCE(m.mime_type, '') NOT LIKE 'image/%'");
27
44
  where.push("COALESCE(m.mime_type, '') NOT LIKE 'video/%'");
@@ -7,7 +7,7 @@
7
7
  * draft, a trashed post, or a page that was deleted out from under it.
8
8
  */
9
9
  import { getDb, query } from '@basicbenframework/core/db';
10
- import { livePost } from "./visibility.js";
10
+ import { livePost, livePage } from "./visibility.js";
11
11
  import { postPath, pagePath, categoryPath, isSafeLinkUrl } from "../helpers/content-paths.js";
12
12
  export const TARGET_TYPES = ['post', 'page', 'category'];
13
13
  /**
@@ -296,11 +296,11 @@ export const Menu = {
296
296
  return map;
297
297
  };
298
298
  // The same visibility rules as the rest of the public API: `livePost` for
299
- // posts (published, not trashed, its time has come), `published = 1` for
300
- // pages. Categories have no visibility of their own.
299
+ // posts (published, not trashed, its time has come, not private), `livePage`
300
+ // for pages. Categories have no visibility of their own.
301
301
  const targets = {
302
302
  post: await lookup('post', list => `SELECT posts.id, posts.slug FROM posts WHERE posts.id IN (${list}) AND ${livePost('posts')}`),
303
- page: await lookup('page', list => `SELECT id, slug FROM pages WHERE id IN (${list}) AND published = 1`),
303
+ page: await lookup('page', list => `SELECT pages.id, pages.slug FROM pages WHERE pages.id IN (${list}) AND ${livePage('pages')}`),
304
304
  category: await lookup('category', list => `SELECT id, slug FROM categories WHERE id IN (${list})`)
305
305
  };
306
306
  const result = {};
@@ -6,6 +6,7 @@ interface CreatePageData {
6
6
  featured_image?: number | null;
7
7
  template?: string;
8
8
  published?: boolean;
9
+ is_private?: number;
9
10
  parent_id?: number;
10
11
  menu_order?: number;
11
12
  meta_title?: string;
@@ -18,6 +19,7 @@ interface UpdatePageData {
18
19
  featured_image?: number | null;
19
20
  template?: string;
20
21
  published?: boolean;
22
+ is_private?: number;
21
23
  parent_id?: number;
22
24
  menu_order?: number;
23
25
  meta_title?: string;
@@ -4,6 +4,7 @@ import { hooks, HOOKS } from '@basicbenframework/core/hooks';
4
4
  import { renderContent } from '@basicbenframework/core/content';
5
5
  import { getStorage } from '@basicbenframework/core/storage';
6
6
  import { uniqueSlug } from "./derive.js";
7
+ import { livePage } from "./visibility.js";
7
8
  /**
8
9
  * Columns `update()` will write.
9
10
  *
@@ -12,7 +13,7 @@ import { uniqueSlug } from "./derive.js";
12
13
  */
13
14
  const UPDATABLE = [
14
15
  'title', 'slug', 'content', 'content_html', 'featured_image', 'template',
15
- 'published', 'parent_id', 'menu_order', 'meta_title', 'meta_description',
16
+ 'published', 'is_private', 'parent_id', 'menu_order', 'meta_title', 'meta_description',
16
17
  'updated_at', ...SEO_COLUMNS
17
18
  ];
18
19
  export const Page = {
@@ -50,13 +51,13 @@ export const Page = {
50
51
  const db = await getDb();
51
52
  return withFeaturedImages(await db.all(`
52
53
  ${SELECT_PAGE}
53
- WHERE pages.published = 1
54
+ WHERE ${livePage('pages')}
54
55
  ORDER BY pages.menu_order ASC, pages.title ASC
55
56
  `));
56
57
  },
57
58
  async findPublishedBySlug(slug) {
58
59
  const db = await getDb();
59
- return first(await db.get(`${SELECT_PAGE} WHERE pages.slug = ? AND pages.published = 1`, [slug]));
60
+ return first(await db.get(`${SELECT_PAGE} WHERE pages.slug = ? AND ${livePage('pages')}`, [slug]));
60
61
  },
61
62
  async tree() {
62
63
  const pages = await this.all();
@@ -87,6 +88,7 @@ export const Page = {
87
88
  featured_image: data.featured_image ?? null,
88
89
  template: data.template || 'default',
89
90
  published: data.published ? 1 : 0,
91
+ is_private: data.is_private ? 1 : 0,
90
92
  parent_id: data.parent_id || null,
91
93
  menu_order: data.menu_order || 0,
92
94
  meta_title: data.meta_title || null,
@@ -105,6 +107,7 @@ export const Page = {
105
107
  featured_image: data.featured_image ?? null,
106
108
  template: data.template || 'default',
107
109
  published: data.published || false,
110
+ is_private: data.is_private ? 1 : 0,
108
111
  parent_id: data.parent_id,
109
112
  menu_order: data.menu_order || 0,
110
113
  meta_title: data.meta_title,
@@ -22,10 +22,13 @@ interface CreatePostData {
22
22
  noindex?: number;
23
23
  visibility?: string;
24
24
  send_newsletter?: number;
25
+ is_private?: number;
25
26
  /** Content type key (migration 038). Absent means `post`. */
26
27
  post_type?: string;
27
28
  /** Custom field values as stored: a JSON string, already validated. */
28
29
  fields?: string | null;
30
+ /** The editor's idempotency key for a first autosave (migration 044). */
31
+ autosave_key?: string;
29
32
  }
30
33
  interface UpdatePostData {
31
34
  user_id?: number;
@@ -51,6 +54,7 @@ interface UpdatePostData {
51
54
  noindex?: number;
52
55
  visibility?: string;
53
56
  send_newsletter?: number;
57
+ is_private?: number;
54
58
  post_type?: string;
55
59
  fields?: string | null;
56
60
  }
@@ -130,6 +134,18 @@ export declare const Post: {
130
134
  findPublishedById(id: number): Promise<PostType | undefined>;
131
135
  create(data: CreatePostData): Promise<PostType>;
132
136
  update(id: number, data: UpdatePostData): Promise<PostType>;
137
+ /**
138
+ * Forget a draft's slug, so the first real save derives one.
139
+ *
140
+ * For the draft an autosave makes from a new post's first words (see
141
+ * `PostController.autosaveNew`): a slug derived then would come from "He",
142
+ * or be `post` for a draft with only a body, and the editor would load it
143
+ * back as if the author had chosen it. Null is what a post with no slug yet
144
+ * already means, and the unique index allows any number of them.
145
+ */
146
+ /** The draft a first autosave with this key already made, if any (migration 044). */
147
+ findByAutosaveKey(userId: number, key: string): Promise<PostType | undefined>;
148
+ forgetSlug(id: number): Promise<void>;
133
149
  /** Gone for good. Only ever called on a post already in the trash. */
134
150
  delete(id: number): Promise<void>;
135
151
  };
@@ -19,7 +19,7 @@ const UPDATABLE = [
19
19
  'status', 'deleted_at', 'live_notified',
20
20
  'og_title', 'og_description', 'og_image', 'twitter_title', 'twitter_description',
21
21
  'twitter_image', 'canonical_url', 'noindex',
22
- 'visibility', 'send_newsletter',
22
+ 'visibility', 'send_newsletter', 'is_private',
23
23
  // Content types (migrations 038–039). Validated by helpers/content-model.ts
24
24
  // before they reach here.
25
25
  'post_type', 'fields'
@@ -262,8 +262,10 @@ export const Post = {
262
262
  live_notified: data.live_notified ?? 1,
263
263
  visibility: data.visibility ?? 'public',
264
264
  send_newsletter: data.send_newsletter ?? 0,
265
+ is_private: data.is_private ? 1 : 0,
265
266
  post_type: data.post_type ?? 'post',
266
267
  fields: data.fields ?? null,
268
+ ...(data.autosave_key ? { autosave_key: data.autosave_key } : {}),
267
269
  ...Object.fromEntries(SEO_FIELDS.filter((key) => data[key] !== undefined).map((key) => [key, data[key]]))
268
270
  });
269
271
  const now = new Date().toISOString();
@@ -309,6 +311,24 @@ export const Post = {
309
311
  await db.run(`UPDATE posts SET ${fields}, updated_at = CURRENT_TIMESTAMP WHERE id = ?`, [...writable.map(([, value]) => value), id]);
310
312
  return this.find(id);
311
313
  },
314
+ /**
315
+ * Forget a draft's slug, so the first real save derives one.
316
+ *
317
+ * For the draft an autosave makes from a new post's first words (see
318
+ * `PostController.autosaveNew`): a slug derived then would come from "He",
319
+ * or be `post` for a draft with only a body, and the editor would load it
320
+ * back as if the author had chosen it. Null is what a post with no slug yet
321
+ * already means, and the unique index allows any number of them.
322
+ */
323
+ /** The draft a first autosave with this key already made, if any (migration 044). */
324
+ async findByAutosaveKey(userId, key) {
325
+ const db = await getDb();
326
+ return db.get('SELECT * FROM posts WHERE user_id = ? AND autosave_key = ?', [userId, key]);
327
+ },
328
+ async forgetSlug(id) {
329
+ const db = await getDb();
330
+ await db.run('UPDATE posts SET slug = NULL WHERE id = ?', [id]);
331
+ },
312
332
  /** Gone for good. Only ever called on a post already in the trash. */
313
333
  async delete(id) {
314
334
  const db = await getDb();
@@ -173,7 +173,7 @@ export declare const PublicContent: {
173
173
  *
174
174
  * Only people who have published: an account with no posts is a user, not an
175
175
  * author, and listing one exposes that the account exists to anyone who asks
176
- * for the author index. Counts come from the same `published = 1` filter the
176
+ * for the author index. Counts come from the same `livePost` filter the
177
177
  * post listing uses, so an archive link never leads to an empty page.
178
178
  */
179
179
  authors(): Promise<PublicAuthor[]>;
@@ -13,7 +13,7 @@
13
13
  */
14
14
  import { getDb } from '@basicbenframework/core/db';
15
15
  import { getStorage, absoluteUrl } from '@basicbenframework/core/storage';
16
- import { livePost, parseStoredTimestamp } from "./visibility.js";
16
+ import { livePost, livePage, parseStoredTimestamp } from "./visibility.js";
17
17
  import { responsiveImage } from "../helpers/images.js";
18
18
  import { siteUrl } from "../helpers/site.js";
19
19
  import { publicExcerpt } from "../helpers/gating.js";
@@ -194,9 +194,9 @@ export const PublicContent = {
194
194
  async pages(options = {}) {
195
195
  const db = await getDb();
196
196
  const { perPage = 10, offset = 0, format = 'html' } = options;
197
- const counted = (await db.get('SELECT COUNT(*) AS total FROM pages WHERE published = 1'));
197
+ const counted = (await db.get(`SELECT COUNT(*) AS total FROM pages WHERE ${livePage('pages')}`));
198
198
  const rows = (await db.all(`SELECT ${PAGE_COLUMNS} ${PAGE_JOINS}
199
- WHERE pages.published = 1
199
+ WHERE ${livePage('pages')}
200
200
  ORDER BY pages.created_at DESC
201
201
  LIMIT ? OFFSET ?`, [perPage, offset]));
202
202
  return { pages: await shapePages(rows, format), total: Number(counted?.total) || 0 };
@@ -205,7 +205,7 @@ export const PublicContent = {
205
205
  async page(identifier, format = 'html') {
206
206
  const db = await getDb();
207
207
  const row = (await db.get(`SELECT ${PAGE_COLUMNS} ${PAGE_JOINS}
208
- WHERE pages.published = 1 AND (pages.slug = ? OR pages.id = ?)`, [identifier, Number(identifier) || -1]));
208
+ WHERE ${livePage('pages')} AND (pages.slug = ? OR pages.id = ?)`, [identifier, Number(identifier) || -1]));
209
209
  return row ? (await shapePages([row], format))[0] : null;
210
210
  },
211
211
  /**
@@ -247,7 +247,7 @@ export const PublicContent = {
247
247
  *
248
248
  * Only people who have published: an account with no posts is a user, not an
249
249
  * author, and listing one exposes that the account exists to anyone who asks
250
- * for the author index. Counts come from the same `published = 1` filter the
250
+ * for the author index. Counts come from the same `livePost` filter the
251
251
  * post listing uses, so an archive link never leads to an empty page.
252
252
  */
253
253
  async authors() {
@@ -14,8 +14,17 @@
14
14
  * Scheduling needs no cron: a scheduled post simply starts matching when its
15
15
  * time comes. What does need a tick is telling webhooks — see `publishDue()` in
16
16
  * `src/hooks.ts`.
17
+ *
18
+ * Not private (migration 043): a private post is published for the people who
19
+ * can edit it, in the admin, and for nobody on any public surface. Folding it
20
+ * into this fragment is what makes that true everywhere at once.
17
21
  */
18
22
  export declare function livePost(alias?: string): string;
23
+ /**
24
+ * When a page is on the public site: published and not private. The page
25
+ * counterpart of `livePost`, for the same reason — one copy of the rule.
26
+ */
27
+ export declare function livePage(alias?: string): string;
19
28
  /** Normalise a date to the stored form, or null. Throws on nonsense. */
20
29
  export declare function toStoredTimestamp(value: unknown): string | null;
21
30
  /** The editorial states a post can be in. Scheduled is published-in-the-future. */
@@ -14,10 +14,24 @@
14
14
  * Scheduling needs no cron: a scheduled post simply starts matching when its
15
15
  * time comes. What does need a tick is telling webhooks — see `publishDue()` in
16
16
  * `src/hooks.ts`.
17
+ *
18
+ * Not private (migration 043): a private post is published for the people who
19
+ * can edit it, in the admin, and for nobody on any public surface. Folding it
20
+ * into this fragment is what makes that true everywhere at once.
17
21
  */
18
22
  export function livePost(alias = 'posts') {
19
23
  const now = new Date().toISOString();
20
- return `(${alias}.published = 1 AND ${alias}.deleted_at IS NULL AND (${alias}.publish_at IS NULL OR ${alias}.publish_at <= '${now}'))`;
24
+ return `(${alias}.published = 1 AND ${alias}.deleted_at IS NULL AND (${alias}.publish_at IS NULL OR ${alias}.publish_at <= '${now}') AND ${notPrivate(alias)})`;
25
+ }
26
+ /**
27
+ * When a page is on the public site: published and not private. The page
28
+ * counterpart of `livePost`, for the same reason — one copy of the rule.
29
+ */
30
+ export function livePage(alias = 'pages') {
31
+ return `(${alias}.published = 1 AND ${notPrivate(alias)})`;
32
+ }
33
+ function notPrivate(alias) {
34
+ return `${alias}.is_private = 0`;
21
35
  }
22
36
  /** Normalise a date to the stored form, or null. Throws on nonsense. */
23
37
  export function toStoredTimestamp(value) {