@murumets-ee/content 0.84.0 → 0.85.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,2 +1,2 @@
1
- import{t as e}from"./chrome-entity-names-zYJzP-_U.mjs";import{t}from"./site-chrome-BUEOhmyf.mjs";import{getBlockTreeFieldName as n}from"@murumets-ee/entity";import{composeChromeRegion as r,stripScopeTags as i}from"@murumets-ee/blocks/render";const a=t;async function o(e,t){let n=e.document&&(!t.claim||t.claim())?await t.readOverrides(e.document.entityType,e.document.id,e.locale):null,o={header:null,footer:null};for(let s of a){if(t.claim&&!t.claim())continue;let a=await t.readChromeDocument(s,e.locale);if(!a)continue;let c={id:a.id,blocks:a.blocks};try{let e=r(c,n);if(!e)continue;o[s]={blocks:i(e.blocks),overridden:e.overridden}}catch(n){t.logger?.warn({region:s,documentId:c.id,locale:e.locale,err:n},`content: chrome region failed to compose (malformed stored blocks, or strip depth exceeded) — serving no chrome for this region`)}}return a.some(e=>o[e]!==null)?o:null}function s(t){return{entity:e,getChrome:async r=>{let i=await t(),{createQueryClient:a}=await import(`@murumets-ee/core/clients`),{schemaRegistry:s}=await import(`@murumets-ee/db`),{eq:c,getTableColumns:l}=await import(`drizzle-orm`),u=e=>{let t=s.get(e);if(t)return l(t)},d=async(e,t,n,r)=>{let o=i.entities.get(e);return o?(await a(o).findMany({limit:1,locale:t,...n!==void 0&&{where:n},...r!==void 0&&{exposeInternalFields:r}}))[0]??null:null},f=i.entities.get(e),p=f?n(f):void 0,m=u(e)?.placement;return!p||!m?null:o(r,{claim:()=>r.budget.claim(`block`,1)>0,readChromeDocument:async(t,n)=>{let r=await d(e,n,c(m,t));if(!r)return null;let i=r[p];return{id:typeof r.id==`string`?r.id:e,blocks:Array.isArray(i)?i:[]}},readOverrides:async(e,t,n)=>{let r=u(e)?.id;if(!r)return null;let i=await d(e,n,c(r,t),[`_overrides`]);if(!i)return null;let a=i._overrides;return a&&typeof a==`object`&&!Array.isArray(a)?a:null},logger:i.logger})}}}export{o as composeChromeRegions,s as createChromeProvider};
1
+ import{t as e}from"./chrome-entity-names-zYJzP-_U.mjs";import{t}from"./site-chrome-DvP9SXGu.mjs";import{getBlockTreeFieldName as n}from"@murumets-ee/entity";import{composeChromeRegion as r,stripScopeTags as i}from"@murumets-ee/blocks/render";const a=t;async function o(e,t){let n=e.document&&(!t.claim||t.claim())?await t.readOverrides(e.document.entityType,e.document.id,e.locale):null,o={header:null,footer:null};for(let s of a){if(t.claim&&!t.claim())continue;let a=await t.readChromeDocument(s,e.locale);if(!a)continue;let c={id:a.id,blocks:a.blocks};try{let e=r(c,n);if(!e)continue;o[s]={blocks:i(e.blocks),overridden:e.overridden}}catch(n){t.logger?.warn({region:s,documentId:c.id,locale:e.locale,err:n},`content: chrome region failed to compose (malformed stored blocks, or strip depth exceeded) — serving no chrome for this region`)}}return a.some(e=>o[e]!==null)?o:null}function s(t){return{entity:e,getChrome:async r=>{let i=await t(),{createQueryClient:a}=await import(`@murumets-ee/core/clients`),{schemaRegistry:s}=await import(`@murumets-ee/db`),{eq:c,getTableColumns:l}=await import(`drizzle-orm`),u=e=>{let t=s.get(e);if(t)return l(t)},d=async(e,t,n,r)=>{let o=i.entities.get(e);return o?(await a(o).findMany({limit:1,locale:t,...n!==void 0&&{where:n},...r!==void 0&&{exposeInternalFields:r}}))[0]??null:null},f=i.entities.get(e),p=f?n(f):void 0,m=u(e)?.placement;return!p||!m?null:o(r,{claim:()=>r.budget.claim(`block`,1)>0,readChromeDocument:async(t,n)=>{let r=await d(e,n,c(m,t));if(!r)return null;let i=r[p];return{id:typeof r.id==`string`?r.id:e,blocks:Array.isArray(i)?i:[]}},readOverrides:async(e,t,n)=>{let r=u(e)?.id;if(!r)return null;let i=await d(e,n,c(r,t),[`_overrides`]);if(!i)return null;let a=i._overrides;return a&&typeof a==`object`&&!Array.isArray(a)?a:null},logger:i.logger})}}}export{o as composeChromeRegions,s as createChromeProvider};
2
2
  //# sourceMappingURL=chrome-provider.mjs.map
package/dist/client.mjs CHANGED
@@ -1,2 +1,2 @@
1
- import{t as e}from"./versionable-Br_G5VGR.mjs";import{n as t,t as n}from"./errors-NRNILhhm.mjs";import{t as r}from"./content-config-store-8omQF5p5.mjs";import{a as i,d as a,f as o,h as s,i as c,l,m as u,n as d,o as f,p,r as m,s as h,t as g,u as _}from"./versions-BDxB6k_S.mjs";import{n as v}from"./plugin-BxOHoKPR.mjs";import{t as y}from"./locale-utils-B0mFoV47.mjs";import{i as b,n as x,r as S}from"./context-Bw0n6P47.mjs";import{blockTreeFieldsOf as C}from"@murumets-ee/entity";import{getApp as w}from"@murumets-ee/core";import{schemaRegistry as T}from"@murumets-ee/db";import{inArray as E}from"drizzle-orm";import"server-only";import{createAdminClient as D}from"@murumets-ee/core/clients";function O(e){return{id:e.id,entityId:e.entityId,locale:e.locale,data:e.data,createdBy:e.createdBy,createdByName:e.createdByName??null,createdAt:e.createdAt,updatedAt:e.updatedAt}}async function k(e,n,r,i=`_`,o){y(i);let s=S(e);if(!s)throw new t(e.entity.name,`drafts`);let c=a(e.entity,r);e.admin.assertBlockTreesValid(c);let l=C(e.entity).some(({name:e})=>Object.hasOwn(c,e))?await s.findOne({entityId:n,locale:i}):null;await e.admin.assertMediaKindsValid(c,l?.data);let u=new Date,d=o?.id??``,f=o?.name??null;return O(await s.upsert({entityId:n,locale:i,data:c,createdBy:d,createdByName:f,createdAt:u,updatedAt:u},{target:[`entityId`,`locale`],set:{data:c,updatedAt:u}}))}const A=[`slug`,`slugMode`,`parent`];async function j(e,n,r,i=`_`,o){y(i);let s=S(e);if(!s)throw new t(e.entity.name,`drafts`);let c=a(e.entity,r);if(Object.keys(c).length===0){let e=await s.findOne({entityId:n,locale:i});return e?O(e):null}e.admin.assertBlockTreesValid(c),e.admin.assertUpdateValid(c);let l=C(e.entity).some(({name:e})=>Object.hasOwn(c,e)),u=e.entity.frontend?.path!==void 0&&A.some(e=>Object.hasOwn(c,e)),d=l||u?await s.findOne({entityId:n,locale:i}):null;if(await e.admin.assertMediaKindsValid(c,d?.data),u){let t={...d?.data??{},...c};if(i===`_`)await e.admin.assertPathAvailable(n,t);else{let r=e.entity.allFields,a={},o={};for(let[e,n]of Object.entries(t))r[e]?.translatable===!0?a[e]=n:o[e]=n;let s=e=>A.some(t=>Object.hasOwn(e,t)&&Object.hasOwn(c,t));s(a)&&await e.admin.assertPathAvailable(n,a,i),s(o)&&await e.admin.assertPathAvailable(n,o)}}let f=new Date;return O(await s.upsert({entityId:n,locale:i,data:c,createdBy:o?.id??``,createdByName:o?.name??null,createdAt:f,updatedAt:f},{target:[`entityId`,`locale`],set:{updatedAt:f},mergeJsonb:[`data`]}))}async function M(e,t,n=`_`){y(n);let r=S(e);if(!r)return null;let i=await r.findOne({entityId:t,locale:n});return i?O(i):null}async function N(e,t,n=`_`){y(n);let r=S(e);return r?(await r.deleteMany({entityId:t,locale:n})).length>0:!1}async function P(e,r,i=`_`,s){if(y(i),!S(e))throw new t(e.entity.name,`drafts`);let c=e.versionableOptions?await e.admin.findById(r,p(i)):null;return e.db.transaction(async l=>{let u={...e,db:l},f=S(u);if(!f)throw new t(e.entity.name,`drafts`);let[p]=await f.deleteMany({entityId:r,locale:i});if(!p)throw new n(r,i);let{publishedAt:m,...h}=p.data??{},g=await o(u,r,a(e.entity,{...h,status:`published`}),i,l),_=F(e.entity,h);return _!==void 0&&await e.admin.updateInternal(r,{_overrides:_},{tx:l}),e.versionableOptions&&await d(u,r,g,c,i,s),g})}function F(e,t){if(!(e.behaviors??[]).some(e=>e.name===`withOverrides`))return;let n=e.allFields._overrides;if(n===void 0||n.internal!==!0)return;let r=t._overrides;if(!(typeof r!=`object`||!r||Array.isArray(r)))return r}async function I(e,t,n=`_`){y(n);let r=S(e);return r?r.exists({entityId:t,locale:n}):!1}async function L(e,t=`_`){y(t);let n=S(e);return n?n.count({locale:t}):0}async function R(e,t,n=`_`){y(n);let r=new Set;if(t.length===0)return r;let i=S(e);if(!i)return r;let a=await i.findMany({where:{entityId:{in:t},locale:n}});for(let e of a)r.add(e.entityId);return r}async function z(e,t,n=`_`){y(n);let i=await M(e,t,n);if(!i)return null;let a=r().defaultLocale,o=n===`_`?{defaultLocale:a}:{locale:n,defaultLocale:a},c=await e.admin.findById(t,o);if(!c)return null;let l=e.entity.allFields,d=c,f=i.data,p={};for(let e of Object.keys(f))p[e]=d[e];let m=s(p,f,l);for(let e of m)e.type===`blockTree`&&(e.blockDiffs=u(Array.isArray(e.from)?e.from:[],Array.isArray(e.to)?e.to:[]));return{diffs:m,current:c,draft:i}}async function B(e,t){let n=(await H(e,[t])).get(t);return n?Object.values(n):[]}async function V(e,n,i,a){y(i);let o=r();if(i===o.defaultLocale){let t={status:a};a===`published`&&(t.publishedAt=new Date),await e.admin.update(n,t);return}let s=b(e);if(!s)throw new t(e.entity.name,`localeStatus`);let c={status:a};await e.admin.updateForLocale(n,c,i,{defaultLocale:o.defaultLocale,localeStatusWriter:(e,t,n)=>v(s,e,t,n)})}async function H(e,t){let n=new Map;if(t.length===0)return n;let r=b(e);if(!r)return n;let i=await r.findMany({where:{entityId:{in:t}}});for(let e of i){let t=e.entityId,r=e.locale,i=n.get(t);i||(i={},n.set(t,i)),i[r]={locale:r,status:e.status,publishedAt:e.publishedAt??null}}return n}function U(e,t,n,r){let i={};for(let a of n){if(a.code===r)continue;let n=t?.get(a.code)??{},o=[];for(let t of e)(n[t]===void 0||n[t]===null)&&o.push(t);i[a.code]={complete:o.length===0,total:e.length,translated:e.length-o.length,missing:o}}return i}async function W(e,t){return(await G(e,[t])).get(t)??{}}async function G(e,t){let n=new Map;if(t.length===0)return n;let i=r(),a=Object.entries(e.entity.allFields).filter(([e,t])=>t.translatable).map(([e])=>e);if(a.length===0)return n;let o=T.get(`${e.entity.name}_translations`);if(!o)return n;let s=await e.db.select().from(o).where(E(o.entityId,t)),c=new Map;for(let e of s){let t=e,n=t.entityId,r=t.locale,i={};for(let e of a)i[e]=t[e];let o=c.get(n);o||(o=new Map,c.set(n,o)),o.set(r,i)}for(let e of t)n.set(e,U(a,c.get(e),i.locales,i.defaultLocale));return n}async function K(e,t){let n=r(),i=t?.locale??n.locales.find(e=>e.code!==n.defaultLocale)?.code;if(!i)return{total:0,complete:0,partial:0,missing:0};let a=await e.admin.findMany();if(a.length===0)return{total:0,complete:0,partial:0,missing:0};let o=await G(e,a.map(e=>e.id)),s=0,c=0,l=0;for(let e of a){let t=o.get(e.id)?.[i];!t||t.translated===0?l++:t.complete?s++:c++}return{total:a.length,complete:s,partial:c,missing:l}}var q=class{ctx;constructor(t){let n=e(t.entity.behaviors);this.ctx=x(t,n)}async create(e){let t=await this.ctx.admin.create(e);return this.ctx.versionableOptions&&await h(this.ctx,t.id,t,null,!1),t}findById(e,t){return this.ctx.admin.findById(e,t)}findMany(e){return this.ctx.admin.findMany(e)}async update(e,t){let n=null;this.ctx.versionableOptions&&(n=await this.ctx.admin.findById(e));let r=await this.ctx.admin.update(e,t);if(this.ctx.versionableOptions&&n){let t=_(n,r),a=await h(this.ctx,e,r,t,!1);if(a!==void 0)return await l(this.ctx,e,a),await i(this.ctx,e),{...r,_version:a};await i(this.ctx,e)}return r}delete(e){return this.ctx.admin.delete(e)}saveTranslation(e,t,n){return this.ctx.admin.saveTranslation(e,t,n)}deleteTranslation(e,t){return this.ctx.admin.deleteTranslation(e,t)}getVersions(e,t){return c(this.ctx,e,t)}getVersion(e,t,n){return m(this.ctx,e,t,n)}compareVersions(e,t,n,r){return g(this.ctx,e,t,n,r)}restoreVersion(e,t,n){return f(this.ctx,e,t,n)}pruneVersions(e,t){return i(this.ctx,e,t)}createVersionSnapshot(e,t,n,r,i){return d(this.ctx,e,t,n,r,i)}getTranslationStatus(e){return W(this.ctx,e)}getTranslationStatusBatch(e){return G(this.ctx,e)}getTranslationReport(e){return K(this.ctx,e)}getLocaleStatus(e){return B(this.ctx,e)}setLocaleStatus(e,t,n){return V(this.ctx,e,t,n)}getLocaleStatusBatch(e){return H(this.ctx,e)}saveDraft(e,t,n,r){return k(this.ctx,e,t,n,r)}mergeDraft(e,t,n,r){return j(this.ctx,e,t,n,r)}getDraft(e,t){return M(this.ctx,e,t)}deleteDraft(e,t){return N(this.ctx,e,t)}publishDraft(e,t,n){return P(this.ctx,e,t,n)}hasDraft(e,t){return I(this.ctx,e,t)}countDrafts(e){return L(this.ctx,e)}hasDraftBatch(e,t){return R(this.ctx,e,t)}compareDraftWithCurrent(e,t){return z(this.ctx,e,t)}};function J(e){return new q({admin:D(e),entity:e,logger:w().logger.child({content:e.name})})}export{q as ContentClient,J as createContentClient};
1
+ import{t as e}from"./versionable-Br_G5VGR.mjs";import{n as t,t as n}from"./errors-NRNILhhm.mjs";import{t as r}from"./content-config-store-8omQF5p5.mjs";import{a as i,d as a,f as o,h as s,i as c,l,m as u,n as d,o as f,p,r as m,s as h,t as g,u as _}from"./versions-C9A4rUAR.mjs";import{n as v}from"./plugin-D0i6odXQ.mjs";import{t as y}from"./locale-utils-B0mFoV47.mjs";import{i as b,n as x,r as S}from"./context-D7eEItCY.mjs";import{blockTreeFieldsOf as C,buildPartitionCondition as w}from"@murumets-ee/entity";import{getApp as T,requireSiteFor as E}from"@murumets-ee/core";import{schemaRegistry as D}from"@murumets-ee/db";import{and as O,inArray as k}from"drizzle-orm";import"server-only";import{createAdminClient as A}from"@murumets-ee/core/clients";function j(e){return{id:e.id,entityId:e.entityId,locale:e.locale,data:e.data,createdBy:e.createdBy,createdByName:e.createdByName??null,createdAt:e.createdAt,updatedAt:e.updatedAt}}async function M(e,n,r,i=`_`,o){y(i);let s=await S(e);if(!s)throw new t(e.entity.name,`drafts`);let c=a(e.entity,r);e.admin.assertBlockTreesValid(c);let l=C(e.entity).some(({name:e})=>Object.hasOwn(c,e))?await s.findOne({entityId:n,locale:i}):null;await e.admin.assertMediaKindsValid(c,l?.data);let u=new Date,d=o?.id??``,f=o?.name??null;return j(await s.upsert({entityId:n,locale:i,data:c,createdBy:d,createdByName:f,createdAt:u,updatedAt:u},{target:[`entityId`,`locale`],set:{data:c,updatedAt:u}}))}const N=[`slug`,`slugMode`,`parent`];async function P(e,n,r,i=`_`,o){y(i);let s=await S(e);if(!s)throw new t(e.entity.name,`drafts`);let c=a(e.entity,r);if(Object.keys(c).length===0){let e=await s.findOne({entityId:n,locale:i});return e?j(e):null}e.admin.assertBlockTreesValid(c),e.admin.assertUpdateValid(c);let l=C(e.entity).some(({name:e})=>Object.hasOwn(c,e)),u=e.entity.frontend?.path!==void 0&&N.some(e=>Object.hasOwn(c,e)),d=l||u?await s.findOne({entityId:n,locale:i}):null;if(await e.admin.assertMediaKindsValid(c,d?.data),u){let t={...d?.data??{},...c};if(i===`_`)await e.admin.assertPathAvailable(n,t);else{let r=e.entity.allFields,a={},o={};for(let[e,n]of Object.entries(t))r[e]?.translatable===!0?a[e]=n:o[e]=n;let s=e=>N.some(t=>Object.hasOwn(e,t)&&Object.hasOwn(c,t));s(a)&&await e.admin.assertPathAvailable(n,a,i),s(o)&&await e.admin.assertPathAvailable(n,o)}}let f=new Date;return j(await s.upsert({entityId:n,locale:i,data:c,createdBy:o?.id??``,createdByName:o?.name??null,createdAt:f,updatedAt:f},{target:[`entityId`,`locale`],set:{updatedAt:f},mergeJsonb:[`data`]}))}async function F(e,t,n=`_`){y(n);let r=await S(e);if(!r)return null;let i=await r.findOne({entityId:t,locale:n});return i?j(i):null}async function I(e,t,n=`_`){y(n);let r=await S(e);return r?(await r.deleteMany({entityId:t,locale:n})).length>0:!1}async function L(e,r,i=`_`,s){if(y(i),!await S(e))throw new t(e.entity.name,`drafts`);let c=e.versionableOptions?await e.admin.findById(r,p(i)):null;return e.db.transaction(async l=>{let u={...e,db:l},f=await S(u);if(!f)throw new t(e.entity.name,`drafts`);let[p]=await f.deleteMany({entityId:r,locale:i});if(!p)throw new n(r,i);let{publishedAt:m,...h}=p.data??{},g=await o(u,r,a(e.entity,{...h,status:`published`}),i,l),_=R(e.entity,h);return _!==void 0&&await e.admin.updateInternal(r,{_overrides:_},{tx:l}),e.versionableOptions&&await d(u,r,g,c,i,s),g})}function R(e,t){if(!(e.behaviors??[]).some(e=>e.name===`withOverrides`))return;let n=e.allFields._overrides;if(n===void 0||n.internal!==!0)return;let r=t._overrides;if(!(typeof r!=`object`||!r||Array.isArray(r)))return r}async function z(e,t,n=`_`){y(n);let r=await S(e);return r?r.exists({entityId:t,locale:n}):!1}async function B(e,t=`_`){y(t);let n=await S(e);return n?n.count({locale:t}):0}async function V(e,t,n=`_`){y(n);let r=new Set;if(t.length===0)return r;let i=await S(e);if(!i)return r;let a=await i.findMany({where:{entityId:{in:t},locale:n}});for(let e of a)r.add(e.entityId);return r}async function H(e,t,n=`_`){y(n);let i=await F(e,t,n);if(!i)return null;let a=r().defaultLocale,o=n===`_`?{defaultLocale:a}:{locale:n,defaultLocale:a},c=await e.admin.findById(t,o);if(!c)return null;let l=e.entity.allFields,d=c,f=i.data,p={};for(let e of Object.keys(f))p[e]=d[e];let m=s(p,f,l);for(let e of m)e.type===`blockTree`&&(e.blockDiffs=u(Array.isArray(e.from)?e.from:[],Array.isArray(e.to)?e.to:[]));return{diffs:m,current:c,draft:i}}async function U(e,t){let n=(await G(e,[t])).get(t);return n?Object.values(n):[]}async function W(e,n,i,a){y(i);let o=r();if(i===o.defaultLocale){let t={status:a};a===`published`&&(t.publishedAt=new Date),await e.admin.update(n,t);return}let s=await b(e);if(!s)throw new t(e.entity.name,`localeStatus`);let c={status:a};await e.admin.updateForLocale(n,c,i,{defaultLocale:o.defaultLocale,localeStatusWriter:(e,t,n)=>v(s,e,t,n)})}async function G(e,t){let n=new Map;if(t.length===0)return n;let r=await b(e);if(!r)return n;let i=await r.findMany({where:{entityId:{in:t}}});for(let e of i){let t=e.entityId,r=e.locale,i=n.get(t);i||(i={},n.set(t,i)),i[r]={locale:r,status:e.status,publishedAt:e.publishedAt??null}}return n}function K(e,t,n,r){let i={};for(let a of n){if(a.code===r)continue;let n=t?.get(a.code)??{},o=[];for(let t of e)(n[t]===void 0||n[t]===null)&&o.push(t);i[a.code]={complete:o.length===0,total:e.length,translated:e.length-o.length,missing:o}}return i}async function q(e,t){return(await J(e,[t])).get(t)??{}}async function J(e,t){let n=new Map;if(t.length===0)return n;let i=r(),a=Object.entries(e.entity.allFields).filter(([e,t])=>t.translatable).map(([e])=>e);if(a.length===0)return n;let o=D.get(`${e.entity.name}_translations`);if(!o)return n;let s=await E(e.entity),c=k(o.entityId,t),l=await e.db.select().from(o).where(s===void 0?c:O(c,w(o,{site:s},e.entity.name))),u=new Map;for(let e of l){let t=e,n=t.entityId,r=t.locale,i={};for(let e of a)i[e]=t[e];let o=u.get(n);o||(o=new Map,u.set(n,o)),o.set(r,i)}for(let e of t)n.set(e,K(a,u.get(e),i.locales,i.defaultLocale));return n}async function Y(e,t){let n=r(),i=t?.locale??n.locales.find(e=>e.code!==n.defaultLocale)?.code;if(!i)return{total:0,complete:0,partial:0,missing:0};let a=await e.admin.findMany();if(a.length===0)return{total:0,complete:0,partial:0,missing:0};let o=await J(e,a.map(e=>e.id)),s=0,c=0,l=0;for(let e of a){let t=o.get(e.id)?.[i];!t||t.translated===0?l++:t.complete?s++:c++}return{total:a.length,complete:s,partial:c,missing:l}}var X=class{ctx;constructor(t){let n=e(t.entity.behaviors);this.ctx=x(t,n)}async create(e){let t=await this.ctx.admin.create(e);return this.ctx.versionableOptions&&await h(this.ctx,t.id,t,null,!1),t}findById(e,t){return this.ctx.admin.findById(e,t)}findMany(e){return this.ctx.admin.findMany(e)}async update(e,t){let n=null;this.ctx.versionableOptions&&(n=await this.ctx.admin.findById(e));let r=await this.ctx.admin.update(e,t);if(this.ctx.versionableOptions&&n){let t=_(n,r),a=await h(this.ctx,e,r,t,!1);if(a!==void 0)return await l(this.ctx,e,a),await i(this.ctx,e),{...r,_version:a};await i(this.ctx,e)}return r}delete(e){return this.ctx.admin.delete(e)}saveTranslation(e,t,n){return this.ctx.admin.saveTranslation(e,t,n)}deleteTranslation(e,t){return this.ctx.admin.deleteTranslation(e,t)}getVersions(e,t){return c(this.ctx,e,t)}getVersion(e,t,n){return m(this.ctx,e,t,n)}compareVersions(e,t,n,r){return g(this.ctx,e,t,n,r)}restoreVersion(e,t,n){return f(this.ctx,e,t,n)}pruneVersions(e,t){return i(this.ctx,e,t)}createVersionSnapshot(e,t,n,r,i){return d(this.ctx,e,t,n,r,i)}getTranslationStatus(e){return q(this.ctx,e)}getTranslationStatusBatch(e){return J(this.ctx,e)}getTranslationReport(e){return Y(this.ctx,e)}getLocaleStatus(e){return U(this.ctx,e)}setLocaleStatus(e,t,n){return W(this.ctx,e,t,n)}getLocaleStatusBatch(e){return G(this.ctx,e)}saveDraft(e,t,n,r){return M(this.ctx,e,t,n,r)}mergeDraft(e,t,n,r){return P(this.ctx,e,t,n,r)}getDraft(e,t){return F(this.ctx,e,t)}deleteDraft(e,t){return I(this.ctx,e,t)}publishDraft(e,t,n){return L(this.ctx,e,t,n)}hasDraft(e,t){return z(this.ctx,e,t)}countDrafts(e){return B(this.ctx,e)}hasDraftBatch(e,t){return V(this.ctx,e,t)}compareDraftWithCurrent(e,t){return H(this.ctx,e,t)}};function Z(e){return new X({admin:A(e),entity:e,logger:T().logger.child({content:e.name})})}export{X as ContentClient,Z as createContentClient};
2
2
  //# sourceMappingURL=client.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"client.mjs","names":[],"sources":["../src/drafts.ts","../src/locale-status.ts","../src/translation-status.ts","../src/client.ts"],"sourcesContent":["/**\n * Draft-overlay operations.\n *\n * Capability: requires the entity to declare `publishable()`. Reads\n * (`getDraft`, `hasDraft`, `countDrafts`, `hasDraftBatch`) silently\n * return falsy when the entity doesn't support drafts; writes\n * (`saveDraft`, `mergeDraft`, `publishDraft`) throw `EntityCapabilityError`.\n */\n\nimport 'server-only'\n\nimport { blockTreeFieldsOf, type FieldConfig } from '@murumets-ee/entity'\nimport type { InferEntityDTO, InferUpdateInput } from '@murumets-ee/entity/admin'\nimport { diffBlocks } from './diff/block-diff.js'\nimport { diffFields } from './diff/field-diff.js'\nimport type { FieldDiff } from './diff/types.js'\nimport { DraftNotFoundError, EntityCapabilityError } from './errors.js'\nimport {\n applyLocaleRoutedUpdate,\n localeFindOptions,\n} from './internal/apply-locale-routed-update.js'\nimport { type ContentContext, getDraftsClient } from './internal/context.js'\nimport { projectToEntityFields } from './internal/projection.js'\nimport { DEFAULT_LOCALE_SENTINEL, validateLocale } from './locale-utils.js'\nimport { getContentConfig } from './plugin.js'\nimport type { DraftsTable } from './schema/drafts.js'\nimport type { DraftEntry } from './types.js'\nimport { createVersionSnapshot } from './versions.js'\n\ntype DraftRow = NonNullable<Awaited<ReturnType<ReturnType<DraftsTable['makeClient']>['findOne']>>>\n\nfunction toDraftEntry(row: DraftRow): DraftEntry {\n return {\n id: row.id,\n entityId: row.entityId,\n locale: row.locale,\n data: row.data,\n createdBy: row.createdBy,\n createdByName: row.createdByName ?? null,\n createdAt: row.createdAt,\n updatedAt: row.updatedAt,\n }\n}\n\n/**\n * Save (upsert) a draft for an entity+locale. One draft per\n * entity+locale — overwrites any existing draft.\n *\n * `data` is projected through the entity's declared field whitelist\n * BEFORE it is stored (same `projectToEntityFields` call `publishDraft`\n * makes on the way out). Storing the caller's JSON verbatim let a draft\n * carry keys the entity never declared, identity/audit columns and\n * `internal: true` fields; publishing filtered them, but `getDraft` and\n * `compareDraftWithCurrent` echoed them straight back to the admin UI,\n * and the drafts table accumulated arbitrary caller-controlled JSON\n * (`plan/admin-api-hardening` F002). Validating at the write closes the\n * asymmetry — the stored draft is now always a subset of what the entity\n * can actually hold.\n */\nexport async function saveDraft<F extends Record<string, FieldConfig>>(\n ctx: ContentContext<F>,\n entityId: string,\n data: InferUpdateInput<F>,\n locale = DEFAULT_LOCALE_SENTINEL,\n user?: { id: string; name?: string },\n): Promise<DraftEntry<InferUpdateInput<F>>> {\n validateLocale(locale)\n const client = getDraftsClient(ctx)\n if (!client) throw new EntityCapabilityError(ctx.entity.name, 'drafts')\n\n const projected = projectToEntityFields(ctx.entity, data as Record<string, unknown>)\n\n // `projectToEntityFields` is a field-NAME whitelist — it never inspects a\n // value, so a `field.blockTree()` column in a draft took arbitrary JSON, and\n // `editor-state` hands the stored draft back as the CANVAS BASE STATE\n // (editor F002). Publishing is already gated by the entity write path, but\n // waiting until publish means the editor loads a tree it cannot represent.\n // Same validator, same judgement — asked here because the draft blob carries\n // no Zod schema of its own.\n ctx.admin.assertBlockTreesValid(projected)\n // F116, same reasoning — and this is precisely the write path the finding\n // was filed against: dava's home-page DRAFT already holds a mismatched\n // media reference. Grandfathering against the draft ALREADY STORED (rather\n // than validating strictly) is what keeps that draft's next autosave\n // working instead of turning \"a broken image\" into \"a draft that can never\n // be saved again\".\n //\n // The lookup is skipped entirely when the PROJECTED payload carries no\n // block-tree field at all — `assertMediaKindsValid` would no-op anyway\n // (same optimization as `saveTranslation`'s), and most entities with\n // drafts have no block-tree field to begin with.\n const hasBlockTreeValue = blockTreeFieldsOf(ctx.entity).some(({ name }) =>\n Object.hasOwn(projected, name),\n )\n const existing = hasBlockTreeValue ? await client.findOne({ entityId, locale }) : null\n await ctx.admin.assertMediaKindsValid(\n projected,\n existing?.data as Record<string, unknown> | undefined,\n )\n\n const now = new Date()\n const createdBy = user?.id ?? ''\n const createdByName = user?.name ?? null\n\n const row = await client.upsert(\n {\n entityId,\n locale,\n data: projected,\n createdBy,\n createdByName,\n createdAt: now,\n updatedAt: now,\n },\n {\n target: ['entityId', 'locale'],\n // On conflict, only update the mutable fields — preserve createdBy/createdAt.\n set: { data: projected, updatedAt: now },\n },\n )\n\n return toDraftEntry(row) as DraftEntry<InferUpdateInput<F>>\n}\n\n/**\n * The keys that move a document's canonical URL in the patterns the toolkit\n * ships (`[slug]`, `[parent.path]`) plus the slug mode that decides whether a\n * clash is refused or auto-suffixed. A merge naming one of them, on a ROUTABLE\n * entity, runs the path-conflict check (see `mergeDraft`); any other merge\n * skips its lookups — the staged draft, the row, and `toolkit_paths` (twice\n * under a parent).\n *\n * A pattern built from another field (`/[category]/[slug]`) is not covered:\n * staging only `category` is refused at Publish rather than here.\n */\nconst PATH_KEYS = ['slug', 'slugMode', 'parent'] as const\n\n/**\n * Stage a PARTIAL change: merge `patch` into the entity+locale draft, creating\n * the draft if there is none. Keys not in `patch` are left exactly as the draft\n * (or, absent a draft key, the live row) has them.\n *\n * This is the write every editing surface uses since editor D019 — \"every edit\n * on every surface saves to the document's one shared draft\". `saveDraft`\n * REPLACES the blob, which is right for a surface that owns the whole document\n * (the menu editor) and wrong for one that owns a few fields of it: page\n * settings saving `title` through `saveDraft` would erase the block edits the\n * canvas staged a second earlier. A draft is therefore a patch over the row, and\n * every reader that shows editable values reads row ⊕ draft.\n *\n * Judged like the entity PATCH it replaces, BEFORE it is stored:\n * - projected through the field whitelist (`internal`, undeclared keys dropped)\n * - `assertBlockTreesValid` + `assertMediaKindsValid` (grandfathered against the\n * stored draft, same as `saveDraft`)\n * - `assertUpdateValid` — the entity's own update schema. `saveDraft` never ran\n * it, which was harmless while the form's Publish still PATCHed; moving a\n * surface into the draft must not move its refusal to Publish, where the\n * author is no longer looking at the field.\n * - `assertPathAvailable` — the path-conflict guard, as a dry run, when the\n * merge moves the URL (see {@link PATH_KEYS}) on a routable entity (F150).\n *\n * 🔴 ONE STATEMENT, not read-modify-write. The merge is `data || patch` inside\n * `ON CONFLICT DO UPDATE` (`TableClient.upsert`'s `mergeJsonb`), so it cannot\n * lose a concurrent write: a read-then-upsert that interleaved with op-commit's\n * or a bound field's stage would write back the draft as it was read — silently\n * reverting the other writer's change. `writeDraft` merges the same way, so\n * neither can erase the other. Top-level `||`, a SHALLOW merge.\n *\n * Resolves `null` when the projected patch is EMPTY and no draft exists: nothing\n * the entity declares was sent, so nothing is staged and no empty draft row is\n * created.\n *\n * ⚠️ The rest of the write path's hooks — `pathParent()`'s cycle check, the\n * partial-unique slug index, `sluggable()`'s regeneration — still run only at\n * Publish, inside its transaction, where a refusal stops the whole publish. The\n * path check here answers \"as of now\"; Publish runs the real guard again.\n */\nexport async function mergeDraft<F extends Record<string, FieldConfig>>(\n ctx: ContentContext<F>,\n entityId: string,\n patch: InferUpdateInput<F>,\n locale = DEFAULT_LOCALE_SENTINEL,\n user?: { id: string; name?: string },\n): Promise<DraftEntry<InferUpdateInput<F>> | null> {\n validateLocale(locale)\n const client = getDraftsClient(ctx)\n if (!client) throw new EntityCapabilityError(ctx.entity.name, 'drafts')\n\n const projected = projectToEntityFields(ctx.entity, patch as Record<string, unknown>)\n // Nothing the entity declares: stage nothing. Upserting `{}` would CREATE an\n // empty draft, and the document would then read \"Draft saved · not live\n // yet\" about a change that does not exist.\n if (Object.keys(projected).length === 0) {\n const current = await client.findOne({ entityId, locale })\n return current ? (toDraftEntry(current) as DraftEntry<InferUpdateInput<F>>) : null\n }\n ctx.admin.assertBlockTreesValid(projected)\n ctx.admin.assertUpdateValid(projected)\n const hasBlockTreeValue = blockTreeFieldsOf(ctx.entity).some(({ name }) =>\n Object.hasOwn(projected, name),\n )\n const touchesPath =\n ctx.entity.frontend?.path !== undefined &&\n PATH_KEYS.some((key) => Object.hasOwn(projected, key))\n const existing =\n hasBlockTreeValue || touchesPath ? await client.findOne({ entityId, locale }) : null\n await ctx.admin.assertMediaKindsValid(\n projected,\n existing?.data as Record<string, unknown> | undefined,\n )\n // A staged slug that another document's URL already holds is refused NOW,\n // beside the field the author typed it in — not first at Publish (editor\n // PR60, F150). Checked against what the draft will hold after this merge,\n // since an earlier stage may have set `slugMode` or `parent`.\n if (touchesPath) {\n const staged = {\n ...((existing?.data as Record<string, unknown> | undefined) ?? {}),\n ...projected,\n }\n if (locale === DEFAULT_LOCALE_SENTINEL) {\n await ctx.admin.assertPathAvailable(entityId, staged)\n } else {\n // Checked the way Publish writes it: `updateForLocale` sends a locale's\n // TRANSLATABLE fields through that locale's guard and the rest (a\n // `parent`, a non-translatable slug) through `update()`, whose guard\n // checks the default locale. One guard over everything would test a\n // shared `parent` against the wrong locale's URLs.\n const fields = ctx.entity.allFields as Record<string, { translatable?: boolean } | undefined>\n const translatable: Record<string, unknown> = {}\n const shared: Record<string, unknown> = {}\n for (const [key, value] of Object.entries(staged)) {\n if (fields[key]?.translatable === true) translatable[key] = value\n else shared[key] = value\n }\n const moves = (part: Record<string, unknown>) =>\n PATH_KEYS.some((key) => Object.hasOwn(part, key) && Object.hasOwn(projected, key))\n if (moves(translatable)) await ctx.admin.assertPathAvailable(entityId, translatable, locale)\n if (moves(shared)) await ctx.admin.assertPathAvailable(entityId, shared)\n }\n }\n\n const now = new Date()\n const row = await client.upsert(\n {\n entityId,\n locale,\n data: projected,\n createdBy: user?.id ?? '',\n createdByName: user?.name ?? null,\n createdAt: now,\n updatedAt: now,\n },\n { target: ['entityId', 'locale'], set: { updatedAt: now }, mergeJsonb: ['data'] },\n )\n return toDraftEntry(row) as DraftEntry<InferUpdateInput<F>>\n}\n\n/**\n * Get the draft for an entity+locale, or null if none exists (or the\n * entity doesn't support drafts).\n */\nexport async function getDraft<F extends Record<string, FieldConfig>>(\n ctx: ContentContext<F>,\n entityId: string,\n locale = DEFAULT_LOCALE_SENTINEL,\n): Promise<DraftEntry<InferUpdateInput<F>> | null> {\n validateLocale(locale)\n const client = getDraftsClient(ctx)\n if (!client) return null\n const row = await client.findOne({ entityId, locale })\n return row ? (toDraftEntry(row) as DraftEntry<InferUpdateInput<F>>) : null\n}\n\n/**\n * Delete (discard) a draft for an entity+locale. Returns whether\n * anything was deleted; safely no-ops on entities without drafts.\n */\nexport async function deleteDraft(\n ctx: ContentContext,\n entityId: string,\n locale = DEFAULT_LOCALE_SENTINEL,\n): Promise<boolean> {\n validateLocale(locale)\n const client = getDraftsClient(ctx)\n if (!client) return false\n const deleted = await client.deleteMany({ entityId, locale })\n return deleted.length > 0\n}\n\n/**\n * Publish a draft: make THIS document's staged changes live.\n *\n * \"Publish\" means one thing on every surface (editor D019): the draft's fields\n * are written to the row for the draft's locale AND the row is put live. The\n * draft is then gone and, if versionable, a version snapshot records what went\n * live.\n *\n * Locale routing mirrors the admin PATCH handler (and the taxonomy fix\n * in 10a7cc2b): a default-locale draft writes the base row; a\n * non-default-locale draft routes translatable fields to\n * `saveTranslation` (→ `{entity}_translations`), `status` to the\n * per-locale status table, and only non-translatable fields (which have\n * no per-locale home) to the base row. Without this split, publishing\n * an `et` draft overwrote the default-locale base row wholesale.\n *\n * ## ONE TRANSACTION (editor PR60, R055 §4)\n *\n * The row write, the locale status, `_overrides`, the draft delete and the\n * version snapshot commit together or not at all. They used to be five separate\n * statements, so a failure part-way left a document whose content was live and\n * whose draft still claimed to be pending — or, worse, whose draft was gone while\n * the row write had not landed.\n *\n * The draft is CLAIMED first, by deleting it and publishing what the delete\n * returned. The delete takes the row lock, so an op-commit that is mid-flight on\n * the same draft either committed before (and its edit is in what we publish) or\n * blocks until we commit and then retries its SERIALIZABLE transaction — or, if it\n * had not read the draft yet, inserts a fresh draft holding only its own patch.\n * Either way it does not write a stale copy back over the published one. The editor also flushes and awaits its own in-flight saves\n * before it calls this, so the lock is the backstop, not the mechanism.\n *\n * Path-index and write notifications fire after COMMIT, not inside it —\n * `AdminClient.afterCommit` defers them on a tracked transaction.\n */\nexport async function publishDraft<F extends Record<string, FieldConfig>>(\n ctx: ContentContext<F>,\n entityId: string,\n locale = DEFAULT_LOCALE_SENTINEL,\n user?: { id: string; name?: string },\n): Promise<InferEntityDTO<F>> {\n validateLocale(locale)\n if (!getDraftsClient(ctx)) {\n throw new EntityCapabilityError(ctx.entity.name, 'drafts')\n }\n\n // Previous state for the version delta — locale-merged, so the delta compares\n // against what this locale's readers actually saw. Read BEFORE the\n // transaction: it is the committed state the publish replaces.\n const previousState: InferEntityDTO<F> | null = ctx.versionableOptions\n ? await ctx.admin.findById(entityId, localeFindOptions(locale))\n : null\n\n return ctx.db.transaction(async (tx) => {\n // Every table client below binds to `tx` through this context — drafts,\n // locale status, versions and the `_version` column write.\n const txCtx: ContentContext<F> = { ...ctx, db: tx }\n const draftsClient = getDraftsClient(txCtx)\n if (!draftsClient) throw new EntityCapabilityError(ctx.entity.name, 'drafts')\n const [claimed] = await draftsClient.deleteMany({ entityId, locale })\n if (!claimed) {\n throw new DraftNotFoundError(entityId, locale)\n }\n\n // `?? {}` because the column is `jsonb NOT NULL`, and that forbids SQL NULL\n // while permitting the JSON literal `null` — which deserializes to JS `null`.\n // A bare cast then made `draftData.status` a TypeError, so a malformed row\n // 500'd the publish route instead of taking the ordinary \"nothing declared,\n // publish the row as-is\" path below. Nothing in this package writes such a\n // row; a seed, a migration or a hand-edit can.\n const claimedData = (claimed.data ?? {}) as Record<string, unknown>\n // `publishedAt` is Publish's to set, like `status` below: a staged value\n // would let whoever wrote the draft back- or forward-date the publication.\n // publishable()'s hook fills it when the UPDATE carries none — which, with\n // the staged value dropped, is every publish: it records the LATEST\n // publication, not the first.\n const { publishedAt: _stagedPublishedAt, ...draftData } = claimedData\n // \"Publish\" means MAKE LIVE, always — the status is not the draft's to\n // decide. Block-editor drafts carry no `status` at all, and before D019 a\n // form-saved draft could carry `status: 'draft'`, which then won: Publish\n // wrote the content and left the document unpublished, so the same button\n // meant \"publish\" on one surface and \"stage\" on another. The publishable()\n // behavior auto-sets `publishedAt` on the transition. The publish-permission\n // gate lives in the admin route, not here.\n const updateData = projectToEntityFields(ctx.entity, { ...draftData, status: 'published' })\n const result = await applyLocaleRoutedUpdate(txCtx, entityId, updateData, locale, tx)\n\n // F009 — promote the page's chrome overrides.\n //\n // `projectToEntityFields` drops every `internal: true` field, deliberately, so\n // `_overrides` cannot ride the generic promotion. That guard is NOT relaxed:\n // this is one named field, written through the trusted `updateInternal` path\n // that `with-overrides.ts` documents as \"the only path that can mutate it\".\n // Before F009 that call site did not exist, so an override survived in the\n // draft buffer and never reached the column — the op committed, the canvas\n // updated, and a reload brought the hidden header back.\n //\n // AFTER the main update, so the override never lands against content that\n // failed to — and inside the same transaction, so neither lands alone.\n // `_overrides` is not translatable, so it belongs on the base row for every\n // locale.\n const overrides = readOverridesForPublish(ctx.entity, draftData)\n if (overrides !== undefined) {\n await ctx.admin.updateInternal(entityId, { _overrides: overrides }, { tx })\n }\n\n if (ctx.versionableOptions) {\n await createVersionSnapshot(txCtx, entityId, result, previousState, locale, user)\n }\n\n return result\n })\n}\n\n/**\n * The page's override map from a draft payload, when the entity declares the\n * field and the draft carries one.\n *\n * Returns `undefined` — never `{}` — so an ordinary content publish does not\n * touch the column. Shape-guarded because a draft payload is stored jsonb: an\n * array or a scalar is malformed data, not an override map. ← F009\n */\nfunction readOverridesForPublish(\n entity: { allFields: Record<string, unknown>; behaviors?: readonly { name: string }[] },\n draftData: Record<string, unknown>,\n): Record<string, unknown> | undefined {\n // The BEHAVIOR, not just a field with the right name — a draft payload is\n // stored jsonb and can be crafted or legacy, so this must not become a way\n // to promote arbitrary JSON into an unrelated internal field on an entity\n // that never opted in. Requiring the behavior also means `beforeUpdate` runs\n // `validateOverridesMap` on the way through `updateInternal`.\n if (!(entity.behaviors ?? []).some((b) => b.name === 'withOverrides')) return undefined\n const field = entity.allFields._overrides as { internal?: boolean } | undefined\n if (field === undefined || field.internal !== true) return undefined\n const value = draftData._overrides\n if (typeof value !== 'object' || value === null || Array.isArray(value)) return undefined\n return value as Record<string, unknown>\n}\n\n/**\n * Quick existence check for list badges — does a draft exist?\n */\nexport async function hasDraft(\n ctx: ContentContext,\n entityId: string,\n locale = DEFAULT_LOCALE_SENTINEL,\n): Promise<boolean> {\n validateLocale(locale)\n const client = getDraftsClient(ctx)\n if (!client) return false\n return client.exists({ entityId, locale })\n}\n\n/**\n * Count drafts for this entity type, optionally filtered by locale.\n * Single indexed COUNT — used by dashboard widgets.\n */\nexport async function countDrafts(\n ctx: ContentContext,\n locale = DEFAULT_LOCALE_SENTINEL,\n): Promise<number> {\n validateLocale(locale)\n const client = getDraftsClient(ctx)\n if (!client) return 0\n return client.count({ locale })\n}\n\n/**\n * Check draft existence for multiple entities in one query. Returns\n * a set of entity IDs that have a draft for `locale`.\n */\nexport async function hasDraftBatch(\n ctx: ContentContext,\n entityIds: string[],\n locale = DEFAULT_LOCALE_SENTINEL,\n): Promise<Set<string>> {\n validateLocale(locale)\n const result = new Set<string>()\n if (entityIds.length === 0) return result\n const client = getDraftsClient(ctx)\n if (!client) return result\n\n const rows = await client.findMany({\n where: { entityId: { in: entityIds }, locale },\n })\n for (const row of rows) {\n result.add(row.entityId as string)\n }\n return result\n}\n\n/**\n * Compare the current draft with the live entity. Returns field-level\n * diffs between the published data and the draft (only for fields\n * present in the draft — missing fields are NOT \"changed to empty\").\n */\nexport async function compareDraftWithCurrent<F extends Record<string, FieldConfig>>(\n ctx: ContentContext<F>,\n entityId: string,\n locale = DEFAULT_LOCALE_SENTINEL,\n): Promise<{\n diffs: FieldDiff[]\n current: InferEntityDTO<F>\n draft: DraftEntry<InferUpdateInput<F>>\n} | null> {\n validateLocale(locale)\n const draft = await getDraft(ctx, entityId, locale)\n if (!draft) return null\n\n // Fetch the live entity with the same locale context as the draft.\n const config = getContentConfig()\n const defaultLocale = config.defaultLocale\n const findOptions =\n locale === DEFAULT_LOCALE_SENTINEL ? { defaultLocale } : { locale, defaultLocale }\n const current = await ctx.admin.findById(entityId, findOptions)\n if (!current) return null\n\n const fieldConfigs = ctx.entity.allFields as Record<string, FieldConfig> | undefined\n const currentRecord = current as Record<string, unknown>\n const draftRecord = draft.data as Record<string, unknown>\n const currentSubset: Record<string, unknown> = {}\n for (const key of Object.keys(draftRecord)) {\n currentSubset[key] = currentRecord[key]\n }\n const diffs = diffFields(currentSubset, draftRecord, fieldConfigs)\n for (const diff of diffs) {\n if (diff.type === 'blockTree') {\n // Normalize a null/undefined side to [] so add/clear of the whole field\n // (null ↔ blockTree[]) still produces a structural diff, not an opaque one.\n diff.blockDiffs = diffBlocks(\n Array.isArray(diff.from) ? diff.from : [],\n Array.isArray(diff.to) ? diff.to : [],\n )\n }\n }\n\n return { diffs, current, draft }\n}\n","/**\n * Per-locale publish status — independent draft/published state for\n * each locale of a publishable + translatable entity.\n *\n * Capability: requires `publishable() + at least one translatable\n * field` (the `_locale_status` table is registered only for that\n * combination). Reads silently return falsy on entities without it;\n * `setLocaleStatus` throws `EntityCapabilityError`.\n */\n\nimport 'server-only'\n\nimport type { FieldConfig } from '@murumets-ee/entity'\nimport type { InferUpdateInput } from '@murumets-ee/entity/admin'\nimport { EntityCapabilityError } from './errors.js'\nimport { type ContentContext, getLocaleStatusClient } from './internal/context.js'\nimport { upsertLocaleStatusRow } from './locale-status-slot.js'\nimport { validateLocale } from './locale-utils.js'\nimport { getContentConfig } from './plugin.js'\nimport type { LocalePublishStatus } from './types.js'\n\n/**\n * Get per-locale publish status overrides for an entity.\n * Missing locale = inherits the base entity status (no row written).\n *\n * **Not permission-gated, deliberately — see {@link getLocaleStatusBatch}.**\n */\nexport async function getLocaleStatus(\n ctx: ContentContext,\n entityId: string,\n): Promise<LocalePublishStatus[]> {\n const map = await getLocaleStatusBatch(ctx, [entityId])\n const entry = map.get(entityId)\n if (!entry) return []\n return Object.values(entry)\n}\n\n/**\n * Set per-locale publish status. Upserts into the locale_status\n * table — except when `locale === defaultLocale`, which updates the\n * base entity status column directly (the per-locale table only\n * stores overrides for non-default locales).\n *\n * **Both branches are publish-gated by the entity layer (D041).** The default\n * branch inherits it from `AdminClient.update`; the non-default branch routes\n * through `AdminClient.updateForLocale`, which asserts the SAME\n * `assertPublishAuthority` from the caller's payload before it hands the write\n * to the locale-status writer. This is deliberately a delegation and not a\n * second predicate in this package: `<entity>_locale_status` is the table the\n * public read predicate (`COALESCE(locale_status.status, main.status)`) resolves\n * against, so a direct `TableClient.upsert` here — which is what this function\n * used to do — is a fourth publish door, reachable from any plugin/route/job\n * holding a `ContentClient` (a PUBLIC subpath export) with no `publish` grant\n * ever consulted.\n */\nexport async function setLocaleStatus<F extends Record<string, FieldConfig>>(\n ctx: ContentContext<F>,\n entityId: string,\n locale: string,\n status: 'draft' | 'published',\n): Promise<void> {\n validateLocale(locale)\n const config = getContentConfig()\n\n // Default locale → update base entity status column.\n if (locale === config.defaultLocale) {\n const data: Record<string, unknown> = { status }\n if (status === 'published') data.publishedAt = new Date()\n await ctx.admin.update(entityId, data as InferUpdateInput<F>)\n return\n }\n\n const client = getLocaleStatusClient(ctx)\n if (!client) {\n // Per-locale status only exists for publishable + translatable\n // entities. Calling on a non-translatable publishable (where the\n // only valid locale is the default) is a programmer error.\n // Checked BEFORE delegating: `updateForLocale` would otherwise fall back to\n // the base `status` column for a missing writer, silently publishing the\n // default locale instead of refusing.\n throw new EntityCapabilityError(ctx.entity.name, 'localeStatus')\n }\n\n // The writer we hand down is the RAW upsert, not this function — the\n // delegation terminates here rather than re-entering `updateForLocale`.\n //\n // Routing through `updateForLocale` rather than calling the upsert directly\n // is what closes the publish door: this branch used to write\n // `<entity>_locale_status` with no permission check at all, so any holder of\n // this public export could make a translation publicly live without\n // `publish`. `updateForLocale` asserts publish authority at the operation\n // entry (D041), so the gate is inherited rather than duplicated here.\n //\n // Widened through `Record<string, unknown>` for the same reason the\n // default-locale branch above does it: `InferUpdateInput<F>` is keyed on the\n // entity's own field map, which a generic `F` cannot be proven to overlap.\n const localeData: Record<string, unknown> = { status }\n await ctx.admin.updateForLocale(entityId, localeData as InferUpdateInput<F>, locale, {\n defaultLocale: config.defaultLocale,\n localeStatusWriter: (id, loc, s) => upsertLocaleStatusRow(client, id, loc, s),\n })\n}\n\n/**\n * Get per-locale publish status for multiple entities in one query.\n *\n * ## Why this read is NOT permission-gated (and what would gate it)\n *\n * It returns publish-state METADATA only — `{ locale, status, publishedAt }` —\n * never field data, so it is not a content-disclosure door the way the write\n * side above is a publish door. What it does expose is an existence oracle for\n * unpublished TRANSLATIONS: a principal without `view_unpublished` learns that\n * `et` is a draft, which `QueryClient` would have hidden. The correct predicate\n * is therefore `view_unpublished` (D017), NOT `publish`.\n *\n * A CodeRabbit pass proposed gating it on exactly that predicate. Deliberately\n * declined, on the strength of **F063**: `view_unpublished` governs `QueryClient`\n * reads — the PUBLIC delivery surface — and is not a disclosure boundary over\n * the admin API, where `AdminClient` shows editors their own drafts by design.\n * `ContentClient` is an in-process server-side API whose consumers are plugins,\n * routes and jobs on the admin side, so gating it here would extend the control\n * onto the surface F063 explicitly recommended NOT extending it to. The concrete\n * cost would be an editor lacking `view_unpublished` no longer able to see that\n * their OWN translation is still a draft.\n *\n * The asymmetry with the write side above is real, not convenient:\n * `setLocaleStatus` MINTS public visibility, so it is gated regardless of which\n * surface calls it. This read hands publish-state metadata to a caller who\n * already holds `view` on the row — they needed its id to ask.\n *\n * It is not applied here because the predicate (`mayViewUnpublishedEntity`) is\n * module-private to `@murumets-ee/entity` — re-deriving it in this package\n * would create exactly the second, drifting copy of a security predicate that\n * D041 exists to eliminate, and there is no read-path equivalent of\n * `updateForLocale` to delegate to. The one in-repo caller\n * (`admin-ui`'s versions route) is already gated by `checkPermission`. Closing\n * this properly means exporting the predicate from `@murumets-ee/entity` and\n * dropping non-`published` rows for principals without it — tracked as the\n * read-side sibling of F060.\n */\nexport async function getLocaleStatusBatch(\n ctx: ContentContext,\n entityIds: string[],\n): Promise<Map<string, Record<string, LocalePublishStatus>>> {\n const result = new Map<string, Record<string, LocalePublishStatus>>()\n if (entityIds.length === 0) return result\n const client = getLocaleStatusClient(ctx)\n if (!client) return result\n\n const rows = await client.findMany({ where: { entityId: { in: entityIds } } })\n for (const r of rows) {\n const eid = r.entityId as string\n const locale = r.locale as string\n let entry = result.get(eid)\n if (!entry) {\n entry = {}\n result.set(eid, entry)\n }\n entry[locale] = {\n locale,\n status: r.status as 'draft' | 'published',\n publishedAt: (r.publishedAt as Date | null) ?? null,\n }\n }\n return result\n}\n","/**\n * Translation status reporting — per-locale completion of translatable\n * fields for one entity, batches of entities, or the whole entity type.\n *\n * Capability: requires the entity to have at least one translatable\n * field. All methods return falsy / empty when the entity has no\n * translatable fields (read-only and defensive).\n */\n\nimport 'server-only'\n\nimport { schemaRegistry } from '@murumets-ee/db'\nimport type { FieldConfig } from '@murumets-ee/entity'\nimport { inArray } from 'drizzle-orm'\nimport type { ContentContext } from './internal/context.js'\nimport { getContentConfig } from './plugin.js'\nimport type { TranslationReport, TranslationStatus } from './types.js'\n\n/**\n * For one entity, compute per-locale completion status across every\n * translatable field. Default-locale rows are skipped.\n */\nfunction computeStatusForEntity(\n translatableFields: string[],\n translatedByLocale: Map<string, Record<string, unknown>> | undefined,\n locales: { code: string }[],\n defaultLocale: string,\n): TranslationStatus {\n const status: TranslationStatus = {}\n for (const locale of locales) {\n if (locale.code === defaultLocale) continue\n const translated = translatedByLocale?.get(locale.code) ?? {}\n const missing: string[] = []\n for (const fieldName of translatableFields) {\n if (translated[fieldName] === undefined || translated[fieldName] === null) {\n missing.push(fieldName)\n }\n }\n status[locale.code] = {\n complete: missing.length === 0,\n total: translatableFields.length,\n translated: translatableFields.length - missing.length,\n missing,\n }\n }\n return status\n}\n\n/**\n * Get translation status for an entity — per-locale completion report.\n */\nexport async function getTranslationStatus(\n ctx: ContentContext,\n entityId: string,\n): Promise<TranslationStatus> {\n // Single-entity is the batch path with one ID — keeps the two\n // codepaths from drifting.\n const map = await getTranslationStatusBatch(ctx, [entityId])\n return map.get(entityId) ?? {}\n}\n\n/**\n * Get translation status for multiple entities in a single query.\n * O(1) DB roundtrips regardless of `entityIds.length`.\n */\nexport async function getTranslationStatusBatch(\n ctx: ContentContext,\n entityIds: string[],\n): Promise<Map<string, TranslationStatus>> {\n const result = new Map<string, TranslationStatus>()\n if (entityIds.length === 0) return result\n\n const config = getContentConfig()\n\n const translatableFields = Object.entries(ctx.entity.allFields as Record<string, FieldConfig>)\n .filter(([_, f]) => f.translatable)\n .map(([name]) => name)\n if (translatableFields.length === 0) return result\n\n // Translation tables are generated in @murumets-ee/entity (with FK\n // refs); accessed via schemaRegistry + direct Drizzle here.\n const translationTable = schemaRegistry.get(`${ctx.entity.name}_translations`)\n if (!translationTable) return result\n\n const translations = await ctx.db\n .select()\n .from(translationTable)\n .where(inArray(translationTable.entityId, entityIds))\n\n // Group: entityId → locale → { fieldName: value }\n const translationsByEntity = new Map<string, Map<string, Record<string, unknown>>>()\n for (const t of translations) {\n const row = t as Record<string, unknown>\n const eid = row.entityId as string\n const locale = row.locale as string\n const fieldValues: Record<string, unknown> = {}\n for (const fieldName of translatableFields) {\n fieldValues[fieldName] = row[fieldName]\n }\n let entry = translationsByEntity.get(eid)\n if (!entry) {\n entry = new Map()\n translationsByEntity.set(eid, entry)\n }\n entry.set(locale, fieldValues)\n }\n\n for (const entityId of entityIds) {\n result.set(\n entityId,\n computeStatusForEntity(\n translatableFields,\n translationsByEntity.get(entityId),\n config.locales,\n config.defaultLocale,\n ),\n )\n }\n\n return result\n}\n\n/**\n * Roll up translation status across every entity of this type.\n *\n * Defaults to the first non-default configured locale; pass\n * `options.locale` to target a specific one. Returns counts of\n * complete / partial / missing entities for that locale.\n */\nexport async function getTranslationReport(\n ctx: ContentContext,\n options?: { locale?: string },\n): Promise<TranslationReport> {\n const config = getContentConfig()\n const targetLocale =\n options?.locale ?? config.locales.find((l) => l.code !== config.defaultLocale)?.code\n if (!targetLocale) return { total: 0, complete: 0, partial: 0, missing: 0 }\n\n const entities = await ctx.admin.findMany()\n if (entities.length === 0) return { total: 0, complete: 0, partial: 0, missing: 0 }\n\n // Single batched query covers every entity at once.\n const statusMap = await getTranslationStatusBatch(\n ctx,\n entities.map((e) => e.id),\n )\n\n let complete = 0\n let partial = 0\n let missing = 0\n for (const entity of entities) {\n const status = statusMap.get(entity.id)\n const localeStatus = status?.[targetLocale]\n if (!localeStatus || localeStatus.translated === 0) missing++\n else if (localeStatus.complete) complete++\n else partial++\n }\n\n return { total: entities.length, complete, partial, missing }\n}\n","/**\n * ContentClient — thin shell over per-feature modules.\n *\n * Wraps AdminClient with version history (`./versions.ts`), draft\n * overlays (`./drafts.ts`), translation status reporting\n * (`./translation-status.ts`), per-locale publish status\n * (`./locale-status.ts`), and block-layout operations (`./layout.ts`).\n *\n * The class is generic over the entity's `AllFields` map: when\n * constructed with a typed entity, every method's input/output is\n * inferred end-to-end. When constructed with a runtime `Entity`\n * (admin-ui's heterogeneous entity loops), the generic defaults to\n * `Record<string, FieldConfig>` and methods accept/return the loose\n * shape — same behavior as the pre-generic version.\n *\n * Usage:\n * import { createContentClient } from '@murumets-ee/content/client'\n * const pages = createContentClient(Page)\n * await pages.create({ title: 'Hello', layout: [...] })\n */\n\nimport 'server-only'\n\nimport { getApp, type Logger } from '@murumets-ee/core'\nimport { createAdminClient } from '@murumets-ee/core/clients'\nimport type { Entity, FieldConfig } from '@murumets-ee/entity'\nimport type {\n AdminClient,\n FindManyOptions,\n InferCreateInput,\n InferEntityDTO,\n InferUpdateInput,\n} from '@murumets-ee/entity/admin'\nimport { getVersionableOptions } from './behaviors/versionable.js'\nimport {\n compareDraftWithCurrent,\n countDrafts,\n deleteDraft,\n getDraft,\n hasDraft,\n hasDraftBatch,\n mergeDraft,\n publishDraft,\n saveDraft,\n} from './drafts.js'\nimport { type ContentContext, createContentContext } from './internal/context.js'\nimport { calculateDelta } from './internal/projection.js'\nimport { getLocaleStatus, getLocaleStatusBatch, setLocaleStatus } from './locale-status.js'\nimport {\n getTranslationReport,\n getTranslationStatus,\n getTranslationStatusBatch,\n} from './translation-status.js'\nimport {\n compareVersions,\n createVersionSnapshot,\n getVersion,\n getVersions,\n pruneVersions,\n restoreVersion,\n saveVersionSnapshot,\n writeVersionColumn,\n} from './versions.js'\n\nexport interface ContentClientConfig<\n AllFields extends Record<string, FieldConfig> = Record<string, FieldConfig>,\n> {\n admin: AdminClient<AllFields>\n entity: Entity<AllFields>\n logger?: Logger\n}\n\nexport class ContentClient<\n AllFields extends Record<string, FieldConfig> = Record<string, FieldConfig>,\n> {\n private ctx: ContentContext<AllFields>\n\n constructor(config: ContentClientConfig<AllFields>) {\n const versionableOptions = getVersionableOptions(config.entity.behaviors)\n this.ctx = createContentContext(config, versionableOptions)\n }\n\n // -----------------------------------------------------------------\n // CRUD (delegated to AdminClient + version snapshots)\n // -----------------------------------------------------------------\n\n async create(data: InferCreateInput<AllFields>): Promise<InferEntityDTO<AllFields>> {\n const result = await this.ctx.admin.create(data)\n if (this.ctx.versionableOptions) {\n await saveVersionSnapshot(this.ctx, result.id, result, null, false)\n }\n return result\n }\n\n findById(id: string, options?: { locale?: string }): Promise<InferEntityDTO<AllFields> | null> {\n return this.ctx.admin.findById(id, options)\n }\n\n findMany(options?: FindManyOptions): Promise<InferEntityDTO<AllFields>[]> {\n return this.ctx.admin.findMany(options)\n }\n\n /**\n * Base-row update + version snapshot. Subject to AdminClient's\n * cross-locale write guard (SD021): under a non-default request-context\n * locale, translatable fields throw `CrossLocaleWriteError` — that's\n * enforcement, not a gap. Locale-belonging writes go through the draft\n * flow (`saveDraft` → `publishDraft`) or `admin.updateForLocale` directly.\n */\n async update(id: string, data: InferUpdateInput<AllFields>): Promise<InferEntityDTO<AllFields>> {\n let previousState: InferEntityDTO<AllFields> | null = null\n if (this.ctx.versionableOptions) {\n previousState = await this.ctx.admin.findById(id)\n }\n\n const result = await this.ctx.admin.update(id, data)\n\n if (this.ctx.versionableOptions && previousState) {\n const delta = calculateDelta(previousState, result)\n const version = await saveVersionSnapshot(this.ctx, id, result, delta, false)\n if (version !== undefined) {\n await writeVersionColumn(this.ctx, id, version)\n await pruneVersions(this.ctx, id)\n return { ...result, _version: version } as InferEntityDTO<AllFields>\n }\n await pruneVersions(this.ctx, id)\n }\n\n return result\n }\n\n delete(id: string): Promise<unknown> {\n return this.ctx.admin.delete(id)\n }\n\n // -----------------------------------------------------------------\n // Translation delegation\n // -----------------------------------------------------------------\n\n saveTranslation(entityId: string, locale: string, translations: Record<string, unknown>) {\n return this.ctx.admin.saveTranslation(entityId, locale, translations)\n }\n\n deleteTranslation(entityId: string, locale?: string) {\n return this.ctx.admin.deleteTranslation(entityId, locale)\n }\n\n // -----------------------------------------------------------------\n // Version history\n // -----------------------------------------------------------------\n\n getVersions(entityId: string, options?: { limit?: number; offset?: number; locale?: string }) {\n return getVersions(this.ctx, entityId, options)\n }\n\n getVersion(entityId: string, version: number, locale?: string) {\n return getVersion(this.ctx, entityId, version, locale)\n }\n\n compareVersions(entityId: string, v1: number, v2: number, locale?: string) {\n return compareVersions(this.ctx, entityId, v1, v2, locale)\n }\n\n restoreVersion(entityId: string, version: number, locale?: string) {\n return restoreVersion(this.ctx, entityId, version, locale)\n }\n\n pruneVersions(entityId: string, locale?: string) {\n return pruneVersions(this.ctx, entityId, locale)\n }\n\n createVersionSnapshot(\n entityId: string,\n currentData: Record<string, unknown>,\n previousData?: Record<string, unknown> | null,\n locale?: string,\n user?: { id: string; name?: string },\n ) {\n return createVersionSnapshot(this.ctx, entityId, currentData, previousData, locale, user)\n }\n\n // -----------------------------------------------------------------\n // Translation status\n // -----------------------------------------------------------------\n\n getTranslationStatus(entityId: string) {\n return getTranslationStatus(this.ctx, entityId)\n }\n\n getTranslationStatusBatch(entityIds: string[]) {\n return getTranslationStatusBatch(this.ctx, entityIds)\n }\n\n getTranslationReport(options?: { locale?: string }) {\n return getTranslationReport(this.ctx, options)\n }\n\n // -----------------------------------------------------------------\n // Per-locale publish status\n // -----------------------------------------------------------------\n\n getLocaleStatus(entityId: string) {\n return getLocaleStatus(this.ctx, entityId)\n }\n\n setLocaleStatus(entityId: string, locale: string, status: 'draft' | 'published') {\n return setLocaleStatus(this.ctx, entityId, locale, status)\n }\n\n getLocaleStatusBatch(entityIds: string[]) {\n return getLocaleStatusBatch(this.ctx, entityIds)\n }\n\n // -----------------------------------------------------------------\n // Drafts\n // -----------------------------------------------------------------\n\n saveDraft(\n entityId: string,\n data: InferUpdateInput<AllFields>,\n locale?: string,\n user?: { id: string; name?: string },\n ) {\n return saveDraft(this.ctx, entityId, data, locale, user)\n }\n\n mergeDraft(\n entityId: string,\n patch: InferUpdateInput<AllFields>,\n locale?: string,\n user?: { id: string; name?: string },\n ) {\n return mergeDraft(this.ctx, entityId, patch, locale, user)\n }\n\n getDraft(entityId: string, locale?: string) {\n return getDraft(this.ctx, entityId, locale)\n }\n\n deleteDraft(entityId: string, locale?: string) {\n return deleteDraft(this.ctx, entityId, locale)\n }\n\n publishDraft(entityId: string, locale?: string, user?: { id: string; name?: string }) {\n return publishDraft(this.ctx, entityId, locale, user)\n }\n\n hasDraft(entityId: string, locale?: string) {\n return hasDraft(this.ctx, entityId, locale)\n }\n\n countDrafts(locale?: string) {\n return countDrafts(this.ctx, locale)\n }\n\n hasDraftBatch(entityIds: string[], locale?: string) {\n return hasDraftBatch(this.ctx, entityIds, locale)\n }\n\n compareDraftWithCurrent(entityId: string, locale?: string) {\n return compareDraftWithCurrent(this.ctx, entityId, locale)\n }\n}\n\n/**\n * Factory — creates a ContentClient for an entity. Must be called\n * after `createApp()`. Generic flows from the entity definition:\n * `createContentClient(Article)` returns a `ContentClient<typeof\n * Article['allFields']>` typed end-to-end.\n */\nexport function createContentClient<AllFields extends Record<string, FieldConfig>>(\n entity: Entity<AllFields>,\n): ContentClient<AllFields> {\n const admin = createAdminClient(entity)\n return new ContentClient<AllFields>({\n admin,\n entity,\n logger: getApp().logger.child({ content: entity.name }),\n })\n}\n"],"mappings":"orBA+BA,SAAS,EAAa,EAA2B,CAC/C,MAAO,CACL,GAAI,EAAI,GACR,SAAU,EAAI,SACd,OAAQ,EAAI,OACZ,KAAM,EAAI,KACV,UAAW,EAAI,UACf,cAAe,EAAI,eAAiB,KACpC,UAAW,EAAI,UACf,UAAW,EAAI,SACjB,CACF,CAiBA,eAAsB,EACpB,EACA,EACA,EACA,EAAA,IACA,EAC0C,CAC1C,EAAe,CAAM,EACrB,IAAM,EAAS,EAAgB,CAAG,EAClC,GAAI,CAAC,EAAQ,MAAM,IAAI,EAAsB,EAAI,OAAO,KAAM,QAAQ,EAEtE,IAAM,EAAY,EAAsB,EAAI,OAAQ,CAA+B,EASnF,EAAI,MAAM,sBAAsB,CAAS,EAezC,IAAM,EAHoB,EAAkB,EAAI,MAAM,CAAC,CAAC,MAAM,CAAE,UAC9D,OAAO,OAAO,EAAW,CAAI,CAEE,EAAI,MAAM,EAAO,QAAQ,CAAE,WAAU,QAAO,CAAC,EAAI,KAClF,MAAM,EAAI,MAAM,sBACd,EACA,GAAU,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AAiB,CAC3B,OAAO,EAAY,KAAK,IAAK,CAAM,CACrC,CAEA,cAAc,EAAqB,EAAiB,CAClD,OAAO,EAAc,KAAK,IAAK,EAAW,CAAM,CAClD,CAEA,wBAAwB,EAAkB,EAAiB,CACzD,OAAO,EAAwB,KAAK,IAAK,EAAU,CAAM,CAC3D,CACF,EAQA,SAAgB,EACd,EAC0B,CAE1B,OAAO,IAAI,EAAyB,CAClC,MAFY,EAAkB,CAE1B,EACJ,SACA,OAAQ,EAAO,CAAC,CAAC,OAAO,MAAM,CAAE,QAAS,EAAO,IAAK,CAAC,CACxD,CAAC,CACH"}
1
+ {"version":3,"file":"client.mjs","names":[],"sources":["../src/drafts.ts","../src/locale-status.ts","../src/translation-status.ts","../src/client.ts"],"sourcesContent":["/**\n * Draft-overlay operations.\n *\n * Capability: requires the entity to declare `publishable()`. Reads\n * (`getDraft`, `hasDraft`, `countDrafts`, `hasDraftBatch`) silently\n * return falsy when the entity doesn't support drafts; writes\n * (`saveDraft`, `mergeDraft`, `publishDraft`) throw `EntityCapabilityError`.\n */\n\nimport 'server-only'\n\nimport { blockTreeFieldsOf, type FieldConfig } from '@murumets-ee/entity'\nimport type { InferEntityDTO, InferUpdateInput } from '@murumets-ee/entity/admin'\nimport { diffBlocks } from './diff/block-diff.js'\nimport { diffFields } from './diff/field-diff.js'\nimport type { FieldDiff } from './diff/types.js'\nimport { DraftNotFoundError, EntityCapabilityError } from './errors.js'\nimport {\n applyLocaleRoutedUpdate,\n localeFindOptions,\n} from './internal/apply-locale-routed-update.js'\nimport { type ContentContext, getDraftsClient } from './internal/context.js'\nimport { projectToEntityFields } from './internal/projection.js'\nimport { DEFAULT_LOCALE_SENTINEL, validateLocale } from './locale-utils.js'\nimport { getContentConfig } from './plugin.js'\nimport type { DraftsTable } from './schema/drafts.js'\nimport type { DraftEntry } from './types.js'\nimport { createVersionSnapshot } from './versions.js'\n\ntype DraftRow = NonNullable<Awaited<ReturnType<ReturnType<DraftsTable['makeClient']>['findOne']>>>\n\nfunction toDraftEntry(row: DraftRow): DraftEntry {\n return {\n id: row.id,\n entityId: row.entityId,\n locale: row.locale,\n data: row.data,\n createdBy: row.createdBy,\n createdByName: row.createdByName ?? null,\n createdAt: row.createdAt,\n updatedAt: row.updatedAt,\n }\n}\n\n/**\n * Save (upsert) a draft for an entity+locale. One draft per\n * entity+locale — overwrites any existing draft.\n *\n * `data` is projected through the entity's declared field whitelist\n * BEFORE it is stored (same `projectToEntityFields` call `publishDraft`\n * makes on the way out). Storing the caller's JSON verbatim let a draft\n * carry keys the entity never declared, identity/audit columns and\n * `internal: true` fields; publishing filtered them, but `getDraft` and\n * `compareDraftWithCurrent` echoed them straight back to the admin UI,\n * and the drafts table accumulated arbitrary caller-controlled JSON\n * (`plan/admin-api-hardening` F002). Validating at the write closes the\n * asymmetry — the stored draft is now always a subset of what the entity\n * can actually hold.\n */\nexport async function saveDraft<F extends Record<string, FieldConfig>>(\n ctx: ContentContext<F>,\n entityId: string,\n data: InferUpdateInput<F>,\n locale = DEFAULT_LOCALE_SENTINEL,\n user?: { id: string; name?: string },\n): Promise<DraftEntry<InferUpdateInput<F>>> {\n validateLocale(locale)\n const client = await getDraftsClient(ctx)\n if (!client) throw new EntityCapabilityError(ctx.entity.name, 'drafts')\n\n const projected = projectToEntityFields(ctx.entity, data as Record<string, unknown>)\n\n // `projectToEntityFields` is a field-NAME whitelist — it never inspects a\n // value, so a `field.blockTree()` column in a draft took arbitrary JSON, and\n // `editor-state` hands the stored draft back as the CANVAS BASE STATE\n // (editor F002). Publishing is already gated by the entity write path, but\n // waiting until publish means the editor loads a tree it cannot represent.\n // Same validator, same judgement — asked here because the draft blob carries\n // no Zod schema of its own.\n ctx.admin.assertBlockTreesValid(projected)\n // F116, same reasoning — and this is precisely the write path the finding\n // was filed against: dava's home-page DRAFT already holds a mismatched\n // media reference. Grandfathering against the draft ALREADY STORED (rather\n // than validating strictly) is what keeps that draft's next autosave\n // working instead of turning \"a broken image\" into \"a draft that can never\n // be saved again\".\n //\n // The lookup is skipped entirely when the PROJECTED payload carries no\n // block-tree field at all — `assertMediaKindsValid` would no-op anyway\n // (same optimization as `saveTranslation`'s), and most entities with\n // drafts have no block-tree field to begin with.\n const hasBlockTreeValue = blockTreeFieldsOf(ctx.entity).some(({ name }) =>\n Object.hasOwn(projected, name),\n )\n const existing = hasBlockTreeValue ? await client.findOne({ entityId, locale }) : null\n await ctx.admin.assertMediaKindsValid(\n projected,\n existing?.data as Record<string, unknown> | undefined,\n )\n\n const now = new Date()\n const createdBy = user?.id ?? ''\n const createdByName = user?.name ?? null\n\n const row = await client.upsert(\n {\n entityId,\n locale,\n data: projected,\n createdBy,\n createdByName,\n createdAt: now,\n updatedAt: now,\n },\n {\n target: ['entityId', 'locale'],\n // On conflict, only update the mutable fields — preserve createdBy/createdAt.\n set: { data: projected, updatedAt: now },\n },\n )\n\n return toDraftEntry(row) as DraftEntry<InferUpdateInput<F>>\n}\n\n/**\n * The keys that move a document's canonical URL in the patterns the toolkit\n * ships (`[slug]`, `[parent.path]`) plus the slug mode that decides whether a\n * clash is refused or auto-suffixed. A merge naming one of them, on a ROUTABLE\n * entity, runs the path-conflict check (see `mergeDraft`); any other merge\n * skips its lookups — the staged draft, the row, and `toolkit_paths` (twice\n * under a parent).\n *\n * A pattern built from another field (`/[category]/[slug]`) is not covered:\n * staging only `category` is refused at Publish rather than here.\n */\nconst PATH_KEYS = ['slug', 'slugMode', 'parent'] as const\n\n/**\n * Stage a PARTIAL change: merge `patch` into the entity+locale draft, creating\n * the draft if there is none. Keys not in `patch` are left exactly as the draft\n * (or, absent a draft key, the live row) has them.\n *\n * This is the write every editing surface uses since editor D019 — \"every edit\n * on every surface saves to the document's one shared draft\". `saveDraft`\n * REPLACES the blob, which is right for a surface that owns the whole document\n * (the menu editor) and wrong for one that owns a few fields of it: page\n * settings saving `title` through `saveDraft` would erase the block edits the\n * canvas staged a second earlier. A draft is therefore a patch over the row, and\n * every reader that shows editable values reads row ⊕ draft.\n *\n * Judged like the entity PATCH it replaces, BEFORE it is stored:\n * - projected through the field whitelist (`internal`, undeclared keys dropped)\n * - `assertBlockTreesValid` + `assertMediaKindsValid` (grandfathered against the\n * stored draft, same as `saveDraft`)\n * - `assertUpdateValid` — the entity's own update schema. `saveDraft` never ran\n * it, which was harmless while the form's Publish still PATCHed; moving a\n * surface into the draft must not move its refusal to Publish, where the\n * author is no longer looking at the field.\n * - `assertPathAvailable` — the path-conflict guard, as a dry run, when the\n * merge moves the URL (see {@link PATH_KEYS}) on a routable entity (F150).\n *\n * 🔴 ONE STATEMENT, not read-modify-write. The merge is `data || patch` inside\n * `ON CONFLICT DO UPDATE` (`TableClient.upsert`'s `mergeJsonb`), so it cannot\n * lose a concurrent write: a read-then-upsert that interleaved with op-commit's\n * or a bound field's stage would write back the draft as it was read — silently\n * reverting the other writer's change. `writeDraft` merges the same way, so\n * neither can erase the other. Top-level `||`, a SHALLOW merge.\n *\n * Resolves `null` when the projected patch is EMPTY and no draft exists: nothing\n * the entity declares was sent, so nothing is staged and no empty draft row is\n * created.\n *\n * ⚠️ The rest of the write path's hooks — `pathParent()`'s cycle check, the\n * partial-unique slug index, `sluggable()`'s regeneration — still run only at\n * Publish, inside its transaction, where a refusal stops the whole publish. The\n * path check here answers \"as of now\"; Publish runs the real guard again.\n */\nexport async function mergeDraft<F extends Record<string, FieldConfig>>(\n ctx: ContentContext<F>,\n entityId: string,\n patch: InferUpdateInput<F>,\n locale = DEFAULT_LOCALE_SENTINEL,\n user?: { id: string; name?: string },\n): Promise<DraftEntry<InferUpdateInput<F>> | null> {\n validateLocale(locale)\n const client = await getDraftsClient(ctx)\n if (!client) throw new EntityCapabilityError(ctx.entity.name, 'drafts')\n\n const projected = projectToEntityFields(ctx.entity, patch as Record<string, unknown>)\n // Nothing the entity declares: stage nothing. Upserting `{}` would CREATE an\n // empty draft, and the document would then read \"Draft saved · not live\n // yet\" about a change that does not exist.\n if (Object.keys(projected).length === 0) {\n const current = await client.findOne({ entityId, locale })\n return current ? (toDraftEntry(current) as DraftEntry<InferUpdateInput<F>>) : null\n }\n ctx.admin.assertBlockTreesValid(projected)\n ctx.admin.assertUpdateValid(projected)\n const hasBlockTreeValue = blockTreeFieldsOf(ctx.entity).some(({ name }) =>\n Object.hasOwn(projected, name),\n )\n const touchesPath =\n ctx.entity.frontend?.path !== undefined &&\n PATH_KEYS.some((key) => Object.hasOwn(projected, key))\n const existing =\n hasBlockTreeValue || touchesPath ? await client.findOne({ entityId, locale }) : null\n await ctx.admin.assertMediaKindsValid(\n projected,\n existing?.data as Record<string, unknown> | undefined,\n )\n // A staged slug that another document's URL already holds is refused NOW,\n // beside the field the author typed it in — not first at Publish (editor\n // PR60, F150). Checked against what the draft will hold after this merge,\n // since an earlier stage may have set `slugMode` or `parent`.\n if (touchesPath) {\n const staged = {\n ...((existing?.data as Record<string, unknown> | undefined) ?? {}),\n ...projected,\n }\n if (locale === DEFAULT_LOCALE_SENTINEL) {\n await ctx.admin.assertPathAvailable(entityId, staged)\n } else {\n // Checked the way Publish writes it: `updateForLocale` sends a locale's\n // TRANSLATABLE fields through that locale's guard and the rest (a\n // `parent`, a non-translatable slug) through `update()`, whose guard\n // checks the default locale. One guard over everything would test a\n // shared `parent` against the wrong locale's URLs.\n const fields = ctx.entity.allFields as Record<string, { translatable?: boolean } | undefined>\n const translatable: Record<string, unknown> = {}\n const shared: Record<string, unknown> = {}\n for (const [key, value] of Object.entries(staged)) {\n if (fields[key]?.translatable === true) translatable[key] = value\n else shared[key] = value\n }\n const moves = (part: Record<string, unknown>) =>\n PATH_KEYS.some((key) => Object.hasOwn(part, key) && Object.hasOwn(projected, key))\n if (moves(translatable)) await ctx.admin.assertPathAvailable(entityId, translatable, locale)\n if (moves(shared)) await ctx.admin.assertPathAvailable(entityId, shared)\n }\n }\n\n const now = new Date()\n const row = await client.upsert(\n {\n entityId,\n locale,\n data: projected,\n createdBy: user?.id ?? '',\n createdByName: user?.name ?? null,\n createdAt: now,\n updatedAt: now,\n },\n { target: ['entityId', 'locale'], set: { updatedAt: now }, mergeJsonb: ['data'] },\n )\n return toDraftEntry(row) as DraftEntry<InferUpdateInput<F>>\n}\n\n/**\n * Get the draft for an entity+locale, or null if none exists (or the\n * entity doesn't support drafts).\n */\nexport async function getDraft<F extends Record<string, FieldConfig>>(\n ctx: ContentContext<F>,\n entityId: string,\n locale = DEFAULT_LOCALE_SENTINEL,\n): Promise<DraftEntry<InferUpdateInput<F>> | null> {\n validateLocale(locale)\n const client = await getDraftsClient(ctx)\n if (!client) return null\n const row = await client.findOne({ entityId, locale })\n return row ? (toDraftEntry(row) as DraftEntry<InferUpdateInput<F>>) : null\n}\n\n/**\n * Delete (discard) a draft for an entity+locale. Returns whether\n * anything was deleted; safely no-ops on entities without drafts.\n */\nexport async function deleteDraft(\n ctx: ContentContext,\n entityId: string,\n locale = DEFAULT_LOCALE_SENTINEL,\n): Promise<boolean> {\n validateLocale(locale)\n const client = await getDraftsClient(ctx)\n if (!client) return false\n const deleted = await client.deleteMany({ entityId, locale })\n return deleted.length > 0\n}\n\n/**\n * Publish a draft: make THIS document's staged changes live.\n *\n * \"Publish\" means one thing on every surface (editor D019): the draft's fields\n * are written to the row for the draft's locale AND the row is put live. The\n * draft is then gone and, if versionable, a version snapshot records what went\n * live.\n *\n * Locale routing mirrors the admin PATCH handler (and the taxonomy fix\n * in 10a7cc2b): a default-locale draft writes the base row; a\n * non-default-locale draft routes translatable fields to\n * `saveTranslation` (→ `{entity}_translations`), `status` to the\n * per-locale status table, and only non-translatable fields (which have\n * no per-locale home) to the base row. Without this split, publishing\n * an `et` draft overwrote the default-locale base row wholesale.\n *\n * ## ONE TRANSACTION (editor PR60, R055 §4)\n *\n * The row write, the locale status, `_overrides`, the draft delete and the\n * version snapshot commit together or not at all. They used to be five separate\n * statements, so a failure part-way left a document whose content was live and\n * whose draft still claimed to be pending — or, worse, whose draft was gone while\n * the row write had not landed.\n *\n * The draft is CLAIMED first, by deleting it and publishing what the delete\n * returned. The delete takes the row lock, so an op-commit that is mid-flight on\n * the same draft either committed before (and its edit is in what we publish) or\n * blocks until we commit and then retries its SERIALIZABLE transaction — or, if it\n * had not read the draft yet, inserts a fresh draft holding only its own patch.\n * Either way it does not write a stale copy back over the published one. The editor also flushes and awaits its own in-flight saves\n * before it calls this, so the lock is the backstop, not the mechanism.\n *\n * Path-index and write notifications fire after COMMIT, not inside it —\n * `AdminClient.afterCommit` defers them on a tracked transaction.\n */\nexport async function publishDraft<F extends Record<string, FieldConfig>>(\n ctx: ContentContext<F>,\n entityId: string,\n locale = DEFAULT_LOCALE_SENTINEL,\n user?: { id: string; name?: string },\n): Promise<InferEntityDTO<F>> {\n validateLocale(locale)\n if (!(await getDraftsClient(ctx))) {\n throw new EntityCapabilityError(ctx.entity.name, 'drafts')\n }\n\n // Previous state for the version delta — locale-merged, so the delta compares\n // against what this locale's readers actually saw. Read BEFORE the\n // transaction: it is the committed state the publish replaces.\n const previousState: InferEntityDTO<F> | null = ctx.versionableOptions\n ? await ctx.admin.findById(entityId, localeFindOptions(locale))\n : null\n\n return ctx.db.transaction(async (tx) => {\n // Every table client below binds to `tx` through this context — drafts,\n // locale status, versions and the `_version` column write.\n const txCtx: ContentContext<F> = { ...ctx, db: tx }\n const draftsClient = await getDraftsClient(txCtx)\n if (!draftsClient) throw new EntityCapabilityError(ctx.entity.name, 'drafts')\n const [claimed] = await draftsClient.deleteMany({ entityId, locale })\n if (!claimed) {\n throw new DraftNotFoundError(entityId, locale)\n }\n\n // `?? {}` because the column is `jsonb NOT NULL`, and that forbids SQL NULL\n // while permitting the JSON literal `null` — which deserializes to JS `null`.\n // A bare cast then made `draftData.status` a TypeError, so a malformed row\n // 500'd the publish route instead of taking the ordinary \"nothing declared,\n // publish the row as-is\" path below. Nothing in this package writes such a\n // row; a seed, a migration or a hand-edit can.\n const claimedData = (claimed.data ?? {}) as Record<string, unknown>\n // `publishedAt` is Publish's to set, like `status` below: a staged value\n // would let whoever wrote the draft back- or forward-date the publication.\n // publishable()'s hook fills it when the UPDATE carries none — which, with\n // the staged value dropped, is every publish: it records the LATEST\n // publication, not the first.\n const { publishedAt: _stagedPublishedAt, ...draftData } = claimedData\n // \"Publish\" means MAKE LIVE, always — the status is not the draft's to\n // decide. Block-editor drafts carry no `status` at all, and before D019 a\n // form-saved draft could carry `status: 'draft'`, which then won: Publish\n // wrote the content and left the document unpublished, so the same button\n // meant \"publish\" on one surface and \"stage\" on another. The publishable()\n // behavior auto-sets `publishedAt` on the transition. The publish-permission\n // gate lives in the admin route, not here.\n const updateData = projectToEntityFields(ctx.entity, { ...draftData, status: 'published' })\n const result = await applyLocaleRoutedUpdate(txCtx, entityId, updateData, locale, tx)\n\n // F009 — promote the page's chrome overrides.\n //\n // `projectToEntityFields` drops every `internal: true` field, deliberately, so\n // `_overrides` cannot ride the generic promotion. That guard is NOT relaxed:\n // this is one named field, written through the trusted `updateInternal` path\n // that `with-overrides.ts` documents as \"the only path that can mutate it\".\n // Before F009 that call site did not exist, so an override survived in the\n // draft buffer and never reached the column — the op committed, the canvas\n // updated, and a reload brought the hidden header back.\n //\n // AFTER the main update, so the override never lands against content that\n // failed to — and inside the same transaction, so neither lands alone.\n // `_overrides` is not translatable, so it belongs on the base row for every\n // locale.\n const overrides = readOverridesForPublish(ctx.entity, draftData)\n if (overrides !== undefined) {\n await ctx.admin.updateInternal(entityId, { _overrides: overrides }, { tx })\n }\n\n if (ctx.versionableOptions) {\n await createVersionSnapshot(txCtx, entityId, result, previousState, locale, user)\n }\n\n return result\n })\n}\n\n/**\n * The page's override map from a draft payload, when the entity declares the\n * field and the draft carries one.\n *\n * Returns `undefined` — never `{}` — so an ordinary content publish does not\n * touch the column. Shape-guarded because a draft payload is stored jsonb: an\n * array or a scalar is malformed data, not an override map. ← F009\n */\nfunction readOverridesForPublish(\n entity: { allFields: Record<string, unknown>; behaviors?: readonly { name: string }[] },\n draftData: Record<string, unknown>,\n): Record<string, unknown> | undefined {\n // The BEHAVIOR, not just a field with the right name — a draft payload is\n // stored jsonb and can be crafted or legacy, so this must not become a way\n // to promote arbitrary JSON into an unrelated internal field on an entity\n // that never opted in. Requiring the behavior also means `beforeUpdate` runs\n // `validateOverridesMap` on the way through `updateInternal`.\n if (!(entity.behaviors ?? []).some((b) => b.name === 'withOverrides')) return undefined\n const field = entity.allFields._overrides as { internal?: boolean } | undefined\n if (field === undefined || field.internal !== true) return undefined\n const value = draftData._overrides\n if (typeof value !== 'object' || value === null || Array.isArray(value)) return undefined\n return value as Record<string, unknown>\n}\n\n/**\n * Quick existence check for list badges — does a draft exist?\n */\nexport async function hasDraft(\n ctx: ContentContext,\n entityId: string,\n locale = DEFAULT_LOCALE_SENTINEL,\n): Promise<boolean> {\n validateLocale(locale)\n const client = await getDraftsClient(ctx)\n if (!client) return false\n return client.exists({ entityId, locale })\n}\n\n/**\n * Count drafts for this entity type, optionally filtered by locale.\n * Single indexed COUNT — used by dashboard widgets.\n */\nexport async function countDrafts(\n ctx: ContentContext,\n locale = DEFAULT_LOCALE_SENTINEL,\n): Promise<number> {\n validateLocale(locale)\n const client = await getDraftsClient(ctx)\n if (!client) return 0\n return client.count({ locale })\n}\n\n/**\n * Check draft existence for multiple entities in one query. Returns\n * a set of entity IDs that have a draft for `locale`.\n */\nexport async function hasDraftBatch(\n ctx: ContentContext,\n entityIds: string[],\n locale = DEFAULT_LOCALE_SENTINEL,\n): Promise<Set<string>> {\n validateLocale(locale)\n const result = new Set<string>()\n if (entityIds.length === 0) return result\n const client = await getDraftsClient(ctx)\n if (!client) return result\n\n const rows = await client.findMany({\n where: { entityId: { in: entityIds }, locale },\n })\n for (const row of rows) {\n result.add(row.entityId as string)\n }\n return result\n}\n\n/**\n * Compare the current draft with the live entity. Returns field-level\n * diffs between the published data and the draft (only for fields\n * present in the draft — missing fields are NOT \"changed to empty\").\n */\nexport async function compareDraftWithCurrent<F extends Record<string, FieldConfig>>(\n ctx: ContentContext<F>,\n entityId: string,\n locale = DEFAULT_LOCALE_SENTINEL,\n): Promise<{\n diffs: FieldDiff[]\n current: InferEntityDTO<F>\n draft: DraftEntry<InferUpdateInput<F>>\n} | null> {\n validateLocale(locale)\n const draft = await getDraft(ctx, entityId, locale)\n if (!draft) return null\n\n // Fetch the live entity with the same locale context as the draft.\n const config = getContentConfig()\n const defaultLocale = config.defaultLocale\n const findOptions =\n locale === DEFAULT_LOCALE_SENTINEL ? { defaultLocale } : { locale, defaultLocale }\n const current = await ctx.admin.findById(entityId, findOptions)\n if (!current) return null\n\n const fieldConfigs = ctx.entity.allFields as Record<string, FieldConfig> | undefined\n const currentRecord = current as Record<string, unknown>\n const draftRecord = draft.data as Record<string, unknown>\n const currentSubset: Record<string, unknown> = {}\n for (const key of Object.keys(draftRecord)) {\n currentSubset[key] = currentRecord[key]\n }\n const diffs = diffFields(currentSubset, draftRecord, fieldConfigs)\n for (const diff of diffs) {\n if (diff.type === 'blockTree') {\n // Normalize a null/undefined side to [] so add/clear of the whole field\n // (null ↔ blockTree[]) still produces a structural diff, not an opaque one.\n diff.blockDiffs = diffBlocks(\n Array.isArray(diff.from) ? diff.from : [],\n Array.isArray(diff.to) ? diff.to : [],\n )\n }\n }\n\n return { diffs, current, draft }\n}\n","/**\n * Per-locale publish status — independent draft/published state for\n * each locale of a publishable + translatable entity.\n *\n * Capability: requires `publishable() + at least one translatable\n * field` (the `_locale_status` table is registered only for that\n * combination). Reads silently return falsy on entities without it;\n * `setLocaleStatus` throws `EntityCapabilityError`.\n */\n\nimport 'server-only'\n\nimport type { FieldConfig } from '@murumets-ee/entity'\nimport type { InferUpdateInput } from '@murumets-ee/entity/admin'\nimport { EntityCapabilityError } from './errors.js'\nimport { type ContentContext, getLocaleStatusClient } from './internal/context.js'\nimport { upsertLocaleStatusRow } from './locale-status-slot.js'\nimport { validateLocale } from './locale-utils.js'\nimport { getContentConfig } from './plugin.js'\nimport type { LocalePublishStatus } from './types.js'\n\n/**\n * Get per-locale publish status overrides for an entity.\n * Missing locale = inherits the base entity status (no row written).\n *\n * **Not permission-gated, deliberately — see {@link getLocaleStatusBatch}.**\n */\nexport async function getLocaleStatus(\n ctx: ContentContext,\n entityId: string,\n): Promise<LocalePublishStatus[]> {\n const map = await getLocaleStatusBatch(ctx, [entityId])\n const entry = map.get(entityId)\n if (!entry) return []\n return Object.values(entry)\n}\n\n/**\n * Set per-locale publish status. Upserts into the locale_status\n * table — except when `locale === defaultLocale`, which updates the\n * base entity status column directly (the per-locale table only\n * stores overrides for non-default locales).\n *\n * **Both branches are publish-gated by the entity layer (D041).** The default\n * branch inherits it from `AdminClient.update`; the non-default branch routes\n * through `AdminClient.updateForLocale`, which asserts the SAME\n * `assertPublishAuthority` from the caller's payload before it hands the write\n * to the locale-status writer. This is deliberately a delegation and not a\n * second predicate in this package: `<entity>_locale_status` is the table the\n * public read predicate (`COALESCE(locale_status.status, main.status)`) resolves\n * against, so a direct `TableClient.upsert` here — which is what this function\n * used to do — is a fourth publish door, reachable from any plugin/route/job\n * holding a `ContentClient` (a PUBLIC subpath export) with no `publish` grant\n * ever consulted.\n */\nexport async function setLocaleStatus<F extends Record<string, FieldConfig>>(\n ctx: ContentContext<F>,\n entityId: string,\n locale: string,\n status: 'draft' | 'published',\n): Promise<void> {\n validateLocale(locale)\n const config = getContentConfig()\n\n // Default locale → update base entity status column.\n if (locale === config.defaultLocale) {\n const data: Record<string, unknown> = { status }\n if (status === 'published') data.publishedAt = new Date()\n await ctx.admin.update(entityId, data as InferUpdateInput<F>)\n return\n }\n\n const client = await getLocaleStatusClient(ctx)\n if (!client) {\n // Per-locale status only exists for publishable + translatable\n // entities. Calling on a non-translatable publishable (where the\n // only valid locale is the default) is a programmer error.\n // Checked BEFORE delegating: `updateForLocale` would otherwise fall back to\n // the base `status` column for a missing writer, silently publishing the\n // default locale instead of refusing.\n throw new EntityCapabilityError(ctx.entity.name, 'localeStatus')\n }\n\n // The writer we hand down is the RAW upsert, not this function — the\n // delegation terminates here rather than re-entering `updateForLocale`.\n //\n // Routing through `updateForLocale` rather than calling the upsert directly\n // is what closes the publish door: this branch used to write\n // `<entity>_locale_status` with no permission check at all, so any holder of\n // this public export could make a translation publicly live without\n // `publish`. `updateForLocale` asserts publish authority at the operation\n // entry (D041), so the gate is inherited rather than duplicated here.\n //\n // Widened through `Record<string, unknown>` for the same reason the\n // default-locale branch above does it: `InferUpdateInput<F>` is keyed on the\n // entity's own field map, which a generic `F` cannot be proven to overlap.\n const localeData: Record<string, unknown> = { status }\n await ctx.admin.updateForLocale(entityId, localeData as InferUpdateInput<F>, locale, {\n defaultLocale: config.defaultLocale,\n localeStatusWriter: (id, loc, s) => upsertLocaleStatusRow(client, id, loc, s),\n })\n}\n\n/**\n * Get per-locale publish status for multiple entities in one query.\n *\n * ## Why this read is NOT permission-gated (and what would gate it)\n *\n * It returns publish-state METADATA only — `{ locale, status, publishedAt }` —\n * never field data, so it is not a content-disclosure door the way the write\n * side above is a publish door. What it does expose is an existence oracle for\n * unpublished TRANSLATIONS: a principal without `view_unpublished` learns that\n * `et` is a draft, which `QueryClient` would have hidden. The correct predicate\n * is therefore `view_unpublished` (D017), NOT `publish`.\n *\n * A CodeRabbit pass proposed gating it on exactly that predicate. Deliberately\n * declined, on the strength of **F063**: `view_unpublished` governs `QueryClient`\n * reads — the PUBLIC delivery surface — and is not a disclosure boundary over\n * the admin API, where `AdminClient` shows editors their own drafts by design.\n * `ContentClient` is an in-process server-side API whose consumers are plugins,\n * routes and jobs on the admin side, so gating it here would extend the control\n * onto the surface F063 explicitly recommended NOT extending it to. The concrete\n * cost would be an editor lacking `view_unpublished` no longer able to see that\n * their OWN translation is still a draft.\n *\n * The asymmetry with the write side above is real, not convenient:\n * `setLocaleStatus` MINTS public visibility, so it is gated regardless of which\n * surface calls it. This read hands publish-state metadata to a caller who\n * already holds `view` on the row — they needed its id to ask.\n *\n * It is not applied here because the predicate (`mayViewUnpublishedEntity`) is\n * module-private to `@murumets-ee/entity` — re-deriving it in this package\n * would create exactly the second, drifting copy of a security predicate that\n * D041 exists to eliminate, and there is no read-path equivalent of\n * `updateForLocale` to delegate to. The one in-repo caller\n * (`admin-ui`'s versions route) is already gated by `checkPermission`. Closing\n * this properly means exporting the predicate from `@murumets-ee/entity` and\n * dropping non-`published` rows for principals without it — tracked as the\n * read-side sibling of F060.\n */\nexport async function getLocaleStatusBatch(\n ctx: ContentContext,\n entityIds: string[],\n): Promise<Map<string, Record<string, LocalePublishStatus>>> {\n const result = new Map<string, Record<string, LocalePublishStatus>>()\n if (entityIds.length === 0) return result\n const client = await getLocaleStatusClient(ctx)\n if (!client) return result\n\n const rows = await client.findMany({ where: { entityId: { in: entityIds } } })\n for (const r of rows) {\n const eid = r.entityId as string\n const locale = r.locale as string\n let entry = result.get(eid)\n if (!entry) {\n entry = {}\n result.set(eid, entry)\n }\n entry[locale] = {\n locale,\n status: r.status as 'draft' | 'published',\n publishedAt: (r.publishedAt as Date | null) ?? null,\n }\n }\n return result\n}\n","/**\n * Translation status reporting — per-locale completion of translatable\n * fields for one entity, batches of entities, or the whole entity type.\n *\n * Capability: requires the entity to have at least one translatable\n * field. All methods return falsy / empty when the entity has no\n * translatable fields (read-only and defensive).\n */\n\nimport 'server-only'\n\nimport { requireSiteFor } from '@murumets-ee/core'\nimport { schemaRegistry } from '@murumets-ee/db'\nimport { buildPartitionCondition, type FieldConfig } from '@murumets-ee/entity'\nimport { and, inArray } from 'drizzle-orm'\nimport type { ContentContext } from './internal/context.js'\nimport { getContentConfig } from './plugin.js'\nimport type { TranslationReport, TranslationStatus } from './types.js'\n\n/**\n * For one entity, compute per-locale completion status across every\n * translatable field. Default-locale rows are skipped.\n */\nfunction computeStatusForEntity(\n translatableFields: string[],\n translatedByLocale: Map<string, Record<string, unknown>> | undefined,\n locales: { code: string }[],\n defaultLocale: string,\n): TranslationStatus {\n const status: TranslationStatus = {}\n for (const locale of locales) {\n if (locale.code === defaultLocale) continue\n const translated = translatedByLocale?.get(locale.code) ?? {}\n const missing: string[] = []\n for (const fieldName of translatableFields) {\n if (translated[fieldName] === undefined || translated[fieldName] === null) {\n missing.push(fieldName)\n }\n }\n status[locale.code] = {\n complete: missing.length === 0,\n total: translatableFields.length,\n translated: translatableFields.length - missing.length,\n missing,\n }\n }\n return status\n}\n\n/**\n * Get translation status for an entity — per-locale completion report.\n */\nexport async function getTranslationStatus(\n ctx: ContentContext,\n entityId: string,\n): Promise<TranslationStatus> {\n // Single-entity is the batch path with one ID — keeps the two\n // codepaths from drifting.\n const map = await getTranslationStatusBatch(ctx, [entityId])\n return map.get(entityId) ?? {}\n}\n\n/**\n * Get translation status for multiple entities in a single query.\n * O(1) DB roundtrips regardless of `entityIds.length`.\n */\nexport async function getTranslationStatusBatch(\n ctx: ContentContext,\n entityIds: string[],\n): Promise<Map<string, TranslationStatus>> {\n const result = new Map<string, TranslationStatus>()\n if (entityIds.length === 0) return result\n\n const config = getContentConfig()\n\n const translatableFields = Object.entries(ctx.entity.allFields as Record<string, FieldConfig>)\n .filter(([_, f]) => f.translatable)\n .map(([name]) => name)\n if (translatableFields.length === 0) return result\n\n // Translation tables are generated in @murumets-ee/entity (with FK\n // refs); accessed via schemaRegistry + direct Drizzle here.\n const translationTable = schemaRegistry.get(`${ctx.entity.name}_translations`)\n if (!translationTable) return result\n\n // A site-bound entity's translation rows are confined to the request's\n // site (multisite D003): ids alone are no boundary — a caller holding\n // another site's id must learn nothing about its translations.\n const site = await requireSiteFor(ctx.entity)\n const byIds = inArray(translationTable.entityId, entityIds)\n const translations = await ctx.db\n .select()\n .from(translationTable)\n .where(\n site !== undefined\n ? and(byIds, buildPartitionCondition(translationTable, { site }, ctx.entity.name))\n : byIds,\n )\n\n // Group: entityId → locale → { fieldName: value }\n const translationsByEntity = new Map<string, Map<string, Record<string, unknown>>>()\n for (const t of translations) {\n const row = t as Record<string, unknown>\n const eid = row.entityId as string\n const locale = row.locale as string\n const fieldValues: Record<string, unknown> = {}\n for (const fieldName of translatableFields) {\n fieldValues[fieldName] = row[fieldName]\n }\n let entry = translationsByEntity.get(eid)\n if (!entry) {\n entry = new Map()\n translationsByEntity.set(eid, entry)\n }\n entry.set(locale, fieldValues)\n }\n\n for (const entityId of entityIds) {\n result.set(\n entityId,\n computeStatusForEntity(\n translatableFields,\n translationsByEntity.get(entityId),\n config.locales,\n config.defaultLocale,\n ),\n )\n }\n\n return result\n}\n\n/**\n * Roll up translation status across every entity of this type.\n *\n * Defaults to the first non-default configured locale; pass\n * `options.locale` to target a specific one. Returns counts of\n * complete / partial / missing entities for that locale.\n */\nexport async function getTranslationReport(\n ctx: ContentContext,\n options?: { locale?: string },\n): Promise<TranslationReport> {\n const config = getContentConfig()\n const targetLocale =\n options?.locale ?? config.locales.find((l) => l.code !== config.defaultLocale)?.code\n if (!targetLocale) return { total: 0, complete: 0, partial: 0, missing: 0 }\n\n const entities = await ctx.admin.findMany()\n if (entities.length === 0) return { total: 0, complete: 0, partial: 0, missing: 0 }\n\n // Single batched query covers every entity at once.\n const statusMap = await getTranslationStatusBatch(\n ctx,\n entities.map((e) => e.id),\n )\n\n let complete = 0\n let partial = 0\n let missing = 0\n for (const entity of entities) {\n const status = statusMap.get(entity.id)\n const localeStatus = status?.[targetLocale]\n if (!localeStatus || localeStatus.translated === 0) missing++\n else if (localeStatus.complete) complete++\n else partial++\n }\n\n return { total: entities.length, complete, partial, missing }\n}\n","/**\n * ContentClient — thin shell over per-feature modules.\n *\n * Wraps AdminClient with version history (`./versions.ts`), draft\n * overlays (`./drafts.ts`), translation status reporting\n * (`./translation-status.ts`), per-locale publish status\n * (`./locale-status.ts`), and block-layout operations (`./layout.ts`).\n *\n * The class is generic over the entity's `AllFields` map: when\n * constructed with a typed entity, every method's input/output is\n * inferred end-to-end. When constructed with a runtime `Entity`\n * (admin-ui's heterogeneous entity loops), the generic defaults to\n * `Record<string, FieldConfig>` and methods accept/return the loose\n * shape — same behavior as the pre-generic version.\n *\n * Usage:\n * import { createContentClient } from '@murumets-ee/content/client'\n * const pages = createContentClient(Page)\n * await pages.create({ title: 'Hello', layout: [...] })\n */\n\nimport 'server-only'\n\nimport { getApp, type Logger } from '@murumets-ee/core'\nimport { createAdminClient } from '@murumets-ee/core/clients'\nimport type { Entity, FieldConfig } from '@murumets-ee/entity'\nimport type {\n AdminClient,\n FindManyOptions,\n InferCreateInput,\n InferEntityDTO,\n InferUpdateInput,\n} from '@murumets-ee/entity/admin'\nimport { getVersionableOptions } from './behaviors/versionable.js'\nimport {\n compareDraftWithCurrent,\n countDrafts,\n deleteDraft,\n getDraft,\n hasDraft,\n hasDraftBatch,\n mergeDraft,\n publishDraft,\n saveDraft,\n} from './drafts.js'\nimport { type ContentContext, createContentContext } from './internal/context.js'\nimport { calculateDelta } from './internal/projection.js'\nimport { getLocaleStatus, getLocaleStatusBatch, setLocaleStatus } from './locale-status.js'\nimport {\n getTranslationReport,\n getTranslationStatus,\n getTranslationStatusBatch,\n} from './translation-status.js'\nimport {\n compareVersions,\n createVersionSnapshot,\n getVersion,\n getVersions,\n pruneVersions,\n restoreVersion,\n saveVersionSnapshot,\n writeVersionColumn,\n} from './versions.js'\n\nexport interface ContentClientConfig<\n AllFields extends Record<string, FieldConfig> = Record<string, FieldConfig>,\n> {\n admin: AdminClient<AllFields>\n entity: Entity<AllFields>\n logger?: Logger\n}\n\nexport class ContentClient<\n AllFields extends Record<string, FieldConfig> = Record<string, FieldConfig>,\n> {\n private ctx: ContentContext<AllFields>\n\n constructor(config: ContentClientConfig<AllFields>) {\n const versionableOptions = getVersionableOptions(config.entity.behaviors)\n this.ctx = createContentContext(config, versionableOptions)\n }\n\n // -----------------------------------------------------------------\n // CRUD (delegated to AdminClient + version snapshots)\n // -----------------------------------------------------------------\n\n async create(data: InferCreateInput<AllFields>): Promise<InferEntityDTO<AllFields>> {\n const result = await this.ctx.admin.create(data)\n if (this.ctx.versionableOptions) {\n await saveVersionSnapshot(this.ctx, result.id, result, null, false)\n }\n return result\n }\n\n findById(id: string, options?: { locale?: string }): Promise<InferEntityDTO<AllFields> | null> {\n return this.ctx.admin.findById(id, options)\n }\n\n findMany(options?: FindManyOptions): Promise<InferEntityDTO<AllFields>[]> {\n return this.ctx.admin.findMany(options)\n }\n\n /**\n * Base-row update + version snapshot. Subject to AdminClient's\n * cross-locale write guard (SD021): under a non-default request-context\n * locale, translatable fields throw `CrossLocaleWriteError` — that's\n * enforcement, not a gap. Locale-belonging writes go through the draft\n * flow (`saveDraft` → `publishDraft`) or `admin.updateForLocale` directly.\n */\n async update(id: string, data: InferUpdateInput<AllFields>): Promise<InferEntityDTO<AllFields>> {\n let previousState: InferEntityDTO<AllFields> | null = null\n if (this.ctx.versionableOptions) {\n previousState = await this.ctx.admin.findById(id)\n }\n\n const result = await this.ctx.admin.update(id, data)\n\n if (this.ctx.versionableOptions && previousState) {\n const delta = calculateDelta(previousState, result)\n const version = await saveVersionSnapshot(this.ctx, id, result, delta, false)\n if (version !== undefined) {\n await writeVersionColumn(this.ctx, id, version)\n await pruneVersions(this.ctx, id)\n return { ...result, _version: version } as InferEntityDTO<AllFields>\n }\n await pruneVersions(this.ctx, id)\n }\n\n return result\n }\n\n delete(id: string): Promise<unknown> {\n return this.ctx.admin.delete(id)\n }\n\n // -----------------------------------------------------------------\n // Translation delegation\n // -----------------------------------------------------------------\n\n saveTranslation(entityId: string, locale: string, translations: Record<string, unknown>) {\n return this.ctx.admin.saveTranslation(entityId, locale, translations)\n }\n\n deleteTranslation(entityId: string, locale?: string) {\n return this.ctx.admin.deleteTranslation(entityId, locale)\n }\n\n // -----------------------------------------------------------------\n // Version history\n // -----------------------------------------------------------------\n\n getVersions(entityId: string, options?: { limit?: number; offset?: number; locale?: string }) {\n return getVersions(this.ctx, entityId, options)\n }\n\n getVersion(entityId: string, version: number, locale?: string) {\n return getVersion(this.ctx, entityId, version, locale)\n }\n\n compareVersions(entityId: string, v1: number, v2: number, locale?: string) {\n return compareVersions(this.ctx, entityId, v1, v2, locale)\n }\n\n restoreVersion(entityId: string, version: number, locale?: string) {\n return restoreVersion(this.ctx, entityId, version, locale)\n }\n\n pruneVersions(entityId: string, locale?: string) {\n return pruneVersions(this.ctx, entityId, locale)\n }\n\n createVersionSnapshot(\n entityId: string,\n currentData: Record<string, unknown>,\n previousData?: Record<string, unknown> | null,\n locale?: string,\n user?: { id: string; name?: string },\n ) {\n return createVersionSnapshot(this.ctx, entityId, currentData, previousData, locale, user)\n }\n\n // -----------------------------------------------------------------\n // Translation status\n // -----------------------------------------------------------------\n\n getTranslationStatus(entityId: string) {\n return getTranslationStatus(this.ctx, entityId)\n }\n\n getTranslationStatusBatch(entityIds: string[]) {\n return getTranslationStatusBatch(this.ctx, entityIds)\n }\n\n getTranslationReport(options?: { locale?: string }) {\n return getTranslationReport(this.ctx, options)\n }\n\n // -----------------------------------------------------------------\n // Per-locale publish status\n // -----------------------------------------------------------------\n\n getLocaleStatus(entityId: string) {\n return getLocaleStatus(this.ctx, entityId)\n }\n\n setLocaleStatus(entityId: string, locale: string, status: 'draft' | 'published') {\n return setLocaleStatus(this.ctx, entityId, locale, status)\n }\n\n getLocaleStatusBatch(entityIds: string[]) {\n return getLocaleStatusBatch(this.ctx, entityIds)\n }\n\n // -----------------------------------------------------------------\n // Drafts\n // -----------------------------------------------------------------\n\n saveDraft(\n entityId: string,\n data: InferUpdateInput<AllFields>,\n locale?: string,\n user?: { id: string; name?: string },\n ) {\n return saveDraft(this.ctx, entityId, data, locale, user)\n }\n\n mergeDraft(\n entityId: string,\n patch: InferUpdateInput<AllFields>,\n locale?: string,\n user?: { id: string; name?: string },\n ) {\n return mergeDraft(this.ctx, entityId, patch, locale, user)\n }\n\n getDraft(entityId: string, locale?: string) {\n return getDraft(this.ctx, entityId, locale)\n }\n\n deleteDraft(entityId: string, locale?: string) {\n return deleteDraft(this.ctx, entityId, locale)\n }\n\n publishDraft(entityId: string, locale?: string, user?: { id: string; name?: string }) {\n return publishDraft(this.ctx, entityId, locale, user)\n }\n\n hasDraft(entityId: string, locale?: string) {\n return hasDraft(this.ctx, entityId, locale)\n }\n\n countDrafts(locale?: string) {\n return countDrafts(this.ctx, locale)\n }\n\n hasDraftBatch(entityIds: string[], locale?: string) {\n return hasDraftBatch(this.ctx, entityIds, locale)\n }\n\n compareDraftWithCurrent(entityId: string, locale?: string) {\n return compareDraftWithCurrent(this.ctx, entityId, locale)\n }\n}\n\n/**\n * Factory — creates a ContentClient for an entity. Must be called\n * after `createApp()`. Generic flows from the entity definition:\n * `createContentClient(Article)` returns a `ContentClient<typeof\n * Article['allFields']>` typed end-to-end.\n */\nexport function createContentClient<AllFields extends Record<string, FieldConfig>>(\n entity: Entity<AllFields>,\n): ContentClient<AllFields> {\n const admin = createAdminClient(entity)\n return new ContentClient<AllFields>({\n admin,\n entity,\n logger: getApp().logger.child({ content: entity.name }),\n })\n}\n"],"mappings":"8uBA+BA,SAAS,EAAa,EAA2B,CAC/C,MAAO,CACL,GAAI,EAAI,GACR,SAAU,EAAI,SACd,OAAQ,EAAI,OACZ,KAAM,EAAI,KACV,UAAW,EAAI,UACf,cAAe,EAAI,eAAiB,KACpC,UAAW,EAAI,UACf,UAAW,EAAI,SACjB,CACF,CAiBA,eAAsB,EACpB,EACA,EACA,EACA,EAAA,IACA,EAC0C,CAC1C,EAAe,CAAM,EACrB,IAAM,EAAS,MAAM,EAAgB,CAAG,EACxC,GAAI,CAAC,EAAQ,MAAM,IAAI,EAAsB,EAAI,OAAO,KAAM,QAAQ,EAEtE,IAAM,EAAY,EAAsB,EAAI,OAAQ,CAA+B,EASnF,EAAI,MAAM,sBAAsB,CAAS,EAezC,IAAM,EAHoB,EAAkB,EAAI,MAAM,CAAC,CAAC,MAAM,CAAE,UAC9D,OAAO,OAAO,EAAW,CAAI,CAEE,EAAI,MAAM,EAAO,QAAQ,CAAE,WAAU,QAAO,CAAC,EAAI,KAClF,MAAM,EAAI,MAAM,sBACd,EACA,GAAU,IACZ,EAEA,IAAM,EAAM,IAAI,KACV,EAAY,GAAM,IAAM,GACxB,EAAgB,GAAM,MAAQ,KAmBpC,OAAO,EAAa,MAjBF,EAAO,OACvB,CACE,WACA,SACA,KAAM,EACN,YACA,gBACA,UA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AAK,IAAK,EAAU,CAAM,CAC5C,CAEA,YAAY,EAAiB,CAC3B,OAAO,EAAY,KAAK,IAAK,CAAM,CACrC,CAEA,cAAc,EAAqB,EAAiB,CAClD,OAAO,EAAc,KAAK,IAAK,EAAW,CAAM,CAClD,CAEA,wBAAwB,EAAkB,EAAiB,CACzD,OAAO,EAAwB,KAAK,IAAK,EAAU,CAAM,CAC3D,CACF,EAQA,SAAgB,EACd,EAC0B,CAE1B,OAAO,IAAI,EAAyB,CAClC,MAFY,EAAkB,CAE1B,EACJ,SACA,OAAQ,EAAO,CAAC,CAAC,OAAO,MAAM,CAAE,QAAS,EAAO,IAAK,CAAC,CACxD,CAAC,CACH"}
@@ -0,0 +1,2 @@
1
+ import{t as e}from"./rolldown-runtime-DK3Fl9T5.mjs";import{t}from"./registry-CaPbY5lm.mjs";import{requireSiteFor as n}from"@murumets-ee/core";import"server-only";var r=e({createContentContext:()=>i,getDraftsClient:()=>a,getLocaleStatusClient:()=>s,getVersionsClient:()=>o});function i(e,t){return{entity:e.entity,admin:e.admin,db:e.admin.getDb(),versionableOptions:t,logger:e.logger}}async function a(e){let{drafts:r}=t(e.entity.name);return r?r.makeClient(e.db,await n(e.entity)):null}async function o(e){let{versions:r}=t(e.entity.name);return r?r.makeClient(e.db,await n(e.entity)):null}async function s(e){let{localeStatus:r}=t(e.entity.name);return r?r.makeClient(e.db,await n(e.entity)):null}export{o as a,s as i,i as n,a as r,r as t};
2
+ //# sourceMappingURL=context-D7eEItCY.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"context-D7eEItCY.mjs","names":[],"sources":["../src/internal/context.ts"],"sourcesContent":["/**\n * Shared per-instance state for ContentClient feature modules.\n *\n * The package's domain modules (`versions.ts`, `drafts.ts`,\n * `translation-status.ts`, `locale-status.ts`, `layout.ts`) are written\n * as free functions that take a `ContentContext` as their first\n * argument. ContentClient itself is a thin shell that builds the\n * context once and forwards every public method to the corresponding\n * free function.\n *\n * Why free functions instead of one class with everything inline:\n * - 1000+ LoC in one class is impossible to navigate and audit.\n * - Each module has clear inputs (the context + method args) and no\n * hidden dependencies on private state.\n * - Splits cleanly along the same boundaries as the per-entity\n * capability tables (drafts, versions, locale_status, ...) — every\n * module owns exactly one capability surface.\n */\n\nimport 'server-only'\n\nimport { type Logger, requireSiteFor } from '@murumets-ee/core'\nimport type { Entity, FieldConfig } from '@murumets-ee/entity'\nimport type { AdminClient } from '@murumets-ee/entity/admin'\nimport type { PostgresJsDatabase } from 'drizzle-orm/postgres-js'\nimport type { getVersionableOptions } from '../behaviors/versionable.js'\nimport { getContentTables } from '../schema/registry.js'\n\n/**\n * Per-instance content context. Built once in `createContentContext()`\n * and threaded through every domain module's free functions.\n */\nexport interface ContentContext<\n AllFields extends Record<string, FieldConfig> = Record<string, FieldConfig>,\n> {\n entity: Entity<AllFields>\n admin: AdminClient<AllFields>\n db: PostgresJsDatabase\n versionableOptions: ReturnType<typeof getVersionableOptions>\n logger?: Logger | undefined\n}\n\n/**\n * Build a content context from an AdminClient + entity. The DB handle\n * is read off the AdminClient (it owns the read-write connection).\n */\nexport function createContentContext<AllFields extends Record<string, FieldConfig>>(\n config: {\n admin: AdminClient<AllFields>\n entity: Entity<AllFields>\n logger?: Logger\n },\n // Lazy import to avoid a static cycle: behaviors/versionable.ts is loaded\n // by client.ts which would otherwise close the loop. Phase-2 validated\n // the static import graph; this is a private helper bundled into the\n // same chunk so the dynamic-vs-static rule doesn't apply.\n versionableOptions: ReturnType<typeof getVersionableOptions>,\n): ContentContext<AllFields> {\n return {\n entity: config.entity,\n admin: config.admin,\n db: config.admin.getDb(),\n versionableOptions,\n logger: config.logger,\n }\n}\n\n// -------------------------------------------------------------------\n// Per-capability TableClient lookups. For a site-bound entity the client\n// is CONFINED to the request's site (multisite D003) — `requireSiteFor`\n// throws when there is none, so a companion read can never widen to every\n// site. Async for that reason: the single-site answer may need a lookup.\n// Each returns null if the entity\n// hasn't registered the corresponding table (i.e. doesn't have the\n// behavior). ContentClient public methods translate that null into\n// either a thrown EntityCapabilityError (writes) or a falsy return\n// (reads).\n// -------------------------------------------------------------------\n\nexport async function getDraftsClient(ctx: ContentContext) {\n const { drafts } = getContentTables(ctx.entity.name)\n return drafts ? drafts.makeClient(ctx.db, await requireSiteFor(ctx.entity)) : null\n}\n\nexport async function getVersionsClient(ctx: ContentContext) {\n const { versions } = getContentTables(ctx.entity.name)\n return versions ? versions.makeClient(ctx.db, await requireSiteFor(ctx.entity)) : null\n}\n\nexport async function getLocaleStatusClient(ctx: ContentContext) {\n const { localeStatus } = getContentTables(ctx.entity.name)\n return localeStatus ? localeStatus.makeClient(ctx.db, await requireSiteFor(ctx.entity)) : null\n}\n"],"mappings":"kRA8CA,SAAgB,EACd,EASA,EAC2B,CAC3B,MAAO,CACL,OAAQ,EAAO,OACf,MAAO,EAAO,MACd,GAAI,EAAO,MAAM,MAAM,EACvB,qBACA,OAAQ,EAAO,MACjB,CACF,CAcA,eAAsB,EAAgB,EAAqB,CACzD,GAAM,CAAE,UAAW,EAAiB,EAAI,OAAO,IAAI,EACnD,OAAO,EAAS,EAAO,WAAW,EAAI,GAAI,MAAM,EAAe,EAAI,MAAM,CAAC,EAAI,IAChF,CAEA,eAAsB,EAAkB,EAAqB,CAC3D,GAAM,CAAE,YAAa,EAAiB,EAAI,OAAO,IAAI,EACrD,OAAO,EAAW,EAAS,WAAW,EAAI,GAAI,MAAM,EAAe,EAAI,MAAM,CAAC,EAAI,IACpF,CAEA,eAAsB,EAAsB,EAAqB,CAC/D,GAAM,CAAE,gBAAiB,EAAiB,EAAI,OAAO,IAAI,EACzD,OAAO,EAAe,EAAa,WAAW,EAAI,GAAI,MAAM,EAAe,EAAI,MAAM,CAAC,EAAI,IAC5F"}
@@ -1 +1 @@
1
- import{n as e,r as t,t as n}from"../site-chrome-BUEOhmyf.mjs";export{n as CHROME_PLACEMENTS,e as CHROME_PLACEMENT_LABELS,t as siteChromeEntity};
1
+ import{n as e,r as t,t as n}from"../site-chrome-DvP9SXGu.mjs";export{n as CHROME_PLACEMENTS,e as CHROME_PLACEMENT_LABELS,t as siteChromeEntity};
package/dist/index.mjs CHANGED
@@ -1,2 +1,2 @@
1
- import{n as e,t}from"./versionable-Br_G5VGR.mjs";import{i as n,n as r,r as i,t as a}from"./errors-NRNILhhm.mjs";import{a as o,i as s,n as c,o as l,r as u,t as d}from"./routing-strategy-DQGPPBlW.mjs";import{t as f}from"./content-config-store-8omQF5p5.mjs";import{USER_ID_MAX_LENGTH as p,field as m}from"@murumets-ee/entity";import{createSystemReachResolver as h,mergeConfigOverrides as g}from"@murumets-ee/core";import{QueryClient as _}from"@murumets-ee/entity/query";import{schemaRegistry as v}from"@murumets-ee/db";import{eq as y}from"drizzle-orm";const b=new Set([`hide`,`patch`,`replace`]),x=Symbol.for(`@murumets-ee/content:withOverrides`),S=new Set([`__proto__`,`constructor`,`prototype`]);function C(e,t,n=0){if(e!=null&&!(typeof e!=`object`||Array.isArray(e)))for(let r of Object.keys(e)){if(S.has(r))throw Error(`withOverrides: reserved key '${r}' at ${t} is not allowed.`);n<3&&C(e[r],`${t}.${r}`,n+1)}}function w(e){if(e==null)return{};if(typeof e!=`object`||Array.isArray(e))throw Error(`withOverrides: _overrides must be a plain object map.`);let t=e,n=Object.keys(t);if(n.length>100)throw Error(`withOverrides: _overrides has ${n.length} entries; cap is 100.`);let r={};for(let e of n){if(S.has(e))throw Error(`withOverrides: reserved key '${e}' is not allowed.`);let n=t[e];if(typeof n!=`object`||!n||Array.isArray(n))throw Error(`withOverrides: _overrides['${e}'] must be a directive object.`);let i=n.kind;if(typeof i!=`string`||!b.has(i))throw Error(`withOverrides: _overrides['${e}'].kind must be one of [hide, patch, replace]; got ${String(i)}.`);if(i===`patch`){let t=n;T(t.props,`_overrides['${e}'].props`),T(t.traits,`_overrides['${e}'].traits`)}if(i===`replace`){let t=n.block;if(typeof t!=`object`||!t||Array.isArray(t)||typeof t.id!=`string`)throw Error(`withOverrides: _overrides['${e}'] replace payload must include an object 'block' with a string 'id'.`)}C(n,`_overrides['${e}']`),r[e]=n}return r}function T(e,t){if(e!==void 0&&(typeof e!=`object`||!e||Array.isArray(e)))throw Error(`withOverrides: ${t} must be an object.`)}function E(){return{name:`withOverrides`,fields:{_overrides:m.json({default:()=>({}),internal:!0,refScan:!0})},hooks:{beforeCreate:async e=>(e._overrides===void 0?e._overrides={}:e._overrides=w(e._overrides),e),beforeUpdate:async(e,t)=>(t._overrides===void 0||(t._overrides=w(t._overrides)),t)},[x]:!0}}function D(e){return e?e.some(e=>!!e?.[x]):!1}const O=[`draft`,`in_review`,`approved`,`rejected`,`published`],k={draft:[`in_review`],in_review:[`approved`,`rejected`],approved:[`published`,`in_review`],rejected:[`in_review`,`draft`],published:[`draft`]};function A(e,t){return e===t?!0:k[e]?.includes(t)??!1}var j=class extends Error{from;to;constructor(e,t){super(`Invalid workflow transition: ${e} → ${t}. Allowed transitions from "${e}": [${(k[e]??[]).join(`, `)}].`),this.name=`WorkflowTransitionError`,this.from=e,this.to=t}};function M(){return{name:`workflowable`,fields:{_workflowStatus:m.select({options:O,default:`draft`,indexed:!0,required:!0,internal:!0}),_workflowAssignee:m.text({required:!1,internal:!0,maxLength:p}),_workflowNote:m.text({required:!1,internal:!0}),_workflowUpdatedAt:m.date({internal:!0})},hooks:{beforeCreate:async e=>(e._workflowStatus=`draft`,e._workflowUpdatedAt=new Date,e),beforeUpdate:async(e,t,n)=>{let r=t._workflowStatus;if(r===void 0)return t;if(!O.includes(r))throw new j(`draft`,r);let i=(await n?.loadCurrent?.())?._workflowStatus??`draft`,a=r;if(!A(i,a))throw new j(i,a);return t._workflowUpdatedAt=new Date,t}}}}function N(e,t){switch(t){case`drafts`:return P(e,`publishable`);case`versions`:return P(e,`versionable`);case`localeStatus`:return P(e,`publishable`)&&F(e);case`translations`:return F(e)}}function P(e,t){return e.behaviors?.some(e=>e.name===t)??!1}function F(e){let t=e.allFields;for(let e of Object.keys(t)){let n=t[e];if(n&&n.translatable===!0)return!0}return!1}const I=h(`locale-registry`);function L(){return f().locales.map((e,t)=>({code:e.code,label:e.label,enabled:!0,direction:`ltr`,sortOrder:t}))}function R(e,t){return e.sortOrder-t.sortOrder||e.code.localeCompare(t.code)}async function z(e){return e.entities?.has(`locale`)?(await new _({entity:s,db:e.db.readOnly,logger:e.logger.child({registry:`locale`}),contextResolver:I}).findMany({limit:1e3})).map(e=>{let t=e;return{code:String(t.code),label:typeof t.label==`string`&&t.label.length>0?t.label:String(t.code),enabled:t.enabled!==!1,direction:t.direction===`rtl`?`rtl`:`ltr`,sortOrder:typeof t.sortOrder==`number`?t.sortOrder:0}}):[]}async function B(e){let t;try{t=await z(e)}catch(t){return e.logger.warn({err:t},`locale registry read failed — falling back to content() defaults`),[...L()].sort(R)}return g({defaults:L(),overrides:t,idOfDefault:e=>e.code,idOfOverride:e=>e.code}).sort(R)}function V(e){return e.filter(e=>e.enabled).map(e=>e.code)}async function H(e,t){let n=V(t??await B(e)),r=f().defaultLocale,i={};try{let{createSettingsClient:t}=await import(`@murumets-ee/settings/runtime`);i=await t(l,{app:e}).getAll()??{}}catch(t){e.logger.warn({err:t},`i18n settings read failed — falling back to content() defaults`)}let a=typeof i.defaultLocale==`string`&&i.defaultLocale.length>0?i.defaultLocale:r,s=n.includes(a)?a:n.includes(r)?r:n[0]??r,c=i.routingStrategy;return{defaultLocale:s,routingStrategy:o.includes(typeof c==`string`?c:``)?c:`no-prefix-default`}}const U=h(`message-registry`),W=2e4;async function G(e,t){if(!e.entities?.has(`message`))return[];let n=v.get(`message`);if(!n)return[];let r=new _({entity:u,db:e.db.readOnly,logger:e.logger.child({registry:`message`}),contextResolver:U});try{let i=await r.findMany({where:y(n.locale,t),limit:W});return i.length>=W&&e.logger.warn({locale:t,cap:W},`message override read hit the row cap — some overrides were not applied`),i.map(e=>{let t=e;return{namespace:String(t.namespace),key:String(t.key),value:String(t.value)}})}catch(n){return e.logger.warn({err:n,locale:t},`message registry read failed — falling back to shipped defaults only`),[]}}export{a as DraftNotFoundError,r as EntityCapabilityError,i as InvalidLocaleError,s as Locale,u as Message,o as ROUTING_STRATEGIES,n as VersionNotFoundError,O as WORKFLOW_STATES,k as WORKFLOW_TRANSITIONS,j as WorkflowTransitionError,V as enabledLocaleCodes,N as entitySupports,t as getVersionableOptions,D as hasWithOverrides,l as i18nSettings,A as isAllowedTransition,d as localePrefixForStrategy,c as prefixDefaultLocaleForStrategy,B as resolveEffectiveLocales,H as resolveI18nConfig,G as resolveMessageOverrides,e as versionable,E as withOverrides,M as workflowable};
1
+ import{n as e,t}from"./versionable-Br_G5VGR.mjs";import{i as n,n as r,r as i,t as a}from"./errors-NRNILhhm.mjs";import{a as o,i as s,n as c,o as l,r as u,t as d}from"./routing-strategy-CQdu1qV7.mjs";import{t as f}from"./content-config-store-8omQF5p5.mjs";import{USER_ID_MAX_LENGTH as p,field as m}from"@murumets-ee/entity";import{createSystemReachResolver as h,mergeConfigOverrides as g}from"@murumets-ee/core";import{QueryClient as _}from"@murumets-ee/entity/query";import{schemaRegistry as v}from"@murumets-ee/db";import{eq as y}from"drizzle-orm";const b=new Set([`hide`,`patch`,`replace`]),x=Symbol.for(`@murumets-ee/content:withOverrides`),S=new Set([`__proto__`,`constructor`,`prototype`]);function C(e,t,n=0){if(e!=null&&!(typeof e!=`object`||Array.isArray(e)))for(let r of Object.keys(e)){if(S.has(r))throw Error(`withOverrides: reserved key '${r}' at ${t} is not allowed.`);n<3&&C(e[r],`${t}.${r}`,n+1)}}function w(e){if(e==null)return{};if(typeof e!=`object`||Array.isArray(e))throw Error(`withOverrides: _overrides must be a plain object map.`);let t=e,n=Object.keys(t);if(n.length>100)throw Error(`withOverrides: _overrides has ${n.length} entries; cap is 100.`);let r={};for(let e of n){if(S.has(e))throw Error(`withOverrides: reserved key '${e}' is not allowed.`);let n=t[e];if(typeof n!=`object`||!n||Array.isArray(n))throw Error(`withOverrides: _overrides['${e}'] must be a directive object.`);let i=n.kind;if(typeof i!=`string`||!b.has(i))throw Error(`withOverrides: _overrides['${e}'].kind must be one of [hide, patch, replace]; got ${String(i)}.`);if(i===`patch`){let t=n;T(t.props,`_overrides['${e}'].props`),T(t.traits,`_overrides['${e}'].traits`)}if(i===`replace`){let t=n.block;if(typeof t!=`object`||!t||Array.isArray(t)||typeof t.id!=`string`)throw Error(`withOverrides: _overrides['${e}'] replace payload must include an object 'block' with a string 'id'.`)}C(n,`_overrides['${e}']`),r[e]=n}return r}function T(e,t){if(e!==void 0&&(typeof e!=`object`||!e||Array.isArray(e)))throw Error(`withOverrides: ${t} must be an object.`)}function E(){return{name:`withOverrides`,fields:{_overrides:m.json({default:()=>({}),internal:!0,refScan:!0})},hooks:{beforeCreate:async e=>(e._overrides===void 0?e._overrides={}:e._overrides=w(e._overrides),e),beforeUpdate:async(e,t)=>(t._overrides===void 0||(t._overrides=w(t._overrides)),t)},[x]:!0}}function D(e){return e?e.some(e=>!!e?.[x]):!1}const O=[`draft`,`in_review`,`approved`,`rejected`,`published`],k={draft:[`in_review`],in_review:[`approved`,`rejected`],approved:[`published`,`in_review`],rejected:[`in_review`,`draft`],published:[`draft`]};function A(e,t){return e===t?!0:k[e]?.includes(t)??!1}var j=class extends Error{from;to;constructor(e,t){super(`Invalid workflow transition: ${e} → ${t}. Allowed transitions from "${e}": [${(k[e]??[]).join(`, `)}].`),this.name=`WorkflowTransitionError`,this.from=e,this.to=t}};function M(){return{name:`workflowable`,fields:{_workflowStatus:m.select({options:O,default:`draft`,indexed:!0,required:!0,internal:!0}),_workflowAssignee:m.text({required:!1,internal:!0,maxLength:p}),_workflowNote:m.text({required:!1,internal:!0}),_workflowUpdatedAt:m.date({internal:!0})},hooks:{beforeCreate:async e=>(e._workflowStatus=`draft`,e._workflowUpdatedAt=new Date,e),beforeUpdate:async(e,t,n)=>{let r=t._workflowStatus;if(r===void 0)return t;if(!O.includes(r))throw new j(`draft`,r);let i=(await n?.loadCurrent?.())?._workflowStatus??`draft`,a=r;if(!A(i,a))throw new j(i,a);return t._workflowUpdatedAt=new Date,t}}}}function N(e,t){switch(t){case`drafts`:return P(e,`publishable`);case`versions`:return P(e,`versionable`);case`localeStatus`:return P(e,`publishable`)&&F(e);case`translations`:return F(e)}}function P(e,t){return e.behaviors?.some(e=>e.name===t)??!1}function F(e){let t=e.allFields;for(let e of Object.keys(t)){let n=t[e];if(n&&n.translatable===!0)return!0}return!1}const I=h(`locale-registry`);function L(){return f().locales.map((e,t)=>({code:e.code,label:e.label,enabled:!0,direction:`ltr`,sortOrder:t}))}function R(e,t){return e.sortOrder-t.sortOrder||e.code.localeCompare(t.code)}async function z(e){return e.entities?.has(`locale`)?(await new _({entity:s,db:e.db.readOnly,logger:e.logger.child({registry:`locale`}),contextResolver:I}).findMany({limit:1e3})).map(e=>{let t=e;return{code:String(t.code),label:typeof t.label==`string`&&t.label.length>0?t.label:String(t.code),enabled:t.enabled!==!1,direction:t.direction===`rtl`?`rtl`:`ltr`,sortOrder:typeof t.sortOrder==`number`?t.sortOrder:0}}):[]}async function B(e){let t;try{t=await z(e)}catch(t){return e.logger.warn({err:t},`locale registry read failed — falling back to content() defaults`),[...L()].sort(R)}return g({defaults:L(),overrides:t,idOfDefault:e=>e.code,idOfOverride:e=>e.code}).sort(R)}function V(e){return e.filter(e=>e.enabled).map(e=>e.code)}async function H(e,t){let n=V(t??await B(e)),r=f().defaultLocale,i={};try{let{createSettingsClient:t}=await import(`@murumets-ee/settings/runtime`);i=await t(l,{app:e}).getAll()??{}}catch(t){e.logger.warn({err:t},`i18n settings read failed — falling back to content() defaults`)}let a=typeof i.defaultLocale==`string`&&i.defaultLocale.length>0?i.defaultLocale:r,s=n.includes(a)?a:n.includes(r)?r:n[0]??r,c=i.routingStrategy;return{defaultLocale:s,routingStrategy:o.includes(typeof c==`string`?c:``)?c:`no-prefix-default`}}const U=h(`message-registry`),W=2e4;async function G(e,t){if(!e.entities?.has(`message`))return[];let n=v.get(`message`);if(!n)return[];let r=new _({entity:u,db:e.db.readOnly,logger:e.logger.child({registry:`message`}),contextResolver:U});try{let i=await r.findMany({where:y(n.locale,t),limit:W});return i.length>=W&&e.logger.warn({locale:t,cap:W},`message override read hit the row cap — some overrides were not applied`),i.map(e=>{let t=e;return{namespace:String(t.namespace),key:String(t.key),value:String(t.value)}})}catch(n){return e.logger.warn({err:n,locale:t},`message registry read failed — falling back to shipped defaults only`),[]}}export{a as DraftNotFoundError,r as EntityCapabilityError,i as InvalidLocaleError,s as Locale,u as Message,o as ROUTING_STRATEGIES,n as VersionNotFoundError,O as WORKFLOW_STATES,k as WORKFLOW_TRANSITIONS,j as WorkflowTransitionError,V as enabledLocaleCodes,N as entitySupports,t as getVersionableOptions,D as hasWithOverrides,l as i18nSettings,A as isAllowedTransition,d as localePrefixForStrategy,c as prefixDefaultLocaleForStrategy,B as resolveEffectiveLocales,H as resolveI18nConfig,G as resolveMessageOverrides,e as versionable,E as withOverrides,M as workflowable};
2
2
  //# sourceMappingURL=index.mjs.map
@@ -0,0 +1,2 @@
1
+ import{t as e}from"./versionable-Br_G5VGR.mjs";import{r as t}from"./errors-NRNILhhm.mjs";import{i as n,o as r,r as i}from"./routing-strategy-CQdu1qV7.mjs";import{n as a,t as o}from"./content-config-store-8omQF5p5.mjs";import{n as s,t as c}from"./registry-CaPbY5lm.mjs";import"./locale-utils-B0mFoV47.mjs";import{n as l}from"./chrome-entity-names-zYJzP-_U.mjs";import{a as u,n as d,r as f,t as p}from"./schema-D8sBQozw.mjs";import{l as m,t as h,u as g}from"./schema-0zayzpD_.mjs";import{r as _,t as v}from"./routes-C9I1iZw8.mjs";import{n as y}from"./locks-5779ugSW.mjs";import{MAX_PATH_DEPTH as b,SITE_COLUMN as x,SITE_HANDLE_MAX_LENGTH as S,buildPartitionCondition as C,hasPathParent as w,isSiteBound as T,resolveEffectiveSlugMode as E,resolvePattern as D}from"@murumets-ee/entity";import{definePlugin as O,getApp as k,getAppOrUndefined as A,getContext as j,getCurrentSite as M,requireSiteFor as N,runAsCli as P,runInEverySite as F}from"@murumets-ee/core";import{column as I,defineTable as L,schemaRegistry as R}from"@murumets-ee/db";import{and as z,asc as B,eq as V,inArray as H,sql as ee}from"drizzle-orm";import{z as U}from"zod";import{createHash as W}from"node:crypto";const G=Symbol.for(`@murumets-ee/content:locale-status-writer`);async function K(e,t,n,r){let i=r===`published`?new Date:null;await e.upsert({entityId:t,locale:n,status:r,publishedAt:i},{target:[`entityId`,`locale`],set:{status:r,publishedAt:i}})}function q(e){globalThis[G]=(n,r)=>{let{localeStatus:i}=c(n.name);if(i)return async(n,a,o,s)=>{let c=j()?.availableLocales??e;if(!c.includes(a))throw new t(a,[...c]);await K(i.makeClient(r,s),n,a,o)}}}async function J(e){let t=j()?.app??A();if(!t)return;let n=t.entities.get(e);if(n)return N(n,t)}function te(){return{async writeDraft({documentType:e,documentId:t,locale:n,dataPatch:r,user:i,tx:a}){let{drafts:o}=c(e);if(!o)return!1;let s=o.makeClient(a,await J(e)),l=new Date;return await s.upsert({entityId:t,locale:n,data:r,createdBy:i.id,createdByName:i.name??null,createdAt:l,updatedAt:l},{target:[`entityId`,`locale`],set:{updatedAt:l},mergeJsonb:[`data`]}),!0},async readDraft({documentType:e,documentId:t,locale:n,db:r}){let{drafts:i}=c(e);if(!i)return null;let a=await i.makeClient(r,await J(e)).findOne({entityId:t,locale:n});return a?{data:a.data??{},createdBy:a.createdBy??null,createdByName:a.createdByName??null,updatedAt:a.updatedAt??null}:null},async readLocaleStatus({documentType:e,documentId:t,locale:n,db:r}){let{localeStatus:i}=c(e);if(!i)return null;let a=await i.makeClient(r,await J(e)).findOne({entityId:t,locale:n});return a?a.status===`published`?`published`:`draft`:null},async hasAnyDraft({documentType:e,documentId:t,db:n}){let{drafts:r}=c(e);return r?r.makeClient(n,await J(e)).exists({entityId:t}):!1},async hasAnyLocaleActivity({documentType:e,documentId:t,db:n}){let{localeStatus:r}=c(e),i=await J(e);if(r&&await r.makeClient(n,i).exists({entityId:t}))return!0;let a=R.get(`${e}_translations`);if(a){let r=a.entityId;if(r!==void 0){let o=i===void 0?V(r,t):z(V(r,t),C(a,{site:i},e));if((await n.select({one:ee`1`}).from(a).where(o).limit(1)).length>0)return!0}}return!1}}}function ne(e){let{defaultLocale:t}=o();return e===`_`||e===t?{defaultLocale:t}:{locale:e,defaultLocale:t}}function re(e){let{defaultLocale:t}=o();return e===`_`||e===t?`_`:e}async function ie(e,t,n,r){let{drafts:i}=c(e);if(!i)return;let a=await i.makeClient(r,await J(e)).findOne({entityId:t,locale:n});return a?a.data??void 0:void 0}function ae(){return{async snapshotCurrentState({documentType:t,documentId:n,locale:r,user:i}){let a=k(),o=a.entities.get(t);if(!o)return!1;let s=e(o.behaviors);if(!s)return!1;let c=a.getClient(o),l=c.getDb(),u=re(r),d=await c.findById(n,ne(u));if(!d)return!1;let f=await ie(t,n,u,l),p=f?{...d,...f}:{...d},[{createContentContext:m},{createVersionSnapshot:h}]=await Promise.all([import(`./context-D7eEItCY.mjs`).then(e=>e.t),import(`./versions-C9A4rUAR.mjs`).then(e=>e.c)]);return await h(m({admin:c,entity:o},s),n,p,d,u,{id:i.id,...i.name==null?{}:{name:i.name}}),!0}}}const oe=Symbol.for(`@murumets-ee/content:path-writers-factory`),Y=Symbol.for(`@murumets-ee/content:cascade-trigger-factory`);function se(e){globalThis[Y]=e}function ce(){let e=globalThis[Y];return typeof e==`function`?e:void 0}function le(e,t){let n=d.makeClient(e.db.readWrite);return async r=>{if(r.action===`delete`){await n.deleteMany({entityType:r.entityName,entityId:r.id});return}if(r.action===`release`){await n.deleteMany({entityType:r.entityName,entityId:r.id,isCanonical:!0});return}let i=o(),a=i.defaultLocale,s=i.reservedPathPrefixes??[],c=r.locale?[r.locale]:i.locales.map(e=>e.code),l=r.viaCascade===!0?e.getSystemClient(t):e.getClient(t),u=async n=>{if(!w(t))return;let i=ce();if(i)try{await i(e,t,r.id,n)}catch(t){e.logger.warn({err:t,entity:r.entityName,id:r.id,locale:n},`toolkit_paths: descendant-cascade trigger threw — the entity write already committed, so tolerating and continuing (paths are rebuildable, D005)`)}};for(let i of c){let o=i===r.locale?r.row??null:await l.findById(r.id,{locale:i,defaultLocale:a});if(!o){await f({pathsClient:n,entityType:r.entityName,entityId:r.id,locale:i,path:null,skipReason:`row-unreadable`,reservedPathPrefixes:s,logger:e.logger});continue}let c=await m({entity:t,row:o,locale:i,defaultLocale:a,pathsClient:n}),d=await f({pathsClient:n,entityType:r.entityName,entityId:r.id,locale:i,path:c.path,...c.skipReason!==void 0&&{skipReason:c.skipReason},reservedPathPrefixes:s,logger:e.logger});(d.outcome===`renamed`||r.action===`restore`&&d.outcome===`created`)&&await u(i)}}}function ue(e,t){let n=d.makeClient(e.db.readWrite);return async r=>{let i=o(),a=i.defaultLocale,s=i.reservedPathPrefixes??[],c=r.locale??a,l=null;r.id!==void 0&&(l=await e.getClient(t).findById(r.id,{locale:c,defaultLocale:a}));let u=E(r.data.slugMode,l?.slugMode);await g({entity:t,data:r.data,currentRow:l,id:r.id,locale:c,defaultLocale:a,slugMode:u,reservedPathPrefixes:s,pathsClient:n})}}function de(){globalThis[oe]=(e,t)=>({pathIndexWriter:le(e,t),pathConflictGuard:ue(e,t)})}const X=U.object({entityType:U.string().min(1),parentId:U.string().uuid(),locale:U.string().min(1)}),Z=U.object({entity:U.string().min(1).optional(),locale:U.string().min(1).optional(),dryRun:U.boolean()});async function fe(e,t,n={}){let{entityType:r,parentId:i,locale:a}=t,s=n.maxItems??2e3,c=n.concurrency??5,l={processed:0,regenerated:0,unchanged:0,skipped:0,failed:0,truncated:!1},p=e=>({phase:e,...l}),h=()=>({entityType:r,parentId:i,locale:a,cap:s,...l}),g=e.entities.get(r);if(!g)return e.logger.warn({entityType:r,parentId:i,locale:a},`paths-cascade: unknown entity type — nothing to regenerate`),n.onProgress?.(p(`done`)),h();if(!w(g))return e.logger.warn({entityType:r,parentId:i,locale:a},`paths-cascade: entity is not a pathParent() hierarchy — nothing to regenerate`),n.onProgress?.(p(`done`)),h();let _=o(),v=_.defaultLocale,y=_.reservedPathPrefixes??[],b=d.makeClient(e.db.readWrite),x=e.getClient(g),S=x.getTable().parent,C=async t=>{let n=t.id;try{let i=await m({entity:g,row:t,locale:a,defaultLocale:v,pathsClient:b});switch((await f({pathsClient:b,entityType:r,entityId:n,locale:a,path:i.path,...i.skipReason!==void 0&&{skipReason:i.skipReason},reservedPathPrefixes:y,logger:e.logger})).outcome){case`created`:case`renamed`:l.regenerated+=1;break;case`unchanged`:l.unchanged+=1;break;default:l.skipped+=1;break}}catch(t){l.failed+=1,e.logger.warn({err:t,entityType:r,id:n,locale:a},`paths-cascade: failed to regenerate one descendant path — continuing (per-item isolation)`)}},T=[i];for(;T.length>0;){let e=s-l.processed;if(e<=0){l.truncated=!0;break}let t=await x.findMany({where:H(S,T),locale:a,defaultLocale:v,limit:e+1});if(t.length===0)break;let r=t;if(t.length>e&&(r=t.slice(0,e),l.truncated=!0),await u(r,c,C),l.processed+=r.length,n.onProgress?.(p(`walking`)),l.truncated)break;T=r.map(e=>e.id)}return l.truncated&&e.logger.warn({entityType:r,parentId:i,locale:a,processed:l.processed,cap:s},`paths-cascade: descendant subtree exceeded the cap — deeper/remaining descendants were NOT regenerated. Run \`lumi paths:rebuild --entity ${r}\` for guaranteed full coverage.`),n.onProgress?.(p(`done`)),h()}async function pe(e,t,n={}){let r=n.pageSize??200,i=n.concurrency??5,a=n.sampleCap??25,s=t.dryRun,c=o(),l=c.defaultLocale,p=c.reservedPathPrefixes??[],h=c.locales.map(e=>e.code),g=t.locale?h.filter(e=>e===t.locale):h,_=[...e.entities.values()].filter(e=>!!e.frontend?.path&&(t.entity===void 0||e.name===t.entity)),v=t.entity!==void 0&&_.length===0,y=t.locale!==void 0&&g.length===0;v&&e.logger.warn({entity:t.entity,dryRun:s},`paths-rebuild: --entity matches no routable entity (one declaring frontend.path) — nothing to rebuild (likely a typo in the entity name)`),y&&e.logger.warn({locale:t.locale,configuredLocales:h,dryRun:s},`paths-rebuild: --locale matches no configured locale — nothing to rebuild (likely a typo in the locale code)`);let x=v||y?{entity:v,locale:y}:void 0,S=_.some(e=>w(e)),C=s&&S?`Preview reflects a SINGLE pass; a pathParent() hierarchy drifted at multiple levels may need the real (non-dry-run) rebuild's multi-pass convergence to fully resolve. The real run always converges.`:void 0,T=d.makeClient(e.db.readWrite),E={scanned:0,changed:0,applied:0,failed:0},D=new Map,O={missing:0,conflicts:0,unchanged:0,skipped:0},k=(e,t)=>{let n=D.get(e);n!==t&&(n!==void 0&&n!==`resolved`&&--O[n],D.set(e,t),t!==`resolved`&&(O[t]+=1))},A=[],j=!1,M=e=>{A.length<a?A.push(e):j=!0},N=0,P=e=>({phase:e,dryRun:s,scope:{entity:t.entity??null,locale:t.locale??null},scanned:E.scanned,changed:E.changed,applied:E.applied,failed:E.failed,missing:O.missing,conflicts:O.conflicts,unchanged:O.unchanged,skipped:O.skipped,passes:N,sample:A,sampleTruncated:j,...C===void 0?{}:{hierarchyNote:C},...x===void 0?{}:{unmatchedScope:x}}),F=async(t,n,r,i)=>{let a=r.id,o=!1;try{let c=await m({entity:t,row:r,locale:i,defaultLocale:l,pathsClient:T}),u=await f({pathsClient:T,entityType:n,entityId:a,locale:i,path:c.path,...c.skipReason!==void 0&&{skipReason:c.skipReason},suppressNoteworthy:[`parent-not-indexed`],reservedPathPrefixes:p,logger:e.logger,dryRun:s}),d=`${n}:${a}:${i}`;switch(u.outcome){case`unchanged`:k(d,`unchanged`);break;case`skipped-null`:case`skipped-reserved`:k(d,`skipped`);break;case`conflict`:k(d,`conflicts`),M({kind:`conflict`,entityType:n,entityId:a,locale:i,oldPath:u.oldPath,newPath:u.newPath,...u.conflictWith?{conflictWith:u.conflictWith.entityId}:{}});break;case`created`:s?k(d,`missing`):(E.applied+=1,o=!0,k(d,`resolved`)),M({kind:`missing`,entityType:n,entityId:a,locale:i,oldPath:null,newPath:u.newPath});break;case`renamed`:E.changed+=1,s||(E.applied+=1,o=!0),k(d,`resolved`),M({kind:`changed`,entityType:n,entityId:a,locale:i,oldPath:u.oldPath,newPath:u.newPath});break}}catch(t){E.failed+=1,e.logger.warn({err:t,entityType:n,id:a,locale:i},`paths-rebuild: failed to process one document — continuing (per-item isolation)`)}return o},I=async t=>{let a=0;for(let o of t){let t=e.getClient(o),s=o.name,c=t.getTable().id;for(let e of g){let d;for(;;){let f=await t.findMany({locale:e,defaultLocale:l,limit:r,orderBy:B(c),...d===void 0?{}:{cursor:{field:`id`,value:d,direction:`asc`}}});if(f.length===0)break;await u(f,i,async t=>{await F(o,s,t,e)&&(a+=1)}),E.scanned+=f.length;let p=f[f.length-1];if(p&&(d=p.id),n.onProgress?.(P(`scanning`)),f.length<r)break}}}return a},L=async t=>{let r=[];for(let[n,i]of D){if(i!==`conflicts`&&i!==`skipped`&&i!==`missing`)continue;let a=n.indexOf(`:`),o=n.lastIndexOf(`:`);if(a<=0||o<=a)continue;let s=n.slice(0,a);if(t.has(s))continue;let c=e.entities.get(s);c!==void 0&&r.push({entity:c,entityType:s,entityId:n.slice(a+1,o),locale:n.slice(o+1)})}if(r.length===0)return 0;let a=0;return await u(r,i,async t=>{let n=await e.getClient(t.entity).findById(t.entityId,{locale:t.locale,defaultLocale:l});n!==null&&(E.scanned+=1,await F(t.entity,t.entityType,n,t.locale)&&(a+=1))}),n.onProgress?.(P(`scanning`)),a},R=_.filter(e=>w(e)),z=new Set(R.map(e=>e.name)),V=s||!S?1:b;for(let e=0;e<V;e++){N=e+1;let t=await I(e===0?_:R);if(e>0&&(t+=await L(z)),t===0)break}j&&e.logger.warn({scanned:E.scanned,changed:E.changed,missing:O.missing,conflicts:O.conflicts,sampleCap:a},`paths-rebuild: more diff entries than the progress sample can hold — see the aggregate counts; the stored sample is truncated`);let H=P(`done`);n.onProgress?.(H);let{phase:ee,...U}=H;return U}async function me(e){let{defineJob:t,registerJob:n,QueueClient:r}=await import(`@murumets-ee/queue/client`),i=t({name:`content:paths-cascade`,description:`Regenerate toolkit_paths canonical rows for the descendants of a renamed routable-hierarchy ancestor (one locale). Walks the full bounded subtree in a single invocation.`,schema:X}),a=t({name:`content:paths-rebuild`,description:`Recompute every routable document's canonical toolkit_paths row (optionally scoped to one entity/locale); dryRun reports the diff without writing. On-demand (lumi paths:rebuild).`,schema:Z});n(i,async t=>{await P(async()=>{let n=await fe(e,X.parse(t.payload),{onProgress:e=>t.updateProgress(e)});e.logger.info(n,`paths-cascade: descendant regeneration complete`)})}),n(a,async t=>{await P(()=>F(async()=>{let n=await pe(e,Z.parse(t.payload),{onProgress:e=>t.updateProgress({...e,site:M()??null})});e.logger.info({dryRun:n.dryRun,scanned:n.scanned,changed:n.changed,missing:n.missing,conflicts:n.conflicts,applied:n.applied,failed:n.failed,passes:n.passes,...n.hierarchyNote===void 0?{}:{hierarchyNote:n.hierarchyNote}},`paths-rebuild: sweep complete`)},{app:e,label:`paths-rebuild`}))}),se(async(e,t,n,a)=>{await new r({app:e,logger:e.logger}).enqueue(i,{entityType:t.name,parentId:n,locale:a})})}const Q=L({name:`toolkit_path_patterns`,columns:{id:I.uuid({primaryKey:!0,defaultRandom:!0}),entityType:I.varchar({length:100,notNull:!0,pgName:`entity_type`}),locale:I.varchar({length:10,notNull:!0}),patternHash:I.varchar({length:64,notNull:!0,pgName:`pattern_hash`}),updatedAt:I.timestamp({notNull:!0,defaultNow:!0,withTimezone:!0,pgName:`updated_at`})},unique:[{on:[`entityType`,`locale`]}]}),he=Q.table;function ge(e,t,n){let r=D(e,t,n);if(r===null)return null;let i=typeof r==`function`?r.toString():JSON.stringify(r);return W(`sha256`).update(i).digest(`hex`)}async function _e(e){let t=o(),n=t.defaultLocale,r=t.locales.map(e=>e.code),i=Q.makeClient(e.db.readWrite);for(let[t,a]of e.entities){let o=a.frontend?.path;if(o!==void 0)for(let a of r){let r=ge(o,a,n);if(r===null)continue;let s=await i.findOne({entityType:t,locale:a});s!==null&&s.patternHash===r||(s!==null&&e.logger.warn({entity:t,locale:a,previousHash:s.patternHash,currentHash:r},`toolkit_paths: frontend.path pattern for '${t}' (locale '${a}') changed since last boot — stale toolkit_paths rows may exist; run \`lumi paths:rebuild --entity ${t}\``),await i.upsert({entityType:t,locale:a,patternHash:r},{target:[`entityType`,`locale`],set:{patternHash:r,updatedAt:new Date}}))}}}const ve=async(e,t,n)=>{if(t.length===0)return new Map;let[{buildEnumerateDeps:r},{getCanonicalPaths:i}]=await Promise.all([import(`./resolve-context-MRZZ3rQl.mjs`).then(e=>e.l),import(`./enumerate-CBqu63Kp.mjs`).then(e=>e.n)]),a=r(k()),o=await a.filterPublished(e,t,n);return o.size===0?new Map:i(e,[...o],n,a)};function $(e,t){return T(e)?L({name:t.name,columns:{...t.columns,[x]:I.varchar({length:S,notNull:!0})},unique:(t.unique??[]).map(e=>({...e,on:[x,...e.on.map(String)]})),partitionColumn:x}):L(t)}function ye(e){return $(e,{name:`${e.name}_drafts`,columns:{id:I.uuid({primaryKey:!0,defaultRandom:!0}),entityId:I.uuid({notNull:!0,pgName:`entity_id`}),locale:I.varchar({length:10,notNull:!0,default:`_`}),data:I.jsonb({notNull:!0}),createdBy:I.varchar({length:255,notNull:!0,pgName:`created_by`}),createdByName:I.varchar({length:255,pgName:`created_by_name`}),createdAt:I.timestamp({notNull:!0,defaultNow:!0,withTimezone:!0,pgName:`created_at`}),updatedAt:I.timestamp({notNull:!0,defaultNow:!0,withTimezone:!0,pgName:`updated_at`})},unique:[{on:[`entityId`,`locale`]}]})}function be(e){return $(e,{name:`${e.name}_locale_status`,columns:{id:I.uuid({primaryKey:!0,defaultRandom:!0}),entityId:I.uuid({notNull:!0,pgName:`entity_id`}),locale:I.varchar({length:10,notNull:!0}),status:I.varchar({length:20,notNull:!0,default:`draft`}),publishedAt:I.timestamp({withTimezone:!0,pgName:`published_at`})},unique:[{on:[`entityId`,`locale`]}]})}function xe(e){return $(e,{name:`${e.name}_versions`,columns:{id:I.uuid({primaryKey:!0,defaultRandom:!0}),entityId:I.uuid({notNull:!0,pgName:`entity_id`}),version:I.integer({notNull:!0}),locale:I.varchar({length:10,notNull:!0,default:`_`}),data:I.jsonb({notNull:!0}),delta:I.jsonb(),status:I.varchar({length:20}),createdBy:I.varchar({length:255,pgName:`created_by`}),createdByName:I.varchar({length:255,pgName:`created_by_name`}),createdAt:I.timestamp({notNull:!0,defaultNow:!0,withTimezone:!0,pgName:`created_at`}),isAutosave:I.boolean({notNull:!0,default:!1,pgName:`is_autosave`})},unique:[{on:[`entityId`,`version`,`locale`]}]})}function Se(e){if(!e.locales||e.locales.length===0)throw Error(`content() requires at least one locale`);if(!e.defaultLocale)throw Error(`content() requires a defaultLocale`);if(!e.locales.some(t=>t.code===e.defaultLocale))throw Error(`defaultLocale "${e.defaultLocale}" not found in locales: [${e.locales.map(e=>e.code).join(`, `)}]`);if(e.reservedPathPrefixes){for(let t of e.reservedPathPrefixes)if(typeof t!=`string`||!t.startsWith(`/`))throw Error(`content(): reservedPathPrefixes entries must be absolute paths starting with '/', got ${JSON.stringify(t)}`)}let t=e.autoTrash??!0,o=t===!1?void 0:{publishable:!0,...typeof t==`object`&&t.exclude?{exclude:t.exclude}:{}};return O({name:`@murumets-ee/content`,contributes:{"blocks.documentDraftStore":te(),"blocks.documentVersionStore":ae(),"blocks.publishedPathResolver":ve,...o?{"trash.autoEnable":o}:{},...e.reservedPathPrefixes?{"routing.reservedPathPrefixes":e.reservedPathPrefixes}:{}},shared:{settings:[r],features:[{resource:`redirect`,actions:[`manage`],defaultRoles:[`admin`],description:`Create, edit, and delete manual URL redirects (toolkit_redirects).`},{resource:`path`,actions:[`resolve`],defaultRoles:[`admin`,`editor`],description:`Resolve a site URL path to the CMS document that serves it.`}]},server:{entities:[n,i],tables:{toolkitContentLocks:y,toolkitPaths:p,toolkitPathPatterns:he,toolkitRedirects:h},routes:[...v(),..._()],seeders:[{name:`content:site-chrome`,description:`Create the empty site_chrome row for each placement (header, footer), as a DRAFT, so they can be edited on the page canvas. Publishing one is what makes /v1/_chrome serve it instead of the delivery template's own fallback. Idempotent — an existing row for a placement is left alone.`,available:l,bootstrap:!0,run:async()=>{let{seedSiteChrome:e}=await import(`@murumets-ee/content/seed`);return await e()}}],init:async t=>{a(e);let n=0,r=0,i=0;for(let[e,a]of t.entities){if(a.behaviors?.some(e=>e.name===`versionable`)){let t=`${e}_versions`;if(!R.has(t)){let n=xe(a);R.register(t,n.table),s(e,{versions:n})}n++}let t=a.behaviors?.some(e=>e.name===`publishable`),o=a.allFields,c=Object.values(o).some(e=>e.translatable);if(t&&c){let t=`${e}_locale_status`;if(!R.has(t)){let n=be(a);R.register(t,n.table),s(e,{localeStatus:n})}r++}if(t){let t=`${e}_drafts`;if(!R.has(t)){let n=ye(a);R.register(t,n.table),s(e,{drafts:n})}i++}}q(e.locales.map(e=>e.code)),de();try{await me(t)}catch(e){t.logger.warn({err:e},"content: failed to register routing path jobs — descendant cascade + `lumi paths:rebuild` will be unavailable (path writes still succeed)")}t.logger.info({locales:e.locales.map(e=>e.code),defaultLocale:e.defaultLocale,versionableEntities:n,localeStatusEntities:r,draftEntities:i},`Content plugin initialized`)},onReady:async e=>{try{await _e(e)}catch(t){e.logger.error({err:t},"content: boot-time frontend-path pattern-drift check failed — continuing app boot without it. Inspect the logged `err` for the cause: a transient DB error can be retried (and `lumi paths:rebuild` re-derives the index if a pattern actually changed), whereas a structural cause — e.g. a missing migration leaving `toolkit_path_patterns` absent — will recur on every boot and needs `lumi migrate`")}}}})}export{K as n,Se as t};
2
+ //# sourceMappingURL=plugin-D0i6odXQ.mjs.map