forked from emdash-cms/emdash
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontent.ts
More file actions
1897 lines (1742 loc) · 53 KB
/
Copy pathcontent.ts
File metadata and controls
1897 lines (1742 loc) · 53 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Content CRUD handlers
*/
import type { Kysely } from "kysely";
import { sql } from "kysely";
import { isSqlite } from "../../database/dialect-helpers.js";
import { BylineRepository } from "../../database/repositories/byline.js";
import type { ContentBylineInput } from "../../database/repositories/byline.js";
import { CommentRepository } from "../../database/repositories/comment.js";
import { ContentRepository, isSystemOrderField } from "../../database/repositories/content.js";
import { RedirectRepository } from "../../database/repositories/redirect.js";
import { RevisionRepository } from "../../database/repositories/revision.js";
import { SeoRepository } from "../../database/repositories/seo.js";
import { TaxonomyRepository } from "../../database/repositories/taxonomy.js";
import {
EmDashValidationError,
ScheduledNotDueError,
InvalidCursorError,
type BylineSummary,
type ContentBylineCredit,
type ContentDateField,
type ContentItem,
type ContentSeo,
type ContentSeoInput,
type FindManyOptions,
} from "../../database/repositories/types.js";
import { UserRepository } from "../../database/repositories/user.js";
import { withTransaction } from "../../database/transaction.js";
import type { Database } from "../../database/types.js";
import { validateIdentifier } from "../../database/validate.js";
import { getI18nConfig, isI18nEnabled } from "../../i18n/config.js";
import { invalidateRedirectCache } from "../../redirects/cache.js";
import { FTSManager } from "../../search/fts-manager.js";
import { invalidateTermCache } from "../../taxonomies/index.js";
import { isMissingTableError } from "../../utils/db-errors.js";
import { encodeRev, validateRev } from "../rev.js";
import type { ApiResult, ContentListResponse, ContentResponse } from "../types.js";
import { validateMediaFields } from "./validate-media-fields.js";
/**
* Narrow a caught error to one carrying a structured `apiError` discriminant.
* Used by transaction callbacks that want to surface a specific error code
* through the standard Error throwing path.
*/
function hasApiError(error: unknown): error is Error & { apiError: { code: string } } {
if (!(error instanceof Error) || !("apiError" in error)) return false;
const { apiError } = error;
return (
typeof apiError === "object" &&
apiError !== null &&
"code" in apiError &&
typeof apiError.code === "string"
);
}
/**
* Extract a slug source (title or name) from content data.
* Returns null if no suitable string field is found.
*/
function getSlugSource(data: Record<string, unknown>): string | null {
if (typeof data.title === "string" && data.title.length > 0) return data.title;
if (typeof data.name === "string" && data.name.length > 0) return data.name;
return null;
}
/** Default SEO values for content without an explicit SEO row */
const SEO_DEFAULTS: ContentSeo = {
title: null,
description: null,
image: null,
canonical: null,
noIndex: false,
};
/**
* Check if a collection has SEO enabled.
*/
async function collectionHasSeo(db: Kysely<Database>, collection: string): Promise<boolean> {
const row = await db
.selectFrom("_emdash_collections")
.select("has_seo")
.where("slug", "=", collection)
.executeTakeFirst();
return row?.has_seo === 1;
}
/**
* Hydrate SEO data on a single content item if the collection has SEO enabled.
*/
async function hydrateSeo(
db: Kysely<Database>,
collection: string,
item: ContentItem,
hasSeo: boolean,
): Promise<void> {
if (!hasSeo) return;
const seoRepo = new SeoRepository(db);
item.seo = await seoRepo.get(collection, item.id);
}
/**
* Hydrate SEO data on multiple content items using a single batch query.
*/
async function hydrateSeoMany(
db: Kysely<Database>,
collection: string,
items: ContentItem[],
hasSeo: boolean,
): Promise<void> {
if (!hasSeo || items.length === 0) return;
const seoRepo = new SeoRepository(db);
const seoMap = await seoRepo.getMany(
collection,
items.map((i) => i.id),
);
for (const item of items) {
item.seo = seoMap.get(item.id) ?? { ...SEO_DEFAULTS };
}
}
async function hydrateBylines(
db: Kysely<Database>,
collection: string,
item: ContentItem,
): Promise<void> {
const bylineRepo = new BylineRepository(db);
// Strict per-locale (migration 040): a credit at locale X renders iff a
// byline row exists at locale X in the credited translation_group. The
// junction itself spans translations; rendering does not fall back.
const localeOpt = item.locale ? { locale: item.locale } : undefined;
const bylines = await bylineRepo.getContentBylines(collection, item.id, localeOpt);
if (bylines.length > 0) {
item.bylines = bylines.map((c) => ({ ...c, source: "explicit" as const }));
item.byline = bylines[0]?.byline ?? null;
return;
}
// `primaryBylineId` is set iff junction rows exist; non-null
// suppresses author fallback even when the credit doesn't resolve
// at this locale.
if (item.primaryBylineId) {
item.bylines = [];
item.byline = null;
return;
}
if (item.authorId) {
// Same strict-locale rule as explicit credits: a user-linked byline
// renders on the entry only when a sibling exists at the entry's
// locale. Without this we'd silently surface the default-locale
// row, which contradicts the per-locale model.
const fallback = await bylineRepo.findByUserId(item.authorId, localeOpt);
if (fallback) {
item.bylines = [{ byline: fallback, sortOrder: 0, roleLabel: null, source: "inferred" }];
item.byline = fallback;
return;
}
}
item.bylines = [];
item.byline = null;
}
/**
* Batch-hydrate bylines for multiple items using two bulk queries instead of N+1.
*
* Items may live at different locales (e.g. a list endpoint returning the
* translations of an entry). Group by `item.locale` and call the strict
* per-locale repo method once per group so each item resolves against its
* own locale's byline rows.
*/
async function hydrateBylinesMany(
db: Kysely<Database>,
collection: string,
items: ContentItem[],
): Promise<void> {
if (items.length === 0) return;
const bylineRepo = new BylineRepository(db);
// 1. Bucket items by locale so we can call the strict-locale repo
// once per bucket. Items with a null/undefined locale (pre-i18n
// rows on a single-locale install) share an "unscoped" bucket.
const localeBuckets = new Map<string | null, ContentItem[]>();
for (const item of items) {
const key = item.locale ?? null;
const bucket = localeBuckets.get(key);
if (bucket) bucket.push(item);
else localeBuckets.set(key, [item]);
}
// 2. Per-locale: fetch explicit credits. Items whose credits don't
// resolve at this locale go through a locale-agnostic "has any
// junction" check before being considered for author inference —
// explicit editorial intent at any locale beats inferred fallback.
const bylinesByItem = new Map<string, ContentBylineCredit[]>();
const itemsNeedingAuthorCheck: ContentItem[] = [];
for (const [locale, bucket] of localeBuckets) {
const localeOpt = locale ? { locale } : undefined;
const ids = bucket.map((i) => i.id);
const credits = await bylineRepo.getContentBylinesMany(collection, ids, localeOpt);
for (const [id, list] of credits) bylinesByItem.set(id, list);
for (const item of bucket) {
if (credits.has(item.id) && credits.get(item.id)!.length > 0) continue;
if (item.authorId) itemsNeedingAuthorCheck.push(item);
}
}
// 3. Author fallback applies only when no explicit credit exists
// (primaryBylineId null).
const fallbackByItem = new Map<string, BylineSummary>();
if (itemsNeedingAuthorCheck.length > 0) {
const authorBuckets = new Map<string | null, ContentItem[]>();
for (const item of itemsNeedingAuthorCheck) {
if (item.primaryBylineId) continue;
const key = item.locale ?? null;
const bucket = authorBuckets.get(key);
if (bucket) bucket.push(item);
else authorBuckets.set(key, [item]);
}
for (const [locale, bucket] of authorBuckets) {
const localeOpt = locale ? { locale } : undefined;
const authorIds = bucket.map((i) => i.authorId).filter((id): id is string => id !== null);
const uniqueAuthorIds = [...new Set(authorIds)];
if (uniqueAuthorIds.length === 0) continue;
const authorMap = await bylineRepo.findByUserIds(uniqueAuthorIds, localeOpt);
for (const item of bucket) {
if (!item.authorId) continue;
const f = authorMap.get(item.authorId);
if (f) fallbackByItem.set(item.id, f);
}
}
}
// 4. Assign to each item.
for (const item of items) {
const explicit = bylinesByItem.get(item.id);
if (explicit && explicit.length > 0) {
item.bylines = explicit.map((c) => ({ ...c, source: "explicit" as const }));
item.byline = explicit[0]?.byline ?? null;
continue;
}
const fallback = fallbackByItem.get(item.id);
if (fallback) {
item.bylines = [{ byline: fallback, sortOrder: 0, roleLabel: null, source: "inferred" }];
item.byline = fallback;
continue;
}
item.bylines = [];
item.byline = null;
}
}
/**
* Resolve an identifier (ID or slug) to a real content ID.
* Returns the ID if found, null if not found.
* When locale is provided, slug lookups are scoped to that locale.
*/
async function resolveId(
repo: ContentRepository,
collection: string,
identifier: string,
locale?: string,
): Promise<string | null> {
const item = await repo.findByIdOrSlug(collection, identifier, locale);
return item?.id ?? null;
}
/**
* Resolve an identifier (ID or slug) to a real content ID,
* including trashed (soft-deleted) items.
*/
async function resolveIdIncludingTrashed(
repo: ContentRepository,
collection: string,
identifier: string,
locale?: string,
): Promise<string | null> {
const item = await repo.findByIdOrSlugIncludingTrashed(collection, identifier, locale);
return item?.id ?? null;
}
/**
* Trashed content item with deletion timestamp
*/
export interface TrashedContentItem {
id: string;
type: string;
slug: string | null;
status: string;
data: Record<string, unknown>;
authorId: string | null;
createdAt: string;
updatedAt: string;
publishedAt: string | null;
deletedAt: string;
}
/**
* Resolve the columns a content-list search should match against. Always
* includes `slug` (a standard column) and adds the `title`/`name` display
* fields when the collection actually defines them, mirroring the admin's
* item-title resolution (title -> name -> slug). Returning only existing
* columns avoids "no such column" errors on collections without them.
*/
async function resolveSearchColumns(db: Kysely<Database>, collection: string): Promise<string[]> {
const columns = ["slug"];
const row = await db
.selectFrom("_emdash_collections")
.select("id")
.where("slug", "=", collection)
.executeTakeFirst();
if (!row) return columns;
const fields = await db
.selectFrom("_emdash_fields")
.select("slug")
.where("collection_id", "=", row.id)
.execute();
const fieldSlugs = new Set(fields.map((f) => f.slug));
for (const candidate of ["title", "name"]) {
if (fieldSlugs.has(candidate)) columns.push(candidate);
}
return columns;
}
/**
* Decide whether the content-list `q` filter can be served from the
* collection's FTS5 index instead of a full-scan substring LIKE (#1517).
*
* Requires SQLite (FTS5 is SQLite-only), search enabled on the collection,
* every non-slug display column present in the searchable-field set (or the
* index would miss matches the LIKE finds), and the index table actually
* existing.
*/
async function canUseFtsForListFilter(
db: Kysely<Database>,
collection: string,
searchColumns: string[],
): Promise<boolean> {
if (!isSqlite(db)) return false;
const ftsManager = new FTSManager(db);
const config = await ftsManager.getSearchConfig(collection);
if (!config?.enabled) return false;
const searchable = new Set(await ftsManager.getSearchableFields(collection));
const covered = searchColumns.every((col) => col === "slug" || searchable.has(col));
if (!covered) return false;
return ftsManager.ftsTableExists(collection);
}
/**
* Create a 301 auto-redirect from an entry's old URL to its new one after a
* slug change, using the collection's URL pattern. Shared by
* handleContentUpdate (direct slug edits) and handleContentPublish (slug edits
* staged as `_slug` in a draft revision, which only land on publish).
*/
async function createSlugChangeRedirect(
db: Kysely<Database>,
collection: string,
oldSlug: string,
newSlug: string,
contentId: string,
): Promise<void> {
const collectionRow = await db
.selectFrom("_emdash_collections")
.select("url_pattern")
.where("slug", "=", collection)
.executeTakeFirst();
const redirectRepo = new RedirectRepository(db);
await redirectRepo.createAutoRedirect(
collection,
oldSlug,
newSlug,
contentId,
collectionRow?.url_pattern ?? null,
);
invalidateRedirectCache();
}
/** Matches a date-only `YYYY-MM-DD` bound (no time component). */
const DATE_ONLY_RE = /^\d{4}-\d{2}-\d{2}$/;
/**
* Normalize a date-range bound to an ISO datetime for lexicographic comparison
* against stored ISO 8601 timestamps. A bare `YYYY-MM-DD` is widened to the
* appropriate UTC day boundary so the range stays inclusive: a `start` bound
* becomes the start of the day and an `end` bound the end of the day.
* Otherwise a date-only upper bound would exclude every same-day row (since
* `2024-06-01T12:00:00Z` sorts after `2024-06-01`). Full datetimes pass
* through unchanged.
*/
function normalizeDateBound(value: string | undefined, edge: "start" | "end"): string | undefined {
if (!value) return undefined;
if (!DATE_ONLY_RE.test(value)) return value;
return edge === "start" ? `${value}T00:00:00.000Z` : `${value}T23:59:59.999Z`;
}
/**
* Create content list handler
*/
export async function handleContentList(
db: Kysely<Database>,
collection: string,
params: {
cursor?: string;
limit?: number;
status?: string;
orderBy?: string;
order?: "asc" | "desc";
locale?: string;
q?: string;
authorId?: string;
dateField?: ContentDateField;
dateFrom?: string;
dateTo?: string;
},
): Promise<ApiResult<ContentListResponse>> {
try {
const repo = new ContentRepository(db);
const where: FindManyOptions["where"] = {};
if (params.status) where.status = params.status;
if (params.locale) where.locale = params.locale;
if (params.authorId) where.authorId = params.authorId;
// A date range requires a target column; ignore stray from/to without
// a field so a half-specified filter doesn't silently drop all rows.
if (params.dateField && (params.dateFrom || params.dateTo)) {
where.dateFilter = {
field: params.dateField,
from: normalizeDateBound(params.dateFrom, "start"),
to: normalizeDateBound(params.dateTo, "end"),
};
}
const q = params.q?.trim();
if (q) {
where.q = q;
where.searchColumns = await resolveSearchColumns(db, collection);
where.useFts = await canUseFtsForListFilter(db, collection, where.searchColumns);
}
// Sorting by a non-system field (a collection's displayField/dateField,
// #1133) needs the collection's *actual* sort fields resolved server-side,
// so the orderBy set stays closed. Only query when it's not a system field.
let sortableExtras: string[] | undefined;
if (params.orderBy && !isSystemOrderField(params.orderBy)) {
const coll = await db
.selectFrom("_emdash_collections")
.select(["display_field", "date_field"])
.where("slug", "=", collection)
.executeTakeFirst();
sortableExtras = [coll?.display_field, coll?.date_field].filter(
(slug): slug is string => !!slug,
);
}
const result = await repo.findMany(collection, {
cursor: params.cursor,
limit: params.limit || 50,
where: Object.keys(where).length > 0 ? where : undefined,
orderBy: params.orderBy
? { field: params.orderBy, direction: params.order || "desc" }
: undefined,
sortableExtras,
});
// Hydrate SEO data if the collection has SEO enabled
const hasSeo = await collectionHasSeo(db, collection);
await hydrateSeoMany(db, collection, result.items, hasSeo);
await hydrateBylinesMany(db, collection, result.items);
return {
success: true,
data: {
items: result.items,
nextCursor: result.nextCursor,
total: result.total,
},
};
} catch (error) {
if (error instanceof InvalidCursorError) {
return {
success: false,
error: { code: "INVALID_CURSOR", message: error.message },
};
}
if (isMissingTableError(error)) {
return {
success: false,
error: {
code: "COLLECTION_NOT_FOUND",
message: `Collection '${collection}' not found`,
},
};
}
if (error instanceof EmDashValidationError) {
// e.g. invalid orderBy field
return {
success: false,
error: { code: "VALIDATION_ERROR", message: error.message },
};
}
console.error("Content list error:", error);
return {
success: false,
error: {
code: "CONTENT_LIST_ERROR",
message: "Failed to list content",
},
};
}
}
/** A content author option for the admin author filter. */
export interface ContentAuthor {
id: string;
name: string | null;
email: string;
avatarUrl: string | null;
}
/**
* List the distinct authors of a collection's live content.
*
* Backs the admin content-list author filter. Unlike `/admin/users` (ADMIN
* only), this is gated on `content:read`, so any editor can filter by author.
* Returns only users who have authored at least one non-trashed entry, sorted
* by display name then email for a stable dropdown order.
*/
export async function handleContentAuthors(
db: Kysely<Database>,
collection: string,
): Promise<ApiResult<{ items: ContentAuthor[] }>> {
try {
const repo = new ContentRepository(db);
const authorIds = await repo.findDistinctAuthorIds(collection);
if (authorIds.length === 0) {
return { success: true, data: { items: [] } };
}
const userRepo = new UserRepository(db);
const users = await userRepo.findByIds(authorIds);
const items: ContentAuthor[] = users
.map((u) => ({ id: u.id, name: u.name, email: u.email, avatarUrl: u.avatarUrl }))
.toSorted((a, b) => (a.name ?? a.email).localeCompare(b.name ?? b.email));
return { success: true, data: { items } };
} catch (error) {
if (isMissingTableError(error)) {
return {
success: false,
error: {
code: "COLLECTION_NOT_FOUND",
message: `Collection '${collection}' not found`,
},
};
}
console.error("Content authors error:", error);
return {
success: false,
error: {
code: "CONTENT_AUTHORS_ERROR",
message: "Failed to list content authors",
},
};
}
}
/**
* Get single content item
*/
export async function handleContentGet(
db: Kysely<Database>,
collection: string,
id: string,
locale?: string,
): Promise<ApiResult<ContentResponse>> {
try {
const repo = new ContentRepository(db);
const item = await repo.findByIdOrSlug(collection, id, locale);
if (!item) {
return {
success: false,
error: {
code: "NOT_FOUND",
message: `Content item not found: ${id}`,
},
};
}
// Hydrate SEO data if the collection has SEO enabled
const hasSeo = await collectionHasSeo(db, collection);
await hydrateSeo(db, collection, item, hasSeo);
await hydrateBylines(db, collection, item);
return {
success: true,
data: { item, _rev: encodeRev(item) },
};
} catch (error) {
console.error("Content get error:", error);
return {
success: false,
error: {
code: "CONTENT_GET_ERROR",
message: "Failed to get content",
},
};
}
}
/**
* Get a content item by id, including trashed items.
* Used by restore endpoint for ownership checks on soft-deleted items.
*/
export async function handleContentGetIncludingTrashed(
db: Kysely<Database>,
collection: string,
id: string,
locale?: string,
): Promise<ApiResult<ContentResponse>> {
try {
const repo = new ContentRepository(db);
const item = await repo.findByIdOrSlugIncludingTrashed(collection, id, locale);
if (!item) {
return {
success: false,
error: {
code: "NOT_FOUND",
message: `Content item not found: ${id}`,
},
};
}
// Hydrate SEO data if the collection has SEO enabled
const hasSeo = await collectionHasSeo(db, collection);
await hydrateSeo(db, collection, item, hasSeo);
await hydrateBylines(db, collection, item);
return {
success: true,
data: { item, _rev: encodeRev(item) },
};
} catch (error) {
console.error("Content get error:", error);
return {
success: false,
error: {
code: "CONTENT_GET_ERROR",
message: "Failed to get content",
},
};
}
}
/**
* Create content item.
*
* Content + SEO writes are wrapped in a transaction so either both succeed
* or neither does. If `body.seo` is provided for a non-SEO collection, the
* API returns a validation error rather than silently dropping it.
*/
export async function handleContentCreate(
db: Kysely<Database>,
collection: string,
body: {
data: Record<string, unknown>;
slug?: string;
status?: string;
authorId?: string;
bylines?: ContentBylineInput[];
locale?: string;
translationOf?: string;
seo?: ContentSeoInput;
taxonomies?: Record<string, string[]>;
createdAt?: string | null;
publishedAt?: string | null;
},
): Promise<ApiResult<ContentResponse>> {
try {
const hasSeo = await collectionHasSeo(db, collection);
// Reject SEO input for non-SEO collections
if (body.seo && !hasSeo) {
return {
success: false,
error: {
code: "VALIDATION_ERROR",
message: `Collection "${collection}" does not have SEO enabled. Remove the seo field or enable SEO on this collection.`,
},
};
}
const mimeCheck = await validateMediaFields(db, collection, body.data);
if (!mimeCheck.success) return mimeCheck;
// Wrap content + SEO writes in a transaction for atomicity
const item = await withTransaction(db, async (trx) => {
const repo = new ContentRepository(trx);
const bylineRepo = new BylineRepository(trx);
// Default to the configured site locale rather than the repo's
// hard-coded "en" — otherwise non-English default-locale sites
// silently create entries in a locale the editor never chose.
const effectiveLocale = body.locale ?? getI18nConfig()?.defaultLocale;
let slug: string | null | undefined = body.slug;
if (!slug) {
const slugSource = getSlugSource(body.data);
if (slugSource) {
slug = await repo.generateUniqueSlug(collection, slugSource, effectiveLocale);
}
}
const created = await repo.create({
type: collection,
slug,
data: body.data,
status: body.status || "draft",
authorId: body.authorId,
locale: effectiveLocale,
translationOf: body.translationOf,
createdAt: body.createdAt,
publishedAt: body.publishedAt,
});
if (body.bylines !== undefined) {
const credits = await bylineRepo.setContentBylines(collection, created.id, body.bylines);
// `setContentBylines` translates wire row ids to their
// `translation_group` before writing. The response-shape
// `primaryBylineId` must match what's now in the DB, so read
// it from the returned credit (whose `byline` came from a
// hydration round-trip).
created.primaryBylineId = credits[0]?.byline.translationGroup ?? null;
}
// When this row is a translation of an existing item, inherit
// the source's taxonomy assignments AND byline credits. Both
// pivots store translation_groups (taxonomies post-mig 036,
// bylines post-mig 040), so a copied row applies across every
// locale of the credited identity — and the locale-strict
// hydration below renders the variant that matches the entry's
// locale (or nothing if no variant exists yet at this locale,
// which is the documented Phase 4 behaviour).
//
// Explicit `body.bylines` wins — `copyContentBylines` no-ops
// when the target already has credits, but the cleaner guard
// is to skip the call entirely.
if (body.translationOf) {
const taxRepo = new TaxonomyRepository(trx);
await taxRepo.copyEntryTerms(collection, body.translationOf, created.id);
if (body.bylines === undefined) {
await bylineRepo.copyContentBylines(collection, body.translationOf, created.id);
// `copyContentBylines` writes the source's primary
// pointer onto the new row; reflect it in-memory so the
// response includes it before hydrateBylines runs.
const source = await repo.findById(collection, body.translationOf);
if (source) created.primaryBylineId = source.primaryBylineId;
}
}
await hydrateBylines(trx, collection, created);
// Side-write SEO data if provided
if (body.seo && hasSeo) {
const seoRepo = new SeoRepository(trx);
created.seo = await seoRepo.upsert(collection, created.id, body.seo);
} else if (hasSeo) {
// Assign defaults in-memory — no DB round-trip needed
created.seo = { ...SEO_DEFAULTS };
}
// Attach taxonomy terms in the same transaction. The MCP tool
// (and the REST create body) previously accepted a `taxonomies`
// field on `content_create` without doing anything with it, so
// agents publishing a categorized/tagged entry had to make N
// follow-up REST calls per taxonomy. This resolves each slug in
// the entry's locale and pipes it through the same
// `setTermsForEntry` path the `.../terms/{taxonomy}` REST route
// uses, so the two entry points can't drift.
if (body.taxonomies) {
await assignTaxonomies(trx, collection, created.id, effectiveLocale, body.taxonomies);
}
return created;
});
return {
success: true,
data: { item, _rev: encodeRev(item) },
};
} catch (error) {
if (isMissingTableError(error)) {
return {
success: false,
error: {
code: "COLLECTION_NOT_FOUND",
message: `Collection '${collection}' not found`,
},
};
}
if (error instanceof EmDashValidationError) {
return {
success: false,
error: { code: "VALIDATION_ERROR", message: error.message },
};
}
// SQLite UNIQUE constraint OR Postgres unique_violation — slug
// collisions and any other unique violations land here. Match
// specifically on "unique constraint failed" / "duplicate key" so we
// don't false-positive on NOT NULL or CHECK violations whose
// messages also contain "constraint failed".
const message = error instanceof Error ? error.message.toLowerCase() : "";
if (message.includes("unique constraint failed") || message.includes("duplicate key")) {
// Detect slug-specific collisions by message fingerprint
if (message.includes("slug")) {
return {
success: false,
error: {
code: "SLUG_CONFLICT",
message: `Slug '${body.slug ?? "(auto-generated)"}' already exists in collection '${collection}'`,
},
};
}
return {
success: false,
error: {
code: "CONFLICT",
message: "Unique constraint violation",
},
};
}
console.error("Content create error:", error);
return {
success: false,
error: {
code: "CONTENT_CREATE_ERROR",
message: "Failed to create content",
},
};
}
}
/**
* Update content item.
* If `_rev` is provided, validates it against the current version before writing.
* No `_rev` = blind write (backwards-compatible for admin UI).
*
* Content + SEO writes are wrapped in a transaction for atomicity.
*/
export async function handleContentUpdate(
db: Kysely<Database>,
collection: string,
id: string,
body: {
data?: Record<string, unknown>;
slug?: string;
status?: string;
authorId?: string | null;
bylines?: ContentBylineInput[];
locale?: string;
_rev?: string;
seo?: ContentSeoInput;
taxonomies?: Record<string, string[]>;
publishedAt?: string | null;
},
): Promise<ApiResult<ContentResponse>> {
try {
const hasSeo = await collectionHasSeo(db, collection);
// Reject SEO input for non-SEO collections
if (body.seo && !hasSeo) {
return {
success: false,
error: {
code: "VALIDATION_ERROR",
message: `Collection "${collection}" does not have SEO enabled. Remove the seo field or enable SEO on this collection.`,
},
};
}
if (body.data) {
const mimeCheck = await validateMediaFields(db, collection, body.data);
if (!mimeCheck.success) return mimeCheck;
}
const repo = new ContentRepository(db);
// Resolve slug → ID if needed
const resolvedId = (await resolveId(repo, collection, id, body.locale)) ?? id;
// Wrap content + SEO writes in a transaction for atomicity.
// The _rev check is inside the transaction so the read-then-write
// is atomic -- no concurrent write can slip between the check and update.
const item = await withTransaction(db, async (trx) => {
const trxRepo = new ContentRepository(trx);
const bylineRepo = new BylineRepository(trx);
// Read existing item once for both _rev check and old slug capture
const existing =
body._rev || body.slug ? await trxRepo.findById(collection, resolvedId) : null;
// Validate _rev if provided (optimistic concurrency)
if (body._rev) {
if (!existing) {
throw Object.assign(new Error(`Content item not found: ${id}`), {
apiError: { code: "NOT_FOUND" as const },
});
}
const revCheck = validateRev(body._rev, existing);
if (!revCheck.valid) {
throw Object.assign(new Error(revCheck.message), {
apiError: { code: "CONFLICT" as const },
});
}
}
// Capture old slug before update for auto-redirect
let oldSlug: string | undefined;
if (body.slug && existing?.slug && existing.slug !== body.slug) {
oldSlug = existing.slug;
}
const updated = await trxRepo.update(collection, resolvedId, {
data: body.data,
slug: body.slug,
status: body.status,
authorId: body.authorId,
publishedAt: body.publishedAt,
});
if (body.bylines !== undefined) {
const credits = await bylineRepo.setContentBylines(collection, resolvedId, body.bylines);
// `setContentBylines` translates wire row ids to their
// `translation_group` before writing. Read the in-memory
// pointer from the persisted credit so the response shape
// matches the DB. See the matching block in handleContentCreate.
updated.primaryBylineId = credits[0]?.byline.translationGroup ?? null;
}
// Create auto-redirect when slug changes
if (oldSlug && body.slug) {
await createSlugChangeRedirect(trx, collection, oldSlug, body.slug, resolvedId);
}
// Sync non-translatable fields to sibling locales in the same
// translation group. Only runs when i18n is enabled, data was updated,
// and the item belongs to a translation group with siblings.
if (isI18nEnabled() && body.data && updated.translationGroup) {
await syncNonTranslatableFields(
trx,
collection,
updated.id,
updated.translationGroup,
body.data,
);
}
// Side-write SEO data if provided, always hydrate for SEO-enabled collections
if (body.seo && hasSeo) {
const seoRepo = new SeoRepository(trx);
updated.seo = await seoRepo.upsert(collection, resolvedId, body.seo);
} else if (hasSeo) {
const seoRepo = new SeoRepository(trx);
updated.seo = await seoRepo.get(collection, resolvedId);
}
await hydrateBylines(trx, collection, updated);
// Replace taxonomy assignments in the same transaction. Uses the
// entry's own locale (post-update) to resolve slugs so an update
// that also changes locale still lands on the correct term
// variants. See handleContentCreate for rationale.
if (body.taxonomies) {
await assignTaxonomies(
trx,
collection,
resolvedId,
updated.locale ?? body.locale,
body.taxonomies,
);
}
return updated;
});
return {