@heyo-sh/heyo-cms 0.3.0 → 0.3.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/ai.js +1 -1
- package/dist/auth.js +1 -1
- package/dist/cli.js +2 -2
- package/dist/config.js +1 -1
- package/dist/content.js +1 -1
- package/dist/db/d1.js +1 -1
- package/dist/db/mongodb.d.ts +2 -1
- package/dist/db/mongodb.d.ts.map +1 -1
- package/dist/db/mongodb.js +2 -2
- package/dist/db/postgres.js +1 -1
- package/dist/db/sql/adapter.d.ts.map +1 -1
- package/dist/db/sql/dialect.d.ts +3 -0
- package/dist/db/sql/dialect.d.ts.map +1 -1
- package/dist/db/sqlite.js +1 -1
- package/dist/db/unique.d.ts +46 -0
- package/dist/db/unique.d.ts.map +1 -0
- package/dist/editor.js +1 -1
- package/dist/fields.js +1 -1
- package/dist/http.js +1 -1
- package/dist/{index-b79c3k6g.js → index-0fe3ngv2.js} +2 -2
- package/dist/{index-1xz3pmtk.js → index-1xwmw8vb.js} +2 -2
- package/dist/{index-mpkhjgvk.js → index-2djaxtj8.js} +4 -4
- package/dist/{index-63x90ejh.js → index-2j6d79fk.js} +6 -6
- package/dist/{index-zyg6bfdq.js → index-2zpnecrk.js} +2 -2
- package/dist/{index-761dec5z.js → index-344y6q4n.js} +2 -2
- package/dist/index-4j1kkeg2.js +2 -0
- package/dist/{index-eqfcxn71.js → index-5j0cqm43.js} +2 -2
- package/dist/{index-wbc2xh4h.js → index-5yt6r97r.js} +6 -6
- package/dist/{index-a8jcwqsf.js → index-78f0ghve.js} +2 -2
- package/dist/{index-szaq03qq.js → index-8j4p950b.js} +2 -2
- package/dist/{index-466cwb0b.js → index-cakys3fy.js} +2 -2
- package/dist/{index-p2cqsmvw.js → index-cnzt9x9x.js} +2 -2
- package/dist/{index-abfzb1ve.js → index-e3yknwyr.js} +2 -2
- package/dist/{index-vf163r10.js → index-fy8r8e53.js} +2 -2
- package/dist/index-gv8j76x3.js +26 -0
- package/dist/{index-dtwe2z69.js → index-mzxsxzkd.js} +4 -4
- package/dist/{index-91fa1gzf.js → index-n09v6gx3.js} +2 -2
- package/dist/{index-axpzy2hj.js → index-pkxgzw6e.js} +2 -2
- package/dist/{index-vzhxn50e.js → index-q6ak9ph4.js} +2 -2
- package/dist/{index-6m1kjq9g.js → index-q6jkbsjp.js} +2 -2
- package/dist/{index-8nzmqy0f.js → index-qgtvymh2.js} +2 -2
- package/dist/{index-s9x07zb3.js → index-qkqtxr65.js} +2 -2
- package/dist/{index-ypcmns0v.js → index-rb9fxtyn.js} +2 -2
- package/dist/{index-a1jv6396.js → index-rpdkj3qk.js} +11 -11
- package/dist/{index-ptttzgtp.js → index-twqpdtfh.js} +3 -3
- package/dist/index.js +1 -1
- package/dist/jobs.js +1 -1
- package/dist/migrations.js +1 -1
- package/dist/query.js +1 -1
- package/dist/{run-rqmtv3cn.js → run-mtgvmy5x.js} +2 -2
- package/dist/schema.js +1 -1
- package/dist/telemetry.js +1 -1
- package/dist/uploads.js +3 -3
- package/dist/webhooks.js +1 -1
- package/package.json +1 -1
- package/dist/index-4qrep5f0.js +0 -26
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{Z,me,_,on,fe,j}from"./index-63x90ejh.js";import{_e,O,A,$e,Je,go,yo,je,hn,l,u}from"./index-axpzy2hj.js";import{s,R,t,We,H,M,S,le,m}from"./index-6m1kjq9g.js";import{sn,ye}from"./index-abfzb1ve.js";import{to,qe}from"./index-wbc2xh4h.js";import{V,J,Zt,Yt}from"./index-zyg6bfdq.js";import{Rt}from"./index-1xz3pmtk.js";import{Ae,ke}from"./index-466cwb0b.js";import{en,tn,nn}from"./index-91fa1gzf.js";import{d}from"./index-9g2n7xa6.js";import{Te}from"./index-ptttzgtp.js";import{ge,et,tt}from"./index-y8kzzn94.js";import{p,Pt}from"./index-s9x07zb3.js";import{ot}from"./index-761dec5z.js";import{un}from"./index-eqfcxn71.js";import{w,se}from"./index-rw0hze6x.js";import{x}from"./index-2ddk43me.js";import{b,ve}from"./index-8nzmqy0f.js";import{e,n}from"./index-x72d1hzh.js";var rt="activity",at=50,lt=200;function De(o){return{async list(i={}){let r=gt(i.limit),a=[];if(i.collection)a.push(t("collection",i.collection));if(i.documentId)a.push(t("document_id",i.documentId));if(i.actorId)a.push(t("actor_id",i.actorId));if(i.action)a.push(t("action",i.action));if(i.source)a.push(t("source",i.source));if(i.cursor)a.push(H("id",i.cursor));let c=await o.database(),f=await c.transaction((v)=>c.query(v,{table:rt,...a.length===0?{}:{where:s(...a)},orderBy:[{path:"id",direction:"desc"}],limit:r+1})),h=f.length>r,g=f.slice(0,r),C=g.at(-1);return{entries:g.map(ct),limit:r,hasNextPage:h,cursor:h&&C?String(C.id):null}}}}function ct(o){let i=o.changes===null||o.changes===void 0?null:u(o.changes);return{id:String(o.id),action:String(o.action),actorId:Y(o.actor_id),actorSource:Y(o.actor_source),source:Y(o.source),collection:Y(o.collection),documentId:Y(o.document_id),locale:Y(o.locale),changes:i,ip:Y(o.ip),createdAt:l(o.created_at)}}function Y(o){return o===null||o===void 0?null:String(o)}function gt(o){if(o===void 0)return at;if(!Number.isInteger(o)||o<1)throw new e(`limit must be a positive integer, received ${o}`,{status:400,code:"invalid_pagination"});return Math.min(o,lt)}function dt(o,i){let r={createBefore:[],createAfter:[],updateBefore:[],updateAfter:[],deleteBefore:[],deleteAfter:[]},a=o.plugins.flatMap((f)=>(f.hooks??[]).filter((h)=>h.collection===i).map((h)=>({plugin:f.id,hook:h}))).sort((f,h)=>(f.hook.priority??0)-(h.hook.priority??0)||f.plugin.localeCompare(h.plugin));for(let{plugin:f,hook:h}of a){let g={source:f,priority:h.priority??0};if(h.timing==="before"){if(h.operation==="create")r.createBefore.push({...g,run:(v,D)=>h.handler(v.data,D)});else if(h.operation==="update")r.updateBefore.push({...g,run:(v,D)=>h.handler(v.data,D)});else r.deleteBefore.push({...g,run:(v,D)=>h.handler(v,D)});continue}let C=async(v,D)=>{await h.handler(v,D)};if(h.operation==="create")r.createAfter.push({...g,run:C});else if(h.operation==="update")r.updateAfter.push({...g,run:(v,D)=>C(v.doc,D)});else r.deleteAfter.push({...g,run:C})}let c=o.pluginHooks.filter((f)=>f.collection===i).sort((f,h)=>f.priority-h.priority||f.plugin.localeCompare(h.plugin));for(let f of c)Ee(r,f.hooks,{source:f.plugin,priority:f.priority});return Ee(r,o.databaseHooks?.[i],{source:"config",priority:bt}),r}var bt=100;function Ee(o,i,r){if(i?.create?.before){let a=i.create.before;o.createBefore.push({...r,run:(c,f)=>a(c,f)})}if(i?.create?.after){let a=i.create.after;o.createAfter.push({...r,run:(c,f)=>a(c,f)})}if(i?.update?.before){let a=i.update.before;o.updateBefore.push({...r,run:async(c,f)=>await a(c,f)})}if(i?.update?.after){let a=i.update.after;o.updateAfter.push({...r,run:(c,f)=>a(c,f)})}if(i?.delete?.before){let a=i.delete.before;o.deleteBefore.push({...r,run:(c,f)=>a(c,f)})}if(i?.delete?.after){let a=i.delete.after;o.deleteAfter.push({...r,run:(c,f)=>a(c,f)})}}async function Ie(o,i,r,a){let c=i;for(let f of o){let h=await f.run(c,r);if(h===!1)return!1;if(h&&typeof h==="object"&&"data"in h)c=a(c,h.data)}return c}async function He(o,i,r){for(let a of o)await a.run(i,r)}function Wt(o){let i=new Set([...Object.keys(o.collections),...Object.keys(o.globals),...o.plugins.flatMap((a)=>(a.hooks??[]).map((c)=>c.collection)),...o.pluginHooks.map((a)=>a.collection)]),r=[];for(let a of[...i].sort()){let c=dt(o,a),f=[["create","before",c.createBefore],["create","after",c.createAfter],["delete","before",c.deleteBefore],["delete","after",c.deleteAfter],["update","before",c.updateBefore],["update","after",c.updateAfter]];for(let[h,g,C]of f)for(let v of C)r.push({collection:a,operation:h,timing:g,source:v.source,priority:v.priority})}return r}var vt="jobs",wt=100,Ct={name:"scheduled-changes",failureType:"document.schedule",failurePayload:(o)=>{let i=je(o);return{collection:String(o.collection),documentId:String(o.id),...i===null?{}:{locale:i.locale,patch:i.data},...o.scheduled_at instanceof Date?{scheduledFor:o.scheduled_at.toISOString()}:{}}},due:async(o,i,r)=>{let a=await o.database();return a.transaction((c)=>a.query(c,{table:p,where:s(le("scheduled_at",!0),M("scheduled_at",i),t("deleted_at",null)),orderBy:[m("scheduled_at","asc"),m("id","asc")],limit:r}))},run:(o,i)=>o.applyScheduled(i)},St={name:"trash-purge",failureType:"trash.purge",failurePayload:(o)=>({collection:String(o.collection),documentId:String(o.id)}),due:async(o,i,r)=>{if(o.config.trash.purgeAfter===!1)return[];let a=await o.database();return a.transaction((c)=>a.query(c,{table:p,where:s(le("deleted_at",!0),le("purge_after",!0),M("purge_after",i)),orderBy:[m("purge_after","asc"),m("id","asc")],limit:r}))},run:(o,i)=>o.purgeExpired(i)};class ut{host;jobs=[Ct,St];constructor(o){this.host=o}list(){return this.jobs.map((o)=>o.name)}register(o){this.jobs.push(o)}async run(o={}){let i=o.now??new Date,r=o.limit??wt,a=o.only?this.jobs.filter((f)=>o.only?.includes(f.name)):this.jobs,c=[];for(let f of a){let h=await f.due(this.host,i,r+1),g=h.slice(0,r),C=0,v=0;for(let D of g)try{await f.run(this.host,D,i),C+=1}catch(I){v+=1,await this.host.recordFailure(f.failureType,f.failurePayload(D),I).catch(()=>{return})}c.push({job:f.name,processed:C,failed:v,more:h.length>r})}return{ranAt:i.toISOString(),processed:c.reduce((f,h)=>f+h.processed,0),failed:c.reduce((f,h)=>f+h.failed,0),results:c}}async failures(o={}){let i=await this.host.database();return(await i.transaction((a)=>i.query(a,{table:vt,where:o.type===void 0?t("status","failed"):s(t("status","failed"),t("type",o.type)),orderBy:[m("created_at","desc"),m("id","desc")],limit:o.limit??50}))).map((a)=>({id:String(a.id),type:String(a.type),payload:a.payload===null||a.payload===void 0?null:u(a.payload),error:a.error===null||a.error===void 0?null:String(a.error),attempts:Number(a.attempts??0),createdAt:l(a.created_at)}))}}var oe="outbox";class pt{queued=[];emit(o,i,r=null){this.queued.push({type:o,data:i,previous:r})}take(){return this.queued.splice(0,this.queued.length)}}class mt{adapter;dispatch;maxAttempts;backoff;leaseMs;now;constructor(o,i,r={}){this.adapter=o;this.dispatch=i;this.maxAttempts=r.maxAttempts??5,this.backoff=r.backoff??((a)=>1000*2**(a-1)),this.leaseMs=r.leaseMs??300000,this.now=r.now??(()=>new Date)}async append(o,i,r){let a=this.now();for(let c of i)await this.adapter.mutate(o,{kind:"insert",table:oe,returning:!1,values:{id:ve("obx"),event_id:b("evt"),type:c.type,payload:c.data,previous:c.previous,actor:r.actor?{id:r.actor.id,source:r.actor.source}:null,collection:r.collection??null,document_id:r.documentId??null,status:"pending",attempts:0,available_at:a,processed_at:null,error:null,created_at:a}})}async drain(o=50){let i=await this.adapter.transaction((a)=>this.adapter.query(a,{table:oe,where:s(S("status",["pending","delivering"]),M("available_at",this.now())),orderBy:[m("created_at","asc"),m("id","asc")],limit:o})),r=0;for(let a of i){if(await this.hasPredecessor(a))continue;let c=await this.claim(a);if(!c)continue;if(Number(c.attempts)>this.maxAttempts){await this.settle(c,!1,Error("Delivery lease expired; attempt budget exhausted."));continue}try{await this.dispatch(kt(c)),await this.settle(c,!0),r+=1}catch(f){await this.settle(c,!1,f)}}return r}async hasPredecessor(o){if(!o.document_id)return!1;return(await this.adapter.transaction((r)=>this.adapter.query(r,{table:oe,where:s(t("collection",o.collection==null?null:String(o.collection)),t("document_id",String(o.document_id)),H("id",String(o.id)),S("status",["pending","delivering"])),limit:1}))).length>0}async claim(o){let i={status:"delivering",attempts:Number(o.attempts??0)+1,available_at:new Date(this.now().getTime()+this.leaseMs)};return(await this.adapter.transaction((a)=>this.adapter.mutate(a,{kind:"update",table:oe,where:s(t("id",String(o.id)),t("status",String(o.status)),t("attempts",Number(o.attempts??0)),M("available_at",this.now())),set:i,returning:!1}))).count===1?{...o,...i}:null}async settle(o,i,r){let a=Number(o.attempts??0),c=a>=this.maxAttempts,f=i?{status:"delivered",attempts:a,processed_at:this.now(),error:null}:{status:c?"failed":"pending",attempts:a,available_at:new Date(this.now().getTime()+this.backoff(a)),error:r instanceof Error?r.message:String(r)};await this.adapter.transaction((h)=>this.adapter.mutate(h,{kind:"update",table:oe,where:s(t("id",String(o.id)),t("status","delivering"),t("attempts",a)),set:f,returning:!1}))}}function kt(o){let i=u(o.actor);return{id:String(o.event_id),type:String(o.type),createdAt:l(o.created_at)??new Date().toISOString(),actor:typeof i.id==="string"?{id:i.id,source:i.source==="api-key"?"api-key":"session"}:null,data:u(o.payload),previous:o.previous===null||o.previous===void 0?null:u(o.previous)}}class ft{options;cache=new Map;queries=0;constructor(o){this.options=o}get queryCount(){return this.queries}async expand(o,i,r){if(r<=0||o.length===0)return;let a=Object.entries(i.fields).map(([h,g])=>({name:h,target:vn(g)})).filter((h)=>Boolean(h.target));if(a.length===0)return;let c=new Map;for(let h of o)for(let g of a)for(let C of At(h[g.name])){if(this.cache.has(Q(g.target,C)))continue;let v=c.get(g.target)??new Set;v.add(C),c.set(g.target,v)}for(let[h,g]of c)await this.load(h,[...g]);let f=new Map;for(let h of o)for(let g of a){let C=h[g.name];h[g.name]=this.substitute(g.target,C,f)}for(let[h,g]of f){let C=this.options.collections[h];if(C)await this.expand(g,C,r-1)}}async load(o,i){let r=this.options.collections[o];if(this.queries+=1,r){for(let g of i)this.cache.set(Q(o,g),null);let c;try{c=await _(r,{actor:this.options.actor??null,operation:"read",locale:this.options.locale.locale,rbac:this.options.rbac})}catch(g){if(g instanceof e&&(g.status===401||g.status===403))return;throw g}let f=[c,t("collection",r.slug),S("id",i),...this.options.includeTrashed?[]:[t("deleted_at",null)]],h=await this.options.adapter.query(this.options.tx,{table:p,where:s(...f)});for(let g of i)this.cache.set(Q(o,g),null);for(let g of h){let C=A(g,r,this.options.locale);this.cache.set(Q(o,String(g.id)),fe(C,r,this.options.actor??null,this.options.locale.locale))}return}for(let c of i)this.cache.set(Q(o,c),null);if(o!=="media"&&o!=="cms_users")return;let a=await this.options.adapter.query(this.options.tx,{table:o,where:S("id",i),...o==="cms_users"?{select:["id","name"]}:{}});for(let c of i)this.cache.set(Q(o,c),null);for(let c of a)this.cache.set(Q(o,String(c.id)),yo(c))}substitute(o,i,r){let a=(c)=>{let f=structuredClone(c),h=r.get(o)??[];return h.push(f),r.set(o,h),f};if(typeof i==="string"){let c=this.cache.get(Q(o,i));return c?a(c):i}if(Array.isArray(i))return i.map((c)=>{if(typeof c!=="string")return c;let f=this.cache.get(Q(o,c));return f?a(f):c});return i??null}}function vn(o){if(o.relationTo)return o.relationTo;return o.type==="media"?"media":void 0}function At(o){if(typeof o==="string")return o.length>0?[o]:[];if(Array.isArray(o))return o.filter((i)=>typeof i==="string");return[]}function Q(o,i){return`${o}:${i}`}var X="slug_history",Fe=50;function he(o){let i=ee(o);if(typeof i.slugify==="function")return i.slugify;let r=i.maxLength;return(a)=>ye(a,r===void 0?{}:{maxLength:r})}function ae(o){return Object.entries(o.fields).filter(([,i])=>i.type==="slug")}function ee(o){return o.options}async function be(o){let i=ae(o.collection);if(i.length===0)return{input:o.input,moves:[]};let r={...o.input},a=[];for(let[c,f]of i){let h=ee(f),g=f.localized?o.locale:"",C=Ot(o.stored,c,f,o.locale),v=r[c],D=he(f),I;if(typeof v==="string"&&v.trim()!==""){if(I=D(v),I==="")throw e.validation(`${o.collection.name}.${c}: "${v}" has no letters or digits to make a slug from`);if(h.unique!==!1)await Ce({...o,field:c,locale:g,slug:I})}else if(v===null||v===""||v===void 0&&C===null){let F=h.from===void 0?null:Tt(o,h.from),B=F===null?"":D(F);if(B!=="")I=h.unique===!1?B:await xt({...o,field:c,locale:g,base:B});else if(v!==void 0)I=null}if(I===void 0)continue;if(r[c]=I,h.history===!0&&C!==null&&I!==null&&I!==C)a.push({field:c,locale:g,from:C,to:I})}return{input:r,moves:a}}async function we(o,i,r,a,c){for(let f of a){let h=s(t("collection",i.name),t("field",f.field),t("locale",f.locale));if(await o.delete(X,s(h,t("document_id",r),t("slug",f.to))),await o.findOne(X,s(h,t("slug",f.from))))continue;await o.insert(X,{id:b("slg"),collection:i.name,field:f.field,locale:f.locale,slug:f.from,document_id:r,created_at:c})}}async function Le(o,i,r,a,c,f){await o.delete(X,s(t("collection",i.name),t("document_id",r),t("field",a),t("locale",c),t("slug",f)))}async function Me(o,i,r){await o.delete(X,s(t("collection",i.name),t("document_id",r)))}function _t(o){let i=o.collection.fields[o.field];return i!==void 0&&ee(i).history===!0}async function Ce(o){let i=o.locale?` in "${o.locale}"`:"",r=await Be(o,o.slug);if(r!==null)throw e.conflict(`The slug "${o.slug}" is already used${i} by another document of ${o.collection.label} (${r}).`);let a=await Ne(o,o.slug);if(a!==null)throw e.conflict(`The slug "${o.slug}" is a previous slug of another document of ${o.collection.label} (${a})${i} and redirects there. Remove it from that document's previous slugs first.`)}async function xt(o){for(let i=1;i<=Fe;i+=1){let r=i===1?o.base:`${o.base}-${i}`;if(await Be(o,r)===null&&await Ne(o,r)===null)return r}throw e.conflict(`No free slug for "${o.base}" after ${Fe} tries; set one explicitly.`)}async function Be(o,i){let r=o.locale?`${o.field}.${o.locale}`:o.field,a=await o.db.query({table:p,where:s(t("collection",o.collection.slug),t(r,i),...o.documentId===null?[]:[We("id",o.documentId)]),limit:1});return a[0]?String(a[0].id):null}async function Ne(o,i){if(!_t(o))return null;let r=await o.db.findOne(X,s(t("collection",o.collection.name),t("field",o.field),t("locale",o.locale),t("slug",i),...o.documentId===null?[]:[We("document_id",o.documentId)]));return r?String(r.document_id):null}function Ot(o,i,r,a){if(!o)return null;let c=r.localized?u(o[i])[a]:o[i];return typeof c==="string"&&c!==""?c:null}function Tt(o,i){let r=o.collection.fields[i];if(!r)return null;let a=o.input[i],c=a!==void 0?a:r.localized?u(o.stored?.[i])[o.locale]??null:o.stored?.[i]??null;return typeof c==="string"&&c.trim()!==""?c:null}async function ze(o){let{db:i,collection:r,field:a,slug:c}=o,f=r.fields[a];if(!f||!sn(c))return[];let h=f.localized,g=[],C=await i.query({table:p,where:s(t("collection",r.slug),t("deleted_at",null),h?R(...o.locales.map((I)=>t(`${a}.${I}`,c))):t(a,c)),limit:20});for(let I of C){let F=u(I.data)[a];if(!h){g.push({id:String(I.id),locale:null,current:!0});continue}for(let B of o.locales)if(u(F)[B]===c)g.push({id:String(I.id),locale:B,current:!0})}let v=[];if(ee(f).history===!0){let I=await i.find(X,s(t("collection",r.name),t("field",a),t("slug",c))),F=await Dt(i,r,I.map((B)=>String(B.document_id)));for(let B of I){let y=String(B.document_id);if(!F.has(y))continue;let P=String(B.locale??"");v.push({id:y,locale:P===""?null:P,current:!1})}}let D=(I)=>I.locale===null||I.locale===o.locale?0:1;return[...g.sort((I,F)=>D(I)-D(F)),...v.sort((I,F)=>D(I)-D(F))]}async function Dt(o,i,r){if(r.length===0)return new Set;let a=await o.query({table:p,where:s(t("collection",i.slug),t("deleted_at",null),S("id",[...new Set(r)]))});return new Set(a.map((c)=>String(c.id)))}async function Ge(o){let i=[t("collection",o.collection.name),t("document_id",o.documentId)];if(o.field!==void 0)i.push(t("field",o.field));if(o.locale!==void 0)i.push(t("locale",o.locale??""));return(await o.db.find(X,s(...i))).map((a)=>({slug:String(a.slug),field:String(a.field),locale:a.locale?String(a.locale):null,createdAt:l(a.created_at)})).sort((a,c)=>(c.createdAt??"").localeCompare(a.createdAt??"")||a.slug.localeCompare(c.slug))}var jt=25,$t=200,Se=[m("deleted_at","desc"),m("id","desc")];async function zt(o){let{adapter:i,config:r,collections:a,args:c}=o,f=O(r,c),h=c.actor??null,g=Jt(c.limit),C=c.collection?[It(a,c.collection)]:Object.values(a),v=[],D=new Map;for(let k of C){let T;try{T=await _(k,{actor:h,operation:"read",locale:f.locale,rbac:r.rbac})}catch(L){if(c.collection)throw L;continue}D.set(k.slug,k),v.push(T?s(t("collection",k.slug),T):t("collection",k.slug))}if(v.length===0)return{entries:[],limit:g,hasNextPage:!1,cursor:null};let I=v.length===D.size&&v.every((k)=>k.kind==="compare")?S("collection",[...D.keys()]):R(...v),F=s(le("deleted_at",!0),I),B=await i.transaction((k)=>i.query(k,{table:p,where:c.cursor?s(F,J(c.cursor,Se)):F,orderBy:Se,limit:g+1})),y=B.length>g,P=B.slice(0,g),W=P.flatMap((k)=>{let T=D.get(String(k.collection));if(!T)return[];let L=A(k,T,f);if(on(T))fe(L,T,h,f.locale);return[{collection:T.name,id:String(k.id),deletedAt:l(k.deleted_at),purgeAfter:l(k.purge_after),document:L}]}),E=P.at(-1);return{entries:W,limit:g,hasNextPage:y,cursor:E?V(E,Se):null}}function It(o,i){let r=o[i];if(!r)throw e.notFound(`No collection named "${i}"`);return r}function Jt(o){if(o===void 0)return jt;if(!Number.isInteger(o)||o<1)throw new e(`limit must be a positive integer, received ${o}`,{status:400,code:"invalid_pagination"});return Math.min(o,$t)}var Et=25,Ft=500,Lt="activity",Mt="media_usages",Ue="cms_ai_mutations",Ke={create:"create",update:"update",trash:"delete",purge:"delete",restore:"update",schedule:"update",unschedule:"update"};class ht{options;cms;pipelines=new Map;byName;bySlug;media=new Map;outbox;delivery=Promise.resolve();constructor(o){this.options=o;this.byName={...o.config.collections,...o.config.globals},this.bySlug=Object.fromEntries(Object.values(this.byName).map((i)=>[i.slug,i]))}bind(o){this.cms=o}buildApi(){let o={};for(let i of Object.values(this.options.config.collections))o[i.name]=this.collectionApi(i);return o}buildGlobals(){let o={};for(let i of Object.values(this.options.config.globals))o[i.name]=this.globalApi(i);return o}buildTrash(){return{list:async(o={})=>{let i=await this.options.database();return zt({adapter:i,config:this.options.config,collections:this.byName,args:o})},restore:(o)=>this.restore(this.requireCollection(o.collection),{...o,id:o.id}),purge:(o)=>this.purge(this.requireCollection(o.collection),{...o,id:o.id})}}buildJobs(){return new ut({config:this.options.config,database:()=>this.options.database(),applyScheduled:(o)=>this.applyScheduled(o),purgeExpired:(o)=>this.purgeExpired(o),recordFailure:(o,i,r)=>this.recordFailure(o,i,r)})}async drainEvents(o){return await this.delivery,(await this.outboxWorker()).drain(o)}async settle(){await this.delivery}async appendEvents(o,i,r){await(await this.outboxWorker()).append(o,i,r)}deliverSoon(){this.scheduleDelivery()}collectionApi(o){return{find:(i)=>this.find(o,i),findOne:(i)=>this.findOne(o,i),findById:(i,r)=>this.findById(o,i,r),count:(i)=>this.count(o,i),create:(i)=>this.create(o,i),update:(i)=>this.update(o,i),delete:(i)=>this.remove(o,i),restore:(i)=>this.restore(o,i),purge:(i)=>this.purge(o,i),schedule:(i)=>this.schedule(o,i),unschedule:(i)=>this.unschedule(o,i),resolveSlug:(i,r)=>this.resolveSlug(o,i,r),previousSlugs:(i)=>this.previousSlugs(o,i),addPreviousSlug:(i)=>this.changePreviousSlug(o,i,"add"),removePreviousSlug:(i)=>this.changePreviousSlug(o,i,"remove")}}slugField(o,i,r){let a=ae(o).filter(([,f])=>!r||ee(f).history===!0),c=i===void 0?a[0]?.[0]:a.find(([f])=>f===i)?.[0];if(c===void 0)throw e.validation(i===void 0?`${o.name} has no slug field${r?" with history":""}`:`${o.name}.${i} is not a slug field${r?" with history":""}`);return c}async resolveSlug(o,i,r={}){let a=this.slugField(o,r.field,!1),c=O(this.options.config,r),f=await this.options.database(),h=await f.transaction((v)=>ze({db:d(f,v),collection:o,field:a,slug:i,locale:c.locale,locales:this.options.config.i18n.locales})),{field:g,...C}=r;for(let v of h){let D=await this.findById(o,v.id,C);if(!D)continue;return{id:v.id,field:a,locale:v.locale,current:v.current,document:D}}return null}async previousSlugs(o,i){let r=this.slugField(o,i.field,!0);if(!await this.findById(o,i.id,{...i,includeTrashed:!0}))throw e.notFound(`No ${o.name} with id "${i.id}"`);let c=o.fields[r],f=await this.options.database();return f.transaction((h)=>Ge({db:d(f,h),collection:o,documentId:i.id,field:r,...i.locale===void 0?{}:{locale:c?.localized?i.locale:null}}))}async changePreviousSlug(o,i,r){let a=this.slugField(o,i.field,!0),c=o.fields[a],f=O(this.options.config,i),h=i.actor??null,g=c.localized?f.locale:"",C=r==="add"?he(c)(i.slug):i.slug;if(C==="")throw e.validation(`"${i.slug}" has no letters or digits to make a slug from`);let v=await this.options.database();return await v.transaction(async(D)=>{let I=d(v,D),F=await this.load(v,D,o,i.id,{actor:h,operation:"update",locale:f,includeTrashed:!1}),B=A(F,o,f);await this.assertAllowed(o,"update",h,f,B),j(o,{[a]:null},h,f.locale,B);let y=c.localized?u(u(F.data)[a])[f.locale]:u(F.data)[a];if(r==="add"){if(y===C)throw e.conflict(`"${C}" is this document's slug already, not a previous one.`);await Ce({db:I,collection:o,documentId:String(F.id),field:a,locale:g,slug:C}),await we(I,o,String(F.id),[{field:a,locale:g,from:C,to:String(y??"")}],new Date)}else await Le(I,o,String(F.id),a,g,C)}),this.previousSlugs(o,{id:i.id,field:a,...i.actor===void 0?{}:{actor:i.actor},...c.localized?{locale:f.locale}:{}})}async find(o,i={}){let r=await this.options.database(),a=O(this.options.config,i),c=i.actor??null,f=await _(o,{actor:c,operation:"read",locale:a.locale,rbac:this.options.config.rbac}),h=this.scope(o,i.where,f,i.includeTrashed),g=Nt(i.orderBy),C=qt(i.limit);return r.transaction(async(v)=>{let D=await r.query(v,{table:p,where:i.cursor?s(h,J(i.cursor,g)):h,orderBy:g,limit:C+1,...i.offset===void 0?{}:{offset:i.offset}}),I=D.length>C,F=D.slice(0,C),B=F.map((W)=>A(W,o,a));await this.expand(r,v,B,o,a,i,c),this.redact(B,o,c,a);let y=null;if(i.count===!0){let W=await r.query(v,{table:p,where:h,count:!0});y=Number(W[0]?.count??0)}let P=F.at(-1);return{docs:B,limit:C,totalDocs:y,hasNextPage:I,cursor:P?V(P,g):null}})}async findOne(o,i={}){return(await this.find(o,{...i,limit:1})).docs[0]??null}async findById(o,i,r={}){return this.findOne(o,{...r,where:t("id",i)})}async count(o,i={}){let r=await this.options.database(),a=O(this.options.config,i),c=await _(o,{actor:i.actor??null,operation:"read",locale:a.locale,rbac:this.options.config.rbac}),f=this.scope(o,i.where,c,i.includeTrashed);return r.transaction(async(h)=>{let g=await r.query(h,{table:p,where:f,count:!0});return Number(g[0]?.count??0)})}async create(o,i){let r=O(this.options.config,i),a=i.actor??null,c={...i.data};return this.runWrite({collection:o,intent:"create",actor:a,source:i.source??"local",locale:r,depth:i.depth,includeTrashed:i.includeTrashed,runId:i.runId,idempotencyKey:i.idempotencyKey,step:async({db:f,hooks:h,context:g})=>{await this.assertAllowed(o,"create",a,r),j(o,c,a,r.locale);let C=await Ie(h.createBefore,{data:c},g,(P,W)=>({...P,data:W}));if(C===!1)return null;let v=i.id??b("doc"),D=await be({db:f,collection:o,input:C.data,stored:null,locale:r.locale,documentId:v}),{data:I,touched:F}=$e(o,D.input,r);Je(o,I,r,Object.keys(o.fields));let B=new Date,y=await f.insert(p,{id:v,collection:o.slug,data:I,created_at:B,updated_at:B,updated_by:a?.id??null,deleted_at:null,purge_after:null,scheduled_at:null,scheduled_patch:null,revision:1});return{doc:A(y,o,r),previous:null,changed:F,stored:I}}})}async update(o,i,r){let a=O(this.options.config,i),c=i.actor??null,f={...i.data};return this.runWrite({collection:o,intent:"update",actor:c,source:i.source??"local",locale:a,depth:i.depth,includeTrashed:i.includeTrashed,runId:i.runId,idempotencyKey:i.idempotencyKey,...r===void 0?{}:{emit:r},step:async({adapter:h,tx:g,db:C,hooks:v,context:D})=>{let I=await this.load(h,g,o,i.id,{actor:c,operation:"update",locale:a,includeTrashed:i.includeTrashed});Re(i.expectedRevision,I);let F=A(I,o,a);await this.assertAllowed(o,"update",c,a,F),j(o,f,c,a.locale,F);let B=await Ie(v.updateBefore,{data:f,previous:F},D,(L,N)=>({...L,data:N}));if(B===!1)return null;let y=await be({db:C,collection:o,input:B.data,stored:u(I.data),locale:a.locale,documentId:String(I.id)}),{data:P,touched:W}=$e(o,y.input,a,u(I.data));Je(o,P,a,W);let E=new Date,k=await this.patch(h,g,I,{data:P,updated_at:E,updated_by:c?.id??null},i.expectedRevision),T=A(k,o,a);return{doc:T,previous:F,changed:go(o,F,T),stored:P,slugMoves:y.moves}}})}async remove(o,i){if(!this.options.config.trash.enabled||i.permanent===!0)return this.purge(o,i);let a=O(this.options.config,i),c=i.actor??null;return this.runWrite({collection:o,intent:"trash",actor:c,source:i.source??"local",locale:a,depth:i.depth,includeTrashed:!0,runId:i.runId,idempotencyKey:i.idempotencyKey,step:async({adapter:f,tx:h,hooks:g,context:C})=>{let v=await this.load(f,h,o,i.id,{actor:c,operation:"delete",locale:a,includeTrashed:!1});Re(i.expectedRevision,v);let D=A(v,o,a);await this.assertAllowed(o,"delete",c,a,D);let I=await Ie(g.deleteBefore,D,C,(y,P)=>P);if(I===!1)return null;let F=new Date,B=await this.patch(f,h,v,{deleted_at:F,purge_after:this.purgeAt(F),scheduled_at:null,scheduled_patch:null,updated_at:F,updated_by:c?.id??null});return{doc:A(B,o,a),previous:I,changed:[]}}})}async restore(o,i){let r=O(this.options.config,i),a=i.actor??null;return this.runWrite({collection:o,intent:"restore",actor:a,source:i.source??"local",locale:r,depth:i.depth,includeTrashed:!0,runId:i.runId,idempotencyKey:i.idempotencyKey,step:async({adapter:c,tx:f})=>{let h=await this.load(c,f,o,i.id,{actor:a,operation:"restore",locale:r,includeTrashed:!0});if(Re(i.expectedRevision,h),h.deleted_at===null||h.deleted_at===void 0)throw e.conflict(`${o.name} "${i.id}" is not in the trash`);let g=A(h,o,r);await this.assertAllowed(o,"restore",a,r,g);let C=new Date,v=await this.patch(c,f,h,{deleted_at:null,purge_after:null,updated_at:C,updated_by:a?.id??null});return{doc:A(v,o,r),previous:g,changed:[],after:!1}}})}async purge(o,i,r={}){let a=O(this.options.config,i),c=i.actor??null;return this.runWrite({collection:o,intent:"purge",actor:c,source:i.source??"local",locale:a,depth:i.depth,includeTrashed:!0,step:async({adapter:f,tx:h,db:g,hooks:C,context:v})=>{let D=await this.load(f,h,o,i.id,{actor:c,operation:"purge",locale:a,includeTrashed:!0,bypassAccess:r.retention===!0}),I=A(D,o,a),F=D.deleted_at!==null&&D.deleted_at!==void 0;if(r.retention!==!0)await this.assertAllowed(o,F?"purge":"delete",c,a,I);let B=F?I:await Ie(C.deleteBefore,I,v,(y,P)=>P);if(B===!1)return null;return await g.delete(p,t("id",String(D.id))),{doc:B,previous:B,changed:[],after:!F,releaseMedia:!0}}})}async schedule(o,i){let r=O(this.options.config,i),a=i.actor??null,c=Ut(i.at),f={...i.data};if(Object.keys(f).length===0)throw e.validation("A scheduled change needs at least one field.");return this.runWrite({collection:o,intent:"schedule",actor:a,source:i.source??"local",locale:r,depth:i.depth,includeTrashed:!1,step:async({adapter:h,tx:g})=>{let C=await this.load(h,g,o,i.id,{actor:a,operation:"update",locale:r,includeTrashed:!1}),v=A(C,o,r);await this.assertAllowed(o,"update",a,r,v),j(o,f,a,r.locale,v);let D=$e(o,f,r,u(C.data));Je(o,D.data,r,D.touched);let I=new Date,F=await this.patch(h,g,C,{scheduled_at:c,scheduled_patch:{data:f,locale:r.locale,actor:a===null?null:{...a}},updated_at:I,updated_by:a?.id??null});return{doc:A(F,o,r),previous:v,changed:[],after:!1}}})}async unschedule(o,i){let r=O(this.options.config,i),a=i.actor??null;return this.runWrite({collection:o,intent:"unschedule",actor:a,source:i.source??"local",locale:r,depth:i.depth,includeTrashed:!1,step:async({adapter:c,tx:f})=>{let h=await this.load(c,f,o,i.id,{actor:a,operation:"update",locale:r,includeTrashed:!1});if(h.scheduled_at===null||h.scheduled_at===void 0)throw e.conflict(`${o.name} "${i.id}" has nothing scheduled`);let g=A(h,o,r);await this.assertAllowed(o,"update",a,r,g);let C=new Date,v=await this.patch(c,f,h,{scheduled_at:null,scheduled_patch:null,updated_at:C,updated_by:a?.id??null});return{doc:A(v,o,r),previous:g,changed:[],after:!1}}})}globalApi(o){return{get:(i)=>this.globalGet(o,i),update:async(i)=>{let r=await this.ensureGlobalRow(o,i);return this.update(o,{...i,id:r})},schedule:async(i)=>{let r=await this.ensureGlobalRow(o,i);return this.schedule(o,{...i,id:r})},unschedule:async(i={})=>this.unschedule(o,{...i,id:te(o)})}}async globalGet(o,i={}){let r=await this.options.database(),a=O(this.options.config,i),c=i.actor??null,f=await _(o,{actor:c,operation:"read",locale:a.locale,rbac:this.options.config.rbac});return r.transaction(async(h)=>{let C=(await r.query(h,{table:p,where:this.scope(o,t("id",te(o)),f,!1),limit:1}))[0]??this.emptyGlobalRow(o,a,null),v=A(C,o,a);return await this.expand(r,h,[v],o,a,i,c),this.redact([v],o,c,a),v})}async ensureGlobalRow(o,i){let r=await this.options.database(),a=O(this.options.config,i),c=te(o);if(await r.transaction(async(h)=>(await r.query(h,{table:p,where:t("id",c),limit:1})).length>0))return c;try{await r.transaction((h)=>r.mutate(h,{kind:"insert",table:p,returning:!1,values:this.emptyGlobalRow(o,a,new Date)}))}catch(h){if(!await r.transaction(async(C)=>(await r.query(C,{table:p,where:t("id",c),limit:1})).length>0))throw h}return c}emptyGlobalRow(o,i,r){let{data:a}=$e(o,{},i);return{id:te(o),collection:o.slug,data:a,created_at:r,updated_at:r,updated_by:null,deleted_at:null,purge_after:null,scheduled_at:null,scheduled_patch:null,revision:1}}async applyScheduled(o){let i=this.bySlug[String(o.collection)],r=je(o),a=o.scheduled_at;if(!i||!r||!(a instanceof Date)){await this.clearSchedule(String(o.id));return}let c=await this.options.database();if((await c.transaction((h)=>c.mutate(h,{kind:"update",table:p,where:s(t("id",String(o.id)),t("scheduled_at",a)),set:{scheduled_at:null,scheduled_patch:null},returning:!1}))).count!==1)return;await this.update(i,{id:String(o.id),data:r.data,locale:r.locale,actor:r.actor,source:"job"},(h,g)=>{h.emit("document.schedule.applied",{collection:i.name,documentId:String(g.doc.id),locale:r.locale,scheduledFor:a.toISOString(),patch:r.data})})}async purgeExpired(o){let i=this.bySlug[String(o.collection)];if(!i){let r=await this.options.database();await r.transaction(async(a)=>{let c=d(r,a);await c.delete(Mt,t("document_id",String(o.id))),await c.delete(p,t("id",String(o.id)))});return}await this.purge(i,{id:String(o.id),actor:null,source:"job",includeTrashed:!0},{retention:!0})}async clearSchedule(o){let i=await this.options.database();await i.transaction((r)=>i.mutate(r,{kind:"update",table:p,where:t("id",o),set:{scheduled_at:null,scheduled_patch:null},returning:!1}))}async recordFailure(o,i,r){let a=r instanceof Error?r.message:String(r),c=await this.options.database(),f=new Date;await c.transaction(async(h)=>{await d(c,h).insert("jobs",{id:ve("job"),type:o,payload:i,status:"failed",run_at:f,attempts:1,locked_at:null,locked_by:null,completed_at:null,error:a,created_at:f}),await this.appendEvents(h,[{type:"job.failed",data:{job:o,error:a,...i},previous:null}],{actor:null})}),this.scheduleDelivery()}async runWrite(o){let i=await this.options.database(),r=await this.outboxWorker(),a=this.pipeline(o.collection.name),c=new pt,f=await i.transaction(async(h)=>{let g=d(i,h),C=await this.replay(g,o);if(C)return C;let v={actor:o.actor,collection:o.collection.name,operation:Ke[o.intent],locale:o.locale.locale,tx:h,db:g,cms:this.instance(),events:c,source:o.source,meta:{}},D=await o.step({adapter:i,tx:h,db:g,hooks:a,context:v});if(D===null)return null;if(this.emitDocumentEvents(c,o,D),await this.syncMedia(g,o,D,c),await this.syncSlugs(g,o,D),o.emit?.(c,D),await r.append(h,c.take(),this.outboxMeta(o,D)),D.after!==!1)await this.runAfter(a,o,D,v);return await r.append(h,c.take(),this.outboxMeta(o,D)),await this.writeActivity(g,o,D),await this.recordIdempotency(g,o,D),await this.expand(i,h,[D.doc],o.collection,o.locale,o,o.actor),D});if(!f)return null;if(!("replayed"in f))this.scheduleDelivery();return this.redact([f.doc],o.collection,o.actor,o.locale),f.doc}async replay(o,i){let r=i.idempotencyKey;if(r===void 0)return null;let a=await o.findOne(Ue,t("idempotency_key",r));if(!a)return null;return{doc:u(a.result),previous:null,changed:[],replayed:!0}}async recordIdempotency(o,i,r){let a=i.idempotencyKey;if(a===void 0)return;await o.insert(Ue,{id:b("aim"),idempotency_key:a,run_id:i.runId??"",collection:i.collection.name,document_id:String(r.doc.id),result:r.doc,created_at:new Date})}async runAfter(o,i,r,a){let c=Ke[i.intent];if(c==="create"){await He(o.createAfter,r.doc,a);return}if(c==="update"){await He(o.updateAfter,{doc:r.doc,previous:r.previous},a);return}await He(o.deleteAfter,r.doc,a)}emitDocumentEvents(o,i,r){let a=(f)=>({collection:i.collection.name,documentId:String(r.doc.id),locale:i.locale.locale,document:ce(f)});switch(i.intent){case"create":{o.emit("document.created",a(r.doc),null);return}case"trash":{o.emit("document.trashed",{...a(r.doc),purgeAfter:r.doc.purgeAfter??null},null);return}case"restore":{o.emit("document.restored",a(r.doc),null);return}case"purge":{o.emit("document.purged",a(r.doc),null);return}case"schedule":{o.emit("document.scheduled",{...a(r.doc),scheduledAt:r.doc.scheduledAt??null,patch:ce(r.doc.scheduledPatch??null)},null);return}case"unschedule":{o.emit("document.schedule.cancelled",{...a(r.doc),scheduledAt:r.previous?.scheduledAt??null},null);return}case"update":break}let c=r.previous;o.emit("document.updated",a(r.doc),a(c));for(let f of r.changed)o.emit("document.field.changed",{collection:i.collection.name,documentId:String(r.doc.id),locale:i.locale.locale,field:f,value:ce(r.doc[f]??null)},{field:f,value:ce(c[f]??null)})}async syncMedia(o,i,r,a){let c=this.options.config.uploads,f=r.releaseMedia===!0;if(!f&&r.stored===void 0)return;if(!f&&!this.referencesMedia(i.collection))return;let h=await nn({db:o,collection:i.collection.name,documentId:String(r.doc.id),references:f?null:tn(i.collection,r.stored??{}),lifecycle:c!==void 0,retention:c?.retention,now:new Date}),g=(C)=>({mediaId:C,collection:i.collection.name,documentId:String(r.doc.id)});for(let C of h.orphaned)a.emit("media.orphaned",g(C));for(let C of h.reclaimed)a.emit("media.reclaimed",g(C))}async syncSlugs(o,i,r){if(!this.keepsSlugHistory(i.collection))return;let a=String(r.doc.id);if(r.releaseMedia===!0){await Me(o,i.collection,a);return}if(r.slugMoves&&r.slugMoves.length>0)await we(o,i.collection,a,r.slugMoves,new Date)}keepsSlugHistory(o){return ae(o).some(([,i])=>ee(i).history===!0)}referencesMedia(o){let i=this.media.get(o.name);if(i!==void 0)return i;let r=en(o);return this.media.set(o.name,r),r}async writeActivity(o,i,r){await o.insert(Lt,{id:ve("act"),actor_id:i.actor?.id??null,actor_source:i.actor?.source??null,action:Qt(i.intent),source:i.source,collection:i.collection.name,document_id:String(r.doc.id),locale:i.locale.locale,changes:{fields:r.changed,...i.runId===void 0?{}:{runId:i.runId}},ip:null,created_at:new Date})}scope(o,i,r,a){let c=[t("collection",o.slug)];if(a!==!0)c.push(t("deleted_at",null));if(i)c.push(i);if(r)c.push(r);return s(...c)}async load(o,i,r,a,c){let f=c.bypassAccess===!0?void 0:await _(r,{actor:c.actor,operation:c.operation,locale:c.locale.locale,rbac:this.options.config.rbac}),g=(await o.query(i,{table:p,where:this.scope(r,t("id",a),f,c.includeTrashed),limit:1}))[0];if(!g)throw e.notFound(`No ${r.name} with id "${a}"`);return g}async patch(o,i,r,a,c){let f=hn(r.revision),h=f+1,g=String(r.id),C=await o.mutate(i,{kind:"update",table:p,where:c===void 0?t("id",g):s(t("id",g),t("revision",c)),set:{...a,revision:h}});if(c!==void 0&&C.count===0)throw Ve(c,f);return C.rows[0]??{...r,...a,revision:h}}async assertAllowed(o,i,r,a,c){if(await _(o,{actor:r,operation:i,locale:a.locale,rbac:this.options.config.rbac,...c===void 0?{}:{record:c}})&&i==="create")throw new e(`access.create on "${o.name}" returned a filter; a create has no row to filter. Return true or false.`,{status:500,code:"invalid_access_rule"})}requireCollection(o){let i=this.byName[o];if(!i)throw e.notFound(`No collection named "${o}"`);return i}purgeAt(o){let i=this.options.config.trash.purgeAfter;if(i===!1)return null;return new Date(o.getTime()+w(i))}async expand(o,i,r,a,c,f,h){if(!f.depth)return;await new ft({adapter:o,tx:i,locale:c,actor:h,rbac:this.options.config.rbac,collections:this.byName,...f.includeTrashed===void 0?{}:{includeTrashed:f.includeTrashed}}).expand(r,a,f.depth)}redact(o,i,r,a){if(!on(i))return;for(let c of o)fe(c,i,r,a.locale)}pipeline(o){let i=this.pipelines.get(o);if(i)return i;let r=dt(this.options.config,o);return this.pipelines.set(o,r),r}outboxMeta(o,i){return{actor:o.actor,collection:o.collection.name,documentId:String(i.doc.id)}}async outboxWorker(){if(this.outbox)return this.outbox;let o=await this.options.database();return this.outbox=new mt(o,this.options.dispatch),this.outbox}scheduleDelivery(){this.delivery=this.delivery.then(async()=>{await(await this.outboxWorker()).drain()}).catch(()=>{return})}instance(){if(!this.cms)throw new e("The engine was used before it was bound.",{status:500,code:"engine_unbound"});return this.cms}}function te(o){return`glb_${o.slug}`}function Nt(o){let i=o&&o.length>0?[...o]:[{path:"updated_at",direction:"desc"}];if(!i.some((r)=>r.path==="id"))i.push({path:"id",direction:i[i.length-1]?.direction??"desc"});return i}function qt(o){if(o===void 0)return Et;if(!Number.isInteger(o)||o<1)throw new e(`limit must be a positive integer, received ${o}`,{status:400,code:"invalid_pagination"});return Math.min(o,Ft)}function Ut(o){let i=o instanceof Date?o:new Date(o);if(Number.isNaN(i.getTime()))throw e.validation(`"${String(o)}" is not a date`);return i}function Ve(o,i){return new e(`This document has changed since you read it (expected revision ${o}, found ${i}). Reload it and apply your change again.`,{status:409,code:"revision_conflict",details:{expectedRevision:o,revision:i}})}function Re(o,i){if(o===void 0)return;if(!Number.isInteger(o)||o<1)throw e.validation(`expectedRevision has to be a positive integer, received ${String(o)}.`);let r=hn(i.revision);if(r!==o)throw Ve(o,r)}function Qt(o){switch(o){case"create":return"document.created";case"update":return"document.updated";case"trash":return"document.trashed";case"restore":return"document.restored";case"purge":return"document.purged";case"schedule":return"document.scheduled";case"unschedule":return"document.schedule.cancelled"}}function ce(o){return JSON.parse(JSON.stringify(o??null))}var Ht={af:"Afrikaans",am:"Amharic",ar:"Arabic",az:"Azerbaijani",be:"Belarusian",bg:"Bulgarian",bn:"Bengali",bs:"Bosnian",ca:"Catalan",cs:"Czech",cy:"Welsh",da:"Danish",de:"German",el:"Greek",en:"English",eo:"Esperanto",es:"Spanish",et:"Estonian",eu:"Basque",fa:"Persian",fi:"Finnish",fil:"Filipino",fo:"Faroese",fr:"French",ga:"Irish",gl:"Galician",gu:"Gujarati",he:"Hebrew",hi:"Hindi",hr:"Croatian",hu:"Hungarian",hy:"Armenian",id:"Indonesian",is:"Icelandic",it:"Italian",ja:"Japanese",ka:"Georgian",kk:"Kazakh",km:"Khmer",kn:"Kannada",ko:"Korean",ku:"Kurdish",ky:"Kyrgyz",lo:"Lao",lt:"Lithuanian",lv:"Latvian",mk:"Macedonian",ml:"Malayalam",mn:"Mongolian",mr:"Marathi",ms:"Malay",mt:"Maltese",my:"Burmese",nb:"Norwegian Bokmål",ne:"Nepali",nl:"Dutch",nn:"Norwegian Nynorsk",no:"Norwegian",pa:"Punjabi",pl:"Polish",ps:"Pashto",pt:"Portuguese",ro:"Romanian",ru:"Russian",si:"Sinhala",sk:"Slovak",sl:"Slovenian",sq:"Albanian",sr:"Serbian",sv:"Swedish",sw:"Swahili",ta:"Tamil",te:"Telugu",th:"Thai",tk:"Turkmen",tl:"Tagalog",tr:"Turkish",tt:"Tatar",uk:"Ukrainian",ur:"Urdu",uz:"Uzbek",vi:"Vietnamese",zh:"Chinese",zu:"Zulu"},Xt={AR:"Argentina",AT:"Austria",AU:"Australia",BE:"Belgium",BR:"Brazil",CA:"Canada",CH:"Switzerland",CL:"Chile",CN:"China",CO:"Colombia",CZ:"Czechia",DE:"Germany",DK:"Denmark",ES:"Spain",FI:"Finland",FR:"France",GB:"United Kingdom",HK:"Hong Kong",IE:"Ireland",IN:"India",IT:"Italy",JP:"Japan",KR:"South Korea",MX:"Mexico",NL:"Netherlands",NO:"Norway",NZ:"New Zealand",PL:"Poland",PT:"Portugal",RU:"Russia",SE:"Sweden",TW:"Taiwan",UA:"Ukraine",US:"United States",ZA:"South Africa"},rn=new Set(["ar","arc","dv","fa","he","ku","ps","sd","ug","ur","yi"]);function Bt(o){let i=Ht[o];if(i)return i;let[r,a]=o.split("-"),c=r===void 0?void 0:Ht[r.toLowerCase()];if(!c)return o;if(a===void 0)return c;let f=a.toUpperCase();return`${c} (${Xt[f]??f})`}function Vt(o){let i=o.split("-")[0];return i!==void 0&&rn.has(i.toLowerCase())}function xn(o){return o.i18n.locales.map((i)=>({code:i,name:Bt(i),rtl:Vt(i),isDefault:i===o.i18n.defaultLocale}))}var q="webhooks",U="webhook_deliveries",an=25,ln=200,cn=5,dn="10s";function Gt(o){let{config:i}=o,r=(y,P)=>(o.fetch??globalThis.fetch)(y,P),a=o.now??(()=>new Date),c=i.webhooks,f=c?.delivery?.retries??cn,h=w(c?.delivery?.timeout??dn),g=c?.delivery?.dlq!==!1,C=c?.delivery?.backoff==="linear",v=()=>{if(c?.enabled)return;throw new e("Webhooks are switched off; set webhooks.enabled to true.",{status:501,code:"webhooks_disabled"})},D=(y)=>C?y*30000:Math.min(3600000,1000*2**y),I=async()=>{let y=await o.database();return y.transaction((P)=>y.query(P,{table:q,where:t("active",!0)}))},F=async(y,P,W,E=a())=>{let k=await o.database(),T=Number(y.attempt??0)+1;if((await k.transaction((z)=>k.mutate(z,{kind:"update",table:U,where:s(t("id",String(y.id)),t("status","pending"),t("attempt",Number(y.attempt??0)),t("next_attempt_at",y.next_attempt_at==null?null:new Date(l(y.next_attempt_at))),R(t("next_attempt_at",null),M("next_attempt_at",E))),set:{attempt:T,next_attempt_at:new Date(E.getTime()+h+30000)},returning:!1}))).count!==1)return ie(y);if(T>f){let z={status:"failed",next_attempt_at:null,error:"Delivery lease expired; attempt budget exhausted."};return await k.transaction((re)=>d(k,re).update(U,s(t("id",String(y.id)),t("attempt",T)),z)),ie({...y,...z,attempt:T})}let N=typeof P.secret==="string"&&P.secret||c?.signing?.secret||"",G={"content-type":"application/json","user-agent":"heyo-cms","x-heyo-event-id":String(y.event_id),"x-heyo-event-type":String(y.event_type),"x-heyo-delivery-id":String(y.id),"x-heyo-attempt":String(T),...gn(P.headers)};if(N.length>0)G[Ae]=await ke(W,N);let K=null,ue=null,ne=null;try{let z=await r(String(P.url),{method:"POST",headers:G,body:W,signal:AbortSignal.timeout(h)});if(K=z.status,ue=await pn(z),!z.ok)ne=`Responded ${z.status}.`}catch(z){ne=z instanceof Error?z.message:String(z)}let xe=ne===null,pe=T>=f,Oe=a(),Pe=xe?{status:"delivered",attempt:T,response_status:K,response_body:ue,error:null,next_attempt_at:null,delivered_at:Oe}:{status:pe?"failed":"pending",attempt:T,response_status:K,response_body:ue,error:ne,next_attempt_at:pe?null:new Date(Oe.getTime()+D(T)),delivered_at:null},st=await k.transaction(async(z)=>(await d(k,z).update(U,s(t("id",String(y.id)),t("status","pending"),t("attempt",T)),Pe),{...y,...Pe}));if(!xe&&pe&&g)await(await o.database()).transaction((re)=>o.emit(re,[{type:"job.failed",data:{job:"webhook-delivery",webhookId:String(y.webhook_id),deliveryId:String(y.id),eventId:String(y.event_id),eventType:String(y.event_type),attempts:T,error:ne??"unknown"},previous:null}],{actor:null})),o.deliver();return ie(st)},B=async(y,P)=>{let W=await o.database(),E=JSON.stringify(P),k=`whd_${P.id}_${String(y.id)}`,T=await W.transaction((N)=>d(W,N).findOne(U,t("id",k)));if(T)return ie(T);let L=await W.transaction(async(N)=>d(W,N).insert(U,{id:k,webhook_id:String(y.id),event_id:P.id,event_type:P.type,status:"pending",attempt:0,request_body:P,response_status:null,response_body:null,error:null,next_attempt_at:a(),delivered_at:null,created_at:a()}));return F(L,y,E)};return{get enabled(){return c?.enabled===!0},async list(y={}){v();let P=await o.database();return(await P.transaction((E)=>P.query(E,{table:q,...y.active===void 0?{}:{where:t("active",y.active)},orderBy:[m("created_at","desc"),m("id","desc")]}))).map(de)},async get(y){v();let P=await o.database(),W=await P.transaction(async(E)=>d(P,E).findOne(q,t("id",y)));return W?de(W):null},async create(y){v(),Ze(y.url),Qe(y.events);let P=await o.database(),W=a();return await P.transaction(async(k)=>{let L=await d(P,k).insert(q,{id:b("whk"),url:y.url,events:y.events,filters:y.filters??null,headers:y.headers??null,secret:y.secret??null,active:y.active!==!1,created_at:W,updated_at:W});return de(L)})},async update(y){if(v(),y.url!==void 0)Ze(y.url);if(y.events!==void 0)Qe(y.events);let P=await o.database();return P.transaction(async(W)=>{let E=d(P,W),k=await E.findOne(q,t("id",y.id));if(!k)throw e.notFound("No such webhook.");let T={updated_at:a()};if(y.url!==void 0)T.url=y.url;if(y.events!==void 0)T.events=y.events;if(y.filters!==void 0)T.filters=y.filters;if(y.headers!==void 0)T.headers=y.headers;if(y.secret!==void 0)T.secret=y.secret;if(y.active!==void 0)T.active=y.active;await E.update(q,t("id",y.id),T);let L=await E.findOne(q,t("id",y.id));return de(L??{...k,...T})})},async remove(y){v();let P=await o.database();return P.transaction(async(W)=>{let E=d(P,W);return await E.delete(U,t("webhook_id",y.id)),await E.delete(q,t("id",y.id))>0})},async deliveries(y={}){v();let P=await o.database(),W=Math.min(ln,Math.max(1,y.limit??an)),E=[m("created_at","desc"),m("id","desc")],k=[];if(y.webhookId)k.push(t("webhook_id",y.webhookId));if(y.status)k.push(t("status",y.status));if(y.eventId)k.push(t("event_id",y.eventId));let T=k.length===0?void 0:s(...k),L=await P.transaction((K)=>P.query(K,{table:U,...y.cursor?{where:T===void 0?J(y.cursor,E):s(T,J(y.cursor,E))}:T===void 0?{}:{where:T},orderBy:E,limit:W+1})),N=L.slice(0,W),G=N.at(-1);return{entries:N.map((K)=>ie(K,y.includeBody===!0)),limit:W,hasNextPage:L.length>W,cursor:G?V(G,E):null}},async test(y){v();let P=await o.database(),W=await P.transaction(async(T)=>d(P,T).findOne(q,t("id",y.id)));if(!W)throw e.notFound("No such webhook.");let E=y.actor??null,k={id:b("evt"),type:"webhook.test",createdAt:a().toISOString(),actor:E?{id:E.id,source:E.source}:null,data:{message:"A test delivery from Heyo CMS. Verify the signature exactly as you would for a real event.",webhookId:String(W.id)},previous:null};return B(W,k)},async retry(y){v();let P=await o.database(),{delivery:W,subscription:E}=await P.transaction(async(L)=>{let N=d(P,L),G=await N.findOne(U,t("id",y.id));if(!G)throw e.notFound("No such delivery.");let K=await N.findOne(q,t("id",String(G.webhook_id)));if(!K)throw e.notFound("That webhook is gone.");return{delivery:G,subscription:K}}),k=JSON.stringify(W.request_body??{}),T=await P.transaction(async(L)=>d(P,L).insert(U,{id:ve("whd"),webhook_id:String(E.id),event_id:String(W.event_id),event_type:String(W.event_type),status:"pending",attempt:0,request_body:W.request_body??null,response_status:null,response_body:null,error:null,next_attempt_at:a(),delivered_at:null,created_at:a()}));return F(T,E,k)},async attemptDelivery(y,P=a()){let W=await o.database(),E=await W.transaction(async(k)=>{let T=d(W,k),L=await T.findOne(U,t("id",y));if(!L||L.status!=="pending")return null;let N=await T.findOne(q,t("id",String(L.webhook_id)));return N?{row:L,subscription:N}:null});if(!E)return null;return F(E.row,E.subscription,JSON.stringify(E.row.request_body??{}),P)},async dispatch(y){if(c?.enabled!==!0)return;let P=await I();for(let W of P){if(!fn(W,y))continue;await B(W,y)}},async drain(y={}){let P={attempted:0,delivered:0,failed:0};if(c?.enabled!==!0)return P;let W=await o.database(),E=y.now??a(),k=await W.transaction((T)=>W.query(T,{table:U,where:s(t("status","pending"),R(t("next_attempt_at",null),M("next_attempt_at",E))),orderBy:[m("next_attempt_at","asc"),m("id","asc")],limit:y.limit??50}));for(let T of k){let L=await W.transaction(async(G)=>d(W,G).findOne(q,t("id",String(T.webhook_id))));if(!L)continue;P.attempted+=1;let N=await F(T,L,JSON.stringify(T.request_body??{}),E);if(N.status==="delivered")P.delivered+=1;else if(N.status==="failed")P.failed+=1}return P},async wants(y){if(c?.enabled!==!0)return!1;return(await I()).some((W)=>Xe(W,y))}}}async function pn(o){let i=o.body?.getReader();if(!i)return"";let r=[],a=0;try{while(a<2000){let{value:h,done:g}=await i.read();if(g)break;let C=h.slice(0,2000-a);r.push(C),a+=C.length}}finally{await i.cancel().catch(()=>{}),i.releaseLock()}let c=new Uint8Array(a),f=0;for(let h of r)c.set(h,f),f+=h.length;return new TextDecoder().decode(c)}function Xe(o,i){return Ye(o.events).some((a)=>{if(a==="*"||a===i)return!0;if(!a.endsWith("*"))return!1;return i.startsWith(a.slice(0,-1))})}function fn(o,i){if(!Xe(o,i.type))return!1;let r=o.filters??null;if(!r)return!0;let a=i.data;if(r.collections?.length){let c=typeof a.collection==="string"?a.collection:null;if(!c||!r.collections.includes(c))return!1}if(r.locales?.length){let c=mn(a);if(c.length>0&&!c.some((f)=>r.locales?.includes(f)))return!1}return!0}function mn(o){if(typeof o.locale==="string")return[o.locale];if(Array.isArray(o.locales))return o.locales.filter((i)=>typeof i==="string");return[]}function de(o){return{id:String(o.id),url:String(o.url),events:Ye(o.events),filters:o.filters?u(o.filters):null,headers:o.headers?u(o.headers):null,hasSecret:typeof o.secret==="string"&&o.secret.length>0,active:o.active===!0||o.active===1,createdAt:l(o.created_at),updatedAt:l(o.updated_at)}}function ie(o,i=!1){return{id:String(o.id),webhookId:String(o.webhook_id),eventId:String(o.event_id),eventType:String(o.event_type),status:String(o.status)??"pending",attempt:Number(o.attempt??0),responseStatus:o.response_status===null||o.response_status===void 0?null:Number(o.response_status),responseBody:o.response_body===null||o.response_body===void 0?null:String(o.response_body),error:o.error===null||o.error===void 0?null:String(o.error),nextAttemptAt:l(o.next_attempt_at),deliveredAt:l(o.delivered_at),createdAt:l(o.created_at),...i?{requestBody:o.request_body===null||o.request_body===void 0?null:u(o.request_body)}:{}}}function Ye(o){if(!Array.isArray(o))return[];return o.filter((i)=>typeof i==="string")}function gn(o){if(typeof o!=="object"||o===null)return{};let i={};for(let[r,a]of Object.entries(o)){if(r.toLowerCase().startsWith("x-heyo-"))continue;if(r.toLowerCase()===Ae)continue;if(typeof a==="string")i[r]=a}return i}function Ze(o){let i;try{i=new URL(o)}catch{throw e.validation(`"${o}" is not a URL.`)}if(i.protocol!=="https:"&&i.protocol!=="http:")throw e.validation("A webhook URL has to be http or https.")}function Qe(o){if(o.length===0)throw e.validation("A webhook has to subscribe to at least one event type.");for(let i of o)if(!/^[a-z][a-z0-9.]*\*?$|^\*$/.test(i))throw e.validation(`"${i}" is not an event type; use "document.updated", "document.*" or "*".`)}var bn="webhook_deliveries";function Kt(o){return{name:"webhook-retries",failureType:"webhook.delivery",failurePayload:(i)=>({deliveryId:String(i.id),webhookId:String(i.webhook_id),eventId:String(i.event_id),eventType:String(i.event_type),attempt:Number(i.attempt??0)}),due:async(i,r,a)=>{let c=await i.database();return c.transaction((f)=>c.query(f,{table:bn,where:s(t("status","pending"),R(t("next_attempt_at",null),M("next_attempt_at",r))),orderBy:[m("next_attempt_at","asc"),m("id","asc")],limit:a}))},run:async(i,r,a)=>{await o.attemptDelivery(String(r.id),a)}}}var yn=new Set(["activity","admin","ai","auth","globals","jobs","locales","media","openapi.json","panel","roles","trash","users","webhooks"]),wn=/^[a-z][a-z0-9_]*$/,Cn=/^[a-z][a-zA-Z0-9_]*$/,Sn=/^[a-z][a-z0-9-]*$/,kn=/^[a-z]{2,3}(-[A-Za-z0-9]{2,8})*$/;function Vn(o){return{...o,kind:"collection"}}function Gn(o){return{...o,kind:"global"}}function Kn(o){let i=An(o),r=Pt({collections:i.collections,globals:i.globals,pluginTables:i.plugins.flatMap((k)=>k.schema?.tables??[])}),a=new Map;for(let k of i.plugins)for(let[T,L]of Object.entries(k.events??{})){if(!L)continue;let N=a.get(T)??new Set;N.add(L),a.set(T,N)}let c,f,g=new ht({config:i,database:()=>E.database(),dispatch:async(k)=>{let T=[...a.get(k.type)??[],...a.get("*")??[]];for(let L of T)await L(k);await F.dispatch(k)}}),C=un({config:i,database:()=>E.database(),emit:(k,T,L)=>g.appendEvents(k,T,L),deliver:()=>g.deliverSoon()}),v=Yt({config:i,database:()=>E.database(),emit:(k,T,L)=>g.appendEvents(k,T,L),deliver:()=>g.deliverSoon()}),D=xn(i),I=De({database:()=>E.database()}),F=Gt({config:i,database:()=>E.database(),emit:(k,T,L)=>g.appendEvents(k,T,L),deliver:()=>g.deliverSoon()}),B=Rt({config:i,database:()=>E.database(),cms:()=>E,emit:(k,T,L)=>g.appendEvents(k,T,L),deliver:()=>g.deliverSoon()}),y=g.buildJobs();if(i.webhooks?.enabled)y.register(Kt(F));if(i.uploads)y.register(Zt({config:i,database:()=>E.database(),storage:()=>v.storage(),emit:(k,T,L)=>g.appendEvents(k,T,L),deliver:()=>g.deliverSoon()}));let P,W=()=>(P??=qe(E),P),E={_config:Object.freeze(i),schema:r,collections:o.collections,handler:(k)=>W().handler(k),_router:{routes:()=>W().routes()},api:g.buildApi(),globals:g.buildGlobals(),auth:C,media:v,ai:B,webhooks:F,trash:g.buildTrash(),jobs:y,locales:{list:()=>D},activity:I,inspect(){return{basePath:i.basePath,database:{id:c?.id??"unresolved",capabilities:c?.capabilities??{transactions:!1,sqlMigrations:!1,jsonQuery:!1}},storage:qn(i),collections:zn(i),schema:r,hooks:Wt(i),routes:W().routes(),admin:{path:`${i.basePath}${i.admin.path}`,panel:i.admin.assets?.id??null},plugins:Un(i),auth:Zn(i),ai:{enabled:i.ai!==void 0,defaultModel:i.ai?.defaultModel??null,assistant:i.ai!==void 0&&i.ai.assistant?.enabled!==!1,actions:me(),providers:Object.keys(i.ai?.auth??{}).sort(),panelManagedKeys:i.ai?.storage?.secret!==void 0},webhooks:{enabled:i.webhooks?.enabled===!0,signed:i.webhooks?.signing?.secret!==void 0,retries:i.webhooks?.delivery?.retries??5},editor:Te(),jobs:E.jobs.list(),trash:{enabled:i.trash.enabled,purgeAfter:i.trash.purgeAfter===!1?null:i.trash.purgeAfter}}},async database(){if(c)return c;return f??=Promise.resolve(typeof i.database==="function"?i.database():i.database).then((k)=>(k.useSchema(r),c=k,k)),f},on(k,T){let L=a.get(k)??new Set;return L.add(T),a.set(k,L),()=>{L.delete(T)}},drainEvents(k){return g.drainEvents(k)},async close(){await g.settle(),await c?.close?.(),c=void 0,f=void 0,a.clear()}};return g.bind(E),E}function An(o){let i=Nn(o.basePath??ge),r=new Set(ot()),a=o.plugins??[];jn(a);let c=Pn(o.collections,a),f=Tn({plugins:a,collections:c,globals:o.globals??{},basePath:i}),h={};for(let[v,D]of Object.entries(c))h[v]=nt(v,D,"collection",r);let g={};for(let[v,D]of Object.entries(o.globals??{}))g[v]=nt(v,D,"global",r);Rn({...h,...g}),Fn({...h,...g}),_n({...h,...g}),On(o,h,g),Dn({...h,...g}),In(o),Jn(o),Wn(o),En(o,i),Mn(o),Hn(o);let C=o.trash?.purgeAfter??"30d";if(typeof C==="string")w(C,"trash.purgeAfter");return{basePath:i,database:o.database,admin:{...o.admin,path:Bn(o.admin?.path??et)},...o.rbac===void 0?{}:{rbac:o.rbac},i18n:$n(o.i18n),...o.uploads===void 0?{}:{uploads:o.uploads.publicPath===void 0?o.uploads:{...o.uploads,publicPath:x(o.uploads.publicPath.trim())}},...o.ai===void 0?{}:{ai:o.ai},...o.webhooks===void 0?{}:{webhooks:o.webhooks},trash:{enabled:o.trash?.enabled??!0,purgeAfter:C},collections:h,globals:g,...o.hooks===void 0?{}:{hooks:o.hooks},...o.databaseHooks===void 0?{}:{databaseHooks:o.databaseHooks},plugins:a,pluginHooks:f,...o.telemetry===void 0?{}:{telemetry:o.telemetry},migrationsDirectory:o.migrations?.directory??tt}}function nt(o,i,r,a){if(!wn.test(o))throw new n(`collections.${o}`,"a collection name must be lowercase letters, digits and underscores, starting with a letter");let c=i.slug??o.replaceAll("_","-");if(!Sn.test(c))throw new n(`collections.${o}.slug`,`"${c}" is not a URL-safe slug`);if(a.has(o)||a.has(c))throw new n(`collections.${o}`,`"${o}" is a reserved system name; pick another`);if(yn.has(c))throw new n(`collections.${o}`,`"${c}" is a URL the CMS serves itself; give the collection another slug`);let f={};for(let[h,g]of Object.entries(i.fields)){if(!Cn.test(h))throw new n(`collections.${o}.fields.${h}`,"a field name must be letters, digits and underscores, starting with a lowercase letter");if(g.required&&g.admin?.hidden===!0)throw new n(`collections.${o}.fields.${h}.admin.hidden`,"a hidden field cannot be required; remove required or show the field");f[h]=g}if(Object.keys(f).length===0)throw new n(`collections.${o}.fields`,"a collection needs at least one field");return{name:o,slug:c,label:i.label??Qn(o),kind:r,fields:f,access:i.access??{},...i.admin===void 0?{}:{admin:i.admin}}}function Rn(o){let i=new Map;for(let r of Object.values(o)){let a=i.get(r.slug);if(a)throw new n(`collections.${r.name}.slug`,`"${r.slug}" is already used by "${a}"; slugs are URLs and index names`);i.set(r.slug,r.name)}}function _n(o){let i=new Set([...Object.keys(o),...ot()]);for(let r of Object.values(o))for(let[a,c]of Object.entries(r.fields)){if(!c.relationTo)continue;if(!i.has(c.relationTo))throw new n(`collections.${r.name}.fields.${a}`,`relation points at "${c.relationTo}", which is not a collection`)}}function On(o,i,r){for(let a of Object.keys(o.databaseHooks??{}))if(!(a in i)&&!(a in r))throw new n(`databaseHooks.${a}`,"no collection or global with this name")}function Pn(o,i){let r={...o},a=new Map;for(let c of i)for(let[f,h]of Object.entries(c.schema?.collections??{})){if(f in o)throw new n(`plugins.${c.id}.schema.collections.${f}`,`the configuration already declares a collection called "${f}"`);let g=a.get(f);if(g)throw new n(`plugins.${c.id}.schema.collections.${f}`,`"${g}" already declares a collection called "${f}"`);a.set(f,c.id),r[f]=h}return r}function Tn(o){let i=[],r=new Map;for(let a of o.plugins){if(!a.extendCollections)continue;let c=a.extendCollections({collections:o.collections,basePath:o.basePath});for(let f of c){let h=o.collections[f.collection]??o.globals[f.collection];if(!h)throw new n(`plugins.${a.id}.extendCollections`,`patches "${f.collection}", which is not a collection or a global`);for(let[g,C]of Object.entries(f.fields??{})){let v=r.get(`${f.collection}.${g}`);if(g in h.fields)throw new n(`plugins.${a.id}.extendCollections`,v?`"${v}" already added "${g}" to ${f.collection}`:`${f.collection} already has a field called "${g}"`);r.set(`${f.collection}.${g}`,a.id),h.fields={...h.fields,[g]:C}}if(f.hooks)i.push({plugin:a.id,collection:f.collection,hooks:f.hooks,priority:0})}}return i}function Dn(o){for(let i of Object.values(o))for(let[r,a]of Object.entries(i.fields)){if(a.aiGenerate!==void 0)it(i,r,a.aiGenerate,`collections.${i.name}.fields.${r}.aiGenerate`);for(let[c,f]of Object.entries(a.ai??{})){if(f!==!0)it(i,r,f,`collections.${i.name}.fields.${r}.ai.${c}`);let h=Z(c),g=`collections.${i.name}.fields.${r}.ai.${c}`;if(!h){if(f===!0||f.prompt===void 0)throw new n(g,"is not a registered AI action; register it with defineAiAction() or give it a prompt");continue}if(!h.appliesTo.includes("*")&&!h.appliesTo.includes(a.type))throw new n(g,`does not apply to a ${a.type} field; it applies to ${h.appliesTo.join(", ")}`);if(h.requiresLocalized&&!a.localized)throw new n(g,"needs a localized field; this one stores a single value for every language")}}}function it(o,i,r,a){if(r.context!==void 0&&!Array.isArray(r.context))throw new n(`${a}.context`,"must be an array of field names");let c=new Set;for(let f of r.context??[]){if(typeof f!=="string"||!o.fields[f]||f===i||c.has(f))throw new n(`${a}.context`,`"${f}" must name a different, existing field of ${o.name} (only once)`);c.add(f)}if(r.maxLength!==void 0&&(!Number.isInteger(r.maxLength)||r.maxLength<1))throw new n(`${a}.maxLength`,"must be a positive integer");if(r.model&&(!r.model.provider||!r.model.model))throw new n(`${a}.model`,"needs a provider and a model")}function jn(o){let i=new Set;for(let a of o){if(i.has(a.id))throw new n(`plugins.${a.id}`,"two plugins share this id");i.add(a.id)}let r=new Map;for(let a of o)for(let c of a.routes??[]){let f=`${c.method} ${c.root===!0?"(root) ":""}${c.path}`,h=r.get(f);if(h)throw new n(`plugins.${a.id}.routes`,`"${f}" is already registered by "${h}"`);r.set(f,a.id)}}function $n(o){let i=o?.locales,r=o?.defaultLocale??i?.[0]??"en";return{defaultLocale:r,locales:i??[r]}}function In(o){let i=o.i18n;if(!i)return;let r=i.locales;if(r!==void 0){if(r.length===0)throw new n("i18n.locales","at least one locale; leave the section out for a single-language site");for(let c of r)if(!kn.test(c))throw new n("i18n.locales",`"${c}" is not a locale code; use a BCP 47 tag such as "en" or "pt-BR"`);if(new Set(r).size!==r.length)throw new n("i18n.locales","duplicate locale codes")}let a=i.defaultLocale;if(a!==void 0&&r&&!r.includes(a))throw new n("i18n.defaultLocale",`"${a}" is not in i18n.locales (${r.map((c)=>`"${c}"`).join(", ")})`)}function Jn(o){let i=o.rbac;if(!i)return;for(let[r,a]of Object.entries(i.roles)){if(!/^[a-z][a-z0-9_-]*$/.test(r))throw new n(`rbac.roles.${r}`,"a role name must be lowercase letters, digits, dashes and underscores, starting with a letter");for(let c of a){if(c==="*")continue;if(!/^[a-z0-9_*-]+:[a-z0-9_*-]+$/.test(c))throw new n(`rbac.roles.${r}`,`"${c}" is not a permission; use "collection:action" or "*"`)}}if(i.defaultRole&&!(i.defaultRole in i.roles))throw new n("rbac.defaultRole",`"${i.defaultRole}" is not one of the configured roles`)}function Wn(o){let i=o.admin?.auth;if(!i)return;let r=new Set;for(let a of i.methods){if(r.has(a))throw new n("admin.auth.methods",`"${a}" is listed twice`);r.add(a)}for(let a of i.apiKeys?.scopes??[])if(!_e(a))throw new n("admin.auth.apiKeys.scopes",`"${a}" is not a scope; use "read", "write", "delete", "*" or "collection:action"`);if(i.sso?.mapRoles&&!o.rbac)throw new n("admin.auth.sso.mapRoles","maps claims onto roles, but no roles are configured; add rbac.roles")}function En(o,i){let r=o.uploads;if(!r)return;if(r.publicPath!==void 0)Ln(r.publicPath,i);if(r.limits?.maxFileSize)se(r.limits.maxFileSize,"uploads.limits.maxFileSize");let a=r.retention?.purgeAfter;if(typeof a==="string")w(a,"uploads.retention.purgeAfter");let c=r.images,f=c?.quality;if(f!==void 0&&(f<1||f>100))throw new n("uploads.images.quality","must be between 1 and 100");for(let[h,g]of Object.entries(c?.variants?.sizes??{})){if(!/^[a-z][a-z0-9-]*$/.test(h))throw new n(`uploads.images.variants.sizes.${h}`,"a size name ends up in a URL; use lowercase letters, digits and dashes");if(to.includes(h))throw new n(`uploads.images.variants.sizes.${h}`,`"${h}" is a media endpoint; pick another size name`);if(g.width===void 0&&g.height===void 0)throw new n(`uploads.images.variants.sizes.${h}`,"needs a width, a height, or both");if(g.fit==="cover"&&(g.width===void 0||g.height===void 0))throw new n(`uploads.images.variants.sizes.${h}`,'fit: "cover" needs both a width and a height')}if(c&&!c.processor){let h=c.convert!==void 0?"convert":c.maxDimensions!==void 0?"maxDimensions":c.variants?.mode==="pregenerate"?'variants.mode: "pregenerate"':null;if(h)throw new n("uploads.images.processor",`${h} has to render pixels, and nothing here can. Add a processor from "@heyo-sh/heyo-cms/uploads" (sharpImages() on Node, cloudflareImages() on Workers), or drop the option.`)}}function Fn(o){for(let i of Object.values(o))for(let[r,a]of Object.entries(i.fields)){if(a.type!=="slug")continue;let c=a.options.from;if(c===void 0)continue;let f=i.fields[String(c)],h=`collections.${i.name}.fields.${r}.from`;if(!f||c===r)throw new n(h,`"${String(c)}" is not another field of ${i.name}`);if(!["text","textarea","email","url","select"].includes(f.type))throw new n(h,`"${String(c)}" is a ${f.type} field; a slug is made from text`)}}function Ln(o,i){let r=x(o.trim()),a="uploads.publicPath";if(r.length===0&&o.trim().startsWith("/"))throw new n("uploads.publicPath",'cannot be "/"; use a path such as "/media"');if(!r.startsWith("/"))throw new n("uploads.publicPath",'must start with "/"');if(!r.split("/").slice(1).every((h)=>/^[A-Za-z0-9._~-]+$/.test(h)))throw new n("uploads.publicPath","may only contain letters, digits, dots, dashes, underscores and tildes between slashes");let f=(h,g)=>h===g||h.startsWith(`${g}/`);if(f(r,i)||f(i,r))throw new n("uploads.publicPath",`"${r}" overlaps basePath "${i}"; files are served from <basePath>/media already — pick a path outside it, such as "/media"`)}function Mn(o){let i=o.ai;if(!i)return;let r=new Set(Object.keys(i.auth??{})),a=i.storage?.secret!==void 0;if(r.size===0&&!a&&i.complete===void 0)throw new n("ai.auth","AI is configured without credentials. Add ai.auth, set ai.storage.secret to manage keys in the panel, or remove the section to disable AI");if(!a&&i.complete===void 0&&!r.has(i.defaultModel.provider))throw new n("ai.defaultModel.provider",`"${i.defaultModel.provider}" has no entry in ai.auth`);let c=i.assistant,f=c?.model?.provider;if(f&&!a&&i.complete===void 0&&!r.has(f))throw new n("ai.assistant.model.provider",`"${f}" has no entry in ai.auth`);for(let[h,g]of[["maxTurns",1],["maxToolCalls",1],["timeoutMs",1000]]){let C=c?.[h];if(C===void 0)continue;if(!Number.isInteger(C)||C<g)throw new n(`ai.assistant.${h}`,`must be an integer of at least ${g}; it is a budget the server enforces, not a hint to the model`)}if(i.storage&&i.storage.secret.length<16)throw new n("ai.storage.secret","must be at least 16 characters; it encrypts the provider keys in the database")}function Hn(o){let i=o.webhooks;if(!i?.enabled)return;if(!i.signing?.secret)throw new n("webhooks.signing.secret","webhooks must be signed; set a secret");if(i.delivery?.timeout)w(i.delivery.timeout,"webhooks.delivery.timeout")}function Bn(o){let i=o.trim();if(!i.startsWith("/"))throw new n("admin.path",'must start with "/"');if(/[?#]/.test(i)||i.includes("//"))throw new n("admin.path","cannot contain a query, a fragment or an empty segment");let r=x(i);if(r.length===0)return"";return r}function Nn(o){let i=o.trim();if(!i.startsWith("/"))throw new n("basePath",'must start with "/"');if(/[?#]/.test(i))throw new n("basePath","cannot contain a query or fragment");if(i.includes("//"))throw new n("basePath","cannot contain empty segments");let r=x(i);if(r.length===0)throw new n("basePath",'cannot be "/"');return r}function zn(o){return[...Object.values(o.collections),...Object.values(o.globals)].map((i)=>({name:i.name,slug:i.slug,kind:i.kind,fields:Object.entries(i.fields).map(([r,a])=>({name:r,type:a.type,localized:a.localized,required:a.required}))}))}function qn(o){let i=o.uploads;if(!i)return null;let r=i.retention?.purgeAfter??"30d";return{id:typeof i.storage==="function"?"unresolved":i.storage.id,variants:i.images?.variants?.mode??null,processor:i.images?.processor?.id??null,purgeAfter:r===!1?null:r}}function Un(o){return o.plugins.map((i)=>({id:i.id,collections:Object.keys(i.schema?.collections??{}).sort(),tables:(i.schema?.tables??[]).map((r)=>r.name).sort(),routes:i.routes?.length??0,hooks:(i.hooks?.length??0)+o.pluginHooks.filter((r)=>r.plugin===i.id).length,migrations:(i.migrations??[]).map((r)=>r.id),client:i.client!==void 0,admin:i.admin!==void 0}))}function Zn(o){let i=o.admin.auth;return{methods:i?.methods??[],twoFactor:i?.twoFactor===!0,apiKeys:i?.apiKeys?.enabled===!0,sso:i?.sso?.issuer??null,roles:Object.keys(o.rbac?.roles??{}).sort(),customRoles:o.rbac?.customRoles===!0}}function Qn(o){return o.replaceAll("_"," ").replace(/^./,(i)=>i.toUpperCase())}function yt(o="system"){return{id:o,source:"session",roles:["admin"],permissions:["*"]}}
|
|
2
|
-
export{
|
|
1
|
+
import{Z,me,_,rn,fe,j}from"./index-2j6d79fk.js";import{_e,O,A,$e,Je,vo,xo,je,gn,l,u}from"./index-pkxgzw6e.js";import{s,R,t,We,H,M,S,le,m}from"./index-q6jkbsjp.js";import{an,ye}from"./index-e3yknwyr.js";import{io,qe}from"./index-5yt6r97r.js";import{V,J,Yt,Qt}from"./index-2zpnecrk.js";import{St}from"./index-1xwmw8vb.js";import{Ae,ke}from"./index-cakys3fy.js";import{tn,nn,on}from"./index-n09v6gx3.js";import{d}from"./index-9g2n7xa6.js";import{Te}from"./index-twqpdtfh.js";import{ge,et,tt}from"./index-y8kzzn94.js";import{p,_t}from"./index-qkqtxr65.js";import{ot}from"./index-344y6q4n.js";import{pn}from"./index-5j0cqm43.js";import{w,se}from"./index-rw0hze6x.js";import{x}from"./index-2ddk43me.js";import{b,ve}from"./index-qgtvymh2.js";import{e,n}from"./index-x72d1hzh.js";var rt="activity",at=50,lt=200;function De(o){return{async list(i={}){let r=dt(i.limit),a=[];if(i.collection)a.push(t("collection",i.collection));if(i.documentId)a.push(t("document_id",i.documentId));if(i.actorId)a.push(t("actor_id",i.actorId));if(i.action)a.push(t("action",i.action));if(i.source)a.push(t("source",i.source));if(i.cursor)a.push(H("id",i.cursor));let c=await o.database(),f=await c.transaction((v)=>c.query(v,{table:rt,...a.length===0?{}:{where:s(...a)},orderBy:[{path:"id",direction:"desc"}],limit:r+1})),h=f.length>r,g=f.slice(0,r),C=g.at(-1);return{entries:g.map(ct),limit:r,hasNextPage:h,cursor:h&&C?String(C.id):null}}}}function ct(o){let i=o.changes===null||o.changes===void 0?null:u(o.changes);return{id:String(o.id),action:String(o.action),actorId:Y(o.actor_id),actorSource:Y(o.actor_source),source:Y(o.source),collection:Y(o.collection),documentId:Y(o.document_id),locale:Y(o.locale),changes:i,ip:Y(o.ip),createdAt:l(o.created_at)}}function Y(o){return o===null||o===void 0?null:String(o)}function dt(o){if(o===void 0)return at;if(!Number.isInteger(o)||o<1)throw new e(`limit must be a positive integer, received ${o}`,{status:400,code:"invalid_pagination"});return Math.min(o,lt)}function ut(o,i){let r={createBefore:[],createAfter:[],updateBefore:[],updateAfter:[],deleteBefore:[],deleteAfter:[]},a=o.plugins.flatMap((f)=>(f.hooks??[]).filter((h)=>h.collection===i).map((h)=>({plugin:f.id,hook:h}))).sort((f,h)=>(f.hook.priority??0)-(h.hook.priority??0)||f.plugin.localeCompare(h.plugin));for(let{plugin:f,hook:h}of a){let g={source:f,priority:h.priority??0};if(h.timing==="before"){if(h.operation==="create")r.createBefore.push({...g,run:(v,D)=>h.handler(v.data,D)});else if(h.operation==="update")r.updateBefore.push({...g,run:(v,D)=>h.handler(v.data,D)});else r.deleteBefore.push({...g,run:(v,D)=>h.handler(v,D)});continue}let C=async(v,D)=>{await h.handler(v,D)};if(h.operation==="create")r.createAfter.push({...g,run:C});else if(h.operation==="update")r.updateAfter.push({...g,run:(v,D)=>C(v.doc,D)});else r.deleteAfter.push({...g,run:C})}let c=o.pluginHooks.filter((f)=>f.collection===i).sort((f,h)=>f.priority-h.priority||f.plugin.localeCompare(h.plugin));for(let f of c)Ee(r,f.hooks,{source:f.plugin,priority:f.priority});return Ee(r,o.databaseHooks?.[i],{source:"config",priority:gt}),r}var gt=100;function Ee(o,i,r){if(i?.create?.before){let a=i.create.before;o.createBefore.push({...r,run:(c,f)=>a(c,f)})}if(i?.create?.after){let a=i.create.after;o.createAfter.push({...r,run:(c,f)=>a(c,f)})}if(i?.update?.before){let a=i.update.before;o.updateBefore.push({...r,run:async(c,f)=>await a(c,f)})}if(i?.update?.after){let a=i.update.after;o.updateAfter.push({...r,run:(c,f)=>a(c,f)})}if(i?.delete?.before){let a=i.delete.before;o.deleteBefore.push({...r,run:(c,f)=>a(c,f)})}if(i?.delete?.after){let a=i.delete.after;o.deleteAfter.push({...r,run:(c,f)=>a(c,f)})}}async function Ie(o,i,r,a){let c=i;for(let f of o){let h=await f.run(c,r);if(h===!1)return!1;if(h&&typeof h==="object"&&"data"in h)c=a(c,h.data)}return c}async function He(o,i,r){for(let a of o)await a.run(i,r)}function zt(o){let i=new Set([...Object.keys(o.collections),...Object.keys(o.globals),...o.plugins.flatMap((a)=>(a.hooks??[]).map((c)=>c.collection)),...o.pluginHooks.map((a)=>a.collection)]),r=[];for(let a of[...i].sort()){let c=ut(o,a),f=[["create","before",c.createBefore],["create","after",c.createAfter],["delete","before",c.deleteBefore],["delete","after",c.deleteAfter],["update","before",c.updateBefore],["update","after",c.updateAfter]];for(let[h,g,C]of f)for(let v of C)r.push({collection:a,operation:h,timing:g,source:v.source,priority:v.priority})}return r}var vt="jobs",wt=100,Ct={name:"scheduled-changes",failureType:"document.schedule",failurePayload:(o)=>{let i=je(o);return{collection:String(o.collection),documentId:String(o.id),...i===null?{}:{locale:i.locale,patch:i.data},...o.scheduled_at instanceof Date?{scheduledFor:o.scheduled_at.toISOString()}:{}}},due:async(o,i,r)=>{let a=await o.database();return a.transaction((c)=>a.query(c,{table:p,where:s(le("scheduled_at",!0),M("scheduled_at",i),t("deleted_at",null)),orderBy:[m("scheduled_at","asc"),m("id","asc")],limit:r}))},run:(o,i)=>o.applyScheduled(i)},kt={name:"trash-purge",failureType:"trash.purge",failurePayload:(o)=>({collection:String(o.collection),documentId:String(o.id)}),due:async(o,i,r)=>{if(o.config.trash.purgeAfter===!1)return[];let a=await o.database();return a.transaction((c)=>a.query(c,{table:p,where:s(le("deleted_at",!0),le("purge_after",!0),M("purge_after",i)),orderBy:[m("purge_after","asc"),m("id","asc")],limit:r}))},run:(o,i)=>o.purgeExpired(i)};class pt{host;jobs=[Ct,kt];constructor(o){this.host=o}list(){return this.jobs.map((o)=>o.name)}register(o){this.jobs.push(o)}async run(o={}){let i=o.now??new Date,r=o.limit??wt,a=o.only?this.jobs.filter((f)=>o.only?.includes(f.name)):this.jobs,c=[];for(let f of a){let h=await f.due(this.host,i,r+1),g=h.slice(0,r),C=0,v=0;for(let D of g)try{await f.run(this.host,D,i),C+=1}catch(I){v+=1,await this.host.recordFailure(f.failureType,f.failurePayload(D),I).catch(()=>{return})}c.push({job:f.name,processed:C,failed:v,more:h.length>r})}return{ranAt:i.toISOString(),processed:c.reduce((f,h)=>f+h.processed,0),failed:c.reduce((f,h)=>f+h.failed,0),results:c}}async failures(o={}){let i=await this.host.database();return(await i.transaction((a)=>i.query(a,{table:vt,where:o.type===void 0?t("status","failed"):s(t("status","failed"),t("type",o.type)),orderBy:[m("created_at","desc"),m("id","desc")],limit:o.limit??50}))).map((a)=>({id:String(a.id),type:String(a.type),payload:a.payload===null||a.payload===void 0?null:u(a.payload),error:a.error===null||a.error===void 0?null:String(a.error),attempts:Number(a.attempts??0),createdAt:l(a.created_at)}))}}var oe="outbox";class mt{queued=[];emit(o,i,r=null){this.queued.push({type:o,data:i,previous:r})}take(){return this.queued.splice(0,this.queued.length)}}class ft{adapter;dispatch;maxAttempts;backoff;leaseMs;now;constructor(o,i,r={}){this.adapter=o;this.dispatch=i;this.maxAttempts=r.maxAttempts??5,this.backoff=r.backoff??((a)=>1000*2**(a-1)),this.leaseMs=r.leaseMs??300000,this.now=r.now??(()=>new Date)}async append(o,i,r){let a=this.now();for(let c of i)await this.adapter.mutate(o,{kind:"insert",table:oe,returning:!1,values:{id:ve("obx"),event_id:b("evt"),type:c.type,payload:c.data,previous:c.previous,actor:r.actor?{id:r.actor.id,source:r.actor.source}:null,collection:r.collection??null,document_id:r.documentId??null,status:"pending",attempts:0,available_at:a,processed_at:null,error:null,created_at:a}})}async drain(o=50){let i=await this.adapter.transaction((a)=>this.adapter.query(a,{table:oe,where:s(S("status",["pending","delivering"]),M("available_at",this.now())),orderBy:[m("created_at","asc"),m("id","asc")],limit:o})),r=0;for(let a of i){if(await this.hasPredecessor(a))continue;let c=await this.claim(a);if(!c)continue;if(Number(c.attempts)>this.maxAttempts){await this.settle(c,!1,Error("Delivery lease expired; attempt budget exhausted."));continue}try{await this.dispatch(At(c)),await this.settle(c,!0),r+=1}catch(f){await this.settle(c,!1,f)}}return r}async hasPredecessor(o){if(!o.document_id)return!1;return(await this.adapter.transaction((r)=>this.adapter.query(r,{table:oe,where:s(t("collection",o.collection==null?null:String(o.collection)),t("document_id",String(o.document_id)),H("id",String(o.id)),S("status",["pending","delivering"])),limit:1}))).length>0}async claim(o){let i={status:"delivering",attempts:Number(o.attempts??0)+1,available_at:new Date(this.now().getTime()+this.leaseMs)};return(await this.adapter.transaction((a)=>this.adapter.mutate(a,{kind:"update",table:oe,where:s(t("id",String(o.id)),t("status",String(o.status)),t("attempts",Number(o.attempts??0)),M("available_at",this.now())),set:i,returning:!1}))).count===1?{...o,...i}:null}async settle(o,i,r){let a=Number(o.attempts??0),c=a>=this.maxAttempts,f=i?{status:"delivered",attempts:a,processed_at:this.now(),error:null}:{status:c?"failed":"pending",attempts:a,available_at:new Date(this.now().getTime()+this.backoff(a)),error:r instanceof Error?r.message:String(r)};await this.adapter.transaction((h)=>this.adapter.mutate(h,{kind:"update",table:oe,where:s(t("id",String(o.id)),t("status","delivering"),t("attempts",a)),set:f,returning:!1}))}}function At(o){let i=u(o.actor);return{id:String(o.event_id),type:String(o.type),createdAt:l(o.created_at)??new Date().toISOString(),actor:typeof i.id==="string"?{id:i.id,source:i.source==="api-key"?"api-key":"session"}:null,data:u(o.payload),previous:o.previous===null||o.previous===void 0?null:u(o.previous)}}class ht{options;cache=new Map;queries=0;constructor(o){this.options=o}get queryCount(){return this.queries}async expand(o,i,r){if(r<=0||o.length===0)return;let a=Object.entries(i.fields).map(([h,g])=>({name:h,target:xn(g)})).filter((h)=>Boolean(h.target));if(a.length===0)return;let c=new Map;for(let h of o)for(let g of a)for(let C of Rt(h[g.name])){if(this.cache.has(Q(g.target,C)))continue;let v=c.get(g.target)??new Set;v.add(C),c.set(g.target,v)}for(let[h,g]of c)await this.load(h,[...g]);let f=new Map;for(let h of o)for(let g of a){let C=h[g.name];h[g.name]=this.substitute(g.target,C,f)}for(let[h,g]of f){let C=this.options.collections[h];if(C)await this.expand(g,C,r-1)}}async load(o,i){let r=this.options.collections[o];if(this.queries+=1,r){for(let g of i)this.cache.set(Q(o,g),null);let c;try{c=await _(r,{actor:this.options.actor??null,operation:"read",locale:this.options.locale.locale,rbac:this.options.rbac})}catch(g){if(g instanceof e&&(g.status===401||g.status===403))return;throw g}let f=[c,t("collection",r.slug),S("id",i),...this.options.includeTrashed?[]:[t("deleted_at",null)]],h=await this.options.adapter.query(this.options.tx,{table:p,where:s(...f)});for(let g of i)this.cache.set(Q(o,g),null);for(let g of h){let C=A(g,r,this.options.locale);this.cache.set(Q(o,String(g.id)),fe(C,r,this.options.actor??null,this.options.locale.locale))}return}for(let c of i)this.cache.set(Q(o,c),null);if(o!=="media"&&o!=="cms_users")return;let a=await this.options.adapter.query(this.options.tx,{table:o,where:S("id",i),...o==="cms_users"?{select:["id","name"]}:{}});for(let c of i)this.cache.set(Q(o,c),null);for(let c of a)this.cache.set(Q(o,String(c.id)),xo(c))}substitute(o,i,r){let a=(c)=>{let f=structuredClone(c),h=r.get(o)??[];return h.push(f),r.set(o,h),f};if(typeof i==="string"){let c=this.cache.get(Q(o,i));return c?a(c):i}if(Array.isArray(i))return i.map((c)=>{if(typeof c!=="string")return c;let f=this.cache.get(Q(o,c));return f?a(f):c});return i??null}}function xn(o){if(o.relationTo)return o.relationTo;return o.type==="media"?"media":void 0}function Rt(o){if(typeof o==="string")return o.length>0?[o]:[];if(Array.isArray(o))return o.filter((i)=>typeof i==="string");return[]}function Q(o,i){return`${o}:${i}`}var X="slug_history",Fe=50;function he(o){let i=ee(o);if(typeof i.slugify==="function")return i.slugify;let r=i.maxLength;return(a)=>ye(a,r===void 0?{}:{maxLength:r})}function ae(o){return Object.entries(o.fields).filter(([,i])=>i.type==="slug")}function ee(o){return o.options}async function be(o){let i=ae(o.collection);if(i.length===0)return{input:o.input,moves:[]};let r={...o.input},a=[];for(let[c,f]of i){let h=ee(f),g=f.localized?o.locale:"",C=Pt(o.stored,c,f,o.locale),v=r[c],D=he(f),I;if(typeof v==="string"&&v.trim()!==""){if(I=D(v),I==="")throw e.validation(`${o.collection.name}.${c}: "${v}" has no letters or digits to make a slug from`);if(h.unique!==!1)await Ce({...o,field:c,locale:g,slug:I})}else if(v===null||v===""||v===void 0&&C===null){let F=h.from===void 0?null:Tt(o,h.from),B=F===null?"":D(F);if(B!=="")I=h.unique===!1?B:await Ot({...o,field:c,locale:g,base:B});else if(v!==void 0)I=null}if(I===void 0)continue;if(r[c]=I,h.history===!0&&C!==null&&I!==null&&I!==C)a.push({field:c,locale:g,from:C,to:I})}return{input:r,moves:a}}async function we(o,i,r,a,c){for(let f of a){let h=s(t("collection",i.name),t("field",f.field),t("locale",f.locale));if(await o.delete(X,s(h,t("document_id",r),t("slug",f.to))),await o.findOne(X,s(h,t("slug",f.from))))continue;await o.insert(X,{id:b("slg"),collection:i.name,field:f.field,locale:f.locale,slug:f.from,document_id:r,created_at:c})}}async function Le(o,i,r,a,c,f){await o.delete(X,s(t("collection",i.name),t("document_id",r),t("field",a),t("locale",c),t("slug",f)))}async function Me(o,i,r){await o.delete(X,s(t("collection",i.name),t("document_id",r)))}function xt(o){let i=o.collection.fields[o.field];return i!==void 0&&ee(i).history===!0}async function Ce(o){let i=o.locale?` in "${o.locale}"`:"",r=await Be(o,o.slug);if(r!==null)throw e.conflict(`The slug "${o.slug}" is already used${i} by another document of ${o.collection.label} (${r}).`);let a=await Ne(o,o.slug);if(a!==null)throw e.conflict(`The slug "${o.slug}" is a previous slug of another document of ${o.collection.label} (${a})${i} and redirects there. Remove it from that document's previous slugs first.`)}async function Ot(o){for(let i=1;i<=Fe;i+=1){let r=i===1?o.base:`${o.base}-${i}`;if(await Be(o,r)===null&&await Ne(o,r)===null)return r}throw e.conflict(`No free slug for "${o.base}" after ${Fe} tries; set one explicitly.`)}async function Be(o,i){let r=o.locale?`${o.field}.${o.locale}`:o.field,a=await o.db.query({table:p,where:s(t("collection",o.collection.slug),t(r,i),...o.documentId===null?[]:[We("id",o.documentId)]),limit:1});return a[0]?String(a[0].id):null}async function Ne(o,i){if(!xt(o))return null;let r=await o.db.findOne(X,s(t("collection",o.collection.name),t("field",o.field),t("locale",o.locale),t("slug",i),...o.documentId===null?[]:[We("document_id",o.documentId)]));return r?String(r.document_id):null}function Pt(o,i,r,a){if(!o)return null;let c=r.localized?u(o[i])[a]:o[i];return typeof c==="string"&&c!==""?c:null}function Tt(o,i){let r=o.collection.fields[i];if(!r)return null;let a=o.input[i],c=a!==void 0?a:r.localized?u(o.stored?.[i])[o.locale]??null:o.stored?.[i]??null;return typeof c==="string"&&c.trim()!==""?c:null}async function ze(o){let{db:i,collection:r,field:a,slug:c}=o,f=r.fields[a];if(!f||!an(c))return[];let h=f.localized,g=[],C=await i.query({table:p,where:s(t("collection",r.slug),t("deleted_at",null),h?R(...o.locales.map((I)=>t(`${a}.${I}`,c))):t(a,c)),limit:20});for(let I of C){let F=u(I.data)[a];if(!h){g.push({id:String(I.id),locale:null,current:!0});continue}for(let B of o.locales)if(u(F)[B]===c)g.push({id:String(I.id),locale:B,current:!0})}let v=[];if(ee(f).history===!0){let I=await i.find(X,s(t("collection",r.name),t("field",a),t("slug",c))),F=await Dt(i,r,I.map((B)=>String(B.document_id)));for(let B of I){let y=String(B.document_id);if(!F.has(y))continue;let P=String(B.locale??"");v.push({id:y,locale:P===""?null:P,current:!1})}}let D=(I)=>I.locale===null||I.locale===o.locale?0:1;return[...g.sort((I,F)=>D(I)-D(F)),...v.sort((I,F)=>D(I)-D(F))]}async function Dt(o,i,r){if(r.length===0)return new Set;let a=await o.query({table:p,where:s(t("collection",i.slug),t("deleted_at",null),S("id",[...new Set(r)]))});return new Set(a.map((c)=>String(c.id)))}async function Ge(o){let i=[t("collection",o.collection.name),t("document_id",o.documentId)];if(o.field!==void 0)i.push(t("field",o.field));if(o.locale!==void 0)i.push(t("locale",o.locale??""));return(await o.db.find(X,s(...i))).map((a)=>({slug:String(a.slug),field:String(a.field),locale:a.locale?String(a.locale):null,createdAt:l(a.created_at)})).sort((a,c)=>(c.createdAt??"").localeCompare(a.createdAt??"")||a.slug.localeCompare(c.slug))}var jt=25,$t=200,Se=[m("deleted_at","desc"),m("id","desc")];async function Ht(o){let{adapter:i,config:r,collections:a,args:c}=o,f=O(r,c),h=c.actor??null,g=Jt(c.limit),C=c.collection?[It(a,c.collection)]:Object.values(a),v=[],D=new Map;for(let k of C){let T;try{T=await _(k,{actor:h,operation:"read",locale:f.locale,rbac:r.rbac})}catch(L){if(c.collection)throw L;continue}D.set(k.slug,k),v.push(T?s(t("collection",k.slug),T):t("collection",k.slug))}if(v.length===0)return{entries:[],limit:g,hasNextPage:!1,cursor:null};let I=v.length===D.size&&v.every((k)=>k.kind==="compare")?S("collection",[...D.keys()]):R(...v),F=s(le("deleted_at",!0),I),B=await i.transaction((k)=>i.query(k,{table:p,where:c.cursor?s(F,J(c.cursor,Se)):F,orderBy:Se,limit:g+1})),y=B.length>g,P=B.slice(0,g),W=P.flatMap((k)=>{let T=D.get(String(k.collection));if(!T)return[];let L=A(k,T,f);if(rn(T))fe(L,T,h,f.locale);return[{collection:T.name,id:String(k.id),deletedAt:l(k.deleted_at),purgeAfter:l(k.purge_after),document:L}]}),E=P.at(-1);return{entries:W,limit:g,hasNextPage:y,cursor:E?V(E,Se):null}}function It(o,i){let r=o[i];if(!r)throw e.notFound(`No collection named "${i}"`);return r}function Jt(o){if(o===void 0)return jt;if(!Number.isInteger(o)||o<1)throw new e(`limit must be a positive integer, received ${o}`,{status:400,code:"invalid_pagination"});return Math.min(o,$t)}var Wt=25,Et=500,Ft="activity",Lt="media_usages",Ue="cms_ai_mutations",Ke={create:"create",update:"update",trash:"delete",purge:"delete",restore:"update",schedule:"update",unschedule:"update"};class yt{options;cms;pipelines=new Map;byName;bySlug;media=new Map;outbox;delivery=Promise.resolve();constructor(o){this.options=o;this.byName={...o.config.collections,...o.config.globals},this.bySlug=Object.fromEntries(Object.values(this.byName).map((i)=>[i.slug,i]))}bind(o){this.cms=o}buildApi(){let o={};for(let i of Object.values(this.options.config.collections))o[i.name]=this.collectionApi(i);return o}buildGlobals(){let o={};for(let i of Object.values(this.options.config.globals))o[i.name]=this.globalApi(i);return o}buildTrash(){return{list:async(o={})=>{let i=await this.options.database();return Ht({adapter:i,config:this.options.config,collections:this.byName,args:o})},restore:(o)=>this.restore(this.requireCollection(o.collection),{...o,id:o.id}),purge:(o)=>this.purge(this.requireCollection(o.collection),{...o,id:o.id})}}buildJobs(){return new pt({config:this.options.config,database:()=>this.options.database(),applyScheduled:(o)=>this.applyScheduled(o),purgeExpired:(o)=>this.purgeExpired(o),recordFailure:(o,i,r)=>this.recordFailure(o,i,r)})}async drainEvents(o){return await this.delivery,(await this.outboxWorker()).drain(o)}async settle(){await this.delivery}async appendEvents(o,i,r){await(await this.outboxWorker()).append(o,i,r)}deliverSoon(){this.scheduleDelivery()}collectionApi(o){return{find:(i)=>this.find(o,i),findOne:(i)=>this.findOne(o,i),findById:(i,r)=>this.findById(o,i,r),count:(i)=>this.count(o,i),create:(i)=>this.create(o,i),update:(i)=>this.update(o,i),delete:(i)=>this.remove(o,i),restore:(i)=>this.restore(o,i),purge:(i)=>this.purge(o,i),schedule:(i)=>this.schedule(o,i),unschedule:(i)=>this.unschedule(o,i),resolveSlug:(i,r)=>this.resolveSlug(o,i,r),previousSlugs:(i)=>this.previousSlugs(o,i),addPreviousSlug:(i)=>this.changePreviousSlug(o,i,"add"),removePreviousSlug:(i)=>this.changePreviousSlug(o,i,"remove")}}slugField(o,i,r){let a=ae(o).filter(([,f])=>!r||ee(f).history===!0),c=i===void 0?a[0]?.[0]:a.find(([f])=>f===i)?.[0];if(c===void 0)throw e.validation(i===void 0?`${o.name} has no slug field${r?" with history":""}`:`${o.name}.${i} is not a slug field${r?" with history":""}`);return c}async resolveSlug(o,i,r={}){let a=this.slugField(o,r.field,!1),c=O(this.options.config,r),f=await this.options.database(),h=await f.transaction((v)=>ze({db:d(f,v),collection:o,field:a,slug:i,locale:c.locale,locales:this.options.config.i18n.locales})),{field:g,...C}=r;for(let v of h){let D=await this.findById(o,v.id,C);if(!D)continue;return{id:v.id,field:a,locale:v.locale,current:v.current,document:D}}return null}async previousSlugs(o,i){let r=this.slugField(o,i.field,!0);if(!await this.findById(o,i.id,{...i,includeTrashed:!0}))throw e.notFound(`No ${o.name} with id "${i.id}"`);let c=o.fields[r],f=await this.options.database();return f.transaction((h)=>Ge({db:d(f,h),collection:o,documentId:i.id,field:r,...i.locale===void 0?{}:{locale:c?.localized?i.locale:null}}))}async changePreviousSlug(o,i,r){let a=this.slugField(o,i.field,!0),c=o.fields[a],f=O(this.options.config,i),h=i.actor??null,g=c.localized?f.locale:"",C=r==="add"?he(c)(i.slug):i.slug;if(C==="")throw e.validation(`"${i.slug}" has no letters or digits to make a slug from`);let v=await this.options.database();return await v.transaction(async(D)=>{let I=d(v,D),F=await this.load(v,D,o,i.id,{actor:h,operation:"update",locale:f,includeTrashed:!1}),B=A(F,o,f);await this.assertAllowed(o,"update",h,f,B),j(o,{[a]:null},h,f.locale,B);let y=c.localized?u(u(F.data)[a])[f.locale]:u(F.data)[a];if(r==="add"){if(y===C)throw e.conflict(`"${C}" is this document's slug already, not a previous one.`);await Ce({db:I,collection:o,documentId:String(F.id),field:a,locale:g,slug:C}),await we(I,o,String(F.id),[{field:a,locale:g,from:C,to:String(y??"")}],new Date)}else await Le(I,o,String(F.id),a,g,C)}),this.previousSlugs(o,{id:i.id,field:a,...i.actor===void 0?{}:{actor:i.actor},...c.localized?{locale:f.locale}:{}})}async find(o,i={}){let r=await this.options.database(),a=O(this.options.config,i),c=i.actor??null,f=await _(o,{actor:c,operation:"read",locale:a.locale,rbac:this.options.config.rbac}),h=this.scope(o,i.where,f,i.includeTrashed),g=Mt(i.orderBy),C=Nt(i.limit);return r.transaction(async(v)=>{let D=await r.query(v,{table:p,where:i.cursor?s(h,J(i.cursor,g)):h,orderBy:g,limit:C+1,...i.offset===void 0?{}:{offset:i.offset}}),I=D.length>C,F=D.slice(0,C),B=F.map((W)=>A(W,o,a));await this.expand(r,v,B,o,a,i,c),this.redact(B,o,c,a);let y=null;if(i.count===!0){let W=await r.query(v,{table:p,where:h,count:!0});y=Number(W[0]?.count??0)}let P=F.at(-1);return{docs:B,limit:C,totalDocs:y,hasNextPage:I,cursor:P?V(P,g):null}})}async findOne(o,i={}){return(await this.find(o,{...i,limit:1})).docs[0]??null}async findById(o,i,r={}){return this.findOne(o,{...r,where:t("id",i)})}async count(o,i={}){let r=await this.options.database(),a=O(this.options.config,i),c=await _(o,{actor:i.actor??null,operation:"read",locale:a.locale,rbac:this.options.config.rbac}),f=this.scope(o,i.where,c,i.includeTrashed);return r.transaction(async(h)=>{let g=await r.query(h,{table:p,where:f,count:!0});return Number(g[0]?.count??0)})}async create(o,i){let r=O(this.options.config,i),a=i.actor??null,c={...i.data};return this.runWrite({collection:o,intent:"create",actor:a,source:i.source??"local",locale:r,depth:i.depth,includeTrashed:i.includeTrashed,runId:i.runId,idempotencyKey:i.idempotencyKey,step:async({db:f,hooks:h,context:g})=>{await this.assertAllowed(o,"create",a,r),j(o,c,a,r.locale);let C=await Ie(h.createBefore,{data:c},g,(P,W)=>({...P,data:W}));if(C===!1)return null;let v=i.id??b("doc"),D=await be({db:f,collection:o,input:C.data,stored:null,locale:r.locale,documentId:v}),{data:I,touched:F}=$e(o,D.input,r);Je(o,I,r,Object.keys(o.fields));let B=new Date,y=await f.insert(p,{id:v,collection:o.slug,data:I,created_at:B,updated_at:B,updated_by:a?.id??null,deleted_at:null,purge_after:null,scheduled_at:null,scheduled_patch:null,revision:1});return{doc:A(y,o,r),previous:null,changed:F,stored:I}}})}async update(o,i,r){let a=O(this.options.config,i),c=i.actor??null,f={...i.data};return this.runWrite({collection:o,intent:"update",actor:c,source:i.source??"local",locale:a,depth:i.depth,includeTrashed:i.includeTrashed,runId:i.runId,idempotencyKey:i.idempotencyKey,...r===void 0?{}:{emit:r},step:async({adapter:h,tx:g,db:C,hooks:v,context:D})=>{let I=await this.load(h,g,o,i.id,{actor:c,operation:"update",locale:a,includeTrashed:i.includeTrashed});Re(i.expectedRevision,I);let F=A(I,o,a);await this.assertAllowed(o,"update",c,a,F),j(o,f,c,a.locale,F);let B=await Ie(v.updateBefore,{data:f,previous:F},D,(L,N)=>({...L,data:N}));if(B===!1)return null;let y=await be({db:C,collection:o,input:B.data,stored:u(I.data),locale:a.locale,documentId:String(I.id)}),{data:P,touched:W}=$e(o,y.input,a,u(I.data));Je(o,P,a,W);let E=new Date,k=await this.patch(h,g,I,{data:P,updated_at:E,updated_by:c?.id??null},i.expectedRevision),T=A(k,o,a);return{doc:T,previous:F,changed:vo(o,F,T),stored:P,slugMoves:y.moves}}})}async remove(o,i){if(!this.options.config.trash.enabled||i.permanent===!0)return this.purge(o,i);let a=O(this.options.config,i),c=i.actor??null;return this.runWrite({collection:o,intent:"trash",actor:c,source:i.source??"local",locale:a,depth:i.depth,includeTrashed:!0,runId:i.runId,idempotencyKey:i.idempotencyKey,step:async({adapter:f,tx:h,hooks:g,context:C})=>{let v=await this.load(f,h,o,i.id,{actor:c,operation:"delete",locale:a,includeTrashed:!1});Re(i.expectedRevision,v);let D=A(v,o,a);await this.assertAllowed(o,"delete",c,a,D);let I=await Ie(g.deleteBefore,D,C,(y,P)=>P);if(I===!1)return null;let F=new Date,B=await this.patch(f,h,v,{deleted_at:F,purge_after:this.purgeAt(F),scheduled_at:null,scheduled_patch:null,updated_at:F,updated_by:c?.id??null});return{doc:A(B,o,a),previous:I,changed:[]}}})}async restore(o,i){let r=O(this.options.config,i),a=i.actor??null;return this.runWrite({collection:o,intent:"restore",actor:a,source:i.source??"local",locale:r,depth:i.depth,includeTrashed:!0,runId:i.runId,idempotencyKey:i.idempotencyKey,step:async({adapter:c,tx:f})=>{let h=await this.load(c,f,o,i.id,{actor:a,operation:"restore",locale:r,includeTrashed:!0});if(Re(i.expectedRevision,h),h.deleted_at===null||h.deleted_at===void 0)throw e.conflict(`${o.name} "${i.id}" is not in the trash`);let g=A(h,o,r);await this.assertAllowed(o,"restore",a,r,g);let C=new Date,v=await this.patch(c,f,h,{deleted_at:null,purge_after:null,updated_at:C,updated_by:a?.id??null});return{doc:A(v,o,r),previous:g,changed:[],after:!1}}})}async purge(o,i,r={}){let a=O(this.options.config,i),c=i.actor??null;return this.runWrite({collection:o,intent:"purge",actor:c,source:i.source??"local",locale:a,depth:i.depth,includeTrashed:!0,step:async({adapter:f,tx:h,db:g,hooks:C,context:v})=>{let D=await this.load(f,h,o,i.id,{actor:c,operation:"purge",locale:a,includeTrashed:!0,bypassAccess:r.retention===!0}),I=A(D,o,a),F=D.deleted_at!==null&&D.deleted_at!==void 0;if(r.retention!==!0)await this.assertAllowed(o,F?"purge":"delete",c,a,I);let B=F?I:await Ie(C.deleteBefore,I,v,(y,P)=>P);if(B===!1)return null;return await g.delete(p,t("id",String(D.id))),{doc:B,previous:B,changed:[],after:!F,releaseMedia:!0}}})}async schedule(o,i){let r=O(this.options.config,i),a=i.actor??null,c=qt(i.at),f={...i.data};if(Object.keys(f).length===0)throw e.validation("A scheduled change needs at least one field.");return this.runWrite({collection:o,intent:"schedule",actor:a,source:i.source??"local",locale:r,depth:i.depth,includeTrashed:!1,step:async({adapter:h,tx:g})=>{let C=await this.load(h,g,o,i.id,{actor:a,operation:"update",locale:r,includeTrashed:!1}),v=A(C,o,r);await this.assertAllowed(o,"update",a,r,v),j(o,f,a,r.locale,v);let D=$e(o,f,r,u(C.data));Je(o,D.data,r,D.touched);let I=new Date,F=await this.patch(h,g,C,{scheduled_at:c,scheduled_patch:{data:f,locale:r.locale,actor:a===null?null:{...a}},updated_at:I,updated_by:a?.id??null});return{doc:A(F,o,r),previous:v,changed:[],after:!1}}})}async unschedule(o,i){let r=O(this.options.config,i),a=i.actor??null;return this.runWrite({collection:o,intent:"unschedule",actor:a,source:i.source??"local",locale:r,depth:i.depth,includeTrashed:!1,step:async({adapter:c,tx:f})=>{let h=await this.load(c,f,o,i.id,{actor:a,operation:"update",locale:r,includeTrashed:!1});if(h.scheduled_at===null||h.scheduled_at===void 0)throw e.conflict(`${o.name} "${i.id}" has nothing scheduled`);let g=A(h,o,r);await this.assertAllowed(o,"update",a,r,g);let C=new Date,v=await this.patch(c,f,h,{scheduled_at:null,scheduled_patch:null,updated_at:C,updated_by:a?.id??null});return{doc:A(v,o,r),previous:g,changed:[],after:!1}}})}globalApi(o){return{get:(i)=>this.globalGet(o,i),update:async(i)=>{let r=await this.ensureGlobalRow(o,i);return this.update(o,{...i,id:r})},schedule:async(i)=>{let r=await this.ensureGlobalRow(o,i);return this.schedule(o,{...i,id:r})},unschedule:async(i={})=>this.unschedule(o,{...i,id:te(o)})}}async globalGet(o,i={}){let r=await this.options.database(),a=O(this.options.config,i),c=i.actor??null,f=await _(o,{actor:c,operation:"read",locale:a.locale,rbac:this.options.config.rbac});return r.transaction(async(h)=>{let C=(await r.query(h,{table:p,where:this.scope(o,t("id",te(o)),f,!1),limit:1}))[0]??this.emptyGlobalRow(o,a,null),v=A(C,o,a);return await this.expand(r,h,[v],o,a,i,c),this.redact([v],o,c,a),v})}async ensureGlobalRow(o,i){let r=await this.options.database(),a=O(this.options.config,i),c=te(o);if(await r.transaction(async(h)=>(await r.query(h,{table:p,where:t("id",c),limit:1})).length>0))return c;try{await r.transaction((h)=>r.mutate(h,{kind:"insert",table:p,returning:!1,values:this.emptyGlobalRow(o,a,new Date)}))}catch(h){if(!await r.transaction(async(C)=>(await r.query(C,{table:p,where:t("id",c),limit:1})).length>0))throw h}return c}emptyGlobalRow(o,i,r){let{data:a}=$e(o,{},i);return{id:te(o),collection:o.slug,data:a,created_at:r,updated_at:r,updated_by:null,deleted_at:null,purge_after:null,scheduled_at:null,scheduled_patch:null,revision:1}}async applyScheduled(o){let i=this.bySlug[String(o.collection)],r=je(o),a=o.scheduled_at;if(!i||!r||!(a instanceof Date)){await this.clearSchedule(String(o.id));return}let c=await this.options.database();if((await c.transaction((h)=>c.mutate(h,{kind:"update",table:p,where:s(t("id",String(o.id)),t("scheduled_at",a)),set:{scheduled_at:null,scheduled_patch:null},returning:!1}))).count!==1)return;await this.update(i,{id:String(o.id),data:r.data,locale:r.locale,actor:r.actor,source:"job"},(h,g)=>{h.emit("document.schedule.applied",{collection:i.name,documentId:String(g.doc.id),locale:r.locale,scheduledFor:a.toISOString(),patch:r.data})})}async purgeExpired(o){let i=this.bySlug[String(o.collection)];if(!i){let r=await this.options.database();await r.transaction(async(a)=>{let c=d(r,a);await c.delete(Lt,t("document_id",String(o.id))),await c.delete(p,t("id",String(o.id)))});return}await this.purge(i,{id:String(o.id),actor:null,source:"job",includeTrashed:!0},{retention:!0})}async clearSchedule(o){let i=await this.options.database();await i.transaction((r)=>i.mutate(r,{kind:"update",table:p,where:t("id",o),set:{scheduled_at:null,scheduled_patch:null},returning:!1}))}async recordFailure(o,i,r){let a=r instanceof Error?r.message:String(r),c=await this.options.database(),f=new Date;await c.transaction(async(h)=>{await d(c,h).insert("jobs",{id:ve("job"),type:o,payload:i,status:"failed",run_at:f,attempts:1,locked_at:null,locked_by:null,completed_at:null,error:a,created_at:f}),await this.appendEvents(h,[{type:"job.failed",data:{job:o,error:a,...i},previous:null}],{actor:null})}),this.scheduleDelivery()}async runWrite(o){let i=await this.options.database(),r=await this.outboxWorker(),a=this.pipeline(o.collection.name),c=new mt,f=await i.transaction(async(h)=>{let g=d(i,h),C=await this.replay(g,o);if(C)return C;let v={actor:o.actor,collection:o.collection.name,operation:Ke[o.intent],locale:o.locale.locale,tx:h,db:g,cms:this.instance(),events:c,source:o.source,meta:{}},D=await o.step({adapter:i,tx:h,db:g,hooks:a,context:v});if(D===null)return null;if(this.emitDocumentEvents(c,o,D),await this.syncMedia(g,o,D,c),await this.syncSlugs(g,o,D),o.emit?.(c,D),await r.append(h,c.take(),this.outboxMeta(o,D)),D.after!==!1)await this.runAfter(a,o,D,v);return await r.append(h,c.take(),this.outboxMeta(o,D)),await this.writeActivity(g,o,D),await this.recordIdempotency(g,o,D),await this.expand(i,h,[D.doc],o.collection,o.locale,o,o.actor),D});if(!f)return null;if(!("replayed"in f))this.scheduleDelivery();return this.redact([f.doc],o.collection,o.actor,o.locale),f.doc}async replay(o,i){let r=i.idempotencyKey;if(r===void 0)return null;let a=await o.findOne(Ue,t("idempotency_key",r));if(!a)return null;return{doc:u(a.result),previous:null,changed:[],replayed:!0}}async recordIdempotency(o,i,r){let a=i.idempotencyKey;if(a===void 0)return;await o.insert(Ue,{id:b("aim"),idempotency_key:a,run_id:i.runId??"",collection:i.collection.name,document_id:String(r.doc.id),result:r.doc,created_at:new Date})}async runAfter(o,i,r,a){let c=Ke[i.intent];if(c==="create"){await He(o.createAfter,r.doc,a);return}if(c==="update"){await He(o.updateAfter,{doc:r.doc,previous:r.previous},a);return}await He(o.deleteAfter,r.doc,a)}emitDocumentEvents(o,i,r){let a=(f)=>({collection:i.collection.name,documentId:String(r.doc.id),locale:i.locale.locale,document:ce(f)});switch(i.intent){case"create":{o.emit("document.created",a(r.doc),null);return}case"trash":{o.emit("document.trashed",{...a(r.doc),purgeAfter:r.doc.purgeAfter??null},null);return}case"restore":{o.emit("document.restored",a(r.doc),null);return}case"purge":{o.emit("document.purged",a(r.doc),null);return}case"schedule":{o.emit("document.scheduled",{...a(r.doc),scheduledAt:r.doc.scheduledAt??null,patch:ce(r.doc.scheduledPatch??null)},null);return}case"unschedule":{o.emit("document.schedule.cancelled",{...a(r.doc),scheduledAt:r.previous?.scheduledAt??null},null);return}case"update":break}let c=r.previous;o.emit("document.updated",a(r.doc),a(c));for(let f of r.changed)o.emit("document.field.changed",{collection:i.collection.name,documentId:String(r.doc.id),locale:i.locale.locale,field:f,value:ce(r.doc[f]??null)},{field:f,value:ce(c[f]??null)})}async syncMedia(o,i,r,a){let c=this.options.config.uploads,f=r.releaseMedia===!0;if(!f&&r.stored===void 0)return;if(!f&&!this.referencesMedia(i.collection))return;let h=await on({db:o,collection:i.collection.name,documentId:String(r.doc.id),references:f?null:nn(i.collection,r.stored??{}),lifecycle:c!==void 0,retention:c?.retention,now:new Date}),g=(C)=>({mediaId:C,collection:i.collection.name,documentId:String(r.doc.id)});for(let C of h.orphaned)a.emit("media.orphaned",g(C));for(let C of h.reclaimed)a.emit("media.reclaimed",g(C))}async syncSlugs(o,i,r){if(!this.keepsSlugHistory(i.collection))return;let a=String(r.doc.id);if(r.releaseMedia===!0){await Me(o,i.collection,a);return}if(r.slugMoves&&r.slugMoves.length>0)await we(o,i.collection,a,r.slugMoves,new Date)}keepsSlugHistory(o){return ae(o).some(([,i])=>ee(i).history===!0)}referencesMedia(o){let i=this.media.get(o.name);if(i!==void 0)return i;let r=tn(o);return this.media.set(o.name,r),r}async writeActivity(o,i,r){await o.insert(Ft,{id:ve("act"),actor_id:i.actor?.id??null,actor_source:i.actor?.source??null,action:Ut(i.intent),source:i.source,collection:i.collection.name,document_id:String(r.doc.id),locale:i.locale.locale,changes:{fields:r.changed,...i.runId===void 0?{}:{runId:i.runId}},ip:null,created_at:new Date})}scope(o,i,r,a){let c=[t("collection",o.slug)];if(a!==!0)c.push(t("deleted_at",null));if(i)c.push(i);if(r)c.push(r);return s(...c)}async load(o,i,r,a,c){let f=c.bypassAccess===!0?void 0:await _(r,{actor:c.actor,operation:c.operation,locale:c.locale.locale,rbac:this.options.config.rbac}),g=(await o.query(i,{table:p,where:this.scope(r,t("id",a),f,c.includeTrashed),limit:1}))[0];if(!g)throw e.notFound(`No ${r.name} with id "${a}"`);return g}async patch(o,i,r,a,c){let f=gn(r.revision),h=f+1,g=String(r.id),C=await o.mutate(i,{kind:"update",table:p,where:c===void 0?t("id",g):s(t("id",g),t("revision",c)),set:{...a,revision:h}});if(c!==void 0&&C.count===0)throw Ve(c,f);return C.rows[0]??{...r,...a,revision:h}}async assertAllowed(o,i,r,a,c){if(await _(o,{actor:r,operation:i,locale:a.locale,rbac:this.options.config.rbac,...c===void 0?{}:{record:c}})&&i==="create")throw new e(`access.create on "${o.name}" returned a filter; a create has no row to filter. Return true or false.`,{status:500,code:"invalid_access_rule"})}requireCollection(o){let i=this.byName[o];if(!i)throw e.notFound(`No collection named "${o}"`);return i}purgeAt(o){let i=this.options.config.trash.purgeAfter;if(i===!1)return null;return new Date(o.getTime()+w(i))}async expand(o,i,r,a,c,f,h){if(!f.depth)return;await new ht({adapter:o,tx:i,locale:c,actor:h,rbac:this.options.config.rbac,collections:this.byName,...f.includeTrashed===void 0?{}:{includeTrashed:f.includeTrashed}}).expand(r,a,f.depth)}redact(o,i,r,a){if(!rn(i))return;for(let c of o)fe(c,i,r,a.locale)}pipeline(o){let i=this.pipelines.get(o);if(i)return i;let r=ut(this.options.config,o);return this.pipelines.set(o,r),r}outboxMeta(o,i){return{actor:o.actor,collection:o.collection.name,documentId:String(i.doc.id)}}async outboxWorker(){if(this.outbox)return this.outbox;let o=await this.options.database();return this.outbox=new ft(o,this.options.dispatch),this.outbox}scheduleDelivery(){this.delivery=this.delivery.then(async()=>{await(await this.outboxWorker()).drain()}).catch(()=>{return})}instance(){if(!this.cms)throw new e("The engine was used before it was bound.",{status:500,code:"engine_unbound"});return this.cms}}function te(o){return`glb_${o.slug}`}function Mt(o){let i=o&&o.length>0?[...o]:[{path:"updated_at",direction:"desc"}];if(!i.some((r)=>r.path==="id"))i.push({path:"id",direction:i[i.length-1]?.direction??"desc"});return i}function Nt(o){if(o===void 0)return Wt;if(!Number.isInteger(o)||o<1)throw new e(`limit must be a positive integer, received ${o}`,{status:400,code:"invalid_pagination"});return Math.min(o,Et)}function qt(o){let i=o instanceof Date?o:new Date(o);if(Number.isNaN(i.getTime()))throw e.validation(`"${String(o)}" is not a date`);return i}function Ve(o,i){return new e(`This document has changed since you read it (expected revision ${o}, found ${i}). Reload it and apply your change again.`,{status:409,code:"revision_conflict",details:{expectedRevision:o,revision:i}})}function Re(o,i){if(o===void 0)return;if(!Number.isInteger(o)||o<1)throw e.validation(`expectedRevision has to be a positive integer, received ${String(o)}.`);let r=gn(i.revision);if(r!==o)throw Ve(o,r)}function Ut(o){switch(o){case"create":return"document.created";case"update":return"document.updated";case"trash":return"document.trashed";case"restore":return"document.restored";case"purge":return"document.purged";case"schedule":return"document.scheduled";case"unschedule":return"document.schedule.cancelled"}}function ce(o){return JSON.parse(JSON.stringify(o??null))}var Bt={af:"Afrikaans",am:"Amharic",ar:"Arabic",az:"Azerbaijani",be:"Belarusian",bg:"Bulgarian",bn:"Bengali",bs:"Bosnian",ca:"Catalan",cs:"Czech",cy:"Welsh",da:"Danish",de:"German",el:"Greek",en:"English",eo:"Esperanto",es:"Spanish",et:"Estonian",eu:"Basque",fa:"Persian",fi:"Finnish",fil:"Filipino",fo:"Faroese",fr:"French",ga:"Irish",gl:"Galician",gu:"Gujarati",he:"Hebrew",hi:"Hindi",hr:"Croatian",hu:"Hungarian",hy:"Armenian",id:"Indonesian",is:"Icelandic",it:"Italian",ja:"Japanese",ka:"Georgian",kk:"Kazakh",km:"Khmer",kn:"Kannada",ko:"Korean",ku:"Kurdish",ky:"Kyrgyz",lo:"Lao",lt:"Lithuanian",lv:"Latvian",mk:"Macedonian",ml:"Malayalam",mn:"Mongolian",mr:"Marathi",ms:"Malay",mt:"Maltese",my:"Burmese",nb:"Norwegian Bokmål",ne:"Nepali",nl:"Dutch",nn:"Norwegian Nynorsk",no:"Norwegian",pa:"Punjabi",pl:"Polish",ps:"Pashto",pt:"Portuguese",ro:"Romanian",ru:"Russian",si:"Sinhala",sk:"Slovak",sl:"Slovenian",sq:"Albanian",sr:"Serbian",sv:"Swedish",sw:"Swahili",ta:"Tamil",te:"Telugu",th:"Thai",tk:"Turkmen",tl:"Tagalog",tr:"Turkish",tt:"Tatar",uk:"Ukrainian",ur:"Urdu",uz:"Uzbek",vi:"Vietnamese",zh:"Chinese",zu:"Zulu"},Xt={AR:"Argentina",AT:"Austria",AU:"Australia",BE:"Belgium",BR:"Brazil",CA:"Canada",CH:"Switzerland",CL:"Chile",CN:"China",CO:"Colombia",CZ:"Czechia",DE:"Germany",DK:"Denmark",ES:"Spain",FI:"Finland",FR:"France",GB:"United Kingdom",HK:"Hong Kong",IE:"Ireland",IN:"India",IT:"Italy",JP:"Japan",KR:"South Korea",MX:"Mexico",NL:"Netherlands",NO:"Norway",NZ:"New Zealand",PL:"Poland",PT:"Portugal",RU:"Russia",SE:"Sweden",TW:"Taiwan",UA:"Ukraine",US:"United States",ZA:"South Africa"},en=new Set(["ar","arc","dv","fa","he","ku","ps","sd","ug","ur","yi"]);function Vt(o){let i=Bt[o];if(i)return i;let[r,a]=o.split("-"),c=r===void 0?void 0:Bt[r.toLowerCase()];if(!c)return o;if(a===void 0)return c;let f=a.toUpperCase();return`${c} (${Xt[f]??f})`}function Gt(o){let i=o.split("-")[0];return i!==void 0&&en.has(i.toLowerCase())}function An(o){return o.i18n.locales.map((i)=>({code:i,name:Vt(i),rtl:Gt(i),isDefault:i===o.i18n.defaultLocale}))}var q="webhooks",U="webhook_deliveries",sn=25,ln=200,cn=5,dn="10s";function Kt(o){let{config:i}=o,r=(y,P)=>(o.fetch??globalThis.fetch)(y,P),a=o.now??(()=>new Date),c=i.webhooks,f=c?.delivery?.retries??cn,h=w(c?.delivery?.timeout??dn),g=c?.delivery?.dlq!==!1,C=c?.delivery?.backoff==="linear",v=()=>{if(c?.enabled)return;throw new e("Webhooks are switched off; set webhooks.enabled to true.",{status:501,code:"webhooks_disabled"})},D=(y)=>C?y*30000:Math.min(3600000,1000*2**y),I=async()=>{let y=await o.database();return y.transaction((P)=>y.query(P,{table:q,where:t("active",!0)}))},F=async(y,P,W,E=a())=>{let k=await o.database(),T=Number(y.attempt??0)+1;if((await k.transaction((z)=>k.mutate(z,{kind:"update",table:U,where:s(t("id",String(y.id)),t("status","pending"),t("attempt",Number(y.attempt??0)),t("next_attempt_at",y.next_attempt_at==null?null:new Date(l(y.next_attempt_at))),R(t("next_attempt_at",null),M("next_attempt_at",E))),set:{attempt:T,next_attempt_at:new Date(E.getTime()+h+30000)},returning:!1}))).count!==1)return ie(y);if(T>f){let z={status:"failed",next_attempt_at:null,error:"Delivery lease expired; attempt budget exhausted."};return await k.transaction((re)=>d(k,re).update(U,s(t("id",String(y.id)),t("attempt",T)),z)),ie({...y,...z,attempt:T})}let N=typeof P.secret==="string"&&P.secret||c?.signing?.secret||"",G={"content-type":"application/json","user-agent":"heyo-cms","x-heyo-event-id":String(y.event_id),"x-heyo-event-type":String(y.event_type),"x-heyo-delivery-id":String(y.id),"x-heyo-attempt":String(T),...hn(P.headers)};if(N.length>0)G[Ae]=await ke(W,N);let K=null,ue=null,ne=null;try{let z=await r(String(P.url),{method:"POST",headers:G,body:W,signal:AbortSignal.timeout(h)});if(K=z.status,ue=await un(z),!z.ok)ne=`Responded ${z.status}.`}catch(z){ne=z instanceof Error?z.message:String(z)}let xe=ne===null,pe=T>=f,Oe=a(),Pe=xe?{status:"delivered",attempt:T,response_status:K,response_body:ue,error:null,next_attempt_at:null,delivered_at:Oe}:{status:pe?"failed":"pending",attempt:T,response_status:K,response_body:ue,error:ne,next_attempt_at:pe?null:new Date(Oe.getTime()+D(T)),delivered_at:null},st=await k.transaction(async(z)=>(await d(k,z).update(U,s(t("id",String(y.id)),t("status","pending"),t("attempt",T)),Pe),{...y,...Pe}));if(!xe&&pe&&g)await(await o.database()).transaction((re)=>o.emit(re,[{type:"job.failed",data:{job:"webhook-delivery",webhookId:String(y.webhook_id),deliveryId:String(y.id),eventId:String(y.event_id),eventType:String(y.event_type),attempts:T,error:ne??"unknown"},previous:null}],{actor:null})),o.deliver();return ie(st)},B=async(y,P)=>{let W=await o.database(),E=JSON.stringify(P),k=`whd_${P.id}_${String(y.id)}`,T=await W.transaction((N)=>d(W,N).findOne(U,t("id",k)));if(T)return ie(T);let L=await W.transaction(async(N)=>d(W,N).insert(U,{id:k,webhook_id:String(y.id),event_id:P.id,event_type:P.type,status:"pending",attempt:0,request_body:P,response_status:null,response_body:null,error:null,next_attempt_at:a(),delivered_at:null,created_at:a()}));return F(L,y,E)};return{get enabled(){return c?.enabled===!0},async list(y={}){v();let P=await o.database();return(await P.transaction((E)=>P.query(E,{table:q,...y.active===void 0?{}:{where:t("active",y.active)},orderBy:[m("created_at","desc"),m("id","desc")]}))).map(de)},async get(y){v();let P=await o.database(),W=await P.transaction(async(E)=>d(P,E).findOne(q,t("id",y)));return W?de(W):null},async create(y){v(),Ze(y.url),Qe(y.events);let P=await o.database(),W=a();return await P.transaction(async(k)=>{let L=await d(P,k).insert(q,{id:b("whk"),url:y.url,events:y.events,filters:y.filters??null,headers:y.headers??null,secret:y.secret??null,active:y.active!==!1,created_at:W,updated_at:W});return de(L)})},async update(y){if(v(),y.url!==void 0)Ze(y.url);if(y.events!==void 0)Qe(y.events);let P=await o.database();return P.transaction(async(W)=>{let E=d(P,W),k=await E.findOne(q,t("id",y.id));if(!k)throw e.notFound("No such webhook.");let T={updated_at:a()};if(y.url!==void 0)T.url=y.url;if(y.events!==void 0)T.events=y.events;if(y.filters!==void 0)T.filters=y.filters;if(y.headers!==void 0)T.headers=y.headers;if(y.secret!==void 0)T.secret=y.secret;if(y.active!==void 0)T.active=y.active;await E.update(q,t("id",y.id),T);let L=await E.findOne(q,t("id",y.id));return de(L??{...k,...T})})},async remove(y){v();let P=await o.database();return P.transaction(async(W)=>{let E=d(P,W);return await E.delete(U,t("webhook_id",y.id)),await E.delete(q,t("id",y.id))>0})},async deliveries(y={}){v();let P=await o.database(),W=Math.min(ln,Math.max(1,y.limit??sn)),E=[m("created_at","desc"),m("id","desc")],k=[];if(y.webhookId)k.push(t("webhook_id",y.webhookId));if(y.status)k.push(t("status",y.status));if(y.eventId)k.push(t("event_id",y.eventId));let T=k.length===0?void 0:s(...k),L=await P.transaction((K)=>P.query(K,{table:U,...y.cursor?{where:T===void 0?J(y.cursor,E):s(T,J(y.cursor,E))}:T===void 0?{}:{where:T},orderBy:E,limit:W+1})),N=L.slice(0,W),G=N.at(-1);return{entries:N.map((K)=>ie(K,y.includeBody===!0)),limit:W,hasNextPage:L.length>W,cursor:G?V(G,E):null}},async test(y){v();let P=await o.database(),W=await P.transaction(async(T)=>d(P,T).findOne(q,t("id",y.id)));if(!W)throw e.notFound("No such webhook.");let E=y.actor??null,k={id:b("evt"),type:"webhook.test",createdAt:a().toISOString(),actor:E?{id:E.id,source:E.source}:null,data:{message:"A test delivery from Heyo CMS. Verify the signature exactly as you would for a real event.",webhookId:String(W.id)},previous:null};return B(W,k)},async retry(y){v();let P=await o.database(),{delivery:W,subscription:E}=await P.transaction(async(L)=>{let N=d(P,L),G=await N.findOne(U,t("id",y.id));if(!G)throw e.notFound("No such delivery.");let K=await N.findOne(q,t("id",String(G.webhook_id)));if(!K)throw e.notFound("That webhook is gone.");return{delivery:G,subscription:K}}),k=JSON.stringify(W.request_body??{}),T=await P.transaction(async(L)=>d(P,L).insert(U,{id:ve("whd"),webhook_id:String(E.id),event_id:String(W.event_id),event_type:String(W.event_type),status:"pending",attempt:0,request_body:W.request_body??null,response_status:null,response_body:null,error:null,next_attempt_at:a(),delivered_at:null,created_at:a()}));return F(T,E,k)},async attemptDelivery(y,P=a()){let W=await o.database(),E=await W.transaction(async(k)=>{let T=d(W,k),L=await T.findOne(U,t("id",y));if(!L||L.status!=="pending")return null;let N=await T.findOne(q,t("id",String(L.webhook_id)));return N?{row:L,subscription:N}:null});if(!E)return null;return F(E.row,E.subscription,JSON.stringify(E.row.request_body??{}),P)},async dispatch(y){if(c?.enabled!==!0)return;let P=await I();for(let W of P){if(!fn(W,y))continue;await B(W,y)}},async drain(y={}){let P={attempted:0,delivered:0,failed:0};if(c?.enabled!==!0)return P;let W=await o.database(),E=y.now??a(),k=await W.transaction((T)=>W.query(T,{table:U,where:s(t("status","pending"),R(t("next_attempt_at",null),M("next_attempt_at",E))),orderBy:[m("next_attempt_at","asc"),m("id","asc")],limit:y.limit??50}));for(let T of k){let L=await W.transaction(async(G)=>d(W,G).findOne(q,t("id",String(T.webhook_id))));if(!L)continue;P.attempted+=1;let N=await F(T,L,JSON.stringify(T.request_body??{}),E);if(N.status==="delivered")P.delivered+=1;else if(N.status==="failed")P.failed+=1}return P},async wants(y){if(c?.enabled!==!0)return!1;return(await I()).some((W)=>Xe(W,y))}}}async function un(o){let i=o.body?.getReader();if(!i)return"";let r=[],a=0;try{while(a<2000){let{value:h,done:g}=await i.read();if(g)break;let C=h.slice(0,2000-a);r.push(C),a+=C.length}}finally{await i.cancel().catch(()=>{}),i.releaseLock()}let c=new Uint8Array(a),f=0;for(let h of r)c.set(h,f),f+=h.length;return new TextDecoder().decode(c)}function Xe(o,i){return Ye(o.events).some((a)=>{if(a==="*"||a===i)return!0;if(!a.endsWith("*"))return!1;return i.startsWith(a.slice(0,-1))})}function fn(o,i){if(!Xe(o,i.type))return!1;let r=o.filters??null;if(!r)return!0;let a=i.data;if(r.collections?.length){let c=typeof a.collection==="string"?a.collection:null;if(!c||!r.collections.includes(c))return!1}if(r.locales?.length){let c=mn(a);if(c.length>0&&!c.some((f)=>r.locales?.includes(f)))return!1}return!0}function mn(o){if(typeof o.locale==="string")return[o.locale];if(Array.isArray(o.locales))return o.locales.filter((i)=>typeof i==="string");return[]}function de(o){return{id:String(o.id),url:String(o.url),events:Ye(o.events),filters:o.filters?u(o.filters):null,headers:o.headers?u(o.headers):null,hasSecret:typeof o.secret==="string"&&o.secret.length>0,active:o.active===!0||o.active===1,createdAt:l(o.created_at),updatedAt:l(o.updated_at)}}function ie(o,i=!1){return{id:String(o.id),webhookId:String(o.webhook_id),eventId:String(o.event_id),eventType:String(o.event_type),status:String(o.status)??"pending",attempt:Number(o.attempt??0),responseStatus:o.response_status===null||o.response_status===void 0?null:Number(o.response_status),responseBody:o.response_body===null||o.response_body===void 0?null:String(o.response_body),error:o.error===null||o.error===void 0?null:String(o.error),nextAttemptAt:l(o.next_attempt_at),deliveredAt:l(o.delivered_at),createdAt:l(o.created_at),...i?{requestBody:o.request_body===null||o.request_body===void 0?null:u(o.request_body)}:{}}}function Ye(o){if(!Array.isArray(o))return[];return o.filter((i)=>typeof i==="string")}function hn(o){if(typeof o!=="object"||o===null)return{};let i={};for(let[r,a]of Object.entries(o)){if(r.toLowerCase().startsWith("x-heyo-"))continue;if(r.toLowerCase()===Ae)continue;if(typeof a==="string")i[r]=a}return i}function Ze(o){let i;try{i=new URL(o)}catch{throw e.validation(`"${o}" is not a URL.`)}if(i.protocol!=="https:"&&i.protocol!=="http:")throw e.validation("A webhook URL has to be http or https.")}function Qe(o){if(o.length===0)throw e.validation("A webhook has to subscribe to at least one event type.");for(let i of o)if(!/^[a-z][a-z0-9.]*\*?$|^\*$/.test(i))throw e.validation(`"${i}" is not an event type; use "document.updated", "document.*" or "*".`)}var bn="webhook_deliveries";function Zt(o){return{name:"webhook-retries",failureType:"webhook.delivery",failurePayload:(i)=>({deliveryId:String(i.id),webhookId:String(i.webhook_id),eventId:String(i.event_id),eventType:String(i.event_type),attempt:Number(i.attempt??0)}),due:async(i,r,a)=>{let c=await i.database();return c.transaction((f)=>c.query(f,{table:bn,where:s(t("status","pending"),R(t("next_attempt_at",null),M("next_attempt_at",r))),orderBy:[m("next_attempt_at","asc"),m("id","asc")],limit:a}))},run:async(i,r,a)=>{await o.attemptDelivery(String(r.id),a)}}}var yn=new Set(["activity","admin","ai","auth","globals","jobs","locales","media","openapi.json","panel","roles","trash","users","webhooks"]),vn=/^[a-z][a-z0-9_]*$/,wn=/^[a-z][a-zA-Z0-9_]*$/,Cn=/^[a-z][a-z0-9-]*$/,Sn=/^[a-z]{2,3}(-[A-Za-z0-9]{2,8})*$/;function Yn(o){return{...o,kind:"collection"}}function Qn(o){return{...o,kind:"global"}}function Xn(o){let i=kn(o),r=_t({collections:i.collections,globals:i.globals,pluginTables:i.plugins.flatMap((k)=>k.schema?.tables??[])}),a=new Map;for(let k of i.plugins)for(let[T,L]of Object.entries(k.events??{})){if(!L)continue;let N=a.get(T)??new Set;N.add(L),a.set(T,N)}let c,f,g=new yt({config:i,database:()=>E.database(),dispatch:async(k)=>{let T=[...a.get(k.type)??[],...a.get("*")??[]];for(let L of T)await L(k);await F.dispatch(k)}}),C=pn({config:i,database:()=>E.database(),emit:(k,T,L)=>g.appendEvents(k,T,L),deliver:()=>g.deliverSoon()}),v=Qt({config:i,database:()=>E.database(),emit:(k,T,L)=>g.appendEvents(k,T,L),deliver:()=>g.deliverSoon()}),D=An(i),I=De({database:()=>E.database()}),F=Kt({config:i,database:()=>E.database(),emit:(k,T,L)=>g.appendEvents(k,T,L),deliver:()=>g.deliverSoon()}),B=St({config:i,database:()=>E.database(),cms:()=>E,emit:(k,T,L)=>g.appendEvents(k,T,L),deliver:()=>g.deliverSoon()}),y=g.buildJobs();if(i.webhooks?.enabled)y.register(Zt(F));if(i.uploads)y.register(Yt({config:i,database:()=>E.database(),storage:()=>v.storage(),emit:(k,T,L)=>g.appendEvents(k,T,L),deliver:()=>g.deliverSoon()}));let P,W=()=>(P??=qe(E),P),E={_config:Object.freeze(i),schema:r,collections:o.collections,handler:(k)=>W().handler(k),_router:{routes:()=>W().routes()},api:g.buildApi(),globals:g.buildGlobals(),auth:C,media:v,ai:B,webhooks:F,trash:g.buildTrash(),jobs:y,locales:{list:()=>D},activity:I,inspect(){return{basePath:i.basePath,database:{id:c?.id??"unresolved",capabilities:c?.capabilities??{transactions:!1,sqlMigrations:!1,jsonQuery:!1}},storage:Gn(i),collections:zn(i),schema:r,hooks:zt(i),routes:W().routes(),admin:{path:`${i.basePath}${i.admin.path}`,panel:i.admin.assets?.id??null},plugins:qn(i),auth:Un(i),ai:{enabled:i.ai!==void 0,defaultModel:i.ai?.defaultModel??null,assistant:i.ai!==void 0&&i.ai.assistant?.enabled!==!1,actions:me(),providers:Object.keys(i.ai?.auth??{}).sort(),panelManagedKeys:i.ai?.storage?.secret!==void 0},webhooks:{enabled:i.webhooks?.enabled===!0,signed:i.webhooks?.signing?.secret!==void 0,retries:i.webhooks?.delivery?.retries??5},editor:Te(),jobs:E.jobs.list(),trash:{enabled:i.trash.enabled,purgeAfter:i.trash.purgeAfter===!1?null:i.trash.purgeAfter}}},async database(){if(c)return c;return f??=Promise.resolve(typeof i.database==="function"?i.database():i.database).then((k)=>(k.useSchema(r),c=k,k)),f},on(k,T){let L=a.get(k)??new Set;return L.add(T),a.set(k,L),()=>{L.delete(T)}},drainEvents(k){return g.drainEvents(k)},async close(){await g.settle(),await c?.close?.(),c=void 0,f=void 0,a.clear()}};return g.bind(E),E}function kn(o){let i=Nn(o.basePath??ge),r=new Set(ot()),a=o.plugins??[];jn(a);let c=Pn(o.collections,a),f=Tn({plugins:a,collections:c,globals:o.globals??{},basePath:i}),h={};for(let[v,D]of Object.entries(c))h[v]=nt(v,D,"collection",r);let g={};for(let[v,D]of Object.entries(o.globals??{}))g[v]=nt(v,D,"global",r);Rn({...h,...g}),Fn({...h,...g}),_n({...h,...g}),On(o,h,g),Dn({...h,...g}),In(o),Jn(o),Wn(o),En(o,i),Mn(o),Hn(o);let C=o.trash?.purgeAfter??"30d";if(typeof C==="string")w(C,"trash.purgeAfter");return{basePath:i,database:o.database,admin:{...o.admin,path:Bn(o.admin?.path??et)},...o.rbac===void 0?{}:{rbac:o.rbac},i18n:$n(o.i18n),...o.uploads===void 0?{}:{uploads:o.uploads.publicPath===void 0?o.uploads:{...o.uploads,publicPath:x(o.uploads.publicPath.trim())}},...o.ai===void 0?{}:{ai:o.ai},...o.webhooks===void 0?{}:{webhooks:o.webhooks},trash:{enabled:o.trash?.enabled??!0,purgeAfter:C},collections:h,globals:g,...o.hooks===void 0?{}:{hooks:o.hooks},...o.databaseHooks===void 0?{}:{databaseHooks:o.databaseHooks},plugins:a,pluginHooks:f,...o.telemetry===void 0?{}:{telemetry:o.telemetry},migrationsDirectory:o.migrations?.directory??tt}}function nt(o,i,r,a){if(!vn.test(o))throw new n(`collections.${o}`,"a collection name must be lowercase letters, digits and underscores, starting with a letter");let c=i.slug??o.replaceAll("_","-");if(!Cn.test(c))throw new n(`collections.${o}.slug`,`"${c}" is not a URL-safe slug`);if(a.has(o)||a.has(c))throw new n(`collections.${o}`,`"${o}" is a reserved system name; pick another`);if(yn.has(c))throw new n(`collections.${o}`,`"${c}" is a URL the CMS serves itself; give the collection another slug`);let f={};for(let[h,g]of Object.entries(i.fields)){if(!wn.test(h))throw new n(`collections.${o}.fields.${h}`,"a field name must be letters, digits and underscores, starting with a lowercase letter");if(g.required&&g.admin?.hidden===!0)throw new n(`collections.${o}.fields.${h}.admin.hidden`,"a hidden field cannot be required; remove required or show the field");f[h]=g}if(Object.keys(f).length===0)throw new n(`collections.${o}.fields`,"a collection needs at least one field");return{name:o,slug:c,label:i.label??Kn(o),kind:r,fields:f,access:i.access??{},...i.admin===void 0?{}:{admin:i.admin}}}function Rn(o){let i=new Map;for(let r of Object.values(o)){let a=i.get(r.slug);if(a)throw new n(`collections.${r.name}.slug`,`"${r.slug}" is already used by "${a}"; slugs are URLs and index names`);i.set(r.slug,r.name)}}function _n(o){let i=new Set([...Object.keys(o),...ot()]);for(let r of Object.values(o))for(let[a,c]of Object.entries(r.fields)){if(!c.relationTo)continue;if(!i.has(c.relationTo))throw new n(`collections.${r.name}.fields.${a}`,`relation points at "${c.relationTo}", which is not a collection`)}}function On(o,i,r){for(let a of Object.keys(o.databaseHooks??{}))if(!(a in i)&&!(a in r))throw new n(`databaseHooks.${a}`,"no collection or global with this name")}function Pn(o,i){let r={...o},a=new Map;for(let c of i)for(let[f,h]of Object.entries(c.schema?.collections??{})){if(f in o)throw new n(`plugins.${c.id}.schema.collections.${f}`,`the configuration already declares a collection called "${f}"`);let g=a.get(f);if(g)throw new n(`plugins.${c.id}.schema.collections.${f}`,`"${g}" already declares a collection called "${f}"`);a.set(f,c.id),r[f]=h}return r}function Tn(o){let i=[],r=new Map;for(let a of o.plugins){if(!a.extendCollections)continue;let c=a.extendCollections({collections:o.collections,basePath:o.basePath});for(let f of c){let h=o.collections[f.collection]??o.globals[f.collection];if(!h)throw new n(`plugins.${a.id}.extendCollections`,`patches "${f.collection}", which is not a collection or a global`);for(let[g,C]of Object.entries(f.fields??{})){let v=r.get(`${f.collection}.${g}`);if(g in h.fields)throw new n(`plugins.${a.id}.extendCollections`,v?`"${v}" already added "${g}" to ${f.collection}`:`${f.collection} already has a field called "${g}"`);r.set(`${f.collection}.${g}`,a.id),h.fields={...h.fields,[g]:C}}if(f.hooks)i.push({plugin:a.id,collection:f.collection,hooks:f.hooks,priority:0})}}return i}function Dn(o){for(let i of Object.values(o))for(let[r,a]of Object.entries(i.fields)){if(a.aiGenerate!==void 0)it(i,r,a.aiGenerate,`collections.${i.name}.fields.${r}.aiGenerate`);for(let[c,f]of Object.entries(a.ai??{})){if(f!==!0)it(i,r,f,`collections.${i.name}.fields.${r}.ai.${c}`);let h=Z(c),g=`collections.${i.name}.fields.${r}.ai.${c}`;if(!h){if(f===!0||f.prompt===void 0)throw new n(g,"is not a registered AI action; register it with defineAiAction() or give it a prompt");continue}if(!h.appliesTo.includes("*")&&!h.appliesTo.includes(a.type))throw new n(g,`does not apply to a ${a.type} field; it applies to ${h.appliesTo.join(", ")}`);if(h.requiresLocalized&&!a.localized)throw new n(g,"needs a localized field; this one stores a single value for every language")}}}function it(o,i,r,a){if(r.context!==void 0&&!Array.isArray(r.context))throw new n(`${a}.context`,"must be an array of field names");let c=new Set;for(let f of r.context??[]){if(typeof f!=="string"||!o.fields[f]||f===i||c.has(f))throw new n(`${a}.context`,`"${f}" must name a different, existing field of ${o.name} (only once)`);c.add(f)}if(r.maxLength!==void 0&&(!Number.isInteger(r.maxLength)||r.maxLength<1))throw new n(`${a}.maxLength`,"must be a positive integer");if(r.model&&(!r.model.provider||!r.model.model))throw new n(`${a}.model`,"needs a provider and a model")}function jn(o){let i=new Set;for(let a of o){if(i.has(a.id))throw new n(`plugins.${a.id}`,"two plugins share this id");i.add(a.id)}let r=new Map;for(let a of o)for(let c of a.routes??[]){let f=`${c.method} ${c.root===!0?"(root) ":""}${c.path}`,h=r.get(f);if(h)throw new n(`plugins.${a.id}.routes`,`"${f}" is already registered by "${h}"`);r.set(f,a.id)}}function $n(o){let i=o?.locales,r=o?.defaultLocale??i?.[0]??"en";return{defaultLocale:r,locales:i??[r]}}function In(o){let i=o.i18n;if(!i)return;let r=i.locales;if(r!==void 0){if(r.length===0)throw new n("i18n.locales","at least one locale; leave the section out for a single-language site");for(let c of r)if(!Sn.test(c))throw new n("i18n.locales",`"${c}" is not a locale code; use a BCP 47 tag such as "en" or "pt-BR"`);if(new Set(r).size!==r.length)throw new n("i18n.locales","duplicate locale codes")}let a=i.defaultLocale;if(a!==void 0&&r&&!r.includes(a))throw new n("i18n.defaultLocale",`"${a}" is not in i18n.locales (${r.map((c)=>`"${c}"`).join(", ")})`)}function Jn(o){let i=o.rbac;if(!i)return;for(let[r,a]of Object.entries(i.roles)){if(!/^[a-z][a-z0-9_-]*$/.test(r))throw new n(`rbac.roles.${r}`,"a role name must be lowercase letters, digits, dashes and underscores, starting with a letter");for(let c of a){if(c==="*")continue;if(!/^[a-z0-9_*-]+:[a-z0-9_*-]+$/.test(c))throw new n(`rbac.roles.${r}`,`"${c}" is not a permission; use "collection:action" or "*"`)}}if(i.defaultRole&&!(i.defaultRole in i.roles))throw new n("rbac.defaultRole",`"${i.defaultRole}" is not one of the configured roles`)}function Wn(o){let i=o.admin?.auth;if(!i)return;let r=new Set;for(let a of i.methods){if(r.has(a))throw new n("admin.auth.methods",`"${a}" is listed twice`);r.add(a)}for(let a of i.apiKeys?.scopes??[])if(!_e(a))throw new n("admin.auth.apiKeys.scopes",`"${a}" is not a scope; use "read", "write", "delete", "*" or "collection:action"`);if(i.sso?.mapRoles&&!o.rbac)throw new n("admin.auth.sso.mapRoles","maps claims onto roles, but no roles are configured; add rbac.roles")}function En(o,i){let r=o.uploads;if(!r)return;if(r.publicPath!==void 0)Ln(r.publicPath,i);if(r.limits?.maxFileSize)se(r.limits.maxFileSize,"uploads.limits.maxFileSize");let a=r.retention?.purgeAfter;if(typeof a==="string")w(a,"uploads.retention.purgeAfter");let c=r.images,f=c?.quality;if(f!==void 0&&(f<1||f>100))throw new n("uploads.images.quality","must be between 1 and 100");for(let[h,g]of Object.entries(c?.variants?.sizes??{})){if(!/^[a-z][a-z0-9-]*$/.test(h))throw new n(`uploads.images.variants.sizes.${h}`,"a size name ends up in a URL; use lowercase letters, digits and dashes");if(io.includes(h))throw new n(`uploads.images.variants.sizes.${h}`,`"${h}" is a media endpoint; pick another size name`);if(g.width===void 0&&g.height===void 0)throw new n(`uploads.images.variants.sizes.${h}`,"needs a width, a height, or both");if(g.fit==="cover"&&(g.width===void 0||g.height===void 0))throw new n(`uploads.images.variants.sizes.${h}`,'fit: "cover" needs both a width and a height')}if(c&&!c.processor){let h=c.convert!==void 0?"convert":c.maxDimensions!==void 0?"maxDimensions":c.variants?.mode==="pregenerate"?'variants.mode: "pregenerate"':null;if(h)throw new n("uploads.images.processor",`${h} has to render pixels, and nothing here can. Add a processor from "@heyo-sh/heyo-cms/uploads" (sharpImages() on Node, cloudflareImages() on Workers), or drop the option.`)}}function Fn(o){for(let i of Object.values(o))for(let[r,a]of Object.entries(i.fields)){if(a.type!=="slug")continue;let c=a.options.from;if(c===void 0)continue;let f=i.fields[String(c)],h=`collections.${i.name}.fields.${r}.from`;if(!f||c===r)throw new n(h,`"${String(c)}" is not another field of ${i.name}`);if(!["text","textarea","email","url","select"].includes(f.type))throw new n(h,`"${String(c)}" is a ${f.type} field; a slug is made from text`)}}function Ln(o,i){let r=x(o.trim()),a="uploads.publicPath";if(r.length===0&&o.trim().startsWith("/"))throw new n("uploads.publicPath",'cannot be "/"; use a path such as "/media"');if(!r.startsWith("/"))throw new n("uploads.publicPath",'must start with "/"');if(!r.split("/").slice(1).every((h)=>/^[A-Za-z0-9._~-]+$/.test(h)))throw new n("uploads.publicPath","may only contain letters, digits, dots, dashes, underscores and tildes between slashes");let f=(h,g)=>h===g||h.startsWith(`${g}/`);if(f(r,i)||f(i,r))throw new n("uploads.publicPath",`"${r}" overlaps basePath "${i}"; files are served from <basePath>/media already — pick a path outside it, such as "/media"`)}function Mn(o){let i=o.ai;if(!i)return;let r=new Set(Object.keys(i.auth??{})),a=i.storage?.secret!==void 0;if(r.size===0&&!a&&i.complete===void 0)throw new n("ai.auth","AI is configured without credentials. Add ai.auth, set ai.storage.secret to manage keys in the panel, or remove the section to disable AI");if(!a&&i.complete===void 0&&!r.has(i.defaultModel.provider))throw new n("ai.defaultModel.provider",`"${i.defaultModel.provider}" has no entry in ai.auth`);let c=i.assistant,f=c?.model?.provider;if(f&&!a&&i.complete===void 0&&!r.has(f))throw new n("ai.assistant.model.provider",`"${f}" has no entry in ai.auth`);for(let[h,g]of[["maxTurns",1],["maxToolCalls",1],["timeoutMs",1000]]){let C=c?.[h];if(C===void 0)continue;if(!Number.isInteger(C)||C<g)throw new n(`ai.assistant.${h}`,`must be an integer of at least ${g}; it is a budget the server enforces, not a hint to the model`)}if(i.storage&&i.storage.secret.length<16)throw new n("ai.storage.secret","must be at least 16 characters; it encrypts the provider keys in the database")}function Hn(o){let i=o.webhooks;if(!i?.enabled)return;if(!i.signing?.secret)throw new n("webhooks.signing.secret","webhooks must be signed; set a secret");if(i.delivery?.timeout)w(i.delivery.timeout,"webhooks.delivery.timeout")}function Bn(o){let i=o.trim();if(!i.startsWith("/"))throw new n("admin.path",'must start with "/"');if(/[?#]/.test(i)||i.includes("//"))throw new n("admin.path","cannot contain a query, a fragment or an empty segment");let r=x(i);if(r.length===0)return"";return r}function Nn(o){let i=o.trim();if(!i.startsWith("/"))throw new n("basePath",'must start with "/"');if(/[?#]/.test(i))throw new n("basePath","cannot contain a query or fragment");if(i.includes("//"))throw new n("basePath","cannot contain empty segments");let r=x(i);if(r.length===0)throw new n("basePath",'cannot be "/"');return r}function zn(o){return[...Object.values(o.collections),...Object.values(o.globals)].map((i)=>({name:i.name,slug:i.slug,kind:i.kind,fields:Object.entries(i.fields).map(([r,a])=>({name:r,type:a.type,localized:a.localized,required:a.required}))}))}function Gn(o){let i=o.uploads;if(!i)return null;let r=i.retention?.purgeAfter??"30d";return{id:typeof i.storage==="function"?"unresolved":i.storage.id,variants:i.images?.variants?.mode??null,processor:i.images?.processor?.id??null,purgeAfter:r===!1?null:r}}function qn(o){return o.plugins.map((i)=>({id:i.id,collections:Object.keys(i.schema?.collections??{}).sort(),tables:(i.schema?.tables??[]).map((r)=>r.name).sort(),routes:i.routes?.length??0,hooks:(i.hooks?.length??0)+o.pluginHooks.filter((r)=>r.plugin===i.id).length,migrations:(i.migrations??[]).map((r)=>r.id),client:i.client!==void 0,admin:i.admin!==void 0}))}function Un(o){let i=o.admin.auth;return{methods:i?.methods??[],twoFactor:i?.twoFactor===!0,apiKeys:i?.apiKeys?.enabled===!0,sso:i?.sso?.issuer??null,roles:Object.keys(o.rbac?.roles??{}).sort(),customRoles:o.rbac?.customRoles===!0}}function Kn(o){return o.replaceAll("_"," ").replace(/^./,(i)=>i.toUpperCase())}function bt(o="system"){return{id:o,source:"session",roles:["admin"],permissions:["*"]}}
|
|
2
|
+
export{ut,Ie,He,zt,pt,mt,ft,ht,xn,Ht,yt,te,Bt,Vt,Gt,An,Kt,Zt,Yn,Qn,Xn,bt};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{Z,Le,
|
|
1
|
+
import{Z,Le,Ot,_,j}from"./index-2j6d79fk.js";import{l}from"./index-pkxgzw6e.js";import{t}from"./index-q6jkbsjp.js";import{d}from"./index-9g2n7xa6.js";import{X}from"./index-twqpdtfh.js";import{ie,fn}from"./index-cnzt9x9x.js";import{b}from"./index-qgtvymh2.js";import{e}from"./index-x72d1hzh.js";var K="v1",ee=12;async function L(n){if(n.length<16)throw new e("ai.storage.secret must be at least 16 characters; it encrypts provider keys.",{status:500,code:"ai_secret_too_short"});let i=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(n));return crypto.subtle.importKey("raw",i,{name:"AES-GCM"},!1,["encrypt","decrypt"])}async function M(n,i){let r=await L(i),a=crypto.getRandomValues(new Uint8Array(ee)),c=await crypto.subtle.encrypt({name:"AES-GCM",iv:a},r,new TextEncoder().encode(n));return[K,ie(a),ie(new Uint8Array(c))].join(".")}async function I(n,i){let[r,a,c]=n.split(".");if(r!==K||!a||!c)throw new e("A stored provider key is not in a format this version can read.",{status:500,code:"ai_credential_unreadable"});let s=await L(i);try{let m=await crypto.subtle.decrypt({name:"AES-GCM",iv:fn(a)},s,fn(c));return new TextDecoder().decode(m)}catch{throw new e("A stored provider key could not be decrypted; ai.storage.secret has probably changed. Re-enter the key in the panel.",{status:500,code:"ai_credential_unreadable"})}}function E(n){return n.length<=4?"****":`…${n.slice(-4)}`}var z;async function F(){return z??=import("@mariozechner/pi-ai").catch(()=>{throw new e('AI needs "@mariozechner/pi-ai". Install it, or set ai.complete to your own implementation.',{status:500,code:"ai_runtime_missing"})}),z}async function Rn(n){let{getModel:i}=await F(),r;try{r=i(n.provider,n.model)}catch{r=void 0}if(r)return r;throw await Tn(n.provider,n.model),new e(`pi could not resolve ${n.provider}/${n.model}.`,{status:500,code:"ai_unknown_model"})}function V(n,i){let r=Sn(n);if(r.includes(i.type))return;throw new e(`The provider "${n}" needs ${r.map((a)=>`"${a}"`).join(" or ")} credentials.`,{status:500,code:"ai_auth_mismatch"})}async function to(n,i){switch(V(n,i),i.type){case"api-key":return{getApiKey:()=>i.token};case"oauth":return{getApiKey:()=>i.getAccessToken()};case"aws":{let{streamSimple:r}=await F();return{streamFn:(a,c,s)=>r(a,c,{...s,region:i.region,...i.accessKeyId===void 0?{}:{accessKeyId:i.accessKeyId},...i.secretAccessKey===void 0?{}:{secretAccessKey:i.secretAccessKey}})}}}}var te=new Set(["github-copilot","openai-codex"]);function Sn(n){if(n==="amazon-bedrock")return["aws"];if(te.has(n))return["oauth"];return["api-key"]}async function Tn(n,i){let{getModel:r,getProviders:a}=await F();try{if(r(n,i))return}catch{}if(!a().includes(n))throw new e(`The AI provider "${n}" is not in pi's catalogue.`,{status:400,code:"ai_unknown_provider"});throw new e(`The provider "${n}" has no model called "${i}".`,{status:400,code:"ai_unknown_model"})}async function no(n){try{let{getModels:i}=await F();return i(n).map((r)=>r.id)}catch{return[]}}var Ke=async(n)=>{let{complete:i,stream:r}=await F(),{model:a,auth:c}=n;V(a.provider,c);let s=await Rn(a),m={systemPrompt:n.system,messages:[{role:"user",content:[{type:"text",text:n.prompt},...(n.images??[]).map((u)=>({type:"image",data:ne(u.data),mimeType:u.contentType}))],timestamp:Date.now()}]},f={...n.maxTokens===void 0?{}:{maxTokens:n.maxTokens},...n.signal===void 0?{}:{signal:n.signal},...c.type==="api-key"?{apiKey:c.token}:{},...c.type==="oauth"?{apiKey:await c.getAccessToken()}:{},...c.type==="aws"?{region:c.region,...c.accessKeyId===void 0?{}:{accessKeyId:c.accessKeyId},...c.secretAccessKey===void 0?{}:{secretAccessKey:c.secretAccessKey}}:{}},A=await i(s,m,f);if(A.stopReason==="error"||A.errorMessage)throw new e(A.errorMessage??"The model returned an error.",{status:502,code:"ai_provider_error"});return{text:A.content.filter((u)=>u.type==="text").map((u)=>u.text).join(""),usage:Cn(A.usage)}};function Cn(n){return{input:n.input??0,output:n.output??0,total:n.totalTokens??(n.input??0)+(n.output??0),cost:n.cost?.total??0}}function ne(n){let i="";for(let r of n)i+=String.fromCharCode(r);return btoa(i)}async function q(n){let i={input:0,output:0,total:0,cost:0},r=async(s)=>{if(!s.trim())return s;let m=await n.complete({system:"Translate CMS text. Answer with the translation only, without quotes or a preamble. Keep names, placeholders and URLs intact.",prompt:`Translate from ${n.sourceLocale} to ${n.locale}. This text belongs to the ${n.fieldName} field:
|
|
2
2
|
|
|
3
|
-
${s}`,...n.signal===void 0?{}:{signal:n.signal}});i.input+=m.usage.input,i.output+=m.usage.output,i.total+=m.usage.total,i.cost+=m.usage.cost;let f=m.text.trim();if(!f)throw Error(`AI returned an empty translation for ${n.fieldName}.`);let A=s.slice(0,s.length-s.trimStart().length),o=s.slice(s.trimEnd().length);return`${A}${f}${o}`},a=async(s)=>{if(Array.isArray(s)){let f=[];for(let A of s)f.push(await a(A));return f}if(!s||typeof s!=="object")return s;let m={...s};if(s.type==="text"&&typeof s.text==="string")m.text=await r(s.text);if(s.type==="image"&&s.attrs&&typeof s.attrs==="object"&&!Array.isArray(s.attrs)){let f={...s.attrs};for(let A of["alt","title"])if(typeof f[A]==="string")f[A]=await r(f[A]);m.attrs=f}if(Array.isArray(s.content))m.content=await a(s.content);return m},c=await a(n.value);return{value:c,preview:X(c),usage:i}}var k="cms_ai_credentials";function
|
|
3
|
+
${s}`,...n.signal===void 0?{}:{signal:n.signal}});i.input+=m.usage.input,i.output+=m.usage.output,i.total+=m.usage.total,i.cost+=m.usage.cost;let f=m.text.trim();if(!f)throw Error(`AI returned an empty translation for ${n.fieldName}.`);let A=s.slice(0,s.length-s.trimStart().length),o=s.slice(s.trimEnd().length);return`${A}${f}${o}`},a=async(s)=>{if(Array.isArray(s)){let f=[];for(let A of s)f.push(await a(A));return f}if(!s||typeof s!=="object")return s;let m={...s};if(s.type==="text"&&typeof s.text==="string")m.text=await r(s.text);if(s.type==="image"&&s.attrs&&typeof s.attrs==="object"&&!Array.isArray(s.attrs)){let f={...s.attrs};for(let A of["alt","title"])if(typeof f[A]==="string")f[A]=await r(f[A]);m.attrs=f}if(Array.isArray(s.content))m.content=await a(s.content);return m},c=await a(n.value);return{value:c,preview:X(c),usage:i}}var k="cms_ai_credentials";function St(n){let{config:i}=n,r=i.ai?.complete??Ke,a=async(o)=>{try{return await r(o)}catch(u){if(u instanceof e)throw u;if(o.signal?.aborted)throw new e("The request was cancelled.",{status:499,code:"ai_aborted",cause:u});let p=u instanceof Error?u.message:"The AI provider could not complete the request.";throw new e(p,{status:502,code:"ai_provider_error",cause:u})}},c=()=>{let o=i.ai;if(!o)throw new e("This deployment has no `ai` section, so AI is switched off.",{status:501,code:"ai_disabled"});return o},s=(o)=>{let u={...i.collections,...i.globals},p=u[o];if(p)return p;let y=Object.values(u).find((h)=>h.slug===o);if(y)return y;throw e.notFound(`No collection called "${o}".`)},m=async(o)=>{let u=c(),p=await oe(n,o);if(p)return{type:"api-key",token:p};let y=u.auth?.[o];if(y)return y;throw new e(`No credentials for the AI provider "${o}". Add them to ai.auth or store them in the panel.`,{status:500,code:"ai_credentials_missing"})},f=async(o)=>{if(!i.uploads)return null;try{let u=await n.cms().media.variant({id:o});if(!u||!u.contentType.startsWith("image/"))return null;let p=new Uint8Array(await new Response(u.body).arrayBuffer());return{contentType:u.contentType,data:p}}catch{return null}},A=async(o,u,p,y)=>{await(await n.database()).transaction((g)=>n.emit(g,[{type:o,data:y===void 0?u:{...u,error:y instanceof Error?y.message:String(y)},previous:null}],{actor:p,...typeof u.collection==="string"?{collection:u.collection}:{},...typeof u.documentId==="string"?{documentId:u.documentId}:{}})),n.deliver()};return{get enabled(){return i.ai!==void 0},get assistantEnabled(){return i.ai!==void 0&&i.ai.assistant?.enabled!==!1},actions(o){return Le(o)},async run(o){let u=c(),p=s(o.collection),y=o.actor??null,h=o.locale??i.i18n.defaultLocale,g=p.fields[o.field];if(!g)throw e.notFound(`"${o.field}" is not a field of ${p.name}.`);let x=o.action==="generate"?g.aiGenerate:g.ai?.[o.action],P=o.variantTranslation===!0&&o.action==="translate"&&g.localized&&["text","textarea","richText","email","url"].includes(g.type);if(x===void 0&&!P)throw e.notFound(`"${o.action}" is not configured on ${p.name}.${o.field}.`);let S=x===void 0||x===!0?{}:x,T=Z(o.action)??Ot(o.action,S.prompt??"");if(T.requiresLocalized&&!g.localized)throw e.validation(`"${o.action}" needs a localized field; ${p.name}.${o.field} stores one value for every language.`);let C=o.sourceLocale??(T.requiresLocalized?i.i18n.defaultLocale:h),{document:R,stored:D}=await U(n,p,o,h),G=T.requiresLocalized&&C!==h?(await U(n,p,o,C,o.variantTranslation===!0)).document:R;await _(p,{actor:y,operation:"update",locale:h,rbac:i.rbac,...D===void 0?{}:{record:D}}),j(p,{[o.field]:null},y,h);let H=re(p,y,h),W=(S.context??[]).filter((w)=>{if(!(w in p.fields))throw e.validation(`ai.context names "${w}", which is not a field of ${p.name}.`);return H.has(w)}),v=S.model??u.defaultModel,Q=await m(v.provider),J={action:o.action,value:G[o.field]??null,field:g,fieldName:o.field,collection:p,context:Object.fromEntries(W.map((w)=>[w,R[w]??null])),document:R,locale:h,sourceLocale:C,options:S,model:v,actor:y,loadImage:f,complete:(w)=>a({...w,model:v,auth:Q}),...o.signal===void 0?{}:{signal:o.signal}},Y=Date.now();try{let w=P&&g.type==="richText"?await q(J):await T.run(J);return await A("ai.task.completed",{collection:p.name,field:o.field,action:o.action,locale:h,provider:v.provider,model:v.model,usage:w.usage,durationMs:Date.now()-Y,...o.id===void 0?{}:{documentId:o.id}},y),{collection:p.name,field:o.field,action:o.action,value:w.value,preview:w.preview,model:v,usage:w.usage}}catch(w){throw await A("ai.task.failed",{collection:p.name,field:o.field,action:o.action,locale:h,provider:v.provider,model:v.model,...o.id===void 0?{}:{documentId:o.id}},y,w),w}},runAssistant(o){return async function*(){let{runAssistant:u}=await import("./run-mtgvmy5x.js");yield*u({args:o,config:i,cms:n.cms(),database:()=>n.database(),authFor:m,record:A})}()},approveAssistantPlan(o){return import("./run-mtgvmy5x.js").then(({approvePlan:u})=>u({args:o,config:i,cms:n.cms(),database:()=>n.database(),record:A}))},async providers(){let o=i.ai,u=new Map;for(let[y,h]of Object.entries(o?.auth??{}))u.set(y,{provider:y,configured:!0,source:"config",type:h.type,hint:null,updatedAt:null});if(o?.storage?.secret){let y=await n.database(),h=await y.transaction((g)=>y.query(g,{table:k}));for(let g of h)u.set(String(g.provider),{provider:String(g.provider),configured:!0,source:"database",type:"api-key",hint:g.hint===null||g.hint===void 0?null:String(g.hint),updatedAt:l(g.updated_at)})}let p=o?.defaultModel.provider;if(p&&!u.has(p))u.set(p,{provider:p,configured:!1,source:null,type:null,hint:null,updatedAt:null});return[...u.values()].sort((y,h)=>y.provider.localeCompare(h.provider))},async setCredential(o){let p=c().storage?.secret;if(!p)throw new e("Set ai.storage.secret to store provider keys in the database; without it keys can only come from ai.auth.",{status:501,code:"ai_storage_disabled"});let y=o.token.trim();if(y.length===0)throw e.validation("A provider key cannot be empty.");let h=await n.database(),g=new Date,x=await M(y,p),P=E(y);return await h.transaction(async(T)=>{let C=d(h,T);if(await C.findOne(k,t("provider",o.provider)))await C.update(k,t("provider",o.provider),{secret:x,hint:P,updated_at:g});else await C.insert(k,{id:b("aic"),provider:o.provider,auth_type:"api-key",secret:x,hint:P,created_at:g,updated_at:g});return{provider:o.provider,configured:!0,source:"database",type:"api-key",hint:P,updatedAt:g.toISOString()}})},async removeCredential(o){c();let u=await n.database();return u.transaction(async(p)=>await d(u,p).delete(k,t("provider",o.provider))>0)}}}async function oe(n,i){let r=n.config.ai?.storage?.secret;if(!r)return null;let a=await n.database(),c=await a.transaction(async(s)=>d(a,s).findOne(k,t("provider",i)));if(!c||typeof c.secret!=="string")return null;return I(c.secret,r)}async function U(n,i,r,a,c=!1){let s=n.cms(),m=r.actor??null,f;if(i.kind==="global"){let o=s.globals[i.name];if(o)f=await o.get({actor:m,locale:a,...c?{fallbackLocale:!1}:{}})}else if(r.id){let A=s.api[i.name],o=A?await A.findById(r.id,{actor:m,locale:a,...c?{fallbackLocale:!1}:{}}):null;if(!o)throw e.notFound(`No ${i.name} with id "${r.id}", or it is not readable.`);f=o}return{document:{...f??{},...r.document??{}},stored:f}}function re(n,i,r){let a=new Set;for(let[c,s]of Object.entries(n.fields)){let m=s.access?.read;if(m&&!m({actor:i,locale:r}))continue;a.add(c)}return a}function At(n,i,r){let a=n.i18n.defaultLocale,c=Object.values(n.collections).map((f)=>B(f,i,a)).filter((f)=>f!==null),s=Object.values(n.globals).map((f)=>B(f,i,a)).filter((f)=>f!==null),m={collections:c,globals:s,defaultLocale:a,locales:r,media:n.uploads!==void 0,trash:n.trash.enabled};return{...m,fingerprint:ae(m)}}function B(n,i,r){if(!O(n,"read",i,r))return null;let a=[];for(let[c,s]of Object.entries(n.fields)){let m=s.access?.read;if(m&&!m({actor:i,locale:r}))continue;a.push(se(c,s,n,i,r))}return{name:n.name,slug:n.slug,label:n.label,kind:n.kind,titleField:Rt(n),fields:a,can:{read:!0,create:n.kind==="collection"&&O(n,"create",i,r),update:O(n,"update",i,r),delete:n.kind==="collection"&&O(n,"delete",i,r)}}}function se(n,i,r,a,c){let s=i.options,m=N(s.options),f=i.type==="list"&&typeof s.fields==="object"&&s.fields!==null?Object.entries(s.fields).map(([A,o])=>{let u=N(o.options.options);return{name:A,type:o.type,required:o.required,...u&&u.length>0?{options:u}:{}}}):void 0;return{name:n,type:i.type,label:typeof s.label==="string"?s.label:n,required:i.required,localized:i.localized===!0,...m&&m.length>0?{options:m}:{},...i.relationTo===void 0?{}:{relationTo:i.relationTo},...f?{rowFields:f}:{},writable:kt(r,n,a,c)}}function N(n){if(!Array.isArray(n))return;return n.map((i)=>typeof i==="string"?i:typeof i==="object"&&i!==null?String(i.value??""):"").filter((i)=>i.length>0)}function kt(n,i,r,a){let c=n.fields[i];if(!c)return!1;if(c.options.readOnly===!0)return!1;try{return j(n,{[i]:null},r,a),!0}catch{return!1}}function Xt(n,i,r,a){let c=n.fields[i]?.access?.read;return c?c({actor:r,locale:a})===!0:!0}function O(n,i,r,a){let c=n.access[i];if(!c)return!0;try{let s=c({actor:r,operation:i,locale:a});if(s instanceof Promise)return!0;return s!==!1}catch{return!0}}function Rt(n){let i=n.admin?.useAsTitle;if(i!==void 0&&n.fields[i])return i;for(let a of["title","name","label"])if(n.fields[a])return a;return Object.entries(n.fields).find(([,a])=>a.type==="text")?.[0]??null}function ae(n){let i=JSON.stringify(n),r=2166136261;for(let a=0;a<i.length;a+=1)r^=i.charCodeAt(a),r=Math.imul(r,16777619)>>>0;return r.toString(16).padStart(8,"0")}export{Rn,to,Sn,Tn,no,Ke,Cn,At,kt,Xt,Rt,St};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import{Ue,
|
|
1
|
+
import{Ue,Nn}from"./index-q6ak9ph4.js";import{$t}from"./index-qkqtxr65.js";import{Ao}from"./index-qgtvymh2.js";import{n}from"./index-x72d1hzh.js";import{mkdir as m,readdir as M,readFile as f,writeFile as h}from"node:fs/promises";import{join as p}from"node:path";var y="meta/snapshot.json",w="meta/plugins.json";class ln{directory;constructor(t){this.directory=t}async readSnapshot(){try{let t=await f(p(this.directory,y),"utf8");return JSON.parse(t)}catch{return $t()}}async writeSnapshot(t){await m(p(this.directory,"meta"),{recursive:!0}),await h(p(this.directory,y),`${JSON.stringify(t,null,2)}
|
|
2
2
|
`,"utf8")}async readPluginLog(){try{let t=await f(p(this.directory,w),"utf8"),r=JSON.parse(t);return Array.isArray(r)?r.filter((i)=>typeof i==="string"):[]}catch{return[]}}async writePluginLog(t){await m(p(this.directory,"meta"),{recursive:!0}),await h(p(this.directory,w),`${JSON.stringify(t,null,2)}
|
|
3
|
-
`,"utf8")}async list(){let t;try{t=await M(this.directory)}catch{return[]}let r=[];for(let i of t.sort()){let c=/^(\d{4}_[a-z0-9_]+)\.(sql|json)$/.exec(i);if(!c)continue;let o=await f(p(this.directory,i),"utf8"),s=c[1],a=c[2];r.push({id:s,file:i,checksum:
|
|
4
|
-
`).filter((i)=>i.startsWith("-- ")&&!/^-- \d{4}_/.test(i)).map((i)=>i.slice(3))}async function
|
|
5
|
-
export{
|
|
3
|
+
`,"utf8")}async list(){let t;try{t=await M(this.directory)}catch{return[]}let r=[];for(let i of t.sort()){let c=/^(\d{4}_[a-z0-9_]+)\.(sql|json)$/.exec(i);if(!c)continue;let o=await f(p(this.directory,i),"utf8"),s=c[1],a=c[2];r.push({id:s,file:i,checksum:Ao(o),artifact:{id:s,extension:a,content:o,summary:P(o,a)}})}return r}async write(t){await m(this.directory,{recursive:!0});let r=`${t.id}.${t.extension}`;return await h(p(this.directory,r),t.content,"utf8"),r}async nextSequence(){let r=(await this.list()).at(-1),i=r?Number(r.id.slice(0,4))+1:0;return String(i).padStart(4,"0")}}function P(t,r){if(r==="json")return JSON.parse(t).summary??[];return t.split(`
|
|
4
|
+
`).filter((i)=>i.startsWith("-- ")&&!/^-- \d{4}_/.test(i)).map((i)=>i.slice(3))}async function tr(t){let{adapter:r,store:i}=t;if(t.plugins.length===0)return[];let c=await i.readPluginLog(),o=[],s=new Set(c);for(let a of t.plugins){let e=`${a.plugin}:${a.id}`;if(s.has(e))continue;if(a.steps.length===0){s.add(e);continue}let u=`${await i.nextSequence()}_${S(a.plugin)}_${S(a.id)}`,d=r.render(a.steps,u),l=await i.write(d);s.add(e),o.push({id:u,file:l})}if(o.length>0)await i.writePluginLog([...s]);return o}function S(t){return t.toLowerCase().replace(/[^a-z0-9]+/g,"_").replace(/^_|_$/g,"")}async function qn(t){let{adapter:r,store:i,target:c}=t,o=await i.readSnapshot(),s=r.plan(o,c),a;if(s.length>0){let u=`${await i.nextSequence()}_${t.name??Nn(s)}`,d=r.render(s,u),l=await i.write(d);await i.writeSnapshot(c),a={id:u,file:l,summary:d.summary}}let e=await tr({adapter:r,store:i,plugins:t.plugins??[]});if(!a)return{created:!1,summary:[],...e.length===0?{}:{plugins:e}};return{created:!0,id:a.id,file:a.file,summary:a.summary,...e.length===0?{}:{plugins:e}}}async function Ln(t){let{adapter:r,store:i}=t,[c,o]=await Promise.all([i.list(),r.listAppliedMigrations()]),s=new Map(o.map((e)=>[e.id,e])),a={applied:[],alreadyApplied:0};for(let e of c){let g=s.get(e.id);if(g){x(e,g.checksum),a.alreadyApplied+=1;continue}await r.applyMigration(e.artifact),await r.recordMigration(e.id,e.checksum),a.applied.push(e.id)}return a}async function Fn(t){let{adapter:r,store:i}=t,[c,o]=await Promise.all([i.list(),r.listAppliedMigrations()]),s=new Map(o.map((e)=>[e.id,e])),a={applied:[],pending:[],modified:[],unplanned:[]};for(let e of c){let g=s.get(e.id);if(!g){a.pending.push(e.id);continue}if(a.applied.push(e.id),g.checksum!==e.checksum)a.modified.push(e.id)}if(t.target){let e=await i.readSnapshot();a.unplanned=r.plan(e,t.target).map((g)=>Ue(g))}return a}function x(t,r){if(t.checksum===r)return;throw new n(t.file,"was modified after it was applied; revert it and write a new migration instead")}
|
|
5
|
+
export{ln,tr,qn,Ln,Fn};
|
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import{he}from"./index-
|
|
2
|
-
`))}}),
|
|
3
|
-
`);return u(t,r)}}),
|
|
1
|
+
import{he}from"./index-rpdkj3qk.js";import{X}from"./index-twqpdtfh.js";import{It,E}from"./index-pkxgzw6e.js";import{e,n}from"./index-x72d1hzh.js";var p=new Map;function pe(t){if(!/^[a-z][a-z0-9-]*$/.test(t.id))throw new n(`ai.actions.${t.id}`,"an action id becomes a URL segment; use lowercase letters, digits and dashes");let i=p.get(t.id);if(i&&i!==t)throw new n(`ai.actions.${t.id}`,"a different action with this id is already registered");return p.set(t.id,t),t}function Z(t){return p.get(t)}function Le(t){return[...p.values()].filter((i)=>i.appliesTo.includes("*")||i.appliesTo.includes(t)).map((i)=>i.id).sort()}function me(){return[...p.keys()].sort()}function Ot(t,i){return{id:t,appliesTo:["*"],label:t,prompt:i,run:(r)=>u(r,i)}}var d=["text","textarea","richText","email","url"],To=pe({id:"generate",appliesTo:d,label:"Generate",prompt:"Write this field from the document below.",async run(t){return u(t,h(t))}}),Co=pe({id:"improve",appliesTo:d,label:"Improve",prompt:"Improve the current value: keep its meaning, tighten the wording, remove filler.",async run(t){let i=w(t);if(i.trim().length===0)throw e.validation(`There is nothing in ${t.fieldName} to improve yet.`);return u(t,[h(t),"","Current value:",i].join(`
|
|
2
|
+
`))}}),Oo=pe({id:"summarize",appliesTo:d,label:"Summarise",prompt:"Summarise the document below into this field.",async run(t){return u(t,h(t))}}),lo=pe({id:"translate",appliesTo:["*"],label:"Translate",prompt:"Translate the value into the target language.",requiresLocalized:!0,async run(t){let i=w(t);if(i.trim().length===0)throw e.validation(`${t.fieldName} is empty in ${t.sourceLocale??"the source language"}; there is nothing to translate.`);let r=[t.options.prompt??lo.prompt,`Source language: ${t.sourceLocale??"unknown"}.`,`Target language: ${t.locale??"unknown"}.`,"Keep formatting, links and names intact. Answer with the translation only.","",i].join(`
|
|
3
|
+
`);return u(t,r)}}),co=pe({id:"alt",appliesTo:["media"],label:"Describe the image",prompt:"Write alternative text for this image: one sentence, describing what is shown, no 'image of' preamble.",async run(t){let i=typeof t.value==="string"?t.value:null;if(!i)throw e.validation(`${t.fieldName} has no file selected yet.`);let r=await t.loadImage(i),o=await t.complete({system:f(t),prompt:[t.options.prompt??co.prompt,r===null?"The image itself is not available; infer from the surrounding content.":"",m(t)].filter((a)=>a.length>0).join(`
|
|
4
4
|
|
|
5
|
-
`),...r===null?{}:{images:[r]},...t.options.maxLength===void 0?{}:{maxTokens:v(t.options.maxLength)},...t.signal===void 0?{}:{signal:t.signal}}),s=b(o.text);return{value:s,preview:s,usage:o.usage}}}),
|
|
5
|
+
`),...r===null?{}:{images:[r]},...t.options.maxLength===void 0?{}:{maxTokens:v(t.options.maxLength)},...t.signal===void 0?{}:{signal:t.signal}}),s=b(o.text);return{value:s,preview:s,usage:o.usage}}}),uo=pe({id:"tags",appliesTo:["multiselect","select","relation"],label:"Suggest values",prompt:"Choose the values that fit the document below.",async run(t){let i=T(t),r=await t.complete({system:f(t),prompt:[t.options.prompt??uo.prompt,i.length>0?`Choose only from: ${i.join(", ")}.`:"Answer with short, lowercase values.","Answer with a comma-separated list and nothing else.",m(t)].join(`
|
|
6
6
|
|
|
7
7
|
`),...t.signal===void 0?{}:{signal:t.signal}}),o=r.text.split(/[,\n]/).map((l)=>l.trim().replace(/^[-*]\s*/,"")).filter((l)=>l.length>0),s=i.length===0?o:o.filter((l)=>i.includes(l));return{value:t.field.type==="multiselect"||t.field.options.many===!0?s:s[0]??null,preview:s.join(", "),usage:r.usage}}});async function u(t,i){let r=await t.complete({system:f(t),prompt:`${i}
|
|
8
8
|
|
|
@@ -10,5 +10,5 @@ ${m(t)}`.trim(),...t.options.maxLength===void 0?{}:{maxTokens:v(t.options.maxLen
|
|
|
10
10
|
${g(o)}`).join(`
|
|
11
11
|
|
|
12
12
|
`)}function g(t){if(t===null||t===void 0)return"";if(typeof t==="string")return t;if(typeof t==="number"||typeof t==="boolean")return String(t);if(Array.isArray(t))return t.map(g).join(", ");if(typeof t==="object"&&t.type)return X(t);return JSON.stringify(t)}function h(t){let i=Z(t.action)?.prompt??"";return t.options.prompt??i}function w(t){return g(t.value)}function T(t){let i=t.field.options.options;if(!Array.isArray(i))return[];return i.filter((r)=>typeof r==="string")}function b(t){return t.replace(/^["'`]+|["'`]+$/g,"").replaceAll(`
|
|
13
|
-
`," ").replace(/\s{2,}/g," ").trim()}function v(t){return Math.max(64,Math.ceil(t/3)+32)}var k={read:"read",create:"create",update:"update",delete:"delete",restore:"delete",purge:"delete"};async function _(t,i){let r=t.access[k[i.operation]];if(!r){F(t,i);return}let o=await r({actor:i.actor,operation:i.operation,locale:i.locale,...i.record===void 0?{}:{record:i.record}});if(o===!0)return;if(o===!1)throw C(t,i);return o}function F(t,i){if(!i.rbac)return;let r=
|
|
14
|
-
export{pe,Z,Le,me,
|
|
13
|
+
`," ").replace(/\s{2,}/g," ").trim()}function v(t){return Math.max(64,Math.ceil(t/3)+32)}var k={read:"read",create:"create",update:"update",delete:"delete",restore:"delete",purge:"delete"};async function _(t,i){let r=t.access[k[i.operation]];if(!r){F(t,i);return}let o=await r({actor:i.actor,operation:i.operation,locale:i.locale,...i.record===void 0?{}:{record:i.record}});if(o===!0)return;if(o===!1)throw C(t,i);return o}function F(t,i){if(!i.rbac)return;let r=It(t.name,i.operation);if(E(i.actor,r))return;throw C(t,i,r)}function C(t,i,r){let o=`${i.operation} ${t.name}`;return i.actor===null?e.unauthorized(`Not allowed to ${o}`):e.forbidden(r?`Not allowed to ${o}; the "${r}" permission is required`:`Not allowed to ${o}`)}var R=new WeakMap;function A(t){let i=R.get(t);if(i)return i;let r={read:[],update:[]};for(let[o,s]of Object.entries(t.fields)){if(s.access?.read)r.read.push(o);if(s.access?.update)r.update.push(o)}return R.set(t,r),r}function rn(t){let i=A(t);return i.read.length>0||i.update.length>0}function fe(t,i,r,o){let s=A(i).read.filter((a)=>{let l=i.fields[a]?.access?.read;return l&&!l({actor:r,record:t,locale:o})});for(let a of["scheduledPatch","_fallback"]){let l=t[a];if(l&&typeof l==="object"&&!Array.isArray(l)){let c={...l};for(let y of s)delete c[y];t[a]=c}}if(Array.isArray(t._localeFields))t._localeFields=t._localeFields.filter((a)=>typeof a==="string"&&!s.includes(a));for(let a of s)delete t[a];return t}function j(t,i,r,o,s){let a=[];for(let l of A(t).update){if(!(l in i))continue;let c=t.fields[l]?.access?.update;if(!c)continue;if(!c({actor:r,locale:o,...s===void 0?{}:{record:s}}))a.push(l)}if(a.length===0)return;throw e.forbidden(`Not allowed to write ${a.map((l)=>`"${l}"`).join(", ")} on ${t.name}`)}
|
|
14
|
+
export{pe,Z,Le,me,Ot,To,Co,Oo,lo,co,uo,_,rn,fe,j};
|