@aglyn/tenant-runtime 1.0.0-beta.160 → 1.0.0-beta.161
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.
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@aglyn/tenant-runtime",
|
|
3
|
-
"version": "1.0.0-beta.
|
|
3
|
+
"version": "1.0.0-beta.161",
|
|
4
4
|
"license": "Apache-2.0",
|
|
5
5
|
"homepage": "https://aglyn.com",
|
|
6
6
|
"repository": {
|
|
@@ -25,8 +25,8 @@
|
|
|
25
25
|
"./package.json": "./package.json"
|
|
26
26
|
},
|
|
27
27
|
"dependencies": {
|
|
28
|
-
"@aglyn/aglyn": "1.0.0-beta.
|
|
29
|
-
"@aglyn/tenant-data-admin": "1.0.0-beta.
|
|
28
|
+
"@aglyn/aglyn": "1.0.0-beta.161",
|
|
29
|
+
"@aglyn/tenant-data-admin": "1.0.0-beta.161",
|
|
30
30
|
"@swc/helpers": "0.5.23"
|
|
31
31
|
},
|
|
32
32
|
"peerDependencies": {
|
|
@@ -174,6 +174,11 @@ export interface CollectionContent {
|
|
|
174
174
|
* which is what every collection published before the setting existed.
|
|
175
175
|
*/
|
|
176
176
|
schemaType?: string;
|
|
177
|
+
/**
|
|
178
|
+
* Whether this collection withholds its ENTRIES from search (AGL-3247).
|
|
179
|
+
* The listing and its category listings stay indexable either way.
|
|
180
|
+
*/
|
|
181
|
+
excludeEntriesFromSearch?: boolean;
|
|
177
182
|
/**
|
|
178
183
|
* Category taxonomy (AGL-582): entries reference these by stable
|
|
179
184
|
* `id`; `name` is the renameable display label.
|
|
@@ -138,6 +138,11 @@ import { PUBLISHED_SITE_DATA_TTL_SECONDS, tenantDataTag, withRenderCache } from
|
|
|
138
138
|
// does not define makes a consumer discard the whole node, costing the
|
|
139
139
|
// page every property it publishes rather than just this one.
|
|
140
140
|
schemaType: normalizeContentSchemaType(collectionDoc.get('schemaType')),
|
|
141
|
+
// "List the collection, not its entries" (AGL-3247). Carried as the
|
|
142
|
+
// STORED boolean rather than as the resolved answer: the render surface
|
|
143
|
+
// composes it with the site-level switch itself, and a pre-resolved flag
|
|
144
|
+
// here would be a second place that has to remember that switch exists.
|
|
145
|
+
excludeEntriesFromSearch: collectionDoc.get('excludeEntriesFromSearch') === true,
|
|
141
146
|
categories: mapCollectionCategories(collectionDoc.get('categories'))
|
|
142
147
|
};
|
|
143
148
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../libs/tenant/runtime/src/lib/get-collection-content.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n AUTHORS_MAX_PER_HOST,\n type CollectionCategory,\n collectionCategorySlug,\n checkEntitlement,\n COLLECTION_SOURCE_MAX,\n collectionTotalPages,\n type ContentAuthorRecord,\n entryMatchesCategoryRoute,\n hostCollectionKind,\n normalizeContentAuthor,\n normalizeContentSchemaType,\n resolveCollectionCategoryBySlug,\n resolveEntryAuthor,\n} from '@aglyn/aglyn/server'\nimport { firebaseAdmin, getOrgForHost } from '@aglyn/tenant-data-admin'\nimport {\n PUBLISHED_SITE_DATA_TTL_SECONDS,\n tenantDataTag,\n withRenderCache,\n} from '@aglyn/tenant-data-admin/render-cache'\n\n/**\n * ONE cached read per collection, shared by every surface that lists it\n * (AGL-1302).\n *\n * It began as the compose-time source only: a Collection entries block in a\n * shared layout re-read up to ~100 entry docs on EVERY page of the site. The\n * routed listing was left out on the argument that the page's own ISR entry\n * amortized it — which is true of ONE address and false of a collection,\n * because a collection is not one address. `/blog`, `/blog/page/2…10`, a\n * `/blog/category/{slug}` per category and `/blog/rss.xml` are all the same\n * data, each paying its own `1 + entries + authors` per window, beside a\n * cache already holding exactly that.\n *\n * The other half of that argument was real and is answered rather than\n * dropped: `flipDueEntry` is a write, and nothing else publishes a content\n * entry, so a cache that stored a collection with a schedule still pending\n * would suppress the render that publishes it. `getPublishedCollectionSource`\n * therefore declines to STORE exactly those collections — see its `store`\n * predicate — which leaves scheduled publishing on the render window it has\n * always been on, and puts everything else on this TTL.\n */\nconst COLLECTION_SOURCE_TTL_SECONDS = PUBLISHED_SITE_DATA_TTL_SECONDS\n\n/**\n * Resolve a public content-collection slug (AGL-954). Commerce's product\n * collections share `hosts/{hostId}/collections`, and a slug is only unique\n * within a kind — a bare `limit(1)` handed the URL to whichever doc Firestore\n * returned first, so a catalog collection could shadow a blog. Reads a small\n * window instead and takes the first content-kind match.\n */\nasync function findContentCollection(\n hostId: string,\n collectionSlug: string,\n): Promise<FirebaseFirestore.QueryDocumentSnapshot | undefined> {\n const matches = await firebaseAdmin\n .app()\n .firestore()\n .collection('hosts')\n .doc(hostId)\n .collection('collections')\n .where('slug', '==', collectionSlug)\n .limit(5)\n .get()\n return matches.docs.find(\n (docSnapshot) => hostCollectionKind(docSnapshot.data()) === 'content',\n )\n}\n\nexport interface CollectionEntrySummary {\n $id: string\n title: string\n slug: string\n excerpt?: string\n /**\n * The byline TEXT (AGL-686). Either the entry's own legacy free-typed\n * string or — since AGL-2486 — the name of the author record `authorId`\n * points at, resolved here so every downstream reader (the Entry Meta\n * block, `{{entry.author}}`, the RSS feed) keeps asking one field.\n */\n authorName?: string\n /** Reference into `hosts/{hostId}/authors` (AGL-2486). */\n authorId?: string\n /**\n * The resolved author RECORD (AGL-2486) — what `Article.author` is built\n * from. Null when the entry names no author, in which case the page falls\n * back to the site's publisher entity exactly as it always has.\n */\n author?: ContentAuthorRecord | null\n body?: string\n coverImage?: string\n /** `og:image:alt` for the cover (AGL-2417); travels WITH `coverImage`. */\n coverImageAlt?: string\n /**\n * The featured video (AGL-2956): a media reference or a URL, a Wistia link\n * included, in the shape `coverImage` is. See\n * `CollectionEntryRecord.coverVideo`.\n */\n coverVideo?: string\n /** Search-result title override (AGL-582); falls back to `title`. */\n seoTitle?: string\n /** Meta description override (AGL-582); falls back to `excerpt`. */\n seoDescription?: string\n /**\n * Stable reference into the collection's `categories` taxonomy\n * (AGL-582); resolved to a display name at render.\n */\n categoryId?: string\n /** Legacy free-typed bucket (AGL-582); read-only fallback. */\n category?: string\n /** Free-form labels (AGL-582). */\n tags?: string[]\n publishedAt?: { seconds: number } | null\n /**\n * Last edited, which is what `Article.dateModified` publishes (AGL-2534).\n *\n * Distinct from {@link publishedAt} on purpose: re-dating a post is not\n * editing it, so the console writes `publishedAt` alone when an author\n * backdates and this stays put. Google reads `dateModified` for freshness.\n */\n updatedAt?: { seconds: number } | null\n /**\n * The collection this entry came out of (AGL-2518), stamped only by a\n * reader that MIXES collections — the author page. Unset on every routed\n * listing, where the route already answers the question. See\n * `CollectionEntryRecord.collectionSlug`.\n */\n collectionSlug?: string\n /** The display name of {@link collectionSlug}. */\n collectionName?: string\n}\n\n/** Entry-doc fields shared by the list and single-entry mappers (AGL-582). */\nfunction mapEntryFields(\n value: FirebaseFirestore.DocumentData,\n): Pick<\n CollectionEntrySummary,\n | 'excerpt'\n | 'coverImage'\n | 'coverImageAlt'\n | 'coverVideo'\n | 'seoTitle'\n | 'seoDescription'\n | 'authorName'\n | 'authorId'\n | 'categoryId'\n | 'category'\n | 'tags'\n | 'updatedAt'\n> {\n return {\n excerpt: value['excerpt'] ?? '',\n // The byline was DECLARED on `CollectionEntrySummary` (AGL-686) and\n // mapped by nobody, so `entry.authorName` was `undefined` on every entry\n // this loader returned — which is every routed entry page and every\n // Collection entries block. The console collected the field, the rules\n // stored it, the JSON-LD builder read it and the Entry Meta block printed\n // it, and all three saw nothing, because the one hop between Firestore\n // and them dropped it (AGL-2486). Written but never read, in the\n // direction that leaves no error behind.\n authorName: value['authorName'] ?? '',\n authorId: value['authorId'] ?? '',\n coverImage: value['coverImage'] ?? '',\n coverImageAlt: value['coverImageAlt'] ?? '',\n // Here, where both read paths pick it up, so a list card and the routed\n // entry page can each bind the featured video (AGL-2956).\n coverVideo: value['coverVideo'] ?? '',\n seoTitle: value['seoTitle'] ?? '',\n seoDescription: value['seoDescription'] ?? '',\n categoryId: value['categoryId'] ?? '',\n category: value['category'] ?? '',\n tags: Array.isArray(value['tags'])\n ? value['tags'].filter((tag): tag is string => typeof tag === 'string')\n : [],\n /*\n `dateModified`'s source (AGL-2534), and it was missing for the same\n reason `authorName` was — the reason this function's own comment above\n describes.\n\n The console has written `updatedAt` on every save, `page.tsx` reads\n `entry.updatedAt.seconds` to publish `Article.dateModified`, a spec\n asserts the conversion, and two console comments explain why it must not\n track `publishedAt`. Nothing mapped it, so `entry.updatedAt` was\n `undefined` on every entry the loader has ever returned and no published\n article has ever carried a `dateModified` — the freshness signal Google\n reads. The spec passed throughout because it builds its entry object by\n hand and never crosses this boundary.\n\n Mapped HERE rather than beside `publishedAt` at the two call sites: this\n is an ordinary field with no `publishAt` fallback and nothing sorts on\n it, so one place is enough — and one place is what stops the next read\n path from forgetting it.\n */\n updatedAt: value['updatedAt']?.seconds\n ? { seconds: value['updatedAt'].seconds }\n : null,\n }\n}\n\n/**\n * The collection doc's category taxonomy (AGL-582), sanitized: only\n * `{ id, name }` pairs with non-empty strings survive, order preserved.\n *\n * `description` rides along when the author wrote one and is dropped when it\n * is blank or not a string, so the head can tell \"described\" from \"not\n * described\" by truthiness alone — an empty string reaching the metadata\n * would suppress the template screen's description and leave the listing with\n * none at all.\n */\nfunction mapCollectionCategories(value: unknown): CollectionCategory[] {\n if (!Array.isArray(value)) return []\n return value\n .filter(\n (item): item is CollectionCategory =>\n typeof item?.id === 'string' &&\n item.id.trim() !== '' &&\n typeof item?.name === 'string' &&\n item.name.trim() !== '',\n )\n .map((item) => {\n const description =\n typeof item.description === 'string' ? item.description.trim() : ''\n return {\n id: item.id,\n name: item.name,\n ...(description ? { description } : {}),\n }\n })\n}\n\n/**\n * The routed view of a collection DOCUMENT (AGL-551): its name and the\n * template screens its list and entry routes render through.\n *\n * `slug` is the slug that was ASKED FOR rather than the one stored, which is\n * what every caller of this file has always returned — a listing has to build\n * its own URLs out of the segment the reader is standing on.\n */\nfunction mapCollectionDoc(\n collectionDoc: FirebaseFirestore.QueryDocumentSnapshot,\n collectionSlug: string,\n): CollectionContent['collection'] {\n return {\n $id: collectionDoc.id,\n displayName: collectionDoc.get('displayName') ?? collectionSlug,\n slug: collectionSlug,\n templateScreenId: collectionDoc.get('templateScreenId') ?? undefined,\n listScreenId: collectionDoc.get('listScreenId') ?? undefined,\n entryScreenId: collectionDoc.get('entryScreenId') ?? undefined,\n // Normalized HERE rather than at the head (AGL-2536), so an unrecognised\n // stored value can never reach the JSON-LD: an `@type` the vocabulary\n // does not define makes a consumer discard the whole node, costing the\n // page every property it publishes rather than just this one.\n schemaType: normalizeContentSchemaType(collectionDoc.get('schemaType')),\n categories: mapCollectionCategories(collectionDoc.get('categories')),\n }\n}\n\n/**\n * Resolve the author RECORDS a set of entries reference (AGL-2486).\n *\n * Costs ZERO reads when no entry names an `authorId`, which is every site\n * that has not adopted custom authors and every entry written before them —\n * the check is on the ids already in hand, not a probe of the collection. When\n * ids are present it is one `getAll` of the DISTINCT ones, bounded by\n * {@link AUTHORS_MAX_PER_HOST} and by the ≤100-entry page above it, rather\n * than a read per entry.\n *\n * Fail-open, like every other read in this file: an authors read that throws\n * leaves the entries with their legacy `authorName` (or the site entity) and\n * the page renders. A byline is not worth a 500.\n */\nasync function attachEntryAuthors(\n hostId: string,\n entries: CollectionEntrySummary[],\n): Promise<void> {\n const ids = [\n ...new Set(\n entries\n .map((entry) => (entry.authorId ?? '').trim())\n .filter(Boolean),\n ),\n ].slice(0, AUTHORS_MAX_PER_HOST)\n let authors: ContentAuthorRecord[] = []\n if (ids.length) {\n try {\n const authorsRef = firebaseAdmin\n .app()\n .firestore()\n .collection('hosts')\n .doc(hostId)\n .collection('authors')\n const snapshots = await firebaseAdmin\n .app()\n .firestore()\n .getAll(...ids.map((id) => authorsRef.doc(id)))\n authors = snapshots\n .map((snapshot) =>\n snapshot.exists\n ? normalizeContentAuthor(snapshot.data(), snapshot.id)\n : null,\n )\n .filter((author): author is ContentAuthorRecord => Boolean(author))\n } catch (error) {\n console.error(error)\n }\n }\n for (const entry of entries) {\n const author = resolveEntryAuthor(entry, authors)\n entry.author = author\n // The byline TEXT is denormalized onto the field everything downstream\n // already reads, so a record-backed author needs no change in the Entry\n // Meta block, the token map, the fallback nodes or the RSS feed. A record\n // WINS over the legacy string on the same entry: picking an author is the\n // more recent statement of who wrote it.\n if (author?.name) entry.authorName = author.name\n }\n}\n\n/**\n * Terminal refusal marker for an entry schedule, the flat-status twin of\n * `publishSchedule.status: 'skipped-unentitled'` on screens (AGL-1185).\n *\n * A field rather than a new `status` value on purpose. `status` is queried\n * (`where('status', 'in', [...])`), rendered by the console, and sorted on by\n * `bundle-timestamps.ts`; adding a member would have meant auditing every one\n * of those readers. A sibling field is invisible to all of them and is read\n * only here.\n */\nconst ENTRY_SCHEDULE_SKIPPED = 'skipped-unentitled'\n\n/** A schedule this entry already had declined, and will not have reconsidered. */\nfunction scheduleAlreadyRefused(\n value: FirebaseFirestore.DocumentData,\n): boolean {\n return value['scheduleStatus'] === ENTRY_SCHEDULE_SKIPPED\n}\n\n/** A scheduled entry whose time has come — before any plan question. */\nexport function isDueScheduled(value: FirebaseFirestore.DocumentData): boolean {\n return (\n value['status'] === 'scheduled' &&\n !scheduleAlreadyRefused(value) &&\n (value['publishAt']?.seconds ?? Number.POSITIVE_INFINITY) * 1000 <=\n Date.now()\n )\n}\n\n/**\n * A scheduled entry still waiting on its time: not due yet, and not refused.\n * Nothing but a render publishes a content entry, so a cache that stored a\n * read holding one would withhold the render that notices it come due — see\n * {@link LiveEntriesRead.pendingSchedule}.\n */\nexport function isPendingScheduled(\n value: FirebaseFirestore.DocumentData,\n): boolean {\n return (\n value['status'] === 'scheduled' &&\n !scheduleAlreadyRefused(value) &&\n !isDueScheduled(value)\n )\n}\n\n/**\n * Is this host's plan allowed to publish on a schedule? (AGL-471 shape.)\n *\n * `React.cache`-deduped per request via `getOrgForHost`, and — this is the\n * part that keeps it off the hot path — every caller below only asks once it\n * has already found a due scheduled entry. A collection with nothing due pays\n * nothing, which is almost every render.\n *\n * THREE answers, not two, and the third is the point. `refused` means we read\n * the plan and it does not carry the entitlement. `unresolved` means we could\n * not find out. Both withhold the entry, but only `refused` may write the\n * terminal marker — burning a schedule permanently on the strength of a\n * hostIndex miss or a transient rejection would destroy a customer's post for\n * a reason that may not be true a second later.\n *\n * Withholding on `unresolved` rather than publishing is what every other\n * entitlement caller on the tenant runtime already does: `apply-publish-schedule`\n * here, and the automation engine's two runners, all pass a possibly\n * undefined org straight into `checkEntitlement`, which resolves a missing\n * plan as free and denies (AGL-247). Opening here instead would make this the\n * one gate in the lib that admits when it cannot see — the exact shape of the\n * free-tier leak `no-plan-gated-entitlement` exists to forbid.\n *\n * The blast radius of withholding is deliberately small: `isLive` answers true\n * for `status: 'published'` before it ever consults this, so an unresolved\n * read hides only the due-scheduled entry, never the published ones, and the\n * next render retries.\n */\nexport type SchedulePermission = 'allowed' | 'refused' | 'unresolved'\n\nexport async function scheduledPublishingPermission(\n hostId: string,\n): Promise<SchedulePermission> {\n try {\n const org = (await getOrgForHost(hostId))?.org\n if (!org) return 'unresolved'\n return checkEntitlement(org, 'scheduledPublishing') ? 'allowed' : 'refused'\n } catch (error) {\n // Caught rather than thrown: the only caller sits inside\n // `getCollectionContent`'s try/catch, which returns an EMPTY collection —\n // so an unhandled rejection here would blank every published entry on the\n // page, not just the scheduled one.\n console.error(error)\n return 'unresolved'\n }\n}\n\n/**\n * Scheduled entries (AGL-123) go live lazily like AGL-61: a due\n * `publishAt` counts as published for this render, and the doc is flipped\n * to `published` fail-open so the state becomes durable.\n *\n * PLAN GATE (AGL-471). `scheduledPublishing` is a Business entitlement, and\n * until now nothing on the entry path checked it: the console let any plan\n * write `status: 'scheduled'`, and this render path published it. Scheduling\n * worked end to end on Free. The screens path has gated this since AGL-471\n * and records its refusal since AGL-1185 — entries were simply never wired\n * to either, which is why the leak was invisible from the screens side.\n *\n * The permission is threaded in rather than resolved here so the org read\n * happens once per call site instead of once per entry.\n *\n * Exported for the one other reader that decides whether an entry is on the\n * site — whether a LINK to it resolves (AGL-3118) — so a link and the page it\n * points at can never disagree about which entries exist.\n */\nexport function isLive(\n value: FirebaseFirestore.DocumentData,\n permission: SchedulePermission,\n): boolean {\n if (value['status'] === 'published') return true\n return permission === 'allowed' && isDueScheduled(value)\n}\n\n/**\n * Make the due state durable — or record that it was refused.\n *\n * The refusal is TERMINAL, for the AGL-1185 reason: left as a bare pending\n * `scheduled`, the entry stays permanently due, so the day the org upgrades\n * to Business the next render publishes it. Content scheduled on a plan that\n * could not honour it, and forgotten, surfacing during an upgrade — exactly\n * when nobody is looking for it. Recording the refusal is what makes it stop\n * being due, and it also stops this path re-reading the org on every\n * subsequent render.\n *\n * Both writes fail open: an error leaves today's state, and the next render\n * retries.\n */\nfunction flipDueEntry(\n docRef: FirebaseFirestore.DocumentReference,\n value: FirebaseFirestore.DocumentData,\n permission: SchedulePermission,\n): void {\n if (value['status'] !== 'scheduled') return\n if (scheduleAlreadyRefused(value)) return\n // `unresolved` writes NOTHING. It withholds this render and leaves the\n // schedule exactly as it found it, so a later render can still publish it.\n if (permission === 'unresolved') return\n if (permission === 'refused') {\n if (!isDueScheduled(value)) return\n docRef\n .update({ scheduleStatus: ENTRY_SCHEDULE_SKIPPED })\n .catch((error) => console.error(error))\n return\n }\n docRef\n .update({ status: 'published', publishedAt: value['publishAt'] })\n .catch((error) => console.error(error))\n}\n\nexport interface CollectionContent {\n /**\n * The zone this site's dates read in (AGL-3237), carried on the CONTENT so\n * it reaches the client.\n *\n * `collection-fallback.tsx` renders through `next/dynamic` from\n * `catch-all-client`, so it formats dates in the browser as well as on the\n * server. A zone it read from its own runtime would be the visitor's, which\n * is precisely the hydration mismatch AGL-1926 fixed — so the server\n * decides it once and it travels here, in the props both renders read.\n */\n timeZone?: string\n collection: {\n $id: string\n displayName: string\n slug: string\n /**\n * Legacy entry-template screen (AGL-105); superseded by\n * `entryScreenId` but still honored when only it is set.\n */\n templateScreenId?: string\n /** List-template screen (AGL-551); `/{collection}` renders through it. */\n listScreenId?: string\n /**\n * Entry-template screen (AGL-551); `/{collection}/{entry}` renders\n * through it with `{{entry.*}}` tokens.\n */\n entryScreenId?: string\n /**\n * What KIND of article this collection publishes (AGL-2536) — the\n * `schema.org` type its entries serialise as. Unset publishes `Article`,\n * which is what every collection published before the setting existed.\n */\n schemaType?: string\n /**\n * Category taxonomy (AGL-582): entries reference these by stable\n * `id`; `name` is the renameable display label.\n */\n categories?: CollectionCategory[]\n } | null\n entries: CollectionEntrySummary[]\n entry: CollectionEntrySummary | null\n /**\n * Whether the read that produced `entries` stopped at\n * {@link COLLECTION_SOURCE_MAX} (AGL-1516). Set on LIST routes only —\n * an entry route reads one document by slug and bounds nothing.\n */\n entriesReachedBound?: boolean\n /**\n * Present ONLY when a verified preview grant revealed an entry the public\n * site withholds (AGL-3205) — never on a public render, and never for an\n * entry that is already live. Its absence is what the preview chrome reads\n * to say \"this one is actually published\", so it must not be set\n * defensively.\n */\n entryPreview?: {\n /** The stored `status` — `scheduled` or `draft`. */\n status: string\n /** The instant it is scheduled for, or null when nothing is scheduled. */\n publishAtSeconds: number | null\n }\n /** List pagination (AGL-620); null for entry pages or unpaginated lists. */\n pagination?: CollectionPagination | null\n /**\n * The category this listing is filtered to (AGL-1321); null on the\n * canonical unfiltered list and on entry pages.\n */\n category?: CollectionRouteCategory | null\n error: unknown\n}\n\n/** The category a `/{collection}/category/{slug}` route addresses (AGL-1321). */\nexport interface CollectionRouteCategory {\n /** The URL segment, normalized — what the canonical link must say. */\n slug: string\n /** Taxonomy id; absent when the segment matched no known category. */\n id?: string\n /** Display label; falls back to the raw segment for an unknown category. */\n name: string\n /**\n * The taxonomy's {@link CollectionCategory.description}, carried onto the\n * route so the head can describe the FILTERED listing rather than inherit\n * the whole collection's description. Absent for an unknown segment, which\n * names no category and therefore has nothing to describe.\n */\n description?: string\n /**\n * Whether the segment resolved against the collection's taxonomy. An\n * unknown category still renders — an empty listing, not a crash — but the\n * page must not invite indexing of a URL that names nothing.\n */\n known: boolean\n}\n\nexport interface CollectionPagination {\n /**\n * 1-based counter for display only (AGL-3219).\n *\n * It is what `{{pagination.page}}` renders and nothing reads it back: a\n * cursor page is addressed by the document it starts after, so this number\n * describes how far a reader has walked rather than where the read began.\n * Hand-edit it in a URL and the label is wrong; the entries are not.\n */\n page: number\n perPage: number\n /**\n * The document id the NEXT (older) page starts after, or `''` when this is\n * the last page (AGL-3219).\n *\n * Set from a `limit(perPage + 1)` probe: the extra row is the only evidence\n * needed that an older page exists, and it costs one document rather than\n * the `count()` aggregation a total used to need. It is also the only\n * honest answer available — see {@link CollectionPagination.totalPages}.\n */\n nextCursor: string\n /** The document id the PREVIOUS (newer) page starts before, or `''`. */\n prevCursor: string\n /**\n * How many pages there are.\n *\n * @deprecated AGL-3219. Still resolved, so a template binding\n * `{{pagination.totalPages}}` keeps rendering, but no longer a promise: a\n * total can only be stated for a collection that fits inside one read, and\n * past that it is absent rather than wrong. It used to be derived from a\n * `count()` over a set the listing's two reads disagreed about, which is\n * how the page 10/11 seam came to repeat an entry. Bind\n * {@link CollectionPagination.nextCursor} instead — `''` means there is\n * nothing older, which is the question a pager is actually asking.\n */\n totalPages?: number\n /** @deprecated AGL-3219, with {@link CollectionPagination.totalPages}. */\n totalEntries?: number\n /**\n * Where `entries` begins in the collection's own order (AGL-3213): 0 for a\n * listing served from the cached read, and the page's own offset for one\n * served by a window read past that read's bound.\n *\n * Both windowing sites subtract it — `collectionEntriesPageWindow` on the\n * way into props, and the Collection entries block on the way into compose.\n * Without it a windowed listing renders empty, because every one of them\n * slices `[(page - 1) * perPage, …)` on the premise that `entries` starts at\n * the beginning of the collection.\n */\n windowStart?: number\n}\n\n/**\n * A bounded read of a collection's live entries (AGL-1516).\n *\n * `reachedBound` is a fact about the QUERY, not about `entries`, and the two\n * genuinely differ: the query asks for `status in ['published', 'scheduled']`\n * and the filter below then drops everything not live yet, so a read that came\n * back holding all {@link COLLECTION_SOURCE_MAX} docs can hand back fewer.\n * Counting the survivors — which is all a downstream consumer can do — reads\n * that as a complete collection, and the one thing a truncated read must never\n * be allowed to claim is completeness.\n */\ninterface LiveEntriesRead {\n entries: CollectionEntrySummary[]\n /** The query came back holding its own `.limit()`. */\n reachedBound: boolean\n /**\n * The read saw a `scheduled` entry whose `publishAt` has NOT arrived and\n * which has not been terminally refused — a schedule this collection is\n * still waiting on.\n *\n * Nothing promotes a content entry on a beat: `publish-schedule-job.ts` is\n * screens-only, so `isLive`/`flipDueEntry` running during a render is the\n * entire mechanism. A cached source therefore does not merely serve stale\n * entries, it withholds the render that would have published one, for as\n * long as the entry stays cached. This is what lets the cache decline to\n * store exactly those collections, so a schedule keeps landing on the\n * render window rather than on the TTL.\n */\n pendingSchedule: boolean\n}\n\n/**\n * The fields a LISTING read of an entry needs — the field mask on the query\n * below (AGL-3213).\n *\n * The point of the mask is the field that is NOT in it. `body` is the whole\n * post, and `mapEntryFields` has never mapped it on this path: a list card\n * binds a title, an excerpt, a cover and a byline, and the routed entry page\n * reads its one document separately. So the markdown of up to\n * {@link COLLECTION_SOURCE_MAX} posts crossed the wire, was parsed out of the\n * response, and was dropped one function later — on every fill of a cache\n * that every listing address, every \"Latest posts\" rail, the feed and the\n * author page share. A changelog is the worst case and also the common one.\n *\n * Firestore bills the document read either way, so this buys no reads; it\n * buys egress and the JSON parse, which is the part of a collection render\n * that grows with how much people have written.\n *\n * Site search is unaffected and must stay that way: it matches on `body`\n * through its OWN query in `apps/tenant/utils/search-content.ts`, which this\n * mask does not touch.\n *\n * ⛔ A reader added to `mapEntryFields` or to the liveness/schedule helpers\n * must be added HERE in the same edit. A field left out does not error — it\n * arrives `undefined`, which is exactly how `authorName` and `updatedAt` went\n * missing for months (AGL-2486, AGL-2534). The four schedule fields are\n * listed first for that reason: `status`, `publishAt` and `scheduleStatus`\n * decide whether an entry is live at all, and `flipDueEntry` WRITES\n * `publishAt` back as `publishedAt`, so a mask that dropped it would publish\n * a due entry with no date.\n */\nconst LIVE_ENTRY_FIELDS = [\n 'status',\n 'publishAt',\n 'publishedAt',\n 'scheduleStatus',\n 'title',\n 'slug',\n 'excerpt',\n 'authorName',\n 'authorId',\n 'coverImage',\n 'coverImageAlt',\n 'coverVideo',\n 'seoTitle',\n 'seoDescription',\n 'categoryId',\n 'category',\n 'tags',\n 'updatedAt',\n] as const\n\n/**\n * Most SCHEDULED entries one live read considers (AGL-3213).\n *\n * Read by its own query rather than taken from the dated page below, because\n * a schedule is invisible to that page: scheduling writes `publishAt` and\n * never `publishedAt`, and `flipDueEntry` during a render is the only thing\n * that publishes one. A schedule the read misses is a post that never goes\n * out. The set is small by nature — a hundred pending schedules on one\n * collection is already an unusual editorial calendar.\n */\nconst SCHEDULED_SOURCE_MAX = 100\n\n/** Everything a public listing may show, before any ordering. */\nfunction liveEntriesBase(\n entriesRef: FirebaseFirestore.CollectionReference,\n): FirebaseFirestore.Query {\n return (\n entriesRef\n .where('status', 'in', ['published', 'scheduled'])\n // Everything this path reads, and nothing else (AGL-3213) — see\n // {@link LIVE_ENTRY_FIELDS}.\n .select(...LIVE_ENTRY_FIELDS)\n )\n}\n\n/**\n * The documents a live read considers, in the order the site shows them\n * (AGL-3213).\n *\n * ## Why this is ordered now, and why ordering alone would have broken it\n *\n * It was `where(status).limit(100)` with NO `orderBy`, sorted in memory\n * afterwards. That is not the newest hundred — it is a hundred documents in\n * NAME order, then sorted. Under the bound the two agree, because a hundred\n * out of a hundred is everything; past it they diverge completely. This site's\n * own changelog reached 166 live entries and its listing showed an arbitrary\n * hundred of them, chosen by document id, with 66 releases reachable only at\n * their own URLs.\n *\n * The comment that used to sit here was right about `orderBy`, though:\n * Firestore returns only documents that HAVE the ordered field, so a dated\n * read does not mis-sort an entry without a date — it hides it. Two of those\n * exist and both matter:\n *\n * A SCHEDULE carries `publishAt` and no `publishedAt` until it goes out.\n * Ordering alone would have stopped scheduled posts publishing\n * at all, silently, because nothing else publishes them.\n * AN IMPORT restores whatever the bundle carried, and\n * `/api/hosts/resources` validates no field for presence\n * either — so a published entry with no `publishedAt` exists.\n *\n * So it is three queries, in the shape the console's sorted window uses\n * (AGL-2853): the DATED page, every SCHEDULE, and — only when the dated page\n * came back SHORT, which is the server's own proof that the collection fits\n * inside the bound — a scan for live entries carrying no date. Past the bound\n * an undated entry sorts after every dated one by definition, so it belongs to\n * the tail pages, which are served by their own window read.\n */\nasync function readLiveEntryDocs(\n entriesRef: FirebaseFirestore.CollectionReference,\n): Promise<{\n docs: FirebaseFirestore.QueryDocumentSnapshot[]\n reachedBound: boolean\n}> {\n try {\n const dated = await liveEntriesBase(entriesRef)\n .orderBy('publishedAt', 'desc')\n // The document name breaks ties, so two entries published in the same\n // second cannot swap places between two reads and move a page boundary\n // under a reader. Descending to match the date: a composite index ends\n // with `__name__` in the last field's direction, which makes this the\n // `(status, publishedAt DESC)` index the console's table already needs.\n .orderBy('__name__', 'desc')\n // Named rather than literal (AGL-1516): a search index has to be able to\n // say \"this read reached its bound\", and it can only do that against a\n // bound it shares with the query. `collectionSourceReachedBound` reads\n // the same constant.\n .limit(COLLECTION_SOURCE_MAX)\n .get()\n\n const scheduled = await entriesRef\n .where('status', '==', 'scheduled')\n .select(...LIVE_ENTRY_FIELDS)\n .limit(SCHEDULED_SOURCE_MAX)\n .get()\n\n /*\n * EITHER read stopping at its own limit means entries went unseen.\n *\n * The dated page is the usual one. The schedule page is the case a dated\n * read alone cannot even detect: a collection holding nothing but pending\n * schedules returns ZERO dated documents, so a bound measured only there\n * would report a complete read of an empty collection — and \"nothing is\n * live here\" is the claim that takes a listing off the site (AGL-3101).\n */\n const reachedBound =\n dated.docs.length >= COLLECTION_SOURCE_MAX ||\n scheduled.docs.length >= SCHEDULED_SOURCE_MAX\n\n const undated = reachedBound\n ? []\n : (\n await liveEntriesBase(entriesRef)\n .orderBy('__name__')\n .limit(COLLECTION_SOURCE_MAX)\n .get()\n ).docs.filter((entryDoc) => !entryDoc.get('publishedAt'))\n\n const seen = new Set<string>()\n const docs: FirebaseFirestore.QueryDocumentSnapshot[] = []\n for (const entryDoc of [...dated.docs, ...scheduled.docs, ...undated]) {\n if (seen.has(entryDoc.id)) continue\n seen.add(entryDoc.id)\n docs.push(entryDoc)\n }\n return { docs, reachedBound }\n } catch (error) {\n /*\n * FAIL SOFT TO THE UNORDERED READ.\n *\n * The ordered query needs the `(status, publishedAt DESC)` composite\n * index. Indexes do NOT ship with a promotion — RELEASING.md deploys them\n * by hand afterwards — so the window between the code landing and the\n * index existing has to degrade rather than break. An arbitrary hundred\n * is a bad listing; a 500 is a customer's blog down.\n */\n console.error(error)\n const unordered = await liveEntriesBase(entriesRef)\n .limit(COLLECTION_SOURCE_MAX)\n .get()\n return {\n docs: unordered.docs,\n reachedBound: unordered.docs.length >= COLLECTION_SOURCE_MAX,\n }\n }\n}\n\n/** The live entries among `docs`, newest first, publishing any that came due. */\nfunction toLiveEntries(\n docs: readonly FirebaseFirestore.QueryDocumentSnapshot[],\n permission: SchedulePermission,\n): CollectionEntrySummary[] {\n return (\n docs\n .filter((entryDoc) => isLive(entryDoc.data(), permission))\n .map((entryDoc) => {\n const value = entryDoc.data()\n flipDueEntry(entryDoc.ref, value, permission)\n return {\n $id: entryDoc.id,\n title: value['title'] ?? entryDoc.id,\n slug: value['slug'] ?? entryDoc.id,\n ...mapEntryFields(value),\n publishedAt: (value['publishedAt'] ?? value['publishAt'])\n ? {\n seconds: (value['publishedAt'] ?? value['publishAt']).seconds,\n }\n : null,\n }\n })\n // An entry carrying no date at all sorts last rather than to 1970 —\n // the same place the query's own order puts it.\n .sort(\n (a, b) => (b.publishedAt?.seconds ?? 0) - (a.publishedAt?.seconds ?? 0),\n )\n )\n}\n\n/**\n * Fetches a collection's live entries (newest first), shared by the route\n * loader and the compose-time Collection entries block (AGL-551).\n */\nasync function listLiveEntries(\n entriesRef: FirebaseFirestore.CollectionReference,\n hostId: string,\n): Promise<LiveEntriesRead> {\n const { docs, reachedBound } = await readLiveEntryDocs(entriesRef)\n\n // Ask the plan question ONLY if something is actually due (AGL-471). A\n // collection with no due schedule — almost every render — never reads the\n // org at all.\n const due = docs.filter((entryDoc) => isDueScheduled(entryDoc.data()))\n const permission: SchedulePermission = due.length\n ? await scheduledPublishingPermission(hostId)\n : 'allowed'\n\n // Record the terminal refusal on its own pass, because a refused entry is\n // NOT live and so never reaches the `flipDueEntry` inside the map below.\n // Without this the entry stays due forever: excluded from every render, and\n // re-reading the org on each one.\n if (permission !== 'allowed') {\n for (const entryDoc of due) {\n flipDueEntry(entryDoc.ref, entryDoc.data(), permission)\n }\n }\n\n // Measured on the RAW docs, before the liveness filter (AGL-1516): a\n // not-yet-due entry is filtered out one line down, so this is the last\n // place that can see one at all.\n const pendingSchedule = docs.some((entryDoc) =>\n isPendingScheduled(entryDoc.data()),\n )\n\n const entries = toLiveEntries(docs, permission)\n\n return {\n entries,\n reachedBound,\n pendingSchedule,\n }\n}\n\n/** One page of a listing, and whether anything older follows it. */\ninterface CollectionListingPage {\n entries: CollectionEntrySummary[]\n /** The `limit(perPage + 1)` probe found an extra row. */\n hasMore: boolean\n}\n\n/**\n * One page of a listing that starts PAST the cached read (AGL-3213),\n * addressed by the document it continues from rather than by a position\n * (AGL-3219).\n *\n * Uncached on purpose, and it is the only read on the collection path that is.\n * The cached source exists because `/blog`, every listing address, the feed\n * and every \"Latest posts\" rail want the same first hundred entries\n * (AGL-1302); a page past that bound wants ten entries nobody else is asking\n * for, and its own ISR entry is already the cache for them.\n *\n * ## Why a cursor, and not the offset this replaces\n *\n * `.offset(n)` asks for a POSITION, and a listing takes its inserts at the\n * head, so every publish moves every position by one. The head pages and this\n * read are cached under different policies and revalidated by different\n * triggers — the publish fan-out refreshes the head eagerly and deliberately\n * stops there — so the two sides were routinely describing the collection as\n * it stood at two different moments, and the seam between them repeated an\n * entry or hid one for as long as the slower side lagged. `v1.0.0-beta.147`\n * shipped and `/changelog` showed `v1-0-0-beta-36` as both the last entry of\n * page 10 and the first of page 11.\n *\n * `startAfter(doc)` asks a question whose answer does not move: what follows\n * THIS entry. Publish a hundred entries at the head and this page returns the\n * same ten. The seam cannot drift because there is no longer a number on\n * either side of it to disagree about.\n *\n * `offset` also billed every document it skipped; a cursor bills none of them.\n */\nasync function readCollectionListingPage(options: {\n hostId: string\n collectionSlug: string\n /** Start after this document id — the older direction. */\n after?: string\n /** Start before this document id — the newer direction. */\n before?: string\n limit: number\n}): Promise<CollectionListingPage | null> {\n try {\n const collectionDoc = await findContentCollection(\n options.hostId,\n options.collectionSlug,\n )\n if (!collectionDoc) return null\n const entriesRef = collectionDoc.ref.collection('entries')\n\n const cursorId = options.before || options.after\n if (!cursorId) return null\n // A direct get, not a `where('slug', ...)` query: the cursor IS the\n // document name, which is the second field the read orders on, so the\n // snapshot it needs is one document rather than an index lookup.\n const cursorDoc = await entriesRef.doc(cursorId).get()\n // A cursor naming a document that no longer exists — deleted, or a URL\n // someone kept — cannot be positioned against. Null sends the caller back\n // to the cached head, which is a page the reader can act on.\n if (!cursorDoc.exists) return null\n\n // Backwards is the same query read the other way up, so both directions\n // rest on an index the project already deploys: `(status, publishedAt)`\n // exists ascending and descending both.\n const backwards = Boolean(options.before)\n const snapshot = await liveEntriesBase(entriesRef)\n .orderBy('publishedAt', backwards ? 'asc' : 'desc')\n .orderBy('__name__', backwards ? 'asc' : 'desc')\n .startAfter(cursorDoc)\n // One more than the page: the extra row is the whole of \"is there\n // another page\", and it replaces a `count()` over the collection.\n .limit(options.limit + 1)\n .get()\n\n const hasMore = snapshot.docs.length > options.limit\n const pageDocs = snapshot.docs.slice(0, options.limit)\n // Read backwards, the newest of the page came back last.\n const docs = backwards ? [...pageDocs].reverse() : pageDocs\n\n const due = docs.filter((entryDoc) => isDueScheduled(entryDoc.data()))\n const permission: SchedulePermission = due.length\n ? await scheduledPublishingPermission(options.hostId)\n : 'allowed'\n if (permission !== 'allowed') {\n for (const entryDoc of due) {\n flipDueEntry(entryDoc.ref, entryDoc.data(), permission)\n }\n }\n const entries = toLiveEntries(docs, permission)\n // The byline reads `authorName`, which a record-backed author only has\n // once resolved — the cached source does this for the entries it holds,\n // and a windowed page holds entries it never saw (AGL-2486).\n await attachEntryAuthors(options.hostId, entries)\n return { entries, hasMore }\n } catch (error) {\n // Fail open to the cached head rather than to a 500: the caller keeps\n // whatever it already had, which is a page the reader has seen before\n // rather than an error they cannot get past.\n console.error(error)\n return null\n }\n}\n\n/**\n * The cursor a retired `/{collection}/page/{n}` address redirects onto\n * (AGL-3219).\n *\n * This is the ONE place a position is still resolved, and it is deliberately\n * the only one: a 301 is served once, the reader lands on an address that\n * cannot drift afterwards, and whatever the position meant at that instant is\n * the page they would have got anyway. Everything downstream is cursors.\n *\n * Keys only — `select()` with no fields asks Firestore for document names and\n * nothing else — so the skipped documents are billed at the cheapest rate the\n * offset can be had for. Returns `''` when the position is past the end,\n * which is a 404 rather than a redirect to nowhere.\n */\nexport async function resolveCollectionPageCursor(options: {\n hostId: string\n collectionSlug: string\n /** 1-based page whose PREVIOUS entry is the cursor. */\n page: number\n perPage: number\n}): Promise<string> {\n const skip = (options.page - 1) * options.perPage - 1\n if (!Number.isFinite(skip) || skip < 0) return ''\n try {\n const collectionDoc = await findContentCollection(\n options.hostId,\n options.collectionSlug,\n )\n if (!collectionDoc) return ''\n const snapshot = await collectionDoc.ref\n .collection('entries')\n .where('status', 'in', ['published', 'scheduled'])\n .select()\n .orderBy('publishedAt', 'desc')\n .orderBy('__name__', 'desc')\n .offset(skip)\n .limit(1)\n .get()\n return snapshot.docs[0]?.id ?? ''\n } catch (error) {\n console.error(error)\n return ''\n }\n}\n\n/** Compose-time view of a collection: its live entries and its taxonomy. */\nexport interface PublishedCollectionSource {\n /**\n * The collection DOCUMENT this source was read from — its display name and\n * its template screen ids — or null when the slug names no content\n * collection.\n *\n * Carried so a routed listing can be served ENTIRELY from this cached\n * source. `getCollectionContent` used to resolve the same document itself\n * and then read the same entries again uncached, which meant `/blog`,\n * every `/blog/page/{n}`, every `/blog/category/{slug}` and the RSS feed\n * each paid a full collection read per regeneration while the identical\n * data already sat in this cache for every OTHER page on the site.\n */\n collection: CollectionContent['collection']\n entries: CollectionEntrySummary[]\n categories: CollectionCategory[]\n /**\n * Whether the read saw a schedule it is still waiting on — see\n * {@link LiveEntriesRead.pendingSchedule}. Never stored, only consulted by\n * the cache above, so no consumer has to know about it.\n */\n pendingSchedule?: boolean\n /**\n * Whether the entries read stopped at {@link COLLECTION_SOURCE_MAX}\n * (AGL-1516) — carried out of the loader because `entries.length` cannot\n * answer it once the liveness filter has run. Fail-open paths report\n * `false`: an empty result is not a bounded read, and describing it as one\n * would tell a reader their search covered less than it did.\n */\n reachedBound: boolean\n}\n\n/**\n * Published entries + category taxonomy for a collection resolved by slug —\n * the data source of the Collection entries block on arbitrary screens\n * (AGL-551/582). Fail-open: errors and unknown slugs resolve to an empty\n * list so a renamed collection never takes a published screen down.\n */\nexport async function getPublishedCollectionSource(options: {\n hostId: string\n collectionSlug: string\n}): Promise<PublishedCollectionSource> {\n try {\n return await withRenderCache({\n key: [\n 'tenant-collection-source',\n options.hostId,\n options.collectionSlug,\n ],\n revalidate: COLLECTION_SOURCE_TTL_SECONDS,\n tags: [tenantDataTag(options.hostId)],\n read: () => readPublishedCollectionSource(options),\n // A collection with a schedule still pending is SERVED but not STORED.\n //\n // No beat publishes a content entry — `flipDueEntry` during a render is\n // the whole mechanism — so storing this source would suppress the very\n // renders that would have noticed the entry coming due, and the post\n // would wait out the TTL rather than land at its time. Declining to\n // store leaves those collections exactly as uncached as they were\n // before this cache existed, which is the only cost this cache is not\n // allowed to reduce.\n //\n // Also refuses a collection that resolved to nothing, for the reason\n // `withRenderCache` states about negatives generally: a slug that\n // misses once must not miss for an hour.\n store: (value) => Boolean(value.collection) && !value.pendingSchedule,\n })\n } catch (error) {\n console.error(error)\n return readPublishedCollectionSource(options)\n }\n}\n\nasync function readPublishedCollectionSource(\n options: {\n hostId: string\n collectionSlug: string\n },\n): Promise<PublishedCollectionSource> {\n try {\n const collectionDoc = await findContentCollection(\n options.hostId,\n options.collectionSlug,\n )\n if (!collectionDoc) {\n return {\n collection: null,\n entries: [],\n categories: [],\n reachedBound: false,\n }\n }\n const { entries, reachedBound, pendingSchedule } = await listLiveEntries(\n collectionDoc.ref.collection('entries'),\n options.hostId,\n )\n // The compose-time source feeds the Collection entries block, whose byline\n // reads `authorName` — so a record-backed author has to be resolved here\n // too, or the block prints nothing for the entries a list page shows\n // (AGL-2486). This result is the cached one, which is what keeps the extra\n // read amortized across every page of the site that carries the block.\n await attachEntryAuthors(options.hostId, entries)\n return {\n collection: mapCollectionDoc(collectionDoc, options.collectionSlug),\n entries,\n categories: mapCollectionCategories(collectionDoc.get('categories')),\n reachedBound,\n ...(pendingSchedule ? { pendingSchedule: true } : {}),\n }\n } catch (error) {\n console.error(error)\n return {\n collection: null,\n entries: [],\n categories: [],\n reachedBound: false,\n }\n }\n}\n\n/** Entries-only view of {@link getPublishedCollectionSource} (AGL-551). */\nexport async function getPublishedCollectionEntries(options: {\n hostId: string\n collectionSlug: string\n}): Promise<CollectionEntrySummary[]> {\n return (await getPublishedCollectionSource(options)).entries\n}\n\n/**\n * Narrows a listing to its routed category and stamps its pagination\n * (AGL-1321 / AGL-620).\n *\n * Category first, ALWAYS: the two have to describe the same set. Counting\n * pages over the whole collection and then filtering would advertise pages\n * that render empty and hide entries that exist.\n *\n * `entriesReachedBound` is read by the caller BEFORE this runs, because a\n * category route hands its already-narrowed entries to compose and the\n * entries block's \"measure the raw set, not the filtered one\" rule then has\n * nothing raw left to measure (AGL-1516).\n */\nfunction applyCategoryAndPagination(\n data: CollectionContent,\n options: {\n page?: number\n perPage?: number\n categorySlug?: string\n },\n listing?: {\n /** Where `data.entries` begins in that collection's order. */\n windowStart?: number\n /** The shared read came back holding its own limit. */\n reachedBound?: boolean\n /**\n * The `perPage + 1` probe of a CURSOR page found an extra row — set only\n * when this listing was served by one, because only that read can answer\n * it (AGL-3219).\n */\n cursorHasMore?: boolean\n },\n): void {\n const { page = 1, perPage } = options\n const routedCategory = (options.categorySlug ?? '').trim()\n if (routedCategory) {\n const match = resolveCollectionCategoryBySlug(\n data.collection?.categories,\n routedCategory,\n )\n data.category = {\n slug: collectionCategorySlug(routedCategory),\n ...(match ? { id: match.id } : {}),\n name: match?.name ?? routedCategory,\n ...(match?.description ? { description: match.description } : {}),\n known: Boolean(match),\n }\n data.entries = data.entries.filter((entry) =>\n entryMatchesCategoryRoute(\n entry,\n { slug: routedCategory, ...(match ? { category: match } : {}) },\n data.collection?.categories,\n ),\n )\n }\n\n if (perPage && perPage > 0) {\n /*\n * The total is the COLLECTION's, not the read's (AGL-3213).\n *\n * `entries.length` was the count, and on a collection inside the bound it\n * still is — the two are the same number there. Past the bound it is the\n * size of the window, which is how `/changelog` advertised \"Page 10 of\n * 10\" while holding 166 entries and linking to 100 of them.\n *\n * A ROUTED CATEGORY keeps counting its own entries, because that is the\n * only honest number available here: the narrowing happens in memory over\n * the cached head, so both the count and the listing describe the same\n * bounded set. Paging a category past the bound needs its own ordered\n * query and a `(categoryId, status, publishedAt DESC)` index; until then\n * a category of a very large collection is capped, and says so by\n * agreeing with what it shows.\n */\n const windowStart = Number(listing?.windowStart)\n const windowed = Number.isFinite(windowStart) && windowStart > 0\n\n /*\n * The cursors, which are the pager's real answer (AGL-3219).\n *\n * `data.entries` is either EXACTLY this page — a cursor read — or the\n * whole cached head, which every listing address shares and each slices\n * its own page out of. So the page's own last entry is at the end of the\n * array in the first case and at `page * perPage - 1` in the second, and\n * the cursor is that entry's document id.\n */\n const pageEnd = windowed ? data.entries.length : page * perPage\n const last = data.entries[pageEnd - 1]\n const first = data.entries[windowed ? 0 : (page - 1) * perPage]\n\n /*\n * Is there an older page?\n *\n * A cursor page KNOWS, because its read asked for one more entry than it\n * needed and the extra row came back. The head has to reason: either it\n * is holding more entries than this page shows, or it is holding all it\n * could read and the read stopped at its own bound, which is the one\n * thing `entries.length` can never tell you about the collection.\n */\n const hasMore =\n listing?.cursorHasMore ??\n (data.entries.length > pageEnd ||\n (Boolean(listing?.reachedBound) && !routedCategory))\n\n /*\n * The deprecated total, stated ONLY where it can be true.\n *\n * A collection that fits inside one read can be counted, and a template\n * binding `{{pagination.totalPages}}` keeps rendering the number it\n * always did. Past the bound there is no honest total — the count and\n * the listing were reading the collection at two different moments, which\n * is what made the seam repeat an entry — so it is left absent rather\n * than asserted. A routed category counts its own narrowed set, which is\n * bounded by the same head and therefore countable.\n */\n const countable = routedCategory || !listing?.reachedBound\n const totalEntries = countable ? data.entries.length : undefined\n\n data.pagination = {\n page,\n perPage,\n nextCursor: hasMore && last?.$id ? last.$id : '',\n prevCursor: page > 1 && first?.$id ? first.$id : '',\n ...(totalEntries === undefined\n ? {}\n : {\n totalEntries,\n totalPages: collectionTotalPages(totalEntries, perPage),\n }),\n ...(windowed ? { windowStart } : {}),\n }\n }\n}\n\n/**\n * Resolves a non-screen path against the host's content collections\n * (Content Collections & Blog): `/{collectionSlug}` returns the published\n * entry list, `/{collectionSlug}/{entrySlug}` one entry. Fail-open — errors\n * resolve to `collection: null` and the caller 404s.\n *\n * A listing resolves only for a collection with a live entry (AGL-3101); one\n * with nothing live answers `collection: null` as well, so its listing, feed\n * and markdown twin are not public until its first entry is.\n */\nexport async function getCollectionContent(options: {\n hostId: string\n collectionSlug: string\n entrySlug?: string\n /**\n * 1-based list page (AGL-620), now a DISPLAY counter (AGL-3219): it labels\n * the page the reader is on and no read is positioned from it. The entries\n * come from `after`/`before`, or from the head of the cached source when\n * neither is set.\n */\n page?: number\n /** Entries per page (AGL-620); when set the list is paginated. */\n perPage?: number\n /**\n * Continue AFTER this entry's document id — the older direction (AGL-3219).\n *\n * What `/{collection}?after={id}` carries. A page defined this way does not\n * move when something is published above it, which is the whole reason the\n * addresses stopped being positions.\n */\n after?: string\n /** Continue BEFORE this entry's document id — the newer direction. */\n before?: string\n /**\n * The site's zone (AGL-3237). Stamped onto the returned content so every\n * reader downstream — including the client fallback renderer — formats from\n * the same string rather than from its own runtime.\n */\n timeZone?: string\n /**\n * Category segment of `/{collection}/category/{slug}` (AGL-1321). Filters\n * the listing before pagination is computed, so page counts and the page\n * windows describe the FILTERED set rather than the whole collection.\n */\n categorySlug?: string\n /**\n * Reveal the named entry even though the public site withholds it — the\n * live-site preview of a scheduled post (AGL-3205).\n *\n * ⛔ A VERIFIED GRANT, NOT A REQUEST. The caller passes `true` only after a\n * signed preview token has been checked against the resolved hostId AND\n * this exact `collectionSlug`/`entrySlug` (`verifyCollectionPreviewToken`).\n * The token format stays in the app that receives the URL; what crosses into\n * this lib is the verdict, so nothing here can be tricked by a payload's own\n * spelling of which entry it names.\n *\n * ENTRY ROUTES ONLY, and one entry at a time. It is ignored on a list route\n * — a preview of one post must not add it to `/blog`, to the feed, or to a\n * Collection entries block on any other page, all of which read the SHARED\n * cached source. Nothing it touches is cached at all.\n *\n * The preview render also writes NOTHING: see the `flipDueEntry` guard\n * below. Publishing a schedule stays the sole business of a public render.\n */\n previewUnpublishedEntry?: boolean\n}): Promise<CollectionContent> {\n const { hostId, collectionSlug, entrySlug } = options\n // Never on a list route, whatever the caller passed: `entrySlug` is what\n // makes the grant addressable at all, and the list is the shared cached\n // read this must stay out of.\n const preview = Boolean(options.previewUnpublishedEntry) && Boolean(entrySlug)\n const data: CollectionContent = {\n // Stamped before any early return, so every shape this function can hand\n // back carries it — including the empty one a 404 renders from.\n ...(options.timeZone ? { timeZone: options.timeZone } : {}),\n collection: null,\n entries: [],\n entry: null,\n pagination: null,\n category: null,\n error: null,\n }\n try {\n // A LIST route is served entirely from the CACHED source, which every\n // other page on the site already shares. It used to resolve the\n // collection and re-read its entries here, uncached, on every\n // regeneration of every listing address — `/blog`, nine `/blog/page/{n}`,\n // one `/blog/category/{slug}` per category, and the RSS feed — so a\n // collection of N live entries cost `1 + N + authors` reads per address\n // per window, for data byte-identical to what the cache was already\n // holding for the home page's \"Latest posts\" rail.\n //\n // An ENTRY route stays where it was: it reads ONE document by slug and\n // has nothing to share.\n if (!entrySlug) {\n const source = await getPublishedCollectionSource({\n hostId,\n collectionSlug,\n })\n if (!source.collection) return data\n // A collection is not a PAGE until something in it is live (AGL-3101).\n // Without this, creating one publishes `/{slug}` at once — an empty\n // listing with a feed and a markdown twin, before a word of it is\n // written. Answering it as no collection makes every listing address\n // 404 the way an unknown slug does, until the first entry is published\n // or its schedule comes due.\n //\n // Read off the UNFILTERED live set, before the category narrows it, so\n // an empty category of a live collection still renders. A read that\n // stopped at its bound cannot prove the collection empty — the live\n // entries may be past it — so that one keeps its listing. The rule\n // lives here and not in the source above: the source also feeds the\n // Collection entries block and the author page, and to them an empty\n // collection is an empty list, not a missing one.\n if (!source.entries.length && !source.reachedBound) return data\n data.collection = source.collection\n data.entries = source.entries\n data.entriesReachedBound = source.reachedBound\n /*\n * A page that starts past the cached read is served by its own window\n * (AGL-3213). Everything before that point comes out of the shared\n * source, so the pages a reader actually visits stay free.\n *\n * Only the unfiltered listing: a category route narrows in memory over\n * the same head, and a window read of the whole collection would hand\n * it ten entries of which any number may belong to another category.\n */\n const { page = 1, perPage } = options\n const cursor = (options.after ?? options.before ?? '').trim()\n let windowStart = 0\n let cursored: CollectionListingPage | null = null\n /*\n * A cursor address is served by its own read (AGL-3219). Everything\n * reachable without one comes out of the shared source, so the pages a\n * reader actually visits stay free.\n *\n * Only the unfiltered listing: a category route narrows in memory over\n * the same head, and a cursor read of the whole collection would hand it\n * ten entries of which any number belong to another category.\n */\n if (perPage && perPage > 0 && cursor && !(options.categorySlug ?? '').trim()) {\n cursored = await readCollectionListingPage({\n hostId,\n collectionSlug,\n ...(options.before ? { before: options.before } : { after: cursor }),\n limit: perPage,\n })\n // Null means the cursor read failed, or named a document that is\n // gone. The cached head is the better answer than an empty page: the\n // reader sees the newest entries rather than nothing at all.\n if (cursored) {\n data.entries = cursored.entries\n /*\n * `entries` is now EXACTLY this page, and both windowing sites\n * slice `[(page - 1) * perPage, …)`. Declaring the window to start\n * at that same offset makes their subtraction come out at zero, so\n * they take the page whole.\n *\n * Both sides of the subtraction are built from the same `page`, so\n * a hand-edited counter in a URL cancels itself out: the label is\n * wrong and the entries are still this cursor's page.\n */\n windowStart = (page - 1) * perPage\n }\n }\n applyCategoryAndPagination(data, options, {\n windowStart,\n reachedBound: source.reachedBound,\n ...(cursored ? { cursorHasMore: cursored.hasMore } : {}),\n })\n return data\n }\n\n const collectionDoc = await findContentCollection(hostId, collectionSlug)\n if (!collectionDoc) return data\n data.collection = mapCollectionDoc(collectionDoc, collectionSlug)\n\n const entryQuery = await collectionDoc.ref\n .collection('entries')\n .where('slug', '==', entrySlug)\n .limit(5)\n .get()\n // Same two-step as `listLiveEntries`: only pay for the org read when\n // something is due, and record the refusal on its own pass because a\n // refused entry never becomes the `entryDoc` below (AGL-471).\n //\n // A PREVIEW RENDER SKIPS BOTH WRITES (AGL-3205). `flipDueEntry` is the\n // entire publishing mechanism for a content entry, and it is a mechanism\n // that belongs to the PUBLIC render: a preview is one person looking at\n // one post through a link, and it must not be able to publish it, nor to\n // burn its schedule with the terminal refusal marker. Skipping the writes\n // costs nothing — the next public render asks the same questions and\n // writes the same answers — and it is what keeps \"nothing but a render\n // publishes a content entry\" true of renders anybody can reach.\n const dueHere = entryQuery.docs.filter((docSnapshot) =>\n isDueScheduled(docSnapshot.data()),\n )\n const permission: SchedulePermission = dueHere.length\n ? await scheduledPublishingPermission(hostId)\n : 'allowed'\n if (permission !== 'allowed' && !preview) {\n for (const docSnapshot of dueHere) {\n flipDueEntry(docSnapshot.ref, docSnapshot.data(), permission)\n }\n }\n /**\n * What a grant reveals: an entry this collection HOLDS and the site does\n * not serve.\n *\n * Deliberately not routed through `isLive`, which is the public answer and\n * has one other reader (`entry-link-routes`) whose whole job is to agree\n * with it. A second, wider answer inside it would make a LINK to a\n * previewed post resolve on the public site.\n *\n * Every status but `published` qualifies, which is `draft` as well as\n * `scheduled`: the ask is \"let me see it before it goes out\", and a post\n * is most worth looking at before its schedule is set. The blast radius is\n * the same either way — one entry, named in the signature, on one host.\n */\n const entryDoc =\n entryQuery.docs.find((docSnapshot) =>\n isLive(docSnapshot.data(), permission),\n ) ?? (preview ? entryQuery.docs[0] : undefined)\n if (entryDoc) {\n const value = entryDoc.data()\n if (!preview) flipDueEntry(entryDoc.ref, value, permission)\n if (preview && !isLive(value, permission)) {\n // The facts the preview chrome states back to the reader, so the page\n // cannot be mistaken for the published post. Read from the stored\n // document rather than inferred from the render.\n data.entryPreview = {\n status: String(value['status'] ?? 'draft'),\n publishAtSeconds:\n typeof value['publishAt']?.seconds === 'number'\n ? value['publishAt'].seconds\n : null,\n }\n }\n data.entry = {\n $id: entryDoc.id,\n title: value['title'] ?? entrySlug,\n slug: entrySlug,\n body: value['body'] ?? '',\n ...mapEntryFields(value),\n publishedAt: (value['publishedAt'] ?? value['publishAt'])\n ? {\n seconds: (value['publishedAt'] ?? value['publishAt']).seconds,\n }\n : null,\n }\n await attachEntryAuthors(hostId, [data.entry])\n }\n } catch (error) {\n console.error(error)\n data.error = error\n }\n return data\n}\n\nexport default getCollectionContent\n"],"names":["AUTHORS_MAX_PER_HOST","collectionCategorySlug","checkEntitlement","COLLECTION_SOURCE_MAX","collectionTotalPages","entryMatchesCategoryRoute","hostCollectionKind","normalizeContentAuthor","normalizeContentSchemaType","resolveCollectionCategoryBySlug","resolveEntryAuthor","firebaseAdmin","getOrgForHost","PUBLISHED_SITE_DATA_TTL_SECONDS","tenantDataTag","withRenderCache","COLLECTION_SOURCE_TTL_SECONDS","findContentCollection","hostId","collectionSlug","matches","app","firestore","collection","doc","where","limit","get","docs","find","docSnapshot","data","mapEntryFields","value","excerpt","authorName","authorId","coverImage","coverImageAlt","coverVideo","seoTitle","seoDescription","categoryId","category","tags","Array","isArray","filter","tag","updatedAt","seconds","mapCollectionCategories","item","id","trim","name","map","description","mapCollectionDoc","collectionDoc","$id","displayName","slug","templateScreenId","undefined","listScreenId","entryScreenId","schemaType","categories","attachEntryAuthors","entries","ids","Set","entry","Boolean","slice","authors","length","authorsRef","snapshots","getAll","snapshot","exists","author","error","console","ENTRY_SCHEDULE_SKIPPED","scheduleAlreadyRefused","isDueScheduled","Number","POSITIVE_INFINITY","Date","now","isPendingScheduled","scheduledPublishingPermission","org","isLive","permission","flipDueEntry","docRef","update","scheduleStatus","catch","status","publishedAt","LIVE_ENTRY_FIELDS","SCHEDULED_SOURCE_MAX","liveEntriesBase","entriesRef","select","readLiveEntryDocs","dated","orderBy","scheduled","reachedBound","undated","entryDoc","seen","has","add","push","unordered","toLiveEntries","ref","title","sort","a","b","listLiveEntries","due","pendingSchedule","some","readCollectionListingPage","options","cursorId","before","after","cursorDoc","backwards","startAfter","hasMore","pageDocs","reverse","resolveCollectionPageCursor","skip","page","perPage","isFinite","offset","getPublishedCollectionSource","key","revalidate","read","readPublishedCollectionSource","store","getPublishedCollectionEntries","applyCategoryAndPagination","listing","routedCategory","categorySlug","match","known","windowStart","windowed","pageEnd","last","first","cursorHasMore","countable","totalEntries","pagination","nextCursor","prevCursor","totalPages","getCollectionContent","entrySlug","preview","previewUnpublishedEntry","timeZone","entryQuery","source","entriesReachedBound","cursor","cursored","dueHere","entryPreview","String","publishAtSeconds","body"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SACEA,oBAAoB,EAEpBC,sBAAsB,EACtBC,gBAAgB,EAChBC,qBAAqB,EACrBC,oBAAoB,EAEpBC,yBAAyB,EACzBC,kBAAkB,EAClBC,sBAAsB,EACtBC,0BAA0B,EAC1BC,+BAA+B,EAC/BC,kBAAkB,QACb,sBAAqB;AAC5B,SAASC,aAAa,EAAEC,aAAa,QAAQ,2BAA0B;AACvE,SACEC,+BAA+B,EAC/BC,aAAa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BAAwBA,KAAK,CAAC,YAAY,IACpD;oBACEiB,SAAS,EAACjB,sBAAAA,KAAK,CAAC,cAAc,YAApBA,sBAAwBA,KAAK,CAAC,YAAY,EAAEiB,OAAO;gBAC/D,IACA;;YAEN,MAAMmB,mBAAmBnD,QAAQ;gBAACa,KAAK0C,KAAK;aAAC;QAC/C;IACF,EAAE,OAAOW,OAAO;QACdC,QAAQD,KAAK,CAACA;QACdrD,KAAKqD,KAAK,GAAGA;IACf;IACA,OAAOrD;AACT;AAEA,eAAe+I,qBAAoB"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../libs/tenant/runtime/src/lib/get-collection-content.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n AUTHORS_MAX_PER_HOST,\n type CollectionCategory,\n collectionCategorySlug,\n checkEntitlement,\n COLLECTION_SOURCE_MAX,\n collectionTotalPages,\n type ContentAuthorRecord,\n entryMatchesCategoryRoute,\n hostCollectionKind,\n normalizeContentAuthor,\n normalizeContentSchemaType,\n resolveCollectionCategoryBySlug,\n resolveEntryAuthor,\n} from '@aglyn/aglyn/server'\nimport { firebaseAdmin, getOrgForHost } from '@aglyn/tenant-data-admin'\nimport {\n PUBLISHED_SITE_DATA_TTL_SECONDS,\n tenantDataTag,\n withRenderCache,\n} from '@aglyn/tenant-data-admin/render-cache'\n\n/**\n * ONE cached read per collection, shared by every surface that lists it\n * (AGL-1302).\n *\n * It began as the compose-time source only: a Collection entries block in a\n * shared layout re-read up to ~100 entry docs on EVERY page of the site. The\n * routed listing was left out on the argument that the page's own ISR entry\n * amortized it — which is true of ONE address and false of a collection,\n * because a collection is not one address. `/blog`, `/blog/page/2…10`, a\n * `/blog/category/{slug}` per category and `/blog/rss.xml` are all the same\n * data, each paying its own `1 + entries + authors` per window, beside a\n * cache already holding exactly that.\n *\n * The other half of that argument was real and is answered rather than\n * dropped: `flipDueEntry` is a write, and nothing else publishes a content\n * entry, so a cache that stored a collection with a schedule still pending\n * would suppress the render that publishes it. `getPublishedCollectionSource`\n * therefore declines to STORE exactly those collections — see its `store`\n * predicate — which leaves scheduled publishing on the render window it has\n * always been on, and puts everything else on this TTL.\n */\nconst COLLECTION_SOURCE_TTL_SECONDS = PUBLISHED_SITE_DATA_TTL_SECONDS\n\n/**\n * Resolve a public content-collection slug (AGL-954). Commerce's product\n * collections share `hosts/{hostId}/collections`, and a slug is only unique\n * within a kind — a bare `limit(1)` handed the URL to whichever doc Firestore\n * returned first, so a catalog collection could shadow a blog. Reads a small\n * window instead and takes the first content-kind match.\n */\nasync function findContentCollection(\n hostId: string,\n collectionSlug: string,\n): Promise<FirebaseFirestore.QueryDocumentSnapshot | undefined> {\n const matches = await firebaseAdmin\n .app()\n .firestore()\n .collection('hosts')\n .doc(hostId)\n .collection('collections')\n .where('slug', '==', collectionSlug)\n .limit(5)\n .get()\n return matches.docs.find(\n (docSnapshot) => hostCollectionKind(docSnapshot.data()) === 'content',\n )\n}\n\nexport interface CollectionEntrySummary {\n $id: string\n title: string\n slug: string\n excerpt?: string\n /**\n * The byline TEXT (AGL-686). Either the entry's own legacy free-typed\n * string or — since AGL-2486 — the name of the author record `authorId`\n * points at, resolved here so every downstream reader (the Entry Meta\n * block, `{{entry.author}}`, the RSS feed) keeps asking one field.\n */\n authorName?: string\n /** Reference into `hosts/{hostId}/authors` (AGL-2486). */\n authorId?: string\n /**\n * The resolved author RECORD (AGL-2486) — what `Article.author` is built\n * from. Null when the entry names no author, in which case the page falls\n * back to the site's publisher entity exactly as it always has.\n */\n author?: ContentAuthorRecord | null\n body?: string\n coverImage?: string\n /** `og:image:alt` for the cover (AGL-2417); travels WITH `coverImage`. */\n coverImageAlt?: string\n /**\n * The featured video (AGL-2956): a media reference or a URL, a Wistia link\n * included, in the shape `coverImage` is. See\n * `CollectionEntryRecord.coverVideo`.\n */\n coverVideo?: string\n /** Search-result title override (AGL-582); falls back to `title`. */\n seoTitle?: string\n /** Meta description override (AGL-582); falls back to `excerpt`. */\n seoDescription?: string\n /**\n * Stable reference into the collection's `categories` taxonomy\n * (AGL-582); resolved to a display name at render.\n */\n categoryId?: string\n /** Legacy free-typed bucket (AGL-582); read-only fallback. */\n category?: string\n /** Free-form labels (AGL-582). */\n tags?: string[]\n publishedAt?: { seconds: number } | null\n /**\n * Last edited, which is what `Article.dateModified` publishes (AGL-2534).\n *\n * Distinct from {@link publishedAt} on purpose: re-dating a post is not\n * editing it, so the console writes `publishedAt` alone when an author\n * backdates and this stays put. Google reads `dateModified` for freshness.\n */\n updatedAt?: { seconds: number } | null\n /**\n * The collection this entry came out of (AGL-2518), stamped only by a\n * reader that MIXES collections — the author page. Unset on every routed\n * listing, where the route already answers the question. See\n * `CollectionEntryRecord.collectionSlug`.\n */\n collectionSlug?: string\n /** The display name of {@link collectionSlug}. */\n collectionName?: string\n}\n\n/** Entry-doc fields shared by the list and single-entry mappers (AGL-582). */\nfunction mapEntryFields(\n value: FirebaseFirestore.DocumentData,\n): Pick<\n CollectionEntrySummary,\n | 'excerpt'\n | 'coverImage'\n | 'coverImageAlt'\n | 'coverVideo'\n | 'seoTitle'\n | 'seoDescription'\n | 'authorName'\n | 'authorId'\n | 'categoryId'\n | 'category'\n | 'tags'\n | 'updatedAt'\n> {\n return {\n excerpt: value['excerpt'] ?? '',\n // The byline was DECLARED on `CollectionEntrySummary` (AGL-686) and\n // mapped by nobody, so `entry.authorName` was `undefined` on every entry\n // this loader returned — which is every routed entry page and every\n // Collection entries block. The console collected the field, the rules\n // stored it, the JSON-LD builder read it and the Entry Meta block printed\n // it, and all three saw nothing, because the one hop between Firestore\n // and them dropped it (AGL-2486). Written but never read, in the\n // direction that leaves no error behind.\n authorName: value['authorName'] ?? '',\n authorId: value['authorId'] ?? '',\n coverImage: value['coverImage'] ?? '',\n coverImageAlt: value['coverImageAlt'] ?? '',\n // Here, where both read paths pick it up, so a list card and the routed\n // entry page can each bind the featured video (AGL-2956).\n coverVideo: value['coverVideo'] ?? '',\n seoTitle: value['seoTitle'] ?? '',\n seoDescription: value['seoDescription'] ?? '',\n categoryId: value['categoryId'] ?? '',\n category: value['category'] ?? '',\n tags: Array.isArray(value['tags'])\n ? value['tags'].filter((tag): tag is string => typeof tag === 'string')\n : [],\n /*\n `dateModified`'s source (AGL-2534), and it was missing for the same\n reason `authorName` was — the reason this function's own comment above\n describes.\n\n The console has written `updatedAt` on every save, `page.tsx` reads\n `entry.updatedAt.seconds` to publish `Article.dateModified`, a spec\n asserts the conversion, and two console comments explain why it must not\n track `publishedAt`. Nothing mapped it, so `entry.updatedAt` was\n `undefined` on every entry the loader has ever returned and no published\n article has ever carried a `dateModified` — the freshness signal Google\n reads. The spec passed throughout because it builds its entry object by\n hand and never crosses this boundary.\n\n Mapped HERE rather than beside `publishedAt` at the two call sites: this\n is an ordinary field with no `publishAt` fallback and nothing sorts on\n it, so one place is enough — and one place is what stops the next read\n path from forgetting it.\n */\n updatedAt: value['updatedAt']?.seconds\n ? { seconds: value['updatedAt'].seconds }\n : null,\n }\n}\n\n/**\n * The collection doc's category taxonomy (AGL-582), sanitized: only\n * `{ id, name }` pairs with non-empty strings survive, order preserved.\n *\n * `description` rides along when the author wrote one and is dropped when it\n * is blank or not a string, so the head can tell \"described\" from \"not\n * described\" by truthiness alone — an empty string reaching the metadata\n * would suppress the template screen's description and leave the listing with\n * none at all.\n */\nfunction mapCollectionCategories(value: unknown): CollectionCategory[] {\n if (!Array.isArray(value)) return []\n return value\n .filter(\n (item): item is CollectionCategory =>\n typeof item?.id === 'string' &&\n item.id.trim() !== '' &&\n typeof item?.name === 'string' &&\n item.name.trim() !== '',\n )\n .map((item) => {\n const description =\n typeof item.description === 'string' ? item.description.trim() : ''\n return {\n id: item.id,\n name: item.name,\n ...(description ? { description } : {}),\n }\n })\n}\n\n/**\n * The routed view of a collection DOCUMENT (AGL-551): its name and the\n * template screens its list and entry routes render through.\n *\n * `slug` is the slug that was ASKED FOR rather than the one stored, which is\n * what every caller of this file has always returned — a listing has to build\n * its own URLs out of the segment the reader is standing on.\n */\nfunction mapCollectionDoc(\n collectionDoc: FirebaseFirestore.QueryDocumentSnapshot,\n collectionSlug: string,\n): CollectionContent['collection'] {\n return {\n $id: collectionDoc.id,\n displayName: collectionDoc.get('displayName') ?? collectionSlug,\n slug: collectionSlug,\n templateScreenId: collectionDoc.get('templateScreenId') ?? undefined,\n listScreenId: collectionDoc.get('listScreenId') ?? undefined,\n entryScreenId: collectionDoc.get('entryScreenId') ?? undefined,\n // Normalized HERE rather than at the head (AGL-2536), so an unrecognised\n // stored value can never reach the JSON-LD: an `@type` the vocabulary\n // does not define makes a consumer discard the whole node, costing the\n // page every property it publishes rather than just this one.\n schemaType: normalizeContentSchemaType(collectionDoc.get('schemaType')),\n // \"List the collection, not its entries\" (AGL-3247). Carried as the\n // STORED boolean rather than as the resolved answer: the render surface\n // composes it with the site-level switch itself, and a pre-resolved flag\n // here would be a second place that has to remember that switch exists.\n excludeEntriesFromSearch:\n collectionDoc.get('excludeEntriesFromSearch') === true,\n categories: mapCollectionCategories(collectionDoc.get('categories')),\n }\n}\n\n/**\n * Resolve the author RECORDS a set of entries reference (AGL-2486).\n *\n * Costs ZERO reads when no entry names an `authorId`, which is every site\n * that has not adopted custom authors and every entry written before them —\n * the check is on the ids already in hand, not a probe of the collection. When\n * ids are present it is one `getAll` of the DISTINCT ones, bounded by\n * {@link AUTHORS_MAX_PER_HOST} and by the ≤100-entry page above it, rather\n * than a read per entry.\n *\n * Fail-open, like every other read in this file: an authors read that throws\n * leaves the entries with their legacy `authorName` (or the site entity) and\n * the page renders. A byline is not worth a 500.\n */\nasync function attachEntryAuthors(\n hostId: string,\n entries: CollectionEntrySummary[],\n): Promise<void> {\n const ids = [\n ...new Set(\n entries\n .map((entry) => (entry.authorId ?? '').trim())\n .filter(Boolean),\n ),\n ].slice(0, AUTHORS_MAX_PER_HOST)\n let authors: ContentAuthorRecord[] = []\n if (ids.length) {\n try {\n const authorsRef = firebaseAdmin\n .app()\n .firestore()\n .collection('hosts')\n .doc(hostId)\n .collection('authors')\n const snapshots = await firebaseAdmin\n .app()\n .firestore()\n .getAll(...ids.map((id) => authorsRef.doc(id)))\n authors = snapshots\n .map((snapshot) =>\n snapshot.exists\n ? normalizeContentAuthor(snapshot.data(), snapshot.id)\n : null,\n )\n .filter((author): author is ContentAuthorRecord => Boolean(author))\n } catch (error) {\n console.error(error)\n }\n }\n for (const entry of entries) {\n const author = resolveEntryAuthor(entry, authors)\n entry.author = author\n // The byline TEXT is denormalized onto the field everything downstream\n // already reads, so a record-backed author needs no change in the Entry\n // Meta block, the token map, the fallback nodes or the RSS feed. A record\n // WINS over the legacy string on the same entry: picking an author is the\n // more recent statement of who wrote it.\n if (author?.name) entry.authorName = author.name\n }\n}\n\n/**\n * Terminal refusal marker for an entry schedule, the flat-status twin of\n * `publishSchedule.status: 'skipped-unentitled'` on screens (AGL-1185).\n *\n * A field rather than a new `status` value on purpose. `status` is queried\n * (`where('status', 'in', [...])`), rendered by the console, and sorted on by\n * `bundle-timestamps.ts`; adding a member would have meant auditing every one\n * of those readers. A sibling field is invisible to all of them and is read\n * only here.\n */\nconst ENTRY_SCHEDULE_SKIPPED = 'skipped-unentitled'\n\n/** A schedule this entry already had declined, and will not have reconsidered. */\nfunction scheduleAlreadyRefused(\n value: FirebaseFirestore.DocumentData,\n): boolean {\n return value['scheduleStatus'] === ENTRY_SCHEDULE_SKIPPED\n}\n\n/** A scheduled entry whose time has come — before any plan question. */\nexport function isDueScheduled(value: FirebaseFirestore.DocumentData): boolean {\n return (\n value['status'] === 'scheduled' &&\n !scheduleAlreadyRefused(value) &&\n (value['publishAt']?.seconds ?? Number.POSITIVE_INFINITY) * 1000 <=\n Date.now()\n )\n}\n\n/**\n * A scheduled entry still waiting on its time: not due yet, and not refused.\n * Nothing but a render publishes a content entry, so a cache that stored a\n * read holding one would withhold the render that notices it come due — see\n * {@link LiveEntriesRead.pendingSchedule}.\n */\nexport function isPendingScheduled(\n value: FirebaseFirestore.DocumentData,\n): boolean {\n return (\n value['status'] === 'scheduled' &&\n !scheduleAlreadyRefused(value) &&\n !isDueScheduled(value)\n )\n}\n\n/**\n * Is this host's plan allowed to publish on a schedule? (AGL-471 shape.)\n *\n * `React.cache`-deduped per request via `getOrgForHost`, and — this is the\n * part that keeps it off the hot path — every caller below only asks once it\n * has already found a due scheduled entry. A collection with nothing due pays\n * nothing, which is almost every render.\n *\n * THREE answers, not two, and the third is the point. `refused` means we read\n * the plan and it does not carry the entitlement. `unresolved` means we could\n * not find out. Both withhold the entry, but only `refused` may write the\n * terminal marker — burning a schedule permanently on the strength of a\n * hostIndex miss or a transient rejection would destroy a customer's post for\n * a reason that may not be true a second later.\n *\n * Withholding on `unresolved` rather than publishing is what every other\n * entitlement caller on the tenant runtime already does: `apply-publish-schedule`\n * here, and the automation engine's two runners, all pass a possibly\n * undefined org straight into `checkEntitlement`, which resolves a missing\n * plan as free and denies (AGL-247). Opening here instead would make this the\n * one gate in the lib that admits when it cannot see — the exact shape of the\n * free-tier leak `no-plan-gated-entitlement` exists to forbid.\n *\n * The blast radius of withholding is deliberately small: `isLive` answers true\n * for `status: 'published'` before it ever consults this, so an unresolved\n * read hides only the due-scheduled entry, never the published ones, and the\n * next render retries.\n */\nexport type SchedulePermission = 'allowed' | 'refused' | 'unresolved'\n\nexport async function scheduledPublishingPermission(\n hostId: string,\n): Promise<SchedulePermission> {\n try {\n const org = (await getOrgForHost(hostId))?.org\n if (!org) return 'unresolved'\n return checkEntitlement(org, 'scheduledPublishing') ? 'allowed' : 'refused'\n } catch (error) {\n // Caught rather than thrown: the only caller sits inside\n // `getCollectionContent`'s try/catch, which returns an EMPTY collection —\n // so an unhandled rejection here would blank every published entry on the\n // page, not just the scheduled one.\n console.error(error)\n return 'unresolved'\n }\n}\n\n/**\n * Scheduled entries (AGL-123) go live lazily like AGL-61: a due\n * `publishAt` counts as published for this render, and the doc is flipped\n * to `published` fail-open so the state becomes durable.\n *\n * PLAN GATE (AGL-471). `scheduledPublishing` is a Business entitlement, and\n * until now nothing on the entry path checked it: the console let any plan\n * write `status: 'scheduled'`, and this render path published it. Scheduling\n * worked end to end on Free. The screens path has gated this since AGL-471\n * and records its refusal since AGL-1185 — entries were simply never wired\n * to either, which is why the leak was invisible from the screens side.\n *\n * The permission is threaded in rather than resolved here so the org read\n * happens once per call site instead of once per entry.\n *\n * Exported for the one other reader that decides whether an entry is on the\n * site — whether a LINK to it resolves (AGL-3118) — so a link and the page it\n * points at can never disagree about which entries exist.\n */\nexport function isLive(\n value: FirebaseFirestore.DocumentData,\n permission: SchedulePermission,\n): boolean {\n if (value['status'] === 'published') return true\n return permission === 'allowed' && isDueScheduled(value)\n}\n\n/**\n * Make the due state durable — or record that it was refused.\n *\n * The refusal is TERMINAL, for the AGL-1185 reason: left as a bare pending\n * `scheduled`, the entry stays permanently due, so the day the org upgrades\n * to Business the next render publishes it. Content scheduled on a plan that\n * could not honour it, and forgotten, surfacing during an upgrade — exactly\n * when nobody is looking for it. Recording the refusal is what makes it stop\n * being due, and it also stops this path re-reading the org on every\n * subsequent render.\n *\n * Both writes fail open: an error leaves today's state, and the next render\n * retries.\n */\nfunction flipDueEntry(\n docRef: FirebaseFirestore.DocumentReference,\n value: FirebaseFirestore.DocumentData,\n permission: SchedulePermission,\n): void {\n if (value['status'] !== 'scheduled') return\n if (scheduleAlreadyRefused(value)) return\n // `unresolved` writes NOTHING. It withholds this render and leaves the\n // schedule exactly as it found it, so a later render can still publish it.\n if (permission === 'unresolved') return\n if (permission === 'refused') {\n if (!isDueScheduled(value)) return\n docRef\n .update({ scheduleStatus: ENTRY_SCHEDULE_SKIPPED })\n .catch((error) => console.error(error))\n return\n }\n docRef\n .update({ status: 'published', publishedAt: value['publishAt'] })\n .catch((error) => console.error(error))\n}\n\nexport interface CollectionContent {\n /**\n * The zone this site's dates read in (AGL-3237), carried on the CONTENT so\n * it reaches the client.\n *\n * `collection-fallback.tsx` renders through `next/dynamic` from\n * `catch-all-client`, so it formats dates in the browser as well as on the\n * server. A zone it read from its own runtime would be the visitor's, which\n * is precisely the hydration mismatch AGL-1926 fixed — so the server\n * decides it once and it travels here, in the props both renders read.\n */\n timeZone?: string\n collection: {\n $id: string\n displayName: string\n slug: string\n /**\n * Legacy entry-template screen (AGL-105); superseded by\n * `entryScreenId` but still honored when only it is set.\n */\n templateScreenId?: string\n /** List-template screen (AGL-551); `/{collection}` renders through it. */\n listScreenId?: string\n /**\n * Entry-template screen (AGL-551); `/{collection}/{entry}` renders\n * through it with `{{entry.*}}` tokens.\n */\n entryScreenId?: string\n /**\n * What KIND of article this collection publishes (AGL-2536) — the\n * `schema.org` type its entries serialise as. Unset publishes `Article`,\n * which is what every collection published before the setting existed.\n */\n schemaType?: string\n /**\n * Whether this collection withholds its ENTRIES from search (AGL-3247).\n * The listing and its category listings stay indexable either way.\n */\n excludeEntriesFromSearch?: boolean\n /**\n * Category taxonomy (AGL-582): entries reference these by stable\n * `id`; `name` is the renameable display label.\n */\n categories?: CollectionCategory[]\n } | null\n entries: CollectionEntrySummary[]\n entry: CollectionEntrySummary | null\n /**\n * Whether the read that produced `entries` stopped at\n * {@link COLLECTION_SOURCE_MAX} (AGL-1516). Set on LIST routes only —\n * an entry route reads one document by slug and bounds nothing.\n */\n entriesReachedBound?: boolean\n /**\n * Present ONLY when a verified preview grant revealed an entry the public\n * site withholds (AGL-3205) — never on a public render, and never for an\n * entry that is already live. Its absence is what the preview chrome reads\n * to say \"this one is actually published\", so it must not be set\n * defensively.\n */\n entryPreview?: {\n /** The stored `status` — `scheduled` or `draft`. */\n status: string\n /** The instant it is scheduled for, or null when nothing is scheduled. */\n publishAtSeconds: number | null\n }\n /** List pagination (AGL-620); null for entry pages or unpaginated lists. */\n pagination?: CollectionPagination | null\n /**\n * The category this listing is filtered to (AGL-1321); null on the\n * canonical unfiltered list and on entry pages.\n */\n category?: CollectionRouteCategory | null\n error: unknown\n}\n\n/** The category a `/{collection}/category/{slug}` route addresses (AGL-1321). */\nexport interface CollectionRouteCategory {\n /** The URL segment, normalized — what the canonical link must say. */\n slug: string\n /** Taxonomy id; absent when the segment matched no known category. */\n id?: string\n /** Display label; falls back to the raw segment for an unknown category. */\n name: string\n /**\n * The taxonomy's {@link CollectionCategory.description}, carried onto the\n * route so the head can describe the FILTERED listing rather than inherit\n * the whole collection's description. Absent for an unknown segment, which\n * names no category and therefore has nothing to describe.\n */\n description?: string\n /**\n * Whether the segment resolved against the collection's taxonomy. An\n * unknown category still renders — an empty listing, not a crash — but the\n * page must not invite indexing of a URL that names nothing.\n */\n known: boolean\n}\n\nexport interface CollectionPagination {\n /**\n * 1-based counter for display only (AGL-3219).\n *\n * It is what `{{pagination.page}}` renders and nothing reads it back: a\n * cursor page is addressed by the document it starts after, so this number\n * describes how far a reader has walked rather than where the read began.\n * Hand-edit it in a URL and the label is wrong; the entries are not.\n */\n page: number\n perPage: number\n /**\n * The document id the NEXT (older) page starts after, or `''` when this is\n * the last page (AGL-3219).\n *\n * Set from a `limit(perPage + 1)` probe: the extra row is the only evidence\n * needed that an older page exists, and it costs one document rather than\n * the `count()` aggregation a total used to need. It is also the only\n * honest answer available — see {@link CollectionPagination.totalPages}.\n */\n nextCursor: string\n /** The document id the PREVIOUS (newer) page starts before, or `''`. */\n prevCursor: string\n /**\n * How many pages there are.\n *\n * @deprecated AGL-3219. Still resolved, so a template binding\n * `{{pagination.totalPages}}` keeps rendering, but no longer a promise: a\n * total can only be stated for a collection that fits inside one read, and\n * past that it is absent rather than wrong. It used to be derived from a\n * `count()` over a set the listing's two reads disagreed about, which is\n * how the page 10/11 seam came to repeat an entry. Bind\n * {@link CollectionPagination.nextCursor} instead — `''` means there is\n * nothing older, which is the question a pager is actually asking.\n */\n totalPages?: number\n /** @deprecated AGL-3219, with {@link CollectionPagination.totalPages}. */\n totalEntries?: number\n /**\n * Where `entries` begins in the collection's own order (AGL-3213): 0 for a\n * listing served from the cached read, and the page's own offset for one\n * served by a window read past that read's bound.\n *\n * Both windowing sites subtract it — `collectionEntriesPageWindow` on the\n * way into props, and the Collection entries block on the way into compose.\n * Without it a windowed listing renders empty, because every one of them\n * slices `[(page - 1) * perPage, …)` on the premise that `entries` starts at\n * the beginning of the collection.\n */\n windowStart?: number\n}\n\n/**\n * A bounded read of a collection's live entries (AGL-1516).\n *\n * `reachedBound` is a fact about the QUERY, not about `entries`, and the two\n * genuinely differ: the query asks for `status in ['published', 'scheduled']`\n * and the filter below then drops everything not live yet, so a read that came\n * back holding all {@link COLLECTION_SOURCE_MAX} docs can hand back fewer.\n * Counting the survivors — which is all a downstream consumer can do — reads\n * that as a complete collection, and the one thing a truncated read must never\n * be allowed to claim is completeness.\n */\ninterface LiveEntriesRead {\n entries: CollectionEntrySummary[]\n /** The query came back holding its own `.limit()`. */\n reachedBound: boolean\n /**\n * The read saw a `scheduled` entry whose `publishAt` has NOT arrived and\n * which has not been terminally refused — a schedule this collection is\n * still waiting on.\n *\n * Nothing promotes a content entry on a beat: `publish-schedule-job.ts` is\n * screens-only, so `isLive`/`flipDueEntry` running during a render is the\n * entire mechanism. A cached source therefore does not merely serve stale\n * entries, it withholds the render that would have published one, for as\n * long as the entry stays cached. This is what lets the cache decline to\n * store exactly those collections, so a schedule keeps landing on the\n * render window rather than on the TTL.\n */\n pendingSchedule: boolean\n}\n\n/**\n * The fields a LISTING read of an entry needs — the field mask on the query\n * below (AGL-3213).\n *\n * The point of the mask is the field that is NOT in it. `body` is the whole\n * post, and `mapEntryFields` has never mapped it on this path: a list card\n * binds a title, an excerpt, a cover and a byline, and the routed entry page\n * reads its one document separately. So the markdown of up to\n * {@link COLLECTION_SOURCE_MAX} posts crossed the wire, was parsed out of the\n * response, and was dropped one function later — on every fill of a cache\n * that every listing address, every \"Latest posts\" rail, the feed and the\n * author page share. A changelog is the worst case and also the common one.\n *\n * Firestore bills the document read either way, so this buys no reads; it\n * buys egress and the JSON parse, which is the part of a collection render\n * that grows with how much people have written.\n *\n * Site search is unaffected and must stay that way: it matches on `body`\n * through its OWN query in `apps/tenant/utils/search-content.ts`, which this\n * mask does not touch.\n *\n * ⛔ A reader added to `mapEntryFields` or to the liveness/schedule helpers\n * must be added HERE in the same edit. A field left out does not error — it\n * arrives `undefined`, which is exactly how `authorName` and `updatedAt` went\n * missing for months (AGL-2486, AGL-2534). The four schedule fields are\n * listed first for that reason: `status`, `publishAt` and `scheduleStatus`\n * decide whether an entry is live at all, and `flipDueEntry` WRITES\n * `publishAt` back as `publishedAt`, so a mask that dropped it would publish\n * a due entry with no date.\n */\nconst LIVE_ENTRY_FIELDS = [\n 'status',\n 'publishAt',\n 'publishedAt',\n 'scheduleStatus',\n 'title',\n 'slug',\n 'excerpt',\n 'authorName',\n 'authorId',\n 'coverImage',\n 'coverImageAlt',\n 'coverVideo',\n 'seoTitle',\n 'seoDescription',\n 'categoryId',\n 'category',\n 'tags',\n 'updatedAt',\n] as const\n\n/**\n * Most SCHEDULED entries one live read considers (AGL-3213).\n *\n * Read by its own query rather than taken from the dated page below, because\n * a schedule is invisible to that page: scheduling writes `publishAt` and\n * never `publishedAt`, and `flipDueEntry` during a render is the only thing\n * that publishes one. A schedule the read misses is a post that never goes\n * out. The set is small by nature — a hundred pending schedules on one\n * collection is already an unusual editorial calendar.\n */\nconst SCHEDULED_SOURCE_MAX = 100\n\n/** Everything a public listing may show, before any ordering. */\nfunction liveEntriesBase(\n entriesRef: FirebaseFirestore.CollectionReference,\n): FirebaseFirestore.Query {\n return (\n entriesRef\n .where('status', 'in', ['published', 'scheduled'])\n // Everything this path reads, and nothing else (AGL-3213) — see\n // {@link LIVE_ENTRY_FIELDS}.\n .select(...LIVE_ENTRY_FIELDS)\n )\n}\n\n/**\n * The documents a live read considers, in the order the site shows them\n * (AGL-3213).\n *\n * ## Why this is ordered now, and why ordering alone would have broken it\n *\n * It was `where(status).limit(100)` with NO `orderBy`, sorted in memory\n * afterwards. That is not the newest hundred — it is a hundred documents in\n * NAME order, then sorted. Under the bound the two agree, because a hundred\n * out of a hundred is everything; past it they diverge completely. This site's\n * own changelog reached 166 live entries and its listing showed an arbitrary\n * hundred of them, chosen by document id, with 66 releases reachable only at\n * their own URLs.\n *\n * The comment that used to sit here was right about `orderBy`, though:\n * Firestore returns only documents that HAVE the ordered field, so a dated\n * read does not mis-sort an entry without a date — it hides it. Two of those\n * exist and both matter:\n *\n * A SCHEDULE carries `publishAt` and no `publishedAt` until it goes out.\n * Ordering alone would have stopped scheduled posts publishing\n * at all, silently, because nothing else publishes them.\n * AN IMPORT restores whatever the bundle carried, and\n * `/api/hosts/resources` validates no field for presence\n * either — so a published entry with no `publishedAt` exists.\n *\n * So it is three queries, in the shape the console's sorted window uses\n * (AGL-2853): the DATED page, every SCHEDULE, and — only when the dated page\n * came back SHORT, which is the server's own proof that the collection fits\n * inside the bound — a scan for live entries carrying no date. Past the bound\n * an undated entry sorts after every dated one by definition, so it belongs to\n * the tail pages, which are served by their own window read.\n */\nasync function readLiveEntryDocs(\n entriesRef: FirebaseFirestore.CollectionReference,\n): Promise<{\n docs: FirebaseFirestore.QueryDocumentSnapshot[]\n reachedBound: boolean\n}> {\n try {\n const dated = await liveEntriesBase(entriesRef)\n .orderBy('publishedAt', 'desc')\n // The document name breaks ties, so two entries published in the same\n // second cannot swap places between two reads and move a page boundary\n // under a reader. Descending to match the date: a composite index ends\n // with `__name__` in the last field's direction, which makes this the\n // `(status, publishedAt DESC)` index the console's table already needs.\n .orderBy('__name__', 'desc')\n // Named rather than literal (AGL-1516): a search index has to be able to\n // say \"this read reached its bound\", and it can only do that against a\n // bound it shares with the query. `collectionSourceReachedBound` reads\n // the same constant.\n .limit(COLLECTION_SOURCE_MAX)\n .get()\n\n const scheduled = await entriesRef\n .where('status', '==', 'scheduled')\n .select(...LIVE_ENTRY_FIELDS)\n .limit(SCHEDULED_SOURCE_MAX)\n .get()\n\n /*\n * EITHER read stopping at its own limit means entries went unseen.\n *\n * The dated page is the usual one. The schedule page is the case a dated\n * read alone cannot even detect: a collection holding nothing but pending\n * schedules returns ZERO dated documents, so a bound measured only there\n * would report a complete read of an empty collection — and \"nothing is\n * live here\" is the claim that takes a listing off the site (AGL-3101).\n */\n const reachedBound =\n dated.docs.length >= COLLECTION_SOURCE_MAX ||\n scheduled.docs.length >= SCHEDULED_SOURCE_MAX\n\n const undated = reachedBound\n ? []\n : (\n await liveEntriesBase(entriesRef)\n .orderBy('__name__')\n .limit(COLLECTION_SOURCE_MAX)\n .get()\n ).docs.filter((entryDoc) => !entryDoc.get('publishedAt'))\n\n const seen = new Set<string>()\n const docs: FirebaseFirestore.QueryDocumentSnapshot[] = []\n for (const entryDoc of [...dated.docs, ...scheduled.docs, ...undated]) {\n if (seen.has(entryDoc.id)) continue\n seen.add(entryDoc.id)\n docs.push(entryDoc)\n }\n return { docs, reachedBound }\n } catch (error) {\n /*\n * FAIL SOFT TO THE UNORDERED READ.\n *\n * The ordered query needs the `(status, publishedAt DESC)` composite\n * index. Indexes do NOT ship with a promotion — RELEASING.md deploys them\n * by hand afterwards — so the window between the code landing and the\n * index existing has to degrade rather than break. An arbitrary hundred\n * is a bad listing; a 500 is a customer's blog down.\n */\n console.error(error)\n const unordered = await liveEntriesBase(entriesRef)\n .limit(COLLECTION_SOURCE_MAX)\n .get()\n return {\n docs: unordered.docs,\n reachedBound: unordered.docs.length >= COLLECTION_SOURCE_MAX,\n }\n }\n}\n\n/** The live entries among `docs`, newest first, publishing any that came due. */\nfunction toLiveEntries(\n docs: readonly FirebaseFirestore.QueryDocumentSnapshot[],\n permission: SchedulePermission,\n): CollectionEntrySummary[] {\n return (\n docs\n .filter((entryDoc) => isLive(entryDoc.data(), permission))\n .map((entryDoc) => {\n const value = entryDoc.data()\n flipDueEntry(entryDoc.ref, value, permission)\n return {\n $id: entryDoc.id,\n title: value['title'] ?? entryDoc.id,\n slug: value['slug'] ?? entryDoc.id,\n ...mapEntryFields(value),\n publishedAt: (value['publishedAt'] ?? value['publishAt'])\n ? {\n seconds: (value['publishedAt'] ?? value['publishAt']).seconds,\n }\n : null,\n }\n })\n // An entry carrying no date at all sorts last rather than to 1970 —\n // the same place the query's own order puts it.\n .sort(\n (a, b) => (b.publishedAt?.seconds ?? 0) - (a.publishedAt?.seconds ?? 0),\n )\n )\n}\n\n/**\n * Fetches a collection's live entries (newest first), shared by the route\n * loader and the compose-time Collection entries block (AGL-551).\n */\nasync function listLiveEntries(\n entriesRef: FirebaseFirestore.CollectionReference,\n hostId: string,\n): Promise<LiveEntriesRead> {\n const { docs, reachedBound } = await readLiveEntryDocs(entriesRef)\n\n // Ask the plan question ONLY if something is actually due (AGL-471). A\n // collection with no due schedule — almost every render — never reads the\n // org at all.\n const due = docs.filter((entryDoc) => isDueScheduled(entryDoc.data()))\n const permission: SchedulePermission = due.length\n ? await scheduledPublishingPermission(hostId)\n : 'allowed'\n\n // Record the terminal refusal on its own pass, because a refused entry is\n // NOT live and so never reaches the `flipDueEntry` inside the map below.\n // Without this the entry stays due forever: excluded from every render, and\n // re-reading the org on each one.\n if (permission !== 'allowed') {\n for (const entryDoc of due) {\n flipDueEntry(entryDoc.ref, entryDoc.data(), permission)\n }\n }\n\n // Measured on the RAW docs, before the liveness filter (AGL-1516): a\n // not-yet-due entry is filtered out one line down, so this is the last\n // place that can see one at all.\n const pendingSchedule = docs.some((entryDoc) =>\n isPendingScheduled(entryDoc.data()),\n )\n\n const entries = toLiveEntries(docs, permission)\n\n return {\n entries,\n reachedBound,\n pendingSchedule,\n }\n}\n\n/** One page of a listing, and whether anything older follows it. */\ninterface CollectionListingPage {\n entries: CollectionEntrySummary[]\n /** The `limit(perPage + 1)` probe found an extra row. */\n hasMore: boolean\n}\n\n/**\n * One page of a listing that starts PAST the cached read (AGL-3213),\n * addressed by the document it continues from rather than by a position\n * (AGL-3219).\n *\n * Uncached on purpose, and it is the only read on the collection path that is.\n * The cached source exists because `/blog`, every listing address, the feed\n * and every \"Latest posts\" rail want the same first hundred entries\n * (AGL-1302); a page past that bound wants ten entries nobody else is asking\n * for, and its own ISR entry is already the cache for them.\n *\n * ## Why a cursor, and not the offset this replaces\n *\n * `.offset(n)` asks for a POSITION, and a listing takes its inserts at the\n * head, so every publish moves every position by one. The head pages and this\n * read are cached under different policies and revalidated by different\n * triggers — the publish fan-out refreshes the head eagerly and deliberately\n * stops there — so the two sides were routinely describing the collection as\n * it stood at two different moments, and the seam between them repeated an\n * entry or hid one for as long as the slower side lagged. `v1.0.0-beta.147`\n * shipped and `/changelog` showed `v1-0-0-beta-36` as both the last entry of\n * page 10 and the first of page 11.\n *\n * `startAfter(doc)` asks a question whose answer does not move: what follows\n * THIS entry. Publish a hundred entries at the head and this page returns the\n * same ten. The seam cannot drift because there is no longer a number on\n * either side of it to disagree about.\n *\n * `offset` also billed every document it skipped; a cursor bills none of them.\n */\nasync function readCollectionListingPage(options: {\n hostId: string\n collectionSlug: string\n /** Start after this document id — the older direction. */\n after?: string\n /** Start before this document id — the newer direction. */\n before?: string\n limit: number\n}): Promise<CollectionListingPage | null> {\n try {\n const collectionDoc = await findContentCollection(\n options.hostId,\n options.collectionSlug,\n )\n if (!collectionDoc) return null\n const entriesRef = collectionDoc.ref.collection('entries')\n\n const cursorId = options.before || options.after\n if (!cursorId) return null\n // A direct get, not a `where('slug', ...)` query: the cursor IS the\n // document name, which is the second field the read orders on, so the\n // snapshot it needs is one document rather than an index lookup.\n const cursorDoc = await entriesRef.doc(cursorId).get()\n // A cursor naming a document that no longer exists — deleted, or a URL\n // someone kept — cannot be positioned against. Null sends the caller back\n // to the cached head, which is a page the reader can act on.\n if (!cursorDoc.exists) return null\n\n // Backwards is the same query read the other way up, so both directions\n // rest on an index the project already deploys: `(status, publishedAt)`\n // exists ascending and descending both.\n const backwards = Boolean(options.before)\n const snapshot = await liveEntriesBase(entriesRef)\n .orderBy('publishedAt', backwards ? 'asc' : 'desc')\n .orderBy('__name__', backwards ? 'asc' : 'desc')\n .startAfter(cursorDoc)\n // One more than the page: the extra row is the whole of \"is there\n // another page\", and it replaces a `count()` over the collection.\n .limit(options.limit + 1)\n .get()\n\n const hasMore = snapshot.docs.length > options.limit\n const pageDocs = snapshot.docs.slice(0, options.limit)\n // Read backwards, the newest of the page came back last.\n const docs = backwards ? [...pageDocs].reverse() : pageDocs\n\n const due = docs.filter((entryDoc) => isDueScheduled(entryDoc.data()))\n const permission: SchedulePermission = due.length\n ? await scheduledPublishingPermission(options.hostId)\n : 'allowed'\n if (permission !== 'allowed') {\n for (const entryDoc of due) {\n flipDueEntry(entryDoc.ref, entryDoc.data(), permission)\n }\n }\n const entries = toLiveEntries(docs, permission)\n // The byline reads `authorName`, which a record-backed author only has\n // once resolved — the cached source does this for the entries it holds,\n // and a windowed page holds entries it never saw (AGL-2486).\n await attachEntryAuthors(options.hostId, entries)\n return { entries, hasMore }\n } catch (error) {\n // Fail open to the cached head rather than to a 500: the caller keeps\n // whatever it already had, which is a page the reader has seen before\n // rather than an error they cannot get past.\n console.error(error)\n return null\n }\n}\n\n/**\n * The cursor a retired `/{collection}/page/{n}` address redirects onto\n * (AGL-3219).\n *\n * This is the ONE place a position is still resolved, and it is deliberately\n * the only one: a 301 is served once, the reader lands on an address that\n * cannot drift afterwards, and whatever the position meant at that instant is\n * the page they would have got anyway. Everything downstream is cursors.\n *\n * Keys only — `select()` with no fields asks Firestore for document names and\n * nothing else — so the skipped documents are billed at the cheapest rate the\n * offset can be had for. Returns `''` when the position is past the end,\n * which is a 404 rather than a redirect to nowhere.\n */\nexport async function resolveCollectionPageCursor(options: {\n hostId: string\n collectionSlug: string\n /** 1-based page whose PREVIOUS entry is the cursor. */\n page: number\n perPage: number\n}): Promise<string> {\n const skip = (options.page - 1) * options.perPage - 1\n if (!Number.isFinite(skip) || skip < 0) return ''\n try {\n const collectionDoc = await findContentCollection(\n options.hostId,\n options.collectionSlug,\n )\n if (!collectionDoc) return ''\n const snapshot = await collectionDoc.ref\n .collection('entries')\n .where('status', 'in', ['published', 'scheduled'])\n .select()\n .orderBy('publishedAt', 'desc')\n .orderBy('__name__', 'desc')\n .offset(skip)\n .limit(1)\n .get()\n return snapshot.docs[0]?.id ?? ''\n } catch (error) {\n console.error(error)\n return ''\n }\n}\n\n/** Compose-time view of a collection: its live entries and its taxonomy. */\nexport interface PublishedCollectionSource {\n /**\n * The collection DOCUMENT this source was read from — its display name and\n * its template screen ids — or null when the slug names no content\n * collection.\n *\n * Carried so a routed listing can be served ENTIRELY from this cached\n * source. `getCollectionContent` used to resolve the same document itself\n * and then read the same entries again uncached, which meant `/blog`,\n * every `/blog/page/{n}`, every `/blog/category/{slug}` and the RSS feed\n * each paid a full collection read per regeneration while the identical\n * data already sat in this cache for every OTHER page on the site.\n */\n collection: CollectionContent['collection']\n entries: CollectionEntrySummary[]\n categories: CollectionCategory[]\n /**\n * Whether the read saw a schedule it is still waiting on — see\n * {@link LiveEntriesRead.pendingSchedule}. Never stored, only consulted by\n * the cache above, so no consumer has to know about it.\n */\n pendingSchedule?: boolean\n /**\n * Whether the entries read stopped at {@link COLLECTION_SOURCE_MAX}\n * (AGL-1516) — carried out of the loader because `entries.length` cannot\n * answer it once the liveness filter has run. Fail-open paths report\n * `false`: an empty result is not a bounded read, and describing it as one\n * would tell a reader their search covered less than it did.\n */\n reachedBound: boolean\n}\n\n/**\n * Published entries + category taxonomy for a collection resolved by slug —\n * the data source of the Collection entries block on arbitrary screens\n * (AGL-551/582). Fail-open: errors and unknown slugs resolve to an empty\n * list so a renamed collection never takes a published screen down.\n */\nexport async function getPublishedCollectionSource(options: {\n hostId: string\n collectionSlug: string\n}): Promise<PublishedCollectionSource> {\n try {\n return await withRenderCache({\n key: [\n 'tenant-collection-source',\n options.hostId,\n options.collectionSlug,\n ],\n revalidate: COLLECTION_SOURCE_TTL_SECONDS,\n tags: [tenantDataTag(options.hostId)],\n read: () => readPublishedCollectionSource(options),\n // A collection with a schedule still pending is SERVED but not STORED.\n //\n // No beat publishes a content entry — `flipDueEntry` during a render is\n // the whole mechanism — so storing this source would suppress the very\n // renders that would have noticed the entry coming due, and the post\n // would wait out the TTL rather than land at its time. Declining to\n // store leaves those collections exactly as uncached as they were\n // before this cache existed, which is the only cost this cache is not\n // allowed to reduce.\n //\n // Also refuses a collection that resolved to nothing, for the reason\n // `withRenderCache` states about negatives generally: a slug that\n // misses once must not miss for an hour.\n store: (value) => Boolean(value.collection) && !value.pendingSchedule,\n })\n } catch (error) {\n console.error(error)\n return readPublishedCollectionSource(options)\n }\n}\n\nasync function readPublishedCollectionSource(\n options: {\n hostId: string\n collectionSlug: string\n },\n): Promise<PublishedCollectionSource> {\n try {\n const collectionDoc = await findContentCollection(\n options.hostId,\n options.collectionSlug,\n )\n if (!collectionDoc) {\n return {\n collection: null,\n entries: [],\n categories: [],\n reachedBound: false,\n }\n }\n const { entries, reachedBound, pendingSchedule } = await listLiveEntries(\n collectionDoc.ref.collection('entries'),\n options.hostId,\n )\n // The compose-time source feeds the Collection entries block, whose byline\n // reads `authorName` — so a record-backed author has to be resolved here\n // too, or the block prints nothing for the entries a list page shows\n // (AGL-2486). This result is the cached one, which is what keeps the extra\n // read amortized across every page of the site that carries the block.\n await attachEntryAuthors(options.hostId, entries)\n return {\n collection: mapCollectionDoc(collectionDoc, options.collectionSlug),\n entries,\n categories: mapCollectionCategories(collectionDoc.get('categories')),\n reachedBound,\n ...(pendingSchedule ? { pendingSchedule: true } : {}),\n }\n } catch (error) {\n console.error(error)\n return {\n collection: null,\n entries: [],\n categories: [],\n reachedBound: false,\n }\n }\n}\n\n/** Entries-only view of {@link getPublishedCollectionSource} (AGL-551). */\nexport async function getPublishedCollectionEntries(options: {\n hostId: string\n collectionSlug: string\n}): Promise<CollectionEntrySummary[]> {\n return (await getPublishedCollectionSource(options)).entries\n}\n\n/**\n * Narrows a listing to its routed category and stamps its pagination\n * (AGL-1321 / AGL-620).\n *\n * Category first, ALWAYS: the two have to describe the same set. Counting\n * pages over the whole collection and then filtering would advertise pages\n * that render empty and hide entries that exist.\n *\n * `entriesReachedBound` is read by the caller BEFORE this runs, because a\n * category route hands its already-narrowed entries to compose and the\n * entries block's \"measure the raw set, not the filtered one\" rule then has\n * nothing raw left to measure (AGL-1516).\n */\nfunction applyCategoryAndPagination(\n data: CollectionContent,\n options: {\n page?: number\n perPage?: number\n categorySlug?: string\n },\n listing?: {\n /** Where `data.entries` begins in that collection's order. */\n windowStart?: number\n /** The shared read came back holding its own limit. */\n reachedBound?: boolean\n /**\n * The `perPage + 1` probe of a CURSOR page found an extra row — set only\n * when this listing was served by one, because only that read can answer\n * it (AGL-3219).\n */\n cursorHasMore?: boolean\n },\n): void {\n const { page = 1, perPage } = options\n const routedCategory = (options.categorySlug ?? '').trim()\n if (routedCategory) {\n const match = resolveCollectionCategoryBySlug(\n data.collection?.categories,\n routedCategory,\n )\n data.category = {\n slug: collectionCategorySlug(routedCategory),\n ...(match ? { id: match.id } : {}),\n name: match?.name ?? routedCategory,\n ...(match?.description ? { description: match.description } : {}),\n known: Boolean(match),\n }\n data.entries = data.entries.filter((entry) =>\n entryMatchesCategoryRoute(\n entry,\n { slug: routedCategory, ...(match ? { category: match } : {}) },\n data.collection?.categories,\n ),\n )\n }\n\n if (perPage && perPage > 0) {\n /*\n * The total is the COLLECTION's, not the read's (AGL-3213).\n *\n * `entries.length` was the count, and on a collection inside the bound it\n * still is — the two are the same number there. Past the bound it is the\n * size of the window, which is how `/changelog` advertised \"Page 10 of\n * 10\" while holding 166 entries and linking to 100 of them.\n *\n * A ROUTED CATEGORY keeps counting its own entries, because that is the\n * only honest number available here: the narrowing happens in memory over\n * the cached head, so both the count and the listing describe the same\n * bounded set. Paging a category past the bound needs its own ordered\n * query and a `(categoryId, status, publishedAt DESC)` index; until then\n * a category of a very large collection is capped, and says so by\n * agreeing with what it shows.\n */\n const windowStart = Number(listing?.windowStart)\n const windowed = Number.isFinite(windowStart) && windowStart > 0\n\n /*\n * The cursors, which are the pager's real answer (AGL-3219).\n *\n * `data.entries` is either EXACTLY this page — a cursor read — or the\n * whole cached head, which every listing address shares and each slices\n * its own page out of. So the page's own last entry is at the end of the\n * array in the first case and at `page * perPage - 1` in the second, and\n * the cursor is that entry's document id.\n */\n const pageEnd = windowed ? data.entries.length : page * perPage\n const last = data.entries[pageEnd - 1]\n const first = data.entries[windowed ? 0 : (page - 1) * perPage]\n\n /*\n * Is there an older page?\n *\n * A cursor page KNOWS, because its read asked for one more entry than it\n * needed and the extra row came back. The head has to reason: either it\n * is holding more entries than this page shows, or it is holding all it\n * could read and the read stopped at its own bound, which is the one\n * thing `entries.length` can never tell you about the collection.\n */\n const hasMore =\n listing?.cursorHasMore ??\n (data.entries.length > pageEnd ||\n (Boolean(listing?.reachedBound) && !routedCategory))\n\n /*\n * The deprecated total, stated ONLY where it can be true.\n *\n * A collection that fits inside one read can be counted, and a template\n * binding `{{pagination.totalPages}}` keeps rendering the number it\n * always did. Past the bound there is no honest total — the count and\n * the listing were reading the collection at two different moments, which\n * is what made the seam repeat an entry — so it is left absent rather\n * than asserted. A routed category counts its own narrowed set, which is\n * bounded by the same head and therefore countable.\n */\n const countable = routedCategory || !listing?.reachedBound\n const totalEntries = countable ? data.entries.length : undefined\n\n data.pagination = {\n page,\n perPage,\n nextCursor: hasMore && last?.$id ? last.$id : '',\n prevCursor: page > 1 && first?.$id ? first.$id : '',\n ...(totalEntries === undefined\n ? {}\n : {\n totalEntries,\n totalPages: collectionTotalPages(totalEntries, perPage),\n }),\n ...(windowed ? { windowStart } : {}),\n }\n }\n}\n\n/**\n * Resolves a non-screen path against the host's content collections\n * (Content Collections & Blog): `/{collectionSlug}` returns the published\n * entry list, `/{collectionSlug}/{entrySlug}` one entry. Fail-open — errors\n * resolve to `collection: null` and the caller 404s.\n *\n * A listing resolves only for a collection with a live entry (AGL-3101); one\n * with nothing live answers `collection: null` as well, so its listing, feed\n * and markdown twin are not public until its first entry is.\n */\nexport async function getCollectionContent(options: {\n hostId: string\n collectionSlug: string\n entrySlug?: string\n /**\n * 1-based list page (AGL-620), now a DISPLAY counter (AGL-3219): it labels\n * the page the reader is on and no read is positioned from it. The entries\n * come from `after`/`before`, or from the head of the cached source when\n * neither is set.\n */\n page?: number\n /** Entries per page (AGL-620); when set the list is paginated. */\n perPage?: number\n /**\n * Continue AFTER this entry's document id — the older direction (AGL-3219).\n *\n * What `/{collection}?after={id}` carries. A page defined this way does not\n * move when something is published above it, which is the whole reason the\n * addresses stopped being positions.\n */\n after?: string\n /** Continue BEFORE this entry's document id — the newer direction. */\n before?: string\n /**\n * The site's zone (AGL-3237). Stamped onto the returned content so every\n * reader downstream — including the client fallback renderer — formats from\n * the same string rather than from its own runtime.\n */\n timeZone?: string\n /**\n * Category segment of `/{collection}/category/{slug}` (AGL-1321). Filters\n * the listing before pagination is computed, so page counts and the page\n * windows describe the FILTERED set rather than the whole collection.\n */\n categorySlug?: string\n /**\n * Reveal the named entry even though the public site withholds it — the\n * live-site preview of a scheduled post (AGL-3205).\n *\n * ⛔ A VERIFIED GRANT, NOT A REQUEST. The caller passes `true` only after a\n * signed preview token has been checked against the resolved hostId AND\n * this exact `collectionSlug`/`entrySlug` (`verifyCollectionPreviewToken`).\n * The token format stays in the app that receives the URL; what crosses into\n * this lib is the verdict, so nothing here can be tricked by a payload's own\n * spelling of which entry it names.\n *\n * ENTRY ROUTES ONLY, and one entry at a time. It is ignored on a list route\n * — a preview of one post must not add it to `/blog`, to the feed, or to a\n * Collection entries block on any other page, all of which read the SHARED\n * cached source. Nothing it touches is cached at all.\n *\n * The preview render also writes NOTHING: see the `flipDueEntry` guard\n * below. Publishing a schedule stays the sole business of a public render.\n */\n previewUnpublishedEntry?: boolean\n}): Promise<CollectionContent> {\n const { hostId, collectionSlug, entrySlug } = options\n // Never on a list route, whatever the caller passed: `entrySlug` is what\n // makes the grant addressable at all, and the list is the shared cached\n // read this must stay out of.\n const preview = Boolean(options.previewUnpublishedEntry) && Boolean(entrySlug)\n const data: CollectionContent = {\n // Stamped before any early return, so every shape this function can hand\n // back carries it — including the empty one a 404 renders from.\n ...(options.timeZone ? { timeZone: options.timeZone } : {}),\n collection: null,\n entries: [],\n entry: null,\n pagination: null,\n category: null,\n error: null,\n }\n try {\n // A LIST route is served entirely from the CACHED source, which every\n // other page on the site already shares. It used to resolve the\n // collection and re-read its entries here, uncached, on every\n // regeneration of every listing address — `/blog`, nine `/blog/page/{n}`,\n // one `/blog/category/{slug}` per category, and the RSS feed — so a\n // collection of N live entries cost `1 + N + authors` reads per address\n // per window, for data byte-identical to what the cache was already\n // holding for the home page's \"Latest posts\" rail.\n //\n // An ENTRY route stays where it was: it reads ONE document by slug and\n // has nothing to share.\n if (!entrySlug) {\n const source = await getPublishedCollectionSource({\n hostId,\n collectionSlug,\n })\n if (!source.collection) return data\n // A collection is not a PAGE until something in it is live (AGL-3101).\n // Without this, creating one publishes `/{slug}` at once — an empty\n // listing with a feed and a markdown twin, before a word of it is\n // written. Answering it as no collection makes every listing address\n // 404 the way an unknown slug does, until the first entry is published\n // or its schedule comes due.\n //\n // Read off the UNFILTERED live set, before the category narrows it, so\n // an empty category of a live collection still renders. A read that\n // stopped at its bound cannot prove the collection empty — the live\n // entries may be past it — so that one keeps its listing. The rule\n // lives here and not in the source above: the source also feeds the\n // Collection entries block and the author page, and to them an empty\n // collection is an empty list, not a missing one.\n if (!source.entries.length && !source.reachedBound) return data\n data.collection = source.collection\n data.entries = source.entries\n data.entriesReachedBound = source.reachedBound\n /*\n * A page that starts past the cached read is served by its own window\n * (AGL-3213). Everything before that point comes out of the shared\n * source, so the pages a reader actually visits stay free.\n *\n * Only the unfiltered listing: a category route narrows in memory over\n * the same head, and a window read of the whole collection would hand\n * it ten entries of which any number may belong to another category.\n */\n const { page = 1, perPage } = options\n const cursor = (options.after ?? options.before ?? '').trim()\n let windowStart = 0\n let cursored: CollectionListingPage | null = null\n /*\n * A cursor address is served by its own read (AGL-3219). Everything\n * reachable without one comes out of the shared source, so the pages a\n * reader actually visits stay free.\n *\n * Only the unfiltered listing: a category route narrows in memory over\n * the same head, and a cursor read of the whole collection would hand it\n * ten entries of which any number belong to another category.\n */\n if (perPage && perPage > 0 && cursor && !(options.categorySlug ?? '').trim()) {\n cursored = await readCollectionListingPage({\n hostId,\n collectionSlug,\n ...(options.before ? { before: options.before } : { after: cursor }),\n limit: perPage,\n })\n // Null means the cursor read failed, or named a document that is\n // gone. The cached head is the better answer than an empty page: the\n // reader sees the newest entries rather than nothing at all.\n if (cursored) {\n data.entries = cursored.entries\n /*\n * `entries` is now EXACTLY this page, and both windowing sites\n * slice `[(page - 1) * perPage, …)`. Declaring the window to start\n * at that same offset makes their subtraction come out at zero, so\n * they take the page whole.\n *\n * Both sides of the subtraction are built from the same `page`, so\n * a hand-edited counter in a URL cancels itself out: the label is\n * wrong and the entries are still this cursor's page.\n */\n windowStart = (page - 1) * perPage\n }\n }\n applyCategoryAndPagination(data, options, {\n windowStart,\n reachedBound: source.reachedBound,\n ...(cursored ? { cursorHasMore: cursored.hasMore } : {}),\n })\n return data\n }\n\n const collectionDoc = await findContentCollection(hostId, collectionSlug)\n if (!collectionDoc) return data\n data.collection = mapCollectionDoc(collectionDoc, collectionSlug)\n\n const entryQuery = await collectionDoc.ref\n .collection('entries')\n .where('slug', '==', entrySlug)\n .limit(5)\n .get()\n // Same two-step as `listLiveEntries`: only pay for the org read when\n // something is due, and record the refusal on its own pass because a\n // refused entry never becomes the `entryDoc` below (AGL-471).\n //\n // A PREVIEW RENDER SKIPS BOTH WRITES (AGL-3205). `flipDueEntry` is the\n // entire publishing mechanism for a content entry, and it is a mechanism\n // that belongs to the PUBLIC render: a preview is one person looking at\n // one post through a link, and it must not be able to publish it, nor to\n // burn its schedule with the terminal refusal marker. Skipping the writes\n // costs nothing — the next public render asks the same questions and\n // writes the same answers — and it is what keeps \"nothing but a render\n // publishes a content entry\" true of renders anybody can reach.\n const dueHere = entryQuery.docs.filter((docSnapshot) =>\n isDueScheduled(docSnapshot.data()),\n )\n const permission: SchedulePermission = dueHere.length\n ? await scheduledPublishingPermission(hostId)\n : 'allowed'\n if (permission !== 'allowed' && !preview) {\n for (const docSnapshot of dueHere) {\n flipDueEntry(docSnapshot.ref, docSnapshot.data(), permission)\n }\n }\n /**\n * What a grant reveals: an entry this collection HOLDS and the site does\n * not serve.\n *\n * Deliberately not routed through `isLive`, which is the public answer and\n * has one other reader (`entry-link-routes`) whose whole job is to agree\n * with it. A second, wider answer inside it would make a LINK to a\n * previewed post resolve on the public site.\n *\n * Every status but `published` qualifies, which is `draft` as well as\n * `scheduled`: the ask is \"let me see it before it goes out\", and a post\n * is most worth looking at before its schedule is set. The blast radius is\n * the same either way — one entry, named in the signature, on one host.\n */\n const entryDoc =\n entryQuery.docs.find((docSnapshot) =>\n isLive(docSnapshot.data(), permission),\n ) ?? (preview ? entryQuery.docs[0] : undefined)\n if (entryDoc) {\n const value = entryDoc.data()\n if (!preview) flipDueEntry(entryDoc.ref, value, permission)\n if (preview && !isLive(value, permission)) {\n // The facts the preview chrome states back to the reader, so the page\n // cannot be mistaken for the published post. Read from the stored\n // document rather than inferred from the render.\n data.entryPreview = {\n status: String(value['status'] ?? 'draft'),\n publishAtSeconds:\n typeof value['publishAt']?.seconds === 'number'\n ? value['publishAt'].seconds\n : null,\n }\n }\n data.entry = {\n $id: entryDoc.id,\n title: value['title'] ?? entrySlug,\n slug: entrySlug,\n body: value['body'] ?? '',\n ...mapEntryFields(value),\n publishedAt: (value['publishedAt'] ?? value['publishAt'])\n ? {\n seconds: (value['publishedAt'] ?? value['publishAt']).seconds,\n }\n : null,\n }\n await attachEntryAuthors(hostId, [data.entry])\n }\n } catch (error) {\n console.error(error)\n data.error = error\n }\n return data\n}\n\nexport default getCollectionContent\n"],"names":["AUTHORS_MAX_PER_HOST","collectionCategorySlug","checkEntitlement","COLLECTION_SOURCE_MAX","collectionTotalPages","entryMatchesCategoryRoute","hostCollectionKind","normalizeContentAuthor","normalizeContentSchemaType","resolveCollectionCategoryBySlug","resolveEntryAuthor","firebaseAdmin","getOrgForHost","PUBLISHED_SITE_DATA_TTL_SECONDS","tenantDataTag","withRenderCache","COLLECTION_SOURCE_TTL_SECONDS","findContentCollection","hostId","collectionSlug","matches","app","firestore","collection","doc","where","limit","get","docs","find","docSnapshot","data","mapEntryFields","value","excerpt","authorName","authorId","coverImage","coverImageAlt","coverVideo","seoTitle","seoDescription","categoryId","category","tags","Array","isArray","filter","tag","updatedAt","seconds","mapCollectionCategories","item","id","trim","name","map","description","mapCollectionDoc","collectionDoc","$id","displayName","slug","templateScreenId","undefined","listScreenId","entryScreenId","schemaType","excludeEntriesFromSearch","categories","attachEntryAuthors","entries","ids","Set","entry","Boolean","slice","authors","length","authorsRef","snapshots","getAll","snapshot","exists","author","error","console","ENTRY_SCHEDULE_SKIPPED","scheduleAlreadyRefused","isDueScheduled","Number","POSITIVE_INFINITY","Date","now","isPendingScheduled","scheduledPublishingPermission","org","isLive","permission","flipDueEntry","docRef","update","scheduleStatus","catch","status","publishedAt","LIVE_ENTRY_FIELDS","SCHEDULED_SOURCE_MAX","liveEntriesBase","entriesRef","select","readLiveEntryDocs","dated","orderBy","scheduled","reachedBound","undated","entryDoc","seen","has","add","push","unordered","toLiveEntries","ref","title","sort","a","b","listLiveEntries","due","pendingSchedule","some","readCollectionListingPage","options","cursorId","before","after","cursorDoc","backwards","startAfter","hasMore","pageDocs","reverse","resolveCollectionPageCursor","skip","page","perPage","isFinite","offset","getPublishedCollectionSource","key","revalidate","read","readPublishedCollectionSource","store","getPublishedCollectionEntries","applyCategoryAndPagination","listing","routedCategory","categorySlug","match","known","windowStart","windowed","pageEnd","last","first","cursorHasMore","countable","totalEntries","pagination","nextCursor","prevCursor","totalPages","getCollectionContent","entrySlug","preview","previewUnpublishedEntry","timeZone","entryQuery","source","entriesReachedBound","cursor","cursored","dueHere","entryPreview","String","publishAtSeconds","body"],"mappings":";AAAA;;;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