@murumets-ee/menus 0.89.0 → 0.91.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.
@@ -1 +1 @@
1
- {"version":3,"file":"resolve.d.mts","names":[],"sources":["../src/get-menu.ts","../src/menu-resolve-context.ts"],"mappings":";;;;;;AAqEA;;;;AAAkC;AAelC;;;;;;;;;;;;;;AAiB4B;AAc5B;;;;;;;;AAEyB;AAIzB;;;;AAOa;AAQb;;;;AAQM;AAQN;;;;;;;;AAC+B;AAY/B;;;;cAhGa,qBAAA;;UAeI,gBAAA;EAyGF;EAvGb,EAAA;EACA,IAAA;EAgHK;EA9GL,KAAA;EAuH0B;;;;;EAjH1B,IAAA;EACA,MAAA;EAoFE;EAlFF,QAAA;EAoFE;EAlFF,aAAA;EACA,QAAA,EAAU,gBAAgB;AAAA;;;;;;;;;;;;UAcX,YAAA;EACf,MAAA;EACA,KAAA,EAAO,gBAAgB;AAAA;AA2FG;AAAA,UAvFX,cAAA;EA+cc;EA7c7B,MAAA;EA6coF;;;;EAxcpF,WAAW;AAAA;AAwcyE;AAAA,UAhcrE,OAAA;EAqdY;;;;;EA/c3B,QAAA;EAmdQ;EAjdR,IAAI;AAAA;;;;;;UAQW,iBAAA;EACf,IAAA,CAAK,GAAA,UAAa,GAAA;AAAA;;;;ACtFpB;;;;;;UDkGiB,eAAA;EClGqD;AAAA;;;;;;ED0GpE,UAAA,GAAa,MAAA,aAAmB,OAAA,CAAQ,OAAA;;;;;;EAMxC,qBAAA,GACE,UAAA,UACA,GAAA,qBACA,MAAA,aACG,OAAA,CAAQ,WAAA;;EAEb,eAAA,GACE,UAAA,UACA,GAAA,qBACA,MAAA,aACG,OAAA,CAAQ,WAAA;;;;;;EAMb,aAAA,GACE,UAAA,UACA,GAAA,qBACA,MAAA,aACG,OAAA,CAAQ,WAAA;;;;;;;EAOb,aAAA;;EAEA,MAAA,GAAS,iBAAA;AAAA;;;;;;;;;;;;;iBAwXK,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A,UACA,GAAA,qBACA,MAAA,aACG,OAAA,CAAQ,WAAA;;;;;;;EAOb,aAAA;;EAEA,MAAA,GAAS,iBAAA;AAAA;;;;;;;;;;;;;iBAwXK,eAAA,CAAgB,IAAA,EAAM,YAAA,EAAc,WAAA,WAAsB,YAAY;;;;;;;;;;;;;;iBAqBhE,OAAA,CACpB,MAAA,UACA,IAAA,EAAM,cAAA,EACN,IAAA,EAAM,eAAA,GACL,OAAA,CAAQ,YAAA;;;;;;;AA5ec;AAIzB;;iBCrDgB,oBAAA,CAAqB,GAAA,EAAK,UAAA,GAAa,eAAe"}
package/dist/resolve.mjs CHANGED
@@ -1,2 +1,2 @@
1
- import{s as e}from"./menu-entity-types-BnKnKbif.mjs";import{t}from"./entity-BC8r_5xy.mjs";import{resolveLinkHref as n}from"@murumets-ee/blocks/links";import{getContentConfig as r}from"@murumets-ee/content/plugin";import{getEntityTitleField as i}from"@murumets-ee/entity";import{buildCanonicalPathsBatchDeps as a,buildEnumerateDeps as o,getCanonicalPaths as s}from"@murumets-ee/content/resolve";import{createSystemReachResolver as c}from"@murumets-ee/core";import{QueryClient as l}from"@murumets-ee/entity/query";import{eq as u,inArray as d}from"drizzle-orm";const f=16;function p(e,t,n){if(typeof e!=`object`||!e||Array.isArray(e))return;let r=e;for(let e of t===n?[t]:[t,n]){if(!Object.hasOwn(r,e))continue;let t=r[e];if(typeof t==`string`&&t.length>0)return t}}function m(e,t){if(typeof e!=`object`||!e||Array.isArray(e))return;let n=e;if(!Object.hasOwn(n,t))return;let r=n[t];return typeof r==`boolean`?r:void 0}function h(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function g(t,n,r,i){let a=new Map,o=new Map,s=500,c=0;function l(e,t,n){let r=e.get(t);r?r.add(n):e.set(t,new Set([n]))}function u(t,d){if(d>i||!Array.isArray(t))return[];let f=t,g=[];for(let t of f){if(s<=0){c++;continue}if(!h(t))continue;let i=t.id,f=t.kind;if(typeof i!=`string`||i.length===0||f!==`link`&&f!==`header`||m(t.enabled,n)===!1)continue;s--;let _;if(f===`link`){let n=e.safeParse(t.link);if(!n.success)continue;_=n.data}else if(t.link!==void 0)continue;let v=u(t.children,d+1);_?.kind===`entity`&&(l(a,_.entity,_.id),p(t.label,n,r)===void 0&&l(o,_.entity,_.id)),g.push({id:i,kind:f,link:_,label:t.label,newTab:t.newTab===!0,children:v})}return g}return{nodes:u(t,1),idsByType:a,titleIdsByType:o,droppedForBudget:c}}async function _(e,t,n,r){let i=new Map,a=new Map,o=new Map,s=[...e.idsByType.entries()];return s.length>16&&n.logger?.warn({handle:r,locale:t,entityTypes:s.length,cap:16},`menu resolution dropped entity-type groups over the fan-out cap`),await Promise.all(s.slice(0,16).map(async([r,s])=>{let c=[...s],l=await n.resolveCanonicalPaths(r,c,t);if(i.set(r,l),l.size===0)return;let u=[...l.keys()],d=await n.filterPublished(r,u,t);a.set(r,d);let f=e.titleIdsByType.get(r);if(f===void 0)return;let p=u.filter(e=>f.has(e)&&d.has(e));p.length!==0&&o.set(r,await n.resolveTitles(r,p,t))})),{paths:i,published:a,titles:o}}function v(e,t,r,i){let a=[];for(let o of e){let e=v(o.children,t,r,i),s=p(o.label,t,i.defaultLocale);if(o.kind===`header`){if(e.length===0||s===void 0)continue;a.push({id:o.id,kind:`header`,label:s,href:null,newTab:!1,isActive:!1,inActiveTrail:!1,children:e});continue}let c=o.link;if(c===void 0)continue;let l,u=s;if(c.kind===`entity`){let e=r.paths.get(c.entity)?.get(c.id);if(e===void 0||r.published.get(c.entity)?.has(c.id)!==!0)continue;l=c.anchor===void 0?e:`${e}#${c.anchor}`,u??=r.titles.get(c.entity)?.get(c.id)}else l=n(c);l===null||l.length===0||u===void 0||u.length===0||a.push({id:o.id,kind:`link`,label:u,href:l,newTab:o.newTab,isActive:!1,inActiveTrail:!1,children:e})}return a}function y(e){let t=e.indexOf(`#`),n=t===-1?e:e.slice(0,t);return n.length>1&&n.endsWith(`/`)?n.slice(0,-1):n}function b(e,t){let n=!1;return{items:e.map(e=>{let r=b(e.children,t),i=e.href!==null&&y(e.href)===t,a=r.containsActive;return(i||a)&&(n=!0),{...e,isActive:i,inActiveTrail:a,children:r.items}}),containsActive:n}}function x(e,t){return{...e,items:b(e.items,y(t)).items}}async function S(e,t,n){if(e.length===0||e.length>128)return null;let r=await n.getMenuRow(e);if(r===null)return null;let i=r.maxDepth,a=typeof i==`number`&&Number.isInteger(i)&&i>=1?Math.min(i,6):3,o=g(r.tree,t.locale,n.defaultLocale,a);o.droppedForBudget>0&&n.logger?.warn({handle:e,locale:t.locale,dropped:o.droppedForBudget,cap:500},`menu resolution dropped items over the node budget`);let s=await _(o,t.locale,n,e),c={handle:e,items:v(o.nodes,t.locale,s,n)};return t.currentPath===void 0?c:x(c,t.currentPath)}function C(e,t){return e[t]}const w=c(`menu-resolver`);function T(e){let n=e.db.readOnly,c=a(e),{filterPublished:f}=o(e);return{getMenuRow:async r=>{let i=new l({entity:t,db:n,logger:e.logger.child({resolve:`menu`}),contextResolver:w}),a=(await i.findMany({where:u(C(i.getTable(),`handle`),r),limit:1}))[0];return a===void 0?null:{maxDepth:a.maxDepth,tree:a.tree}},resolveCanonicalPaths:(e,t,n)=>s(e,t,n,c),filterPublished:f,resolveTitles:async(t,r,a)=>{let o=new Map;if(r.length===0)return o;let s=e.entities.get(t);if(s===void 0)return o;let c=i(s);if(c===`id`)return o;let u=new l({entity:s,db:n,logger:e.logger.child({resolve:`menu-title`,entity:t}),contextResolver:w}),f=C(u.getTable(),`id`);for(let e=0;e<r.length;e+=500){let t=r.slice(e,e+500),n=await u.findMany({where:d(f,[...t]),locale:a,limit:t.length});for(let e of n){let t=e,n=t.id,r=t[c];typeof n==`string`&&typeof r==`string`&&r.length>0&&o.set(n,r)}}return o},defaultLocale:r().defaultLocale,logger:e.logger.child({resolve:`menu`})}}export{f as MAX_MENU_ENTITY_TYPES,T as buildMenuResolveDeps,S as getMenu,x as markActiveTrail};
1
+ import{s as e}from"./menu-entity-types-BnKnKbif.mjs";import{t}from"./entity-BC8r_5xy.mjs";import{resolveLinkHref as n}from"@murumets-ee/blocks/links";import{getContentConfig as r}from"@murumets-ee/content/plugin";import{getEntityTitleField as i,isTemplateDrawn as a}from"@murumets-ee/entity";import{createDetailTemplateProvider as o}from"@murumets-ee/content/detail-template";import{buildCanonicalPathsBatchDeps as s,buildEnumerateDeps as c,getCanonicalPaths as l}from"@murumets-ee/content/resolve";import{createSystemReachResolver as u}from"@murumets-ee/core";import{QueryClient as d}from"@murumets-ee/entity/query";import{eq as f,inArray as p}from"drizzle-orm";const m=16;function h(e,t,n){if(typeof e!=`object`||!e||Array.isArray(e))return;let r=e;for(let e of t===n?[t]:[t,n]){if(!Object.hasOwn(r,e))continue;let t=r[e];if(typeof t==`string`&&t.length>0)return t}}function g(e,t){if(typeof e!=`object`||!e||Array.isArray(e))return;let n=e;if(!Object.hasOwn(n,t))return;let r=n[t];return typeof r==`boolean`?r:void 0}function _(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function v(t,n,r,i){let a=new Map,o=new Map,s=500,c=0;function l(e,t,n){let r=e.get(t);r?r.add(n):e.set(t,new Set([n]))}function u(t,d){if(d>i||!Array.isArray(t))return[];let f=t,p=[];for(let t of f){if(s<=0){c++;continue}if(!_(t))continue;let i=t.id,f=t.kind;if(typeof i!=`string`||i.length===0||f!==`link`&&f!==`header`||g(t.enabled,n)===!1)continue;s--;let m;if(f===`link`){let n=e.safeParse(t.link);if(!n.success)continue;m=n.data}else if(t.link!==void 0)continue;let v=u(t.children,d+1);m?.kind===`entity`&&(l(a,m.entity,m.id),h(t.label,n,r)===void 0&&l(o,m.entity,m.id)),p.push({id:i,kind:f,link:m,label:t.label,newTab:t.newTab===!0,children:v})}return p}return{nodes:u(t,1),idsByType:a,titleIdsByType:o,droppedForBudget:c}}async function y(e,t,n,r){let i=new Map,a=new Map,o=new Map,s=[...e.idsByType.entries()];return s.length>16&&n.logger?.warn({handle:r,locale:t,entityTypes:s.length,cap:16},`menu resolution dropped entity-type groups over the fan-out cap`),await Promise.all(s.slice(0,16).map(async([r,s])=>{let c=[...s],l=await n.resolveCanonicalPaths(r,c,t);if(i.set(r,l),l.size===0)return;let u=[...l.keys()],d=await n.filterPublished(r,u,t);a.set(r,d);let f=e.titleIdsByType.get(r);if(f===void 0)return;let p=u.filter(e=>f.has(e)&&d.has(e));p.length!==0&&o.set(r,await n.resolveTitles(r,p,t))})),{paths:i,published:a,titles:o}}function b(e,t,r,i){let a=[];for(let o of e){let e=b(o.children,t,r,i),s=h(o.label,t,i.defaultLocale);if(o.kind===`header`){if(e.length===0||s===void 0)continue;a.push({id:o.id,kind:`header`,label:s,href:null,newTab:!1,isActive:!1,inActiveTrail:!1,children:e});continue}let c=o.link;if(c===void 0)continue;let l,u=s;if(c.kind===`entity`){let e=r.paths.get(c.entity)?.get(c.id);if(e===void 0||r.published.get(c.entity)?.has(c.id)!==!0)continue;l=c.anchor===void 0?e:`${e}#${c.anchor}`,u??=r.titles.get(c.entity)?.get(c.id)}else l=n(c);l===null||l.length===0||u===void 0||u.length===0||a.push({id:o.id,kind:`link`,label:u,href:l,newTab:o.newTab,isActive:!1,inActiveTrail:!1,children:e})}return a}function x(e){let t=e.indexOf(`#`),n=t===-1?e:e.slice(0,t);return n.length>1&&n.endsWith(`/`)?n.slice(0,-1):n}function S(e,t){let n=!1;return{items:e.map(e=>{let r=S(e.children,t),i=e.href!==null&&x(e.href)===t,a=r.containsActive;return(i||a)&&(n=!0),{...e,isActive:i,inActiveTrail:a,children:r.items}}),containsActive:n}}function C(e,t){return{...e,items:S(e.items,x(t)).items}}async function w(e,t,n){if(e.length===0||e.length>128)return null;let r=await n.getMenuRow(e);if(r===null)return null;let i=r.maxDepth,a=typeof i==`number`&&Number.isInteger(i)&&i>=1?Math.min(i,6):3,o=v(r.tree,t.locale,n.defaultLocale,a);o.droppedForBudget>0&&n.logger?.warn({handle:e,locale:t.locale,dropped:o.droppedForBudget,cap:500},`menu resolution dropped items over the node budget`);let s=await y(o,t.locale,n,e),c={handle:e,items:b(o.nodes,t.locale,s,n)};return t.currentPath===void 0?c:C(c,t.currentPath)}function T(e,t){return e[t]}const E=u(`menu-resolver`);function D(e){let n=e.db.readOnly,u=s(e),{filterPublished:m}=c(e);return{getMenuRow:async r=>{let i=new d({entity:t,db:n,logger:e.logger.child({resolve:`menu`}),contextResolver:E}),a=(await i.findMany({where:f(T(i.getTable(),`handle`),r),limit:1}))[0];return a===void 0?null:{maxDepth:a.maxDepth,tree:a.tree}},resolveCanonicalPaths:(e,t,n)=>l(e,t,n,u),filterPublished:m,resolveTitles:async(t,s,c)=>{let l=new Map;if(s.length===0)return l;let u=e.entities.get(t);if(u===void 0)return l;let f=a(u)?o(()=>e,{defaultLocale:r().defaultLocale}):void 0,m=i(u);if(f===void 0&&m===`id`)return l;let h=new d({entity:u,db:n,logger:e.logger.child({resolve:`menu-title`,entity:t}),contextResolver:E}),g=T(h.getTable(),`id`);for(let n=0;n<s.length;n+=500){let r=s.slice(n,n+500),i=await h.findMany({where:p(g,[...r]),locale:c,limit:r.length});for(let n of i){let r=n,i=r.id,a;if(f===void 0)a=r[m];else try{a=(await f.publicRow({entity:t,row:r,locale:c})).title}catch(n){e.logger.warn({err:n,entity:t},`menus: detail-template title projection failed — the item is dropped`)}typeof i==`string`&&typeof a==`string`&&a.length>0&&l.set(i,a)}}return l},defaultLocale:r().defaultLocale,logger:e.logger.child({resolve:`menu`})}}export{m as MAX_MENU_ENTITY_TYPES,D as buildMenuResolveDeps,w as getMenu,C as markActiveTrail};
2
2
  //# sourceMappingURL=resolve.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"resolve.mjs","names":[],"sources":["../src/get-menu.ts","../src/internal/columns.ts","../src/menu-resolve-context.ts"],"sourcesContent":["/**\n * `getMenu()` — turn a stored menu tree into a render-ready structure for one\n * locale (plan/routing phase 11 §2), plus the pure `markActiveTrail()` helper\n * (phase 11 §3).\n *\n * **Leaf module.** Every cross-package capability (the menu row read, the\n * `toolkit_paths` forward index, the publish gate, live entity titles) arrives\n * through the injected {@link MenuResolveDeps}; nothing here imports\n * `@murumets-ee/core` or `@murumets-ee/content`. Concrete deps are built from a\n * live app in `./menu-resolve-context.ts` — the same leaf/seam split\n * `@murumets-ee/content`'s `paths/enumerate.ts` ↔ `paths/resolve-context.ts`\n * uses, and the reason the deps' function types are declared structurally here\n * rather than imported (assignability is still checked, at the seam).\n *\n * **Security.** The resolved output feeds PUBLIC page navigation, so it must\n * never surface an unpublished or deleted document:\n * - the menu itself is read through a publish-filtered client (an unpublished\n * menu resolves to `null` — nothing renders),\n * - every entity-linked item must have BOTH a canonical path in\n * `toolkit_paths` for the requested locale AND survive the batched publish\n * gate; missing either → the item (and its subtree) is dropped,\n * - `url` / `email` targets are re-gated through the same `sanitizeHref`\n * protocol allowlist the write path uses, so a value that reached the column\n * by some route other than the entity API (a direct DB edit, a restored\n * dump) still cannot become a `javascript:` href,\n * - every filtering decision fails CLOSED — anything unresolvable is dropped,\n * never rendered with a placeholder.\n *\n * **No unbounded fan-out** (CLAUDE.md). Backend work is bounded by the number\n * of distinct ENTITY TYPES in the tree, never by the number of items: the walk\n * collects ids grouped by type, then issues at most THREE batched calls per\n * group (forward index → publish gate → titles). The group count is itself hard-\n * capped ({@link MAX_MENU_ENTITY_TYPES}) and the walk carries a node budget\n * ({@link MAX_MENU_TREE_NODES}), so one render costs a fixed, small number of\n * round-trips no matter what the stored tree looks like.\n *\n * **Read-time validation is per-node, not whole-tree.** The write path already\n * runs `buildMenuTreeSchema()` (`menuTreeValidation()`), and this module\n * deliberately does NOT re-run it: that schema whitelists locale KEYS against\n * the app's configured locales, so re-parsing at read time would fail the WHOLE\n * menu — site navigation gone — the moment an operator removes a locale from\n * config after a menu was saved. The locale whitelist is a write-time authoring\n * check with no read-time security value. What DOES matter at read time (node\n * shape, the `LinkValue` protocol gate) is re-checked per node here, and a\n * malformed node is dropped on its own without taking the menu down with it.\n */\n\nimport { resolveLinkHref } from '@murumets-ee/blocks/links'\nimport {\n DEFAULT_MENU_DEPTH,\n LinkValueSchema,\n MAX_MENU_DEPTH,\n MAX_MENU_TREE_NODES,\n type MenuLinkValue,\n} from './menu-item-schema.js'\n\n// ---------------------------------------------------------------------------\n// Bounds\n// ---------------------------------------------------------------------------\n\n/**\n * Hard cap on the number of DISTINCT entity types one menu may fan out over.\n *\n * The batched pipeline costs three DB round-trips per type group, so this — not\n * the item count — is what bounds a render's backend work. A navigation menu\n * pointing at more than a handful of routable types is malformed by\n * construction; types past the cap are dropped (their items disappear) and\n * logged, never silently truncated.\n */\nexport const MAX_MENU_ENTITY_TYPES = 16\n\n/**\n * Longest `handle` accepted — rejected before any DB work. A defensive cap, not\n * a mirror of the entity's `handle` column (`varchar(255)`): a handle is a\n * hand-authored navigation key, so anything approaching this length is\n * malformed by construction.\n */\nconst MAX_HANDLE_LENGTH = 128\n\n// ---------------------------------------------------------------------------\n// Public shape (phase 11 §2)\n// ---------------------------------------------------------------------------\n\n/** One render-ready menu item (phase 11 §2 — exact shape). */\nexport interface ResolvedMenuItem {\n /** The stored item's stable id (DND identity; also a stable React key). */\n id: string\n kind: 'link' | 'header'\n /** Resolved label: the per-locale override, else the live entity title. */\n label: string\n /**\n * Locale-relative canonical path from `toolkit_paths` (+ `#anchor` when set),\n * external `url` / `email` targets verbatim (protocol-gated), `null` for\n * `header` items.\n */\n href: string | null\n newTab: boolean\n /** Exact `currentPath` match on the path part (any `#anchor` ignored). */\n isActive: boolean\n /** An ancestor BY TREE of the active item — never a path-prefix guess. */\n inActiveTrail: boolean\n children: ResolvedMenuItem[]\n}\n\n/**\n * A resolved menu.\n *\n * Phase 11 §2 names `ResolvedMenuItem` and uses `ResolvedMenu` as `getMenu`'s\n * return type without spelling its fields out; this is the minimal wrapper that\n * satisfies it — the requested `handle` (so a caller holding several resolved\n * menus can tell them apart, and so `markActiveTrail` can round-trip a menu\n * without losing its identity) plus the item forest. Deliberately carries no\n * `maxDepth` / `title`: the depth clamp is already APPLIED in `items`, and a\n * menu's admin-facing title is not a rendering concern.\n */\nexport interface ResolvedMenu {\n handle: string\n items: ResolvedMenuItem[]\n}\n\n/** Options for {@link getMenu} (phase 11 §2). */\nexport interface GetMenuOptions {\n /** The locale to resolve labels, visibility and canonical paths for. */\n locale: string\n /**\n * The page being rendered, for active-trail marking. SSG frontends usually\n * OMIT this (one build-time fetch) and call {@link markActiveTrail} per page.\n */\n currentPath?: string | undefined\n}\n\n// ---------------------------------------------------------------------------\n// Injected dependencies\n// ---------------------------------------------------------------------------\n\n/** The projected `menu` row {@link getMenu} reads. */\nexport interface MenuRow {\n /**\n * The menu's own depth cap. Absent / out of range falls back to the entity\n * default — the clamp is renderer-enforced independently of the editor\n * (phase 07 §2.7), so a bad stored value can never widen it.\n */\n maxDepth?: number | null | undefined\n /** Raw `menu.tree` JSONB. Untrusted shape — validated per node during the walk. */\n tree: unknown\n}\n\n/**\n * Structural minimum of a pino/toolkit logger. Declared here (rather than\n * imported) so this module stays import-free; `app.logger.child(...)` satisfies\n * it structurally.\n */\nexport interface MenuResolveLogger {\n warn(obj: object, msg: string): void\n}\n\n/**\n * Everything {@link getMenu} needs from the outside world.\n *\n * Function-shaped (not reader-shaped) on purpose: the concrete implementations\n * live in `./menu-resolve-context.ts`, where assignability against\n * `@murumets-ee/content`'s real `getCanonicalPaths` / `PublishFilter` is\n * type-checked at the seam — so this module needs no `@murumets-ee/content`\n * import and drift is still a build error.\n */\nexport interface MenuResolveDeps {\n /**\n * Fetch the PUBLISHED menu row by handle, or `null`.\n *\n * The publish filter is the implementation's responsibility (the app-side\n * factory reads through a publish-filtering `QueryClient`) — a draft menu\n * must never resolve, per phase 11 §2.\n */\n getMenuRow: (handle: string) => Promise<MenuRow | null>\n /**\n * Batched forward index read: which of `ids` have a canonical path in\n * `locale`? Does NOT publish-filter — {@link MenuResolveDeps.filterPublished}\n * is the required second step.\n */\n resolveCanonicalPaths: (\n entityType: string,\n ids: readonly string[],\n locale: string,\n ) => Promise<ReadonlyMap<string, string>>\n /** Batched publish gate: which of `ids` are published in `locale`? */\n filterPublished: (\n entityType: string,\n ids: readonly string[],\n locale: string,\n ) => Promise<ReadonlySet<string>>\n /**\n * Batched live-title read: `id → display title` for `locale`. Only called for\n * the ids that actually need one (no per-locale label override), and never\n * for `header` items (they have no linked entity to borrow a title from).\n */\n resolveTitles: (\n entityType: string,\n ids: readonly string[],\n locale: string,\n ) => Promise<ReadonlyMap<string, string>>\n /**\n * Fallback locale for label overrides — the app's configured content\n * `defaultLocale`. A label present only in the default locale still renders\n * (the same locale → default fallback `mergeTranslations` gives entity data),\n * instead of silently dropping a partially-translated item.\n */\n defaultLocale: string\n /** Optional — used to report DROPPED work (never silent truncation). */\n logger?: MenuResolveLogger | undefined\n}\n\n// ---------------------------------------------------------------------------\n// Locale-map reads (defensive: these run against raw JSONB)\n// ---------------------------------------------------------------------------\n\n/**\n * Read one locale's string out of a raw `label` map, falling back to\n * `defaultLocale`. Own-property reads only, so a `__proto__` / `constructor`\n * key in stored JSON can't produce a value. Empty strings count as absent — an\n * item labelled `''` renders as an invisible link.\n */\nfunction readLocaleString(map: unknown, locale: string, defaultLocale: string): string | undefined {\n if (map === null || typeof map !== 'object' || Array.isArray(map)) return undefined\n const record: Record<string, unknown> = map as Record<string, unknown>\n for (const key of locale === defaultLocale ? [locale] : [locale, defaultLocale]) {\n if (!Object.hasOwn(record, key)) continue\n const value = record[key]\n if (typeof value === 'string' && value.length > 0) return value\n }\n return undefined\n}\n\n/**\n * Read one locale's visibility flag. NO default-locale fallback on purpose:\n * `enabled` is per-locale visibility in both directions (phase 08 §3), so\n * hiding an item in `en` must not hide it in `et`.\n */\nfunction readLocaleBoolean(map: unknown, locale: string): boolean | undefined {\n if (map === null || typeof map !== 'object' || Array.isArray(map)) return undefined\n const record: Record<string, unknown> = map as Record<string, unknown>\n if (!Object.hasOwn(record, locale)) return undefined\n const value = record[locale]\n return typeof value === 'boolean' ? value : undefined\n}\n\n// ---------------------------------------------------------------------------\n// Pass 1 — structural narrowing + id collection (one walk)\n// ---------------------------------------------------------------------------\n\n/**\n * A node that survived structural validation. Data-driven filtering (publish\n * state, canonical path, label availability, empty-header pruning) happens in\n * pass 2, once the batched lookups have run.\n */\ninterface PreparedNode {\n id: string\n kind: 'link' | 'header'\n link: MenuLinkValue | undefined\n /** Raw label map — read per locale in pass 2. */\n label: unknown\n newTab: boolean\n children: PreparedNode[]\n}\n\ninterface PreparedTree {\n nodes: PreparedNode[]\n /** entityType → every linked id (needs a path + publish check). */\n idsByType: Map<string, Set<string>>\n /** entityType → the subset with no usable label override (needs a live title). */\n titleIdsByType: Map<string, Set<string>>\n /** Nodes discarded because a hard bound was hit (reported, never silent). */\n droppedForBudget: number\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === 'object' && !Array.isArray(value)\n}\n\n/**\n * Walk the raw tree ONCE: validate each node's shape, apply the two filters\n * that need no I/O (per-locale `enabled`, the `maxDepth` clamp), and collect\n * the entity ids the batched lookups will need — grouped by entity type, so\n * pass 2 issues one call per GROUP rather than one per item.\n *\n * Bounded by {@link MAX_MENU_TREE_NODES} visited nodes and {@link MAX_MENU_DEPTH}\n * levels regardless of what is stored, so a hand-edited row can't turn a page\n * render into unbounded work.\n */\nfunction prepareTree(\n rawTree: unknown,\n locale: string,\n defaultLocale: string,\n maxDepth: number,\n): PreparedTree {\n const idsByType = new Map<string, Set<string>>()\n const titleIdsByType = new Map<string, Set<string>>()\n let budget = MAX_MENU_TREE_NODES\n let droppedForBudget = 0\n\n function collect(target: Map<string, Set<string>>, entityType: string, id: string): void {\n const bucket = target.get(entityType)\n if (bucket) bucket.add(id)\n else target.set(entityType, new Set([id]))\n }\n\n function walk(value: unknown, depth: number): PreparedNode[] {\n if (depth > maxDepth || !Array.isArray(value)) return []\n // `Array.isArray` narrows `unknown` to `any[]`; re-binding keeps elements `unknown`.\n const rawNodes: readonly unknown[] = value\n const out: PreparedNode[] = []\n\n for (const raw of rawNodes) {\n if (budget <= 0) {\n droppedForBudget++\n continue\n }\n if (!isPlainObject(raw)) continue\n\n const id = raw.id\n const kind = raw.kind\n if (typeof id !== 'string' || id.length === 0) continue\n if (kind !== 'link' && kind !== 'header') continue\n // Per-locale visibility drops the node AND its subtree — checked before\n // recursing so a hidden branch costs nothing.\n if (readLocaleBoolean(raw.enabled, locale) === false) continue\n\n budget--\n\n let link: MenuLinkValue | undefined\n if (kind === 'link') {\n // Re-validate the stored LinkValue — this is the `sanitizeHref`\n // protocol gate, the one write-time check that genuinely matters again\n // at read time (see the module header). A malformed link drops just\n // this node.\n const parsed = LinkValueSchema.safeParse(raw.link)\n if (!parsed.success) continue\n link = parsed.data\n } else if (raw.link !== undefined) {\n // A header carrying a link target is a shape violation — drop it\n // rather than render a half-defined node.\n continue\n }\n\n const children = walk(raw.children, depth + 1)\n\n if (link?.kind === 'entity') {\n collect(idsByType, link.entity, link.id)\n // Only items WITHOUT a usable override need a live title, so the title\n // read stays as small as possible — and header items, which have no\n // linked entity, can never reach this branch at all.\n if (readLocaleString(raw.label, locale, defaultLocale) === undefined) {\n collect(titleIdsByType, link.entity, link.id)\n }\n }\n\n out.push({ id, kind, link, label: raw.label, newTab: raw.newTab === true, children })\n }\n\n return out\n }\n\n const nodes = walk(rawTree, 1)\n return { nodes, idsByType, titleIdsByType, droppedForBudget }\n}\n\n// ---------------------------------------------------------------------------\n// Pass 2 — batched lookups\n// ---------------------------------------------------------------------------\n\ninterface ResolvedLookups {\n paths: Map<string, ReadonlyMap<string, string>>\n published: Map<string, ReadonlySet<string>>\n titles: Map<string, ReadonlyMap<string, string>>\n}\n\n/**\n * Run the batched lookups: for each entity-type GROUP, one forward-index read,\n * then one publish gate over the ids that had a path, then (only when some item\n * needs it) one title read. Exactly one call each, never per item, and\n * `MAX_MENU_ENTITY_TYPES` bounds the group count — so the number of round-trips\n * per render is fixed.\n *\n * Groups run CONCURRENTLY (bounded by the already-enforced `MAX_MENU_ENTITY_TYPES`\n * cap, never an unbounded `Promise.all`) — they're independent, and this sits on\n * a public SSR request path where the 3-step-per-group sequencing was otherwise\n * fully serial (up to 48 round-trips back to back for one render). Only the\n * THREE STEPS WITHIN one group stay ordered (path lookup → publish gate → title\n * read), since each depends on the previous step's output.\n *\n * How each dep handles an over-large id list is the DEP's business, and they\n * differ: `getCanonicalPaths` chunks internally, and so does the title reader in\n * `./menu-resolve-context.ts` (`TITLE_BATCH_SIZE`). `filterPublished` (content's\n * `buildEnumerateDeps`) does NOT — it issues a single `inArray` over whatever it\n * is handed. That is safe HERE because the id list is bounded tree-wide by\n * {@link MAX_MENU_TREE_NODES} (500) before it ever reaches this function, not\n * because the dep protects itself. A caller that lifts the node budget must\n * revisit that.\n */\nasync function runLookups(\n prepared: PreparedTree,\n locale: string,\n deps: MenuResolveDeps,\n handle: string,\n): Promise<ResolvedLookups> {\n const paths = new Map<string, ReadonlyMap<string, string>>()\n const published = new Map<string, ReadonlySet<string>>()\n const titles = new Map<string, ReadonlyMap<string, string>>()\n\n const groups = [...prepared.idsByType.entries()]\n if (groups.length > MAX_MENU_ENTITY_TYPES) {\n deps.logger?.warn(\n { handle, locale, entityTypes: groups.length, cap: MAX_MENU_ENTITY_TYPES },\n 'menu resolution dropped entity-type groups over the fan-out cap',\n )\n }\n\n await Promise.all(\n groups.slice(0, MAX_MENU_ENTITY_TYPES).map(async ([entityType, idSet]) => {\n const ids = [...idSet]\n // (1) Forward index — which ids have a canonical path in this locale?\n const pathMap = await deps.resolveCanonicalPaths(entityType, ids, locale)\n paths.set(entityType, pathMap)\n if (pathMap.size === 0) return\n\n // (2) Publish gate — `resolveCanonicalPaths` does NOT filter by publish\n // state (`toolkit_paths` has no status column), so this is the\n // required no-unpublished-leak step. Batched, over only the ids that\n // had a path.\n const candidates = [...pathMap.keys()]\n const publishedIds = await deps.filterPublished(entityType, candidates, locale)\n published.set(entityType, publishedIds)\n\n // (3) Live titles — only for items with no usable override, and only for\n // ids that will actually survive pass 3 (had a path AND published) —\n // fetching a title for an id that's about to be dropped is wasted work.\n const needTitles = prepared.titleIdsByType.get(entityType)\n if (needTitles === undefined) return\n const titleIds = candidates.filter((id) => needTitles.has(id) && publishedIds.has(id))\n if (titleIds.length === 0) return\n titles.set(entityType, await deps.resolveTitles(entityType, titleIds, locale))\n }),\n )\n\n return { paths, published, titles }\n}\n\n// ---------------------------------------------------------------------------\n// Pass 3 — resolve + filter, bottom-up\n// ---------------------------------------------------------------------------\n\n/**\n * Resolve prepared nodes into {@link ResolvedMenuItem}s, dropping everything\n * that can't render. Children resolve BEFORE their parent so empty-header\n * pruning sees the already-filtered child list (phase 11 §2: \"header item whose\n * surviving children are all dropped → dropped\").\n */\nfunction resolveNodes(\n nodes: readonly PreparedNode[],\n locale: string,\n lookups: ResolvedLookups,\n deps: MenuResolveDeps,\n): ResolvedMenuItem[] {\n const out: ResolvedMenuItem[] = []\n\n for (const node of nodes) {\n const children = resolveNodes(node.children, locale, lookups, deps)\n const override = readLocaleString(node.label, locale, deps.defaultLocale)\n\n if (node.kind === 'header') {\n // No empty dropdowns (phase 11 §2), and no label → nothing to click on.\n if (children.length === 0) continue\n if (override === undefined) continue\n out.push({\n id: node.id,\n kind: 'header',\n label: override,\n href: null,\n newTab: false,\n isActive: false,\n inActiveTrail: false,\n children,\n })\n continue\n }\n\n const link = node.link\n if (link === undefined) continue\n\n let href: string | null\n let label = override\n\n if (link.kind === 'entity') {\n const path = lookups.paths.get(link.entity)?.get(link.id)\n // No canonical path at all → the target was deleted, never published in\n // this locale, or its type isn't routable. Unpublished → same outcome.\n if (path === undefined) continue\n if (lookups.published.get(link.entity)?.has(link.id) !== true) continue\n href = link.anchor === undefined ? path : `${path}#${link.anchor}`\n label ??= lookups.titles.get(link.entity)?.get(link.id)\n } else {\n // `url` / `email` — the only remaining kinds, so there is no dead\n // fallback branch to carry: `MenuLinkValue` has exactly three arms. A\n // `media` link is rejected at the WRITE boundary by `LinkValueSchema`,\n // which is also what drops one that reached the column by some other\n // route (a direct edit, a restored dump) — `prepareTree`'s `safeParse`\n // never lets it get this far.\n //\n // Verbatim external targets, protocol-gated once more by blocks'\n // `resolveLinkHref` (`mailto:` composition included) — the single source\n // of truth for what may become an `<a href>`. It returns `null` for\n // anything it cannot turn into an href, and a `null` href is dropped just\n // below — so widening `MenuLinkValue` later fails CLOSED here by default\n // rather than emitting a half-resolved item.\n href = resolveLinkHref(link)\n }\n\n // An item with no href or no resolvable label renders as either a dead\n // anchor or an invisible one — drop it, matching every other filter here.\n if (href === null || href.length === 0) continue\n if (label === undefined || label.length === 0) continue\n\n out.push({\n id: node.id,\n kind: 'link',\n label,\n href,\n newTab: node.newTab,\n isActive: false,\n inActiveTrail: false,\n children,\n })\n }\n\n return out\n}\n\n// ---------------------------------------------------------------------------\n// Active trail (phase 11 §3)\n// ---------------------------------------------------------------------------\n\n/**\n * The comparable path part of an href or a current path: the `#fragment` is\n * dropped (an anchor item on the current page is still \"the current page\", per\n * phase 11 §2) and a trailing slash is normalized away, so `/about` and\n * `/about/` match. The root `/` keeps its slash.\n */\nfunction comparablePath(value: string): string {\n const hash = value.indexOf('#')\n const path = hash === -1 ? value : value.slice(0, hash)\n return path.length > 1 && path.endsWith('/') ? path.slice(0, -1) : path\n}\n\ninterface MarkResult {\n items: ResolvedMenuItem[]\n containsActive: boolean\n}\n\nfunction markNodes(nodes: readonly ResolvedMenuItem[], target: string): MarkResult {\n let containsActive = false\n const items = nodes.map((node): ResolvedMenuItem => {\n const marked = markNodes(node.children, target)\n const isActive = node.href !== null && comparablePath(node.href) === target\n // Ancestry is read off the TREE, never guessed from a path prefix — prefix\n // guessing breaks across translated bases and across sibling paths that\n // merely share a prefix (`/about` vs `/about-us`).\n const inActiveTrail = marked.containsActive\n if (isActive || inActiveTrail) containsActive = true\n return { ...node, isActive, inActiveTrail, children: marked.items }\n })\n return { items, containsActive }\n}\n\n/**\n * Mark `isActive` / `inActiveTrail` on a resolved menu for one page.\n *\n * PURE — no I/O, and the input menu is not mutated (a new tree is returned), so\n * an SSG build can fetch a menu ONCE and mark it per page without the pages\n * contaminating each other. `getMenu` calls this internally when\n * `opts.currentPath` is given, so there is exactly one implementation of the\n * ancestry walk.\n *\n * `isActive` is an EXACT match on the path part; `inActiveTrail` marks strict\n * tree ancestors of an active item (an active item is not its own ancestor).\n */\nexport function markActiveTrail(menu: ResolvedMenu, currentPath: string): ResolvedMenu {\n return { ...menu, items: markNodes(menu.items, comparablePath(currentPath)).items }\n}\n\n// ---------------------------------------------------------------------------\n// Entry point\n// ---------------------------------------------------------------------------\n\n/**\n * Resolve a stored menu into a render-ready tree for one locale (phase 11 §2).\n *\n * Returns `null` when the menu does not exist or is not published — a draft\n * menu renders nowhere public. A published menu whose every item was filtered\n * out returns an EMPTY item list, not `null`: \"the menu exists but has nothing\n * to show here\" is a different fact from \"there is no such menu\".\n *\n * Filtering order (phase 11 §2, not reorderable): menu unpublished → `null`;\n * `enabled[locale] === false` → dropped with its subtree; entity target deleted\n * or unpublished-in-locale → dropped; header with no surviving children →\n * dropped; depth clamped to the menu's own `maxDepth`.\n */\nexport async function getMenu(\n handle: string,\n opts: GetMenuOptions,\n deps: MenuResolveDeps,\n): Promise<ResolvedMenu | null> {\n if (handle.length === 0 || handle.length > MAX_HANDLE_LENGTH) return null\n\n const row = await deps.getMenuRow(handle)\n if (row === null) return null\n\n // Renderer-enforced clamp — independent of the editor's own check (phase 07\n // §2.7), and never wider than the absolute ceiling even if the column is not.\n const stored = row.maxDepth\n const maxDepth =\n typeof stored === 'number' && Number.isInteger(stored) && stored >= 1\n ? Math.min(stored, MAX_MENU_DEPTH)\n : DEFAULT_MENU_DEPTH\n\n const prepared = prepareTree(row.tree, opts.locale, deps.defaultLocale, maxDepth)\n if (prepared.droppedForBudget > 0) {\n deps.logger?.warn(\n {\n handle,\n locale: opts.locale,\n dropped: prepared.droppedForBudget,\n cap: MAX_MENU_TREE_NODES,\n },\n 'menu resolution dropped items over the node budget',\n )\n }\n\n const lookups = await runLookups(prepared, opts.locale, deps, handle)\n const menu: ResolvedMenu = {\n handle,\n items: resolveNodes(prepared.nodes, opts.locale, lookups, deps),\n }\n\n return opts.currentPath === undefined ? menu : markActiveTrail(menu, opts.currentPath)\n}\n","/**\n * Typed column access for a dynamically-generated entity table.\n *\n * `AdminClient.getTable()` / `QueryClient.getTable()` both return\n * `PgTableWithColumns<any>` (Drizzle cannot type columns that are generated\n * from a runtime entity definition), so reading a column off one directly\n * yields `any` and silently erodes this package's type coverage. Narrowing\n * through this helper pins the ONE column being filtered on — the same idiom\n * `@murumets-ee/content`'s `buildEnumerateDeps` uses.\n *\n * Internal to `@murumets-ee/menus`; not part of any public entry.\n */\n\nimport type { PgColumn, PgTableWithColumns } from 'drizzle-orm/pg-core'\n\n/** Read one named column off a runtime-generated entity table, typed. */\nexport function column<K extends string>(\n // biome-ignore lint/suspicious/noExplicitAny: Drizzle cannot type dynamically-generated column schemas — `PgTableWithColumns<any>` is `getTable()`'s own declared return type (CLAUDE.md's sanctioned case).\n table: PgTableWithColumns<any>,\n name: K,\n): PgColumn {\n return (table as unknown as Record<K, PgColumn>)[name]\n}\n","/**\n * App-binding for {@link import('./get-menu.js').getMenu} (plan/routing PR09).\n *\n * `./get-menu.ts` is a LEAF — it takes every dependency as an injected function\n * so it imports no `@murumets-ee/core` graph. THIS module is the outer seam\n * that holds those imports and builds concrete deps from a live `ToolkitApp`,\n * mirroring `@murumets-ee/content`'s `paths/resolve-context.ts` exactly. Because\n * the real `getCanonicalPaths` / `PublishFilter` are ASSIGNED to the leaf's\n * structurally-declared dep slots here, drift between the two packages is a\n * build error at this file rather than a silent divergence.\n *\n * **Reads run under an ELEVATED system context** (same `SYSTEM_CONTEXT` shape\n * and rationale as content's `resolve-context.ts` — read that file's header).\n * Rendering a menu is a SYSTEM derivation: it must work for an anonymous public\n * request, or for a build-time SSG run with no request context at all, and must\n * not fail just because the caller holds no per-entity `view` grant. Elevation\n * bypasses ONLY the permission/scope assertion — `QueryClient`'s PUBLISH filter\n * and trashed-row exclusion still apply, because the elevated context grants\n * reach WITHOUT `view_unpublished` (D017; see {@link SYSTEM_CONTEXT}), so:\n * - an unpublished / trashed MENU still resolves to `null` (nothing renders),\n * - an unpublished / trashed TARGET is still absent from the publish gate and\n * from the title read, so its item is dropped.\n * The only data elevation exposes is a published document's title + canonical\n * path — the same facts the public sitemap already enumerates.\n */\n\nimport { getContentConfig } from '@murumets-ee/content/plugin'\nimport {\n buildCanonicalPathsBatchDeps,\n buildEnumerateDeps,\n getCanonicalPaths,\n} from '@murumets-ee/content/resolve'\nimport type { ToolkitApp } from '@murumets-ee/core'\nimport { createSystemReachResolver } from '@murumets-ee/core'\nimport type { SecurityContext } from '@murumets-ee/entity'\nimport { getEntityTitleField } from '@murumets-ee/entity'\nimport { QueryClient } from '@murumets-ee/entity/query'\nimport { eq, inArray } from 'drizzle-orm'\nimport { Menu } from './entity.js'\nimport type { MenuResolveDeps, MenuRow } from './get-menu.js'\nimport { column } from './internal/columns.js'\n\n/**\n * Elevated **reach** resolver — grants reach, never visibility of unpublished\n * rows. See the file header.\n *\n * That invariant used to rest on `QueryClient` applying the publish filter\n * unconditionally; since D017 it rests on this resolver withholding\n * `view_unpublished`, which {@link createSystemReachResolver} does centrally.\n * A `checker: () => true` here would make `_menu` render items pointing at\n * draft documents.\n */\n// Named, not defaulted: `content`'s path resolver is the other elevated reader\n// and passes `'path-resolver'`. Two of them logging the default `'system'` would\n// be indistinguishable in audit output.\nconst SYSTEM_CONTEXT: () => SecurityContext = createSystemReachResolver('menu-resolver')\n\n/** Ids per batched title lookup — mirrors content's `CANONICAL_BATCH_SIZE`. */\nconst TITLE_BATCH_SIZE = 500\n\n/**\n * Build the concrete {@link MenuResolveDeps} for an app.\n *\n * Cheap to call per request (it constructs no clients eagerly — each read\n * builds its own `QueryClient`, matching `buildEnumerateDeps`'s per-call shape,\n * so this never depends on plugin boot ORDER).\n */\nexport function buildMenuResolveDeps(app: ToolkitApp): MenuResolveDeps {\n const db = app.db.readOnly\n const canonicalBatch = buildCanonicalPathsBatchDeps(app)\n const { filterPublished } = buildEnumerateDeps(app)\n\n return {\n getMenuRow: async (handle: string): Promise<MenuRow | null> => {\n const client = new QueryClient({\n entity: Menu,\n db,\n logger: app.logger.child({ resolve: 'menu' }),\n contextResolver: SYSTEM_CONTEXT,\n })\n // `publishable()` on `Menu` means this client filters to PUBLISHED rows\n // for any principal without `view_unpublished` — and `SYSTEM_CONTEXT`\n // withholds it (D017), so the filter always applies HERE. A draft menu\n // returns nothing, which `getMenu` turns into `null`. Do not swap this\n // resolver for a blanket `checker: () => true`: that grants the action and\n // silently publishes drafts.\n //\n // No `locale` is passed: the menu entity has no translations and no\n // locale-status table (locale variance lives INSIDE the tree, per D009),\n // so a locale would only cost a pointless translation merge.\n const rows = await client.findMany({\n where: eq(column(client.getTable(), 'handle'), handle),\n limit: 1,\n })\n const row = rows[0]\n if (row === undefined) return null\n return { maxDepth: row.maxDepth, tree: row.tree }\n },\n\n resolveCanonicalPaths: (entityType, ids, locale) =>\n getCanonicalPaths(entityType, ids, locale, canonicalBatch),\n\n filterPublished,\n\n resolveTitles: async (entityType, ids, locale) => {\n const titles = new Map<string, string>()\n if (ids.length === 0) return titles\n // An unregistered entity type yields NO title, so its items are dropped\n // — fail-closed, matching `buildEnumerateDeps`'s own unknown-type branch.\n const entity = app.entities.get(entityType)\n if (entity === undefined) return titles\n\n const titleField = getEntityTitleField(entity)\n // `getEntityTitleField` degrades to the row's own `id` when the entity has\n // no display-able field — a raw UUID is not a menu label. Fail closed and\n // let the item drop, matching this module's own stated posture.\n if (titleField === 'id') return titles\n const client = new QueryClient({\n entity,\n db,\n logger: app.logger.child({ resolve: 'menu-title', entity: entityType }),\n contextResolver: SYSTEM_CONTEXT,\n })\n const idColumn = column(client.getTable(), 'id')\n\n for (let i = 0; i < ids.length; i += TITLE_BATCH_SIZE) {\n const chunk = ids.slice(i, i + TITLE_BATCH_SIZE)\n // `locale` drives `mergeTranslations`, so a translatable title comes\n // back in the requested locale (falling back to the base row's value)\n // — the \"live entity title (locale-merged)\" phase 11 §2 asks for.\n const rows = await client.findMany({\n where: inArray(idColumn, [...chunk]),\n locale,\n limit: chunk.length,\n })\n for (const row of rows) {\n const record: Record<string, unknown> = row\n const id = record.id\n const title = record[titleField]\n if (typeof id === 'string' && typeof title === 'string' && title.length > 0) {\n titles.set(id, title)\n }\n }\n }\n return titles\n },\n\n defaultLocale: getContentConfig().defaultLocale,\n logger: app.logger.child({ resolve: 'menu' }),\n }\n}\n"],"mappings":"8iBAqEA,MAAa,EAAwB,GAwJrC,SAAS,EAAiB,EAAc,EAAgB,EAA2C,CACjG,GAAoB,OAAO,GAAQ,WAA/B,GAA2C,MAAM,QAAQ,CAAG,EAAG,OACnE,IAAM,EAAkC,EACxC,IAAK,IAAM,KAAO,IAAW,EAAgB,CAAC,CAAM,EAAI,CAAC,EAAQ,CAAa,EAAG,CAC/E,GAAI,CAAC,OAAO,OAAO,EAAQ,CAAG,EAAG,SACjC,IAAM,EAAQ,EAAO,GACrB,GAAI,OAAO,GAAU,UAAY,EAAM,OAAS,EAAG,OAAO,CAC5D,CAEF,CAOA,SAAS,EAAkB,EAAc,EAAqC,CAC5E,GAAoB,OAAO,GAAQ,WAA/B,GAA2C,MAAM,QAAQ,CAAG,EAAG,OACnE,IAAM,EAAkC,EACxC,GAAI,CAAC,OAAO,OAAO,EAAQ,CAAM,EAAG,OACpC,IAAM,EAAQ,EAAO,GACrB,OAAO,OAAO,GAAU,UAAY,EAAQ,IAAA,EAC9C,CA+BA,SAAS,EAAc,EAAkD,CACvE,OAAyB,OAAO,GAAU,YAAnC,GAA+C,CAAC,MAAM,QAAQ,CAAK,CAC5E,CAYA,SAAS,EACP,EACA,EACA,EACA,EACc,CACd,IAAM,EAAY,IAAI,IAChB,EAAiB,IAAI,IACvB,EAAA,IACA,EAAmB,EAEvB,SAAS,EAAQ,EAAkC,EAAoB,EAAkB,CACvF,IAAM,EAAS,EAAO,IAAI,CAAU,EAChC,EAAQ,EAAO,IAAI,CAAE,EACpB,EAAO,IAAI,EAAY,IAAI,IAA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B,KACvB,CAAE,SAAU,EAAI,SAAU,KAAM,EAAI,IAAK,CAClD,EAEA,uBAAwB,EAAY,EAAK,IACvC,EAAkB,EAAY,EAAK,EAAQ,CAAc,EAE3D,kBAEA,cAAe,MAAO,EAAY,EAAK,IAAW,CAChD,IAAM,EAAS,IAAI,IACnB,GAAI,EAAI,SAAW,EAAG,OAAO,EAG7B,IAAM,EAAS,EAAI,SAAS,IAAI,CAAU,EAC1C,GAAI,IAAW,IAAA,GAAW,OAAO,EAEjC,IAAM,EAAa,EAAoB,CAAM,EAI7C,GAAI,IAAe,KAAM,OAAO,EAChC,IAAM,EAAS,IAAI,EAAY,CAC7B,SACA,KACA,OAAQ,EAAI,OAAO,MAAM,CAAE,QAAS,aAAc,OAAQ,CAAW,CAAC,EACtE,gBAAiB,CACnB,CAAC,EACK,EAAW,EAAO,EAAO,SAAS,EAAG,IAAI,EAE/C,IAAK,IAAI,EAAI,EAAG,EAAI,EAAI,OAAQ,GAAK,IAAkB,CACrD,IAAM,EAAQ,EAAI,MAAM,EAAG,EAAI,GAAgB,EAIzC,EAAO,MAAM,EAAO,SAAS,CACjC,MAAO,EAAQ,EAAU,CAAC,GAAG,CAAK,CAAC,EACnC,SACA,MAAO,EAAM,MACf,CAAC,EACD,IAAK,IAAM,KAAO,EAAM,CACtB,IAAM,EAAkC,EAClC,EAAK,EAAO,GACZ,EAAQ,EAAO,GACjB,OAAO,GAAO,UAAY,OAAO,GAAU,UAAY,EAAM,OAAS,GACxE,EAAO,IAAI,EAAI,CAAK,CAExB,CACF,CACA,OAAO,CACT,EAEA,cAAe,EAAiB,CAAC,CAAC,cAClC,OAAQ,EAAI,OAAO,MAAM,CAAE,QAAS,MAAO,CAAC,CAC9C,CACF"}
1
+ {"version":3,"file":"resolve.mjs","names":[],"sources":["../src/get-menu.ts","../src/internal/columns.ts","../src/menu-resolve-context.ts"],"sourcesContent":["/**\n * `getMenu()` — turn a stored menu tree into a render-ready structure for one\n * locale (plan/routing phase 11 §2), plus the pure `markActiveTrail()` helper\n * (phase 11 §3).\n *\n * **Leaf module.** Every cross-package capability (the menu row read, the\n * `toolkit_paths` forward index, the publish gate, live entity titles) arrives\n * through the injected {@link MenuResolveDeps}; nothing here imports\n * `@murumets-ee/core` or `@murumets-ee/content`. Concrete deps are built from a\n * live app in `./menu-resolve-context.ts` — the same leaf/seam split\n * `@murumets-ee/content`'s `paths/enumerate.ts` ↔ `paths/resolve-context.ts`\n * uses, and the reason the deps' function types are declared structurally here\n * rather than imported (assignability is still checked, at the seam).\n *\n * **Security.** The resolved output feeds PUBLIC page navigation, so it must\n * never surface an unpublished or deleted document:\n * - the menu itself is read through a publish-filtered client (an unpublished\n * menu resolves to `null` — nothing renders),\n * - every entity-linked item must have BOTH a canonical path in\n * `toolkit_paths` for the requested locale AND survive the batched publish\n * gate; missing either → the item (and its subtree) is dropped,\n * - `url` / `email` targets are re-gated through the same `sanitizeHref`\n * protocol allowlist the write path uses, so a value that reached the column\n * by some route other than the entity API (a direct DB edit, a restored\n * dump) still cannot become a `javascript:` href,\n * - every filtering decision fails CLOSED — anything unresolvable is dropped,\n * never rendered with a placeholder.\n *\n * **No unbounded fan-out** (CLAUDE.md). Backend work is bounded by the number\n * of distinct ENTITY TYPES in the tree, never by the number of items: the walk\n * collects ids grouped by type, then issues at most THREE batched calls per\n * group (forward index → publish gate → titles). The group count is itself hard-\n * capped ({@link MAX_MENU_ENTITY_TYPES}) and the walk carries a node budget\n * ({@link MAX_MENU_TREE_NODES}), so one render costs a fixed, small number of\n * round-trips no matter what the stored tree looks like.\n *\n * **Read-time validation is per-node, not whole-tree.** The write path already\n * runs `buildMenuTreeSchema()` (`menuTreeValidation()`), and this module\n * deliberately does NOT re-run it: that schema whitelists locale KEYS against\n * the app's configured locales, so re-parsing at read time would fail the WHOLE\n * menu — site navigation gone — the moment an operator removes a locale from\n * config after a menu was saved. The locale whitelist is a write-time authoring\n * check with no read-time security value. What DOES matter at read time (node\n * shape, the `LinkValue` protocol gate) is re-checked per node here, and a\n * malformed node is dropped on its own without taking the menu down with it.\n */\n\nimport { resolveLinkHref } from '@murumets-ee/blocks/links'\nimport {\n DEFAULT_MENU_DEPTH,\n LinkValueSchema,\n MAX_MENU_DEPTH,\n MAX_MENU_TREE_NODES,\n type MenuLinkValue,\n} from './menu-item-schema.js'\n\n// ---------------------------------------------------------------------------\n// Bounds\n// ---------------------------------------------------------------------------\n\n/**\n * Hard cap on the number of DISTINCT entity types one menu may fan out over.\n *\n * The batched pipeline costs three DB round-trips per type group, so this — not\n * the item count — is what bounds a render's backend work. A navigation menu\n * pointing at more than a handful of routable types is malformed by\n * construction; types past the cap are dropped (their items disappear) and\n * logged, never silently truncated.\n */\nexport const MAX_MENU_ENTITY_TYPES = 16\n\n/**\n * Longest `handle` accepted — rejected before any DB work. A defensive cap, not\n * a mirror of the entity's `handle` column (`varchar(255)`): a handle is a\n * hand-authored navigation key, so anything approaching this length is\n * malformed by construction.\n */\nconst MAX_HANDLE_LENGTH = 128\n\n// ---------------------------------------------------------------------------\n// Public shape (phase 11 §2)\n// ---------------------------------------------------------------------------\n\n/** One render-ready menu item (phase 11 §2 — exact shape). */\nexport interface ResolvedMenuItem {\n /** The stored item's stable id (DND identity; also a stable React key). */\n id: string\n kind: 'link' | 'header'\n /** Resolved label: the per-locale override, else the live entity title. */\n label: string\n /**\n * Locale-relative canonical path from `toolkit_paths` (+ `#anchor` when set),\n * external `url` / `email` targets verbatim (protocol-gated), `null` for\n * `header` items.\n */\n href: string | null\n newTab: boolean\n /** Exact `currentPath` match on the path part (any `#anchor` ignored). */\n isActive: boolean\n /** An ancestor BY TREE of the active item — never a path-prefix guess. */\n inActiveTrail: boolean\n children: ResolvedMenuItem[]\n}\n\n/**\n * A resolved menu.\n *\n * Phase 11 §2 names `ResolvedMenuItem` and uses `ResolvedMenu` as `getMenu`'s\n * return type without spelling its fields out; this is the minimal wrapper that\n * satisfies it — the requested `handle` (so a caller holding several resolved\n * menus can tell them apart, and so `markActiveTrail` can round-trip a menu\n * without losing its identity) plus the item forest. Deliberately carries no\n * `maxDepth` / `title`: the depth clamp is already APPLIED in `items`, and a\n * menu's admin-facing title is not a rendering concern.\n */\nexport interface ResolvedMenu {\n handle: string\n items: ResolvedMenuItem[]\n}\n\n/** Options for {@link getMenu} (phase 11 §2). */\nexport interface GetMenuOptions {\n /** The locale to resolve labels, visibility and canonical paths for. */\n locale: string\n /**\n * The page being rendered, for active-trail marking. SSG frontends usually\n * OMIT this (one build-time fetch) and call {@link markActiveTrail} per page.\n */\n currentPath?: string | undefined\n}\n\n// ---------------------------------------------------------------------------\n// Injected dependencies\n// ---------------------------------------------------------------------------\n\n/** The projected `menu` row {@link getMenu} reads. */\nexport interface MenuRow {\n /**\n * The menu's own depth cap. Absent / out of range falls back to the entity\n * default — the clamp is renderer-enforced independently of the editor\n * (phase 07 §2.7), so a bad stored value can never widen it.\n */\n maxDepth?: number | null | undefined\n /** Raw `menu.tree` JSONB. Untrusted shape — validated per node during the walk. */\n tree: unknown\n}\n\n/**\n * Structural minimum of a pino/toolkit logger. Declared here (rather than\n * imported) so this module stays import-free; `app.logger.child(...)` satisfies\n * it structurally.\n */\nexport interface MenuResolveLogger {\n warn(obj: object, msg: string): void\n}\n\n/**\n * Everything {@link getMenu} needs from the outside world.\n *\n * Function-shaped (not reader-shaped) on purpose: the concrete implementations\n * live in `./menu-resolve-context.ts`, where assignability against\n * `@murumets-ee/content`'s real `getCanonicalPaths` / `PublishFilter` is\n * type-checked at the seam — so this module needs no `@murumets-ee/content`\n * import and drift is still a build error.\n */\nexport interface MenuResolveDeps {\n /**\n * Fetch the PUBLISHED menu row by handle, or `null`.\n *\n * The publish filter is the implementation's responsibility (the app-side\n * factory reads through a publish-filtering `QueryClient`) — a draft menu\n * must never resolve, per phase 11 §2.\n */\n getMenuRow: (handle: string) => Promise<MenuRow | null>\n /**\n * Batched forward index read: which of `ids` have a canonical path in\n * `locale`? Does NOT publish-filter — {@link MenuResolveDeps.filterPublished}\n * is the required second step.\n */\n resolveCanonicalPaths: (\n entityType: string,\n ids: readonly string[],\n locale: string,\n ) => Promise<ReadonlyMap<string, string>>\n /** Batched publish gate: which of `ids` are published in `locale`? */\n filterPublished: (\n entityType: string,\n ids: readonly string[],\n locale: string,\n ) => Promise<ReadonlySet<string>>\n /**\n * Batched live-title read: `id → display title` for `locale`. Only called for\n * the ids that actually need one (no per-locale label override), and never\n * for `header` items (they have no linked entity to borrow a title from).\n */\n resolveTitles: (\n entityType: string,\n ids: readonly string[],\n locale: string,\n ) => Promise<ReadonlyMap<string, string>>\n /**\n * Fallback locale for label overrides — the app's configured content\n * `defaultLocale`. A label present only in the default locale still renders\n * (the same locale → default fallback `mergeTranslations` gives entity data),\n * instead of silently dropping a partially-translated item.\n */\n defaultLocale: string\n /** Optional — used to report DROPPED work (never silent truncation). */\n logger?: MenuResolveLogger | undefined\n}\n\n// ---------------------------------------------------------------------------\n// Locale-map reads (defensive: these run against raw JSONB)\n// ---------------------------------------------------------------------------\n\n/**\n * Read one locale's string out of a raw `label` map, falling back to\n * `defaultLocale`. Own-property reads only, so a `__proto__` / `constructor`\n * key in stored JSON can't produce a value. Empty strings count as absent — an\n * item labelled `''` renders as an invisible link.\n */\nfunction readLocaleString(map: unknown, locale: string, defaultLocale: string): string | undefined {\n if (map === null || typeof map !== 'object' || Array.isArray(map)) return undefined\n const record: Record<string, unknown> = map as Record<string, unknown>\n for (const key of locale === defaultLocale ? [locale] : [locale, defaultLocale]) {\n if (!Object.hasOwn(record, key)) continue\n const value = record[key]\n if (typeof value === 'string' && value.length > 0) return value\n }\n return undefined\n}\n\n/**\n * Read one locale's visibility flag. NO default-locale fallback on purpose:\n * `enabled` is per-locale visibility in both directions (phase 08 §3), so\n * hiding an item in `en` must not hide it in `et`.\n */\nfunction readLocaleBoolean(map: unknown, locale: string): boolean | undefined {\n if (map === null || typeof map !== 'object' || Array.isArray(map)) return undefined\n const record: Record<string, unknown> = map as Record<string, unknown>\n if (!Object.hasOwn(record, locale)) return undefined\n const value = record[locale]\n return typeof value === 'boolean' ? value : undefined\n}\n\n// ---------------------------------------------------------------------------\n// Pass 1 — structural narrowing + id collection (one walk)\n// ---------------------------------------------------------------------------\n\n/**\n * A node that survived structural validation. Data-driven filtering (publish\n * state, canonical path, label availability, empty-header pruning) happens in\n * pass 2, once the batched lookups have run.\n */\ninterface PreparedNode {\n id: string\n kind: 'link' | 'header'\n link: MenuLinkValue | undefined\n /** Raw label map — read per locale in pass 2. */\n label: unknown\n newTab: boolean\n children: PreparedNode[]\n}\n\ninterface PreparedTree {\n nodes: PreparedNode[]\n /** entityType → every linked id (needs a path + publish check). */\n idsByType: Map<string, Set<string>>\n /** entityType → the subset with no usable label override (needs a live title). */\n titleIdsByType: Map<string, Set<string>>\n /** Nodes discarded because a hard bound was hit (reported, never silent). */\n droppedForBudget: number\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === 'object' && !Array.isArray(value)\n}\n\n/**\n * Walk the raw tree ONCE: validate each node's shape, apply the two filters\n * that need no I/O (per-locale `enabled`, the `maxDepth` clamp), and collect\n * the entity ids the batched lookups will need — grouped by entity type, so\n * pass 2 issues one call per GROUP rather than one per item.\n *\n * Bounded by {@link MAX_MENU_TREE_NODES} visited nodes and {@link MAX_MENU_DEPTH}\n * levels regardless of what is stored, so a hand-edited row can't turn a page\n * render into unbounded work.\n */\nfunction prepareTree(\n rawTree: unknown,\n locale: string,\n defaultLocale: string,\n maxDepth: number,\n): PreparedTree {\n const idsByType = new Map<string, Set<string>>()\n const titleIdsByType = new Map<string, Set<string>>()\n let budget = MAX_MENU_TREE_NODES\n let droppedForBudget = 0\n\n function collect(target: Map<string, Set<string>>, entityType: string, id: string): void {\n const bucket = target.get(entityType)\n if (bucket) bucket.add(id)\n else target.set(entityType, new Set([id]))\n }\n\n function walk(value: unknown, depth: number): PreparedNode[] {\n if (depth > maxDepth || !Array.isArray(value)) return []\n // `Array.isArray` narrows `unknown` to `any[]`; re-binding keeps elements `unknown`.\n const rawNodes: readonly unknown[] = value\n const out: PreparedNode[] = []\n\n for (const raw of rawNodes) {\n if (budget <= 0) {\n droppedForBudget++\n continue\n }\n if (!isPlainObject(raw)) continue\n\n const id = raw.id\n const kind = raw.kind\n if (typeof id !== 'string' || id.length === 0) continue\n if (kind !== 'link' && kind !== 'header') continue\n // Per-locale visibility drops the node AND its subtree — checked before\n // recursing so a hidden branch costs nothing.\n if (readLocaleBoolean(raw.enabled, locale) === false) continue\n\n budget--\n\n let link: MenuLinkValue | undefined\n if (kind === 'link') {\n // Re-validate the stored LinkValue — this is the `sanitizeHref`\n // protocol gate, the one write-time check that genuinely matters again\n // at read time (see the module header). A malformed link drops just\n // this node.\n const parsed = LinkValueSchema.safeParse(raw.link)\n if (!parsed.success) continue\n link = parsed.data\n } else if (raw.link !== undefined) {\n // A header carrying a link target is a shape violation — drop it\n // rather than render a half-defined node.\n continue\n }\n\n const children = walk(raw.children, depth + 1)\n\n if (link?.kind === 'entity') {\n collect(idsByType, link.entity, link.id)\n // Only items WITHOUT a usable override need a live title, so the title\n // read stays as small as possible — and header items, which have no\n // linked entity, can never reach this branch at all.\n if (readLocaleString(raw.label, locale, defaultLocale) === undefined) {\n collect(titleIdsByType, link.entity, link.id)\n }\n }\n\n out.push({ id, kind, link, label: raw.label, newTab: raw.newTab === true, children })\n }\n\n return out\n }\n\n const nodes = walk(rawTree, 1)\n return { nodes, idsByType, titleIdsByType, droppedForBudget }\n}\n\n// ---------------------------------------------------------------------------\n// Pass 2 — batched lookups\n// ---------------------------------------------------------------------------\n\ninterface ResolvedLookups {\n paths: Map<string, ReadonlyMap<string, string>>\n published: Map<string, ReadonlySet<string>>\n titles: Map<string, ReadonlyMap<string, string>>\n}\n\n/**\n * Run the batched lookups: for each entity-type GROUP, one forward-index read,\n * then one publish gate over the ids that had a path, then (only when some item\n * needs it) one title read. Exactly one call each, never per item, and\n * `MAX_MENU_ENTITY_TYPES` bounds the group count — so the number of round-trips\n * per render is fixed.\n *\n * Groups run CONCURRENTLY (bounded by the already-enforced `MAX_MENU_ENTITY_TYPES`\n * cap, never an unbounded `Promise.all`) — they're independent, and this sits on\n * a public SSR request path where the 3-step-per-group sequencing was otherwise\n * fully serial (up to 48 round-trips back to back for one render). Only the\n * THREE STEPS WITHIN one group stay ordered (path lookup → publish gate → title\n * read), since each depends on the previous step's output.\n *\n * How each dep handles an over-large id list is the DEP's business, and they\n * differ: `getCanonicalPaths` chunks internally, and so does the title reader in\n * `./menu-resolve-context.ts` (`TITLE_BATCH_SIZE`). `filterPublished` (content's\n * `buildEnumerateDeps`) does NOT — it issues a single `inArray` over whatever it\n * is handed. That is safe HERE because the id list is bounded tree-wide by\n * {@link MAX_MENU_TREE_NODES} (500) before it ever reaches this function, not\n * because the dep protects itself. A caller that lifts the node budget must\n * revisit that.\n */\nasync function runLookups(\n prepared: PreparedTree,\n locale: string,\n deps: MenuResolveDeps,\n handle: string,\n): Promise<ResolvedLookups> {\n const paths = new Map<string, ReadonlyMap<string, string>>()\n const published = new Map<string, ReadonlySet<string>>()\n const titles = new Map<string, ReadonlyMap<string, string>>()\n\n const groups = [...prepared.idsByType.entries()]\n if (groups.length > MAX_MENU_ENTITY_TYPES) {\n deps.logger?.warn(\n { handle, locale, entityTypes: groups.length, cap: MAX_MENU_ENTITY_TYPES },\n 'menu resolution dropped entity-type groups over the fan-out cap',\n )\n }\n\n await Promise.all(\n groups.slice(0, MAX_MENU_ENTITY_TYPES).map(async ([entityType, idSet]) => {\n const ids = [...idSet]\n // (1) Forward index — which ids have a canonical path in this locale?\n const pathMap = await deps.resolveCanonicalPaths(entityType, ids, locale)\n paths.set(entityType, pathMap)\n if (pathMap.size === 0) return\n\n // (2) Publish gate — `resolveCanonicalPaths` does NOT filter by publish\n // state (`toolkit_paths` has no status column), so this is the\n // required no-unpublished-leak step. Batched, over only the ids that\n // had a path.\n const candidates = [...pathMap.keys()]\n const publishedIds = await deps.filterPublished(entityType, candidates, locale)\n published.set(entityType, publishedIds)\n\n // (3) Live titles — only for items with no usable override, and only for\n // ids that will actually survive pass 3 (had a path AND published) —\n // fetching a title for an id that's about to be dropped is wasted work.\n const needTitles = prepared.titleIdsByType.get(entityType)\n if (needTitles === undefined) return\n const titleIds = candidates.filter((id) => needTitles.has(id) && publishedIds.has(id))\n if (titleIds.length === 0) return\n titles.set(entityType, await deps.resolveTitles(entityType, titleIds, locale))\n }),\n )\n\n return { paths, published, titles }\n}\n\n// ---------------------------------------------------------------------------\n// Pass 3 — resolve + filter, bottom-up\n// ---------------------------------------------------------------------------\n\n/**\n * Resolve prepared nodes into {@link ResolvedMenuItem}s, dropping everything\n * that can't render. Children resolve BEFORE their parent so empty-header\n * pruning sees the already-filtered child list (phase 11 §2: \"header item whose\n * surviving children are all dropped → dropped\").\n */\nfunction resolveNodes(\n nodes: readonly PreparedNode[],\n locale: string,\n lookups: ResolvedLookups,\n deps: MenuResolveDeps,\n): ResolvedMenuItem[] {\n const out: ResolvedMenuItem[] = []\n\n for (const node of nodes) {\n const children = resolveNodes(node.children, locale, lookups, deps)\n const override = readLocaleString(node.label, locale, deps.defaultLocale)\n\n if (node.kind === 'header') {\n // No empty dropdowns (phase 11 §2), and no label → nothing to click on.\n if (children.length === 0) continue\n if (override === undefined) continue\n out.push({\n id: node.id,\n kind: 'header',\n label: override,\n href: null,\n newTab: false,\n isActive: false,\n inActiveTrail: false,\n children,\n })\n continue\n }\n\n const link = node.link\n if (link === undefined) continue\n\n let href: string | null\n let label = override\n\n if (link.kind === 'entity') {\n const path = lookups.paths.get(link.entity)?.get(link.id)\n // No canonical path at all → the target was deleted, never published in\n // this locale, or its type isn't routable. Unpublished → same outcome.\n if (path === undefined) continue\n if (lookups.published.get(link.entity)?.has(link.id) !== true) continue\n href = link.anchor === undefined ? path : `${path}#${link.anchor}`\n label ??= lookups.titles.get(link.entity)?.get(link.id)\n } else {\n // `url` / `email` — the only remaining kinds, so there is no dead\n // fallback branch to carry: `MenuLinkValue` has exactly three arms. A\n // `media` link is rejected at the WRITE boundary by `LinkValueSchema`,\n // which is also what drops one that reached the column by some other\n // route (a direct edit, a restored dump) — `prepareTree`'s `safeParse`\n // never lets it get this far.\n //\n // Verbatim external targets, protocol-gated once more by blocks'\n // `resolveLinkHref` (`mailto:` composition included) — the single source\n // of truth for what may become an `<a href>`. It returns `null` for\n // anything it cannot turn into an href, and a `null` href is dropped just\n // below — so widening `MenuLinkValue` later fails CLOSED here by default\n // rather than emitting a half-resolved item.\n href = resolveLinkHref(link)\n }\n\n // An item with no href or no resolvable label renders as either a dead\n // anchor or an invisible one — drop it, matching every other filter here.\n if (href === null || href.length === 0) continue\n if (label === undefined || label.length === 0) continue\n\n out.push({\n id: node.id,\n kind: 'link',\n label,\n href,\n newTab: node.newTab,\n isActive: false,\n inActiveTrail: false,\n children,\n })\n }\n\n return out\n}\n\n// ---------------------------------------------------------------------------\n// Active trail (phase 11 §3)\n// ---------------------------------------------------------------------------\n\n/**\n * The comparable path part of an href or a current path: the `#fragment` is\n * dropped (an anchor item on the current page is still \"the current page\", per\n * phase 11 §2) and a trailing slash is normalized away, so `/about` and\n * `/about/` match. The root `/` keeps its slash.\n */\nfunction comparablePath(value: string): string {\n const hash = value.indexOf('#')\n const path = hash === -1 ? value : value.slice(0, hash)\n return path.length > 1 && path.endsWith('/') ? path.slice(0, -1) : path\n}\n\ninterface MarkResult {\n items: ResolvedMenuItem[]\n containsActive: boolean\n}\n\nfunction markNodes(nodes: readonly ResolvedMenuItem[], target: string): MarkResult {\n let containsActive = false\n const items = nodes.map((node): ResolvedMenuItem => {\n const marked = markNodes(node.children, target)\n const isActive = node.href !== null && comparablePath(node.href) === target\n // Ancestry is read off the TREE, never guessed from a path prefix — prefix\n // guessing breaks across translated bases and across sibling paths that\n // merely share a prefix (`/about` vs `/about-us`).\n const inActiveTrail = marked.containsActive\n if (isActive || inActiveTrail) containsActive = true\n return { ...node, isActive, inActiveTrail, children: marked.items }\n })\n return { items, containsActive }\n}\n\n/**\n * Mark `isActive` / `inActiveTrail` on a resolved menu for one page.\n *\n * PURE — no I/O, and the input menu is not mutated (a new tree is returned), so\n * an SSG build can fetch a menu ONCE and mark it per page without the pages\n * contaminating each other. `getMenu` calls this internally when\n * `opts.currentPath` is given, so there is exactly one implementation of the\n * ancestry walk.\n *\n * `isActive` is an EXACT match on the path part; `inActiveTrail` marks strict\n * tree ancestors of an active item (an active item is not its own ancestor).\n */\nexport function markActiveTrail(menu: ResolvedMenu, currentPath: string): ResolvedMenu {\n return { ...menu, items: markNodes(menu.items, comparablePath(currentPath)).items }\n}\n\n// ---------------------------------------------------------------------------\n// Entry point\n// ---------------------------------------------------------------------------\n\n/**\n * Resolve a stored menu into a render-ready tree for one locale (phase 11 §2).\n *\n * Returns `null` when the menu does not exist or is not published — a draft\n * menu renders nowhere public. A published menu whose every item was filtered\n * out returns an EMPTY item list, not `null`: \"the menu exists but has nothing\n * to show here\" is a different fact from \"there is no such menu\".\n *\n * Filtering order (phase 11 §2, not reorderable): menu unpublished → `null`;\n * `enabled[locale] === false` → dropped with its subtree; entity target deleted\n * or unpublished-in-locale → dropped; header with no surviving children →\n * dropped; depth clamped to the menu's own `maxDepth`.\n */\nexport async function getMenu(\n handle: string,\n opts: GetMenuOptions,\n deps: MenuResolveDeps,\n): Promise<ResolvedMenu | null> {\n if (handle.length === 0 || handle.length > MAX_HANDLE_LENGTH) return null\n\n const row = await deps.getMenuRow(handle)\n if (row === null) return null\n\n // Renderer-enforced clamp — independent of the editor's own check (phase 07\n // §2.7), and never wider than the absolute ceiling even if the column is not.\n const stored = row.maxDepth\n const maxDepth =\n typeof stored === 'number' && Number.isInteger(stored) && stored >= 1\n ? Math.min(stored, MAX_MENU_DEPTH)\n : DEFAULT_MENU_DEPTH\n\n const prepared = prepareTree(row.tree, opts.locale, deps.defaultLocale, maxDepth)\n if (prepared.droppedForBudget > 0) {\n deps.logger?.warn(\n {\n handle,\n locale: opts.locale,\n dropped: prepared.droppedForBudget,\n cap: MAX_MENU_TREE_NODES,\n },\n 'menu resolution dropped items over the node budget',\n )\n }\n\n const lookups = await runLookups(prepared, opts.locale, deps, handle)\n const menu: ResolvedMenu = {\n handle,\n items: resolveNodes(prepared.nodes, opts.locale, lookups, deps),\n }\n\n return opts.currentPath === undefined ? menu : markActiveTrail(menu, opts.currentPath)\n}\n","/**\n * Typed column access for a dynamically-generated entity table.\n *\n * `AdminClient.getTable()` / `QueryClient.getTable()` both return\n * `PgTableWithColumns<any>` (Drizzle cannot type columns that are generated\n * from a runtime entity definition), so reading a column off one directly\n * yields `any` and silently erodes this package's type coverage. Narrowing\n * through this helper pins the ONE column being filtered on — the same idiom\n * `@murumets-ee/content`'s `buildEnumerateDeps` uses.\n *\n * Internal to `@murumets-ee/menus`; not part of any public entry.\n */\n\nimport type { PgColumn, PgTableWithColumns } from 'drizzle-orm/pg-core'\n\n/** Read one named column off a runtime-generated entity table, typed. */\nexport function column<K extends string>(\n // biome-ignore lint/suspicious/noExplicitAny: Drizzle cannot type dynamically-generated column schemas — `PgTableWithColumns<any>` is `getTable()`'s own declared return type (CLAUDE.md's sanctioned case).\n table: PgTableWithColumns<any>,\n name: K,\n): PgColumn {\n return (table as unknown as Record<K, PgColumn>)[name]\n}\n","/**\n * App-binding for {@link import('./get-menu.js').getMenu} (plan/routing PR09).\n *\n * `./get-menu.ts` is a LEAF — it takes every dependency as an injected function\n * so it imports no `@murumets-ee/core` graph. THIS module is the outer seam\n * that holds those imports and builds concrete deps from a live `ToolkitApp`,\n * mirroring `@murumets-ee/content`'s `paths/resolve-context.ts` exactly. Because\n * the real `getCanonicalPaths` / `PublishFilter` are ASSIGNED to the leaf's\n * structurally-declared dep slots here, drift between the two packages is a\n * build error at this file rather than a silent divergence.\n *\n * **Reads run under an ELEVATED system context** (same `SYSTEM_CONTEXT` shape\n * and rationale as content's `resolve-context.ts` — read that file's header).\n * Rendering a menu is a SYSTEM derivation: it must work for an anonymous public\n * request, or for a build-time SSG run with no request context at all, and must\n * not fail just because the caller holds no per-entity `view` grant. Elevation\n * bypasses ONLY the permission/scope assertion — `QueryClient`'s PUBLISH filter\n * and trashed-row exclusion still apply, because the elevated context grants\n * reach WITHOUT `view_unpublished` (D017; see {@link SYSTEM_CONTEXT}), so:\n * - an unpublished / trashed MENU still resolves to `null` (nothing renders),\n * - an unpublished / trashed TARGET is still absent from the publish gate and\n * from the title read, so its item is dropped.\n * The only data elevation exposes is a published document's title + canonical\n * path — the same facts the public sitemap already enumerates.\n */\n\nimport { createDetailTemplateProvider } from '@murumets-ee/content/detail-template'\nimport { getContentConfig } from '@murumets-ee/content/plugin'\nimport {\n buildCanonicalPathsBatchDeps,\n buildEnumerateDeps,\n getCanonicalPaths,\n} from '@murumets-ee/content/resolve'\nimport type { ToolkitApp } from '@murumets-ee/core'\nimport { createSystemReachResolver } from '@murumets-ee/core'\nimport type { SecurityContext } from '@murumets-ee/entity'\nimport { getEntityTitleField, isTemplateDrawn } from '@murumets-ee/entity'\nimport { QueryClient } from '@murumets-ee/entity/query'\nimport { eq, inArray } from 'drizzle-orm'\nimport { Menu } from './entity.js'\nimport type { MenuResolveDeps, MenuRow } from './get-menu.js'\nimport { column } from './internal/columns.js'\n\n/**\n * Elevated **reach** resolver — grants reach, never visibility of unpublished\n * rows. See the file header.\n *\n * That invariant used to rest on `QueryClient` applying the publish filter\n * unconditionally; since D017 it rests on this resolver withholding\n * `view_unpublished`, which {@link createSystemReachResolver} does centrally.\n * A `checker: () => true` here would make `_menu` render items pointing at\n * draft documents.\n */\n// Named, not defaulted: `content`'s path resolver is the other elevated reader\n// and passes `'path-resolver'`. Two of them logging the default `'system'` would\n// be indistinguishable in audit output.\nconst SYSTEM_CONTEXT: () => SecurityContext = createSystemReachResolver('menu-resolver')\n\n/** Ids per batched title lookup — mirrors content's `CANONICAL_BATCH_SIZE`. */\nconst TITLE_BATCH_SIZE = 500\n\n/**\n * Build the concrete {@link MenuResolveDeps} for an app.\n *\n * Cheap to call per request (it constructs no clients eagerly — each read\n * builds its own `QueryClient`, matching `buildEnumerateDeps`'s per-call shape,\n * so this never depends on plugin boot ORDER).\n */\nexport function buildMenuResolveDeps(app: ToolkitApp): MenuResolveDeps {\n const db = app.db.readOnly\n const canonicalBatch = buildCanonicalPathsBatchDeps(app)\n const { filterPublished } = buildEnumerateDeps(app)\n\n return {\n getMenuRow: async (handle: string): Promise<MenuRow | null> => {\n const client = new QueryClient({\n entity: Menu,\n db,\n logger: app.logger.child({ resolve: 'menu' }),\n contextResolver: SYSTEM_CONTEXT,\n })\n // `publishable()` on `Menu` means this client filters to PUBLISHED rows\n // for any principal without `view_unpublished` — and `SYSTEM_CONTEXT`\n // withholds it (D017), so the filter always applies HERE. A draft menu\n // returns nothing, which `getMenu` turns into `null`. Do not swap this\n // resolver for a blanket `checker: () => true`: that grants the action and\n // silently publishes drafts.\n //\n // No `locale` is passed: the menu entity has no translations and no\n // locale-status table (locale variance lives INSIDE the tree, per D009),\n // so a locale would only cost a pointless translation merge.\n const rows = await client.findMany({\n where: eq(column(client.getTable(), 'handle'), handle),\n limit: 1,\n })\n const row = rows[0]\n if (row === undefined) return null\n return { maxDepth: row.maxDepth, tree: row.tree }\n },\n\n resolveCanonicalPaths: (entityType, ids, locale) =>\n getCanonicalPaths(entityType, ids, locale, canonicalBatch),\n\n filterPublished,\n\n resolveTitles: async (entityType, ids, locale) => {\n const titles = new Map<string, string>()\n if (ids.length === 0) return titles\n // An unregistered entity type yields NO title, so its items are dropped\n // — fail-closed, matching `buildEnumerateDeps`'s own unknown-type branch.\n const entity = app.entities.get(entityType)\n if (entity === undefined) return titles\n\n // A row DRAWN BY A STORED TEMPLATE (block-library D009, F051) is public\n // only as far as its site's detail bindings say. Its admin title column is\n // not one of those values (a legal document's is its `type` key), so it is\n // never read for a label: the item takes the row's DECLARED title — the\n // same one its own page shows — and drops if the site declares none.\n const declaredTitles = isTemplateDrawn(entity)\n ? createDetailTemplateProvider(() => app, {\n defaultLocale: getContentConfig().defaultLocale,\n })\n : undefined\n\n const titleField = getEntityTitleField(entity)\n // `getEntityTitleField` degrades to the row's own `id` when the entity has\n // no display-able field — a raw UUID is not a menu label. Fail closed and\n // let the item drop, matching this module's own stated posture.\n if (declaredTitles === undefined && titleField === 'id') return titles\n const client = new QueryClient({\n entity,\n db,\n logger: app.logger.child({ resolve: 'menu-title', entity: entityType }),\n contextResolver: SYSTEM_CONTEXT,\n })\n const idColumn = column(client.getTable(), 'id')\n\n for (let i = 0; i < ids.length; i += TITLE_BATCH_SIZE) {\n const chunk = ids.slice(i, i + TITLE_BATCH_SIZE)\n // `locale` drives `mergeTranslations`, so a translatable title comes\n // back in the requested locale (falling back to the base row's value)\n // — the \"live entity title (locale-merged)\" phase 11 §2 asks for.\n const rows = await client.findMany({\n where: inArray(idColumn, [...chunk]),\n locale,\n limit: chunk.length,\n })\n for (const row of rows) {\n const record: Record<string, unknown> = row\n const id = record.id\n let title: unknown\n if (declaredTitles === undefined) {\n title = record[titleField]\n } else {\n // Per ITEM, like everything else here: a projection that throws\n // costs that one label (the item drops), never the whole menu.\n try {\n title = (await declaredTitles.publicRow({ entity: entityType, row: record, locale }))\n .title\n } catch (err) {\n app.logger.warn(\n { err, entity: entityType },\n 'menus: detail-template title projection failed — the item is dropped',\n )\n }\n }\n if (typeof id === 'string' && typeof title === 'string' && title.length > 0) {\n titles.set(id, title)\n }\n }\n }\n return titles\n },\n\n defaultLocale: getContentConfig().defaultLocale,\n logger: app.logger.child({ resolve: 'menu' }),\n }\n}\n"],"mappings":"upBAqEA,MAAa,EAAwB,GAwJrC,SAAS,EAAiB,EAAc,EAAgB,EAA2C,CACjG,GAAoB,OAAO,GAAQ,WAA/B,GAA2C,MAAM,QAAQ,CAAG,EAAG,OACnE,IAAM,EAAkC,EACxC,IAAK,IAAM,KAAO,IAAW,EAAgB,CAAC,CAAM,EAAI,CAAC,EAAQ,CAAa,EAAG,CAC/E,GAAI,CAAC,OAAO,OAAO,EAAQ,CAAG,EAAG,SACjC,IAAM,EAAQ,EAAO,GACrB,GAAI,OAAO,GAAU,UAAY,EAAM,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,CACnB,CAAC,EACK,EAAW,EAAO,EAAO,SAAS,EAAG,IAAI,EAE/C,IAAK,IAAI,EAAI,EAAG,EAAI,EAAI,OAAQ,GAAK,IAAkB,CACrD,IAAM,EAAQ,EAAI,MAAM,EAAG,EAAI,GAAgB,EAIzC,EAAO,MAAM,EAAO,SAAS,CACjC,MAAO,EAAQ,EAAU,CAAC,GAAG,CAAK,CAAC,EACnC,SACA,MAAO,EAAM,MACf,CAAC,EACD,IAAK,IAAM,KAAO,EAAM,CACtB,IAAM,EAAkC,EAClC,EAAK,EAAO,GACd,EACJ,GAAI,IAAmB,IAAA,GACrB,EAAQ,EAAO,QAIf,GAAI,CACF,GAAS,MAAM,EAAe,UAAU,CAAE,OAAQ,EAAY,IAAK,EAAQ,QAAO,CAAC,EAAA,CAChF,KACL,OAAS,EAAK,CACZ,EAAI,OAAO,KACT,CAAE,MAAK,OAAQ,CAAW,EAC1B,sEACF,CACF,CAEE,OAAO,GAAO,UAAY,OAAO,GAAU,UAAY,EAAM,OAAS,GACxE,EAAO,IAAI,EAAI,CAAK,CAExB,CACF,CACA,OAAO,CACT,EAEA,cAAe,EAAiB,CAAC,CAAC,cAClC,OAAQ,EAAI,OAAO,MAAM,CAAE,QAAS,MAAO,CAAC,CAC9C,CACF"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@murumets-ee/menus",
3
- "version": "0.89.0",
3
+ "version": "0.91.0",
4
4
  "license": "Elastic-2.0",
5
5
  "type": "module",
6
6
  "exports": {
@@ -35,10 +35,10 @@
35
35
  "dependencies": {
36
36
  "drizzle-orm": "^0.45.2",
37
37
  "zod": "^3.24.1",
38
- "@murumets-ee/blocks": "0.89.0",
39
- "@murumets-ee/core": "0.89.0",
40
- "@murumets-ee/entity": "0.89.0",
41
- "@murumets-ee/content": "0.89.0"
38
+ "@murumets-ee/blocks": "0.91.0",
39
+ "@murumets-ee/content": "0.91.0",
40
+ "@murumets-ee/core": "0.91.0",
41
+ "@murumets-ee/entity": "0.91.0"
42
42
  },
43
43
  "devDependencies": {
44
44
  "@types/node": "^20.19.42",
@@ -46,7 +46,7 @@
46
46
  "tsdown": "^0.22.2",
47
47
  "typescript": "^5.7.3",
48
48
  "vitest": "^2.1.8",
49
- "@murumets-ee/db": "0.89.0"
49
+ "@murumets-ee/db": "0.91.0"
50
50
  },
51
51
  "typeCoverage": {
52
52
  "atLeast": 100