palgres 0.56.0 → 0.57.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/chunks/BNQMEBLI.js +399 -0
- package/dist/chunks/{LQHZIV3S.js → DICUMSL4.js} +2 -2
- package/dist/chunks/FZHMSYP2.js +5 -0
- package/dist/dsl.js +2 -2
- package/dist/index.js +68 -68
- package/dist/testing.js +2 -2
- package/package.json +1 -1
- package/types/access/src/apply.d.ts +7 -0
- package/types/access/src/base.d.ts +25 -1
- package/types/access/src/compile.d.ts +11 -1
- package/types/access/src/errors.d.ts +1 -1
- package/types/access/src/index.d.ts +3 -3
- package/types/access/src/model.d.ts +20 -1
- package/types/access/src/reference.d.ts +7 -3
- package/types/access/src/text.d.ts +14 -2
- package/types/access/src/world.d.ts +8 -1
- package/types/palgres/src/access.d.ts +10 -0
- package/types/palgres/src/query/access.d.ts +64 -15
- package/types/palgres/src/query/index.d.ts +1 -1
- package/dist/chunks/JPYKRUNF.js +0 -5
- package/dist/chunks/YTA5WUZJ.js +0 -309
package/dist/testing.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
/*! palgres 0.
|
|
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/JPYKRUNF.js";import{o as we,r as ye,y as K,z as Q}from"./chunks/YTA5WUZJ.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};
|
|
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};
|
package/package.json
CHANGED
|
@@ -42,6 +42,8 @@ export interface Before {
|
|
|
42
42
|
schema: string;
|
|
43
43
|
table: string;
|
|
44
44
|
}[];
|
|
45
|
+
/** The database's roles, by name (its own, not the server's built-in ones): whether the visitor's is among them. */
|
|
46
|
+
roles?: string[];
|
|
45
47
|
catalog: unknown;
|
|
46
48
|
}
|
|
47
49
|
/** What relationships are kept, by (type, relation, kind of subject), and which compiled schema is active. */
|
|
@@ -49,6 +51,11 @@ export interface Kept {
|
|
|
49
51
|
active: string | null;
|
|
50
52
|
/** The engine that compiled the schema in force (base.ts ENGINE); absent when none is, or read by an older reader. */
|
|
51
53
|
engine?: string | null;
|
|
54
|
+
/**
|
|
55
|
+
* The relationships that hold, counted by what a schema would call them: `subject_type` is the kind of subject as
|
|
56
|
+
* a schema writes it (`user`, `user:*`, `public`, a type). One whose time has passed is not among them: nothing
|
|
57
|
+
* reads it, and it is in no schema's way.
|
|
58
|
+
*/
|
|
52
59
|
relationships: {
|
|
53
60
|
object_type: string;
|
|
54
61
|
relation: string;
|
|
@@ -3,7 +3,7 @@ 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
5
|
/** The engine's generation: a database compiled by another is compiled again. */
|
|
6
|
-
export declare const ENGINE = "
|
|
6
|
+
export declare const ENGINE = "3";
|
|
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
|
|
@@ -24,8 +24,30 @@ export interface Roles {
|
|
|
24
24
|
authenticated: string;
|
|
25
25
|
/** The role the app's own work takes: it asks for anyone, and gives and takes relationships. */
|
|
26
26
|
service: string;
|
|
27
|
+
/**
|
|
28
|
+
* The role a request takes when nobody has signed in: it holds what is the public's, and nothing else. A database
|
|
29
|
+
* need not have it — a schema that opens nothing to the public asks nothing of it.
|
|
30
|
+
*/
|
|
31
|
+
visitor: string;
|
|
27
32
|
}
|
|
28
33
|
export declare const DEFAULT_ROLES: Roles;
|
|
34
|
+
/** The id a relationship kept for every signed-in user ('user', '*'), or for the public ('public', '*'), is written under. */
|
|
35
|
+
export declare const ANY_ID = "*";
|
|
36
|
+
/** A relationship that counts: it has no end, or its end is still to come (the statement's own moment). */
|
|
37
|
+
export declare const LIVE: (r: string) => string;
|
|
38
|
+
/** LIVE, for a statement that may meet relationships an earlier engine made: no end is kept there, and every row holds. */
|
|
39
|
+
export declare const LIVE_OF_ANY_ENGINE: (r: string) => string;
|
|
40
|
+
/**
|
|
41
|
+
* The kind of subject a kept relationship has, as a schema writes it: `user`, `user:*` (every signed-in user — kept
|
|
42
|
+
* under the id nobody has), `public`, or a type. What a schema keeps is compared with what the database holds by this.
|
|
43
|
+
*/
|
|
44
|
+
export declare const KIND: (r: string) => string;
|
|
45
|
+
/**
|
|
46
|
+
* Until engine 3 "*" was an id like any other, and a relationship could be given to a user called that. Read by
|
|
47
|
+
* this engine it would be every signed-in user's — an object opened by a row nobody meant to open it with. The
|
|
48
|
+
* schema is not put in over such a row: it is taken first (the earlier engine's own revoke takes it).
|
|
49
|
+
*/
|
|
50
|
+
export declare function starGuard(): string;
|
|
29
51
|
/** An id as an integer, or null when its text is not one: at most 18 digits, so none overflows. */
|
|
30
52
|
export declare const INT_TEXT = "^-?[0-9]{1,18}$";
|
|
31
53
|
/** A uuid's hyphenated form, either case. */
|
|
@@ -45,5 +67,7 @@ export declare const REFUSED: {
|
|
|
45
67
|
readonly notTaken: 'PA005';
|
|
46
68
|
/** The role asks for itself alone: it cannot name another subject. */
|
|
47
69
|
readonly notAllowed: 'PA006';
|
|
70
|
+
/** A relationship's end that is not still to come. */
|
|
71
|
+
readonly badTime: 'PA007';
|
|
48
72
|
};
|
|
49
73
|
export declare function baseStatements(roles?: Roles): string[];
|
|
@@ -27,6 +27,11 @@ export declare const MAX_PLANNING_KB: number;
|
|
|
27
27
|
export declare const MAX_PLANNING_MS = 100;
|
|
28
28
|
export interface CompileOptions {
|
|
29
29
|
roles?: Partial<Roles>;
|
|
30
|
+
/**
|
|
31
|
+
* Whether the database has the visitor's role (Roles.visitor). A schema that opens a name to the public is asked
|
|
32
|
+
* by that role, and is refused where there is none: it would say "the public" and open nothing.
|
|
33
|
+
*/
|
|
34
|
+
visitor?: boolean;
|
|
30
35
|
/** false: the schema's `rows` rules make no policy (whoever compiles writes the tables' policies itself). */
|
|
31
36
|
rows?: boolean;
|
|
32
37
|
/** 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. */
|
|
@@ -88,12 +93,17 @@ export interface Compiled {
|
|
|
88
93
|
*/
|
|
89
94
|
recheck: string[];
|
|
90
95
|
tables: CompiledTable[];
|
|
91
|
-
/**
|
|
96
|
+
/**
|
|
97
|
+
* Every (type, name) a subject can hold, the view `access` shows it as, the type of its `id` (as pg_type names
|
|
98
|
+
* it), and whether a visitor can hold it (it is read through a relation the public holds): those alone are the
|
|
99
|
+
* visitor's role's to ask.
|
|
100
|
+
*/
|
|
92
101
|
names: {
|
|
93
102
|
type: string;
|
|
94
103
|
name: string;
|
|
95
104
|
view: string;
|
|
96
105
|
idType: string;
|
|
106
|
+
open: boolean;
|
|
97
107
|
}[];
|
|
98
108
|
/** The policies the schema's `rows` rules make, by table. */
|
|
99
109
|
policies: {
|
|
@@ -1,4 +1,4 @@
|
|
|
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';
|
|
1
|
+
export type AccessErrorCode = 'syntax' | 'invalid_name' | 'duplicate' | 'unknown_name' | 'unknown_type' | 'not_a_holder' | 'not_an_object_relation' | 'needs_table' | 'needs_role' | '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
2
|
export declare class AccessError extends Error {
|
|
3
3
|
readonly code: AccessErrorCode;
|
|
4
4
|
/** The line of the schema's text it is about, from 1; 0 when it is about no one line. */
|
|
@@ -1,10 +1,10 @@
|
|
|
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, objectTargets, MAX_DEPTH, USER, type Model, type Relation, type TypeModel } from './model.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';
|
|
4
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';
|
|
5
|
+
export { ACCESS, baseStatements, DEFAULT_ROLES, ENGINE, KIND, LIVE_OF_ANY_ENGINE, MARK, MAX_ID, 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
|
-
export { reference, type Reference } from './reference.js';
|
|
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';
|
|
@@ -1,5 +1,9 @@
|
|
|
1
|
-
import
|
|
1
|
+
import { EVERY_USER, PUBLIC } from './text.js';
|
|
2
|
+
import type { ColumnRelationAst, Condition, PermissionAst, RelationAst, RowCommand, RowRelationAst, SchemaAst, StoredRelationAst } from './text.js';
|
|
3
|
+
export { EVERY_USER, PUBLIC };
|
|
2
4
|
export declare const USER = "user";
|
|
5
|
+
/** The id a relationship kept for every signed-in user, or for the public, is written under. No subject is called this. */
|
|
6
|
+
export declare const ANY = "*";
|
|
3
7
|
/** How long a chain of permissions derived from one another may be. A schema past it is refused when declared. */
|
|
4
8
|
export declare const MAX_DEPTH = 16;
|
|
5
9
|
export declare const MAX_TYPES = 200;
|
|
@@ -51,6 +55,7 @@ export interface TableRef {
|
|
|
51
55
|
}
|
|
52
56
|
export type StoredRelation = StoredRelationAst;
|
|
53
57
|
export type ColumnRelation = ColumnRelationAst;
|
|
58
|
+
export type RowRelation = RowRelationAst;
|
|
54
59
|
export type Relation = RelationAst;
|
|
55
60
|
export type Permission = PermissionAst;
|
|
56
61
|
export interface RowsRule {
|
|
@@ -74,6 +79,8 @@ export interface Model {
|
|
|
74
79
|
}[];
|
|
75
80
|
/** How many lookups the database plans for a (type, name) (MAX_PLANNED). */
|
|
76
81
|
planned(type: string, name: string): number;
|
|
82
|
+
/** Whether somebody who has not signed in can hold a (type, name): it is read through a relation the public holds. */
|
|
83
|
+
open(type: string, name: string): boolean;
|
|
77
84
|
}
|
|
78
85
|
/** A name as an SQL identifier's part: the one dot a name may carry becomes two underscores, which no name has. */
|
|
79
86
|
export declare const mangle: (name: string) => string;
|
|
@@ -81,6 +88,18 @@ export declare const mangle: (name: string) => string;
|
|
|
81
88
|
export declare const heldByUsers: (r: Relation) => boolean;
|
|
82
89
|
/** The types a relation leads to. */
|
|
83
90
|
export declare const objectTargets: (r: Relation) => string[];
|
|
91
|
+
/** Whether a stored relation is given to one subject by id (`user`). */
|
|
92
|
+
export declare const takesUsers: (r: Relation) => boolean;
|
|
93
|
+
/** The open subjects a stored relation takes: every signed-in user, the public. */
|
|
94
|
+
/**
|
|
95
|
+
* How many lookups a relation is, held directly: one — and, for a kept relation, one for each way it can be held:
|
|
96
|
+
* by a user's own id, by every signed-in user, by the public (each is a lookup of its own in what is compiled).
|
|
97
|
+
* One read from a column or from the row counts its condition's terms with it.
|
|
98
|
+
*/
|
|
99
|
+
export declare const lookupsOf: (r: Relation | undefined) => number;
|
|
100
|
+
export declare const takesOpen: (r: Relation) => ("public" | "user:*")[];
|
|
101
|
+
/** Whether a relation holds for somebody who has not signed in: kept for the public, or read from the row for it. */
|
|
102
|
+
export declare const heldByPublic: (r: Relation) => boolean;
|
|
84
103
|
/** The columns of the type's table a condition reads. */
|
|
85
104
|
export declare function columnsOf(c: Condition | null): string[];
|
|
86
105
|
/** Checks a schema read from text and answers the model. Throws AccessError naming what does not hold together. */
|
|
@@ -1,12 +1,16 @@
|
|
|
1
1
|
import type { Model } from './model.js';
|
|
2
2
|
import type { World } from './world.js';
|
|
3
|
+
/** Who asks: a subject's id, '*' (somebody signed in, nothing else known of them), or null (a visitor). */
|
|
4
|
+
export type Asker = string | null;
|
|
3
5
|
export interface Reference {
|
|
4
6
|
/** holds(subject, type, id, name). */
|
|
5
|
-
check(subject:
|
|
7
|
+
check(subject: Asker, type: string, id: string, name: string): boolean;
|
|
6
8
|
/** The ids (as the key's type writes them — canonical) of the objects of `type` the subject holds `name` on, sorted. */
|
|
7
|
-
objects(subject:
|
|
8
|
-
/** The subjects that hold `name` on (type, id), sorted. */
|
|
9
|
+
objects(subject: Asker, type: string, name: string): string[];
|
|
10
|
+
/** The subjects that hold `name` on (type, id), sorted: each one named by a relationship — never '*'. */
|
|
9
11
|
subjects(type: string, id: string, name: string): string[];
|
|
12
|
+
/** How wide `name` is open on (type, id): to everyone, to every signed-in user, or to nobody but those it names. */
|
|
13
|
+
open(type: string, id: string, name: string): 'public' | 'users' | 'visitors' | null;
|
|
10
14
|
}
|
|
11
15
|
/** Answers a schema's three questions from the facts of one world. */
|
|
12
16
|
export declare function reference(model: Model, world: World): Reference;
|
|
@@ -45,11 +45,15 @@ export type Expr = {
|
|
|
45
45
|
base: Expr;
|
|
46
46
|
minus: Expr;
|
|
47
47
|
};
|
|
48
|
+
/** Every signed-in user, as a relation's subject: whoever asks holds it, as long as somebody is signed in. */
|
|
49
|
+
export declare const EVERY_USER = "user:*";
|
|
50
|
+
/** Everyone, signed in or not, as a relation's subject. */
|
|
51
|
+
export declare const PUBLIC = "public";
|
|
48
52
|
/** A relationship kept in Palbase's table: given and taken through the API. */
|
|
49
53
|
export interface StoredRelationAst {
|
|
50
54
|
kind: 'stored';
|
|
51
55
|
name: string;
|
|
52
|
-
/** 'user', or the names of types. */
|
|
56
|
+
/** 'user', 'user:*', 'public', or the names of types. */
|
|
53
57
|
subjects: string[];
|
|
54
58
|
line: number;
|
|
55
59
|
}
|
|
@@ -63,7 +67,15 @@ export interface ColumnRelationAst {
|
|
|
63
67
|
where: Condition | null;
|
|
64
68
|
line: number;
|
|
65
69
|
}
|
|
66
|
-
|
|
70
|
+
/** A relationship read from the row itself: every signed-in user, or the public, holds it where the condition is true. */
|
|
71
|
+
export interface RowRelationAst {
|
|
72
|
+
kind: 'row';
|
|
73
|
+
name: string;
|
|
74
|
+
subject: typeof EVERY_USER | typeof PUBLIC;
|
|
75
|
+
where: Condition;
|
|
76
|
+
line: number;
|
|
77
|
+
}
|
|
78
|
+
export type RelationAst = StoredRelationAst | ColumnRelationAst | RowRelationAst;
|
|
67
79
|
export interface PermissionAst {
|
|
68
80
|
name: string;
|
|
69
81
|
expr: Expr;
|
|
@@ -16,13 +16,18 @@ export interface TableShape {
|
|
|
16
16
|
}
|
|
17
17
|
/** A column's value. An integer is a number or a bigint; a uuid and a text are strings. */
|
|
18
18
|
export type Value = string | number | bigint | boolean | null;
|
|
19
|
-
/**
|
|
19
|
+
/**
|
|
20
|
+
* One stored relationship: `subjectType` is 'user' or a type's name, with the subject's or the object's id — or it
|
|
21
|
+
* names nobody in particular: ('user', '*') is every signed-in user, ('public', '*') is everyone.
|
|
22
|
+
*/
|
|
20
23
|
export interface Relationship {
|
|
21
24
|
objectType: string;
|
|
22
25
|
objectId: string;
|
|
23
26
|
relation: string;
|
|
24
27
|
subjectType: string;
|
|
25
28
|
subjectId: string;
|
|
29
|
+
/** The moment it stops counting, in milliseconds since the epoch; absent or null: it does not end. */
|
|
30
|
+
expiresAt?: number | null;
|
|
26
31
|
}
|
|
27
32
|
export interface World {
|
|
28
33
|
/** By type name, for each type that names a table. */
|
|
@@ -31,6 +36,8 @@ export interface World {
|
|
|
31
36
|
rows: Record<string, Value>[];
|
|
32
37
|
}>;
|
|
33
38
|
relationships: Relationship[];
|
|
39
|
+
/** The moment the questions are asked at (milliseconds since the epoch); absent: now. */
|
|
40
|
+
now?: number;
|
|
34
41
|
}
|
|
35
42
|
/**
|
|
36
43
|
* An id as its type writes it, or null when the text is no value of that type: an integer's digits without a sign's
|
|
@@ -37,6 +37,8 @@ export interface RecordedAccess {
|
|
|
37
37
|
export interface AccessRoles {
|
|
38
38
|
authenticated: string;
|
|
39
39
|
service: string;
|
|
40
|
+
/** The role a request takes when nobody has signed in (anon, when left out): what is the public's is its to ask. */
|
|
41
|
+
visitor?: string;
|
|
40
42
|
}
|
|
41
43
|
/**
|
|
42
44
|
* The model's access schema, compiled against the model's own tables; null when it has none. Throws AccessError when
|
|
@@ -49,6 +51,14 @@ export declare function compileAccess(schema: Schema, roles: AccessRoles, aliase
|
|
|
49
51
|
/** The digest a model's access schema compiles to: what the model carries, so that a compiler that writes it otherwise is another version. */
|
|
50
52
|
export declare function accessDigest(schema: Omit<Schema, 'access'>, text: string, roles: AccessRoles): string;
|
|
51
53
|
export declare function recordAccess(c: Compiled, text: string): RecordedAccess;
|
|
54
|
+
/**
|
|
55
|
+
* The names a policy reads that a visitor cannot hold on a row of the table (nothing can open them to the public):
|
|
56
|
+
* none, when the policy can be the visitor's role's too. Null when it cannot be said — the table is no type's.
|
|
57
|
+
*/
|
|
58
|
+
export declare function closedToVisitors(texts: (string | undefined)[], table: {
|
|
59
|
+
schema: string;
|
|
60
|
+
name: string;
|
|
61
|
+
}, compiled: Pick<Compiled, 'tables' | 'names'> | null): string[] | null;
|
|
52
62
|
/**
|
|
53
63
|
* A policy's text with each name it reads replaced by that name's predicate on the table's rows. Answers what is
|
|
54
64
|
* wrong instead when the table is no type's, or the type has no such name.
|
|
@@ -5,27 +5,44 @@ export interface AccessObject<K extends string = string> {
|
|
|
5
5
|
type: K;
|
|
6
6
|
id: AccessId;
|
|
7
7
|
}
|
|
8
|
-
/**
|
|
8
|
+
/** Every signed-in user, as who holds a relation: whoever asks holds it, as long as somebody is signed in. */
|
|
9
|
+
export type AccessEveryUser = {
|
|
10
|
+
everyUser: true;
|
|
11
|
+
};
|
|
12
|
+
/** Everyone, signed in or not, as who holds a relation. */
|
|
13
|
+
export type AccessPublic = {
|
|
14
|
+
public: true;
|
|
15
|
+
};
|
|
16
|
+
/**
|
|
17
|
+
* Who holds a relation: a user by id (a bare string is one), an object — `{ type: "team", id }` — or nobody in
|
|
18
|
+
* particular, where the relation takes them: `{ everyUser: true }` (every signed-in user), `{ public: true }`
|
|
19
|
+
* (everyone). Everyone is never said by an id: "*" is refused as one, so an id that comes from a request names one
|
|
20
|
+
* user or nobody.
|
|
21
|
+
*/
|
|
9
22
|
export type AccessSubject = string | {
|
|
10
23
|
user: string;
|
|
11
|
-
} | AccessObject;
|
|
24
|
+
} | AccessObject | AccessEveryUser | AccessPublic;
|
|
12
25
|
export interface AccessRelationship {
|
|
13
26
|
object: {
|
|
14
27
|
type: string;
|
|
15
28
|
id: string;
|
|
16
29
|
};
|
|
17
30
|
relation: string;
|
|
31
|
+
/** `{ type: "user", id: "*" }` is every signed-in user; `{ type: "public", id: "*" }` is everyone. */
|
|
18
32
|
subject: {
|
|
19
33
|
type: string;
|
|
20
34
|
id: string;
|
|
21
35
|
};
|
|
22
36
|
/** When it was given, ISO 8601. */
|
|
23
37
|
since: string;
|
|
38
|
+
/** The moment it ends, ISO 8601; null when it does not. */
|
|
39
|
+
until: string | null;
|
|
24
40
|
}
|
|
25
41
|
export interface AccessHistoryEntry {
|
|
26
|
-
/** ISO 8601. */
|
|
42
|
+
/** ISO 8601. An ending's is the moment the relationship ended. */
|
|
27
43
|
at: string;
|
|
28
|
-
|
|
44
|
+
/** 'expire': it was given until a moment, and that moment came. */
|
|
45
|
+
action: 'grant' | 'revoke' | 'expire';
|
|
29
46
|
object: {
|
|
30
47
|
type: string;
|
|
31
48
|
id: string;
|
|
@@ -37,6 +54,8 @@ export interface AccessHistoryEntry {
|
|
|
37
54
|
};
|
|
38
55
|
/** Who did it: what the app said (`by`), else the request's user, else the database login. */
|
|
39
56
|
by: string | null;
|
|
57
|
+
/** The end it was given with (a grant), or had (a revoke, an ending), ISO 8601; null when it had none. */
|
|
58
|
+
until: string | null;
|
|
40
59
|
}
|
|
41
60
|
export interface AccessFilter {
|
|
42
61
|
/** Of this object; without an id, of every object of the type. */
|
|
@@ -49,7 +68,9 @@ export interface AccessFilter {
|
|
|
49
68
|
/** At most this many (default 100, at most 1000). */
|
|
50
69
|
limit?: number;
|
|
51
70
|
}
|
|
52
|
-
|
|
71
|
+
/** How wide a name is open on an object (`openTo`). */
|
|
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';
|
|
53
74
|
/** What an access question or change was refused for. Thrown before anything is sent wherever the schema alone says so. */
|
|
54
75
|
export declare class AccessRefused extends Error {
|
|
55
76
|
readonly code: AccessRefusal;
|
|
@@ -73,7 +94,7 @@ export type AccessSubjectOf<A, K, R> = K extends keyof A ? A[K] extends {
|
|
|
73
94
|
relations: infer M;
|
|
74
95
|
} ? R extends keyof M ? M[R] extends infer S extends string ? (S extends 'user' ? string | {
|
|
75
96
|
user: string;
|
|
76
|
-
} : {
|
|
97
|
+
} : S extends 'user:*' ? AccessEveryUser : S extends 'public' ? AccessPublic : {
|
|
77
98
|
type: S;
|
|
78
99
|
id: AccessId;
|
|
79
100
|
}) : AccessSubject : AccessSubject : AccessSubject : AccessSubject;
|
|
@@ -84,7 +105,7 @@ export type AccessSubjectOf<A, K, R> = K extends keyof A ? A[K] extends {
|
|
|
84
105
|
* are the service role's: `Database.$asService().$access` — where those three are still about the caller.
|
|
85
106
|
*/
|
|
86
107
|
export interface AccessOps<A = unknown> {
|
|
87
|
-
/** Whether the caller holds `name` — a relation or a permission — on the object. Nobody is signed in:
|
|
108
|
+
/** Whether the caller holds `name` — a relation or a permission — on the object. Nobody is signed in: only what is the public's. */
|
|
88
109
|
can<K extends AccessTypeOf<A>>(name: AccessNameOf<A, K>, object: AccessObject<K>): Promise<boolean>;
|
|
89
110
|
/** The ids of the objects of `type` the caller holds `name` on. */
|
|
90
111
|
objects<K extends AccessTypeOf<A>>(name: AccessNameOf<A, K>, type: K): Promise<string[]>;
|
|
@@ -94,30 +115,52 @@ export interface AccessOps<A = unknown> {
|
|
|
94
115
|
check<K extends AccessTypeOf<A>>(subject: string, name: AccessNameOf<A, K>, object: AccessObject<K>): Promise<boolean>;
|
|
95
116
|
/** The ids of the objects of `type` that `subject` holds `name` on. The service role's. */
|
|
96
117
|
objectsOf<K extends AccessTypeOf<A>>(subject: string, name: AccessNameOf<A, K>, type: K): Promise<string[]>;
|
|
97
|
-
/**
|
|
118
|
+
/**
|
|
119
|
+
* The users who hold `name` on the object by something that names them, sorted — not everyone, when it is open
|
|
120
|
+
* (`openTo` says that). Refused past 10,000 related subjects: ask `check` then. The service role's.
|
|
121
|
+
*/
|
|
98
122
|
subjects<K extends AccessTypeOf<A>>(name: AccessNameOf<A, K>, object: AccessObject<K>): Promise<string[]>;
|
|
123
|
+
/**
|
|
124
|
+
* How wide `name` is open on the object: "public" — whoever asks holds it, signed in or not; "users" — whoever has
|
|
125
|
+
* signed in does (but those an exclusion takes away), and a visitor does not; "visitors" — whoever has not signed
|
|
126
|
+
* in does, and somebody signed in only where something names them; null — only who is named. The service role's.
|
|
127
|
+
*/
|
|
128
|
+
openTo<K extends AccessTypeOf<A>>(name: AccessNameOf<A, K>, object: AccessObject<K>): Promise<AccessOpen>;
|
|
99
129
|
/**
|
|
100
130
|
* Gives `subject` the relation on the object; false when they had it. The object must exist (a type with a table).
|
|
101
|
-
* `by` is who did it, kept in the history: the request's user when it is not said.
|
|
131
|
+
* `by` is who did it, kept in the history: the request's user when it is not said. `until` is the moment it ends
|
|
132
|
+
* by itself — still to come; given again while held, a relationship takes the end said now (none: it no longer
|
|
133
|
+
* ends). The service role's.
|
|
102
134
|
*/
|
|
103
135
|
grant<K extends AccessTypeOf<A>, R extends AccessRelationOf<A, K>>(object: AccessObject<K>, relation: R, subject: AccessSubjectOf<A, K, R>, options?: {
|
|
104
136
|
by?: string;
|
|
137
|
+
until?: Date | string;
|
|
105
138
|
}): Promise<boolean>;
|
|
106
139
|
/** Takes the relation back; false when they did not have it. In force from the next statement on. The service role's. */
|
|
107
140
|
revoke<K extends AccessTypeOf<A>, R extends AccessRelationOf<A, K>>(object: AccessObject<K>, relation: R, subject: AccessSubjectOf<A, K, R>, options?: {
|
|
108
141
|
by?: string;
|
|
109
142
|
}): Promise<boolean>;
|
|
110
|
-
/** The relationships kept
|
|
143
|
+
/** The relationships kept — those that have not ended — by object, relation and subject. The service role's. */
|
|
111
144
|
relationships(filter?: AccessFilter): Promise<AccessRelationship[]>;
|
|
112
145
|
/** What was given and taken, the latest first: who, to whom, when. The service role's. */
|
|
113
146
|
history(filter?: AccessFilter): Promise<AccessHistoryEntry[]>;
|
|
147
|
+
/**
|
|
148
|
+
* Removes relationships whose time has passed — `limit` at most (10,000), the longest ended first — and answers
|
|
149
|
+
* how many went. Nothing reads them meanwhile, so no answer changes: it gives their rows back, and each is a line
|
|
150
|
+
* of the history at the moment it ended. For a job of the app's own. The service role's.
|
|
151
|
+
*/
|
|
152
|
+
sweep(options?: {
|
|
153
|
+
limit?: number;
|
|
154
|
+
}): Promise<number>;
|
|
114
155
|
}
|
|
115
156
|
/** What a version's access schema lets the app say, read from its text once. */
|
|
116
157
|
export interface AccessNames {
|
|
117
158
|
/** The compiled schema's name in the database. */
|
|
118
159
|
schema: string;
|
|
160
|
+
/** By type: the names a subject can hold, those among them a visitor can (Model.open), and what each kept relation takes. */
|
|
119
161
|
types: Map<string, {
|
|
120
162
|
names: Set<string>;
|
|
163
|
+
open: Set<string>;
|
|
121
164
|
kept: Map<string, Set<string>>;
|
|
122
165
|
}>;
|
|
123
166
|
}
|
|
@@ -146,24 +189,30 @@ export interface AccessWhere {
|
|
|
146
189
|
export interface AccessVia {
|
|
147
190
|
/** Whom `can`, `objects` and `held` are about; undefined when nobody is signed in. */
|
|
148
191
|
caller(): string | undefined;
|
|
149
|
-
|
|
150
|
-
|
|
192
|
+
/** `subject` null: a visitor. */
|
|
193
|
+
check(subject: string | null, name: string, type: string, id: string): boolean;
|
|
194
|
+
objects(subject: string | null, name: string, type: string): string[];
|
|
151
195
|
subjects(name: string, type: string, id: string): string[];
|
|
196
|
+
open(name: string, type: string, id: string): AccessOpen;
|
|
197
|
+
/** How many relationships whose time had passed went, `limit` at most. */
|
|
198
|
+
sweep(limit: number): number;
|
|
199
|
+
/** `until`: the moment it ends, in milliseconds since the epoch (a grant's alone). */
|
|
152
200
|
change(fn: 'grant' | 'revoke', object: {
|
|
153
201
|
type: string;
|
|
154
202
|
id: string;
|
|
155
203
|
}, relation: string, subject: {
|
|
156
204
|
type: string;
|
|
157
205
|
id: string;
|
|
158
|
-
}, by: string | undefined): boolean;
|
|
206
|
+
}, by: string | undefined, until?: number): boolean;
|
|
159
207
|
relationships(where: AccessWhere, limit: number): AccessRelationship[];
|
|
160
208
|
history(where: AccessWhere, limit: number): AccessHistoryEntry[];
|
|
161
209
|
}
|
|
162
210
|
/**
|
|
163
211
|
* The access operations over what asks (`raw`: the transaction current when each is called), for the version whose
|
|
164
212
|
* access schema `names` are — undefined when the app declares none: every operation then says so. `as` is whose
|
|
165
|
-
* transaction it is: nobody (anon)
|
|
166
|
-
*
|
|
213
|
+
* transaction it is: nobody's (anon) is asked only the names the public can hold — the rest it holds on nothing,
|
|
214
|
+
* and its role is not the database's to ask them — and only the service role's names a subject or changes who holds
|
|
215
|
+
* what — said here, since the database's refusal would end the transaction.
|
|
167
216
|
*/
|
|
168
217
|
export declare function accessOps(raw: () => Asks, names: AccessNames | undefined, as: AccessAsker, unanswered?: string, via?: AccessVia): AccessOps;
|
|
169
218
|
export {};
|
|
@@ -89,7 +89,7 @@ export declare function createDatabase<T = Record<never, never>, S = Record<neve
|
|
|
89
89
|
export type { DatabaseAdmissionOptions } from './admission.js';
|
|
90
90
|
export { fieldAddress, type FieldCipher, type FieldsSource } from '../fields.js';
|
|
91
91
|
export { AccessRefused, accessNames, accessTypesBlock } from './access.js';
|
|
92
|
-
export type { AccessFilter, AccessHistoryEntry, AccessId, AccessNameOf, AccessNames, AccessObject, AccessOps, AccessRefusal, AccessRelationOf, AccessRelationship, AccessSubject, AccessSubjectOf, AccessTypeOf } from './access.js';
|
|
92
|
+
export type { AccessEveryUser, AccessFilter, AccessHistoryEntry, AccessId, AccessNameOf, AccessNames, AccessObject, AccessOpen, AccessPublic, AccessOps, AccessRefusal, AccessRelationOf, AccessRelationship, AccessSubject, AccessSubjectOf, AccessTypeOf } from './access.js';
|
|
93
93
|
export type { AtomicClient, DBClient, DBOps, FindManyOptions, RowLock, SearchOptions } from './client.js';
|
|
94
94
|
export type { Embed } from './search.js';
|
|
95
95
|
export type { DatabaseBudget, DatabaseDiagnostics, DatabaseDiagnosticsOptions, DatabaseQueryEvent } from './diagnostics.js';
|