@murumets-ee/content 0.37.0 → 0.38.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/admin.mjs +1 -1
- package/dist/chrome-provider.d.mts +107 -0
- package/dist/chrome-provider.d.mts.map +1 -0
- package/dist/chrome-provider.mjs +2 -0
- package/dist/chrome-provider.mjs.map +1 -0
- package/dist/client.mjs +1 -1
- package/dist/client.mjs.map +1 -1
- package/dist/entities/index.d.mts +32 -10
- package/dist/entities/index.d.mts.map +1 -1
- package/dist/entities/index.mjs.map +1 -1
- package/dist/index-Bsmju0UF.d.mts.map +1 -1
- package/dist/index.mjs +1 -1
- package/dist/index.mjs.map +1 -1
- package/dist/{locale-utils-Dyw5qWDf.mjs → locale-utils-DFEk4CE9.mjs} +2 -2
- package/dist/{locale-utils-Dyw5qWDf.mjs.map → locale-utils-DFEk4CE9.mjs.map} +1 -1
- package/dist/plugin-BSxbiGc1.mjs +2 -0
- package/dist/plugin-BSxbiGc1.mjs.map +1 -0
- package/dist/plugin.mjs +1 -1
- package/dist/query-client.mjs +1 -1
- package/dist/resolve-context-BVk6uObB.mjs +2 -0
- package/dist/resolve-context-BVk6uObB.mjs.map +1 -0
- package/dist/resolve.d.mts +19 -10
- package/dist/resolve.d.mts.map +1 -1
- package/dist/resolve.mjs +1 -1
- package/dist/resolve.mjs.map +1 -1
- package/dist/{routes-D3dzAfQw.mjs → routes-Bc9DcaPk.mjs} +2 -2
- package/dist/{routes-D3dzAfQw.mjs.map → routes-Bc9DcaPk.mjs.map} +1 -1
- package/dist/schema-BJxAwPrI.mjs.map +1 -1
- package/package.json +13 -9
- package/dist/plugin-BTynhZMx.mjs +0 -2
- package/dist/plugin-BTynhZMx.mjs.map +0 -1
- package/dist/resolve-context-p3m6gn3_.mjs +0 -2
- package/dist/resolve-context-p3m6gn3_.mjs.map +0 -1
package/dist/resolve.d.mts
CHANGED
|
@@ -120,8 +120,11 @@ interface ResolveNoneResult {
|
|
|
120
120
|
type ResolveResult = ResolveDocumentResult | ResolveRedirectResult | ResolveNoneResult;
|
|
121
121
|
/**
|
|
122
122
|
* Is `(entityType, entityId)` published in `locale`? Backed by
|
|
123
|
-
* `QueryClient.findById
|
|
124
|
-
*
|
|
123
|
+
* `QueryClient.findById`, which applies the publish filter for any principal
|
|
124
|
+
* WITHOUT `view_unpublished` (D017) — so the answer is only "published" if the
|
|
125
|
+
* injected client's context withholds that action, which the real one
|
|
126
|
+
* (`resolve-context.ts`'s reach context) does. See {@link createPublishChecker}.
|
|
127
|
+
* `resolveDraftPath` bypasses this entirely.
|
|
125
128
|
*/
|
|
126
129
|
interface PublishChecker {
|
|
127
130
|
isPublished(entityType: string, entityId: string, locale: string): Promise<boolean>;
|
|
@@ -187,8 +190,11 @@ declare function getCanonicalPath(entityType: string, entityId: string, locale:
|
|
|
187
190
|
* Build a {@link PublishChecker} from an entity resolver + a query-client
|
|
188
191
|
* factory. `isPublished` is `false` for an unknown entity type, else
|
|
189
192
|
* `findById(id, { locale }) !== null` — a non-null result means "published in
|
|
190
|
-
* that locale" because `QueryClient`
|
|
191
|
-
*
|
|
193
|
+
* that locale" because `QueryClient` applies the publish filter (and excludes
|
|
194
|
+
* trashed rows) for every principal without `view_unpublished` (D017). The
|
|
195
|
+
* factory therefore has to hand back a client whose context withholds that
|
|
196
|
+
* action; `resolve-context.ts`'s reach context is the one in-repo
|
|
197
|
+
* implementation and does. F027 point 1.
|
|
192
198
|
*/
|
|
193
199
|
declare function createPublishChecker(deps: {
|
|
194
200
|
entityResolver: EntityResolver;
|
|
@@ -299,9 +305,11 @@ type PathEnumReader = {
|
|
|
299
305
|
* Batch publish check: return the SUBSET of `entityIds` that is published in
|
|
300
306
|
* `locale`. Called ONCE per entity-type group per page. The concrete
|
|
301
307
|
* implementation (see `resolve-context.ts`) runs an elevated-context
|
|
302
|
-
* `QueryClient.findMany({ where: inArray(getTable().id, ids), locale })` —
|
|
303
|
-
*
|
|
304
|
-
*
|
|
308
|
+
* `QueryClient.findMany({ where: inArray(getTable().id, ids), locale })` — so no
|
|
309
|
+
* unpublished/trashed id comes back. Since D017 the publish filter is
|
|
310
|
+
* CONDITIONAL (it holds for any principal without `view_unpublished`); what
|
|
311
|
+
* keeps that true here is that the elevated context is a REACH context which
|
|
312
|
+
* withholds that action, not that the filter is unconditional.
|
|
305
313
|
*/
|
|
306
314
|
type PublishFilter = (entityType: string, entityIds: readonly string[], locale: string) => Promise<ReadonlySet<string>>;
|
|
307
315
|
/** One enumerated path row (phase 05 §2 — exact shape). */
|
|
@@ -541,9 +549,10 @@ declare function createHomepageReader(db: PostgresJsDatabase): HomepageReader;
|
|
|
541
549
|
* Build the deps for {@link import('./enumerate.js').enumeratePaths} — the
|
|
542
550
|
* `toolkit_paths` reader plus a BATCHED publish filter. `filterPublished` runs
|
|
543
551
|
* ONE elevated-context `QueryClient.findMany({ where: inArray(getTable().id,
|
|
544
|
-
* ids), locale })` per entity-type group (not per row) — the
|
|
545
|
-
*
|
|
546
|
-
*
|
|
552
|
+
* ids), locale })` per entity-type group (not per row) — the trash filter
|
|
553
|
+
* applies unconditionally, and the publish filter applies because the elevated
|
|
554
|
+
* context WITHHOLDS `view_unpublished` (D017; see file header), so no
|
|
555
|
+
* unpublished/trashed id is returned. An unknown/unregistered entity type yields the empty set (its
|
|
547
556
|
* rows are treated as unpublished → dropped, fail-closed).
|
|
548
557
|
*/
|
|
549
558
|
declare function buildEnumerateDeps(app: ToolkitApp): EnumeratePathsDeps;
|
package/dist/resolve.d.mts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"resolve.d.mts","names":[],"sources":["../src/redirects/target.ts","../src/paths/index-reader.ts","../src/paths/homepage.ts","../src/paths/resolve.ts","../src/paths/enumerate.ts","../src/paths/sitemap.ts","../src/paths/redirects-list.ts","../src/paths/resolve-context.ts"],"mappings":";;;;;;;KA8BY,cAAA;EACN,IAAA;EAAgB,MAAA;EAAgB,EAAA;AAAA;EAChC,IAAA;EAAa,GAAA;AAAA;EACb,IAAA;EAAc,IAAA;AAAA;;;;;;;;;AAHpB;;;;;;;;;;;;AAGwB;;;;ACJxB;;;;;;ADIwB,KCJZ,YAAA;EACV,UAAA;EACA,QAAA;EACA,MAAA;EACA,IAAA;EACA,WAAA;AAAA;;KAIU,cAAA;EACV,UAAA;EACA,QAAA;EACA,MAAA;EACA,IAAA;EACA,WAAA;AAAA;AAAW;AAAA,KAID,eAAA;EACV,OAAA,CAAQ,KAAA,EAAO,cAAA,GAAiB,OAAA,CAAQ,YAAA;EACxC,QAAA,CAAS,OAAA;IACP,KAAA,GAAQ,cAAA,EAF8B;IAItC,OAAA,GAAU,KAAA;MAAQ,MAAA;MAAqB,GAAA;IAAA;IACvC,KAAA;EAAA,IACE,OAAA,CAAQ,YAAA;AAAA;;;;UClCG,eAAA;EACf,MAAA;EACA,EAAE;AAAA;ADOJ;;;;AAAA,cCAa,qBAAA,EAAqB,CAAA,CAAA,SAAA;;;;;;;;;;;;;;iBASlB,oBAAA,CAAqB,KAAA,YAAiB,eAAe;;;;UCEpD,qBAAA;EACf,IAAA;EACA,UAAA;EACA,EAAA;AAAA;;UAGe,qBAAA;EACf,IAAA;EACA,EAAA;EACA,MAAA;AAAA;AFNW;AAAA,UESI,iBAAA;EACf,IAAI;AAAA;AAAA,KAEM,aAAA,GAAgB,qBAAA,GAAwB,qBAAA,GAAwB,iBAAA
|
|
1
|
+
{"version":3,"file":"resolve.d.mts","names":[],"sources":["../src/redirects/target.ts","../src/paths/index-reader.ts","../src/paths/homepage.ts","../src/paths/resolve.ts","../src/paths/enumerate.ts","../src/paths/sitemap.ts","../src/paths/redirects-list.ts","../src/paths/resolve-context.ts"],"mappings":";;;;;;;KA8BY,cAAA;EACN,IAAA;EAAgB,MAAA;EAAgB,EAAA;AAAA;EAChC,IAAA;EAAa,GAAA;AAAA;EACb,IAAA;EAAc,IAAA;AAAA;;;;;;;;;AAHpB;;;;;;;;;;;;AAGwB;;;;ACJxB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AAA,EAAK,UAAA,GAAa,uBAAuB;;;ANhH5D;;;;AClC1B;;iBK0MgB,gBAAA,CAAiB,GAAA,EAAK,UAAA,GAAa,WAAW;;ALxM1D;AAOJ;;;;;;;;iBKmNgB,sBAAA,CAAuB,GAAA,EAAK,UAAA,GAAa,iBAAiB;;;;;;;;iBAiB1D,gBAAA,CAAiB,GAAA,EAAK,UAAA,GAAa,eAAA,GAAkB,cAAA"}
|
package/dist/resolve.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as e,c as t,d as n,i as r,n as i,o as a,r as o,s,t as c,u as l}from"./resolve-context-
|
|
1
|
+
import{a as e,c as t,d as n,i as r,n as i,o as a,r as o,s,t as c,u as l}from"./resolve-context-BVk6uObB.mjs";import{a as u,c as d,g as f,i as p,o as m,p as h,r as g,s as _}from"./schema-BJxAwPrI.mjs";async function*v(e,t,n={}){let r=n.pageSize??200,i=n.publishConcurrency??5,{locale:a,entityType:o}=e,s=e.afterId;for(;;){let e={locale:a,isCanonical:!0};o!==void 0&&(e.entityType=o),s!==void 0&&(e.id={gt:s});let n=await t.pathsClient.findMany({where:e,orderBy:[{column:`id`,dir:`asc`}],limit:r});if(n.length===0)break;let c=new Map;for(let e of n){let t=c.get(e.entityType);t?t.push(e):c.set(e.entityType,[e])}let l=new Map;await f([...c.entries()],i,async([e,n])=>{let r=await t.filterPublished(e,n.map(e=>e.entityId),a);l.set(e,r)});for(let e of n)l.get(e.entityType)?.has(e.entityId)&&(yield{path:e.path,entityType:e.entityType,id:e.entityId,updatedAt:e.updatedAt});let u=n[n.length-1];if(!u||(s=u.id,n.length<r))break}}async function y(e,t,n,r){let i=new Map;for(let a=0;a<t.length;a+=500){let o=t.slice(a,a+500),s=await r.pathsClient.findMany({where:{entityType:e,locale:n,isCanonical:!0,entityId:{in:[...o]}},limit:o.length});for(let e of s)i.set(e.entityId,e.path)}return i}const b=4e4,x=`sitemap.xml`;async function*S(e,t,n={}){let r=N(e.maxUrlsPerFile,b),i=N(n.batchSize,200),a=A(e.baseUrl),o=[];for(let s of e.locales){let c=[],l=null,u=0,d=()=>{if(c.length===0)return null;let e=M(s,u),t=(l??new Date).toISOString(),n={kind:`urlset`,filename:e,xml:T(c)};return o.push({filename:e,lastmod:t}),c=[],l=null,u+=1,n},f=v({locale:s},t.enumerate,n.enumerate);for await(let n of P(f,i)){let i=await w(n,s,t);if(i.length===0)continue;let o=await C(i,s,e,t);for(let t of i){let n=o.get(t.id)??[{locale:s,path:t.path}];if(c.push(E(t,s,n,e,a)),(l===null||t.updatedAt>l)&&(l=t.updatedAt),c.length>=r){let e=d();e&&(yield e)}}}let p=d();p&&(yield p)}o.length>1&&(yield{kind:`index`,filename:x,xml:D(o,a)})}async function C(e,t,n,r){let i=new Map;for(let n of e)i.set(n.id,[{locale:t,path:n.path}]);let a=n.locales.filter(e=>e!==t);if(a.length===0)return i;let o=new Map;for(let t of e){let e=o.get(t.entityType);e?e.push(t.id):o.set(t.entityType,[t.id])}for(let e of a)for(let[t,n]of o){let a=await y(t,n,e,r.canonicalBatch);if(a.size===0)continue;let o=[...a.keys()],s=await r.enumerate.filterPublished(t,o,e),c=r.filterNoIndex===void 0?void 0:await r.filterNoIndex(t,o,e);for(let[t,n]of a){if(!s.has(t)||c?.has(t))continue;let r=i.get(t);r&&r.push({locale:e,path:n})}}return i}async function w(e,t,n){let r=n.filterNoIndex;if(r===void 0)return[...e];let i=new Map;for(let t of e){let e=i.get(t.entityType);e?e.push(t.id):i.set(t.entityType,[t.id])}let a=new Map;return await f([...i.entries()],5,async([e,n])=>{a.set(e,await r(e,n,t))}),e.filter(e=>!a.get(e.entityType)?.has(e.id))}function T(e){return`<?xml version="1.0" encoding="UTF-8"?>
|
|
2
2
|
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xhtml="http://www.w3.org/1999/xhtml">\n${e.join(`
|
|
3
3
|
`)}\n</urlset>\n`}function E(e,t,n,r,i){let a=k(i,r.prefix,t,e.path),o=n.map(e=>` ${O(e.locale,k(i,r.prefix,e.locale,e.path))}`),s=n.find(e=>e.locale===r.defaultLocale);return s&&o.push(` ${O(`x-default`,k(i,r.prefix,s.locale,s.path))}`),` <url>
|
|
4
4
|
<loc>${j(a)}</loc>\n <lastmod>${e.updatedAt.toISOString()}</lastmod>\n${o.join(`
|
package/dist/resolve.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"resolve.mjs","names":[],"sources":["../src/paths/enumerate.ts","../src/paths/sitemap.ts","../src/paths/redirects-list.ts"],"sourcesContent":["/**\n * Path enumeration for SSG / sitemaps (plan/routing PR06; phase\n * `05-resolution-and-enumeration-api.md` §2).\n *\n * `enumeratePaths` streams the PUBLISHED canonical `(path, entityType, id,\n * updatedAt)` rows for one locale. It powers `getStaticPaths` + the sitemap\n * helper, so it must NEVER leak an unpublished document (CLAUDE.md #1 — the\n * output feeds public build artifacts).\n *\n * **Security + availability.** Two properties matter here:\n * 1. *No unpublished leak.* `toolkit_paths` carries no publish-status column,\n * so each page's rows are publish-checked against the live entity via the\n * injected {@link EnumeratePathsDeps.filterPublished} — an unpublished (or\n * trashed) document is dropped from the stream.\n * 2. *No unbounded fan-out* (CLAUDE.md \"no amplification\"). Work is bounded by\n * PAGE SIZE, not by total document count: rows are keyset-paginated on the\n * immutable `id` PK (one index query per page), and the publish check is\n * BATCHED — ONE call per distinct entity-type bucket per page (a handful of\n * types at most; the routable set is config-time-fixed, never\n * attacker-influenced), never one call per row.\n *\n * **Leaf module.** Every cross-package dependency (the index reader, the publish\n * filter) is injected via `deps`; this module imports no `@murumets-ee/core` and\n * no `server-only` graph. Concrete deps are built from an app in\n * `./resolve-context.ts` (`buildEnumerateDeps`), keeping the resolution surface\n * off the `lumi` CLI command graph (F027 guardrail).\n *\n * Function-form-path entities need NO special handling — their rows were already\n * materialized into `toolkit_paths` at write time (F004 / phase 05 §2), so a\n * plain index read includes them.\n */\n\nimport { mapBounded } from './apply-path.js'\n\n// ---------------------------------------------------------------------------\n// Read surface (a `type` alias, per index-reader.ts's Deviation-1 rationale, so\n// the real `ToolkitPathsClient` stays assignable to it without any cast).\n// ---------------------------------------------------------------------------\n\n/** The projected `toolkit_paths` row the enumeration + batch lookup read. */\nexport type PathEnumRow = {\n id: string\n entityType: string\n entityId: string\n locale: string\n path: string\n updatedAt: Date\n}\n\n/**\n * The (operator-carrying) where shapes enumeration issues: keyset `id > cursor`,\n * `entityId IN (...)` for the batch lookup, plus plain-value equality filters.\n * A subset of the real client's `ColumnOperators` where-clause, so the real\n * `ToolkitPathsClient` is assignable to {@link PathEnumReader}.\n */\nexport type PathEnumWhere = {\n id?: { gt: string }\n entityType?: string\n entityId?: { in: string[] }\n locale?: string\n path?: string\n isCanonical?: boolean\n}\n\n/**\n * The batched keyset read surface {@link enumeratePaths} / {@link getCanonicalPaths}\n * need. NARROWER than Task 1's point-lookup `PathIndexReader` (which only orders\n * by `updatedAt` and takes plain-value where): enumeration needs `id`-ordering,\n * a `{ gt }` cursor, and `{ in }` batching. Construct the real client directly\n * (`toolkitPathsTable.makeClient(db)`) — it satisfies this type.\n */\nexport type PathEnumReader = {\n findMany(options: {\n where?: PathEnumWhere\n orderBy?: Array<{ column: 'id'; dir?: 'asc' | 'desc' }>\n limit?: number\n }): Promise<PathEnumRow[]>\n}\n\n/**\n * Batch publish check: return the SUBSET of `entityIds` that is published in\n * `locale`. Called ONCE per entity-type group per page. The concrete\n * implementation (see `resolve-context.ts`) runs an elevated-context\n * `QueryClient.findMany({ where: inArray(getTable().id, ids), locale })` — the\n * publish + trash filters apply unconditionally, so no unpublished/trashed id\n * comes back.\n */\nexport type PublishFilter = (\n entityType: string,\n entityIds: readonly string[],\n locale: string,\n) => Promise<ReadonlySet<string>>\n\n// ---------------------------------------------------------------------------\n// Public surface\n// ---------------------------------------------------------------------------\n\n/** One enumerated path row (phase 05 §2 — exact shape). */\nexport interface PathEntry {\n path: string\n entityType: string\n id: string\n updatedAt: Date\n}\n\n/** Options for {@link enumeratePaths} (phase 05 §2 — exact shape). */\nexport interface EnumeratePathsOptions {\n /** Enumerate this locale's canonical rows only. */\n locale: string\n /** Optionally narrow to a single routable entity type. */\n entityType?: string\n /**\n * Resume the keyset AFTER this `toolkit_paths` row id (exclusive); omit to\n * start from the beginning. The value is the opaque `toolkit_paths` PK the\n * internal page cursor advances on — NOT the yielded `PathEntry.id`, which is\n * the DOCUMENT (entity) id. A cross-request paginating caller (e.g. the\n * content-api `_paths` endpoint) resolves the last consumed entry's row PK and\n * passes it here to continue exactly where the prior page stopped, with no row\n * skipped or repeated. Fully backward-compatible: existing callers omit it and\n * traverse from the start unchanged.\n */\n afterId?: string\n}\n\n/** Injected dependencies for {@link enumeratePaths}. */\nexport interface EnumeratePathsDeps {\n pathsClient: PathEnumReader\n filterPublished: PublishFilter\n}\n\n/** Internal tuning seam (page size / batch concurrency). Real callers omit it. */\nexport interface EnumeratePathsTuning {\n /** Rows per index page. Defaults to {@link ENUMERATE_PAGE_SIZE}. Tests force a small value. */\n pageSize?: number\n /** Peak concurrent publish-check groups. Defaults to {@link PUBLISH_CHECK_CONCURRENCY}. */\n publishConcurrency?: number\n}\n\n/**\n * Index page size — mirrors the rebuild job's `REBUILD_PAGE_SIZE`. Must stay\n * ≤ the `defineTable` `MAX_LIMIT` (1000), which THROWS rather than clamps.\n */\nconst ENUMERATE_PAGE_SIZE = 200\n\n/**\n * Peak concurrent publish-check groups per page. A page holds a handful of\n * distinct entity types at most, so this bound is rarely reached — it exists so\n * the fan-out is EXPLICITLY capped (CLAUDE.md), never `Promise.all` over an\n * unbounded set.\n */\nconst PUBLISH_CHECK_CONCURRENCY = 5\n\n/**\n * Stream the published canonical paths for `opts.locale` (optionally narrowed to\n * `opts.entityType`), keyset-paginated with a per-page batched publish filter.\n * See the module header for the security + fan-out guarantees.\n */\nexport async function* enumeratePaths(\n opts: EnumeratePathsOptions,\n deps: EnumeratePathsDeps,\n tuning: EnumeratePathsTuning = {},\n): AsyncGenerator<PathEntry> {\n const pageSize = tuning.pageSize ?? ENUMERATE_PAGE_SIZE\n const concurrency = tuning.publishConcurrency ?? PUBLISH_CHECK_CONCURRENCY\n const { locale, entityType } = opts\n\n // Seed from `opts.afterId` so a caller can resume mid-stream; undefined starts\n // at the beginning (every existing caller's behavior, unchanged).\n let cursorId: string | undefined = opts.afterId\n for (;;) {\n // Keyset cursor on the immutable `id` PK (the rebuild job's precedent):\n // visits every canonical row exactly once even under concurrent mutation,\n // which OFFSET paging cannot guarantee.\n const where: PathEnumWhere = { locale, isCanonical: true }\n if (entityType !== undefined) where.entityType = entityType\n if (cursorId !== undefined) where.id = { gt: cursorId }\n\n const page = await deps.pathsClient.findMany({\n where,\n orderBy: [{ column: 'id', dir: 'asc' }],\n limit: pageSize,\n })\n if (page.length === 0) break\n\n // Group this page's rows by entity type (bounded: the routable-type set is\n // small + config-fixed), then ONE publish check per group.\n const byType = new Map<string, PathEnumRow[]>()\n for (const row of page) {\n const bucket = byType.get(row.entityType)\n if (bucket) bucket.push(row)\n else byType.set(row.entityType, [row])\n }\n\n const publishedByType = new Map<string, ReadonlySet<string>>()\n await mapBounded([...byType.entries()], concurrency, async ([type, rows]) => {\n const published = await deps.filterPublished(\n type,\n rows.map((r) => r.entityId),\n locale,\n )\n publishedByType.set(type, published)\n })\n\n // Yield only the page's PUBLISHED rows, preserving the id-ascending order.\n for (const row of page) {\n if (publishedByType.get(row.entityType)?.has(row.entityId)) {\n yield { path: row.path, entityType: row.entityType, id: row.entityId, updatedAt: row.updatedAt }\n }\n }\n\n // Advance the cursor to the last (max-id) row of this raw page. `page` is\n // non-empty here (length-0 broke above). Publish-filtering is a POST-filter,\n // so the cursor always steps over every index row regardless of publish state.\n const lastRow = page[page.length - 1]\n if (!lastRow) break\n cursorId = lastRow.id\n if (page.length < pageSize) break\n }\n}\n\n// ---------------------------------------------------------------------------\n// getCanonicalPaths — batched forward lookup (search url re-point), NO publish filter\n// ---------------------------------------------------------------------------\n\n/** Deps for {@link getCanonicalPaths}. */\nexport interface CanonicalPathsBatchDeps {\n pathsClient: PathEnumReader\n}\n\n/**\n * Max ids per batched index query — well under `defineTable`'s `MAX_LIMIT`\n * (1000, which throws rather than clamps). Search result pages are far smaller\n * than this, so this is one query in practice; larger id sets chunk safely.\n */\nconst CANONICAL_BATCH_SIZE = 500\n\n/**\n * The current canonical paths for many `(entityType, entityId)` in ONE locale,\n * as an `entityId → path` map — the batched sibling of `getCanonicalPath`.\n *\n * **No publish filter — deliberate**, matching `getCanonicalPath` (and the\n * search url builder it re-points): a search result's url is display-only and\n * the caller already gates row visibility. One index query per {@link\n * CANONICAL_BATCH_SIZE}-sized chunk (one query total for a normal search page),\n * so it never fans out per row.\n */\nexport async function getCanonicalPaths(\n entityType: string,\n entityIds: readonly string[],\n locale: string,\n deps: CanonicalPathsBatchDeps,\n): Promise<Map<string, string>> {\n const result = new Map<string, string>()\n for (let i = 0; i < entityIds.length; i += CANONICAL_BATCH_SIZE) {\n const chunk = entityIds.slice(i, i + CANONICAL_BATCH_SIZE)\n const rows = await deps.pathsClient.findMany({\n where: { entityType, locale, isCanonical: true, entityId: { in: [...chunk] } },\n limit: chunk.length,\n })\n for (const row of rows) result.set(row.entityId, row.path)\n }\n return result\n}\n","/**\n * Sitemap generation for the routed content surface (plan/routing PR07; phase\n * `05-resolution-and-enumeration-api.md` §4).\n *\n * `generateSitemap` streams the standard-protocol sitemap document set for the\n * configured locales: one `<urlset>` per locale (split into numbered files at\n * {@link SitemapOptions.maxUrlsPerFile}), plus a `<sitemapindex>` when the run\n * produced more than one file. Each `<url>` carries a `<lastmod>` (from the\n * enumerated `updatedAt`) and the full `xhtml:link` hreflang-alternates set —\n * including an `x-default` pointing at the default-locale URL. It is a PURE\n * generator, NOT an HTTP endpoint: the frontend recipe (PR08) mounts it in a\n * route handler; this module only produces the documents.\n *\n * **Security (CLAUDE.md #1).** The output feeds a public build artifact, so it\n * must NEVER leak an unpublished / trashed document. Two independent publish\n * gates apply:\n * 1. The primary rows come from {@link enumeratePaths}, which publish-filters\n * each page against the entity (unpublished/trashed dropped) for the\n * sitemap's OWN locale.\n * 2. The cross-locale hreflang alternates come from {@link getCanonicalPaths},\n * which does NOT publish-filter (it is a display-only forward index read).\n * So this module ADDITIONALLY runs the same batched `filterPublished` over\n * every candidate other-locale alternate before linking it — an\n * unpublished-in-that-locale document is never emitted as an alternate.\n *\n * **No unbounded fan-out (CLAUDE.md \"no amplification\").** The cross-locale\n * alternate lookup is BATCHED exactly like `enumeratePaths`'s own publish check:\n * per {@link SITEMAP_ALTERNATES_BATCH_SIZE}-sized chunk of enumerated rows, the\n * work is ONE `getCanonicalPaths` + ONE `filterPublished` per (entity-type\n * group × other locale) — bounded by (batch size × distinct routable types ×\n * locale count), NEVER one query per document. `getAlternates` (the per-document\n * N-locale function) is deliberately NOT used here — calling it per enumerated\n * row would be the O(rows × locales) amplification this bound forbids.\n *\n * **`noIndex` exclusion (PR 11's `seoMeta()`).** `SitemapDeps.filterNoIndex` is\n * an OPTIONAL batched dep, same shape as `filterPublished` (a `PublishFilter`)\n * but semantics-inverted: it returns the subset of ids that ARE `noIndex` in\n * the given locale. It lives on `deps`, not `opts`, because — like\n * `filterPublished` — a real implementation needs a DB read, and `noIndex` is\n * `translatable: true`, so the SAME callback must be invoked once per\n * (locale, entity-type group, batch) to see the right per-locale value; a\n * per-entry (locale-blind) predicate could not express this correctly. Omitted\n * → nothing excluded (current default). See `excludeNoIndexed`.\n *\n * **Leaf module.** Every cross-package dependency is injected via `deps`\n * ({@link SitemapDeps}); this module imports no `@murumets-ee/core` and no\n * `server-only` graph. Concrete deps are built from an app in\n * `./resolve-context.ts` (`buildSitemapDeps`).\n */\n\nimport { mapBounded } from './apply-path.js'\nimport {\n type CanonicalPathsBatchDeps,\n enumeratePaths,\n type EnumeratePathsDeps,\n type EnumeratePathsTuning,\n getCanonicalPaths,\n type PathEntry,\n type PublishFilter,\n} from './enumerate.js'\n\n// ---------------------------------------------------------------------------\n// Public surface\n// ---------------------------------------------------------------------------\n\n/** Options for {@link generateSitemap}. */\nexport interface SitemapOptions {\n /** The locales to emit a `<urlset>` for (configured content locales). */\n locales: readonly string[]\n /**\n * The default locale — its URL is the `x-default` hreflang target. Explicit\n * (NOT inferred from `locales` order) so callers stay unambiguous.\n */\n defaultLocale: string\n /** Absolute site origin, e.g. `https://example.com` (trailing slash tolerated). */\n baseUrl: string\n /**\n * Per-locale URL prefix rule (e.g. `(l) => l === 'en' ? '' : '/' + l`). The\n * frontend owns the locale-prefix convention (D002); omitted → no prefix.\n */\n prefix?: (locale: string) => string\n /**\n * Max `<url>` entries per file before splitting (sitemap protocol caps at\n * 50 000). Defaults to {@link DEFAULT_MAX_URLS_PER_FILE}.\n */\n maxUrlsPerFile?: number\n}\n\n/** Injected dependencies for {@link generateSitemap}. */\nexport interface SitemapDeps {\n /**\n * Deps for {@link enumeratePaths} — the `toolkit_paths` reader plus the\n * batched `filterPublished`. `filterPublished` is REUSED for the cross-locale\n * alternate publish gate (same batched shape), so no second publish surface is\n * needed.\n */\n enumerate: EnumeratePathsDeps\n /**\n * Deps for {@link getCanonicalPaths} — the batched cross-locale forward index\n * read (NO publish filter; this module applies `enumerate.filterPublished` on\n * top).\n */\n canonicalBatch: CanonicalPathsBatchDeps\n /**\n * Optional: batched `noIndex` check, same shape as `filterPublished` but\n * semantics-inverted — returns the subset of `entityIds` that ARE `noIndex`\n * in `locale` (PR 11's `seoMeta()`). Called at most once per (entity-type\n * group, batch), never once per entry — see `excludeNoIndexed`. Omitted →\n * nothing excluded (current default).\n */\n filterNoIndex?: PublishFilter\n}\n\n/** Internal tuning seam (batch size / enumerate page size). Real callers omit it. */\nexport interface SitemapTuning {\n /**\n * Enumerated rows per cross-locale alternate batch. Defaults to\n * {@link SITEMAP_ALTERNATES_BATCH_SIZE}. Tests force a small value to span\n * multiple batches. Bounds the per-batch fan-out (see module header).\n */\n batchSize?: number\n /** Passed through to {@link enumeratePaths} for its own paging/publish tuning. */\n enumerate?: EnumeratePathsTuning\n}\n\n/** One emitted sitemap document. */\nexport interface SitemapFile {\n /** `'urlset'` for a per-locale URL set, `'index'` for the sitemap index. */\n kind: 'urlset' | 'index'\n /**\n * Suggested filename served at `${baseUrl}/${filename}`. Per-locale urlsets are\n * `sitemap-<locale>.xml` (first) / `sitemap-<locale>-<n>.xml` (splits, n≥2);\n * the index is {@link SITEMAP_INDEX_FILENAME}.\n */\n filename: string\n /** The complete, well-formed XML document text (trailing newline included). */\n xml: string\n}\n\n/** Default `<url>` cap per file — under the sitemap protocol's 50 000 hard limit. */\nexport const DEFAULT_MAX_URLS_PER_FILE = 40_000\n\n/** Filename of the emitted sitemap index (referenced by the mounting route). */\nexport const SITEMAP_INDEX_FILENAME = 'sitemap.xml'\n\n/**\n * Enumerated rows per cross-locale alternate batch. Aligned with\n * `enumeratePaths`'s own page size so a batch is ~one enumeration page; the\n * exact value only affects HOW MANY batched lookups run, never their per-batch\n * bound (see module header). Never per-row.\n */\nconst SITEMAP_ALTERNATES_BATCH_SIZE = 200\n\n// ---------------------------------------------------------------------------\n// Generator\n// ---------------------------------------------------------------------------\n\n/** One resolved hreflang alternate (a published, canonical per-locale URL). */\ninterface Alternate {\n locale: string\n path: string\n}\n\n/**\n * Stream the sitemap document set for `opts.locales`. See the module header for\n * the security + fan-out guarantees. Yields each `<urlset>` file as it fills,\n * then a `<sitemapindex>` LAST iff more than one file was produced.\n */\nexport async function* generateSitemap(\n opts: SitemapOptions,\n deps: SitemapDeps,\n tuning: SitemapTuning = {},\n): AsyncGenerator<SitemapFile> {\n const maxUrls = normalizePositiveInt(opts.maxUrlsPerFile, DEFAULT_MAX_URLS_PER_FILE)\n const batchSize = normalizePositiveInt(tuning.batchSize, SITEMAP_ALTERNATES_BATCH_SIZE)\n const base = stripTrailingSlash(opts.baseUrl)\n\n /** (filename, lastmod) of every urlset file produced — feeds the index. */\n const producedFiles: Array<{ filename: string; lastmod: string }> = []\n\n for (const locale of opts.locales) {\n let buffer: string[] = []\n let bufferMaxUpdatedAt: Date | null = null\n let fileIndex = 0\n\n /** Flush the current buffer as a numbered urlset file (or return null if empty). */\n const flush = (): SitemapFile | null => {\n if (buffer.length === 0) return null\n const filename = urlsetFilename(locale, fileIndex)\n const lastmod = (bufferMaxUpdatedAt ?? new Date()).toISOString()\n const file: SitemapFile = { kind: 'urlset', filename, xml: buildUrlset(buffer) }\n producedFiles.push({ filename, lastmod })\n buffer = []\n bufferMaxUpdatedAt = null\n fileIndex += 1\n return file\n }\n\n const source = enumeratePaths({ locale }, deps.enumerate, tuning.enumerate)\n for await (const batch of chunkAsync(source, batchSize)) {\n // Exclude noIndex rows FIRST so they're never fetched cross-locale.\n const kept = await excludeNoIndexed(batch, locale, deps)\n if (kept.length === 0) continue\n\n // ONE batched cross-locale lookup per (entity-type group × other locale).\n const alternatesByEntry = await resolveAlternates(kept, locale, opts, deps)\n\n for (const entry of kept) {\n const alternates = alternatesByEntry.get(entry.id) ?? [{ locale, path: entry.path }]\n buffer.push(buildUrlEntry(entry, locale, alternates, opts, base))\n if (bufferMaxUpdatedAt === null || entry.updatedAt > bufferMaxUpdatedAt) {\n bufferMaxUpdatedAt = entry.updatedAt\n }\n if (buffer.length >= maxUrls) {\n const full = flush()\n if (full) yield full\n }\n }\n }\n\n const tail = flush()\n if (tail) yield tail\n }\n\n // The index is only meaningful when it references more than one file.\n if (producedFiles.length > 1) {\n yield { kind: 'index', filename: SITEMAP_INDEX_FILENAME, xml: buildIndex(producedFiles, base) }\n }\n}\n\n/**\n * Resolve the full hreflang-alternate set for a batch of same-locale entries.\n * The current locale is always a self-alternate (`enumeratePaths` already proved\n * it published + canonical there). Every OTHER locale is resolved with ONE\n * batched `getCanonicalPaths` (forward index) + ONE batched `filterPublished`\n * (publish gate) per (entity-type group × locale) — never per row.\n */\nasync function resolveAlternates(\n entries: readonly PathEntry[],\n currentLocale: string,\n opts: SitemapOptions,\n deps: SitemapDeps,\n): Promise<Map<string, Alternate[]>> {\n const result = new Map<string, Alternate[]>()\n // Seed each entry with its self-alternate (its own published canonical URL).\n for (const entry of entries) result.set(entry.id, [{ locale: currentLocale, path: entry.path }])\n\n const otherLocales = opts.locales.filter((l) => l !== currentLocale)\n if (otherLocales.length === 0) return result\n\n // Group the batch's ids by entity type (bounded: routable types are few + config-fixed).\n const idsByType = new Map<string, string[]>()\n for (const entry of entries) {\n const bucket = idsByType.get(entry.entityType)\n if (bucket) bucket.push(entry.id)\n else idsByType.set(entry.entityType, [entry.id])\n }\n\n for (const otherLocale of otherLocales) {\n for (const [type, ids] of idsByType) {\n // (1) Forward index: which of these ids have a canonical row in otherLocale?\n const pathMap = await getCanonicalPaths(type, ids, otherLocale, deps.canonicalBatch)\n if (pathMap.size === 0) continue\n // (2) Publish gate: of THOSE, which are actually published in otherLocale?\n // getCanonicalPaths does NOT publish-filter — this is the required\n // no-unpublished-leak step, batched (never per-row).\n const candidateIds = [...pathMap.keys()]\n const publishedIds = await deps.enumerate.filterPublished(type, candidateIds, otherLocale)\n // (3) noIndex gate — same shape, other-locale value. Without this, a\n // document marked noIndex in `otherLocale` (excluded from ITS OWN\n // urlset by `excludeNoIndexed` below) still gets published as an\n // hreflang alternate on every OTHER locale's urlset, publishing the\n // exact URL the editor asked to hide.\n const noIndexIds =\n deps.filterNoIndex !== undefined\n ? await deps.filterNoIndex(type, candidateIds, otherLocale)\n : undefined\n for (const [id, path] of pathMap) {\n if (!publishedIds.has(id)) continue\n if (noIndexIds?.has(id)) continue\n const alternates = result.get(id)\n if (alternates) alternates.push({ locale: otherLocale, path })\n }\n }\n }\n\n return result\n}\n\n/**\n * Peak concurrent `noIndex`-check groups per batch — mirrors `enumerate.ts`'s\n * `PUBLISH_CHECK_CONCURRENCY` bound (CLAUDE.md \"no amplification\"): a batch\n * holds a handful of distinct entity types at most, so this is rarely reached\n * — it exists so the fan-out is EXPLICITLY capped, never unbounded.\n */\nconst NOINDEX_CHECK_CONCURRENCY = 5\n\n/**\n * Keep the entries `deps.filterNoIndex` does NOT report as `noIndex` in\n * `locale` (all of them when the dep is omitted — current default: nothing\n * excluded). Groups the batch by entity type (mirrors `enumeratePaths`'s own\n * `byType` grouping) and calls `deps.filterNoIndex` ONCE per (entity-type\n * group, batch) — never once per entry — bounded to\n * {@link NOINDEX_CHECK_CONCURRENCY} concurrent groups.\n *\n * FAIL-CLOSED, deliberately, unlike `loadMetaPanelData`'s fail-open contract\n * (`packages/admin-ui/src/server/meta-panel-data.ts`): `mapBounded` does not\n * catch per-item errors (see its own doc comment in `apply-path.ts`), so a\n * `deps.filterNoIndex` rejection aborts the whole `generateSitemap` run rather\n * than silently including a possibly-noIndexed row. A build-time sitemap\n * generator failing loudly is preferable to a build succeeding with a leaked\n * noIndex URL.\n */\nasync function excludeNoIndexed(\n entries: readonly PathEntry[],\n locale: string,\n deps: SitemapDeps,\n): Promise<PathEntry[]> {\n const filterNoIndex = deps.filterNoIndex\n if (filterNoIndex === undefined) return [...entries]\n\n // Group this batch's ids by entity type (bounded: routable types are few).\n const idsByType = new Map<string, string[]>()\n for (const entry of entries) {\n const bucket = idsByType.get(entry.entityType)\n if (bucket) bucket.push(entry.id)\n else idsByType.set(entry.entityType, [entry.id])\n }\n\n const noIndexedByType = new Map<string, ReadonlySet<string>>()\n await mapBounded([...idsByType.entries()], NOINDEX_CHECK_CONCURRENCY, async ([type, ids]) => {\n noIndexedByType.set(type, await filterNoIndex(type, ids, locale))\n })\n\n return entries.filter((entry) => !noIndexedByType.get(entry.entityType)?.has(entry.id))\n}\n\n// ---------------------------------------------------------------------------\n// XML builders\n// ---------------------------------------------------------------------------\n\nconst URLSET_HEADER =\n '<?xml version=\"1.0\" encoding=\"UTF-8\"?>\\n' +\n '<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\" ' +\n 'xmlns:xhtml=\"http://www.w3.org/1999/xhtml\">'\n\nconst INDEX_HEADER =\n '<?xml version=\"1.0\" encoding=\"UTF-8\"?>\\n' +\n '<sitemapindex xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\">'\n\n/** Wrap the buffered `<url>` blocks in a `<urlset>` envelope. */\nfunction buildUrlset(urlBlocks: readonly string[]): string {\n return `${URLSET_HEADER}\\n${urlBlocks.join('\\n')}\\n</urlset>\\n`\n}\n\n/** Build one `<url>` block: `<loc>`, `<lastmod>`, one `xhtml:link` per alternate + x-default. */\nfunction buildUrlEntry(\n entry: PathEntry,\n currentLocale: string,\n alternates: readonly Alternate[],\n opts: SitemapOptions,\n base: string,\n): string {\n const loc = absoluteUrl(base, opts.prefix, currentLocale, entry.path)\n const links = alternates.map(\n (alt) => ` ${hreflangLink(alt.locale, absoluteUrl(base, opts.prefix, alt.locale, alt.path))}`,\n )\n // x-default → the default-locale URL, when the document is published there.\n const defaultAlt = alternates.find((alt) => alt.locale === opts.defaultLocale)\n if (defaultAlt) {\n links.push(\n ` ${hreflangLink('x-default', absoluteUrl(base, opts.prefix, defaultAlt.locale, defaultAlt.path))}`,\n )\n }\n return (\n ' <url>\\n' +\n ` <loc>${escapeXml(loc)}</loc>\\n` +\n ` <lastmod>${entry.updatedAt.toISOString()}</lastmod>\\n` +\n `${links.join('\\n')}\\n` +\n ' </url>'\n )\n}\n\n/** Build the `<sitemapindex>` referencing every produced urlset file. */\nfunction buildIndex(files: ReadonlyArray<{ filename: string; lastmod: string }>, base: string): string {\n const entries = files.map(\n (f) =>\n ' <sitemap>\\n' +\n ` <loc>${escapeXml(`${base}/${f.filename}`)}</loc>\\n` +\n ` <lastmod>${f.lastmod}</lastmod>\\n` +\n ' </sitemap>',\n )\n return `${INDEX_HEADER}\\n${entries.join('\\n')}\\n</sitemapindex>\\n`\n}\n\n/** One `<xhtml:link rel=\"alternate\" hreflang=... href=.../>` tag (both values escaped). */\nfunction hreflangLink(hreflang: string, href: string): string {\n return `<xhtml:link rel=\"alternate\" hreflang=\"${escapeXml(hreflang)}\" href=\"${escapeXml(href)}\"/>`\n}\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\n/** `baseUrl` + optional `prefix(locale)` + `path` — the absolute, un-escaped URL. */\nfunction absoluteUrl(\n base: string,\n prefix: SitemapOptions['prefix'],\n locale: string,\n path: string,\n): string {\n return `${base}${prefix ? prefix(locale) : ''}${path}`\n}\n\n/** Strip any trailing slash(es) so `base + '/' + file` / `base + path` never doubles up. */\nfunction stripTrailingSlash(url: string): string {\n return url.replace(/\\/+$/, '')\n}\n\n/**\n * Escape the five XML predefined entities. `&` MUST be replaced first so the\n * entity ampersands it introduces are not re-escaped.\n */\nfunction escapeXml(value: string): string {\n return value\n .replace(/&/g, '&')\n .replace(/</g, '<')\n .replace(/>/g, '>')\n .replace(/\"/g, '"')\n .replace(/'/g, ''')\n}\n\n/** `sitemap-<locale>.xml` (index 0) / `sitemap-<locale>-<n>.xml` (splits, n≥2). */\nfunction urlsetFilename(locale: string, index: number): string {\n return index === 0 ? `sitemap-${locale}.xml` : `sitemap-${locale}-${index + 1}.xml`\n}\n\n/**\n * A finite, ≥1 integer from a config-derived value, else `fallback`. Guards a 0 /\n * negative / fractional / NaN `maxUrlsPerFile` or `batchSize` from producing a\n * zero-length split loop.\n */\nfunction normalizePositiveInt(value: number | undefined, fallback: number): number {\n if (value === undefined || !Number.isFinite(value)) return fallback\n const floored = Math.floor(value)\n return floored >= 1 ? floored : fallback\n}\n\n/**\n * Buffer an async source into fixed-size chunks — bounds the per-batch\n * cross-locale fan-out (see module header). The final chunk may be short.\n */\nasync function* chunkAsync<T>(source: AsyncIterable<T>, size: number): AsyncGenerator<T[]> {\n let buffer: T[] = []\n for await (const item of source) {\n buffer.push(item)\n if (buffer.length >= size) {\n yield buffer\n buffer = []\n }\n }\n if (buffer.length > 0) yield buffer\n}\n","/**\n * Build-time redirect list for SSG frontends (plan/routing PR08; phase\n * `06-frontend-adapters.md` §3, finding F037 point 3).\n *\n * `getRedirects` streams the full `(from, to, status)` redirect set for one\n * locale — the manual (`toolkit_redirects`) rows PLUS the automatic historical\n * (`toolkit_paths` non-canonical) rows — so a frontend can materialize a static\n * redirect map (`_redirects` / `vercel.json` / an nginx include) at build time.\n * It is a PURE generator, not an HTTP endpoint: the frontend recipe (PR08 Task\n * 2b) maps the yielded entries into its host's adapter format.\n *\n * **Security (CLAUDE.md #1).** The output feeds a public, static build artifact,\n * so a redirect must NEVER point at content the live site would 404 — a static\n * 301 to unpublished content has no request-time fallback to catch it (unlike\n * `resolvePath`, where the target's own canonical tier re-checks). So every\n * redirect whose target is a resolved DOCUMENT (entity-kind manual + all\n * historical) is publish-gated with the SAME batched `filterPublished` primitive\n * `enumeratePaths` / `generateSitemap` use, and an unpublished target is DROPPED\n * — mirroring `resolvePath`'s tier-4 `checkPublished` gate. `url`-kind targets\n * are admin-authored external URLs (never a public write); `path`-kind targets\n * are gated on the target path currently serving canonical content, matching\n * `resolveManualRedirect`'s own path-kind branch.\n *\n * **No unbounded fan-out (CLAUDE.md \"no amplification\").** Both halves are\n * keyset-paginated on the immutable `id` PK (one index query per page), and the\n * document resolution + publish check are BATCHED — one `getCanonicalPaths` +\n * one `filterPublished` per (page × distinct entity-type group), never one query\n * per row (mirrors `enumeratePaths`'s / the sitemap's own bound). Manual redirects\n * are admin-authored (bounded volume, not content-scaled) but are still paginated\n * on principle. The only inherently per-row read is the `path`-kind existence\n * check — one bounded `limit: 1` lookup per surviving `path`-kind manual row —\n * which can't be batched (it keys on the target PATH, not an id set) and rides on\n * the same bounded admin-authored volume.\n *\n * **Precedence, mirroring `resolvePath`.** `resolvePath` resolves\n * canonical → manual → historical, and within manual a locale-specific row wins\n * over the catch-all (`locale IS NULL`) row (`lookupManualRedirect`). This list\n * reproduces that ordering: locale-specific manual rows first (claiming their\n * `from`), then catch-all manual rows (skipped where a locale-specific row\n * already claimed the path), then historical rows (skipped where ANY manual\n * redirect claimed the path — matching resolvePath's tier-3-before-tier-4\n * short-circuit, which fires even when the manual row itself resolves to nothing).\n *\n * **Not reproduced (deliberate, deps stay minimal).** (1) The homepage-collision\n * collapse (`resolvePath` sends a redirect that targets the homepage document\n * straight to `/`): a manual/historical redirect targeting the homepage instead\n * emits its pattern URL, which the live `resolvePath` then 301s to `/` — one\n * extra hop for a rare case, not a broken link, and it avoids threading a\n * `homepageReader` dep. (2) `path`-kind live multi-hop walking: `path` targets are\n * collapsed to ≤1 hop at save time (`collapsePathTarget`, phase 04 §3), so a\n * single existence lookup suffices; a rebuild re-runs this generator whenever\n * redirects change. (3) The multi-document historical collision (two docs holding\n * a historical row at the same path — findRedirectTarget's documented\n * approximate/self-healing edge, F014): this list emits at most one rule per\n * `from` (first that resolves, in id order) rather than most-recent-updated wins.\n *\n * **Leaf module.** Every cross-package dependency is injected via `deps`; this\n * module imports no `@murumets-ee/core` and no `server-only` graph. Concrete deps\n * are built from an app in `./resolve-context.ts` (`buildRedirectsListDeps`).\n */\n\nimport {\n type CanonicalPathsBatchDeps,\n getCanonicalPaths,\n type PathEnumReader,\n type PathEnumRow,\n type PathEnumWhere,\n type PublishFilter,\n} from './enumerate.js'\nimport { normalizePath } from './generate-path.js'\nimport type { RedirectTarget } from '../redirects/target.js'\n\n// ---------------------------------------------------------------------------\n// Read surface — `type` aliases (not interfaces) so the real\n// `ToolkitRedirectsClient`, typed against `WhereClause`'s template-literal index\n// signature, stays assignable without a cast (same rationale as\n// `PathEnumReader` / `index-reader.ts`'s Deviation-1).\n// ---------------------------------------------------------------------------\n\n/** The projected `toolkit_redirects` row the manual-redirect enumeration reads. */\nexport type RedirectListRow = {\n id: string\n fromPath: string\n /** BCP47 locale, or `null` for the catch-all (all-locales) row. */\n locale: string | null\n target: RedirectTarget\n status: number\n}\n\n/**\n * The (operator-carrying) where shapes the manual enumeration issues: a keyset\n * `id > cursor` plus a `locale` equality (a concrete locale, or `null` for the\n * catch-all stratum). A subset of the real client's `WhereClause`, so the real\n * `ToolkitRedirectsClient` is assignable to {@link RedirectListReader}.\n */\nexport type RedirectListWhere = {\n id?: { gt: string }\n locale?: string | null\n}\n\n/**\n * The batched keyset read surface the manual half needs over `toolkit_redirects`.\n * Construct the real client directly (`toolkitRedirectsTable.makeClient(db)`) —\n * it satisfies this type.\n */\nexport type RedirectListReader = {\n findMany(options: {\n where?: RedirectListWhere\n orderBy?: Array<{ column: 'id'; dir?: 'asc' | 'desc' }>\n limit?: number\n }): Promise<RedirectListRow[]>\n}\n\n// ---------------------------------------------------------------------------\n// Public surface\n// ---------------------------------------------------------------------------\n\n/** One emitted redirect. `301` permanent, `302` temporary (phase 05 §2 shape). */\nexport interface RedirectEntry {\n from: string\n to: string\n status: 301 | 302\n}\n\n/** Options for {@link getRedirects}. */\nexport interface RedirectsListOptions {\n /** Emit this locale's redirects only (mirrors `enumeratePaths` / `generateSitemap`). */\n locale: string\n}\n\n/** Injected dependencies for {@link getRedirects}. */\nexport interface RedirectsListDeps {\n /** Keyset reader over `toolkit_redirects` (manual redirects). */\n redirectsClient: RedirectListReader\n /**\n * Keyset reader over `toolkit_paths` — the historical (non-canonical) rows AND\n * the `path`-kind existence check. Reuses `enumeratePaths`'s exact reader shape.\n */\n pathsClient: PathEnumReader\n /** Batched forward index read for owning-document current-canonical resolution. */\n canonicalBatch: CanonicalPathsBatchDeps\n /** The SAME batched publish filter `enumeratePaths` / `generateSitemap` use. */\n filterPublished: PublishFilter\n}\n\n/** Internal tuning seam (page size). Real callers omit it. */\nexport interface RedirectsListTuning {\n /** Rows per keyset page. Defaults to {@link REDIRECTS_PAGE_SIZE}. Tests force a small value. */\n pageSize?: number\n}\n\n/**\n * Redirect-list page size — same order of magnitude as `enumeratePaths`'s\n * `ENUMERATE_PAGE_SIZE` (200). Must stay ≤ the `defineTable` `MAX_LIMIT` (1000),\n * which THROWS rather than clamps.\n */\nconst REDIRECTS_PAGE_SIZE = 200\n\n/**\n * Stream the redirect list for `opts.locale`: manual redirects (locale-specific\n * then catch-all, deduped by precedence) followed by historical redirects\n * (skipping any `from` a manual redirect already claimed). See the module header\n * for the security + fan-out + precedence guarantees.\n */\nexport async function* getRedirects(\n opts: RedirectsListOptions,\n deps: RedirectsListDeps,\n tuning: RedirectsListTuning = {},\n): AsyncGenerator<RedirectEntry> {\n const { locale } = opts\n const pageSize = tuning.pageSize ?? REDIRECTS_PAGE_SIZE\n\n /**\n * Every `from` a manual redirect (either stratum) OWNS for this locale. Serves\n * two roles: (1) a locale-specific row shadows a catch-all row at the same\n * path; (2) ANY manual redirect at a path shadows the historical tier there —\n * even when the manual row itself resolves to nothing (resolvePath tier-3\n * short-circuit). Populated for EVERY manual row seen (dropped or emitted).\n */\n const manualFrom = new Set<string>()\n\n // ── Tier 3a: locale-specific manual redirects ──────────────────────────────\n yield* manualRedirects(locale, locale, deps, pageSize, manualFrom)\n // ── Tier 3b: catch-all (locale IS NULL) manual redirects ───────────────────\n // `manualFrom` now holds every locale-specific `from`, so catch-all rows at\n // those paths are suppressed inside `manualRedirects`.\n yield* manualRedirects(locale, null, deps, pageSize, manualFrom)\n\n // ── Tier 4: historical (automatic rename) redirects ────────────────────────\n yield* historicalRedirects(locale, deps, pageSize, manualFrom)\n}\n\n// ---------------------------------------------------------------------------\n// Manual redirects\n// ---------------------------------------------------------------------------\n\n/**\n * Stream one `locale` stratum of `toolkit_redirects` (a concrete locale, or\n * `null` for the catch-all rows), keyset-paginated. Records every surviving\n * `from` in `manualFrom` (for precedence + historical shadowing) and yields the\n * resolved, publish-gated entries in id-ascending order.\n */\nasync function* manualRedirects(\n locale: string,\n whereLocale: string | null,\n deps: RedirectsListDeps,\n pageSize: number,\n manualFrom: Set<string>,\n): AsyncGenerator<RedirectEntry> {\n let cursorId: string | undefined\n for (;;) {\n const where: RedirectListWhere = { locale: whereLocale }\n if (cursorId !== undefined) where.id = { gt: cursorId }\n\n const page = await deps.redirectsClient.findMany({\n where,\n orderBy: [{ column: 'id', dir: 'asc' }],\n limit: pageSize,\n })\n if (page.length === 0) break\n\n // Drop rows whose `from` a higher-precedence manual redirect already claimed\n // (a locale-specific row shadowing a catch-all one). Record every surviving\n // `from` — even one we go on to DROP — so precedence + historical shadowing\n // hold regardless of resolution outcome (matches resolvePath's short-circuit).\n const survivors: RedirectListRow[] = []\n for (const row of page) {\n if (manualFrom.has(row.fromPath)) continue\n manualFrom.add(row.fromPath)\n survivors.push(row)\n }\n\n // Batched entity-kind resolution: group by target entity type, then ONE\n // getCanonicalPaths + ONE filterPublished per type group (never per row).\n const resolvedEntityTo = await resolveEntityTargets(survivors, locale, deps)\n\n // Emit in survivor (id) order.\n for (const row of survivors) {\n const status = toRedirectStatus(row.status)\n const target = row.target\n\n if (target.kind === 'url') {\n // Terminal external URL — admin-authored, no publish gate, no self-loop.\n yield { from: row.fromPath, to: target.url, status }\n continue\n }\n\n if (target.kind === 'entity') {\n const to = resolvedEntityTo.get(row.id)\n // Dropped when unpublished / no canonical row (matches resolvePath's\n // tier-3 `{kind:'none'}`). Skip a degenerate self-redirect too.\n if (to !== undefined && to !== row.fromPath) {\n yield { from: row.fromPath, to, status }\n }\n continue\n }\n\n // target.kind === 'path' — collapsed to ≤1 hop at save time, so one bounded\n // existence lookup suffices. Emit only when the target path currently serves\n // canonical content (matches resolveManualRedirect's path-kind branch).\n const to = normalizePath(target.path)\n if (to === row.fromPath) continue\n if (await pathServesCanonical(deps.pathsClient, locale, to)) {\n yield { from: row.fromPath, to, status }\n }\n }\n\n const lastRow = page[page.length - 1]\n if (!lastRow) break\n cursorId = lastRow.id\n if (page.length < pageSize) break\n }\n}\n\n/**\n * Resolve the entity-kind targets in a page to their published canonical path,\n * BATCHED by entity type: one `getCanonicalPaths` (forward index) + one\n * `filterPublished` (publish gate) per distinct target type — never per row\n * (mirrors the sitemap's `resolveAlternates` bucketing). Returns a\n * `redirectRowId → path` map holding only the rows that resolve AND publish.\n */\nasync function resolveEntityTargets(\n rows: readonly RedirectListRow[],\n locale: string,\n deps: RedirectsListDeps,\n): Promise<Map<string, string>> {\n const result = new Map<string, string>()\n\n // Group entity-kind rows by target entity type (bounded: routable types are\n // few + config-fixed). Capture `(redirectRowId, targetId)` while the union arm\n // is still narrowed, so no discriminant re-cast is needed downstream.\n const targetsByType = new Map<string, Array<{ rowId: string; targetId: string }>>()\n for (const row of rows) {\n if (row.target.kind !== 'entity') continue\n const pair = { rowId: row.id, targetId: row.target.id }\n const bucket = targetsByType.get(row.target.entity)\n if (bucket) bucket.push(pair)\n else targetsByType.set(row.target.entity, [pair])\n }\n\n for (const [type, targets] of targetsByType) {\n const ids = targets.map((t) => t.targetId)\n // (1) Forward index: which target ids have a canonical row in `locale`?\n const pathMap = await getCanonicalPaths(type, ids, locale, deps.canonicalBatch)\n const candidateIds = [...pathMap.keys()]\n if (candidateIds.length === 0) continue\n // (2) Publish gate: of THOSE, which are actually published in `locale`?\n const published = await deps.filterPublished(type, candidateIds, locale)\n for (const { rowId, targetId } of targets) {\n const path = pathMap.get(targetId)\n if (path !== undefined && published.has(targetId)) result.set(rowId, path)\n }\n }\n\n return result\n}\n\n/** True iff `path` currently serves a canonical document in `locale` (one bounded lookup). */\nasync function pathServesCanonical(\n pathsClient: PathEnumReader,\n locale: string,\n path: string,\n): Promise<boolean> {\n const rows = await pathsClient.findMany({\n where: { locale, path, isCanonical: true },\n limit: 1,\n })\n return rows.length > 0\n}\n\n// ---------------------------------------------------------------------------\n// Historical redirects\n// ---------------------------------------------------------------------------\n\n/**\n * Stream the historical (automatic rename) redirects for `locale`: the demoted\n * (`is_canonical = false`) `toolkit_paths` rows, each resolved to its owning\n * document's CURRENT canonical path. Keyset-paginated; per page, ONE\n * `getCanonicalPaths` + ONE `filterPublished` per entity-type group (never per\n * row). Drops rows whose document has no live published canonical variant\n * anymore (matches `findRedirectTarget`'s `null`), and any `from` a manual\n * redirect already claimed (tier-3 wins) or an already-emitted historical `from`\n * (at most one rule per `from`).\n */\nasync function* historicalRedirects(\n locale: string,\n deps: RedirectsListDeps,\n pageSize: number,\n manualFrom: ReadonlySet<string>,\n): AsyncGenerator<RedirectEntry> {\n /** Historical `from`s already emitted — dedup the documented multi-doc collision. */\n const emittedFrom = new Set<string>()\n let cursorId: string | undefined\n for (;;) {\n const where: PathEnumWhere = { locale, isCanonical: false }\n if (cursorId !== undefined) where.id = { gt: cursorId }\n\n const page = await deps.pathsClient.findMany({\n where,\n orderBy: [{ column: 'id', dir: 'asc' }],\n limit: pageSize,\n })\n if (page.length === 0) break\n\n // Group this page's rows by entity type, then ONE batched canonical lookup +\n // ONE publish check per group. `entityId → current published canonical path`.\n const byType = new Map<string, PathEnumRow[]>()\n for (const row of page) {\n const bucket = byType.get(row.entityType)\n if (bucket) bucket.push(row)\n else byType.set(row.entityType, [row])\n }\n\n const currentPath = new Map<string, string>()\n for (const [type, rows] of byType) {\n const ids = rows.map((r) => r.entityId)\n const pathMap = await getCanonicalPaths(type, ids, locale, deps.canonicalBatch)\n const candidateIds = [...pathMap.keys()]\n if (candidateIds.length === 0) continue\n const published = await deps.filterPublished(type, candidateIds, locale)\n for (const [id, path] of pathMap) {\n if (published.has(id)) currentPath.set(id, path)\n }\n }\n\n for (const row of page) {\n // A manual redirect at this path wins (tier 3 before tier 4).\n if (manualFrom.has(row.path)) continue\n // Already emitted a historical rule at this `from` (multi-doc collision).\n if (emittedFrom.has(row.path)) continue\n const to = currentPath.get(row.entityId)\n if (to === undefined) continue // no live published canonical → dropped\n if (to === row.path) continue // self-redirect (from == to) → skip\n emittedFrom.add(row.path)\n yield { from: row.path, to, status: 301 }\n }\n\n const lastRow = page[page.length - 1]\n if (!lastRow) break\n cursorId = lastRow.id\n if (page.length < pageSize) break\n }\n}\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Narrow the DB `status` integer (validated `301 | 302` at write time) to the\n * result union. Defaults to `301` for any unexpected value — never a raw number\n * leaking into the typed entry (mirrors `resolve.ts`'s `toRedirectStatus`).\n */\nfunction toRedirectStatus(status: number): 301 | 302 {\n return status === 302 ? 302 : 301\n}\n"],"mappings":"wMA6JA,eAAuB,EACrB,EACA,EACA,EAA+B,CAAC,EACL,CAC3B,IAAM,EAAW,EAAO,UAAY,IAC9B,EAAc,EAAO,oBAAsB,EAC3C,CAAE,SAAQ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AAM,IAAM,GAChC"}
|
|
1
|
+
{"version":3,"file":"resolve.mjs","names":[],"sources":["../src/paths/enumerate.ts","../src/paths/sitemap.ts","../src/paths/redirects-list.ts"],"sourcesContent":["/**\n * Path enumeration for SSG / sitemaps (plan/routing PR06; phase\n * `05-resolution-and-enumeration-api.md` §2).\n *\n * `enumeratePaths` streams the PUBLISHED canonical `(path, entityType, id,\n * updatedAt)` rows for one locale. It powers `getStaticPaths` + the sitemap\n * helper, so it must NEVER leak an unpublished document (CLAUDE.md #1 — the\n * output feeds public build artifacts).\n *\n * **Security + availability.** Two properties matter here:\n * 1. *No unpublished leak.* `toolkit_paths` carries no publish-status column,\n * so each page's rows are publish-checked against the live entity via the\n * injected {@link EnumeratePathsDeps.filterPublished} — an unpublished (or\n * trashed) document is dropped from the stream.\n * 2. *No unbounded fan-out* (CLAUDE.md \"no amplification\"). Work is bounded by\n * PAGE SIZE, not by total document count: rows are keyset-paginated on the\n * immutable `id` PK (one index query per page), and the publish check is\n * BATCHED — ONE call per distinct entity-type bucket per page (a handful of\n * types at most; the routable set is config-time-fixed, never\n * attacker-influenced), never one call per row.\n *\n * **Leaf module.** Every cross-package dependency (the index reader, the publish\n * filter) is injected via `deps`; this module imports no `@murumets-ee/core` and\n * no `server-only` graph. Concrete deps are built from an app in\n * `./resolve-context.ts` (`buildEnumerateDeps`), keeping the resolution surface\n * off the `lumi` CLI command graph (F027 guardrail).\n *\n * Function-form-path entities need NO special handling — their rows were already\n * materialized into `toolkit_paths` at write time (F004 / phase 05 §2), so a\n * plain index read includes them.\n */\n\nimport { mapBounded } from './apply-path.js'\n\n// ---------------------------------------------------------------------------\n// Read surface (a `type` alias, per index-reader.ts's Deviation-1 rationale, so\n// the real `ToolkitPathsClient` stays assignable to it without any cast).\n// ---------------------------------------------------------------------------\n\n/** The projected `toolkit_paths` row the enumeration + batch lookup read. */\nexport type PathEnumRow = {\n id: string\n entityType: string\n entityId: string\n locale: string\n path: string\n updatedAt: Date\n}\n\n/**\n * The (operator-carrying) where shapes enumeration issues: keyset `id > cursor`,\n * `entityId IN (...)` for the batch lookup, plus plain-value equality filters.\n * A subset of the real client's `ColumnOperators` where-clause, so the real\n * `ToolkitPathsClient` is assignable to {@link PathEnumReader}.\n */\nexport type PathEnumWhere = {\n id?: { gt: string }\n entityType?: string\n entityId?: { in: string[] }\n locale?: string\n path?: string\n isCanonical?: boolean\n}\n\n/**\n * The batched keyset read surface {@link enumeratePaths} / {@link getCanonicalPaths}\n * need. NARROWER than Task 1's point-lookup `PathIndexReader` (which only orders\n * by `updatedAt` and takes plain-value where): enumeration needs `id`-ordering,\n * a `{ gt }` cursor, and `{ in }` batching. Construct the real client directly\n * (`toolkitPathsTable.makeClient(db)`) — it satisfies this type.\n */\nexport type PathEnumReader = {\n findMany(options: {\n where?: PathEnumWhere\n orderBy?: Array<{ column: 'id'; dir?: 'asc' | 'desc' }>\n limit?: number\n }): Promise<PathEnumRow[]>\n}\n\n/**\n * Batch publish check: return the SUBSET of `entityIds` that is published in\n * `locale`. Called ONCE per entity-type group per page. The concrete\n * implementation (see `resolve-context.ts`) runs an elevated-context\n * `QueryClient.findMany({ where: inArray(getTable().id, ids), locale })` — so no\n * unpublished/trashed id comes back. Since D017 the publish filter is\n * CONDITIONAL (it holds for any principal without `view_unpublished`); what\n * keeps that true here is that the elevated context is a REACH context which\n * withholds that action, not that the filter is unconditional.\n */\nexport type PublishFilter = (\n entityType: string,\n entityIds: readonly string[],\n locale: string,\n) => Promise<ReadonlySet<string>>\n\n// ---------------------------------------------------------------------------\n// Public surface\n// ---------------------------------------------------------------------------\n\n/** One enumerated path row (phase 05 §2 — exact shape). */\nexport interface PathEntry {\n path: string\n entityType: string\n id: string\n updatedAt: Date\n}\n\n/** Options for {@link enumeratePaths} (phase 05 §2 — exact shape). */\nexport interface EnumeratePathsOptions {\n /** Enumerate this locale's canonical rows only. */\n locale: string\n /** Optionally narrow to a single routable entity type. */\n entityType?: string\n /**\n * Resume the keyset AFTER this `toolkit_paths` row id (exclusive); omit to\n * start from the beginning. The value is the opaque `toolkit_paths` PK the\n * internal page cursor advances on — NOT the yielded `PathEntry.id`, which is\n * the DOCUMENT (entity) id. A cross-request paginating caller (e.g. the\n * content-api `_paths` endpoint) resolves the last consumed entry's row PK and\n * passes it here to continue exactly where the prior page stopped, with no row\n * skipped or repeated. Fully backward-compatible: existing callers omit it and\n * traverse from the start unchanged.\n */\n afterId?: string\n}\n\n/** Injected dependencies for {@link enumeratePaths}. */\nexport interface EnumeratePathsDeps {\n pathsClient: PathEnumReader\n filterPublished: PublishFilter\n}\n\n/** Internal tuning seam (page size / batch concurrency). Real callers omit it. */\nexport interface EnumeratePathsTuning {\n /** Rows per index page. Defaults to {@link ENUMERATE_PAGE_SIZE}. Tests force a small value. */\n pageSize?: number\n /** Peak concurrent publish-check groups. Defaults to {@link PUBLISH_CHECK_CONCURRENCY}. */\n publishConcurrency?: number\n}\n\n/**\n * Index page size — mirrors the rebuild job's `REBUILD_PAGE_SIZE`. Must stay\n * ≤ the `defineTable` `MAX_LIMIT` (1000), which THROWS rather than clamps.\n */\nconst ENUMERATE_PAGE_SIZE = 200\n\n/**\n * Peak concurrent publish-check groups per page. A page holds a handful of\n * distinct entity types at most, so this bound is rarely reached — it exists so\n * the fan-out is EXPLICITLY capped (CLAUDE.md), never `Promise.all` over an\n * unbounded set.\n */\nconst PUBLISH_CHECK_CONCURRENCY = 5\n\n/**\n * Stream the published canonical paths for `opts.locale` (optionally narrowed to\n * `opts.entityType`), keyset-paginated with a per-page batched publish filter.\n * See the module header for the security + fan-out guarantees.\n */\nexport async function* enumeratePaths(\n opts: EnumeratePathsOptions,\n deps: EnumeratePathsDeps,\n tuning: EnumeratePathsTuning = {},\n): AsyncGenerator<PathEntry> {\n const pageSize = tuning.pageSize ?? ENUMERATE_PAGE_SIZE\n const concurrency = tuning.publishConcurrency ?? PUBLISH_CHECK_CONCURRENCY\n const { locale, entityType } = opts\n\n // Seed from `opts.afterId` so a caller can resume mid-stream; undefined starts\n // at the beginning (every existing caller's behavior, unchanged).\n let cursorId: string | undefined = opts.afterId\n for (;;) {\n // Keyset cursor on the immutable `id` PK (the rebuild job's precedent):\n // visits every canonical row exactly once even under concurrent mutation,\n // which OFFSET paging cannot guarantee.\n const where: PathEnumWhere = { locale, isCanonical: true }\n if (entityType !== undefined) where.entityType = entityType\n if (cursorId !== undefined) where.id = { gt: cursorId }\n\n const page = await deps.pathsClient.findMany({\n where,\n orderBy: [{ column: 'id', dir: 'asc' }],\n limit: pageSize,\n })\n if (page.length === 0) break\n\n // Group this page's rows by entity type (bounded: the routable-type set is\n // small + config-fixed), then ONE publish check per group.\n const byType = new Map<string, PathEnumRow[]>()\n for (const row of page) {\n const bucket = byType.get(row.entityType)\n if (bucket) bucket.push(row)\n else byType.set(row.entityType, [row])\n }\n\n const publishedByType = new Map<string, ReadonlySet<string>>()\n await mapBounded([...byType.entries()], concurrency, async ([type, rows]) => {\n const published = await deps.filterPublished(\n type,\n rows.map((r) => r.entityId),\n locale,\n )\n publishedByType.set(type, published)\n })\n\n // Yield only the page's PUBLISHED rows, preserving the id-ascending order.\n for (const row of page) {\n if (publishedByType.get(row.entityType)?.has(row.entityId)) {\n yield { path: row.path, entityType: row.entityType, id: row.entityId, updatedAt: row.updatedAt }\n }\n }\n\n // Advance the cursor to the last (max-id) row of this raw page. `page` is\n // non-empty here (length-0 broke above). Publish-filtering is a POST-filter,\n // so the cursor always steps over every index row regardless of publish state.\n const lastRow = page[page.length - 1]\n if (!lastRow) break\n cursorId = lastRow.id\n if (page.length < pageSize) break\n }\n}\n\n// ---------------------------------------------------------------------------\n// getCanonicalPaths — batched forward lookup (search url re-point), NO publish filter\n// ---------------------------------------------------------------------------\n\n/** Deps for {@link getCanonicalPaths}. */\nexport interface CanonicalPathsBatchDeps {\n pathsClient: PathEnumReader\n}\n\n/**\n * Max ids per batched index query — well under `defineTable`'s `MAX_LIMIT`\n * (1000, which throws rather than clamps). Search result pages are far smaller\n * than this, so this is one query in practice; larger id sets chunk safely.\n */\nconst CANONICAL_BATCH_SIZE = 500\n\n/**\n * The current canonical paths for many `(entityType, entityId)` in ONE locale,\n * as an `entityId → path` map — the batched sibling of `getCanonicalPath`.\n *\n * **No publish filter — deliberate**, matching `getCanonicalPath` (and the\n * search url builder it re-points): a search result's url is display-only and\n * the caller already gates row visibility. One index query per {@link\n * CANONICAL_BATCH_SIZE}-sized chunk (one query total for a normal search page),\n * so it never fans out per row.\n */\nexport async function getCanonicalPaths(\n entityType: string,\n entityIds: readonly string[],\n locale: string,\n deps: CanonicalPathsBatchDeps,\n): Promise<Map<string, string>> {\n const result = new Map<string, string>()\n for (let i = 0; i < entityIds.length; i += CANONICAL_BATCH_SIZE) {\n const chunk = entityIds.slice(i, i + CANONICAL_BATCH_SIZE)\n const rows = await deps.pathsClient.findMany({\n where: { entityType, locale, isCanonical: true, entityId: { in: [...chunk] } },\n limit: chunk.length,\n })\n for (const row of rows) result.set(row.entityId, row.path)\n }\n return result\n}\n","/**\n * Sitemap generation for the routed content surface (plan/routing PR07; phase\n * `05-resolution-and-enumeration-api.md` §4).\n *\n * `generateSitemap` streams the standard-protocol sitemap document set for the\n * configured locales: one `<urlset>` per locale (split into numbered files at\n * {@link SitemapOptions.maxUrlsPerFile}), plus a `<sitemapindex>` when the run\n * produced more than one file. Each `<url>` carries a `<lastmod>` (from the\n * enumerated `updatedAt`) and the full `xhtml:link` hreflang-alternates set —\n * including an `x-default` pointing at the default-locale URL. It is a PURE\n * generator, NOT an HTTP endpoint: the frontend recipe (PR08) mounts it in a\n * route handler; this module only produces the documents.\n *\n * **Security (CLAUDE.md #1).** The output feeds a public build artifact, so it\n * must NEVER leak an unpublished / trashed document. Two independent publish\n * gates apply:\n * 1. The primary rows come from {@link enumeratePaths}, which publish-filters\n * each page against the entity (unpublished/trashed dropped) for the\n * sitemap's OWN locale.\n * 2. The cross-locale hreflang alternates come from {@link getCanonicalPaths},\n * which does NOT publish-filter (it is a display-only forward index read).\n * So this module ADDITIONALLY runs the same batched `filterPublished` over\n * every candidate other-locale alternate before linking it — an\n * unpublished-in-that-locale document is never emitted as an alternate.\n *\n * **No unbounded fan-out (CLAUDE.md \"no amplification\").** The cross-locale\n * alternate lookup is BATCHED exactly like `enumeratePaths`'s own publish check:\n * per {@link SITEMAP_ALTERNATES_BATCH_SIZE}-sized chunk of enumerated rows, the\n * work is ONE `getCanonicalPaths` + ONE `filterPublished` per (entity-type\n * group × other locale) — bounded by (batch size × distinct routable types ×\n * locale count), NEVER one query per document. `getAlternates` (the per-document\n * N-locale function) is deliberately NOT used here — calling it per enumerated\n * row would be the O(rows × locales) amplification this bound forbids.\n *\n * **`noIndex` exclusion (PR 11's `seoMeta()`).** `SitemapDeps.filterNoIndex` is\n * an OPTIONAL batched dep, same shape as `filterPublished` (a `PublishFilter`)\n * but semantics-inverted: it returns the subset of ids that ARE `noIndex` in\n * the given locale. It lives on `deps`, not `opts`, because — like\n * `filterPublished` — a real implementation needs a DB read, and `noIndex` is\n * `translatable: true`, so the SAME callback must be invoked once per\n * (locale, entity-type group, batch) to see the right per-locale value; a\n * per-entry (locale-blind) predicate could not express this correctly. Omitted\n * → nothing excluded (current default). See `excludeNoIndexed`.\n *\n * **Leaf module.** Every cross-package dependency is injected via `deps`\n * ({@link SitemapDeps}); this module imports no `@murumets-ee/core` and no\n * `server-only` graph. Concrete deps are built from an app in\n * `./resolve-context.ts` (`buildSitemapDeps`).\n */\n\nimport { mapBounded } from './apply-path.js'\nimport {\n type CanonicalPathsBatchDeps,\n enumeratePaths,\n type EnumeratePathsDeps,\n type EnumeratePathsTuning,\n getCanonicalPaths,\n type PathEntry,\n type PublishFilter,\n} from './enumerate.js'\n\n// ---------------------------------------------------------------------------\n// Public surface\n// ---------------------------------------------------------------------------\n\n/** Options for {@link generateSitemap}. */\nexport interface SitemapOptions {\n /** The locales to emit a `<urlset>` for (configured content locales). */\n locales: readonly string[]\n /**\n * The default locale — its URL is the `x-default` hreflang target. Explicit\n * (NOT inferred from `locales` order) so callers stay unambiguous.\n */\n defaultLocale: string\n /** Absolute site origin, e.g. `https://example.com` (trailing slash tolerated). */\n baseUrl: string\n /**\n * Per-locale URL prefix rule (e.g. `(l) => l === 'en' ? '' : '/' + l`). The\n * frontend owns the locale-prefix convention (D002); omitted → no prefix.\n */\n prefix?: (locale: string) => string\n /**\n * Max `<url>` entries per file before splitting (sitemap protocol caps at\n * 50 000). Defaults to {@link DEFAULT_MAX_URLS_PER_FILE}.\n */\n maxUrlsPerFile?: number\n}\n\n/** Injected dependencies for {@link generateSitemap}. */\nexport interface SitemapDeps {\n /**\n * Deps for {@link enumeratePaths} — the `toolkit_paths` reader plus the\n * batched `filterPublished`. `filterPublished` is REUSED for the cross-locale\n * alternate publish gate (same batched shape), so no second publish surface is\n * needed.\n */\n enumerate: EnumeratePathsDeps\n /**\n * Deps for {@link getCanonicalPaths} — the batched cross-locale forward index\n * read (NO publish filter; this module applies `enumerate.filterPublished` on\n * top).\n */\n canonicalBatch: CanonicalPathsBatchDeps\n /**\n * Optional: batched `noIndex` check, same shape as `filterPublished` but\n * semantics-inverted — returns the subset of `entityIds` that ARE `noIndex`\n * in `locale` (PR 11's `seoMeta()`). Called at most once per (entity-type\n * group, batch), never once per entry — see `excludeNoIndexed`. Omitted →\n * nothing excluded (current default).\n */\n filterNoIndex?: PublishFilter\n}\n\n/** Internal tuning seam (batch size / enumerate page size). Real callers omit it. */\nexport interface SitemapTuning {\n /**\n * Enumerated rows per cross-locale alternate batch. Defaults to\n * {@link SITEMAP_ALTERNATES_BATCH_SIZE}. Tests force a small value to span\n * multiple batches. Bounds the per-batch fan-out (see module header).\n */\n batchSize?: number\n /** Passed through to {@link enumeratePaths} for its own paging/publish tuning. */\n enumerate?: EnumeratePathsTuning\n}\n\n/** One emitted sitemap document. */\nexport interface SitemapFile {\n /** `'urlset'` for a per-locale URL set, `'index'` for the sitemap index. */\n kind: 'urlset' | 'index'\n /**\n * Suggested filename served at `${baseUrl}/${filename}`. Per-locale urlsets are\n * `sitemap-<locale>.xml` (first) / `sitemap-<locale>-<n>.xml` (splits, n≥2);\n * the index is {@link SITEMAP_INDEX_FILENAME}.\n */\n filename: string\n /** The complete, well-formed XML document text (trailing newline included). */\n xml: string\n}\n\n/** Default `<url>` cap per file — under the sitemap protocol's 50 000 hard limit. */\nexport const DEFAULT_MAX_URLS_PER_FILE = 40_000\n\n/** Filename of the emitted sitemap index (referenced by the mounting route). */\nexport const SITEMAP_INDEX_FILENAME = 'sitemap.xml'\n\n/**\n * Enumerated rows per cross-locale alternate batch. Aligned with\n * `enumeratePaths`'s own page size so a batch is ~one enumeration page; the\n * exact value only affects HOW MANY batched lookups run, never their per-batch\n * bound (see module header). Never per-row.\n */\nconst SITEMAP_ALTERNATES_BATCH_SIZE = 200\n\n// ---------------------------------------------------------------------------\n// Generator\n// ---------------------------------------------------------------------------\n\n/** One resolved hreflang alternate (a published, canonical per-locale URL). */\ninterface Alternate {\n locale: string\n path: string\n}\n\n/**\n * Stream the sitemap document set for `opts.locales`. See the module header for\n * the security + fan-out guarantees. Yields each `<urlset>` file as it fills,\n * then a `<sitemapindex>` LAST iff more than one file was produced.\n */\nexport async function* generateSitemap(\n opts: SitemapOptions,\n deps: SitemapDeps,\n tuning: SitemapTuning = {},\n): AsyncGenerator<SitemapFile> {\n const maxUrls = normalizePositiveInt(opts.maxUrlsPerFile, DEFAULT_MAX_URLS_PER_FILE)\n const batchSize = normalizePositiveInt(tuning.batchSize, SITEMAP_ALTERNATES_BATCH_SIZE)\n const base = stripTrailingSlash(opts.baseUrl)\n\n /** (filename, lastmod) of every urlset file produced — feeds the index. */\n const producedFiles: Array<{ filename: string; lastmod: string }> = []\n\n for (const locale of opts.locales) {\n let buffer: string[] = []\n let bufferMaxUpdatedAt: Date | null = null\n let fileIndex = 0\n\n /** Flush the current buffer as a numbered urlset file (or return null if empty). */\n const flush = (): SitemapFile | null => {\n if (buffer.length === 0) return null\n const filename = urlsetFilename(locale, fileIndex)\n const lastmod = (bufferMaxUpdatedAt ?? new Date()).toISOString()\n const file: SitemapFile = { kind: 'urlset', filename, xml: buildUrlset(buffer) }\n producedFiles.push({ filename, lastmod })\n buffer = []\n bufferMaxUpdatedAt = null\n fileIndex += 1\n return file\n }\n\n const source = enumeratePaths({ locale }, deps.enumerate, tuning.enumerate)\n for await (const batch of chunkAsync(source, batchSize)) {\n // Exclude noIndex rows FIRST so they're never fetched cross-locale.\n const kept = await excludeNoIndexed(batch, locale, deps)\n if (kept.length === 0) continue\n\n // ONE batched cross-locale lookup per (entity-type group × other locale).\n const alternatesByEntry = await resolveAlternates(kept, locale, opts, deps)\n\n for (const entry of kept) {\n const alternates = alternatesByEntry.get(entry.id) ?? [{ locale, path: entry.path }]\n buffer.push(buildUrlEntry(entry, locale, alternates, opts, base))\n if (bufferMaxUpdatedAt === null || entry.updatedAt > bufferMaxUpdatedAt) {\n bufferMaxUpdatedAt = entry.updatedAt\n }\n if (buffer.length >= maxUrls) {\n const full = flush()\n if (full) yield full\n }\n }\n }\n\n const tail = flush()\n if (tail) yield tail\n }\n\n // The index is only meaningful when it references more than one file.\n if (producedFiles.length > 1) {\n yield { kind: 'index', filename: SITEMAP_INDEX_FILENAME, xml: buildIndex(producedFiles, base) }\n }\n}\n\n/**\n * Resolve the full hreflang-alternate set for a batch of same-locale entries.\n * The current locale is always a self-alternate (`enumeratePaths` already proved\n * it published + canonical there). Every OTHER locale is resolved with ONE\n * batched `getCanonicalPaths` (forward index) + ONE batched `filterPublished`\n * (publish gate) per (entity-type group × locale) — never per row.\n */\nasync function resolveAlternates(\n entries: readonly PathEntry[],\n currentLocale: string,\n opts: SitemapOptions,\n deps: SitemapDeps,\n): Promise<Map<string, Alternate[]>> {\n const result = new Map<string, Alternate[]>()\n // Seed each entry with its self-alternate (its own published canonical URL).\n for (const entry of entries) result.set(entry.id, [{ locale: currentLocale, path: entry.path }])\n\n const otherLocales = opts.locales.filter((l) => l !== currentLocale)\n if (otherLocales.length === 0) return result\n\n // Group the batch's ids by entity type (bounded: routable types are few + config-fixed).\n const idsByType = new Map<string, string[]>()\n for (const entry of entries) {\n const bucket = idsByType.get(entry.entityType)\n if (bucket) bucket.push(entry.id)\n else idsByType.set(entry.entityType, [entry.id])\n }\n\n for (const otherLocale of otherLocales) {\n for (const [type, ids] of idsByType) {\n // (1) Forward index: which of these ids have a canonical row in otherLocale?\n const pathMap = await getCanonicalPaths(type, ids, otherLocale, deps.canonicalBatch)\n if (pathMap.size === 0) continue\n // (2) Publish gate: of THOSE, which are actually published in otherLocale?\n // getCanonicalPaths does NOT publish-filter — this is the required\n // no-unpublished-leak step, batched (never per-row).\n const candidateIds = [...pathMap.keys()]\n const publishedIds = await deps.enumerate.filterPublished(type, candidateIds, otherLocale)\n // (3) noIndex gate — same shape, other-locale value. Without this, a\n // document marked noIndex in `otherLocale` (excluded from ITS OWN\n // urlset by `excludeNoIndexed` below) still gets published as an\n // hreflang alternate on every OTHER locale's urlset, publishing the\n // exact URL the editor asked to hide.\n const noIndexIds =\n deps.filterNoIndex !== undefined\n ? await deps.filterNoIndex(type, candidateIds, otherLocale)\n : undefined\n for (const [id, path] of pathMap) {\n if (!publishedIds.has(id)) continue\n if (noIndexIds?.has(id)) continue\n const alternates = result.get(id)\n if (alternates) alternates.push({ locale: otherLocale, path })\n }\n }\n }\n\n return result\n}\n\n/**\n * Peak concurrent `noIndex`-check groups per batch — mirrors `enumerate.ts`'s\n * `PUBLISH_CHECK_CONCURRENCY` bound (CLAUDE.md \"no amplification\"): a batch\n * holds a handful of distinct entity types at most, so this is rarely reached\n * — it exists so the fan-out is EXPLICITLY capped, never unbounded.\n */\nconst NOINDEX_CHECK_CONCURRENCY = 5\n\n/**\n * Keep the entries `deps.filterNoIndex` does NOT report as `noIndex` in\n * `locale` (all of them when the dep is omitted — current default: nothing\n * excluded). Groups the batch by entity type (mirrors `enumeratePaths`'s own\n * `byType` grouping) and calls `deps.filterNoIndex` ONCE per (entity-type\n * group, batch) — never once per entry — bounded to\n * {@link NOINDEX_CHECK_CONCURRENCY} concurrent groups.\n *\n * FAIL-CLOSED, deliberately, unlike `loadMetaPanelData`'s fail-open contract\n * (`packages/admin-ui/src/server/meta-panel-data.ts`): `mapBounded` does not\n * catch per-item errors (see its own doc comment in `apply-path.ts`), so a\n * `deps.filterNoIndex` rejection aborts the whole `generateSitemap` run rather\n * than silently including a possibly-noIndexed row. A build-time sitemap\n * generator failing loudly is preferable to a build succeeding with a leaked\n * noIndex URL.\n */\nasync function excludeNoIndexed(\n entries: readonly PathEntry[],\n locale: string,\n deps: SitemapDeps,\n): Promise<PathEntry[]> {\n const filterNoIndex = deps.filterNoIndex\n if (filterNoIndex === undefined) return [...entries]\n\n // Group this batch's ids by entity type (bounded: routable types are few).\n const idsByType = new Map<string, string[]>()\n for (const entry of entries) {\n const bucket = idsByType.get(entry.entityType)\n if (bucket) bucket.push(entry.id)\n else idsByType.set(entry.entityType, [entry.id])\n }\n\n const noIndexedByType = new Map<string, ReadonlySet<string>>()\n await mapBounded([...idsByType.entries()], NOINDEX_CHECK_CONCURRENCY, async ([type, ids]) => {\n noIndexedByType.set(type, await filterNoIndex(type, ids, locale))\n })\n\n return entries.filter((entry) => !noIndexedByType.get(entry.entityType)?.has(entry.id))\n}\n\n// ---------------------------------------------------------------------------\n// XML builders\n// ---------------------------------------------------------------------------\n\nconst URLSET_HEADER =\n '<?xml version=\"1.0\" encoding=\"UTF-8\"?>\\n' +\n '<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\" ' +\n 'xmlns:xhtml=\"http://www.w3.org/1999/xhtml\">'\n\nconst INDEX_HEADER =\n '<?xml version=\"1.0\" encoding=\"UTF-8\"?>\\n' +\n '<sitemapindex xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\">'\n\n/** Wrap the buffered `<url>` blocks in a `<urlset>` envelope. */\nfunction buildUrlset(urlBlocks: readonly string[]): string {\n return `${URLSET_HEADER}\\n${urlBlocks.join('\\n')}\\n</urlset>\\n`\n}\n\n/** Build one `<url>` block: `<loc>`, `<lastmod>`, one `xhtml:link` per alternate + x-default. */\nfunction buildUrlEntry(\n entry: PathEntry,\n currentLocale: string,\n alternates: readonly Alternate[],\n opts: SitemapOptions,\n base: string,\n): string {\n const loc = absoluteUrl(base, opts.prefix, currentLocale, entry.path)\n const links = alternates.map(\n (alt) => ` ${hreflangLink(alt.locale, absoluteUrl(base, opts.prefix, alt.locale, alt.path))}`,\n )\n // x-default → the default-locale URL, when the document is published there.\n const defaultAlt = alternates.find((alt) => alt.locale === opts.defaultLocale)\n if (defaultAlt) {\n links.push(\n ` ${hreflangLink('x-default', absoluteUrl(base, opts.prefix, defaultAlt.locale, defaultAlt.path))}`,\n )\n }\n return (\n ' <url>\\n' +\n ` <loc>${escapeXml(loc)}</loc>\\n` +\n ` <lastmod>${entry.updatedAt.toISOString()}</lastmod>\\n` +\n `${links.join('\\n')}\\n` +\n ' </url>'\n )\n}\n\n/** Build the `<sitemapindex>` referencing every produced urlset file. */\nfunction buildIndex(files: ReadonlyArray<{ filename: string; lastmod: string }>, base: string): string {\n const entries = files.map(\n (f) =>\n ' <sitemap>\\n' +\n ` <loc>${escapeXml(`${base}/${f.filename}`)}</loc>\\n` +\n ` <lastmod>${f.lastmod}</lastmod>\\n` +\n ' </sitemap>',\n )\n return `${INDEX_HEADER}\\n${entries.join('\\n')}\\n</sitemapindex>\\n`\n}\n\n/** One `<xhtml:link rel=\"alternate\" hreflang=... href=.../>` tag (both values escaped). */\nfunction hreflangLink(hreflang: string, href: string): string {\n return `<xhtml:link rel=\"alternate\" hreflang=\"${escapeXml(hreflang)}\" href=\"${escapeXml(href)}\"/>`\n}\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\n/** `baseUrl` + optional `prefix(locale)` + `path` — the absolute, un-escaped URL. */\nfunction absoluteUrl(\n base: string,\n prefix: SitemapOptions['prefix'],\n locale: string,\n path: string,\n): string {\n return `${base}${prefix ? prefix(locale) : ''}${path}`\n}\n\n/** Strip any trailing slash(es) so `base + '/' + file` / `base + path` never doubles up. */\nfunction stripTrailingSlash(url: string): string {\n return url.replace(/\\/+$/, '')\n}\n\n/**\n * Escape the five XML predefined entities. `&` MUST be replaced first so the\n * entity ampersands it introduces are not re-escaped.\n */\nfunction escapeXml(value: string): string {\n return value\n .replace(/&/g, '&')\n .replace(/</g, '<')\n .replace(/>/g, '>')\n .replace(/\"/g, '"')\n .replace(/'/g, ''')\n}\n\n/** `sitemap-<locale>.xml` (index 0) / `sitemap-<locale>-<n>.xml` (splits, n≥2). */\nfunction urlsetFilename(locale: string, index: number): string {\n return index === 0 ? `sitemap-${locale}.xml` : `sitemap-${locale}-${index + 1}.xml`\n}\n\n/**\n * A finite, ≥1 integer from a config-derived value, else `fallback`. Guards a 0 /\n * negative / fractional / NaN `maxUrlsPerFile` or `batchSize` from producing a\n * zero-length split loop.\n */\nfunction normalizePositiveInt(value: number | undefined, fallback: number): number {\n if (value === undefined || !Number.isFinite(value)) return fallback\n const floored = Math.floor(value)\n return floored >= 1 ? floored : fallback\n}\n\n/**\n * Buffer an async source into fixed-size chunks — bounds the per-batch\n * cross-locale fan-out (see module header). The final chunk may be short.\n */\nasync function* chunkAsync<T>(source: AsyncIterable<T>, size: number): AsyncGenerator<T[]> {\n let buffer: T[] = []\n for await (const item of source) {\n buffer.push(item)\n if (buffer.length >= size) {\n yield buffer\n buffer = []\n }\n }\n if (buffer.length > 0) yield buffer\n}\n","/**\n * Build-time redirect list for SSG frontends (plan/routing PR08; phase\n * `06-frontend-adapters.md` §3, finding F037 point 3).\n *\n * `getRedirects` streams the full `(from, to, status)` redirect set for one\n * locale — the manual (`toolkit_redirects`) rows PLUS the automatic historical\n * (`toolkit_paths` non-canonical) rows — so a frontend can materialize a static\n * redirect map (`_redirects` / `vercel.json` / an nginx include) at build time.\n * It is a PURE generator, not an HTTP endpoint: the frontend recipe (PR08 Task\n * 2b) maps the yielded entries into its host's adapter format.\n *\n * **Security (CLAUDE.md #1).** The output feeds a public, static build artifact,\n * so a redirect must NEVER point at content the live site would 404 — a static\n * 301 to unpublished content has no request-time fallback to catch it (unlike\n * `resolvePath`, where the target's own canonical tier re-checks). So every\n * redirect whose target is a resolved DOCUMENT (entity-kind manual + all\n * historical) is publish-gated with the SAME batched `filterPublished` primitive\n * `enumeratePaths` / `generateSitemap` use, and an unpublished target is DROPPED\n * — mirroring `resolvePath`'s tier-4 `checkPublished` gate. `url`-kind targets\n * are admin-authored external URLs (never a public write); `path`-kind targets\n * are gated on the target path currently serving canonical content, matching\n * `resolveManualRedirect`'s own path-kind branch.\n *\n * **No unbounded fan-out (CLAUDE.md \"no amplification\").** Both halves are\n * keyset-paginated on the immutable `id` PK (one index query per page), and the\n * document resolution + publish check are BATCHED — one `getCanonicalPaths` +\n * one `filterPublished` per (page × distinct entity-type group), never one query\n * per row (mirrors `enumeratePaths`'s / the sitemap's own bound). Manual redirects\n * are admin-authored (bounded volume, not content-scaled) but are still paginated\n * on principle. The only inherently per-row read is the `path`-kind existence\n * check — one bounded `limit: 1` lookup per surviving `path`-kind manual row —\n * which can't be batched (it keys on the target PATH, not an id set) and rides on\n * the same bounded admin-authored volume.\n *\n * **Precedence, mirroring `resolvePath`.** `resolvePath` resolves\n * canonical → manual → historical, and within manual a locale-specific row wins\n * over the catch-all (`locale IS NULL`) row (`lookupManualRedirect`). This list\n * reproduces that ordering: locale-specific manual rows first (claiming their\n * `from`), then catch-all manual rows (skipped where a locale-specific row\n * already claimed the path), then historical rows (skipped where ANY manual\n * redirect claimed the path — matching resolvePath's tier-3-before-tier-4\n * short-circuit, which fires even when the manual row itself resolves to nothing).\n *\n * **Not reproduced (deliberate, deps stay minimal).** (1) The homepage-collision\n * collapse (`resolvePath` sends a redirect that targets the homepage document\n * straight to `/`): a manual/historical redirect targeting the homepage instead\n * emits its pattern URL, which the live `resolvePath` then 301s to `/` — one\n * extra hop for a rare case, not a broken link, and it avoids threading a\n * `homepageReader` dep. (2) `path`-kind live multi-hop walking: `path` targets are\n * collapsed to ≤1 hop at save time (`collapsePathTarget`, phase 04 §3), so a\n * single existence lookup suffices; a rebuild re-runs this generator whenever\n * redirects change. (3) The multi-document historical collision (two docs holding\n * a historical row at the same path — findRedirectTarget's documented\n * approximate/self-healing edge, F014): this list emits at most one rule per\n * `from` (first that resolves, in id order) rather than most-recent-updated wins.\n *\n * **Leaf module.** Every cross-package dependency is injected via `deps`; this\n * module imports no `@murumets-ee/core` and no `server-only` graph. Concrete deps\n * are built from an app in `./resolve-context.ts` (`buildRedirectsListDeps`).\n */\n\nimport {\n type CanonicalPathsBatchDeps,\n getCanonicalPaths,\n type PathEnumReader,\n type PathEnumRow,\n type PathEnumWhere,\n type PublishFilter,\n} from './enumerate.js'\nimport { normalizePath } from './generate-path.js'\nimport type { RedirectTarget } from '../redirects/target.js'\n\n// ---------------------------------------------------------------------------\n// Read surface — `type` aliases (not interfaces) so the real\n// `ToolkitRedirectsClient`, typed against `WhereClause`'s template-literal index\n// signature, stays assignable without a cast (same rationale as\n// `PathEnumReader` / `index-reader.ts`'s Deviation-1).\n// ---------------------------------------------------------------------------\n\n/** The projected `toolkit_redirects` row the manual-redirect enumeration reads. */\nexport type RedirectListRow = {\n id: string\n fromPath: string\n /** BCP47 locale, or `null` for the catch-all (all-locales) row. */\n locale: string | null\n target: RedirectTarget\n status: number\n}\n\n/**\n * The (operator-carrying) where shapes the manual enumeration issues: a keyset\n * `id > cursor` plus a `locale` equality (a concrete locale, or `null` for the\n * catch-all stratum). A subset of the real client's `WhereClause`, so the real\n * `ToolkitRedirectsClient` is assignable to {@link RedirectListReader}.\n */\nexport type RedirectListWhere = {\n id?: { gt: string }\n locale?: string | null\n}\n\n/**\n * The batched keyset read surface the manual half needs over `toolkit_redirects`.\n * Construct the real client directly (`toolkitRedirectsTable.makeClient(db)`) —\n * it satisfies this type.\n */\nexport type RedirectListReader = {\n findMany(options: {\n where?: RedirectListWhere\n orderBy?: Array<{ column: 'id'; dir?: 'asc' | 'desc' }>\n limit?: number\n }): Promise<RedirectListRow[]>\n}\n\n// ---------------------------------------------------------------------------\n// Public surface\n// ---------------------------------------------------------------------------\n\n/** One emitted redirect. `301` permanent, `302` temporary (phase 05 §2 shape). */\nexport interface RedirectEntry {\n from: string\n to: string\n status: 301 | 302\n}\n\n/** Options for {@link getRedirects}. */\nexport interface RedirectsListOptions {\n /** Emit this locale's redirects only (mirrors `enumeratePaths` / `generateSitemap`). */\n locale: string\n}\n\n/** Injected dependencies for {@link getRedirects}. */\nexport interface RedirectsListDeps {\n /** Keyset reader over `toolkit_redirects` (manual redirects). */\n redirectsClient: RedirectListReader\n /**\n * Keyset reader over `toolkit_paths` — the historical (non-canonical) rows AND\n * the `path`-kind existence check. Reuses `enumeratePaths`'s exact reader shape.\n */\n pathsClient: PathEnumReader\n /** Batched forward index read for owning-document current-canonical resolution. */\n canonicalBatch: CanonicalPathsBatchDeps\n /** The SAME batched publish filter `enumeratePaths` / `generateSitemap` use. */\n filterPublished: PublishFilter\n}\n\n/** Internal tuning seam (page size). Real callers omit it. */\nexport interface RedirectsListTuning {\n /** Rows per keyset page. Defaults to {@link REDIRECTS_PAGE_SIZE}. Tests force a small value. */\n pageSize?: number\n}\n\n/**\n * Redirect-list page size — same order of magnitude as `enumeratePaths`'s\n * `ENUMERATE_PAGE_SIZE` (200). Must stay ≤ the `defineTable` `MAX_LIMIT` (1000),\n * which THROWS rather than clamps.\n */\nconst REDIRECTS_PAGE_SIZE = 200\n\n/**\n * Stream the redirect list for `opts.locale`: manual redirects (locale-specific\n * then catch-all, deduped by precedence) followed by historical redirects\n * (skipping any `from` a manual redirect already claimed). See the module header\n * for the security + fan-out + precedence guarantees.\n */\nexport async function* getRedirects(\n opts: RedirectsListOptions,\n deps: RedirectsListDeps,\n tuning: RedirectsListTuning = {},\n): AsyncGenerator<RedirectEntry> {\n const { locale } = opts\n const pageSize = tuning.pageSize ?? REDIRECTS_PAGE_SIZE\n\n /**\n * Every `from` a manual redirect (either stratum) OWNS for this locale. Serves\n * two roles: (1) a locale-specific row shadows a catch-all row at the same\n * path; (2) ANY manual redirect at a path shadows the historical tier there —\n * even when the manual row itself resolves to nothing (resolvePath tier-3\n * short-circuit). Populated for EVERY manual row seen (dropped or emitted).\n */\n const manualFrom = new Set<string>()\n\n // ── Tier 3a: locale-specific manual redirects ──────────────────────────────\n yield* manualRedirects(locale, locale, deps, pageSize, manualFrom)\n // ── Tier 3b: catch-all (locale IS NULL) manual redirects ───────────────────\n // `manualFrom` now holds every locale-specific `from`, so catch-all rows at\n // those paths are suppressed inside `manualRedirects`.\n yield* manualRedirects(locale, null, deps, pageSize, manualFrom)\n\n // ── Tier 4: historical (automatic rename) redirects ────────────────────────\n yield* historicalRedirects(locale, deps, pageSize, manualFrom)\n}\n\n// ---------------------------------------------------------------------------\n// Manual redirects\n// ---------------------------------------------------------------------------\n\n/**\n * Stream one `locale` stratum of `toolkit_redirects` (a concrete locale, or\n * `null` for the catch-all rows), keyset-paginated. Records every surviving\n * `from` in `manualFrom` (for precedence + historical shadowing) and yields the\n * resolved, publish-gated entries in id-ascending order.\n */\nasync function* manualRedirects(\n locale: string,\n whereLocale: string | null,\n deps: RedirectsListDeps,\n pageSize: number,\n manualFrom: Set<string>,\n): AsyncGenerator<RedirectEntry> {\n let cursorId: string | undefined\n for (;;) {\n const where: RedirectListWhere = { locale: whereLocale }\n if (cursorId !== undefined) where.id = { gt: cursorId }\n\n const page = await deps.redirectsClient.findMany({\n where,\n orderBy: [{ column: 'id', dir: 'asc' }],\n limit: pageSize,\n })\n if (page.length === 0) break\n\n // Drop rows whose `from` a higher-precedence manual redirect already claimed\n // (a locale-specific row shadowing a catch-all one). Record every surviving\n // `from` — even one we go on to DROP — so precedence + historical shadowing\n // hold regardless of resolution outcome (matches resolvePath's short-circuit).\n const survivors: RedirectListRow[] = []\n for (const row of page) {\n if (manualFrom.has(row.fromPath)) continue\n manualFrom.add(row.fromPath)\n survivors.push(row)\n }\n\n // Batched entity-kind resolution: group by target entity type, then ONE\n // getCanonicalPaths + ONE filterPublished per type group (never per row).\n const resolvedEntityTo = await resolveEntityTargets(survivors, locale, deps)\n\n // Emit in survivor (id) order.\n for (const row of survivors) {\n const status = toRedirectStatus(row.status)\n const target = row.target\n\n if (target.kind === 'url') {\n // Terminal external URL — admin-authored, no publish gate, no self-loop.\n yield { from: row.fromPath, to: target.url, status }\n continue\n }\n\n if (target.kind === 'entity') {\n const to = resolvedEntityTo.get(row.id)\n // Dropped when unpublished / no canonical row (matches resolvePath's\n // tier-3 `{kind:'none'}`). Skip a degenerate self-redirect too.\n if (to !== undefined && to !== row.fromPath) {\n yield { from: row.fromPath, to, status }\n }\n continue\n }\n\n // target.kind === 'path' — collapsed to ≤1 hop at save time, so one bounded\n // existence lookup suffices. Emit only when the target path currently serves\n // canonical content (matches resolveManualRedirect's path-kind branch).\n const to = normalizePath(target.path)\n if (to === row.fromPath) continue\n if (await pathServesCanonical(deps.pathsClient, locale, to)) {\n yield { from: row.fromPath, to, status }\n }\n }\n\n const lastRow = page[page.length - 1]\n if (!lastRow) break\n cursorId = lastRow.id\n if (page.length < pageSize) break\n }\n}\n\n/**\n * Resolve the entity-kind targets in a page to their published canonical path,\n * BATCHED by entity type: one `getCanonicalPaths` (forward index) + one\n * `filterPublished` (publish gate) per distinct target type — never per row\n * (mirrors the sitemap's `resolveAlternates` bucketing). Returns a\n * `redirectRowId → path` map holding only the rows that resolve AND publish.\n */\nasync function resolveEntityTargets(\n rows: readonly RedirectListRow[],\n locale: string,\n deps: RedirectsListDeps,\n): Promise<Map<string, string>> {\n const result = new Map<string, string>()\n\n // Group entity-kind rows by target entity type (bounded: routable types are\n // few + config-fixed). Capture `(redirectRowId, targetId)` while the union arm\n // is still narrowed, so no discriminant re-cast is needed downstream.\n const targetsByType = new Map<string, Array<{ rowId: string; targetId: string }>>()\n for (const row of rows) {\n if (row.target.kind !== 'entity') continue\n const pair = { rowId: row.id, targetId: row.target.id }\n const bucket = targetsByType.get(row.target.entity)\n if (bucket) bucket.push(pair)\n else targetsByType.set(row.target.entity, [pair])\n }\n\n for (const [type, targets] of targetsByType) {\n const ids = targets.map((t) => t.targetId)\n // (1) Forward index: which target ids have a canonical row in `locale`?\n const pathMap = await getCanonicalPaths(type, ids, locale, deps.canonicalBatch)\n const candidateIds = [...pathMap.keys()]\n if (candidateIds.length === 0) continue\n // (2) Publish gate: of THOSE, which are actually published in `locale`?\n const published = await deps.filterPublished(type, candidateIds, locale)\n for (const { rowId, targetId } of targets) {\n const path = pathMap.get(targetId)\n if (path !== undefined && published.has(targetId)) result.set(rowId, path)\n }\n }\n\n return result\n}\n\n/** True iff `path` currently serves a canonical document in `locale` (one bounded lookup). */\nasync function pathServesCanonical(\n pathsClient: PathEnumReader,\n locale: string,\n path: string,\n): Promise<boolean> {\n const rows = await pathsClient.findMany({\n where: { locale, path, isCanonical: true },\n limit: 1,\n })\n return rows.length > 0\n}\n\n// ---------------------------------------------------------------------------\n// Historical redirects\n// ---------------------------------------------------------------------------\n\n/**\n * Stream the historical (automatic rename) redirects for `locale`: the demoted\n * (`is_canonical = false`) `toolkit_paths` rows, each resolved to its owning\n * document's CURRENT canonical path. Keyset-paginated; per page, ONE\n * `getCanonicalPaths` + ONE `filterPublished` per entity-type group (never per\n * row). Drops rows whose document has no live published canonical variant\n * anymore (matches `findRedirectTarget`'s `null`), and any `from` a manual\n * redirect already claimed (tier-3 wins) or an already-emitted historical `from`\n * (at most one rule per `from`).\n */\nasync function* historicalRedirects(\n locale: string,\n deps: RedirectsListDeps,\n pageSize: number,\n manualFrom: ReadonlySet<string>,\n): AsyncGenerator<RedirectEntry> {\n /** Historical `from`s already emitted — dedup the documented multi-doc collision. */\n const emittedFrom = new Set<string>()\n let cursorId: string | undefined\n for (;;) {\n const where: PathEnumWhere = { locale, isCanonical: false }\n if (cursorId !== undefined) where.id = { gt: cursorId }\n\n const page = await deps.pathsClient.findMany({\n where,\n orderBy: [{ column: 'id', dir: 'asc' }],\n limit: pageSize,\n })\n if (page.length === 0) break\n\n // Group this page's rows by entity type, then ONE batched canonical lookup +\n // ONE publish check per group. `entityId → current published canonical path`.\n const byType = new Map<string, PathEnumRow[]>()\n for (const row of page) {\n const bucket = byType.get(row.entityType)\n if (bucket) bucket.push(row)\n else byType.set(row.entityType, [row])\n }\n\n const currentPath = new Map<string, string>()\n for (const [type, rows] of byType) {\n const ids = rows.map((r) => r.entityId)\n const pathMap = await getCanonicalPaths(type, ids, locale, deps.canonicalBatch)\n const candidateIds = [...pathMap.keys()]\n if (candidateIds.length === 0) continue\n const published = await deps.filterPublished(type, candidateIds, locale)\n for (const [id, path] of pathMap) {\n if (published.has(id)) currentPath.set(id, path)\n }\n }\n\n for (const row of page) {\n // A manual redirect at this path wins (tier 3 before tier 4).\n if (manualFrom.has(row.path)) continue\n // Already emitted a historical rule at this `from` (multi-doc collision).\n if (emittedFrom.has(row.path)) continue\n const to = currentPath.get(row.entityId)\n if (to === undefined) continue // no live published canonical → dropped\n if (to === row.path) continue // self-redirect (from == to) → skip\n emittedFrom.add(row.path)\n yield { from: row.path, to, status: 301 }\n }\n\n const lastRow = page[page.length - 1]\n if (!lastRow) break\n cursorId = lastRow.id\n if (page.length < pageSize) break\n }\n}\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Narrow the DB `status` integer (validated `301 | 302` at write time) to the\n * result union. Defaults to `301` for any unexpected value — never a raw number\n * leaking into the typed entry (mirrors `resolve.ts`'s `toRedirectStatus`).\n */\nfunction toRedirectStatus(status: number): 301 | 302 {\n return status === 302 ? 302 : 301\n}\n"],"mappings":"wMA+JA,eAAuB,EACrB,EACA,EACA,EAA+B,CAAC,EACL,CAC3B,IAAM,EAAW,EAAO,UAAY,IAC9B,EAAc,EAAO,oBAAsB,EAC3C,CAAE,SAAQ,cAAe,EAI3B,EAA+B,EAAK,QACxC,OAAS,CAIP,IAAM,EAAuB,CAAE,SAAQ,YAAa,EAAK,EACrD,IAAe,IAAA,KAAW,EAAM,WAAa,GAC7C,IAAa,IAAA,KAAW,EAAM,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}from"@murumets-ee/entity";import{combineAdminRoutes as s,defineAdminRoute as c,getContext as l,safeAudit as u}from"@murumets-ee/core";import{and as d,eq as f}from"drizzle-orm";import{z as p}from"zod";import{entityRefs as m}from"@murumets-ee/entity/refs";const h=[`admin`,`editor`];function g(e,t=200){return new Response(JSON.stringify(e),{status:t,headers:{"Content-Type":`application/json`}})}const _={kind:`none`};function v(e){return e===null||e.length===0?{error:`query param 'path' is required`}:e.length>2048?{error:`query param 'path' is too long`}:e.startsWith(`/`)?e.startsWith(`//`)?{error:`query param 'path' must not be protocol-relative`}:e.includes(`?`)||e.includes(`#`)?{error:`query param 'path' must not include a query or fragment`}:{path:e}:{error:`query param 'path' must start with '/'`}}function y(t,n){let r=e(),i=t??n??r.defaultLocale;return(l()?.availableLocales??r.locales.map(e=>e.code)).includes(i)?{locale:i}:{error:`query param 'locale' is not a content locale`}}const b=async(e,t)=>{let n=new URL(e.url).searchParams,r=v(n.get(`path`));if(`error`in r)return g({error:r.error},400);let a=y(n.get(`locale`),t.locale??t.defaultLocale);if(`error`in a)return g({error:a.error},400);let{locale:o}=a,{buildResolveDeps:s}=await import(`./resolve-context-p3m6gn3_.mjs`).then(e=>e.l),c=s(t.app),l=(e,n)=>t.checkPermission(e,`view`)?{kind:`document`,entityType:e,id:n}:_,u=await i(r.path,o,c);if(u.kind===`document`)return g(l(u.entityType,u.id));if(u.kind===`none`)return g(_);if(!(u.to.startsWith(`/`)&&!u.to.startsWith(`//`)))return g({kind:`redirect`,to:u.to});let d=await i(u.to,o,c);return g(d.kind===`document`?l(d.entityType,d.id):_)};function x(){return s([c({prefix:`paths`,path:`resolve`,method:`GET`,permission:`path:resolve`,defaultRoles:h,description:`Resolve a site URL path to the CMS document that serves it (editor canvas link navigation).`,handler:b})])}var S=class extends Error{fromPath;prefix;constructor(e,t){super(`Redirect source "${e}" falls under the reserved prefix "${t}" and cannot be used — that path range is owned by the framework.`),this.name=`RedirectReservedPrefixError`,this.fromPath=e,this.prefix=t}},C=class extends Error{fromPath;locale;conflictingLocale;constructor(e,t,n){super(`Redirect source "${e}" already serves content in locale "${n}" (it is a live canonical URL). Choose a different source path, or unpublish/rename the content first.`),this.name=`RedirectServesContentError`,this.fromPath=e,this.locale=t,this.conflictingLocale=n}},w=class extends Error{entity;constructor(e){super(`Redirect target references entity type "${e}", which is not a registered entity. Check the entity name.`),this.name=`RedirectUnknownEntityError`,this.entity=e}},T=class extends Error{entity;id;constructor(e,t){super(`Redirect target ${e} "${t}" does not exist. Redirect to a document that exists, or use a URL/path target instead.`),this.name=`RedirectTargetNotFoundError`,this.entity=e,this.id=t}},E=class extends Error{fromPath;locale;constructor(e,t){super(`Redirect source "${e}"${t===null?``:` (locale "${t}")`} resolves back to itself — a redirect cannot point at its own source path. Choose a different destination.`),this.name=`RedirectSelfReferenceError`,this.fromPath=e,this.locale=t}};const D=`toolkit_redirects`;async function O(e,t,n){n.kind===`entity`&&await e.insert(m).values({sourceEntity:D,sourceId:t,sourceField:`target`,targetEntity:n.entity,targetId:n.id,relationKind:`link`}).onConflictDoNothing()}async function k(e,t){await e.delete(m).where(d(f(m.sourceEntity,D),f(m.sourceId,t)))}const A=p.discriminatedUnion(`kind`,[p.object({kind:p.literal(`entity`),entity:p.string().min(1),id:p.string().uuid()}),p.object({kind:p.literal(`url`),url:p.string().max(2048).url()}),p.object({kind:p.literal(`path`),path:p.string().min(1).max(2048).startsWith(`/`)})]);function j(e){return r(e)}function ee(e){let t=j(e.fromPath),n=o(t,e.reservedPathPrefixes);if(n!==void 0)throw new S(t,n)}async function te(e){let t=j(e.fromPath);if(e.locale!==null){let n=await e.pathsClient.findOne({path:t,isCanonical:!0,locale:e.locale});if(n)throw new C(t,e.locale,n.locale);return}let n=await e.pathsClient.findOne({path:t,isCanonical:!0,locale:{in:[...e.configuredLocales]}});if(n)throw new C(t,null,n.locale)}async function M(e){if(e.target.kind!==`path`)return e.target;let t=j(e.target.path),n=e.excludeId===void 0?{}:{id:{ne:e.excludeId}};if(e.locale!==null){let r=await e.redirectsClient.findOne({fromPath:t,locale:e.locale,...n});if(r)return r.target}let r=await e.redirectsClient.findOne({fromPath:t,locale:null,...n});return r?r.target:{kind:`path`,path:t}}async function N(e){if(e.target.kind!==`entity`)return;let{entity:t,id:n}=e.target,r=e.resolveClient(t);if(r===void 0)throw new w(t);if(await r.findById(n)==null)throw new T(t,n)}const P=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,F=/^[a-zA-Z0-9:_.-]{1,100}$/,I=`redirect:manage`,L=[`admin`];function R(e,t=200){return new Response(JSON.stringify(e),{status:t,headers:{"Content-Type":`application/json`}})}function z(e,t){return R({error:e},t)}async function B(e,t){let n;try{n=await e.json()}catch{return{response:z(`Invalid JSON body`,400)}}let r=t.safeParse(n);if(!r.success){let e=r.error.issues[0];return{response:z(e?`${e.path.join(`.`)||`body`}: ${e.message}`:`Invalid body`,400)}}return{data:r.data}}function V(e,t){if(e===null||!/^\d+$/.test(e))return t;let n=Number(e);return Number.isSafeInteger(n)?n:t}function H(e){return e.name===void 0?{userId:e.id}:{userId:e.id,userName:e.name}}async function U(){let{getApp:e}=await import(`@murumets-ee/core`);return e()}async function W(){return(await U()).db.readWrite}async function G(){let e=await U();return t=>{let n=e.entities.get(t);return n?e.getClient(n):void 0}}function K(e){return e}const q=p.union([p.literal(301),p.literal(302)]),J=p.string().min(1).max(2048).startsWith(`/`),Y=p.object({locale:p.string().min(1).nullable(),fromPath:J,target:A,status:q.default(301)}),X=p.object({locale:p.string().min(1).nullable().optional(),fromPath:J.optional(),target:A.optional(),status:q.optional()});function Z(t){return t===null||e().locales.map(e=>e.code).includes(t)?null:z(`Unknown locale "${t}" — not one of the configured content locales.`,400)}function Q(e){if(e instanceof S)return R({error:e.message,fromPath:e.fromPath,prefix:e.prefix},409);if(e instanceof C)return R({error:e.message,fromPath:e.fromPath,locale:e.locale,conflictingLocale:e.conflictingLocale},409);if(e instanceof E)return R({error:e.message,fromPath:e.fromPath,locale:e.locale},409);if(e instanceof w)return R({error:e.message,entity:e.entity},400);if(e instanceof T)return R({error:e.message,entity:e.entity,id:e.id},400);if(t(e))return R({error:`A redirect already exists for this locale + source path.`},409);throw e}async function $(t){let r=e(),i=r.reservedPathPrefixes??[],o=r.locales.map(e=>e.code),s=j(t.fromPath);return ee({fromPath:s,reservedPathPrefixes:i}),await N({target:t.target,resolveClient:t.resolveClient}),(await W()).transaction(async e=>{let r=K(e),i=n.makeClient(r),c=a.makeClient(r);await te({fromPath:s,locale:t.locale,configuredLocales:o,pathsClient:c});let l=await M({target:t.target,locale:t.locale,redirectsClient:i,...t.id===null?{}:{excludeId:t.id}});if(l.kind===`path`&&j(l.path)===s)throw new E(s,t.locale);if(t.id===null){let e=await i.insert({locale:t.locale,fromPath:s,target:l,status:t.status,createdBy:t.userId});return await O(r,e.id,l),e}let u=await i.update({id:t.id},{locale:t.locale,fromPath:s,target:l,status:t.status,updatedAt:new Date});return u?(await k(r,t.id),await O(r,t.id,l),u):null})}const ne=async e=>{let t=new URL(e.url),r=t.searchParams.get(`locale`),i=Math.min(Math.max(V(t.searchParams.get(`limit`),50),1),200),a=Math.min(V(t.searchParams.get(`offset`),0),1e5),o;if(r!==null&&r!==``){let e=Z(r);if(e)return e;o=r}let s=n.makeClient(await W());return R({items:o===void 0?await s.findMany({orderBy:[{column:`createdAt`,dir:`desc`}],limit:i,offset:a}):await s.findMany({where:{locale:o},orderBy:[{column:`createdAt`,dir:`desc`}],limit:i,offset:a}),total:o===void 0?await s.count():await s.count({locale:o})})},re=async(e,t)=>{let n=await B(e,Y);if(`response`in n)return n.response;let r=n.data,i=Z(r.locale);if(i)return i;try{let e=await G(),n=await $({id:null,locale:r.locale,fromPath:r.fromPath,target:r.target,status:r.status,userId:t.user.id,resolveClient:e});return n?(u(t,{action:`redirect.created`,entityType:`redirect`,entityId:n.id,...H(t.user),metadata:{locale:n.locale,fromPath:n.fromPath,targetKind:n.target.kind}}),R({item:n},201)):z(`Failed to create redirect`,500)}catch(e){return Q(e)}},ie=async(e,t)=>{let r=t.segments[0];if(!r||!P.test(r))return z(`Invalid id`,400);let i=await B(e,X);if(`response`in i)return i.response;let a=i.data,o=await n.makeClient(await W()).findOne({id:r});if(!o)return z(`Not found`,404);let s=a.locale===void 0?o.locale:a.locale,c=a.fromPath===void 0?o.fromPath:a.fromPath,l=a.target===void 0?o.target:a.target,d=a.status===void 0?o.status:a.status,f=Z(s);if(f)return f;try{let e=await G(),n=await $({id:r,locale:s,fromPath:c,target:l,status:d,userId:t.user.id,resolveClient:e});return n?(u(t,{action:`redirect.updated`,entityType:`redirect`,entityId:n.id,...H(t.user),metadata:{locale:n.locale,fromPath:n.fromPath,targetKind:n.target.kind}}),R({item:n})):z(`Not found`,404)}catch(e){return Q(e)}},ae=async(e,t)=>{let r=t.segments[0];if(!r||!P.test(r))return z(`Invalid id`,400);let i=await(await W()).transaction(async e=>{let t=K(e);return await k(t,r),n.makeClient(t).delete({id:r})});return i?(u(t,{action:`redirect.deleted`,entityType:`redirect`,entityId:r,...H(t.user),metadata:{locale:i.locale,fromPath:i.fromPath}}),R({ok:!0})):z(`Not found`,404)},oe=async e=>{let t=new URL(e.url),n=t.searchParams.get(`entityType`),r=t.searchParams.get(`entityId`);if(!n||!F.test(n))return z(`entityType is required`,400);if(!r||!P.test(r))return z(`entityId is required and must be a UUID`,400);let i=t.searchParams.get(`locale`),o;if(i!==null&&i!==``){let e=Z(i);if(e)return e;o=i}return R({items:await a.makeClient(await W()).findMany({where:{entityType:n,entityId:r,isCanonical:!1,...o!==void 0&&{locale:o}},orderBy:[{column:`updatedAt`,dir:`desc`}],limit:100})})};function se(){return s([c({prefix:`redirects`,path:``,method:`GET`,permission:I,defaultRoles:L,description:`List manual URL redirects (paginated, optional locale filter).`,handler:ne}),c({prefix:`redirects`,path:`history`,method:`GET`,permission:I,defaultRoles:L,description:`Read-only automatic-redirect (rename) history for one document.`,handler:oe}),c({prefix:`redirects`,path:``,method:`POST`,permission:I,defaultRoles:L,description:`Create a manual URL redirect.`,handler:re}),c({prefix:`redirects`,path:``,method:`PATCH`,matchAnyPath:!0,permission:I,defaultRoles:L,description:`Update a manual URL redirect by id.`,handler:ie}),c({prefix:`redirects`,path:``,method:`DELETE`,matchAnyPath:!0,permission:I,defaultRoles:L,description:`Delete a manual URL redirect by id.`,handler:ae})])}export{x as n,se as t};
|
|
2
|
-
//# sourceMappingURL=routes-
|
|
1
|
+
import{t as e}from"./content-config-store-8omQF5p5.mjs";import{h as t,n,p as r,s as i,u as a}from"./schema-BJxAwPrI.mjs";import{matchReservedPrefix as o}from"@murumets-ee/entity";import{combineAdminRoutes as s,defineAdminRoute as c,getContext as l,safeAudit as u}from"@murumets-ee/core";import{and as d,eq as f}from"drizzle-orm";import{z as p}from"zod";import{entityRefs as m}from"@murumets-ee/entity/refs";const h=[`admin`,`editor`];function g(e,t=200){return new Response(JSON.stringify(e),{status:t,headers:{"Content-Type":`application/json`}})}const _={kind:`none`};function v(e){return e===null||e.length===0?{error:`query param 'path' is required`}:e.length>2048?{error:`query param 'path' is too long`}:e.startsWith(`/`)?e.startsWith(`//`)?{error:`query param 'path' must not be protocol-relative`}:e.includes(`?`)||e.includes(`#`)?{error:`query param 'path' must not include a query or fragment`}:{path:e}:{error:`query param 'path' must start with '/'`}}function y(t,n){let r=e(),i=t??n??r.defaultLocale;return(l()?.availableLocales??r.locales.map(e=>e.code)).includes(i)?{locale:i}:{error:`query param 'locale' is not a content locale`}}const b=async(e,t)=>{let n=new URL(e.url).searchParams,r=v(n.get(`path`));if(`error`in r)return g({error:r.error},400);let a=y(n.get(`locale`),t.locale??t.defaultLocale);if(`error`in a)return g({error:a.error},400);let{locale:o}=a,{buildResolveDeps:s}=await import(`./resolve-context-BVk6uObB.mjs`).then(e=>e.l),c=s(t.app),l=(e,n)=>t.checkPermission(e,`view`)?{kind:`document`,entityType:e,id:n}:_,u=await i(r.path,o,c);if(u.kind===`document`)return g(l(u.entityType,u.id));if(u.kind===`none`)return g(_);if(!(u.to.startsWith(`/`)&&!u.to.startsWith(`//`)))return g({kind:`redirect`,to:u.to});let d=await i(u.to,o,c);return g(d.kind===`document`?l(d.entityType,d.id):_)};function x(){return s([c({prefix:`paths`,path:`resolve`,method:`GET`,permission:`path:resolve`,defaultRoles:h,description:`Resolve a site URL path to the CMS document that serves it (editor canvas link navigation).`,handler:b})])}var S=class extends Error{fromPath;prefix;constructor(e,t){super(`Redirect source "${e}" falls under the reserved prefix "${t}" and cannot be used — that path range is owned by the framework.`),this.name=`RedirectReservedPrefixError`,this.fromPath=e,this.prefix=t}},C=class extends Error{fromPath;locale;conflictingLocale;constructor(e,t,n){super(`Redirect source "${e}" already serves content in locale "${n}" (it is a live canonical URL). Choose a different source path, or unpublish/rename the content first.`),this.name=`RedirectServesContentError`,this.fromPath=e,this.locale=t,this.conflictingLocale=n}},w=class extends Error{entity;constructor(e){super(`Redirect target references entity type "${e}", which is not a registered entity. Check the entity name.`),this.name=`RedirectUnknownEntityError`,this.entity=e}},T=class extends Error{entity;id;constructor(e,t){super(`Redirect target ${e} "${t}" does not exist. Redirect to a document that exists, or use a URL/path target instead.`),this.name=`RedirectTargetNotFoundError`,this.entity=e,this.id=t}},E=class extends Error{fromPath;locale;constructor(e,t){super(`Redirect source "${e}"${t===null?``:` (locale "${t}")`} resolves back to itself — a redirect cannot point at its own source path. Choose a different destination.`),this.name=`RedirectSelfReferenceError`,this.fromPath=e,this.locale=t}};const D=`toolkit_redirects`;async function O(e,t,n){n.kind===`entity`&&await e.insert(m).values({sourceEntity:D,sourceId:t,sourceField:`target`,targetEntity:n.entity,targetId:n.id,relationKind:`link`}).onConflictDoNothing()}async function k(e,t){await e.delete(m).where(d(f(m.sourceEntity,D),f(m.sourceId,t)))}const A=p.discriminatedUnion(`kind`,[p.object({kind:p.literal(`entity`),entity:p.string().min(1),id:p.string().uuid()}),p.object({kind:p.literal(`url`),url:p.string().max(2048).url()}),p.object({kind:p.literal(`path`),path:p.string().min(1).max(2048).startsWith(`/`)})]);function j(e){return r(e)}function ee(e){let t=j(e.fromPath),n=o(t,e.reservedPathPrefixes);if(n!==void 0)throw new S(t,n)}async function te(e){let t=j(e.fromPath);if(e.locale!==null){let n=await e.pathsClient.findOne({path:t,isCanonical:!0,locale:e.locale});if(n)throw new C(t,e.locale,n.locale);return}let n=await e.pathsClient.findOne({path:t,isCanonical:!0,locale:{in:[...e.configuredLocales]}});if(n)throw new C(t,null,n.locale)}async function M(e){if(e.target.kind!==`path`)return e.target;let t=j(e.target.path),n=e.excludeId===void 0?{}:{id:{ne:e.excludeId}};if(e.locale!==null){let r=await e.redirectsClient.findOne({fromPath:t,locale:e.locale,...n});if(r)return r.target}let r=await e.redirectsClient.findOne({fromPath:t,locale:null,...n});return r?r.target:{kind:`path`,path:t}}async function N(e){if(e.target.kind!==`entity`)return;let{entity:t,id:n}=e.target,r=e.resolveClient(t);if(r===void 0)throw new w(t);if(await r.findById(n)==null)throw new T(t,n)}const P=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,F=/^[a-zA-Z0-9:_.-]{1,100}$/,I=`redirect:manage`,L=[`admin`];function R(e,t=200){return new Response(JSON.stringify(e),{status:t,headers:{"Content-Type":`application/json`}})}function z(e,t){return R({error:e},t)}async function B(e,t){let n;try{n=await e.json()}catch{return{response:z(`Invalid JSON body`,400)}}let r=t.safeParse(n);if(!r.success){let e=r.error.issues[0];return{response:z(e?`${e.path.join(`.`)||`body`}: ${e.message}`:`Invalid body`,400)}}return{data:r.data}}function V(e,t){if(e===null||!/^\d+$/.test(e))return t;let n=Number(e);return Number.isSafeInteger(n)?n:t}function H(e){return e.name===void 0?{userId:e.id}:{userId:e.id,userName:e.name}}async function U(){let{getApp:e}=await import(`@murumets-ee/core`);return e()}async function W(){return(await U()).db.readWrite}async function G(){let e=await U();return t=>{let n=e.entities.get(t);return n?e.getClient(n):void 0}}function K(e){return e}const q=p.union([p.literal(301),p.literal(302)]),J=p.string().min(1).max(2048).startsWith(`/`),Y=p.object({locale:p.string().min(1).nullable(),fromPath:J,target:A,status:q.default(301)}),X=p.object({locale:p.string().min(1).nullable().optional(),fromPath:J.optional(),target:A.optional(),status:q.optional()});function Z(t){return t===null||e().locales.map(e=>e.code).includes(t)?null:z(`Unknown locale "${t}" — not one of the configured content locales.`,400)}function Q(e){if(e instanceof S)return R({error:e.message,fromPath:e.fromPath,prefix:e.prefix},409);if(e instanceof C)return R({error:e.message,fromPath:e.fromPath,locale:e.locale,conflictingLocale:e.conflictingLocale},409);if(e instanceof E)return R({error:e.message,fromPath:e.fromPath,locale:e.locale},409);if(e instanceof w)return R({error:e.message,entity:e.entity},400);if(e instanceof T)return R({error:e.message,entity:e.entity,id:e.id},400);if(t(e))return R({error:`A redirect already exists for this locale + source path.`},409);throw e}async function $(t){let r=e(),i=r.reservedPathPrefixes??[],o=r.locales.map(e=>e.code),s=j(t.fromPath);return ee({fromPath:s,reservedPathPrefixes:i}),await N({target:t.target,resolveClient:t.resolveClient}),(await W()).transaction(async e=>{let r=K(e),i=n.makeClient(r),c=a.makeClient(r);await te({fromPath:s,locale:t.locale,configuredLocales:o,pathsClient:c});let l=await M({target:t.target,locale:t.locale,redirectsClient:i,...t.id===null?{}:{excludeId:t.id}});if(l.kind===`path`&&j(l.path)===s)throw new E(s,t.locale);if(t.id===null){let e=await i.insert({locale:t.locale,fromPath:s,target:l,status:t.status,createdBy:t.userId});return await O(r,e.id,l),e}let u=await i.update({id:t.id},{locale:t.locale,fromPath:s,target:l,status:t.status,updatedAt:new Date});return u?(await k(r,t.id),await O(r,t.id,l),u):null})}const ne=async e=>{let t=new URL(e.url),r=t.searchParams.get(`locale`),i=Math.min(Math.max(V(t.searchParams.get(`limit`),50),1),200),a=Math.min(V(t.searchParams.get(`offset`),0),1e5),o;if(r!==null&&r!==``){let e=Z(r);if(e)return e;o=r}let s=n.makeClient(await W());return R({items:o===void 0?await s.findMany({orderBy:[{column:`createdAt`,dir:`desc`}],limit:i,offset:a}):await s.findMany({where:{locale:o},orderBy:[{column:`createdAt`,dir:`desc`}],limit:i,offset:a}),total:o===void 0?await s.count():await s.count({locale:o})})},re=async(e,t)=>{let n=await B(e,Y);if(`response`in n)return n.response;let r=n.data,i=Z(r.locale);if(i)return i;try{let e=await G(),n=await $({id:null,locale:r.locale,fromPath:r.fromPath,target:r.target,status:r.status,userId:t.user.id,resolveClient:e});return n?(u(t,{action:`redirect.created`,entityType:`redirect`,entityId:n.id,...H(t.user),metadata:{locale:n.locale,fromPath:n.fromPath,targetKind:n.target.kind}}),R({item:n},201)):z(`Failed to create redirect`,500)}catch(e){return Q(e)}},ie=async(e,t)=>{let r=t.segments[0];if(!r||!P.test(r))return z(`Invalid id`,400);let i=await B(e,X);if(`response`in i)return i.response;let a=i.data,o=await n.makeClient(await W()).findOne({id:r});if(!o)return z(`Not found`,404);let s=a.locale===void 0?o.locale:a.locale,c=a.fromPath===void 0?o.fromPath:a.fromPath,l=a.target===void 0?o.target:a.target,d=a.status===void 0?o.status:a.status,f=Z(s);if(f)return f;try{let e=await G(),n=await $({id:r,locale:s,fromPath:c,target:l,status:d,userId:t.user.id,resolveClient:e});return n?(u(t,{action:`redirect.updated`,entityType:`redirect`,entityId:n.id,...H(t.user),metadata:{locale:n.locale,fromPath:n.fromPath,targetKind:n.target.kind}}),R({item:n})):z(`Not found`,404)}catch(e){return Q(e)}},ae=async(e,t)=>{let r=t.segments[0];if(!r||!P.test(r))return z(`Invalid id`,400);let i=await(await W()).transaction(async e=>{let t=K(e);return await k(t,r),n.makeClient(t).delete({id:r})});return i?(u(t,{action:`redirect.deleted`,entityType:`redirect`,entityId:r,...H(t.user),metadata:{locale:i.locale,fromPath:i.fromPath}}),R({ok:!0})):z(`Not found`,404)},oe=async e=>{let t=new URL(e.url),n=t.searchParams.get(`entityType`),r=t.searchParams.get(`entityId`);if(!n||!F.test(n))return z(`entityType is required`,400);if(!r||!P.test(r))return z(`entityId is required and must be a UUID`,400);let i=t.searchParams.get(`locale`),o;if(i!==null&&i!==``){let e=Z(i);if(e)return e;o=i}return R({items:await a.makeClient(await W()).findMany({where:{entityType:n,entityId:r,isCanonical:!1,...o!==void 0&&{locale:o}},orderBy:[{column:`updatedAt`,dir:`desc`}],limit:100})})};function se(){return s([c({prefix:`redirects`,path:``,method:`GET`,permission:I,defaultRoles:L,description:`List manual URL redirects (paginated, optional locale filter).`,handler:ne}),c({prefix:`redirects`,path:`history`,method:`GET`,permission:I,defaultRoles:L,description:`Read-only automatic-redirect (rename) history for one document.`,handler:oe}),c({prefix:`redirects`,path:``,method:`POST`,permission:I,defaultRoles:L,description:`Create a manual URL redirect.`,handler:re}),c({prefix:`redirects`,path:``,method:`PATCH`,matchAnyPath:!0,permission:I,defaultRoles:L,description:`Update a manual URL redirect by id.`,handler:ie}),c({prefix:`redirects`,path:``,method:`DELETE`,matchAnyPath:!0,permission:I,defaultRoles:L,description:`Delete a manual URL redirect by id.`,handler:ae})])}export{x as n,se as t};
|
|
2
|
+
//# sourceMappingURL=routes-Bc9DcaPk.mjs.map
|