palgres 0.53.0 → 0.55.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.
Files changed (37) hide show
  1. package/dist/chunks/5EMZSH7B.js +5 -0
  2. package/dist/chunks/DLP3GKUJ.js +309 -0
  3. package/dist/chunks/EBHTHWOS.js +2 -0
  4. package/dist/dsl.js +2 -2
  5. package/dist/index.js +156 -125
  6. package/dist/testing.js +2 -2
  7. package/package.json +1 -1
  8. package/types/access/src/apply.d.ts +98 -0
  9. package/types/access/src/base.d.ts +49 -0
  10. package/types/access/src/catalog.d.ts +53 -0
  11. package/types/access/src/compile.d.ts +120 -0
  12. package/types/access/src/errors.d.ts +7 -0
  13. package/types/access/src/index.d.ts +10 -0
  14. package/types/access/src/model.d.ts +87 -0
  15. package/types/access/src/reference.d.ts +12 -0
  16. package/types/access/src/text.d.ts +104 -0
  17. package/types/access/src/validation.d.ts +22 -0
  18. package/types/access/src/world.d.ts +43 -0
  19. package/types/palgres/src/access.d.ts +63 -0
  20. package/types/palgres/src/connect.d.ts +10 -1
  21. package/types/palgres/src/dsl/policy.d.ts +24 -0
  22. package/types/palgres/src/dsl/to-model.d.ts +11 -1
  23. package/types/palgres/src/forget.d.ts +6 -6
  24. package/types/palgres/src/index.d.ts +1 -1
  25. package/types/palgres/src/model.d.ts +8 -0
  26. package/types/palgres/src/plan.d.ts +5 -1
  27. package/types/palgres/src/query/access.d.ts +169 -0
  28. package/types/palgres/src/query/env-gen.d.ts +2 -0
  29. package/types/palgres/src/query/index.d.ts +9 -7
  30. package/types/palgres/src/query/surface.d.ts +7 -1
  31. package/types/palgres/src/query/typed.d.ts +13 -5
  32. package/types/palgres/src/testing/access.d.ts +17 -0
  33. package/types/palgres/src/testing/fake.d.ts +13 -1
  34. package/types/palgres/src/testing/index.d.ts +2 -1
  35. package/dist/chunks/ULLX3GNS.js +0 -2
  36. package/dist/chunks/X2B6AJ7P.js +0 -5
  37. package/dist/chunks/XPFGITD6.js +0 -2
package/dist/testing.js CHANGED
@@ -1,2 +1,2 @@
1
- /*! palgres 0.53.0 — Palbase SDK License (see LICENSE) */
2
- import{$ as wn,D as U,E as fn,F as Y,J as Z,K as V,L as z,M as dn,O as P,W as _,aa as $n,e as cn,g as ln}from"./chunks/ULLX3GNS.js";import"./chunks/X2B6AJ7P.js";import{randomUUID as Rn}from"node:crypto";var On=/^\d{4}-\d{2}-\d{2}([T ]\d{2}:\d{2}(:\d{2}(\.\d+)?)?)?(Z|[+-]\d{2}(:?\d{2})?)?$/,bn=/^([+-]?)(\d*)(?:\.(\d*))?$/;function q(e){if(e instanceof Date)return e.getTime();if(typeof e=="string"&&On.test(e)){let t=Date.parse(e);return Number.isNaN(t)?null:t}return null}function B(e){if(typeof e=="number")return Number.isFinite(e)?B(String(e)):null;if(typeof e!="string"||/e/i.test(e))return null;let t=bn.exec(e.trim());if(t===null||t[2]===""&&(t[3]??"")==="")return null;let a=t[3]??"";return{unit:BigInt(`${t[1]==="-"?"-":""}${t[2]===""?"0":t[2]}${a}`),scale:a.length}}function K(e,t){return e.unit*10n**BigInt(t-e.scale)}function tn(e,t){if(e==null||t===null||t===void 0)return null;let a=q(e),c=q(t);if(a!==null&&c!==null)return Math.sign(a-c);let w=B(e),f=B(t);if(w!==null&&f!==null){let d=Math.max(w.scale,f.scale),h=K(w,d)-K(f,d);return h===0n?0:h<0n?-1:1}return typeof e==typeof t&&(typeof e=="string"||typeof e=="boolean"||typeof e=="number")?e<t?-1:e>t?1:0:null}function N(e,t){return e==null||t===null||t===void 0?!1:e instanceof Date||t instanceof Date?q(e)!==null&&q(e)===q(t):Array.isArray(e)&&Array.isArray(t)?e.length===t.length&&e.every((a,c)=>N(a,t[c])):e===t}function H(e){let t=((e?.days??0)*86400+(e?.hours??0)*3600+(e?.minutes??0)*60+(e?.seconds??0))*1e3;return new Date(Date.now()-t).toISOString()}function v(e,t,a){if(e==null)return null;if(typeof e=="number"&&typeof t=="number")return e+a*t;let c=B(e),w=B(t);if(c===null||w===null)throw new Error(`increment()/decrement() on a value that is not a number (${JSON.stringify(e)}): Postgres refuses it ("operator does not exist")`);let f=Math.max(c.scale,w.scale),d=K(c,f)+BigInt(a)*K(w,f);if(f===0)return typeof e=="number"?Number(d):d.toString();let h=d<0n,R=(h?-d:d).toString().padStart(f+1,"0"),k=`${h?"-":""}${R.slice(0,-f)}.${R.slice(-f)}`;return typeof e=="number"?Number(k):k}function kn(e,t){let a=A=>{let C=(A.unit<0n?-A.unit:A.unit).toString().padStart(A.scale+1,"0"),J=C.slice(0,C.length-A.scale),n=C.slice(C.length-A.scale),r=J.padStart(Math.ceil(J.length/4)*4,"0").match(/.{4}/g)??[],s=n.padEnd(Math.ceil(n.length/4)*4,"0").match(/.{4}/g)??[],i=[...r.map((u,l)=>[r.length-1-l,Number(u)]),...s.map((u,l)=>[-1-l,Number(u)])].find(([,u])=>u!==0);return i?[i[0],i[1]]:[0,0]},[c,w]=a(e),[f,d]=a(t),h=c-f-(w<=d?1:0),R=Math.min(Math.max(16-h*4,e.scale,t.scale,0),1e3),k=e.unit*10n**BigInt(R+t.scale),E=t.unit*10n**BigInt(e.scale),T=k/E,x=k%E;2n*(x<0n?-x:x)>=(E<0n?-E:E)&&(T+=k<0n!=E<0n?-1n:1n);let I=T<0n,W=(I?-T:T).toString().padStart(R+1,"0");return`${I?"-":""}${R===0?W:`${W.slice(0,-R)}.${W.slice(-R)}`}`}var $=e=>structuredClone(e);function rn(e,t,a){if(fn(a))throw new Error(`${e}(${t}): 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(!(a===null||typeof a!="object"))for(let[c,w]of Object.entries(a))if(c==="OR"||c==="AND")for(let f of Array.isArray(w)?w:[])rn(e,t,f);else c==="NOT"&&rn(e,t,w)}function D(e,t,a){return cn(new ln({fields:[{field:t,message:a}]},`${e}: ${t} ${a}`))}function on(e,t,a="where"){for(let[c,w]of Object.entries(t))if(c==="OR"||c==="AND"){let f=w;if(c==="AND"&&f.length===0)throw D(e,`${a}.AND`,"is an empty list \u2014 no condition at all. Leave it out, or name a condition in it.");f.forEach((d,h)=>{if(Object.keys(d).length===0)throw D(e,`${a}.${c}[${h}]`,"holds no condition \u2014 a branch that matches every row. Name a condition in it, or leave it out.");on(e,d,`${a}.${c}[${h}]`)})}else if(c==="NOT"){if(Array.isArray(w))throw D(e,`${a}.NOT`,"is a list \u2014 NOT takes one filter object. For several conditions, NOT: { AND: [...] } or NOT: { OR: [...] }.");if(Object.keys(w).length===0)throw D(e,`${a}.NOT`,"holds no condition \u2014 NOT of nothing is not a filter. Name the condition to exclude.");on(e,w,`${a}.NOT`)}else if(c==="has"&&Object.keys(w??{}).length===0)throw D(e,`${a}.has`,"names no relation \u2014 no condition. Name one: has: { <relation>: { \u2026 } }.")}function F(e,t){if(Object.keys(t).length===0)throw D(e,"where",`holds no condition, so ${e} would reach EVERY row of the table. Name a condition.`)}function sn(e){let t=!1;for(let a of e){if(a===!1)return!1;a===null&&(t=!0)}return t?null:!0}function mn(e){let t=!1;for(let a of e){if(a===!0)return!0;a===null&&(t=!0)}return t?null:!1}var j=e=>e==null;function L(e,t,a,c){return sn(Object.entries(c).map(([w,f])=>{if(w==="OR")return mn(f.map(d=>L(e,t,a,d)));if(w==="AND")return sn(f.map(d=>L(e,t,a,d)));if(w==="NOT"){let d=L(e,t,a,f);return d===null?null:!d}if(w==="has")throw new Error(`${e}(${t}): 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 xn(e,t,a,w,f)}))}var gn=["neq","gt","gte","lt","lte"];function Q(e,t){return j(e)||j(t)?null:N(e,t)}function xn(e,t,a,c,w){let f=a[c];return w===null?j(f):U(w)?Q(f,a[w.$col]):V(w)?Q(f,H(_(w)?.minus)):typeof w=="object"&&!Array.isArray(w)&&!(w instanceof Date)?sn(Object.entries(w).map(([d,h])=>{if(V(h)){if(!gn.includes(d))throw new Error(`${e}(${t}): where.${c}.${d} cannot take now()`);return G(d,f,H(_(h)?.minus))}if(Z(h))throw new Error(`${e}(${t}): where.${c}.${d} was given increment()/decrement() \u2014 a write, not a value to compare with`);if(U(h)){if(!gn.includes(d))throw new Error(`${e}(${t}): where.${c}.${d} cannot take col()`);return G(d,f,a[h.$col])}switch(d){case"in":{if(!Array.isArray(h))throw new Error(`${e}(${t}): where.${c}.in is a list`);return mn(h.map(R=>Q(f,R)))}case"neq":return h===null?!j(f):G(d,f,h);case"gt":case"gte":case"lt":case"lte":return G(d,f,h);case"isNull":if(typeof h!="boolean")throw new Error(`${e}(${t}): where.${c}.isNull is true or false`);return h?j(f):!j(f);case"overlaps":if(!Array.isArray(h))throw new Error(`${e}(${t}): where.${c}.overlaps is a list`);if(f!=null&&!Array.isArray(f))throw new Error(`${e}(${t}): where.${c}: "overlaps" is an array column's operator`);return j(f)?null:h.some(R=>f.some(k=>N(R,k)));case"contains":case"icontains":case"startsWith":case"endsWith":{if(d==="contains"&&Array.isArray(h))return j(f)?null:Array.isArray(f)&&h.every(R=>f.some(k=>N(R,k)));if(typeof h!="string")throw new Error(`${e}(${t}): where.${c}.${d} is text`);return j(f)?null:typeof f!="string"?!1:d==="contains"?f.includes(h):d==="icontains"?f.toLowerCase().includes(h.toLowerCase()):d==="startsWith"?f.startsWith(h):f.endsWith(h)}default:throw new Error(`${e}(${t}): where.${c} has no operator "${d}"`)}})):Q(f,w)}function G(e,t,a){if(j(t)||j(a))return null;if(e==="neq")return!N(t,a);let c=tn(t,a);return c===null?!1:e==="gt"?c>0:e==="gte"?c>=0:e==="lt"?c<0:c<=0}function En(){let e=new Map,t=new Map,a=new Map,c=new Map,w=[],f=n=>{let r=e.get(n);return r||e.set(n,r=[]),r},d=(n,r,s)=>{let o=n.get(r);o?o.push(s):n.set(r,[s])},h=n=>n.id===void 0?{id:Rn(),...n}:{...n},R=()=>{let n={store:new Map([...e].map(([r,s])=>[r,s.map($)])),inserted:hn(t),updated:hn(a),deleted:new Map([...c].map(([r,s])=>[r,[...s]]))};return()=>{e=n.store,t=n.inserted,a=n.updated,c=n.deleted}};function k(n,r,s){let o={};for(let[i,u]of Object.entries(s)){let l=_(u);if(l!==null&&l.fn==="now")o[i]=H(l.minus);else{if(l!==null)throw new Error(`${n}(${r}): "${i}" was given ${l.fn==="inc"?"increment()":"decrement()"} \u2014 the row does not exist yet, so there is no current value to change`);o[i]=u}}return P(n,r,Object.keys(o),o),z(n,r,Object.keys(o),o),o}function E(n,r,s,o){P(n,r,Object.keys(o),o);let i={};for(let[u,l]of Object.entries(o)){let g=_(l);g!==null&&g.fn==="now"?i[u]=H(g.minus):g!==null?i[u]=v(s[u],g.by,g.fn==="inc"?1:-1):i[u]=l}return z(n,r,Object.keys(i),i),i}function T(n,r,s){let o=h(k(n,r,s));return f(r).push(o),d(t,r,$(o)),$(o)}function x(n,r,s){return dn(n,r,s),rn(n,r,s),s!==void 0&&on(n,s),(e.get(r)??[]).filter(o=>s===void 0||L(n,r,o,s)===!0)}let I={diagnostics:()=>null,async query(n,r=[]){return w.push({sql:n,params:r}),[]},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,r){let s=(e.get(n)??[]).find(o=>o.id===r);return s?$(s):null},async findMany(n,r,s){let{limit:o,offset:i}=s??{};if(o!==void 0&&(!Number.isInteger(o)||o<0))throw new Error(`findMany(${n}): limit is a whole number, 0 or more (got ${String(o)})`);if(i!==void 0){if(!Number.isInteger(i)||i<0)throw new Error(`findMany(${n}): offset is a whole number, 0 or more (got ${String(i)})`);if(o===void 0)throw new Error(`findMany(${n}): offset comes with limit \u2014 an offset into an unbounded result is not a page`)}if(s?.with!==void 0&&Object.keys(s.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 u=x("findMany",n,r),l=s?.orderBy===void 0?[]:Array.isArray(s.orderBy)?s.orderBy:[s.orderBy];l.length>0&&(u=[...u].sort((y,p)=>{for(let O of l){let b=O.direction==="desc"?-1:1,M=y[O.column],S=p[O.column],X=M==null,an=S==null;if(X||an){if(X&&an)continue;let pn=O.nulls===void 0?b===-1:O.nulls==="first";return(X?1:-1)*(pn?-1:1)}let un=tn(M,S)??(String(M)<String(S)?-1:String(M)>String(S)?1:0);if(un!==0)return un*b}return 0}));let g=o===void 0?u:u.slice(i??0,(i??0)+o),m=s?.select;return g.map(y=>m===void 0||m.length===0?$(y):Object.fromEntries(m.map(p=>[p,structuredClone(y[p])])))},async count(n,r={}){return x("count",n,r).length},async aggregate(n,r){let s=x("aggregate",n,r.where),o=r.groupBy??[],i=l=>{let g={},m=y=>l.map(p=>p[y]).filter(p=>p!=null);for(let y of r.sum??[]){let p=m(y);(g.sum??={})[y]=p.length===0?null:String(p.reduce((O,b)=>v(O,b,1),"0"))}for(let y of r.avg??[]){let p=m(y),O=p.some(b=>typeof b=="number"&&!Number.isInteger(b));(g.avg??={})[y]=p.length===0?null:O?p.reduce((b,M)=>b+M,0)/p.length:kn(B(p.reduce((b,M)=>v(b,M,1),"0")),{unit:BigInt(p.length),scale:0})}for(let[y,p]of[["min",-1],["max",1]])for(let O of r[y]??[]){let b=m(O);(g[y]??={})[O]=b.length===0?null:b.reduce((M,S)=>(tn(S,M)??0)*p>0?S:M)}return r.count===!0?g.count=l.length:r.count!==void 0&&r.count!==!1&&(g.count=Object.fromEntries(Object.entries(r.count).map(([y,p])=>[y,l.filter(O=>L("aggregate",n,O,p)===!0).length]))),g};if(o.length===0)return i(s);let u=new Map;for(let l of s){let g=JSON.stringify(o.map(m=>l[m]));u.set(g,[...u.get(g)??[],l])}return[...u.values()].map(l=>({...i(l),...Object.fromEntries(o.map(g=>[g,l[0][g]]))}))},async insert(n,r){return T("insert",n,r)},insertMany:(async(n,r,s)=>{if(wn(s),s?.onConflict?.length||s?.action!==void 0)throw new Error(`insertMany(${n}): the fake database knows no unique constraint to collide with \u2014 test onConflict against Postgres`);if(r.length===0)return s?.returning===!1?0:[];let o=Object.keys(r[0]);r.forEach((u,l)=>{let g=o.filter(y=>!(y in u)),m=Object.keys(u).filter(y=>!o.includes(y));if(g.length>0||m.length>0)throw new Error(`insertMany(${n}): row ${l} has not the first row's columns${g.length?` (missing ${g.join(", ")})`:""}${m.length?` (extra ${m.join(", ")})`:""} \u2014 write null for an empty one, or insert rows of another shape in a call of their own`)});let i=r.map(u=>T("insertMany",n,u));return s?.returning===!1?i.length:i}),async put(n,r,s){if(!s?.onConflict?.length)throw new Error(`put(${n}): onConflict names at least one column`);let o=k("put",n,r),i=f(n).find(u=>s.onConflict.every(l=>N(u[l],o[l])));if(!i)return T("put",n,r);for(let[u,l]of Object.entries(o))s.onConflict.includes(u)||(i[u]=l);return d(a,n,$(i)),$(i)},async update(n,r,s){let o=e.get(n)??[],i=o.findIndex(u=>u.id===r);return i<0?(P("update",n,Object.keys(s),s),null):(o[i]={...o[i],...E("update",n,o[i],s)},d(a,n,$(o[i])),$(o[i]))},async updateMany(n,r,s,o){F("updateMany",r);let i=x("updateMany",n,r),u=f(n),l=[];for(let g of i){let m=u.indexOf(g);u[m]={...g,...E("updateMany",n,g,s)},d(a,n,$(u[m])),l.push($(u[m]))}return i.length===0&&P("updateMany",n,Object.keys(s),s),o?.returning===!1?l.length:l},async delete(n,r){let s=e.get(n)??[],o=s.findIndex(i=>i.id===r);o<0||(s.splice(o,1),d(c,n,r))},async deleteMany(n,r){F("deleteMany",r);let s=x("deleteMany",n,r);e.set(n,(e.get(n)??[]).filter(o=>!s.includes(o)));for(let o of s)d(c,n,String(o.id));return s.length},async claim(n,r,s={}){let o=Object.keys(r);if(o.length===0)throw new Error(`claim(${n}): no unique field \u2014 claim takes a key; without one, insert(${n}, \u2026)`);P("claim",n,o,r);let i=(e.get(n)??[]).find(u=>o.every(l=>N(u[l],r[l])));return i?{inserted:!1,row:$(i)}:{inserted:!0,row:T("claim",n,{...r,...s})}},async lockRows(n,r){if(r.length===0)return;let s=e.get(n)??[],o=[...new Set(r)].filter(i=>!s.some(u=>u.id===i));if(o.length>0&&s.length>0)throw new Error(`lockRows(${n}): no row with id ${o.join(", ")}`)},async lockRowsWhere(n,r,s){let o=s?.mode??"update";if(!["update","share","noKeyUpdate"].includes(o))throw new Error(`lockRowsWhere(${n}): mode is "update", "share" or "noKeyUpdate" (got "${String(o)}")`);F("lockRowsWhere",r),x("lockRowsWhere",n,r)},async advisoryXactLock(){}};function W(n){let r=R(),s=[];try{for(let o of n.ops){let i=A(o,s);s.push(i);let u=Tn(o.guard,i.rows.length);if(u)throw u}}catch(o){throw r(),o}return{results:s}}function A(n,r){let s=i=>Object.fromEntries(Object.entries(i??{}).map(([u,l])=>[u,yn(l,r)])),o=`transaction plan ${n.op}`;switch(n.op){case"insert":return nn(T(o,n.table,s(n.values)));case"insertMany":{let i=(n.rows??[]).map(g=>s(g)),u=n.onConflict??[];if(n.action!==void 0&&u.length===0)throw new Error(`${o}(${n.table}): the fake database knows no unique key to collide with \u2014 name onConflict columns, or test this against Postgres`);let l=[];for(let g of i){let m=u.length>0?f(n.table).find(y=>u.every(p=>N(y[p],g[p]))):void 0;if(!(m&&n.action==="ignore")){if(m&&n.action==="update"){Object.assign(m,E(o,n.table,m,Object.fromEntries(Object.entries(g).filter(([y])=>!u.includes(y))))),d(a,n.table,$(m)),l.push($(m));continue}l.push(T(o,n.table,g))}}return{rows:l,rows_affected:l.length}}case"upsert":{let i=s(n.values),u=n.onConflict??[];if(Object.keys(i).length===0||u.length===0)throw Object.assign(new Error(`put on ${n.table} needs columns and onConflict`),{error_code:"tx_bad_upsert"});let l=f(n.table).find(g=>u.every(m=>N(g[m],i[m])));return l?(Object.assign(l,E(o,n.table,l,Object.fromEntries(Object.entries(i).filter(([g])=>!u.includes(g))))),d(a,n.table,$(l)),nn($(l))):nn(T(o,n.table,i))}case"update":{let i=s(n.set);if(Object.keys(i).length===0)throw new Error(`update ${n.table}: nothing to set`);let u=en(n.where,r);F(o,u);let l=f(n.table),g=[];for(let m of x(o,n.table,u)){let y=l.indexOf(m);l[y]={...m,...E(o,n.table,m,i)},d(a,n.table,$(l[y])),g.push($(l[y]))}return{rows:g,rows_affected:g.length}}case"delete":{let i=en(n.where,r);F(o,i);let u=x(o,n.table,i);e.set(n.table,f(n.table).filter(l=>!u.includes(l)));for(let l of u)d(c,n.table,String(l.id));return{rows:u.map($),rows_affected:u.length}}case"select":{let i=x(o,n.table,en(n.where,r));return n.limit!==void 0&&(i=i.slice(0,n.limit)),{rows:i.map($),rows_affected:i.length}}default:throw new Error(`unknown operation "${String(n.op)}" in a transaction plan`)}}let C={...I,async txPlan(n){return W(n)},async attempt(n){let r=R();try{return await n(I)}catch(s){throw r(),s}},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=>(t.get(n)??[]).map($),updated:n=>(a.get(n)??[]).map($),deleted:n=>[...c.get(n)??[]],seed(n,r){e.set(n,r.map($))},queries:w}}function hn(e){return new Map([...e].map(([t,a])=>[t,a.map($)]))}function nn(e){return{rows:[e],rows_affected:1}}function yn(e,t){if(!Y(e))return e;let a=t[e.$ref.op]?.rows[0];if(!a)throw Object.assign(new Error(`transaction plan: operation ${e.$ref.op} produced no row to reference`),{error_code:"tx_ref_unresolved"});return a[e.$ref.field]}function en(e,t){let a=c=>{if(Y(c)){let w=yn(c,t);if(w==null)throw Object.assign(new Error(`transaction plan: a filter's reference to operation ${c.$ref.op}'s "${c.$ref.field}" is NULL`),{error_code:"tx_ref_null"});return w}return Array.isArray(c)?c.map(a):c!==null&&typeof c=="object"&&!U(c)&&!Z(c)&&!V(c)&&!(c instanceof Date)?Object.fromEntries(Object.entries(c).map(([w,f])=>[w,a(f)])):c};return a(e??{})}function Tn(e,t){return e?(e.kind==="one"?t===1:e.kind==="none"?t===0:e.kind==="atLeast"?t>=e.n:t<=e.n)?null:Object.assign(new Error(`transaction expectation failed: ${e.kind} (${t} row(s))`),{error_code:"tx_guard_failed",slot:e.slot}):null}export{En as createFakeClient,$n as typedDatabase};
1
+ /*! palgres 0.55.0 — Palbase SDK License (see LICENSE) */
2
+ import{F as pe,G as be,P as G,Q as Re,R as ne,V as te,W as J,X as re,Y as $e,_ as B,ga as U,la as Oe,ma as Ie,n as he,p as me}from"./chunks/5EMZSH7B.js";import{o as we,r as ye,y as K,z as Q}from"./chunks/DLP3GKUJ.js";import{randomUUID as De}from"node:crypto";var Te=/^[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}$/,ke="user";function Se(n){let t=n.filter(i=>i!=null);return t.length===0?"text":t.every(i=>typeof i=="boolean")?"bool":t.every(i=>typeof i=="bigint"||typeof i=="number"&&Number.isInteger(i))?"int":t.every(i=>typeof i=="bigint"||typeof i=="number"&&Number.isFinite(i))?"numeric":t.every(i=>typeof i=="string"&&Te.test(i))?"uuid":"text"}function Ce(n,t){return t==null?null:n==="bool"||n==="int"||n==="numeric"||typeof t=="string"?t:String(t)}var je=n=>n.schema==="public"?n.name:`${n.schema}.${n.name}`;function xe(n,t){let i=ye(we(n)),l=be(n,"memory"),g,f=[],m=[],p=new Map,O=[...i.types.values()].filter(y=>y.table),k=y=>{let d=i.types.get(y),w=new Set;if(!d?.table)return[];w.add(d.table.key??"id");let e=r=>{let s=r;s.parts?s.parts.forEach(e):s.part?e(s.part):s.column&&w.add(s.column)};for(let r of d.relations.values())r.kind==="column"&&(w.add(r.column),r.where&&e(r.where));return[...w]},S=()=>{let y=new Map;for(let d of O){let w=d.table,e=t.rows(je(w)),r=w.key??"id",s={};for(let a of k(d.name))s[a]=Se(e.map(u=>u[a]));let o={key:r,columns:s};y.set(d.name,{shape:o,rows:e.map(a=>Object.fromEntries(Object.entries(s).map(([u,c])=>[u,Ce(c,a[u])])))})}return{tables:y,relationships:f}},N=(y,d,w)=>{let e=y.tables.get(d);if(!e)return w;let r=e.shape.columns[e.shape.key],s=K(r,w);return s===null?null:e.rows.some(a=>{let u=a[e.shape.key];return u!==null&&K(r,String(u))===s})?s:void 0},M=()=>{for(let d of O){let w=d.table,e=je(w),r=w.key??"id",s=t.deleted(e),o=Math.min(p.get(e)??0,s.length),a=c=>Te.test(c)?c.toLowerCase():c,u=new Set(s.slice(o).map(c=>c[r]).filter(c=>c!=null).map(c=>a(String(c))));p.set(e,s.length),u.size>0&&C(d.name,c=>u.has(a(c)),"access: row deleted")}let y=S();for(let d of O)C(d.name,w=>N(y,d.name,w)===void 0,"access: row deleted");return S()},C=(y,d,w)=>{let e=[];for(let r of f)r.objectType===y&&d(r.objectId)||r.subjectType===y&&d(r.subjectId)?E("revoke",r,w):e.push(r);f=e},E=(y,d,w)=>{m.unshift({at:new Date().toISOString(),action:y,object:{type:d.objectType,id:d.objectId},relation:d.relation,subject:{type:d.subjectType,id:d.subjectId},by:w})},T=(y,d)=>(y.object_type===void 0||y.object_type===d.objectType)&&(y.object_id===void 0||y.object_id===d.objectId)&&(y.relation===void 0||y.relation===d.relation)&&(y.subject_type===void 0||y.subject_type===d.subjectType)&&(y.subject_id===void 0||y.subject_id===d.subjectId),D=(y,d)=>{for(let w of["objectType","objectId","relation","subjectType","subjectId"])if(y[w]!==d[w])return y[w]<d[w]?-1:1;return 0};return{names:l,via:{caller:()=>g,check(y,d,w,e){let r=M(),s=N(r,w,e);return s==null?!1:Q(i,r).check(y,w,s,d)},objects:(y,d,w)=>Q(i,M()).objects(y,w,d),subjects(y,d,w){let e=M(),r=N(e,d,w);return r==null?[]:Q(i,e).subjects(d,r,y)},change(y,d,w,e,r){let s=M(),o=(u,c,h)=>{if(c===ke)return h;let b=N(s,c,h);if(b==null)throw new pe("no_object",`Database.$access: there is no ${c} ${JSON.stringify(h)} (${u}) \u2014 a relationship is given on an object that exists`);return b};if(y==="revoke"){let u=($,A)=>{let x=$===ke?void 0:s.tables.get($);return x?K(x.shape.columns[x.shape.key],A):A},c=u(d.type,d.id),h=u(e.type,e.id);if(c===null||h===null)return!1;let b={objectType:d.type,objectId:c,relation:w,subjectType:e.type,subjectId:h},R=f.findIndex($=>D($,b)===0);return R<0?!1:(f.splice(R,1),E("revoke",b,r??g??null),!0)}let a={objectType:d.type,objectId:o("the object",d.type,d.id),relation:w,subjectType:e.type,subjectId:o("the subject",e.type,e.id)};return f.some(u=>D(u,a)===0)?!1:(f.push({...a,since:new Date().toISOString()}),E("grant",a,r??g??null),!0)},relationships(y,d){return M(),f.filter(w=>T(y,w)).sort(D).slice(0,d).map(w=>({object:{type:w.objectType,id:w.objectId},relation:w.relation,subject:{type:w.subjectType,id:w.subjectId},since:w.since}))},history(y,d){return M(),m.filter(w=>T(y,{objectType:w.object.type,objectId:w.object.id,relation:w.relation,subjectType:w.subject.type,subjectId:w.subject.id})).slice(0,d).map(w=>({...w,object:{...w.object},subject:{...w.subject}}))}},signedInAs(y){g=y},snapshot(){let y={relationships:f.map(d=>({...d})),history:m.map(d=>({...d})),seen:new Map(p),user:g};return()=>{f=y.relationships,m=y.history,p=y.seen,g=y.user}}}}var Fe=/^\d{4}-\d{2}-\d{2}([T ]\d{2}:\d{2}(:\d{2}(\.\d+)?)?)?(Z|[+-]\d{2}(:?\d{2})?)?$/,Pe=/^([+-]?)(\d*)(?:\.(\d*))?$/;function v(n){if(n instanceof Date)return n.getTime();if(typeof n=="string"&&Fe.test(n)){let t=Date.parse(n);return Number.isNaN(t)?null:t}return null}function V(n){if(typeof n=="number")return Number.isFinite(n)?V(String(n)):null;if(typeof n!="string"||/e/i.test(n))return null;let t=Pe.exec(n.trim());if(t===null||t[2]===""&&(t[3]??"")==="")return null;let i=t[3]??"";return{unit:BigInt(`${t[1]==="-"?"-":""}${t[2]===""?"0":t[2]}${i}`),scale:i.length}}function Y(n,t){return n.unit*10n**BigInt(t-n.scale)}function ce(n,t){if(n==null||t===null||t===void 0)return null;let i=v(n),l=v(t);if(i!==null&&l!==null)return Math.sign(i-l);let g=V(n),f=V(t);if(g!==null&&f!==null){let m=Math.max(g.scale,f.scale),p=Y(g,m)-Y(f,m);return p===0n?0:p<0n?-1:1}return typeof n==typeof t&&(typeof n=="string"||typeof n=="boolean"||typeof n=="number")?n<t?-1:n>t?1:0:null}function P(n,t){return n==null||t===null||t===void 0?!1:n instanceof Date||t instanceof Date?v(n)!==null&&v(n)===v(t):Array.isArray(n)&&Array.isArray(t)?n.length===t.length&&n.every((i,l)=>P(i,t[l])):n===t}function Z(n){let t=((n?.days??0)*86400+(n?.hours??0)*3600+(n?.minutes??0)*60+(n?.seconds??0))*1e3;return new Date(Date.now()-t).toISOString()}function se(n,t,i){if(n==null)return null;if(typeof n=="number"&&typeof t=="number")return n+i*t;let l=V(n),g=V(t);if(l===null||g===null)throw new Error(`increment()/decrement() on a value that is not a number (${JSON.stringify(n)}): Postgres refuses it ("operator does not exist")`);let f=Math.max(l.scale,g.scale),m=Y(l,f)+BigInt(i)*Y(g,f);if(f===0)return typeof n=="number"?Number(m):m.toString();let p=m<0n,O=(p?-m:m).toString().padStart(f+1,"0"),k=`${p?"-":""}${O.slice(0,-f)}.${O.slice(-f)}`;return typeof n=="number"?Number(k):k}function _e(n,t){let i=T=>{let D=(T.unit<0n?-T.unit:T.unit).toString().padStart(T.scale+1,"0"),q=D.slice(0,D.length-T.scale),y=D.slice(D.length-T.scale),d=q.padStart(Math.ceil(q.length/4)*4,"0").match(/.{4}/g)??[],w=y.padEnd(Math.ceil(y.length/4)*4,"0").match(/.{4}/g)??[],r=[...d.map((s,o)=>[d.length-1-o,Number(s)]),...w.map((s,o)=>[-1-o,Number(s)])].find(([,s])=>s!==0);return r?[r[0],r[1]]:[0,0]},[l,g]=i(n),[f,m]=i(t),p=l-f-(g<=m?1:0),O=Math.min(Math.max(16-p*4,n.scale,t.scale,0),1e3),k=n.unit*10n**BigInt(O+t.scale),S=t.unit*10n**BigInt(n.scale),N=k/S,M=k%S;2n*(M<0n?-M:M)>=(S<0n?-S:S)&&(N+=k<0n!=S<0n?-1n:1n);let C=N<0n,E=(C?-N:N).toString().padStart(O+1,"0");return`${C?"-":""}${O===0?E:`${E.slice(0,-O)}.${E.slice(-O)}`}`}var j=n=>structuredClone(n);function ue(n,t,i){if(Re(i))throw new Error(`${n}(${t}): 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(!(i===null||typeof i!="object"))for(let[l,g]of Object.entries(i))if(l==="OR"||l==="AND")for(let f of Array.isArray(g)?g:[])ue(n,t,f);else l==="NOT"&&ue(n,t,g)}function W(n,t,i){return he(new me({fields:[{field:t,message:i}]},`${n}: ${t} ${i}`))}function le(n,t,i="where"){for(let[l,g]of Object.entries(t))if(l==="OR"||l==="AND"){let f=g;if(l==="AND"&&f.length===0)throw W(n,`${i}.AND`,"is an empty list \u2014 no condition at all. Leave it out, or name a condition in it.");f.forEach((m,p)=>{if(Object.keys(m).length===0)throw W(n,`${i}.${l}[${p}]`,"holds no condition \u2014 a branch that matches every row. Name a condition in it, or leave it out.");le(n,m,`${i}.${l}[${p}]`)})}else if(l==="NOT"){if(Array.isArray(g))throw W(n,`${i}.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 W(n,`${i}.NOT`,"holds no condition \u2014 NOT of nothing is not a filter. Name the condition to exclude.");le(n,g,`${i}.NOT`)}else if(l==="has"&&Object.keys(g??{}).length===0)throw W(n,`${i}.has`,"names no relation \u2014 no condition. Name one: has: { <relation>: { \u2026 } }.")}function L(n,t){if(Object.keys(t).length===0)throw W(n,"where",`holds no condition, so ${n} would reach EVERY row of the table. Name a condition.`)}function fe(n){let t=!1;for(let i of n){if(i===!1)return!1;i===null&&(t=!0)}return t?null:!0}function Ee(n){let t=!1;for(let i of n){if(i===!0)return!0;i===null&&(t=!0)}return t?null:!1}var F=n=>n==null;function H(n,t,i,l){return fe(Object.entries(l).map(([g,f])=>{if(g==="OR")return Ee(f.map(m=>H(n,t,i,m)));if(g==="AND")return fe(f.map(m=>H(n,t,i,m)));if(g==="NOT"){let m=H(n,t,i,f);return m===null?null:!m}if(g==="has")throw new Error(`${n}(${t}): 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 Be(n,t,i,g,f)}))}var Ae=["neq","gt","gte","lt","lte"];function z(n,t){return F(n)||F(t)?null:P(n,t)}function Be(n,t,i,l,g){let f=i[l];return g===null?F(f):G(g)?z(f,i[g.$col]):J(g)?z(f,Z(U(g)?.minus)):typeof g=="object"&&!Array.isArray(g)&&!(g instanceof Date)?fe(Object.entries(g).map(([m,p])=>{if(J(p)){if(!Ae.includes(m))throw new Error(`${n}(${t}): where.${l}.${m} cannot take now()`);return X(m,f,Z(U(p)?.minus))}if(te(p))throw new Error(`${n}(${t}): where.${l}.${m} was given increment()/decrement() \u2014 a write, not a value to compare with`);if(G(p)){if(!Ae.includes(m))throw new Error(`${n}(${t}): where.${l}.${m} cannot take col()`);return X(m,f,i[p.$col])}switch(m){case"in":{if(!Array.isArray(p))throw new Error(`${n}(${t}): where.${l}.in is a list`);return Ee(p.map(O=>z(f,O)))}case"neq":return p===null?!F(f):X(m,f,p);case"gt":case"gte":case"lt":case"lte":return X(m,f,p);case"isNull":if(typeof p!="boolean")throw new Error(`${n}(${t}): where.${l}.isNull is true or false`);return p?F(f):!F(f);case"overlaps":if(!Array.isArray(p))throw new Error(`${n}(${t}): where.${l}.overlaps is a list`);if(f!=null&&!Array.isArray(f))throw new Error(`${n}(${t}): where.${l}: "overlaps" is an array column's operator`);return F(f)?null:p.some(O=>f.some(k=>P(O,k)));case"contains":case"icontains":case"startsWith":case"endsWith":{if(m==="contains"&&Array.isArray(p))return F(f)?null:Array.isArray(f)&&p.every(O=>f.some(k=>P(O,k)));if(typeof p!="string")throw new Error(`${n}(${t}): where.${l}.${m} is text`);return F(f)?null:typeof f!="string"?!1:m==="contains"?f.includes(p):m==="icontains"?f.toLowerCase().includes(p.toLowerCase()):m==="startsWith"?f.startsWith(p):f.endsWith(p)}default:throw new Error(`${n}(${t}): where.${l} has no operator "${m}"`)}})):z(f,g)}function X(n,t,i){if(F(t)||F(i))return null;if(n==="neq")return!P(t,i);let l=ce(t,i);return l===null?!1:n==="gt"?l>0:n==="gte"?l>=0:n==="lt"?l<0:l<=0}function We(n={}){let t=new Map,i=new Map,l=new Map,g=new Map,f=new Map,m=[],p=n.access===void 0?void 0:xe(n.access,{rows:e=>t.get(e)??[],deleted:e=>f.get(e)??[]});p?.signedInAs(n.user);let O=e=>{let r=t.get(e);return r||t.set(e,r=[]),r},k=(e,r,s)=>{let o=e.get(r);o?o.push(s):e.set(r,[s])},S=e=>e.id===void 0?{id:De(),...e}:{...e},N=()=>{let e={store:new Map([...t].map(([s,o])=>[s,o.map(j)])),inserted:oe(i),updated:oe(l),deleted:new Map([...g].map(([s,o])=>[s,[...o]])),removed:oe(f)},r=p?.snapshot();return()=>{t=e.store,i=e.inserted,l=e.updated,g=e.deleted,f=e.removed,r?.()}};function M(e,r,s){let o={};for(let[a,u]of Object.entries(s)){let c=U(u);if(c!==null&&c.fn==="now")o[a]=Z(c.minus);else{if(c!==null)throw new Error(`${e}(${r}): "${a}" was given ${c.fn==="inc"?"increment()":"decrement()"} \u2014 the row does not exist yet, so there is no current value to change`);o[a]=u}}return B(e,r,Object.keys(o),o),re(e,r,Object.keys(o),o),o}function C(e,r,s,o){B(e,r,Object.keys(o),o);let a={};for(let[u,c]of Object.entries(o)){let h=U(c);h!==null&&h.fn==="now"?a[u]=Z(h.minus):h!==null?a[u]=se(s[u],h.by,h.fn==="inc"?1:-1):a[u]=c}return re(e,r,Object.keys(a),a),a}function E(e,r,s){let o=S(M(e,r,s));return O(r).push(o),k(i,r,j(o)),j(o)}function T(e,r,s){return $e(e,r,s),ue(e,r,s),s!==void 0&&le(e,s),(t.get(r)??[]).filter(o=>s===void 0||H(e,r,o,s)===!0)}let D={diagnostics:()=>null,async query(e,r=[]){return m.push({sql:e,params:r}),[]},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(e){throw new Error(`search(${e}): the fake database has neither embeddings nor full text \u2014 test search against Postgres`)},async findById(e,r){let s=(t.get(e)??[]).find(o=>o.id===r);return s?j(s):null},async findMany(e,r,s){let{limit:o,offset:a}=s??{};if(o!==void 0&&(!Number.isInteger(o)||o<0))throw new Error(`findMany(${e}): limit is a whole number, 0 or more (got ${String(o)})`);if(a!==void 0){if(!Number.isInteger(a)||a<0)throw new Error(`findMany(${e}): offset is a whole number, 0 or more (got ${String(a)})`);if(o===void 0)throw new Error(`findMany(${e}): offset comes with limit \u2014 an offset into an unbounded result is not a page`)}if(s?.with!==void 0&&Object.keys(s.with).length>0)throw new Error(`findMany(${e}): 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 u=T("findMany",e,r),c=s?.orderBy===void 0?[]:Array.isArray(s.orderBy)?s.orderBy:[s.orderBy];c.length>0&&(u=[...u].sort((R,$)=>{for(let A of c){let x=A.direction==="desc"?-1:1,I=R[A.column],_=$[A.column],ee=I==null,de=_==null;if(ee||de){if(ee&&de)continue;let Ne=A.nulls===void 0?x===-1:A.nulls==="first";return(ee?1:-1)*(Ne?-1:1)}let ge=ce(I,_)??(String(I)<String(_)?-1:String(I)>String(_)?1:0);if(ge!==0)return ge*x}return 0}));let h=o===void 0?u:u.slice(a??0,(a??0)+o),b=s?.select;return h.map(R=>b===void 0||b.length===0?j(R):Object.fromEntries(b.map($=>[$,structuredClone(R[$])])))},async count(e,r={}){return T("count",e,r).length},async aggregate(e,r){let s=T("aggregate",e,r.where),o=r.groupBy??[],a=c=>{let h={},b=R=>c.map($=>$[R]).filter($=>$!=null);for(let R of r.sum??[]){let $=b(R);(h.sum??={})[R]=$.length===0?null:String($.reduce((A,x)=>se(A,x,1),"0"))}for(let R of r.avg??[]){let $=b(R),A=$.some(x=>typeof x=="number"&&!Number.isInteger(x));(h.avg??={})[R]=$.length===0?null:A?$.reduce((x,I)=>x+I,0)/$.length:_e(V($.reduce((x,I)=>se(x,I,1),"0")),{unit:BigInt($.length),scale:0})}for(let[R,$]of[["min",-1],["max",1]])for(let A of r[R]??[]){let x=b(A);(h[R]??={})[A]=x.length===0?null:x.reduce((I,_)=>(ce(_,I)??0)*$>0?_:I)}return r.count===!0?h.count=c.length:r.count!==void 0&&r.count!==!1&&(h.count=Object.fromEntries(Object.entries(r.count).map(([R,$])=>[R,c.filter(A=>H("aggregate",e,A,$)===!0).length]))),h};if(o.length===0)return a(s);let u=new Map;for(let c of s){let h=JSON.stringify(o.map(b=>c[b]));u.set(h,[...u.get(h)??[],c])}return[...u.values()].map(c=>({...a(c),...Object.fromEntries(o.map(h=>[h,c[0][h]]))}))},async insert(e,r){return E("insert",e,r)},insertMany:(async(e,r,s)=>{if(Oe(s),s?.onConflict?.length||s?.action!==void 0)throw new Error(`insertMany(${e}): the fake database knows no unique constraint to collide with \u2014 test onConflict against Postgres`);if(r.length===0)return s?.returning===!1?0:[];let o=Object.keys(r[0]);r.forEach((u,c)=>{let h=o.filter(R=>!(R in u)),b=Object.keys(u).filter(R=>!o.includes(R));if(h.length>0||b.length>0)throw new Error(`insertMany(${e}): row ${c} has not the first row's columns${h.length?` (missing ${h.join(", ")})`:""}${b.length?` (extra ${b.join(", ")})`:""} \u2014 write null for an empty one, or insert rows of another shape in a call of their own`)});let a=r.map(u=>E("insertMany",e,u));return s?.returning===!1?a.length:a}),async put(e,r,s){if(!s?.onConflict?.length)throw new Error(`put(${e}): onConflict names at least one column`);let o=M("put",e,r),a=O(e).find(u=>s.onConflict.every(c=>P(u[c],o[c])));if(!a)return E("put",e,r);for(let[u,c]of Object.entries(o))s.onConflict.includes(u)||(a[u]=c);return k(l,e,j(a)),j(a)},async update(e,r,s){let o=t.get(e)??[],a=o.findIndex(u=>u.id===r);return a<0?(B("update",e,Object.keys(s),s),null):(o[a]={...o[a],...C("update",e,o[a],s)},k(l,e,j(o[a])),j(o[a]))},async updateMany(e,r,s,o){L("updateMany",r);let a=T("updateMany",e,r),u=O(e),c=[];for(let h of a){let b=u.indexOf(h);u[b]={...h,...C("updateMany",e,h,s)},k(l,e,j(u[b])),c.push(j(u[b]))}return a.length===0&&B("updateMany",e,Object.keys(s),s),o?.returning===!1?c.length:c},async delete(e,r){let s=t.get(e)??[],o=s.findIndex(u=>u.id===r);if(o<0)return;let[a]=s.splice(o,1);k(g,e,r),k(f,e,a)},async deleteMany(e,r){L("deleteMany",r);let s=T("deleteMany",e,r);t.set(e,(t.get(e)??[]).filter(o=>!s.includes(o)));for(let o of s)k(g,e,String(o.id)),k(f,e,o);return s.length},async claim(e,r,s={}){let o=Object.keys(r);if(o.length===0)throw new Error(`claim(${e}): no unique field \u2014 claim takes a key; without one, insert(${e}, \u2026)`);B("claim",e,o,r);let a=(t.get(e)??[]).find(u=>o.every(c=>P(u[c],r[c])));return a?{inserted:!1,row:j(a)}:{inserted:!0,row:E("claim",e,{...r,...s})}},async lockRows(e,r){if(r.length===0)return;let s=t.get(e)??[],o=[...new Set(r)].filter(a=>!s.some(u=>u.id===a));if(o.length>0&&s.length>0)throw new Error(`lockRows(${e}): no row with id ${o.join(", ")}`)},async lockRowsWhere(e,r,s){let o=s?.mode??"update";if(!["update","share","noKeyUpdate"].includes(o))throw new Error(`lockRowsWhere(${e}): mode is "update", "share" or "noKeyUpdate" (got "${String(o)}")`);L("lockRowsWhere",r),T("lockRowsWhere",e,r)},async advisoryXactLock(){}};function q(e){let r=N(),s=[];try{for(let o of e.ops){let a=y(o,s);s.push(a);let u=Ve(o.guard,a.rows.length);if(u)throw u}}catch(o){throw r(),o}return{results:s}}function y(e,r){let s=a=>Object.fromEntries(Object.entries(a??{}).map(([u,c])=>[u,Me(c,r)])),o=`transaction plan ${e.op}`;switch(e.op){case"insert":return ie(E(o,e.table,s(e.values)));case"insertMany":{let a=(e.rows??[]).map(h=>s(h)),u=e.onConflict??[];if(e.action!==void 0&&u.length===0)throw new Error(`${o}(${e.table}): the fake database knows no unique key to collide with \u2014 name onConflict columns, or test this against Postgres`);let c=[];for(let h of a){let b=u.length>0?O(e.table).find(R=>u.every($=>P(R[$],h[$]))):void 0;if(!(b&&e.action==="ignore")){if(b&&e.action==="update"){Object.assign(b,C(o,e.table,b,Object.fromEntries(Object.entries(h).filter(([R])=>!u.includes(R))))),k(l,e.table,j(b)),c.push(j(b));continue}c.push(E(o,e.table,h))}}return{rows:c,rows_affected:c.length}}case"upsert":{let a=s(e.values),u=e.onConflict??[];if(Object.keys(a).length===0||u.length===0)throw Object.assign(new Error(`put on ${e.table} needs columns and onConflict`),{error_code:"tx_bad_upsert"});let c=O(e.table).find(h=>u.every(b=>P(h[b],a[b])));return c?(Object.assign(c,C(o,e.table,c,Object.fromEntries(Object.entries(a).filter(([h])=>!u.includes(h))))),k(l,e.table,j(c)),ie(j(c))):ie(E(o,e.table,a))}case"update":{let a=s(e.set);if(Object.keys(a).length===0)throw new Error(`update ${e.table}: nothing to set`);let u=ae(e.where,r);L(o,u);let c=O(e.table),h=[];for(let b of T(o,e.table,u)){let R=c.indexOf(b);c[R]={...b,...C(o,e.table,b,a)},k(l,e.table,j(c[R])),h.push(j(c[R]))}return{rows:h,rows_affected:h.length}}case"delete":{let a=ae(e.where,r);L(o,a);let u=T(o,e.table,a);t.set(e.table,O(e.table).filter(c=>!u.includes(c)));for(let c of u)k(g,e.table,String(c.id)),k(f,e.table,c);return{rows:u.map(j),rows_affected:u.length}}case"select":{let a=T(o,e.table,ae(e.where,r));return e.limit!==void 0&&(a=a.slice(0,e.limit)),{rows:a.map(j),rows_affected:a.length}}default:throw new Error(`unknown operation "${String(e.op)}" in a transaction plan`)}}let d={...D,async txPlan(e){return q(e)},async attempt(e){let r=N();try{return await e(D)}catch(s){throw r(),s}},async atomic(){throw new Error("the fake database cannot reproduce a transaction's isolation, COMMIT or retry \u2014 test $atomic against Postgres")}};return{...d,asService:()=>d,inserted:e=>(i.get(e)??[]).map(j),updated:e=>(l.get(e)??[]).map(j),deleted:e=>[...g.get(e)??[]],seed(e,r){t.set(e,r.map(j))},queries:m,...p===void 0?{}:{access:p}}}function oe(n){return new Map([...n].map(([t,i])=>[t,i.map(j)]))}function ie(n){return{rows:[n],rows_affected:1}}function Me(n,t){if(!ne(n))return n;let i=t[n.$ref.op]?.rows[0];if(!i)throw Object.assign(new Error(`transaction plan: operation ${n.$ref.op} produced no row to reference`),{error_code:"tx_ref_unresolved"});return i[n.$ref.field]}function ae(n,t){let i=l=>{if(ne(l)){let g=Me(l,t);if(g==null)throw Object.assign(new Error(`transaction plan: a filter's reference to operation ${l.$ref.op}'s "${l.$ref.field}" is NULL`),{error_code:"tx_ref_null"});return g}return Array.isArray(l)?l.map(i):l!==null&&typeof l=="object"&&!G(l)&&!te(l)&&!J(l)&&!(l instanceof Date)?Object.fromEntries(Object.entries(l).map(([g,f])=>[g,i(f)])):l};return i(n??{})}function Ve(n,t){return n?(n.kind==="one"?t===1:n.kind==="none"?t===0:n.kind==="atLeast"?t>=n.n:t<=n.n)?null:Object.assign(new Error(`transaction expectation failed: ${n.kind} (${t} row(s))`),{error_code:"tx_guard_failed",slot:n.slot}):null}export{We as createFakeClient,Ie as typedDatabase};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "palgres",
3
- "version": "0.53.0",
3
+ "version": "0.55.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",
@@ -0,0 +1,98 @@
1
+ import { type Compiled, type CompileOptions } from './compile.js';
2
+ import { type Model } from './model.js';
3
+ export interface ApplyOptions extends CompileOptions {
4
+ /** Take away the relationships of relations the new schema no longer keeps, instead of refusing. */
5
+ dropRelationships?: boolean;
6
+ /** Compiled schemas (their digests) to leave in place beside the new one: another version of the app still asks them. */
7
+ keep?: string[];
8
+ }
9
+ /** What is in the database before anything is changed. */
10
+ export interface Before {
11
+ /** The comment on the schema `access`; null when there is no such schema. */
12
+ mark: string | null;
13
+ exists: boolean;
14
+ /** The compiled schemas there (access_<digest>), with how many views and functions each holds. */
15
+ compiled: {
16
+ name: string;
17
+ views: number;
18
+ functions: number;
19
+ }[];
20
+ /** The views `access` shows names as, with the type of their `id`. */
21
+ aliases: {
22
+ name: string;
23
+ type: string;
24
+ }[];
25
+ /** The triggers access itself put on tables (they run a function of access'), whether each is on for the app's work, and the type and key they were made for. */
26
+ triggers: {
27
+ schema: string;
28
+ table: string;
29
+ name: string;
30
+ enabled?: boolean;
31
+ args?: string;
32
+ }[];
33
+ /** The row policies access itself made (they carry its mark), and whether their table has row-level security on. */
34
+ policies: {
35
+ schema: string;
36
+ table: string;
37
+ name: string;
38
+ rls?: boolean;
39
+ }[];
40
+ /** Tables with a trigger of their own that would fire after a change before access' (EARLY_TRIGGER). */
41
+ early: {
42
+ schema: string;
43
+ table: string;
44
+ }[];
45
+ catalog: unknown;
46
+ }
47
+ /** What relationships are kept, by (type, relation, kind of subject), and which compiled schema is active. */
48
+ export interface Kept {
49
+ active: string | null;
50
+ /** The engine that compiled the schema in force (base.ts ENGINE); absent when none is, or read by an older reader. */
51
+ engine?: string | null;
52
+ relationships: {
53
+ object_type: string;
54
+ relation: string;
55
+ subject_type: string;
56
+ count: number;
57
+ }[];
58
+ }
59
+ /** Reads the database as it is: one row, one column `before`, JSON. It names nothing of access', so it runs anywhere. */
60
+ export declare function beforeQuery(model: Model): string;
61
+ /** Reads what access keeps. Run only where `before.exists` and the mark is Palbase's: it names access' own tables. */
62
+ export declare function keptQuery(): string;
63
+ export interface Planned {
64
+ compiled: Compiled;
65
+ /** Run in one transaction, in order, as the tables' owner. Empty when the database already has this schema. */
66
+ statements: string[];
67
+ /** The schema that was active, when it is another: what this replaces. */
68
+ replaces: string | null;
69
+ /** True when the database already answers from this schema and nothing is run. */
70
+ unchanged: boolean;
71
+ /** Relationships taken away because the schema no longer keeps their relation (with dropRelationships). */
72
+ dropped: {
73
+ object_type: string;
74
+ relation: string;
75
+ subject_type: string;
76
+ count: number;
77
+ }[];
78
+ }
79
+ /**
80
+ * What to run to make `text` the database's access schema. Throws AccessError when the schema does not hold
81
+ * together, names a table the database does not have as it says, or would orphan relationships.
82
+ */
83
+ export declare function plan(text: string, beforeAnswer: unknown, keptAnswer: unknown | null, options?: ApplyOptions): Planned;
84
+ /**
85
+ * Takes a compiled schema out of the database — refusing, by name, while anything outside it still reads its views:
86
+ * nothing of the app's may hang on a compiled schema (`access.*` is what it is told to read), and what does would
87
+ * go with it unsaid.
88
+ */
89
+ export declare function dropCompiled(s: string): string[];
90
+ /** Takes away what `access.*` answers through, where no schema is in force any more; the relationships and their history stay. */
91
+ export declare function unpoint(): string[];
92
+ /** Something that runs one statement and answers its rows. */
93
+ export type Run = (sql: string) => PromiseLike<Record<string, unknown>[]>;
94
+ /**
95
+ * Applies a schema through a connection: `transaction` runs its function inside one transaction and hands it what
96
+ * runs a statement there. Answers what was planned (and run).
97
+ */
98
+ export declare function apply(transaction: <T>(fn: (run: Run) => Promise<T>) => PromiseLike<T>, text: string, options?: ApplyOptions): Promise<Planned>;
@@ -0,0 +1,49 @@
1
+ /** The schema Palbase keeps access in. A database that has one of that name already, not Palbase's, is refused. */
2
+ export declare const ACCESS = "access";
3
+ /** Written on the schema: how a database's `access` is known to be Palbase's. */
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 = "2";
7
+ /**
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
+ * table that lacks one, or has one off (or on for replicas alone), has not been watched. Each is a row's own, so
10
+ * they act in the order the statement changed the rows; and Postgres fires a table's triggers in the order of their
11
+ * names, so these begin with a mark that comes before any letter or digit: a trigger of the table's own that
12
+ * changes another row's key acts after access has followed this one.
13
+ */
14
+ export declare const TRIGGERS: readonly ['!access_fresh', '!access_forget', '!access_move', '!access_empty'];
15
+ /** The last of them in the order triggers of one event fire (their names', byte by byte). */
16
+ export declare const LAST_TRIGGER: string;
17
+ /**
18
+ * A trigger of pg_trigger (by its alias) that fires after a change of rows (not before it, not instead of it) and is
19
+ * named to fire before the last of access': it would see a row whose relationships have not followed it yet.
20
+ */
21
+ export declare const EARLY_TRIGGER: (g: string) => string;
22
+ export interface Roles {
23
+ /** The role a signed-in request takes: it asks for itself alone. */
24
+ authenticated: string;
25
+ /** The role the app's own work takes: it asks for anyone, and gives and takes relationships. */
26
+ service: string;
27
+ }
28
+ export declare const DEFAULT_ROLES: Roles;
29
+ /** An id as an integer, or null when its text is not one: at most 18 digits, so none overflows. */
30
+ export declare const INT_TEXT = "^-?[0-9]{1,18}$";
31
+ /** A uuid's hyphenated form, either case. */
32
+ export declare const UUID_TEXT = "^[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}$";
33
+ /** The longest id kept: a subject's, or an object's of a type without a table. */
34
+ export declare const MAX_ID = 256;
35
+ export declare const REFUSED: {
36
+ /** No such type, relation or permission. */
37
+ readonly unknown: 'PA001';
38
+ /** The object named has no row. */
39
+ readonly noObject: 'PA002';
40
+ /** A subject's or an object's id that is no id. */
41
+ readonly badId: 'PA003';
42
+ /** More than the engine walks in one question. */
43
+ readonly tooMany: 'PA004';
44
+ /** The relation does not take this kind of subject. */
45
+ readonly notTaken: 'PA005';
46
+ /** The role asks for itself alone: it cannot name another subject. */
47
+ readonly notAllowed: 'PA006';
48
+ };
49
+ export declare function baseStatements(roles?: Roles): string[];
@@ -0,0 +1,53 @@
1
+ /** How a column's values compare (world.ts' families, and an enum, which a `where` compares as its label). */
2
+ export type ColumnFamily = 'text' | 'uuid' | 'int' | 'bool' | 'numeric' | 'enum';
3
+ export interface ColumnInfo {
4
+ /** The type's name as pg_type has it (int8, uuid, text, an enum's own name). */
5
+ type: string;
6
+ /** null: a type no schema can read (a timestamp, json, an array). */
7
+ family: ColumnFamily | null;
8
+ }
9
+ export interface TableInfo {
10
+ schema: string;
11
+ name: string;
12
+ /** pg_class.relkind: 'r' a table, 'p' a partitioned one; anything else is refused. */
13
+ kind: string;
14
+ /** The primary key's columns, in order; empty when it has none. */
15
+ primaryKey: string[];
16
+ /**
17
+ * The columns that each identify a row by themselves, at every moment: NOT NULL, and unique alone (the primary key
18
+ * of one column, a unique constraint or index of that column and no other) by a check that is not deferrable —
19
+ * under a deferred one two rows share a key until the transaction ends, and what follows a row's key (its
20
+ * relationships, taken with it or cleared for a new one) would act on the other row's.
21
+ */
22
+ identifying: string[];
23
+ columns: Map<string, ColumnInfo>;
24
+ /** FORCE ROW LEVEL SECURITY: the table's owner is held to its policies too. */
25
+ forcesRowSecurity: boolean;
26
+ /** Other tables inherit from it: their rows show through it, and its policies do not cover them when asked directly. */
27
+ hasChildren: boolean;
28
+ /** It is a partition, or inherits from another table: its rows are read through that one too, past its own policies. */
29
+ hasParent: boolean;
30
+ /** How many indexes it has: the planner reads every one each time a lookup reads the table (MAX_TABLE_INDEXES). */
31
+ indexes: number;
32
+ }
33
+ export interface Catalog {
34
+ table(schema: string, name: string): TableInfo | undefined;
35
+ }
36
+ /** The statement that reads the catalog for these tables: one row, one column, a JSON array (catalogFrom reads it). */
37
+ export declare function catalogQuery(tables: {
38
+ schema: string;
39
+ name: string;
40
+ }[]): string;
41
+ /** The catalog from catalogQuery's answer: the JSON itself, or its text. */
42
+ export declare function catalogFrom(answer: unknown): Catalog;
43
+ /** A catalog from tables described by hand: what a test, or a caller that already knows its tables, gives. */
44
+ export declare function catalogOf(tables: {
45
+ schema?: string;
46
+ name: string;
47
+ primaryKey: string[];
48
+ identifying?: string[];
49
+ indexes?: number;
50
+ columns: Record<string, string>;
51
+ forcesRowSecurity?: boolean;
52
+ enums?: string[];
53
+ }[]): Catalog;
@@ -0,0 +1,120 @@
1
+ import { type Roles } from './base.js';
2
+ import type { Catalog } from './catalog.js';
3
+ import { type Model } from './model.js';
4
+ import type { RowCommand } from './text.js';
5
+ /** The most candidates "who holds this" walks before it refuses: a question past it is asked another way. */
6
+ export declare const MAX_SUBJECTS = 10000;
7
+ /** The most rows the candidates are gathered from, each relation's and each arrow's together, before that. */
8
+ export declare const MAX_CANDIDATE_ROWS = 100000;
9
+ /**
10
+ * The most objects one "who holds this" walks through kept relationships, at every level together: an object related
11
+ * to a great many others that nobody holds anything on gives no candidates, but each is still walked (200,000 took
12
+ * 814 ms to answer nothing).
13
+ */
14
+ export declare const MAX_WALKED = 10000;
15
+ /**
16
+ * The most subjects × related objects one "who holds this" asks over: each subject is checked in turn, and a check
17
+ * reads the object's related objects again (5,000 subjects through 5,000 related sessions took 42 s).
18
+ */
19
+ export declare const MAX_SUBJECT_WORK = 1000000;
20
+ /**
21
+ * What the database may spend planning one name, measured when a schema is put in — and each time it is put in
22
+ * again, whatever changed around it: the indexes of a table and what they carry (a partial index's predicate, an
23
+ * expression), its statistics, its width, the indexes of access.relationships. What the schema alone decides is
24
+ * bounded by MAX_PLANNED; this is the database's side of it.
25
+ */
26
+ export declare const MAX_PLANNING_KB: number;
27
+ export declare const MAX_PLANNING_MS = 100;
28
+ export interface CompileOptions {
29
+ roles?: Partial<Roles>;
30
+ /** false: the schema's `rows` rules make no policy (whoever compiles writes the tables' policies itself). */
31
+ rows?: boolean;
32
+ /** The names whose predicate (Compiled.predicates) the caller puts in a row policy of its own: what they read is opened to a request's role. */
33
+ policies?: {
34
+ type: string;
35
+ name: string;
36
+ }[];
37
+ /** The views `access` shows names as today, with the type of their `id`: one whose type changes is dropped and made again. */
38
+ aliases?: {
39
+ name: string;
40
+ type: string;
41
+ }[];
42
+ /**
43
+ * The row policies the caller makes of its own on a type's table (an app's, in palgres), each with the names its
44
+ * USING and its WITH CHECK read, once for each time they read one (null: the clause is not there). One statement
45
+ * plans a name once for each place the policies that apply to it read it (Compiled.recheck); the schema's own
46
+ * `rows` rules are counted without it.
47
+ */
48
+ guards?: Guard[];
49
+ }
50
+ export interface Guard {
51
+ type: string;
52
+ command: 'all' | RowCommand;
53
+ using: string[] | null;
54
+ check: string[] | null;
55
+ }
56
+ export interface CompiledTable {
57
+ type: string;
58
+ schema: string;
59
+ name: string;
60
+ key: string;
61
+ }
62
+ export interface Compiled {
63
+ /** Twelve hexadecimal digits of the model, its tables' shape, the engine and the roles. */
64
+ digest: string;
65
+ /** The schema the compiled objects are in: access_<digest>. */
66
+ schema: string;
67
+ /** Builds that schema. Can be run again: what is there is replaced by the same, what is missing is made. */
68
+ build: string[];
69
+ /** Makes it the one `access.*` answers from, with the tables' triggers and policies: point, watch, rows, open and record, in that order. Can be run again. */
70
+ activate: string[];
71
+ /** The triggers on each table of a type: a row deleted takes its relationships with it. */
72
+ watch: string[];
73
+ /** Who may read the compiled views. */
74
+ open: string[];
75
+ /** The row policies the schema's `rows` rules make. */
76
+ rows: string[];
77
+ /** What `access.*` answers from: its functions and the views it shows the names as. */
78
+ point: string[];
79
+ /** Says in access' own table that this schema is the one in force. */
80
+ record: string[];
81
+ /**
82
+ * What is checked again each time the schema is put in, changed or not — run where the compiled schema is there,
83
+ * in the transaction that puts it in: no trigger of a type's table's own fires before access' (they may come after
84
+ * the schema), and what the database spends planning each name (MAX_PLANNING_KB, MAX_PLANNING_MS; smallest first,
85
+ * and one the ones before it show would be far past is refused unplanned) — and what one statement on a type's
86
+ * table spends, planning a name once for each place its policies read it: an UPDATE reads the rows its SELECT
87
+ * policies show, checks them by its USING, and the new row by its WITH CHECK.
88
+ */
89
+ recheck: string[];
90
+ tables: CompiledTable[];
91
+ /** Every (type, name) a subject can hold, the view `access` shows it as, and the type of its `id` (as pg_type names it). */
92
+ names: {
93
+ type: string;
94
+ name: string;
95
+ view: string;
96
+ idType: string;
97
+ }[];
98
+ /** The policies the schema's `rows` rules make, by table. */
99
+ policies: {
100
+ schema: string;
101
+ table: string;
102
+ name: string;
103
+ command: RowCommand;
104
+ }[];
105
+ /**
106
+ * For each type with a table and each name a subject can hold on it: "the asker holds it on this row", written
107
+ * over the table's own columns (qualified by the table's name) — what a row policy of that table says.
108
+ */
109
+ predicates: {
110
+ type: string;
111
+ name: string;
112
+ sql: string;
113
+ }[];
114
+ }
115
+ export declare function compile(model: Model, catalog: Catalog, text: string, options?: CompileOptions): Compiled;
116
+ /** The columns of each table a model reads: what must not be dropped under it, and what an index helps. */
117
+ export declare function readColumns(model: Model): {
118
+ type: string;
119
+ column: string;
120
+ }[];
@@ -0,0 +1,7 @@
1
+ export type AccessErrorCode = 'syntax' | 'invalid_name' | 'duplicate' | 'unknown_name' | 'unknown_type' | 'not_a_holder' | 'not_an_object_relation' | 'needs_table' | 'cycle' | 'too_deep' | 'too_large' | 'not_supported' | 'unknown_table' | 'unknown_column' | 'key_not_supported' | 'type_mismatch' | 'forced_row_security' | 'not_palbase_access' | 'relationships_in_the_way';
2
+ export declare class AccessError extends Error {
3
+ readonly code: AccessErrorCode;
4
+ /** The line of the schema's text it is about, from 1; 0 when it is about no one line. */
5
+ readonly line: number;
6
+ constructor(code: AccessErrorCode, message: string, line?: number);
7
+ }
@@ -0,0 +1,10 @@
1
+ export { AccessError, type AccessErrorCode } from './errors.js';
2
+ export { parse, type Condition, type Expr, type Literal, type RowCommand, type SchemaAst } from './text.js';
3
+ export { validate, mangle, heldByUsers, objectTargets, MAX_DEPTH, USER, type Model, type Relation, type TypeModel } from './model.js';
4
+ export { catalogFrom, catalogOf, catalogQuery, type Catalog, type ColumnFamily, type TableInfo } from './catalog.js';
5
+ export { ACCESS, baseStatements, DEFAULT_ROLES, ENGINE, MARK, MAX_ID, REFUSED, TRIGGERS, type Roles } from './base.js';
6
+ export { compile, readColumns, MAX_SUBJECTS, type Compiled, type CompiledTable, type CompileOptions, type Guard } from './compile.js';
7
+ export { apply, beforeQuery, dropCompiled, keptQuery, plan, unpoint, type ApplyOptions, type Before, type Kept, type Planned, type Run } from './apply.js';
8
+ export { reference, type Reference } from './reference.js';
9
+ export { canonicalId, idOf, type Family, type Relationship, type TableShape, type Value, type World } from './world.js';
10
+ export { runValidation, schemaPathOf, ValidationFileError, type ValidationFailure, type ValidationResult } from './validation.js';
@@ -0,0 +1,87 @@
1
+ import type { ColumnRelationAst, Condition, PermissionAst, RelationAst, RowCommand, SchemaAst, StoredRelationAst } from './text.js';
2
+ export declare const USER = "user";
3
+ /** How long a chain of permissions derived from one another may be. A schema past it is refused when declared. */
4
+ export declare const MAX_DEPTH = 16;
5
+ export declare const MAX_TYPES = 200;
6
+ export declare const MAX_NAMES = 100;
7
+ export declare const MAX_EXPR_NODES = 200;
8
+ /**
9
+ * How many relations a permission may come to once everything it is derived from is written out — each permission
10
+ * it names by its own expression, each arrow by what it leads to. The database plans a query of that size for every
11
+ * statement the permission guards (about a tenth of a millisecond a term, measured), and one that grows by
12
+ * multiplying — the same permissions named again and again through several paths — reaches tens of thousands
13
+ * within a few levels: a schema past the limit is refused when declared, not found out in production.
14
+ */
15
+ export declare const MAX_EXPANSION = 200;
16
+ /** How many comparisons one `where` may hold: it is written out wherever its relation is read. */
17
+ export declare const MAX_WHERE_TERMS = 50;
18
+ /**
19
+ * How many terms the whole schema may come to once every name of it is written out as the database is given it —
20
+ * each permission with what it names of its own type in full, each relation read from a column with its condition.
21
+ * The factors above are bounded one by one; their product is bounded here: past it, a schema of a few kilobytes
22
+ * would compile to tens of megabytes of SQL (and the app compiles its schema each time it starts).
23
+ */
24
+ export declare const MAX_WRITTEN = 25000;
25
+ /**
26
+ * How many lookups the database may plan for one name. A name read through another type's (an arrow) is planned
27
+ * with that name's whole definition inside it, more than once: an EXISTS Postgres cannot turn into a join is planned
28
+ * both hashed and not — twice over through a relation read from a column, four times through a kept one (its arrow
29
+ * reads a view of the relationships with the other type's view inside). Measured on Postgres 18 (11.11): 140 KB of
30
+ * the planner's memory and 0.055 ms a lookup, the same within a few percent from one schema to the next. A
31
+ * company → product → session → record chain read from columns is 133 lookups (18.8 MB, 7.5 ms); a random schema
32
+ * five levels deep through kept relations came to 4,300 (546 MB, 239 ms) for one question. At most this many: about
33
+ * 42 MB and 17 ms, on every statement a policy guards.
34
+ */
35
+ export declare const MAX_PLANNED = 300;
36
+ /**
37
+ * How many indexes a type's table may have. The planner reads every index of a table each time a lookup reads it,
38
+ * and the time grows faster than the count: the company → product → session → record chain above planned in 5.3 ms
39
+ * with each table's key alone, 9.7 ms with 150 indexes on each table, 46 ms with 300 and 169 ms with 600 (a quarter
40
+ * on two columns, the rest partial on the column the chain reads; Postgres 18, 11.11). Up to this many, a name within
41
+ * MAX_PLANNED stays within about two and a half times what it costs on bare tables, however wide they are: the same
42
+ * chain on tables of 1,500 columns (the most Postgres holds is 1,600) with 150 indexes each, 11.8 ms and 23.9 MB
43
+ * against 5.2 ms and 17.2 MB.
44
+ */
45
+ export declare const MAX_TABLE_INDEXES = 150;
46
+ export interface TableRef {
47
+ schema: string;
48
+ name: string;
49
+ /** null until the catalog says which column is the key. */
50
+ key: string | null;
51
+ }
52
+ export type StoredRelation = StoredRelationAst;
53
+ export type ColumnRelation = ColumnRelationAst;
54
+ export type Relation = RelationAst;
55
+ export type Permission = PermissionAst;
56
+ export interface RowsRule {
57
+ command: RowCommand;
58
+ name: string;
59
+ }
60
+ export interface TypeModel {
61
+ name: string;
62
+ table: TableRef | null;
63
+ relations: Map<string, Relation>;
64
+ permissions: Map<string, Permission>;
65
+ rows: RowsRule[];
66
+ }
67
+ export interface Model {
68
+ /** In the order the schema declares them. */
69
+ types: Map<string, TypeModel>;
70
+ /** Every (type, name), each after everything its meaning reads: the order to build them in. */
71
+ order: {
72
+ type: string;
73
+ name: string;
74
+ }[];
75
+ /** How many lookups the database plans for a (type, name) (MAX_PLANNED). */
76
+ planned(type: string, name: string): number;
77
+ }
78
+ /** A name as an SQL identifier's part: the one dot a name may carry becomes two underscores, which no name has. */
79
+ export declare const mangle: (name: string) => string;
80
+ /** Whether a relation can be held by a subject (rather than only followed by an arrow). */
81
+ export declare const heldByUsers: (r: Relation) => boolean;
82
+ /** The types a relation leads to. */
83
+ export declare const objectTargets: (r: Relation) => string[];
84
+ /** The columns of the type's table a condition reads. */
85
+ export declare function columnsOf(c: Condition | null): string[];
86
+ /** Checks a schema read from text and answers the model. Throws AccessError naming what does not hold together. */
87
+ export declare function validate(ast: SchemaAst): Model;
@@ -0,0 +1,12 @@
1
+ import type { Model } from './model.js';
2
+ import type { World } from './world.js';
3
+ export interface Reference {
4
+ /** holds(subject, type, id, name). */
5
+ check(subject: string, type: string, id: string, name: string): boolean;
6
+ /** The ids (as the key's type writes them — canonical) of the objects of `type` the subject holds `name` on, sorted. */
7
+ objects(subject: string, type: string, name: string): string[];
8
+ /** The subjects that hold `name` on (type, id), sorted. */
9
+ subjects(type: string, id: string, name: string): string[];
10
+ }
11
+ /** Answers a schema's three questions from the facts of one world. */
12
+ export declare function reference(model: Model, world: World): Reference;