-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy pathquery.ts
More file actions
1478 lines (1356 loc) · 50.9 KB
/
Copy pathquery.ts
File metadata and controls
1478 lines (1356 loc) · 50.9 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
/// <reference types="astro/client" />
/**
* Query functions for EmDash content
*
* These wrap Astro's getLiveCollection/getLiveEntry with type filtering.
* Use these instead of calling Astro's functions directly.
*
* Error handling follows Astro's pattern - returns { entries/entry, error }
* so callers can gracefully handle errors (including 404s).
*
* Preview mode is handled implicitly via ALS request context —
* no parameters needed. The middleware verifies the preview token
* and sets the context; query functions read it automatically.
*
* The triple-slash directive above pulls in the ambient declaration for
* `astro:content` (used by the dynamic imports below) so this source
* file typechecks even when reached transitively by a sibling package
* whose tsconfig doesn't list `astro/client` in `compilerOptions.types`.
*
* Note: the directive is stripped from the compiled output (`dist/*`)
* by tsdown, so it does not propagate to downstream consumers of the
* published package. Consumers are Astro sites and already provide their
* own `astro/client` ambient surface anyway, so the runtime dynamic
* import resolves there at typecheck time without our help.
*/
import { encodeCursor, type ContentSeo } from "./database/repositories/types.js";
import { getFallbackChain, getI18nConfig, isI18nEnabled } from "./i18n/config.js";
import {
creditsFromFoldedBylines,
CURSOR_RAW_VALUES,
FOLDED_BYLINES,
FOLDED_BYLINES_EXIST,
FOLDED_TERMS,
loadPublishedDates,
type WhereRange,
type WhereValue,
} from "./loader.js";
import {
cachedQuery,
contentCacheNamespaces,
contentNamespaces,
invalidateSchemaObjectCache,
} from "./object-cache/index.js";
import { primeSeoPanel } from "./page/seo-panel.js";
import { requestCached } from "./request-cache.js";
import { getRequestContext } from "./request-context.js";
import { resetRegisteredCollectionsCache } from "./schema/collection-slugs-cache.js";
import { compileUrlPattern } from "./schema/url-pattern.js";
import type { TaxonomyTerm } from "./taxonomies/types.js";
import { isMissingColumnError, isMissingTableError } from "./utils/db-errors.js";
import {
createEditable,
createNoop,
type EditProxy,
type EditableOptions,
} from "./visual-editing/editable.js";
/**
* Collection type registry for type-safe queries.
*
* This interface is extended by the generated emdash-env.d.ts file
* to provide type inference for collection names and their data shapes.
*
* @example
* ```ts
* // In emdash-env.d.ts (generated):
* declare module "emdash" {
* interface EmDashCollections {
* posts: { title: string; content: PortableTextBlock[]; };
* pages: { title: string; body: PortableTextBlock[]; };
* }
* }
*
* // Then in your code:
* const { entries } = await getEmDashCollection("posts");
* // entries[0].data.title is typed as string
* ```
*/
// eslint-disable-next-line @typescript-eslint/no-empty-object-type
export interface EmDashCollections {}
/**
* Helper type to infer the data type for a collection.
* Returns the registered type if known, otherwise falls back to Record<string, unknown>.
*/
export type InferCollectionData<T extends string> = T extends keyof EmDashCollections
? EmDashCollections[T]
: Record<string, unknown>;
/**
* Sort direction
*/
export type SortDirection = "asc" | "desc";
/**
* Order by specification - field name to direction
* @example { created_at: "desc" } - Sort by created_at descending
* @example { title: "asc" } - Sort by title ascending
* @example { published_at: "desc", title: "asc" } - Multi-field sort
*/
export type OrderBySpec = Record<string, SortDirection>;
export type { WhereRange, WhereValue };
/**
* Fields shared by every collection query, independent of pagination mode.
*
* Cursor and offset pagination are mutually exclusive, so they live on the
* `CursorCollectionFilter` / `OffsetCollectionFilter` variants rather than
* here. Use the {@link CollectionFilter} union for any value that may be
* either.
*/
export interface CollectionFilterBase {
status?: "draft" | "published" | "archived";
limit?: number;
/**
* Filter by field values, taxonomy terms, byline credits, or ranges.
*
* Taxonomy names are detected automatically and filtered via JOIN.
* The reserved `byline` key filters by byline credit (any credit, not
* just the primary one) via the `_emdash_content_bylines` junction
* table; its value is one or more byline translation groups. This
* matches co-authored entries, which `primary_byline_id` alone misses.
* Other keys are treated as column filters on the content table.
*
* @example { category: 'news' } - Filter by taxonomy term
* @example { category: ['news', 'featured'] } - Filter by multiple terms (OR)
* @example { byline: '01HXYZ...' } - Entries credited to a byline (any position)
* @example { byline: ['01HXYZ...', '01HABC...'] } - Credited to any of these bylines (OR)
* @example { series: 'main' } - Exact match on a content field
* @example { published_at: { gte: '2024-01-01', lt: '2025-01-01' } } - Date range
*/
where?: Record<string, WhereValue>;
/**
* Order results by field(s)
* @default { created_at: "desc" }
* @example { created_at: "desc" } - Sort by created_at descending (default)
* @example { title: "asc" } - Sort by title ascending
* @example { published_at: "desc", title: "asc" } - Multi-field sort
*/
orderBy?: OrderBySpec;
/**
* Filter by locale. When set, only returns entries in this locale.
* Only relevant when i18n is configured.
* @example "en" — English entries only
* @example "fr" — French entries only
*/
locale?: string;
}
/** Keyset-paginated query filter. Cannot also carry an `offset`. */
export interface CursorCollectionFilter extends CollectionFilterBase {
/**
* Opaque cursor for keyset pagination.
* Pass the `nextCursor` value from a previous result to fetch the next page.
* @example
* ```ts
* const cursor = Astro.url.searchParams.get("cursor") ?? undefined;
* const { entries, nextCursor } = await getEmDashCollection("posts", {
* limit: 10,
* cursor,
* });
* ```
*/
cursor?: string;
offset?: never;
}
/** Offset-paginated query filter. Cannot also carry a `cursor`. */
export interface OffsetCollectionFilter extends CollectionFilterBase {
/**
* Skip this many entries before returning results (offset pagination).
*
* Use with `limit` to render numbered archive routes like `/page/2`
* without walking cursors or over-fetching from the start:
*
* ```ts
* const perPage = 20;
* const { entries, hasMore } = await getEmDashCollection("posts", {
* limit: perPage,
* offset: (page - 1) * perPage,
* orderBy: { published_at: "desc" },
* });
* ```
*
* Only a positive integer applies.
*/
offset?: number;
cursor?: never;
}
/**
* Filter for `getEmDashCollection`.
*
* A union of the cursor and offset pagination variants: supplying both
* `cursor` and `offset` is a compile-time error, since they are mutually
* exclusive ways to express "the next page" (cursor wins at runtime).
*/
export type CollectionFilter = CursorCollectionFilter | OffsetCollectionFilter;
export interface ContentEntry<T = Record<string, unknown>> {
id: string;
data: T;
/** Visual editing annotations. Spread onto elements: {...entry.edit.title} */
edit: EditProxy;
}
/** Cache hint returned by the content loader for route caching */
export interface CacheHint {
tags?: string[];
lastModified?: Date;
}
interface PublishedDatesResult {
dates: Date[];
cacheHint: CacheHint;
error?: Error;
}
/** @internal Publication dates for the Archives widget. */
export async function getPublishedDates(
type: string,
options?: { locale?: string },
): Promise<PublishedDatesResult> {
const locale = effectiveLocaleKey(options) || undefined;
const key = `publishedDates:${JSON.stringify([type, locale])}`;
try {
return await requestCached(key, () =>
cachedQuery<PublishedDatesResult>({
namespace: contentCacheNamespaces(type),
key,
load: async () => {
const rows = await loadPublishedDates(type, locale);
const dates: Date[] = [];
let lastModified: Date | undefined;
for (const row of rows) {
if (row.published_at) {
const date = new Date(row.published_at);
if (!Number.isNaN(date.getTime())) dates.push(date);
}
if (row.updated_at) {
const modified = new Date(row.updated_at);
if (!Number.isNaN(modified.getTime()) && (!lastModified || modified > lastModified)) {
lastModified = modified;
}
}
}
return { dates, cacheHint: { tags: [type], lastModified } };
},
}),
);
} catch (error) {
return {
dates: [],
cacheHint: {},
error:
isMissingTableError(error) || isMissingColumnError(error)
? undefined
: error instanceof Error
? error
: new Error("Failed to load publication dates"),
};
}
}
/**
* Result from getEmDashCollection
*/
export interface CollectionResult<T> {
/** The entries (empty array if error or none found) */
entries: ContentEntry<T>[];
/** Error if the query failed */
error?: Error;
/** Cache hint for route caching (pass to Astro.cache.set()) */
cacheHint: CacheHint;
/**
* Opaque cursor for the next page.
* Undefined when there are no more results.
* Pass this as `cursor` in the next query to get the next page.
*/
nextCursor?: string;
/**
* Whether more entries exist beyond this page. Set whenever `limit` is
* provided (cursor or offset pagination), so numbered archive routes can
* render a "next page" link without computing a total count.
*/
hasMore?: boolean;
}
/**
* Result from getEmDashEntry
*/
export interface EntryResult<T> {
/** The entry, or null if not found */
entry: ContentEntry<T> | null;
/** Error if the query failed (not set for "not found", only for actual errors) */
error?: Error;
/** Whether we're in preview mode (valid token was provided) */
isPreview: boolean;
/** Set when a fallback locale was used instead of the requested locale */
fallbackLocale?: string;
/** Cache hint for route caching (pass to Astro.cache.set()) */
cacheHint: CacheHint;
}
const COLLECTION_NAME = "_emdash";
/** Symbol key for edit metadata on PT arrays — avoids collision with user data */
const EMDASH_EDIT = Symbol.for("__emdash");
/** Edit metadata attached to PT arrays in edit mode */
export interface EditFieldMeta {
collection: string;
id: string;
field: string;
}
/** Type guard for EditFieldMeta */
function isEditFieldMeta(value: unknown): value is EditFieldMeta {
if (typeof value !== "object" || value === null) return false;
if (!("collection" in value) || !("id" in value) || !("field" in value)) return false;
// After `in` checks, TS narrows to Record<"collection" | "id" | "field", unknown>
const { collection, id, field } = value;
return typeof collection === "string" && typeof id === "string" && typeof field === "string";
}
/**
* Read edit metadata from a value (returns undefined if not tagged).
* Uses Object.getOwnPropertyDescriptor to access Symbol-keyed property
* without an unsafe type assertion.
*/
export function getEditMeta(value: unknown): EditFieldMeta | undefined {
if (value && typeof value === "object") {
const desc = Object.getOwnPropertyDescriptor(value, EMDASH_EDIT);
const meta: unknown = desc?.value;
if (isEditFieldMeta(meta)) {
return meta;
}
}
return undefined;
}
/**
* Tag PT-like arrays in entry data with edit metadata (non-enumerable).
* A PT array is identified by: is an array, first element has _type property.
*/
function tagEditableFields(data: Record<string, unknown>, collection: string, id: string): void {
for (const [field, value] of Object.entries(data)) {
if (
Array.isArray(value) &&
value.length > 0 &&
value[0] &&
typeof value[0] === "object" &&
"_type" in value[0]
) {
Object.defineProperty(value, EMDASH_EDIT, {
value: { collection, id, field } satisfies EditFieldMeta,
enumerable: false,
configurable: true,
});
}
}
}
/** Safely read a string field from a Record, with optional fallback */
function dataStr(data: Record<string, unknown>, key: string, fallback = ""): string {
const val = data[key];
return typeof val === "string" ? val : fallback;
}
/** Type guard for Record<string, unknown> */
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null && !Array.isArray(value);
}
/** Extract data as Record from an Astro entry (which is any-typed) */
function entryData(entry: { data?: unknown }): Record<string, unknown> {
return isRecord(entry.data) ? entry.data : {};
}
/** Extract the database ID from entry data (data.id is the ULID, entry.id is the slug) */
function entryDatabaseId(entry: { id: string; data?: unknown }): string {
const d = entryData(entry);
return dataStr(d, "id") || entry.id;
}
/** Extract edit options from entry data for the proxy */
function entryEditOptions(entry: { data?: unknown }): EditableOptions {
const data = entryData(entry);
const status = dataStr(data, "status", "draft");
const draftRevisionId = dataStr(data, "draftRevisionId") || undefined;
const liveRevisionId = dataStr(data, "liveRevisionId") || undefined;
const hasDraft = !!draftRevisionId && draftRevisionId !== liveRevisionId;
return { status, hasDraft };
}
function stripRevisionMetadata(entry: { data?: unknown }): void {
const data = entryData(entry);
delete data.draftRevisionId;
delete data.liveRevisionId;
}
function canExposeRevisionMetadata(
entry: { id: string; data?: unknown },
collection: string,
): boolean {
const ctx = getRequestContext();
if (ctx?.editMode) return true;
if (ctx?.preview?.collection !== collection) return false;
const dbId = entryDatabaseId(entry);
return ctx.preview.id === dbId || ctx.preview.id === entry.id;
}
/**
* Get all entries of a content type
*
* Returns { entries, error } for graceful error handling.
*
* When emdash-env.d.ts is generated, the collection name will be
* type-checked and the return type will be inferred automatically.
*
* @example
* ```ts
* import { getEmDashCollection } from "emdash";
*
* const { entries: posts, error } = await getEmDashCollection("posts");
* if (error) {
* console.error("Failed to load posts:", error);
* return;
* }
* // posts[0].data.title is typed (if emdash-env.d.ts exists)
*
* // With filters
* const { entries: drafts } = await getEmDashCollection("posts", { status: "draft" });
* ```
*/
export async function getEmDashCollection<T extends string, D = InferCollectionData<T>>(
type: T,
filter?: CollectionFilter,
): Promise<CollectionResult<D>> {
// Cache per (type, filter) within a single request. Edit mode and
// preview are request-scoped and stable, so they don't need to be
// part of the key. Widgets and layouts frequently request the same
// collection shape as the page itself (e.g. a "recent posts" list
// appears on the home page AND in the sidebar) — caching collapses
// those duplicate queries, along with the bylines and taxonomy-term
// hydration each call would otherwise re-do.
//
// Bucket small limits to a shared minimum so a page with several
// "recent N posts" widgets at slightly different limits (e.g. a
// post-detail page asking for 4 in the body and 5 in the sidebar)
// shares one fetch + hydration round-trip rather than running two.
// Cursor-paginated calls are exempt: their limit is part of the
// pagination contract.
const bucketed = bucketFilter(filter);
// Preview and edit-mode requests skip `loadCollectionCached`. That path
// reduces every entry to a JSON snapshot (`entrySnapshot`) and rebuilds it
// with `reviveEntry`, which cannot carry the `edit` proxy and re-attaches
// the no-op — so annotations spread as `{...entry.edit.title}` would render
// nothing on list pages. `getEmDashEntry` has the same bypass for the same
// reason (see its `serveDrafts` branch). The request-scoped cache still
// collapses duplicate queries within the render.
const ctx = getRequestContext();
const serveDrafts = ctx?.editMode === true || ctx?.preview !== undefined;
const cached = await requestCached(collectionCacheKey(type, bucketed.fetchFilter), () =>
serveDrafts
? getEmDashCollectionUncached<T, D>(type, bucketed.fetchFilter)
: loadCollectionCached<T, D>(type, bucketed.fetchFilter),
);
return bucketed.requestedLimit === undefined
? cached
: sliceCollectionResult(cached, bucketed.requestedLimit, filter?.orderBy);
}
/** Shape of a cached collection snapshot (entries reduced to JSON-safe form). */
interface CachedCollectionValue {
entries: unknown[];
nextCursor?: string;
hasMore?: boolean;
cacheHint: CacheHint;
}
/**
* Distributed (L2) read-through around {@link getEmDashCollectionUncached}.
*
* Caches a JSON-safe snapshot keyed by collection + filter + effective locale,
* folding the shared `bylines`/`taxonomies` epochs into the key so renaming an
* author or term invalidates affected lists. Errors are never cached.
*/
async function loadCollectionCached<T extends string, D = InferCollectionData<T>>(
type: T,
filter?: CollectionFilter,
): Promise<CollectionResult<D>> {
const snapshot = await cachedQuery<ContentSnapshot<CachedCollectionValue>>({
namespace: contentNamespaces(type),
key: `collection:${collectionCacheKey(type, filter)}|loc=${effectiveLocaleKey(filter)}`,
load: async () => {
const result = await getEmDashCollectionUncached<T, D>(type, filter);
if (result.error) {
return { ok: false, error: result.error, cacheHint: result.cacheHint };
}
return {
ok: true,
value: {
entries: result.entries.map(entrySnapshot),
nextCursor: result.nextCursor,
hasMore: result.hasMore,
cacheHint: result.cacheHint,
},
};
},
cacheable: (snap) => snap.ok,
});
if (!snapshot.ok) {
return { entries: [], error: snapshot.error, cacheHint: snapshot.cacheHint };
}
return {
entries: snapshot.value.entries.map((entry) => {
const revived = reviveEntry<D>(entry);
if (!canExposeRevisionMetadata(revived, type)) stripRevisionMetadata(revived);
return revived;
}),
nextCursor: snapshot.value.nextCursor,
hasMore: snapshot.value.hasMore,
cacheHint: snapshot.value.cacheHint,
};
}
/**
* Threshold for limit bucketing. Page templates routinely render small
* "recent posts" widgets at limits 3-8; rounding those up to a single
* shared bucket lets one fetch satisfy several widgets within a request.
* Above this, the requested limit is honoured exactly — bucketing limit:50
* to limit:64 would waste hydration work for callers fetching real pages.
*/
const BUCKET_LIMIT_THRESHOLD = 10;
interface BucketedFilter {
/** Filter to pass to the loader (with limit possibly raised). */
fetchFilter: CollectionFilter | undefined;
/** Original limit; defined only when bucketing was applied. */
requestedLimit: number | undefined;
}
/** @internal exported for unit tests; not part of the public API. */
export function bucketFilter(filter: CollectionFilter | undefined): BucketedFilter {
const limit = filter?.limit;
if (
limit === undefined ||
limit >= BUCKET_LIMIT_THRESHOLD ||
limit <= 0 ||
filter?.cursor !== undefined ||
// Offset paginates a deliberate page window; its limit is part of the
// pagination contract, so don't round it up the way "recent N" widgets get.
filter?.offset !== undefined
) {
return { fetchFilter: filter, requestedLimit: undefined };
}
return {
fetchFilter: { ...filter, limit: BUCKET_LIMIT_THRESHOLD },
requestedLimit: limit,
};
}
/**
* Slice a cached bucketed result down to the originally-requested limit
* and recompute `nextCursor` from the row that would have been the
* over-fetch detector for that limit. When truncation is needed, returns
* a shallow-copied result with a new `entries` array; otherwise returns
* the cached result unchanged (including error results and results
* already within the requested limit).
*/
/** @internal exported for unit tests; not part of the public API. */
export function sliceCollectionResult<D>(
cached: CollectionResult<D>,
limit: number,
orderBy: OrderBySpec | undefined,
): CollectionResult<D> {
if (cached.error) return cached;
if (cached.entries.length <= limit) return cached;
const sliced = cached.entries.slice(0, limit);
// Mirror the loader's encoding: cursor points at the last returned row,
// so "next page" picks up at the row immediately after it. See
// buildCursorCondition in loader.ts — it filters strictly past this row.
const lastEntry = sliced.at(-1);
const nextCursor = lastEntry ? encodeEntryCursor(lastEntry, orderBy) : undefined;
// Truncating to the requested limit means at least one more entry existed.
return { ...cached, entries: sliced, nextCursor, hasMore: true };
}
/** Map of database column names to camelCase keys present on entry.data. */
const ENTRY_DATA_KEY_MAP: Record<string, string> = {
created_at: "createdAt",
updated_at: "updatedAt",
published_at: "publishedAt",
scheduled_at: "scheduledAt",
author_id: "authorId",
primary_byline_id: "primaryBylineId",
};
// Mirror loader.ts FIELD_NAME_PATTERN. Kept in sync intentionally — diverging
// would let the encoder accept a field name the loader's getPrimarySort then
// rejected, producing a cursor that paginates against a different column.
const FIELD_NAME_PATTERN = /^[a-zA-Z_][a-zA-Z0-9_]*$/;
/**
* Encode a `nextCursor` from a content entry, mirroring the loader's
* encoding scheme: `(orderValue, id)` where `orderValue` is the primary
* sort field's stringified value. For date columns, reads the raw DB
* string the loader stashed via CURSOR_RAW_VALUES — round-tripping the
* parsed Date through `toISOString()` would lose precision for stored
* values that aren't already ISO-with-milliseconds.
*/
function encodeEntryCursor<D>(
entry: ContentEntry<D>,
orderBy: OrderBySpec | undefined,
): string | undefined {
const data = entryData(entry);
const id = dataStr(data, "id");
if (!id) return undefined;
// Match loader.ts getPrimarySort: take the first valid field, default to created_at.
let dbField = "created_at";
if (orderBy) {
for (const field of Object.keys(orderBy)) {
if (FIELD_NAME_PATTERN.test(field)) {
dbField = field;
break;
}
}
}
// Date columns: prefer the raw stored string captured by the loader so
// the cursor matches what a direct loader fetch would emit, regardless
// of how the DB stored the timestamp.
const rawDateValuesRaw = Reflect.get(data, CURSOR_RAW_VALUES);
if (rawDateValuesRaw !== null && typeof rawDateValuesRaw === "object") {
const raw = Reflect.get(rawDateValuesRaw, dbField);
if (typeof raw === "string") return encodeCursor(raw, id);
}
const dataKey = ENTRY_DATA_KEY_MAP[dbField] ?? dbField;
const value = data[dataKey];
let orderValue: string;
if (value instanceof Date) {
orderValue = value.toISOString();
} else if (typeof value === "string" || typeof value === "number") {
orderValue = String(value);
} else {
// Match the loader's empty-string fallback for null/undefined order
// values so cursor decoding stays valid even at the boundary.
orderValue = "";
}
return encodeCursor(orderValue, id);
}
/**
* Build a canonical cache key for `getEmDashCollection`.
*
* `JSON.stringify` is insertion-order-sensitive, so two callers passing
* semantically identical filters with different key orders would miss
* the cache. We fix the top-level field order and sort `where` keys
* (order there is irrelevant), while preserving `orderBy` key order
* because that's the sort priority.
*/
function collectionCacheKey(type: string, filter?: CollectionFilter): string {
if (!filter) return `collection:${type}:`;
const parts = [
filter.status ?? "",
filter.limit ?? "",
filter.cursor ?? "",
filter.offset ?? "",
filter.where ? stableStringify(filter.where) : "",
filter.orderBy ? JSON.stringify(filter.orderBy) : "",
filter.locale ?? "",
];
return `collection:${type}:${parts.join("|")}`;
}
function stableStringify(value: Record<string, unknown>): string {
return JSON.stringify(stableOrder(value));
}
function stableOrder(value: Record<string, unknown>): Record<string, unknown> {
const keys = Object.keys(value).toSorted();
const ordered: Record<string, unknown> = {};
for (const k of keys) {
const v = value[k];
if (isRecord(v)) {
ordered[k] = stableOrder(v);
} else {
ordered[k] = v;
}
}
return ordered;
}
// ── Object-cache (L2) serialization for content reads ───────────────────────
//
// Content entries can't be stored verbatim: each carries a non-serializable
// `edit` proxy (a function) and a non-enumerable `CURSOR_RAW_VALUES` symbol on
// `data` (raw date strings used to reproduce the loader's pagination cursor).
// We reduce each entry to a JSON-safe snapshot before caching — copying the
// cursor-raw values into an enumerable field and dropping `edit` — then rebuild
// the symbol and re-attach a no-op `edit` on the way out. The object cache's
// codec preserves `Date` instances, so timestamps survive the round-trip.
//
// L2 is only consulted for anonymous, non-preview, non-edit requests (see
// `shouldBypass` in object-cache), where `edit` is always the no-op variant —
// so dropping and recreating it is lossless.
/** Enumerable field carrying the {@link CURSOR_RAW_VALUES} payload in snapshots. */
const CURSOR_RAW_FIELD = "__emdashCursorRaw";
/** Result wrapper distinguishing a cached error from a cacheable success. */
type ContentSnapshot<S> =
| { ok: true; value: S }
| { ok: false; error?: Error; cacheHint: CacheHint };
function entrySnapshot<D>(entry: ContentEntry<D>): Record<string, unknown> {
const data = entryData(entry);
const rawCursor = Reflect.get(data, CURSOR_RAW_VALUES);
// Drop the `edit` function; copy enumerable data + the cursor-raw values.
const { edit: _edit, ...rest } = entry as ContentEntry<D> & { edit?: unknown };
return {
...rest,
data: { ...data, [CURSOR_RAW_FIELD]: rawCursor ?? {} },
};
}
function reviveEntry<D>(raw: unknown): ContentEntry<D> {
// eslint-disable-next-line typescript/no-unsafe-type-assertion -- snapshot shape produced by entrySnapshot
const entry = raw as Record<string, unknown>;
// eslint-disable-next-line typescript/no-unsafe-type-assertion -- snapshot `data` is always a record
const data: Record<string, unknown> = { ...(entry.data as Record<string, unknown>) };
// eslint-disable-next-line typescript/no-unsafe-type-assertion -- snapshot field written by entrySnapshot
const rawCursor = (data[CURSOR_RAW_FIELD] as Record<string, string> | undefined) ?? {};
delete data[CURSOR_RAW_FIELD];
Object.defineProperty(data, CURSOR_RAW_VALUES, {
value: rawCursor,
enumerable: false,
configurable: false,
writable: false,
});
// eslint-disable-next-line typescript/no-unsafe-type-assertion -- rebuilt to the ContentEntry shape with a no-op edit proxy
return { ...entry, data, edit: createNoop() } as ContentEntry<D>;
}
/** Resolve the effective locale used by content reads, for the L2 cache key. */
function effectiveLocaleKey(filter?: { locale?: string }): string {
const ctx = getRequestContext();
const i18nConfig = getI18nConfig();
return (
filter?.locale ?? ctx?.locale ?? (isI18nEnabled() ? i18nConfig!.defaultLocale : undefined) ?? ""
);
}
async function getEmDashCollectionUncached<T extends string, D = InferCollectionData<T>>(
type: T,
filter?: CollectionFilter,
): Promise<CollectionResult<D>> {
// Dynamic import to avoid build-time issues
const { getLiveCollection } = await import("astro:content");
// Resolve locale: explicit filter > ALS context > defaultLocale (when i18n enabled)
// Without this, queries return all locale rows, producing broken IDs
const ctx = getRequestContext();
const i18nConfig = getI18nConfig();
const resolvedLocale =
filter?.locale ?? ctx?.locale ?? (isI18nEnabled() ? i18nConfig!.defaultLocale : undefined);
const requestedLimit = filter?.limit;
// cursor and offset are mutually exclusive on the loader filter union, so
// spread only the one in play (cursor wins) rather than emitting both keys.
const pageParam =
filter?.cursor !== undefined
? { cursor: filter.cursor }
: filter?.offset !== undefined
? { offset: filter.offset }
: {};
const result = await getLiveCollection(COLLECTION_NAME, {
type,
status: filter?.status,
limit: requestedLimit && requestedLimit > 0 ? requestedLimit + 1 : filter?.limit,
...pageParam,
where: filter?.where,
orderBy: filter?.orderBy,
locale: resolvedLocale,
});
const { entries, error, cacheHint } = result;
if (error) {
return { entries: [], error, cacheHint: {} };
}
const hasMore = requestedLimit != null && requestedLimit > 0 && entries.length > requestedLimit;
const pageEntries = hasMore ? entries.slice(0, requestedLimit) : entries;
const nextCursor = hasMore ? encodeEntryCursor(pageEntries.at(-1), filter?.orderBy) : undefined;
// `hasMore` is only meaningful when a limit bounds the page; otherwise the
// query returned everything and there is no "next page" to report.
const hasMoreResult = requestedLimit != null && requestedLimit > 0 ? hasMore : undefined;
const isEditMode = ctx?.editMode ?? false;
const entriesWithEdit = pageEntries.map((entry: ContentEntry<D>) => {
const dbId = entryDatabaseId(entry);
if (isEditMode) {
tagEditableFields(entryData(entry), type, dbId);
}
if (!canExposeRevisionMetadata(entry, type)) {
stripRevisionMetadata(entry);
}
return {
...entry,
edit: isEditMode ? createEditable(type, dbId, entryEditOptions(entry)) : createNoop(),
};
});
// Eagerly hydrate bylines and taxonomy terms for all entries in parallel.
// Both are independent queries, so running them concurrently halves the
// round-trip cost on remote databases (D1 replicas, etc.).
await Promise.all([
hydrateEntryBylines(type, entriesWithEdit),
// Use the content query locale as the preferred term locale; hydration
// falls back only to the configured default when a group lacks that variant.
hydrateEntryTerms(type, entriesWithEdit, resolvedLocale),
]);
return {
entries: entriesWithEdit,
nextCursor,
hasMore: hasMoreResult,
cacheHint: cacheHint ?? {},
};
}
/**
* Get a single entry by type and ID/slug
*
* Returns { entry, error, isPreview } for graceful error handling.
* - entry is null if not found (not an error)
* - error is set only for actual errors (db issues, etc.)
*
* Preview mode is detected automatically from request context (ALS).
* When the URL has a valid `_preview` token, the middleware sets preview
* context and this function serves draft revision data if available.
*
* @example
* ```ts
* import { getEmDashEntry } from "emdash";
*
* // Simple usage — preview just works via middleware
* const { entry: post, isPreview, error } = await getEmDashEntry("posts", "my-slug");
* if (!post) return Astro.redirect("/404");
* ```
*/
export async function getEmDashEntry<T extends string, D = InferCollectionData<T>>(
type: T,
id: string,
options?: { locale?: string },
): Promise<EntryResult<D>> {
// Dynamic import to avoid build-time issues
const { getLiveEntry } = await import("astro:content");
// Check ALS for preview and edit mode context
const ctx = getRequestContext();
const preview = ctx?.preview;
const isEditMode = ctx?.editMode ?? false;
const isPreviewMode = !!preview && preview.collection === type;
// Edit mode implies preview — editors should see draft content
const serveDrafts = isPreviewMode || isEditMode;
// Resolve locale: explicit option > ALS context > undefined (no filter)
const requestedLocale = options?.locale ?? ctx?.locale;
/** Wrap a raw Astro entry with edit proxy, tagging editable fields if needed */
function wrapEntry(raw: ContentEntry<D>): ContentEntry<D> {
const dbId = entryDatabaseId(raw);
if (isEditMode) {
tagEditableFields(entryData(raw), type, dbId);
}
return {
...raw,
edit: isEditMode ? createEditable(type, dbId, entryEditOptions(raw)) : createNoop(),
};
}
/** Check if an entry has completed publication. */
function isVisible(entry: ContentEntry<D>): boolean {
return dataStr(entryData(entry), "status") === "published";
}
// Build the fallback chain: [requestedLocale, fallback1, ..., defaultLocale]
// When i18n is disabled or no locale requested, just use a single-element chain
const localeChain =
requestedLocale && isI18nEnabled() ? getFallbackChain(requestedLocale) : [requestedLocale];
/** Return a successful EntryResult with bylines and taxonomy terms hydrated */
async function successResult(
wrapped: ContentEntry<D>,
opts: { isPreview: boolean; fallbackLocale?: string; cacheHint: CacheHint },
): Promise<EntryResult<D>> {
if (!opts.isPreview) stripRevisionMetadata(wrapped);
// No-i18n callers use the legacy wildcard cache key. The query path still
// resolves against the stored content-row locale when this is undefined.
const termLocale = isI18nEnabled()
? dataStr(entryData(wrapped), "locale") || undefined
: undefined;
await Promise.all([
hydrateEntryBylines(type, [wrapped]),
hydrateEntryTerms(type, [wrapped], termLocale),
]);
return {
entry: wrapped,
isPreview: opts.isPreview,
fallbackLocale: opts.fallbackLocale,
cacheHint: opts.cacheHint,
};
}
if (serveDrafts) {
// Draft mode: try each locale in the fallback chain
for (let i = 0; i < localeChain.length; i++) {
const locale = localeChain[i];
const fallbackLocale = i > 0 ? locale : undefined;
const {
entry: baseEntry,
error: baseError,
cacheHint,
} = await getLiveEntry(COLLECTION_NAME, {
type,
id,
locale,
});
if (baseError) {
return { entry: null, error: baseError, isPreview: serveDrafts, cacheHint: {} };
}
if (!baseEntry) continue; // Try next locale in chain
// Preview tokens are item-scoped: verify the resolved entry matches.
// Edit mode (authenticated editors) has collection-wide draft access.
if (isPreviewMode && !isEditMode) {
const dbId = entryDatabaseId(baseEntry);
if (preview.id !== dbId && preview.id !== id) {
// Token doesn't match — serve only if publicly visible, without draft access
if (isVisible(baseEntry)) {
return successResult(wrapEntry(baseEntry), {
isPreview: false,
fallbackLocale,
cacheHint: cacheHint ?? {},
});
}
// Not visible — try next locale in fallback chain
continue;
}
}
// Check if entry has a draft revision — if so, re-fetch with revision data
const baseData = entryData(baseEntry);
const draftRevisionId = dataStr(baseData, "draftRevisionId") || undefined;
if (draftRevisionId) {
const { entry: draftEntry, error: draftError } = await getLiveEntry(COLLECTION_NAME, {
type,
id,
revisionId: draftRevisionId,
locale,
});
if (!draftError && draftEntry) {
return successResult(wrapEntry(draftEntry), {
isPreview: serveDrafts,
fallbackLocale,
cacheHint: cacheHint ?? {},
});
}
}
return successResult(wrapEntry(baseEntry), {
isPreview: serveDrafts,
fallbackLocale,
cacheHint: cacheHint ?? {},
});
}
// No entry found in any locale
return { entry: null, isPreview: serveDrafts, cacheHint: {} };
}
// Normal mode: try each locale in the fallback chain, only return published
// content. The full resolution (fallback chain + visibility + byline/term
// hydration) is wrapped in the distributed L2 cache, keyed by the requested
// locale. Preview/edit requests took the `serveDrafts` branch above and