palgres 0.57.0 → 0.59.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/testing.js CHANGED
@@ -1,2 +1,2 @@
1
- /*! palgres 0.57.0 — Palbase SDK License (see LICENSE) */
2
- import{F as je,G as Oe,P as z,Q as ke,R as ie,V as ae,W as X,X as ce,Y as xe,_ as L,ga as Q,la as Ae,ma as Fe,n as Re,p as $e}from"./chunks/FZHMSYP2.js";import{E as Z,F as K,q as he,u as be}from"./chunks/BNQMEBLI.js";import{randomUUID as Be}from"node:crypto";var Ne=/^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/,Te="access: its time passed",Ee="user";function _e(t){let s=t.filter(c=>c!=null);return s.length===0?"text":s.every(c=>typeof c=="boolean")?"bool":s.every(c=>typeof c=="bigint"||typeof c=="number"&&Number.isInteger(c))?"int":s.every(c=>typeof c=="bigint"||typeof c=="number"&&Number.isFinite(c))?"numeric":s.every(c=>typeof c=="string"&&Ne.test(c))?"uuid":"text"}function Pe(t,s){return s==null?null:t==="bool"||t==="int"||t==="numeric"||typeof s=="string"?s:String(s)}var Me=t=>t.schema==="public"?t.name:`${t.schema}.${t.name}`;function Ie(t,s){let c=be(he(t)),d=Oe(t,"memory"),g,f=[],p=[],y=0,j=new Map,$=[...c.types.values()].filter(e=>e.table),S=e=>{let r=c.types.get(e),i=new Set;if(!r?.table)return[];i.add(r.table.key??"id");let o=u=>{let w=u;w.parts?w.parts.forEach(o):w.part?o(w.part):w.column&&i.add(w.column)};for(let u of r.relations.values())u.kind!=="stored"&&(u.kind==="column"&&i.add(u.column),u.where&&o(u.where));return[...i]},D=()=>{let e=new Map;for(let r of $){let i=r.table,o=s.rows(Me(i)),u=i.key??"id",w={};for(let m of S(r.name))w[m]=_e(o.map(b=>b[m]));let h={key:u,columns:w};e.set(r.name,{shape:h,rows:o.map(m=>Object.fromEntries(Object.entries(w).map(([b,R])=>[b,Pe(R,m[b])])))})}return{tables:e,relationships:f,now:Date.now()}},M=(e,r,i)=>{let o=e.tables.get(r);if(!o)return i;let u=o.shape.columns[o.shape.key],w=Z(u,i);return w===null?null:o.rows.some(m=>{let b=m[o.shape.key];return b!==null&&Z(u,String(b))===w})?w:void 0},T=()=>{for(let r of $){let i=r.table,o=Me(i),u=i.key??"id",w=s.deleted(o),h=Math.min(j.get(o)??0,w.length),m=R=>Ne.test(R)?R.toLowerCase():R,b=new Set(w.slice(h).map(R=>R[u]).filter(R=>R!=null).map(R=>m(String(R))));j.set(o,w.length),b.size>0&&W(r.name,R=>b.has(m(R)),"access: row deleted")}let e=D();for(let r of $)W(r.name,i=>M(e,r.name,i)===void 0,"access: row deleted");return D()},x=e=>e.expiresAt!==void 0&&e.expiresAt!==null&&e.expiresAt<=Date.now(),A=(e,r)=>x(e)?q("expire",e,Te,e.expiresAt):q("revoke",e,r),N=(e,r)=>{let i=[],o=0;for(let u of f)e(u)?(A(u,r),o++):i.push(u);return f=i,o},W=(e,r,i)=>{N(o=>o.objectType===e&&r(o.objectId)||o.subjectType===e&&r(o.subjectId),i)},P=e=>new Date(e).toISOString().replace("Z","000Z"),C=e=>e==null?null:P(e),q=(e,r,i,o)=>{p.push({seq:++y,at:P(o??Date.now()),action:e,object:{type:r.objectType,id:r.objectId},relation:r.relation,subject:{type:r.subjectType,id:r.subjectId},by:i,until:C(r.expiresAt)})},n=(e,r)=>(e.object_type===void 0||e.object_type===r.objectType)&&(e.object_id===void 0||e.object_id===r.objectId)&&(e.relation===void 0||e.relation===r.relation)&&(e.subject_type===void 0||e.subject_type===r.subjectType)&&(e.subject_id===void 0||e.subject_id===r.subjectId),a=(e,r)=>{for(let i of["objectType","objectId","relation","subjectType","subjectId"])if(e[i]!==r[i])return e[i]<r[i]?-1:1;return 0};return{names:d,via:{caller:()=>g,check(e,r,i,o){let u=T(),w=M(u,i,o);return w==null?!1:K(c,u).check(e,i,w,r)},objects:(e,r,i)=>K(c,T()).objects(e,i,r),subjects(e,r,i){let o=T(),u=M(o,r,i);return u==null?[]:K(c,o).subjects(r,u,e)},open(e,r,i){let o=T(),u=M(o,r,i);return u==null?null:K(c,o).open(r,u,e)},change(e,r,i,o,u,w){let h=T(),m=(k,E,F)=>{if(E===Ee)return F;let B=M(h,E,F);if(B==null)throw new je("no_object",`Database.$access: there is no ${E} ${JSON.stringify(F)} (${k}) \u2014 a relationship is given on an object that exists`);return B};if(e==="revoke"){let k=(U,me)=>{let oe=U===Ee?void 0:h.tables.get(U);return oe?Z(oe.shape.columns[oe.shape.key],me):me},E=k(r.type,r.id),F=k(o.type,o.id);if(E===null||F===null)return!1;let B={objectType:r.type,objectId:E,relation:i,subjectType:o.type,subjectId:F},V=f.find(U=>a(U,B)===0);if(!V)return!1;let se=!x(V);return N(U=>U===V,u??g??null),se}let b={objectType:r.type,objectId:m("the object",r.type,r.id),relation:i,subjectType:o.type,subjectId:m("the subject",o.type,o.id),expiresAt:w??null};N(k=>k.objectType===b.objectType&&k.objectId===b.objectId&&x(k),null);let R=f.find(k=>a(k,b)===0);return R?((R.expiresAt??null)!==(b.expiresAt??null)&&(R.expiresAt=b.expiresAt,q("grant",b,u??g??null)),!1):(f.push({...b,since:P(Date.now())}),q("grant",b,u??g??null),!0)},sweep(e){T();let r=f.filter(x).sort((i,o)=>i.expiresAt-o.expiresAt).slice(0,e);return N(i=>r.includes(i),null)},relationships(e,r){return T(),f.filter(i=>!x(i)&&n(e,i)).sort(a).slice(0,r).map(i=>({object:{type:i.objectType,id:i.objectId},relation:i.relation,subject:{type:i.subjectType,id:i.subjectId},since:i.since,until:C(i.expiresAt)}))},history(e,r){T();let i=f.filter(x).map(o=>({seq:Number.POSITIVE_INFINITY,at:C(o.expiresAt),action:"expire",object:{type:o.objectType,id:o.objectId},relation:o.relation,subject:{type:o.subjectType,id:o.subjectId},by:Te,until:C(o.expiresAt)}));return[...p,...i].filter(o=>n(e,{objectType:o.object.type,objectId:o.object.id,relation:o.relation,subjectType:o.subject.type,subjectId:o.subject.id})).sort((o,u)=>o.at!==u.at?o.at<u.at?1:-1:u.seq===o.seq?0:u.seq>o.seq?1:-1).slice(0,r).map(({seq:o,...u})=>({...u,object:{...u.object},subject:{...u.subject}}))}},signedInAs(e){g=e},snapshot(){let e={relationships:f.map(r=>({...r})),history:p.map(r=>({...r})),written:y,seen:new Map(j),user:g};return()=>{f=e.relationships,p=e.history,y=e.written,j=e.seen,g=e.user}}}}var We=/^\d{4}-\d{2}-\d{2}([T ]\d{2}:\d{2}(:\d{2}(\.\d+)?)?)?(Z|[+-]\d{2}(:?\d{2})?)?$/,qe=/^([+-]?)(\d*)(?:\.(\d*))?$/;function J(t){if(t instanceof Date)return t.getTime();if(typeof t=="string"&&We.test(t)){let s=Date.parse(t);return Number.isNaN(s)?null:s}return null}function H(t){if(typeof t=="number")return Number.isFinite(t)?H(String(t)):null;if(typeof t!="string"||/e/i.test(t))return null;let s=qe.exec(t.trim());if(s===null||s[2]===""&&(s[3]??"")==="")return null;let c=s[3]??"";return{unit:BigInt(`${s[1]==="-"?"-":""}${s[2]===""?"0":s[2]}${c}`),scale:c.length}}function te(t,s){return t.unit*10n**BigInt(s-t.scale)}function ge(t,s){if(t==null||s===null||s===void 0)return null;let c=J(t),d=J(s);if(c!==null&&d!==null)return Math.sign(c-d);let g=H(t),f=H(s);if(g!==null&&f!==null){let p=Math.max(g.scale,f.scale),y=te(g,p)-te(f,p);return y===0n?0:y<0n?-1:1}return typeof t==typeof s&&(typeof t=="string"||typeof t=="boolean"||typeof t=="number")?t<s?-1:t>s?1:0:null}function _(t,s){return t==null||s===null||s===void 0?!1:t instanceof Date||s instanceof Date?J(t)!==null&&J(t)===J(s):Array.isArray(t)&&Array.isArray(s)?t.length===s.length&&t.every((c,d)=>_(c,s[d])):t===s}function re(t){let s=((t?.days??0)*86400+(t?.hours??0)*3600+(t?.minutes??0)*60+(t?.seconds??0))*1e3;return new Date(Date.now()-s).toISOString()}function ue(t,s,c){if(t==null)return null;if(typeof t=="number"&&typeof s=="number")return t+c*s;let d=H(t),g=H(s);if(d===null||g===null)throw new Error(`increment()/decrement() on a value that is not a number (${JSON.stringify(t)}): Postgres refuses it ("operator does not exist")`);let f=Math.max(d.scale,g.scale),p=te(d,f)+BigInt(c)*te(g,f);if(f===0)return typeof t=="number"?Number(p):p.toString();let y=p<0n,j=(y?-p:p).toString().padStart(f+1,"0"),$=`${y?"-":""}${j.slice(0,-f)}.${j.slice(-f)}`;return typeof t=="number"?Number($):$}function Ve(t,s){let c=A=>{let N=(A.unit<0n?-A.unit:A.unit).toString().padStart(A.scale+1,"0"),W=N.slice(0,N.length-A.scale),P=N.slice(N.length-A.scale),C=W.padStart(Math.ceil(W.length/4)*4,"0").match(/.{4}/g)??[],q=P.padEnd(Math.ceil(P.length/4)*4,"0").match(/.{4}/g)??[],a=[...C.map((l,e)=>[C.length-1-e,Number(l)]),...q.map((l,e)=>[-1-e,Number(l)])].find(([,l])=>l!==0);return a?[a[0],a[1]]:[0,0]},[d,g]=c(t),[f,p]=c(s),y=d-f-(g<=p?1:0),j=Math.min(Math.max(16-y*4,t.scale,s.scale,0),1e3),$=t.unit*10n**BigInt(j+s.scale),S=s.unit*10n**BigInt(t.scale),D=$/S,M=$%S;2n*(M<0n?-M:M)>=(S<0n?-S:S)&&(D+=$<0n!=S<0n?-1n:1n);let T=D<0n,x=(T?-D:D).toString().padStart(j+1,"0");return`${T?"-":""}${j===0?x:`${x.slice(0,-j)}.${x.slice(-j)}`}`}var O=t=>structuredClone(t);function we(t,s,c){if(ke(c))throw new Error(`${t}(${s}): the fake database runs no SQL, so a sqlFragment cannot be evaluated \u2014 write the filter in the filter language (gt, gte, lt, lte, neq, in, contains, isNull, OR, AND, NOT), or test this against Postgres`);if(!(c===null||typeof c!="object"))for(let[d,g]of Object.entries(c))if(d==="OR"||d==="AND")for(let f of Array.isArray(g)?g:[])we(t,s,f);else d==="NOT"&&we(t,s,g)}function v(t,s,c){return Re(new $e({fields:[{field:s,message:c}]},`${t}: ${s} ${c}`))}function pe(t,s,c="where"){for(let[d,g]of Object.entries(s))if(d==="OR"||d==="AND"){let f=g;if(d==="AND"&&f.length===0)throw v(t,`${c}.AND`,"is an empty list \u2014 no condition at all. Leave it out, or name a condition in it.");f.forEach((p,y)=>{if(Object.keys(p).length===0)throw v(t,`${c}.${d}[${y}]`,"holds no condition \u2014 a branch that matches every row. Name a condition in it, or leave it out.");pe(t,p,`${c}.${d}[${y}]`)})}else if(d==="NOT"){if(Array.isArray(g))throw v(t,`${c}.NOT`,"is a list \u2014 NOT takes one filter object. For several conditions, NOT: { AND: [...] } or NOT: { OR: [...] }.");if(Object.keys(g).length===0)throw v(t,`${c}.NOT`,"holds no condition \u2014 NOT of nothing is not a filter. Name the condition to exclude.");pe(t,g,`${c}.NOT`)}else if(d==="has"&&Object.keys(g??{}).length===0)throw v(t,`${c}.has`,"names no relation \u2014 no condition. Name one: has: { <relation>: { \u2026 } }.")}function G(t,s){if(Object.keys(s).length===0)throw v(t,"where",`holds no condition, so ${t} would reach EVERY row of the table. Name a condition.`)}function ye(t){let s=!1;for(let c of t){if(c===!1)return!1;c===null&&(s=!0)}return s?null:!0}function De(t){let s=!1;for(let c of t){if(c===!0)return!0;c===null&&(s=!0)}return s?null:!1}var I=t=>t==null;function Y(t,s,c,d){return ye(Object.entries(d).map(([g,f])=>{if(g==="OR")return De(f.map(p=>Y(t,s,c,p)));if(g==="AND")return ye(f.map(p=>Y(t,s,c,p)));if(g==="NOT"){let p=Y(t,s,c,f);return p===null?null:!p}if(g==="has")throw new Error(`${t}(${s}): the fake database has no relations, so a \`has\` filter cannot be decided for a row \u2014 read the related table first and filter by its ids ({ id: { in: [\u2026] } }), or test this against Postgres`);return Ue(t,s,c,g,f)}))}var Se=["neq","gt","gte","lt","lte"];function ee(t,s){return I(t)||I(s)?null:_(t,s)}function Ue(t,s,c,d,g){let f=c[d];return g===null?I(f):z(g)?ee(f,c[g.$col]):X(g)?ee(f,re(Q(g)?.minus)):typeof g=="object"&&!Array.isArray(g)&&!(g instanceof Date)?ye(Object.entries(g).map(([p,y])=>{if(X(y)){if(!Se.includes(p))throw new Error(`${t}(${s}): where.${d}.${p} cannot take now()`);return ne(p,f,re(Q(y)?.minus))}if(ae(y))throw new Error(`${t}(${s}): where.${d}.${p} was given increment()/decrement() \u2014 a write, not a value to compare with`);if(z(y)){if(!Se.includes(p))throw new Error(`${t}(${s}): where.${d}.${p} cannot take col()`);return ne(p,f,c[y.$col])}switch(p){case"in":{if(!Array.isArray(y))throw new Error(`${t}(${s}): where.${d}.in is a list`);return De(y.map(j=>ee(f,j)))}case"neq":return y===null?!I(f):ne(p,f,y);case"gt":case"gte":case"lt":case"lte":return ne(p,f,y);case"isNull":if(typeof y!="boolean")throw new Error(`${t}(${s}): where.${d}.isNull is true or false`);return y?I(f):!I(f);case"overlaps":if(!Array.isArray(y))throw new Error(`${t}(${s}): where.${d}.overlaps is a list`);if(f!=null&&!Array.isArray(f))throw new Error(`${t}(${s}): where.${d}: "overlaps" is an array column's operator`);return I(f)?null:y.some(j=>f.some($=>_(j,$)));case"contains":case"icontains":case"startsWith":case"endsWith":{if(p==="contains"&&Array.isArray(y))return I(f)?null:Array.isArray(f)&&y.every(j=>f.some($=>_(j,$)));if(typeof y!="string")throw new Error(`${t}(${s}): where.${d}.${p} is text`);return I(f)?null:typeof f!="string"?!1:p==="contains"?f.includes(y):p==="icontains"?f.toLowerCase().includes(y.toLowerCase()):p==="startsWith"?f.startsWith(y):f.endsWith(y)}default:throw new Error(`${t}(${s}): where.${d} has no operator "${p}"`)}})):ee(f,g)}function ne(t,s,c){if(I(s)||I(c))return null;if(t==="neq")return!_(s,c);let d=ge(s,c);return d===null?!1:t==="gt"?d>0:t==="gte"?d>=0:t==="lt"?d<0:d<=0}function Le(t={}){let s=new Map,c=new Map,d=new Map,g=new Map,f=new Map,p=[],y=t.access===void 0?void 0:Ie(t.access,{rows:n=>s.get(n)??[],deleted:n=>f.get(n)??[]});y?.signedInAs(t.user);let j=n=>{let a=s.get(n);return a||s.set(n,a=[]),a},$=(n,a,l)=>{let e=n.get(a);e?e.push(l):n.set(a,[l])},S=n=>n.id===void 0?{id:Be(),...n}:{...n},D=()=>{let n={store:new Map([...s].map(([l,e])=>[l,e.map(O)])),inserted:le(c),updated:le(d),deleted:new Map([...g].map(([l,e])=>[l,[...e]])),removed:le(f)},a=y?.snapshot();return()=>{s=n.store,c=n.inserted,d=n.updated,g=n.deleted,f=n.removed,a?.()}};function M(n,a,l){let e={};for(let[r,i]of Object.entries(l)){let o=Q(i);if(o!==null&&o.fn==="now")e[r]=re(o.minus);else{if(o!==null)throw new Error(`${n}(${a}): "${r}" was given ${o.fn==="inc"?"increment()":"decrement()"} \u2014 the row does not exist yet, so there is no current value to change`);e[r]=i}}return L(n,a,Object.keys(e),e),ce(n,a,Object.keys(e),e),e}function T(n,a,l,e){L(n,a,Object.keys(e),e);let r={};for(let[i,o]of Object.entries(e)){let u=Q(o);u!==null&&u.fn==="now"?r[i]=re(u.minus):u!==null?r[i]=ue(l[i],u.by,u.fn==="inc"?1:-1):r[i]=o}return ce(n,a,Object.keys(r),r),r}function x(n,a,l){let e=S(M(n,a,l));return j(a).push(e),$(c,a,O(e)),O(e)}function A(n,a,l){return xe(n,a,l),we(n,a,l),l!==void 0&&pe(n,l),(s.get(a)??[]).filter(e=>l===void 0||Y(n,a,e,l)===!0)}let N={diagnostics:()=>null,async query(n,a=[]){return p.push({sql:n,params:a}),[]},async findUnique(){throw new Error("the fake database knows no table's declared unique keys \u2014 find the row with findMany, or test this against Postgres")},async page(){throw new Error("the fake database cannot reproduce Postgres' cursor ordering, collation or row-level security \u2014 test pagination against Postgres")},async search(n){throw new Error(`search(${n}): the fake database has neither embeddings nor full text \u2014 test search against Postgres`)},async findById(n,a){let l=(s.get(n)??[]).find(e=>e.id===a);return l?O(l):null},async findMany(n,a,l){let{limit:e,offset:r}=l??{};if(e!==void 0&&(!Number.isInteger(e)||e<0))throw new Error(`findMany(${n}): limit is a whole number, 0 or more (got ${String(e)})`);if(r!==void 0){if(!Number.isInteger(r)||r<0)throw new Error(`findMany(${n}): offset is a whole number, 0 or more (got ${String(r)})`);if(e===void 0)throw new Error(`findMany(${n}): offset comes with limit \u2014 an offset into an unbounded result is not a page`)}if(l?.with!==void 0&&Object.keys(l.with).length>0)throw new Error(`findMany(${n}): the fake database has no relations, so \`with\` cannot be read \u2014 seed and query the related table on its own, or test this against Postgres`);let i=A("findMany",n,a),o=l?.orderBy===void 0?[]:Array.isArray(l.orderBy)?l.orderBy:[l.orderBy];o.length>0&&(i=[...i].sort((h,m)=>{for(let b of o){let R=b.direction==="desc"?-1:1,k=h[b.column],E=m[b.column],F=k==null,B=E==null;if(F||B){if(F&&B)continue;let se=b.nulls===void 0?R===-1:b.nulls==="first";return(F?1:-1)*(se?-1:1)}let V=ge(k,E)??(String(k)<String(E)?-1:String(k)>String(E)?1:0);if(V!==0)return V*R}return 0}));let u=e===void 0?i:i.slice(r??0,(r??0)+e),w=l?.select;return u.map(h=>w===void 0||w.length===0?O(h):Object.fromEntries(w.map(m=>[m,structuredClone(h[m])])))},async count(n,a={}){return A("count",n,a).length},async aggregate(n,a){let l=A("aggregate",n,a.where),e=a.groupBy??[],r=o=>{let u={},w=h=>o.map(m=>m[h]).filter(m=>m!=null);for(let h of a.sum??[]){let m=w(h);(u.sum??={})[h]=m.length===0?null:String(m.reduce((b,R)=>ue(b,R,1),"0"))}for(let h of a.avg??[]){let m=w(h),b=m.some(R=>typeof R=="number"&&!Number.isInteger(R));(u.avg??={})[h]=m.length===0?null:b?m.reduce((R,k)=>R+k,0)/m.length:Ve(H(m.reduce((R,k)=>ue(R,k,1),"0")),{unit:BigInt(m.length),scale:0})}for(let[h,m]of[["min",-1],["max",1]])for(let b of a[h]??[]){let R=w(b);(u[h]??={})[b]=R.length===0?null:R.reduce((k,E)=>(ge(E,k)??0)*m>0?E:k)}return a.count===!0?u.count=o.length:a.count!==void 0&&a.count!==!1&&(u.count=Object.fromEntries(Object.entries(a.count).map(([h,m])=>[h,o.filter(b=>Y("aggregate",n,b,m)===!0).length]))),u};if(e.length===0)return r(l);let i=new Map;for(let o of l){let u=JSON.stringify(e.map(w=>o[w]));i.set(u,[...i.get(u)??[],o])}return[...i.values()].map(o=>({...r(o),...Object.fromEntries(e.map(u=>[u,o[0][u]]))}))},async insert(n,a){return x("insert",n,a)},insertMany:(async(n,a,l)=>{if(Ae(l),l?.onConflict?.length||l?.action!==void 0)throw new Error(`insertMany(${n}): the fake database knows no unique constraint to collide with \u2014 test onConflict against Postgres`);if(a.length===0)return l?.returning===!1?0:[];let e=Object.keys(a[0]);a.forEach((i,o)=>{let u=e.filter(h=>!(h in i)),w=Object.keys(i).filter(h=>!e.includes(h));if(u.length>0||w.length>0)throw new Error(`insertMany(${n}): row ${o} has not the first row's columns${u.length?` (missing ${u.join(", ")})`:""}${w.length?` (extra ${w.join(", ")})`:""} \u2014 write null for an empty one, or insert rows of another shape in a call of their own`)});let r=a.map(i=>x("insertMany",n,i));return l?.returning===!1?r.length:r}),async put(n,a,l){if(!l?.onConflict?.length)throw new Error(`put(${n}): onConflict names at least one column`);let e=M("put",n,a),r=j(n).find(i=>l.onConflict.every(o=>_(i[o],e[o])));if(!r)return x("put",n,a);for(let[i,o]of Object.entries(e))l.onConflict.includes(i)||(r[i]=o);return $(d,n,O(r)),O(r)},async update(n,a,l){let e=s.get(n)??[],r=e.findIndex(i=>i.id===a);return r<0?(L("update",n,Object.keys(l),l),null):(e[r]={...e[r],...T("update",n,e[r],l)},$(d,n,O(e[r])),O(e[r]))},async updateMany(n,a,l,e){G("updateMany",a);let r=A("updateMany",n,a),i=j(n),o=[];for(let u of r){let w=i.indexOf(u);i[w]={...u,...T("updateMany",n,u,l)},$(d,n,O(i[w])),o.push(O(i[w]))}return r.length===0&&L("updateMany",n,Object.keys(l),l),e?.returning===!1?o.length:o},async delete(n,a){let l=s.get(n)??[],e=l.findIndex(i=>i.id===a);if(e<0)return;let[r]=l.splice(e,1);$(g,n,a),$(f,n,r)},async deleteMany(n,a){G("deleteMany",a);let l=A("deleteMany",n,a);s.set(n,(s.get(n)??[]).filter(e=>!l.includes(e)));for(let e of l)$(g,n,String(e.id)),$(f,n,e);return l.length},async claim(n,a,l={}){let e=Object.keys(a);if(e.length===0)throw new Error(`claim(${n}): no unique field \u2014 claim takes a key; without one, insert(${n}, \u2026)`);L("claim",n,e,a);let r=(s.get(n)??[]).find(i=>e.every(o=>_(i[o],a[o])));return r?{inserted:!1,row:O(r)}:{inserted:!0,row:x("claim",n,{...a,...l})}},async lockRows(n,a){if(a.length===0)return;let l=s.get(n)??[],e=[...new Set(a)].filter(r=>!l.some(i=>i.id===r));if(e.length>0&&l.length>0)throw new Error(`lockRows(${n}): no row with id ${e.join(", ")}`)},async lockRowsWhere(n,a,l){let e=l?.mode??"update";if(!["update","share","noKeyUpdate"].includes(e))throw new Error(`lockRowsWhere(${n}): mode is "update", "share" or "noKeyUpdate" (got "${String(e)}")`);G("lockRowsWhere",a),A("lockRowsWhere",n,a)},async advisoryXactLock(){}};function W(n){let a=D(),l=[];try{for(let e of n.ops){let r=P(e,l);l.push(r);let i=ve(e.guard,r.rows.length);if(i)throw i}}catch(e){throw a(),e}return{results:l}}function P(n,a){let l=r=>Object.fromEntries(Object.entries(r??{}).map(([i,o])=>[i,Ce(o,a)])),e=`transaction plan ${n.op}`;switch(n.op){case"insert":return fe(x(e,n.table,l(n.values)));case"insertMany":{let r=(n.rows??[]).map(u=>l(u)),i=n.onConflict??[];if(n.action!==void 0&&i.length===0)throw new Error(`${e}(${n.table}): the fake database knows no unique key to collide with \u2014 name onConflict columns, or test this against Postgres`);let o=[];for(let u of r){let w=i.length>0?j(n.table).find(h=>i.every(m=>_(h[m],u[m]))):void 0;if(!(w&&n.action==="ignore")){if(w&&n.action==="update"){Object.assign(w,T(e,n.table,w,Object.fromEntries(Object.entries(u).filter(([h])=>!i.includes(h))))),$(d,n.table,O(w)),o.push(O(w));continue}o.push(x(e,n.table,u))}}return{rows:o,rows_affected:o.length}}case"upsert":{let r=l(n.values),i=n.onConflict??[];if(Object.keys(r).length===0||i.length===0)throw Object.assign(new Error(`put on ${n.table} needs columns and onConflict`),{error_code:"tx_bad_upsert"});let o=j(n.table).find(u=>i.every(w=>_(u[w],r[w])));return o?(Object.assign(o,T(e,n.table,o,Object.fromEntries(Object.entries(r).filter(([u])=>!i.includes(u))))),$(d,n.table,O(o)),fe(O(o))):fe(x(e,n.table,r))}case"update":{let r=l(n.set);if(Object.keys(r).length===0)throw new Error(`update ${n.table}: nothing to set`);let i=de(n.where,a);G(e,i);let o=j(n.table),u=[];for(let w of A(e,n.table,i)){let h=o.indexOf(w);o[h]={...w,...T(e,n.table,w,r)},$(d,n.table,O(o[h])),u.push(O(o[h]))}return{rows:u,rows_affected:u.length}}case"delete":{let r=de(n.where,a);G(e,r);let i=A(e,n.table,r);s.set(n.table,j(n.table).filter(o=>!i.includes(o)));for(let o of i)$(g,n.table,String(o.id)),$(f,n.table,o);return{rows:i.map(O),rows_affected:i.length}}case"select":{let r=A(e,n.table,de(n.where,a));return n.limit!==void 0&&(r=r.slice(0,n.limit)),{rows:r.map(O),rows_affected:r.length}}default:throw new Error(`unknown operation "${String(n.op)}" in a transaction plan`)}}let C={...N,async txPlan(n){return W(n)},async attempt(n){let a=D();try{return await n(N)}catch(l){throw a(),l}},async atomic(){throw new Error("the fake database cannot reproduce a transaction's isolation, COMMIT or retry \u2014 test $atomic against Postgres")}};return{...C,asService:()=>C,inserted:n=>(c.get(n)??[]).map(O),updated:n=>(d.get(n)??[]).map(O),deleted:n=>[...g.get(n)??[]],seed(n,a){s.set(n,a.map(O))},queries:p,...y===void 0?{}:{access:y}}}function le(t){return new Map([...t].map(([s,c])=>[s,c.map(O)]))}function fe(t){return{rows:[t],rows_affected:1}}function Ce(t,s){if(!ie(t))return t;let c=s[t.$ref.op]?.rows[0];if(!c)throw Object.assign(new Error(`transaction plan: operation ${t.$ref.op} produced no row to reference`),{error_code:"tx_ref_unresolved"});return c[t.$ref.field]}function de(t,s){let c=d=>{if(ie(d)){let g=Ce(d,s);if(g==null)throw Object.assign(new Error(`transaction plan: a filter's reference to operation ${d.$ref.op}'s "${d.$ref.field}" is NULL`),{error_code:"tx_ref_null"});return g}return Array.isArray(d)?d.map(c):d!==null&&typeof d=="object"&&!z(d)&&!ae(d)&&!X(d)&&!(d instanceof Date)?Object.fromEntries(Object.entries(d).map(([g,f])=>[g,c(f)])):d};return c(t??{})}function ve(t,s){return t?(t.kind==="one"?s===1:t.kind==="none"?s===0:t.kind==="atLeast"?s>=t.n:s<=t.n)?null:Object.assign(new Error(`transaction expectation failed: ${t.kind} (${s} row(s))`),{error_code:"tx_guard_failed",slot:t.slot}):null}export{Le as createFakeClient,Fe as typedDatabase};
1
+ /*! palgres 0.59.0 — Palbase SDK License (see LICENSE) */
2
+ import{$ as H,F as ae,G as Ee,I as Me,Q as ee,R as Ie,S as ue,W as le,X as ne,Y as fe,Z as Ne,ha as J,ma as Se,n as Te,na as Ue,p as Ae}from"./chunks/53ZKW4FS.js";import{G as Q,H as G,I as Oe,J as ce,K as xe,q as $e,u as ke}from"./chunks/45KHGTPJ.js";import{randomUUID as He}from"node:crypto";var Pe=/^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/,De="access: its time passed",Ce="user";function Fe(t){let o=t.filter(u=>u!=null);return o.length===0?"text":o.every(u=>typeof u=="boolean")?"bool":o.every(u=>typeof u=="bigint"||typeof u=="number"&&Number.isInteger(u))?"int":o.every(u=>typeof u=="bigint"||typeof u=="number"&&Number.isFinite(u))?"numeric":o.every(u=>typeof u=="string"&&Pe.test(u))?"uuid":"text"}function Le(t,o){return o==null?null:t==="bool"||t==="int"||t==="numeric"||typeof o=="string"?o:String(o)}var de=t=>t.schema==="public"?t.name:`${t.schema}.${t.name}`;function _e(t,o){let u=ke($e(t)),d=Ee(t,"memory"),p,f=[],w=[],m=0,O=new Map,k=[...u.types.values()].filter(e=>e.table),_=e=>{let r=u.types.get(e),i=new Set;if(!r?.table)return[];i.add(r.table.key??"id");let s=a=>{let g=a;g.parts?g.parts.forEach(s):g.part?s(g.part):g.column&&i.add(g.column)};for(let a of r.relations.values())a.kind!=="stored"&&(a.kind==="column"&&i.add(a.column),a.where&&s(a.where));return[...i]},F=()=>{let e=new Map;for(let r of k){let i=r.table,s=o.rows(de(i)),a=i.key??"id",g={};for(let b of _(r.name))g[b]=Fe(s.map(y=>y[b]));let h={key:a,columns:g};e.set(r.name,{shape:h,rows:s.map(b=>Object.fromEntries(Object.entries(g).map(([y,j])=>[y,Le(j,b[y])])))})}return{tables:e,relationships:f,now:Date.now()}},C=(e,r,i)=>{let s=e.tables.get(r);if(!s)return i;let a=s.shape.columns[s.shape.key],g=Q(a,i);return g===null?null:s.rows.some(b=>{let y=b[s.shape.key];return y!==null&&Q(a,String(y))===g})?g:void 0},M=()=>{for(let r of k){let i=r.table,s=de(i),a=i.key??"id",g=o.deleted(s),h=Math.min(O.get(s)??0,g.length),b=j=>Pe.test(j)?j.toLowerCase():j,y=new Set(g.slice(h).map(j=>j[a]).filter(j=>j!=null).map(j=>b(String(j))));O.set(s,g.length),y.size>0&&V(r.name,j=>y.has(b(j)),"access: row deleted")}let e=F();for(let r of k)V(r.name,i=>C(e,r.name,i)===void 0,"access: row deleted");return F()},T=e=>e.expiresAt!==void 0&&e.expiresAt!==null&&e.expiresAt<=Date.now(),E=(e,r)=>T(e)?W("expire",e,De,e.expiresAt):W("revoke",e,r),N=(e,r)=>{let i=[],s=0;for(let a of f)e(a)?(E(a,r),s++):i.push(a);return f=i,s},V=(e,r,i)=>{N(s=>s.objectType===e&&r(s.objectId)||s.subjectType===e&&r(s.subjectId),i)},U=e=>new Date(e).toISOString().replace("Z","000Z"),B=e=>e==null?null:U(e),W=(e,r,i,s)=>{w.push({seq:++m,at:U(s??Date.now()),action:e,object:{type:r.objectType,id:r.objectId},relation:r.relation,subject:{type:r.subjectType,id:r.subjectId},by:i,until:B(r.expiresAt)})},X=(e,r)=>(e.object_type===void 0||e.object_type===r.objectType)&&(e.object_id===void 0||e.object_id===r.objectId)&&(e.relation===void 0||e.relation===r.relation)&&(e.subject_type===void 0||e.subject_type===r.subjectType)&&(e.subject_id===void 0||e.subject_id===r.subjectId),n=(e,r)=>{for(let i of["objectType","objectId","relation","subjectType","subjectId"])if(e[i]!==r[i])return e[i]<r[i]?-1:1;return 0},c={caller:()=>p,check(e,r,i,s){let a=M(),g=C(a,i,s);return g==null?!1:G(u,a).check(e,i,g,r)},objects:(e,r,i)=>G(u,M()).objects(e,i,r),subjects(e,r,i){let s=M(),a=C(s,r,i);return a==null?[]:G(u,s).subjects(r,a,e)},open(e,r,i){let s=M(),a=C(s,r,i);return a==null?null:G(u,s).open(r,a,e)},change(e,r,i,s,a,g){let h=M(),b=(R,I,S)=>{if(I===Ce)return S;let A=C(h,I,S);if(A==null)throw new ae("no_object",`Database.$access: there is no ${I} ${JSON.stringify(S)} (${R}) \u2014 a relationship is given on an object that exists`);return A};if(e==="revoke"){let R=(L,je)=>{let ie=L===Ce?void 0:h.tables.get(L);return ie?Q(ie.shape.columns[ie.shape.key],je):je},I=R(r.type,r.id),S=R(s.type,s.id);if(I===null||S===null)return!1;let A={objectType:r.type,objectId:I,relation:i,subjectType:s.type,subjectId:S},D=f.find(L=>n(L,A)===0);if(!D)return!1;let Ve=!T(D);return N(L=>L===D,a??p??null),Ve}let y={objectType:r.type,objectId:b("the object",r.type,r.id),relation:i,subjectType:s.type,subjectId:b("the subject",s.type,s.id),expiresAt:g??null},j=u.trees.find(R=>R.type===y.objectType&&R.relation===y.relation&&u.types.get(R.type)?.relations.get(R.relation)?.kind==="stored");if(j&&y.subjectType===y.objectType){let R=Date.now(),I=f.filter(A=>A.objectType===j.type&&A.relation===j.relation&&A.subjectType===j.type&&!T(A)),S=xe(j,I,y.objectId,y.subjectId,R)??ce(j.type,j.depth,y.objectId,y.subjectId,A=>I.filter(D=>D.objectId===A).map(D=>D.subjectId),A=>I.filter(D=>D.subjectId===A).map(D=>D.objectId));if(S)throw new ae(Me[S.code],`Database.$access: ${S.message}`)}N(R=>R.objectType===y.objectType&&R.objectId===y.objectId&&T(R),null);let $=f.find(R=>n(R,y)===0);return $?(($.expiresAt??null)!==(y.expiresAt??null)&&($.expiresAt=y.expiresAt,W("grant",y,a??p??null)),!1):(f.push({...y,since:U(Date.now())}),W("grant",y,a??p??null),!0)},sweep(e){M();let r=f.filter(T).sort((i,s)=>i.expiresAt-s.expiresAt).slice(0,e);return N(i=>r.includes(i),null)},relationships(e,r){return M(),f.filter(i=>!T(i)&&X(e,i)).sort(n).slice(0,r).map(i=>({object:{type:i.objectType,id:i.objectId},relation:i.relation,subject:{type:i.subjectType,id:i.subjectId},since:i.since,until:B(i.expiresAt)}))},history(e,r){M();let i=f.filter(T).map(s=>({seq:Number.POSITIVE_INFINITY,at:B(s.expiresAt),action:"expire",object:{type:s.objectType,id:s.objectId},relation:s.relation,subject:{type:s.subjectType,id:s.subjectId},by:De,until:B(s.expiresAt)}));return[...w,...i].filter(s=>X(e,{objectType:s.object.type,objectId:s.object.id,relation:s.relation,subjectType:s.subject.type,subjectId:s.subject.id})).sort((s,a)=>s.at!==a.at?s.at<a.at?1:-1:a.seq===s.seq?0:a.seq>s.seq?1:-1).slice(0,r).map(({seq:s,...a})=>({...a,object:{...a.object},subject:{...a.subject}}))}},l=e=>{let r=k.find(i=>de(i.table)===e);return r?u.trees.flatMap(i=>{let s=i.type===r.name?r.relations.get(i.relation):void 0;return s?.kind==="column"?[{type:r.name,key:r.table?.key??"id",column:s.column,depth:i.depth}]:[]}):[]};return{names:d,via:c,nested:e=>l(e).length>0,misplaced(e,r,i){for(let s of l(e)){let a=Fe(i.map($=>$[s.key])),g=$=>$==null?null:Q(a,String($)),h=new Map;for(let $ of i){let R=g($[s.key]);R!==null&&h.set(R,g($[s.column]))}let b=new Map;for(let $ of r){let R=g($[s.key]);R!==null&&b.set(R,g($[s.column]))}let y=$=>[...h].filter(([,R])=>R===$).map(([R])=>R),j=$=>$!==null&&h.has($)?$:null;for(let[$,R]of h){if(b.has($)&&b.get($)===R||R===null&&y($).length===0)continue;if(R!==null&&!h.has(R))return Oe(s.type,$,R);let I=ce(s.type,s.depth,$,j(R),S=>[j(h.get(S)??null)].filter(A=>A!==null),y);if(I)return I}}return null},signedInAs(e){p=e},snapshot(){let e={relationships:f.map(r=>({...r})),history:w.map(r=>({...r})),written:m,seen:new Map(O),user:p};return()=>{f=e.relationships,w=e.history,m=e.written,O=e.seen,p=e.user}}}}var Ke=/^\d{4}-\d{2}-\d{2}([T ]\d{2}:\d{2}(:\d{2}(\.\d+)?)?)?(Z|[+-]\d{2}(:?\d{2})?)?$/,ve=/^([+-]?)(\d*)(?:\.(\d*))?$/;function Z(t){if(t instanceof Date)return t.getTime();if(typeof t=="string"&&Ke.test(t)){let o=Date.parse(t);return Number.isNaN(o)?null:o}return null}function v(t){if(typeof t=="number")return Number.isFinite(t)?v(String(t)):null;if(typeof t!="string"||/e/i.test(t))return null;let o=ve.exec(t.trim());if(o===null||o[2]===""&&(o[3]??"")==="")return null;let u=o[3]??"";return{unit:BigInt(`${o[1]==="-"?"-":""}${o[2]===""?"0":o[2]}${u}`),scale:u.length}}function se(t,o){return t.unit*10n**BigInt(o-t.scale)}function ye(t,o){if(t==null||o===null||o===void 0)return null;let u=Z(t),d=Z(o);if(u!==null&&d!==null)return Math.sign(u-d);let p=v(t),f=v(o);if(p!==null&&f!==null){let w=Math.max(p.scale,f.scale),m=se(p,w)-se(f,w);return m===0n?0:m<0n?-1:1}return typeof t==typeof o&&(typeof t=="string"||typeof t=="boolean"||typeof t=="number")?t<o?-1:t>o?1:0:null}function q(t,o){return t==null||o===null||o===void 0?!1:t instanceof Date||o instanceof Date?Z(t)!==null&&Z(t)===Z(o):Array.isArray(t)&&Array.isArray(o)?t.length===o.length&&t.every((u,d)=>q(u,o[d])):t===o}function oe(t){let o=((t?.days??0)*86400+(t?.hours??0)*3600+(t?.minutes??0)*60+(t?.seconds??0))*1e3;return new Date(Date.now()-o).toISOString()}function ge(t,o,u){if(t==null)return null;if(typeof t=="number"&&typeof o=="number")return t+u*o;let d=v(t),p=v(o);if(d===null||p===null)throw new Error(`increment()/decrement() on a value that is not a number (${JSON.stringify(t)}): Postgres refuses it ("operator does not exist")`);let f=Math.max(d.scale,p.scale),w=se(d,f)+BigInt(u)*se(p,f);if(f===0)return typeof t=="number"?Number(w):w.toString();let m=w<0n,O=(m?-w:w).toString().padStart(f+1,"0"),k=`${m?"-":""}${O.slice(0,-f)}.${O.slice(-f)}`;return typeof t=="number"?Number(k):k}function Qe(t,o){let u=E=>{let N=(E.unit<0n?-E.unit:E.unit).toString().padStart(E.scale+1,"0"),V=N.slice(0,N.length-E.scale),U=N.slice(N.length-E.scale),B=V.padStart(Math.ceil(V.length/4)*4,"0").match(/.{4}/g)??[],W=U.padEnd(Math.ceil(U.length/4)*4,"0").match(/.{4}/g)??[],n=[...B.map((c,l)=>[B.length-1-l,Number(c)]),...W.map((c,l)=>[-1-l,Number(c)])].find(([,c])=>c!==0);return n?[n[0],n[1]]:[0,0]},[d,p]=u(t),[f,w]=u(o),m=d-f-(p<=w?1:0),O=Math.min(Math.max(16-m*4,t.scale,o.scale,0),1e3),k=t.unit*10n**BigInt(O+o.scale),_=o.unit*10n**BigInt(t.scale),F=k/_,C=k%_;2n*(C<0n?-C:C)>=(_<0n?-_:_)&&(F+=k<0n!=_<0n?-1n:1n);let M=F<0n,T=(M?-F:F).toString().padStart(O+1,"0");return`${M?"-":""}${O===0?T:`${T.slice(0,-O)}.${T.slice(-O)}`}`}var x=t=>structuredClone(t);function he(t,o,u){if(Ie(u))throw new Error(`${t}(${o}): the fake database runs no SQL, so a sqlFragment cannot be evaluated \u2014 write the filter in the filter language (gt, gte, lt, lte, neq, in, contains, isNull, OR, AND, NOT), or test this against Postgres`);if(!(u===null||typeof u!="object"))for(let[d,p]of Object.entries(u))if(d==="OR"||d==="AND")for(let f of Array.isArray(p)?p:[])he(t,o,f);else d==="NOT"&&he(t,o,p)}function K(t,o,u){return Te(new Ae({fields:[{field:o,message:u}]},`${t}: ${o} ${u}`))}function be(t,o,u="where"){for(let[d,p]of Object.entries(o))if(d==="OR"||d==="AND"){let f=p;if(d==="AND"&&f.length===0)throw K(t,`${u}.AND`,"is an empty list \u2014 no condition at all. Leave it out, or name a condition in it.");f.forEach((w,m)=>{if(Object.keys(w).length===0)throw K(t,`${u}.${d}[${m}]`,"holds no condition \u2014 a branch that matches every row. Name a condition in it, or leave it out.");be(t,w,`${u}.${d}[${m}]`)})}else if(d==="NOT"){if(Array.isArray(p))throw K(t,`${u}.NOT`,"is a list \u2014 NOT takes one filter object. For several conditions, NOT: { AND: [...] } or NOT: { OR: [...] }.");if(Object.keys(p).length===0)throw K(t,`${u}.NOT`,"holds no condition \u2014 NOT of nothing is not a filter. Name the condition to exclude.");be(t,p,`${u}.NOT`)}else if(d==="has"&&Object.keys(p??{}).length===0)throw K(t,`${u}.has`,"names no relation \u2014 no condition. Name one: has: { <relation>: { \u2026 } }.")}function Y(t,o){if(Object.keys(o).length===0)throw K(t,"where",`holds no condition, so ${t} would reach EVERY row of the table. Name a condition.`)}function Re(t){let o=!1;for(let u of t){if(u===!1)return!1;u===null&&(o=!0)}return o?null:!0}function We(t){let o=!1;for(let u of t){if(u===!0)return!0;u===null&&(o=!0)}return o?null:!1}var P=t=>t==null;function z(t,o,u,d){return Re(Object.entries(d).map(([p,f])=>{if(p==="OR")return We(f.map(w=>z(t,o,u,w)));if(p==="AND")return Re(f.map(w=>z(t,o,u,w)));if(p==="NOT"){let w=z(t,o,u,f);return w===null?null:!w}if(p==="has")throw new Error(`${t}(${o}): the fake database has no relations, so a \`has\` filter cannot be decided for a row \u2014 read the related table first and filter by its ids ({ id: { in: [\u2026] } }), or test this against Postgres`);return Ge(t,o,u,p,f)}))}var Be=["neq","gt","gte","lt","lte"];function te(t,o){return P(t)||P(o)?null:q(t,o)}function Ge(t,o,u,d,p){let f=u[d];return p===null?P(f):ee(p)?te(f,u[p.$col]):ne(p)?te(f,oe(J(p)?.minus)):typeof p=="object"&&!Array.isArray(p)&&!(p instanceof Date)?Re(Object.entries(p).map(([w,m])=>{if(ne(m)){if(!Be.includes(w))throw new Error(`${t}(${o}): where.${d}.${w} cannot take now()`);return re(w,f,oe(J(m)?.minus))}if(le(m))throw new Error(`${t}(${o}): where.${d}.${w} was given increment()/decrement() \u2014 a write, not a value to compare with`);if(ee(m)){if(!Be.includes(w))throw new Error(`${t}(${o}): where.${d}.${w} cannot take col()`);return re(w,f,u[m.$col])}switch(w){case"in":{if(!Array.isArray(m))throw new Error(`${t}(${o}): where.${d}.in is a list`);return We(m.map(O=>te(f,O)))}case"neq":return m===null?!P(f):re(w,f,m);case"gt":case"gte":case"lt":case"lte":return re(w,f,m);case"isNull":if(typeof m!="boolean")throw new Error(`${t}(${o}): where.${d}.isNull is true or false`);return m?P(f):!P(f);case"overlaps":if(!Array.isArray(m))throw new Error(`${t}(${o}): where.${d}.overlaps is a list`);if(f!=null&&!Array.isArray(f))throw new Error(`${t}(${o}): where.${d}: "overlaps" is an array column's operator`);return P(f)?null:m.some(O=>f.some(k=>q(O,k)));case"contains":case"icontains":case"startsWith":case"endsWith":{if(w==="contains"&&Array.isArray(m))return P(f)?null:Array.isArray(f)&&m.every(O=>f.some(k=>q(O,k)));if(typeof m!="string")throw new Error(`${t}(${o}): where.${d}.${w} is text`);return P(f)?null:typeof f!="string"?!1:w==="contains"?f.includes(m):w==="icontains"?f.toLowerCase().includes(m.toLowerCase()):w==="startsWith"?f.startsWith(m):f.endsWith(m)}default:throw new Error(`${t}(${o}): where.${d} has no operator "${w}"`)}})):te(f,p)}function re(t,o,u){if(P(o)||P(u))return null;if(t==="neq")return!q(o,u);let d=ye(o,u);return d===null?!1:t==="gt"?d>0:t==="gte"?d>=0:t==="lt"?d<0:d<=0}function Je(t={}){let o=new Map,u=new Map,d=new Map,p=new Map,f=new Map,w=[],m=t.access===void 0?void 0:_e(t.access,{rows:n=>o.get(n)??[],deleted:n=>f.get(n)??[]});m?.signedInAs(t.user);let O=n=>{let c=o.get(n);return c||o.set(n,c=[]),c},k=(n,c,l)=>{let e=n.get(c);e?e.push(l):n.set(c,[l])},_=n=>n.id===void 0?{id:He(),...n}:{...n},F=()=>{let n={store:new Map([...o].map(([l,e])=>[l,e.map(x)])),inserted:pe(u),updated:pe(d),deleted:new Map([...p].map(([l,e])=>[l,[...e]])),removed:pe(f)},c=m?.snapshot();return()=>{o=n.store,u=n.inserted,d=n.updated,p=n.deleted,f=n.removed,c?.()}};function C(n,c,l){let e={};for(let[r,i]of Object.entries(l)){let s=J(i);if(s!==null&&s.fn==="now")e[r]=oe(s.minus);else{if(s!==null)throw new Error(`${n}(${c}): "${r}" was given ${s.fn==="inc"?"increment()":"decrement()"} \u2014 the row does not exist yet, so there is no current value to change`);e[r]=i}}return H(n,c,Object.keys(e),e),fe(n,c,Object.keys(e),e),e}function M(n,c,l,e){H(n,c,Object.keys(e),e);let r={};for(let[i,s]of Object.entries(e)){let a=J(s);a!==null&&a.fn==="now"?r[i]=oe(a.minus):a!==null?r[i]=ge(l[i],a.by,a.fn==="inc"?1:-1):r[i]=s}return fe(n,c,Object.keys(r),r),r}function T(n,c,l){let e=_(C(n,c,l));return O(c).push(e),k(u,c,x(e)),x(e)}function E(n,c,l){return Ne(n,c,l),he(n,c,l),l!==void 0&&be(n,l),(o.get(c)??[]).filter(e=>l===void 0||z(n,c,e,l)===!0)}let N=n=>async(c,...l)=>{if(!m?.nested(c))return n(c,...l);let e=(o.get(c)??[]).map(x),r=F(),i=await n(c,...l),s=m.misplaced(c,e,o.get(c)??[]);if(s)throw r(),Object.assign(new Error(s.message),{code:s.code});return i},V={diagnostics:()=>null,async query(n,c=[]){return w.push({sql:n,params:c}),[]},async findUnique(){throw new Error("the fake database knows no table's declared unique keys \u2014 find the row with findMany, or test this against Postgres")},async page(){throw new Error("the fake database cannot reproduce Postgres' cursor ordering, collation or row-level security \u2014 test pagination against Postgres")},async search(n){throw new Error(`search(${n}): the fake database has neither embeddings nor full text \u2014 test search against Postgres`)},async findById(n,c){let l=(o.get(n)??[]).find(e=>e.id===c);return l?x(l):null},async findMany(n,c,l){let{limit:e,offset:r}=l??{};if(e!==void 0&&(!Number.isInteger(e)||e<0))throw new Error(`findMany(${n}): limit is a whole number, 0 or more (got ${String(e)})`);if(r!==void 0){if(!Number.isInteger(r)||r<0)throw new Error(`findMany(${n}): offset is a whole number, 0 or more (got ${String(r)})`);if(e===void 0)throw new Error(`findMany(${n}): offset comes with limit \u2014 an offset into an unbounded result is not a page`)}if(l?.with!==void 0&&Object.keys(l.with).length>0)throw new Error(`findMany(${n}): the fake database has no relations, so \`with\` cannot be read \u2014 seed and query the related table on its own, or test this against Postgres`);let i=E("findMany",n,c),s=l?.orderBy===void 0?[]:Array.isArray(l.orderBy)?l.orderBy:[l.orderBy];s.length>0&&(i=[...i].sort((h,b)=>{for(let y of s){let j=y.direction==="desc"?-1:1,$=h[y.column],R=b[y.column],I=$==null,S=R==null;if(I||S){if(I&&S)continue;let D=y.nulls===void 0?j===-1:y.nulls==="first";return(I?1:-1)*(D?-1:1)}let A=ye($,R)??(String($)<String(R)?-1:String($)>String(R)?1:0);if(A!==0)return A*j}return 0}));let a=e===void 0?i:i.slice(r??0,(r??0)+e),g=l?.select;return a.map(h=>g===void 0||g.length===0?x(h):Object.fromEntries(g.map(b=>[b,structuredClone(h[b])])))},async count(n,c={}){return E("count",n,c).length},async aggregate(n,c){let l=E("aggregate",n,c.where),e=c.groupBy??[],r=s=>{let a={},g=h=>s.map(b=>b[h]).filter(b=>b!=null);for(let h of c.sum??[]){let b=g(h);(a.sum??={})[h]=b.length===0?null:String(b.reduce((y,j)=>ge(y,j,1),"0"))}for(let h of c.avg??[]){let b=g(h),y=b.some(j=>typeof j=="number"&&!Number.isInteger(j));(a.avg??={})[h]=b.length===0?null:y?b.reduce((j,$)=>j+$,0)/b.length:Qe(v(b.reduce((j,$)=>ge(j,$,1),"0")),{unit:BigInt(b.length),scale:0})}for(let[h,b]of[["min",-1],["max",1]])for(let y of c[h]??[]){let j=g(y);(a[h]??={})[y]=j.length===0?null:j.reduce(($,R)=>(ye(R,$)??0)*b>0?R:$)}return c.count===!0?a.count=s.length:c.count!==void 0&&c.count!==!1&&(a.count=Object.fromEntries(Object.entries(c.count).map(([h,b])=>[h,s.filter(y=>z("aggregate",n,y,b)===!0).length]))),a};if(e.length===0)return r(l);let i=new Map;for(let s of l){let a=JSON.stringify(e.map(g=>s[g]));i.set(a,[...i.get(a)??[],s])}return[...i.values()].map(s=>({...r(s),...Object.fromEntries(e.map(a=>[a,s[0][a]]))}))},insert:N(async(n,c)=>T("insert",n,c)),insertMany:N(async(n,c,l)=>{if(Se(l),l?.onConflict?.length||l?.action!==void 0)throw new Error(`insertMany(${n}): the fake database knows no unique constraint to collide with \u2014 test onConflict against Postgres`);if(c.length===0)return l?.returning===!1?0:[];let e=Object.keys(c[0]);c.forEach((i,s)=>{let a=e.filter(h=>!(h in i)),g=Object.keys(i).filter(h=>!e.includes(h));if(a.length>0||g.length>0)throw new Error(`insertMany(${n}): row ${s} has not the first row's columns${a.length?` (missing ${a.join(", ")})`:""}${g.length?` (extra ${g.join(", ")})`:""} \u2014 write null for an empty one, or insert rows of another shape in a call of their own`)});let r=c.map(i=>T("insertMany",n,i));return l?.returning===!1?r.length:r}),put:N(async(n,c,l)=>{if(!l?.onConflict?.length)throw new Error(`put(${n}): onConflict names at least one column`);let e=C("put",n,c),r=O(n).find(i=>l.onConflict.every(s=>q(i[s],e[s])));if(!r)return T("put",n,c);for(let[i,s]of Object.entries(e))l.onConflict.includes(i)||(r[i]=s);return k(d,n,x(r)),x(r)}),update:N(async(n,c,l)=>{let e=o.get(n)??[],r=e.findIndex(i=>i.id===c);return r<0?(H("update",n,Object.keys(l),l),null):(e[r]={...e[r],...M("update",n,e[r],l)},k(d,n,x(e[r])),x(e[r]))}),updateMany:N(async(n,c,l,e)=>{Y("updateMany",c);let r=E("updateMany",n,c),i=O(n),s=[];for(let a of r){let g=i.indexOf(a);i[g]={...a,...M("updateMany",n,a,l)},k(d,n,x(i[g])),s.push(x(i[g]))}return r.length===0&&H("updateMany",n,Object.keys(l),l),e?.returning===!1?s.length:s}),async delete(n,c){let l=o.get(n)??[],e=l.findIndex(i=>i.id===c);if(e<0)return;let[r]=l.splice(e,1);k(p,n,c),k(f,n,r)},async deleteMany(n,c){Y("deleteMany",c);let l=E("deleteMany",n,c);o.set(n,(o.get(n)??[]).filter(e=>!l.includes(e)));for(let e of l)k(p,n,String(e.id)),k(f,n,e);return l.length},claim:N(async(n,c,l={})=>{let e=Object.keys(c);if(e.length===0)throw new Error(`claim(${n}): no unique field \u2014 claim takes a key; without one, insert(${n}, \u2026)`);H("claim",n,e,c);let r=(o.get(n)??[]).find(i=>e.every(s=>q(i[s],c[s])));return r?{inserted:!1,row:x(r)}:{inserted:!0,row:T("claim",n,{...c,...l})}}),async lockRows(n,c){if(c.length===0)return;let l=o.get(n)??[],e=[...new Set(c)].filter(r=>!l.some(i=>i.id===r));if(e.length>0&&l.length>0)throw new Error(`lockRows(${n}): no row with id ${e.join(", ")}`)},async lockRowsWhere(n,c,l){let e=l?.mode??"update";if(!["update","share","noKeyUpdate"].includes(e))throw new Error(`lockRowsWhere(${n}): mode is "update", "share" or "noKeyUpdate" (got "${String(e)}")`);Y("lockRowsWhere",c),E("lockRowsWhere",n,c)},async advisoryXactLock(){}};function U(n){let c=F(),l=[];try{for(let e of n.ops){let r=m?.nested(e.table)?(o.get(e.table)??[]).map(x):null,i=B(e,l),s=r===null?null:m?.misplaced(e.table,r,o.get(e.table)??[])??null;if(s)throw Object.assign(new Error(s.message),{code:s.code});l.push(i);let a=Ye(e.guard,i.rows.length);if(a)throw a}}catch(e){throw c(),e}return{results:l}}function B(n,c){let l=r=>Object.fromEntries(Object.entries(r??{}).map(([i,s])=>[i,qe(s,c)])),e=`transaction plan ${n.op}`;switch(n.op){case"insert":return we(T(e,n.table,l(n.values)));case"insertMany":{let r=(n.rows??[]).map(a=>l(a)),i=n.onConflict??[];if(n.action!==void 0&&i.length===0)throw new Error(`${e}(${n.table}): the fake database knows no unique key to collide with \u2014 name onConflict columns, or test this against Postgres`);let s=[];for(let a of r){let g=i.length>0?O(n.table).find(h=>i.every(b=>q(h[b],a[b]))):void 0;if(!(g&&n.action==="ignore")){if(g&&n.action==="update"){Object.assign(g,M(e,n.table,g,Object.fromEntries(Object.entries(a).filter(([h])=>!i.includes(h))))),k(d,n.table,x(g)),s.push(x(g));continue}s.push(T(e,n.table,a))}}return{rows:s,rows_affected:s.length}}case"upsert":{let r=l(n.values),i=n.onConflict??[];if(Object.keys(r).length===0||i.length===0)throw Object.assign(new Error(`put on ${n.table} needs columns and onConflict`),{error_code:"tx_bad_upsert"});let s=O(n.table).find(a=>i.every(g=>q(a[g],r[g])));return s?(Object.assign(s,M(e,n.table,s,Object.fromEntries(Object.entries(r).filter(([a])=>!i.includes(a))))),k(d,n.table,x(s)),we(x(s))):we(T(e,n.table,r))}case"update":{let r=l(n.set);if(Object.keys(r).length===0)throw new Error(`update ${n.table}: nothing to set`);let i=me(n.where,c);Y(e,i);let s=O(n.table),a=[];for(let g of E(e,n.table,i)){let h=s.indexOf(g);s[h]={...g,...M(e,n.table,g,r)},k(d,n.table,x(s[h])),a.push(x(s[h]))}return{rows:a,rows_affected:a.length}}case"delete":{let r=me(n.where,c);Y(e,r);let i=E(e,n.table,r);o.set(n.table,O(n.table).filter(s=>!i.includes(s)));for(let s of i)k(p,n.table,String(s.id)),k(f,n.table,s);return{rows:i.map(x),rows_affected:i.length}}case"select":{let r=E(e,n.table,me(n.where,c));return n.limit!==void 0&&(r=r.slice(0,n.limit)),{rows:r.map(x),rows_affected:r.length}}default:throw new Error(`unknown operation "${String(n.op)}" in a transaction plan`)}}let W={...V,async txPlan(n){return U(n)},async attempt(n){let c=F();try{return await n(V)}catch(l){throw c(),l}},async atomic(){throw new Error("the fake database cannot reproduce a transaction's isolation, COMMIT or retry \u2014 test $atomic against Postgres")}};return{...W,asService:()=>W,inserted:n=>(u.get(n)??[]).map(x),updated:n=>(d.get(n)??[]).map(x),deleted:n=>[...p.get(n)??[]],seed(n,c){o.set(n,c.map(x))},queries:w,...m===void 0?{}:{access:m}}}function pe(t){return new Map([...t].map(([o,u])=>[o,u.map(x)]))}function we(t){return{rows:[t],rows_affected:1}}function qe(t,o){if(!ue(t))return t;let u=o[t.$ref.op]?.rows[0];if(!u)throw Object.assign(new Error(`transaction plan: operation ${t.$ref.op} produced no row to reference`),{error_code:"tx_ref_unresolved"});return u[t.$ref.field]}function me(t,o){let u=d=>{if(ue(d)){let p=qe(d,o);if(p==null)throw Object.assign(new Error(`transaction plan: a filter's reference to operation ${d.$ref.op}'s "${d.$ref.field}" is NULL`),{error_code:"tx_ref_null"});return p}return Array.isArray(d)?d.map(u):d!==null&&typeof d=="object"&&!ee(d)&&!le(d)&&!ne(d)&&!(d instanceof Date)?Object.fromEntries(Object.entries(d).map(([p,f])=>[p,u(f)])):d};return u(t??{})}function Ye(t,o){return t?(t.kind==="one"?o===1:t.kind==="none"?o===0:t.kind==="atLeast"?o>=t.n:o<=t.n)?null:Object.assign(new Error(`transaction expectation failed: ${t.kind} (${o} row(s))`),{error_code:"tx_guard_failed",slot:t.slot}):null}export{Je as createFakeClient,Ue as typedDatabase};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "palgres",
3
- "version": "0.57.0",
3
+ "version": "0.59.0",
4
4
  "description": "Palgres: the typed Postgres layer of Palbase's DB machines — schema, migrations and queries.",
5
5
  "license": "SEE LICENSE IN LICENSE",
6
6
  "homepage": "https://palbase.studio",
@@ -2,8 +2,8 @@
2
2
  export declare const ACCESS = "access";
3
3
  /** Written on the schema: how a database's `access` is known to be Palbase's. */
4
4
  export declare const MARK = "palbase access";
5
- /** The engine's generation: a database compiled by another is compiled again. */
6
- export declare const ENGINE = "3";
5
+ /** The engine's generation: a database compiled by another is compiled again. (4: a type's objects nested in each other.) */
6
+ export declare const ENGINE = "4";
7
7
  /**
8
8
  * The triggers a type's table carries, by name: a row made, a row deleted, a row's key changed, the table emptied. A
9
9
  * table that lacks one, or has one off (or on for replicas alone), has not been watched. Each is a row's own, so
@@ -12,6 +12,12 @@ export declare const ENGINE = "3";
12
12
  * changes another row's key acts after access has followed this one.
13
13
  */
14
14
  export declare const TRIGGERS: readonly ['!access_fresh', '!access_forget', '!access_move', '!access_empty'];
15
+ /**
16
+ * The trigger a type's table carries when a permission of it is derived from itself through a column (a folder in a
17
+ * folder): it refuses a row put inside itself, or more levels deep than the type's depth. It decides nothing of a
18
+ * row's relationships, so it is no part of what watches a table (TRIGGERS), nor of the order those fire in.
19
+ */
20
+ export declare const NEST_TRIGGER = "!access_nest";
15
21
  /** The last of them in the order triggers of one event fire (their names', byte by byte). */
16
22
  export declare const LAST_TRIGGER: string;
17
23
  /**
@@ -69,5 +75,13 @@ export declare const REFUSED: {
69
75
  readonly notAllowed: 'PA006';
70
76
  /** A relationship's end that is not still to come. */
71
77
  readonly badTime: 'PA007';
78
+ /** A write that would put an object inside itself (a folder in a folder in itself). */
79
+ readonly cycle: 'PA008';
80
+ /** A write that would nest objects more levels deep than their type's depth. */
81
+ readonly tooDeep: 'PA009';
82
+ /** One parent more than an object nested by relationships may have (MAX_PARENTS). */
83
+ readonly tooManyParents: 'PA010';
72
84
  };
85
+ /** How many objects of its own type one object nested by relationships may be in (a team in teams). */
86
+ export declare const MAX_PARENTS = 32;
73
87
  export declare function baseStatements(roles?: Roles): string[];
@@ -93,6 +93,18 @@ export interface Compiled {
93
93
  */
94
94
  recheck: string[];
95
95
  tables: CompiledTable[];
96
+ /** The tables whose rows are kept a tree by NEST_TRIGGER (a folder in a folder), with what it is made with. */
97
+ nests: {
98
+ schema: string;
99
+ table: string;
100
+ args: string[];
101
+ }[];
102
+ /** The types nested by relationships (a team in teams), with the relation and how deep: what its grant holds them to. */
103
+ kept: {
104
+ type: string;
105
+ relation: string;
106
+ depth: number;
107
+ }[];
96
108
  /**
97
109
  * Every (type, name) a subject can hold, the view `access` shows it as, the type of its `id` (as pg_type names
98
110
  * it), and whether a visitor can hold it (it is read through a relation the public holds): those alone are the
@@ -1,10 +1,11 @@
1
1
  export { AccessError, type AccessErrorCode } from './errors.js';
2
2
  export { parse, type Condition, type Expr, type Literal, type RowCommand, type SchemaAst } from './text.js';
3
- export { validate, mangle, heldByUsers, heldByPublic, objectTargets, takesOpen, takesUsers, ANY, EVERY_USER, MAX_DEPTH, PUBLIC, USER, type Model, type Relation, type TypeModel } from './model.js';
3
+ export { validate, mangle, heldByUsers, heldByPublic, objectTargets, takesOpen, takesUsers, ANY, DEFAULT_NESTING, EVERY_USER, MAX_DEPTH, MAX_NESTING, PUBLIC, USER, type Model, type Nesting, type Relation, type Tree, type TypeModel } from './model.js';
4
4
  export { catalogFrom, catalogOf, catalogQuery, type Catalog, type ColumnFamily, type TableInfo } from './catalog.js';
5
- export { ACCESS, baseStatements, DEFAULT_ROLES, ENGINE, KIND, LIVE_OF_ANY_ENGINE, MARK, MAX_ID, REFUSED, starGuard, TRIGGERS, type Roles } from './base.js';
5
+ export { ACCESS, baseStatements, DEFAULT_ROLES, ENGINE, KIND, LIVE_OF_ANY_ENGINE, MARK, MAX_ID, MAX_PARENTS, NEST_TRIGGER, REFUSED, starGuard, TRIGGERS, type Roles } from './base.js';
6
6
  export { compile, readColumns, MAX_SUBJECTS, type Compiled, type CompiledTable, type CompileOptions, type Guard } from './compile.js';
7
7
  export { apply, beforeQuery, dropCompiled, keptQuery, plan, unpoint, type ApplyOptions, type Before, type Kept, type Planned, type Run } from './apply.js';
8
8
  export { reference, type Asker, type Reference } from './reference.js';
9
9
  export { canonicalId, idOf, type Family, type Relationship, type TableShape, type Value, type World } from './world.js';
10
10
  export { runValidation, schemaPathOf, ValidationFileError, type ValidationFailure, type ValidationResult } from './validation.js';
11
+ export { edges, notThere, placed, tooManyParents, treeProblem, type Misplaced } from './tree.js';
@@ -6,6 +6,9 @@ export declare const USER = "user";
6
6
  export declare const ANY = "*";
7
7
  /** How long a chain of permissions derived from one another may be. A schema past it is refused when declared. */
8
8
  export declare const MAX_DEPTH = 16;
9
+ /** How many levels a type's objects may be nested in one another (a folder in a folder): when the schema says none, and at most. */
10
+ export declare const DEFAULT_NESTING = 16;
11
+ export declare const MAX_NESTING = 32;
9
12
  export declare const MAX_TYPES = 200;
10
13
  export declare const MAX_NAMES = 100;
11
14
  export declare const MAX_EXPR_NODES = 200;
@@ -65,13 +68,32 @@ export interface RowsRule {
65
68
  export interface TypeModel {
66
69
  name: string;
67
70
  table: TableRef | null;
71
+ /** How many levels its objects may be nested in one another (`depth`; DEFAULT_NESTING when it is not said). */
72
+ depth: number;
68
73
  relations: Map<string, Relation>;
69
74
  permissions: Map<string, Permission>;
70
75
  rows: RowsRule[];
71
76
  }
77
+ /** A permission derived from itself through a relation to its own type: the relation, and how many levels deep. */
78
+ export interface Nesting {
79
+ type: string;
80
+ name: string;
81
+ relation: string;
82
+ depth: number;
83
+ }
84
+ /** A relation of a type to its own type that a permission is derived from itself through: its objects make a tree. */
85
+ export interface Tree {
86
+ type: string;
87
+ relation: string;
88
+ depth: number;
89
+ }
72
90
  export interface Model {
73
91
  /** In the order the schema declares them. */
74
92
  types: Map<string, TypeModel>;
93
+ /** The permission (type, name) is derived from itself through a relation to its own type: which, and how deep. */
94
+ nesting(type: string, name: string): Nesting | null;
95
+ /** Each relation some permission of its type is derived from itself through, once: the objects it leads to make a tree. */
96
+ trees: Tree[];
75
97
  /** Every (type, name), each after everything its meaning reads: the order to build them in. */
76
98
  order: {
77
99
  type: string;
@@ -98,6 +98,11 @@ export interface TableAst {
98
98
  export interface TypeAst {
99
99
  name: string;
100
100
  table: TableAst | null;
101
+ /** `depth N`: how many levels its objects may be nested in one another; null when it is not said. */
102
+ depth: {
103
+ levels: number;
104
+ line: number;
105
+ } | null;
101
106
  relations: RelationAst[];
102
107
  permissions: PermissionAst[];
103
108
  rows: RowsAst[];
@@ -0,0 +1,22 @@
1
+ import { REFUSED } from './base.js';
2
+ import type { Model, Tree } from './model.js';
3
+ import { type Relationship, type World } from './world.js';
4
+ /** What is wrong with where an object would be: its code (the database's SQLSTATE) and what the database says. */
5
+ export interface Misplaced {
6
+ code: typeof REFUSED.cycle | typeof REFUSED.tooDeep | typeof REFUSED.tooManyParents | typeof REFUSED.noObject;
7
+ message: string;
8
+ }
9
+ /** A row put in one that is not there (nested by a column): refused, as a foreign key would. */
10
+ export declare const notThere: (type: string, id: string, parent: string) => Misplaced;
11
+ /**
12
+ * Where `id` would be, put in `parent` (or in none), in a tree whose objects' parents `parentsOf` says and whose
13
+ * objects' children `childrenOf` says, as the write would leave them: inside itself, or too deep — or fine (null).
14
+ * Up a level at a time, every way there is (each object once a level); down along the longest way.
15
+ */
16
+ export declare function placed(type: string, depth: number, id: string, parent: string | null, parentsOf: (id: string) => string[], childrenOf: (id: string) => string[]): Misplaced | null;
17
+ /** Whether an object nested by relationships is in as many others already, `parent` aside, as one may be. */
18
+ export declare function tooManyParents(tree: Tree, relationships: Relationship[], id: string, parent: string, now?: number): Misplaced | null;
19
+ /** A tree's edges as they are in a world: child → parents, by the column of its type's table or by its relationships. */
20
+ export declare function edges(model: Model, world: World, tree: Tree): Map<string, string[]>;
21
+ /** What is wrong with a world's tree as the database checks it when a schema is put in: the first object that is not where it may be. */
22
+ export declare function treeProblem(model: Model, world: World, tree: Tree): Misplaced | null;
@@ -33,6 +33,18 @@ export interface RecordedAccess {
33
33
  }[];
34
34
  /** The relations whose relationships are kept, each with the kinds of subject it takes: type, relation, subject. */
35
35
  stored: [string, string, string][];
36
+ /** The tables whose rows are kept a tree, with what their trigger is made with (none: compiled before nesting). */
37
+ nests?: {
38
+ schema: string;
39
+ table: string;
40
+ args: string[];
41
+ }[];
42
+ /** The types nested by relationships its grant holds to a tree, and how deep (none: compiled before nesting). */
43
+ kept?: {
44
+ type: string;
45
+ relation: string;
46
+ depth: number;
47
+ }[];
36
48
  }
37
49
  export interface AccessRoles {
38
50
  authenticated: string;
@@ -70,7 +70,7 @@ export interface AccessFilter {
70
70
  }
71
71
  /** How wide a name is open on an object (`openTo`). */
72
72
  export type AccessOpen = 'public' | 'users' | 'visitors' | null;
73
- export type AccessRefusal = 'no_schema' | 'unknown_type' | 'unknown_name' | 'not_kept' | 'bad_id' | 'no_object' | 'too_many' | 'not_the_service' | 'bad_time';
73
+ export type AccessRefusal = 'no_schema' | 'unknown_type' | 'unknown_name' | 'not_kept' | 'bad_id' | 'no_object' | 'too_many' | 'not_the_service' | 'bad_time' | 'cycle' | 'too_deep' | 'too_many_parents';
74
74
  /** What an access question or change was refused for. Thrown before anything is sent wherever the schema alone says so. */
75
75
  export declare class AccessRefused extends Error {
76
76
  readonly code: AccessRefusal;
@@ -207,6 +207,13 @@ export interface AccessVia {
207
207
  relationships(where: AccessWhere, limit: number): AccessRelationship[];
208
208
  history(where: AccessWhere, limit: number): AccessHistoryEntry[];
209
209
  }
210
+ /** What the database refuses a nested type's tree with, as the app hears it (testing/access.ts refuses with the same). */
211
+ export declare const TREE_REFUSALS: {
212
+ readonly PA002: 'no_object';
213
+ readonly PA008: 'cycle';
214
+ readonly PA009: 'too_deep';
215
+ readonly PA010: 'too_many_parents';
216
+ };
210
217
  /**
211
218
  * The access operations over what asks (`raw`: the transaction current when each is called), for the version whose
212
219
  * access schema `names` are — undefined when the app declares none: every operation then says so. `as` is whose
@@ -1,3 +1,4 @@
1
+ import { type Misplaced } from '../../../access/src/index.js';
1
2
  import { type AccessNames, type AccessVia } from '../query/access.js';
2
3
  type Row = Record<string, unknown>;
3
4
  /** What the access in memory reads of the fake: a table's rows now, and the rows deleted from it so far. */
@@ -8,6 +9,10 @@ export interface AccessHost {
8
9
  export interface MemoryAccess {
9
10
  names: AccessNames;
10
11
  via: AccessVia;
12
+ /** Whether a table's rows are kept a tree (a type of it is nested through a column). */
13
+ nested(table: string): boolean;
14
+ /** What a write did wrong to a nested table's tree, from its rows before to its rows after: null when nothing. */
15
+ misplaced(table: string, before: Row[], after: Row[]): Misplaced | null;
11
16
  /** Who the caller is from now on: `can`, `objects` and `held` are about them. Undefined: nobody is signed in. */
12
17
  signedInAs(user: string | undefined): void;
13
18
  /** Everything as it is now, to be put back (a savepoint's way back, with the rows'). */