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
@@ -0,0 +1,5 @@
1
+ /*! palgres 0.55.0 — Palbase SDK License (see LICENSE) */
2
+ import{H as re,o as me,p as te,q as xe,r as ke,t as j}from"./DLP3GKUJ.js";var Ze=Symbol.for("palbase.backend.httpError"),je=Symbol.for("palbase.backend.engineRaised"),A=Object.freeze({uniqueViolation:"23505",foreignKeyViolation:"23503",serializationFailure:"40001",deadlockDetected:"40P01",queryCancelled:"57014",lockNotAvailable:"55P03",inFailedTransaction:"25P02",insufficientPrivilege:"42501"}),O=class extends Error{[Ze]=!0;status;error;errorDescription;data;retryAfter;constructor(n,t,r,o,i){super(r),this.name="HttpError",this.status=n,this.error=t,this.errorDescription=r,o!==void 0&&(this.data=o),i!==void 0&&(this.retryAfter=i)}};function Se(e){return e[je]=!0,e}function An(e){return typeof e=="object"&&e!==null&&e[je]===!0}function P(e){let n=e.replace(/([a-z0-9])([A-Z])/g,"$1 $2");return n.charAt(0).toUpperCase()+n.slice(1).toLowerCase()}var N=class extends O{constructor(n,t){super(400,"bad_request",t??P("BadRequest"),n),this.name="BadRequest"}},Re=class extends O{constructor(n,t,r){super(404,t??"not_found",n??P("NotFound"),r),this.name="NotFound"}},S=class extends O{constructor(n,t,r){super(409,t??"conflict",n??P("Conflict"),r),this.name="Conflict"}},$e=class extends S{constraint;sqlstate=A.uniqueViolation;static is(n){return typeof n=="object"&&n!==null&&n.name==="UniqueViolation"&&typeof n.constraint=="string"}constructor(n,t,r,o){super(t??"Unique constraint violated",r??"unique_violation",o),this.name="UniqueViolation",this.constraint=n}};function On(e){if(typeof e!="object"||e===null||e.retryable!==!0)return!1;let n=e.sqlstate;return n===A.serializationFailure||n===A.deadlockDetected}var Te=class extends S{retryable=!0;sqlstate;static is(n){return typeof n=="object"&&n!==null&&n.name==="SerializationFailure"}constructor(n=A.serializationFailure,t,r){super(t??"the transaction could not be serialized with a concurrent one \u2014 run it again from the start (put the reads a decision rests on and its writes in $atomic, with { retry: n })","serialization_failure",r),this.name="SerializationFailure",this.sqlstate=n}},Ae=class extends S{retryable=!0;sqlstate;static is(n){return typeof n=="object"&&n!==null&&n.name==="DeadlockDetected"}constructor(n=A.deadlockDetected,t,r){super(t??"deadlock: two transactions waited on each other's locks and this one was cancelled \u2014 take locks in one order: Database.$lockRows(table, ids) when you have the ids, Database.$lockRowsWhere(table, filter) when you have a filter","deadlock_detected",r),this.name="DeadlockDetected",this.sqlstate=n}},Oe=class extends Error{sqlstate=A.inFailedTransaction;static is(n){return typeof n=="object"&&n!==null&&n.name==="TransactionAborted"}constructor(n,t){super(n,{cause:t}),this.name="TransactionAborted"}},Ee=class extends O{constructor(n,t){super(429,"too_many_requests",t??P("TooManyRequests"),n,n.retryAfter),this.name="TooManyRequests"}};function D(e){let n=e,t=r=>typeof r=="string"&&/^[0-9A-Z]{5}$/.test(r);if(t(n?.code))return n.code;if(t(n?.errno))return n.errno}var Qe=new Set(["57P03","53300","08001","08004","ERR_POSTGRES_CONNECTION_REFUSED","ERR_POSTGRES_CONNECTION_FAILED","ERR_POSTGRES_CONNECTION_TIMEOUT","ECONNREFUSED","CONNECT_TIMEOUT"]),en=new Set(["57P01","57P02","08000","08003","08006","08007","08P01","ERR_POSTGRES_CONNECTION_CLOSED","CONNECTION_CLOSED","CONNECTION_DESTROYED","ECONNRESET","ETIMEDOUT","EPIPE"]);function En(e){return e instanceof Error&&e.code===void 0&&e.message==="connection must be a PostgresSQLConnection"}function jn(e){let n=e;for(let t=0;t<4&&typeof n=="object"&&n!==null;t++){let r=D(n),o=n.code,i=s=>r!==void 0&&s.has(r)||typeof o=="string"&&s.has(o);if(i(en))return"lost";if(i(Qe))return"never";n=n.cause}}function Sn(e){let n=e;for(let t=0;t<4&&typeof n=="object"&&n!==null;t++){let r=n.sqlstate,o=D(n)??(typeof r=="string"?r:void 0);if(o!==void 0)return!o.startsWith("08")&&!/^57P0[123]$/.test(o);n=n.cause}return!1}function _n(e){let n=e,t=n?.constraint??n?.constraint_name;if(typeof t=="string"&&t.length>0)return t;let r=String(e?.message??"");return/violates unique constraint "([^"]+)"/.exec(r)?.[1]??""}var m=e=>`"${e.replace(/"/g,'""')}"`,Pn=(e,n)=>`${m(e)}.${m(n)}`,Dn=e=>`'${e.replace(/'/g,"''")}'`;function Cn(e){if(e.includes("\0"))throw new TypeError("a NUL character cannot be sent to Postgres");return`E'${e.replace(/\\/g,"\\\\").replace(/'/g,"''")}'`}var Mn=e=>e.map(m).join(", "),nn=new Set(["now","current_timestamp","current_date","current_time","localtimestamp","localtime","transaction_timestamp","statement_timestamp"]);function vn(e){return[...oe(e)].some(n=>n.call&&!nn.has(n.name.toLowerCase()))}function*oe(e){let n=0;for(;n<e.length;){let t=e[n];if(t==="'"){for(n++;n<e.length;)if(e[n]==="'"&&e[n+1]==="'")n+=2;else{if(e[n]==="'")break;n++}n++;continue}if(t==="$"){let r=/^\$[A-Za-z_]*\$/.exec(e.slice(n));if(r){let o=e.indexOf(r[0],n+r[0].length);n=o<0?e.length:o+r[0].length;continue}}if(t==='"'){let r=n+1,o="";for(;r<e.length;)if(e[r]==='"'&&e[r+1]==='"')o+='"',r+=2;else{if(e[r]==='"')break;o+=e[r++]}let i=r+1;yield{start:n,end:i,name:o,quoted:!0,call:/^\s*\(/.test(e.slice(i))},n=i;continue}if(/[A-Za-z_]/.test(t)&&(n===0||!/[A-Za-z0-9_$]/.test(e[n-1]))){let r=/^[A-Za-z_][A-Za-z0-9_$]*/.exec(e.slice(n)),o=n+r[0].length;yield{start:n,end:o,name:r[0],quoted:!1,call:/^\s*\(/.test(e.slice(o))},n=o;continue}n++}}function Wn(e,n){for(let t of oe(e))if(!t.call&&(t.quoted?t.name===n:t.name.toLowerCase()===n.toLowerCase()))return!0;return!1}function In(e,n){if(n.size===0)return e;let t="",r=0;for(let o of oe(e)){if(o.call)continue;let i=n.get(o.quoted?o.name:tn(n,o.name)??"");i!==void 0&&(t+=e.slice(r,o.start)+m(i),r=o.end)}return t+e.slice(r)}function tn(e,n){if(e.has(n))return n;let t=n.toLowerCase();for(let r of e.keys())if(r.toLowerCase()===t)return r}var qn=e=>`(NOT EXISTS (SELECT 1 FROM unnest(i.indclass::oid[]) AS oc(oid) JOIN pg_catalog.pg_opclass o ON o.oid = oc.oid WHERE NOT o.opcdefault)
3
+ AND NOT i.indnullsnotdistinct AND ${e}.reloptions IS NULL
4
+ AND NOT EXISTS (SELECT 1 FROM unnest(i.indcollation::oid[], i.indkey::int2[]) AS x(coll, att) JOIN pg_catalog.pg_attribute a ON a.attrelid = i.indrelid AND a.attnum = x.att WHERE x.att > 0 AND x.coll <> a.attcollation))`;var h=class extends Error{code;constructor(n,t,r){super(t,r),this.name="AccessRefused",this.code=n}};function rn(e,n){let t=ke(me(e)),r=new Map;for(let o of t.types.values()){let i=new Set,s=new Map;for(let a of o.relations.values())xe(a)&&i.add(a.name),a.kind==="stored"&&s.set(a.name,new Set(a.subjects));for(let a of o.permissions.keys())i.add(a);r.set(o.name,{names:i,kept:s})}return{schema:`access_${n}`,types:r}}function Un(e,n){let t=rn(e,""),r=o=>{let i=[...o].sort();return i.length===0?"never":i.map(s=>JSON.stringify(s)).join(" | ")};return[...t.types].map(([o,i])=>{let s=[...i.kept].sort(([a],[d])=>a<d?-1:a>d?1:0).map(([a,d])=>`${JSON.stringify(a)}: ${r(d)}`);return`${n}${o}: { names: ${r(i.names)}; relations: {${s.length===0?"":` ${s.join("; ")} `}} };`}).join(`
5
+ `)}var on="names a subject or changes who holds what: it is the service role's \u2014 Database.$asService().$access",sn={PA001:"unknown_name",PA002:"no_object",PA003:"bad_id",PA004:"too_many",PA005:"not_kept",PA006:"not_the_service"};function C(e,n){let t=typeof n=="string"?n:typeof n=="bigint"||typeof n=="number"&&Number.isSafeInteger(n)?String(n):void 0;if(t===void 0)throw new h("bad_id",`Database.$access: ${e} is a string or a whole number, not ${typeof n=="number"?String(n):typeof n}`);if(t===""||t.length>j)throw new h("bad_id",`Database.$access: ${e} is empty or longer than ${j} characters`);return t}function _e(e,n,t,r,o){let i=t==="anon",s=()=>{if(!n)throw new h("no_schema",`Database.$access: ${r??"the app declares no access schema \u2014 PalbaseFactory.create(\u2026, { db: { schemas, access } })"}`);return n},a=(l,u)=>{let c=typeof u=="string"?l.types.get(u):void 0;if(!c)throw new h("unknown_type",`Database.$access: the access schema has no type ${JSON.stringify(u)} \u2014 it has ${[...l.types.keys()].join(", ")||"none"}`);return c},d=(l,u,c)=>{let f=a(l,u);if(typeof c!="string"||!f.names.has(c))throw new h("unknown_name",`Database.$access: type ${String(u)} has no relation or permission ${JSON.stringify(c)} a user can hold \u2014 it has ${[...f.names].sort().join(", ")||"none"}`)},g=(l,u)=>{let c=u;if(c===null||typeof c!="object")throw new h("bad_id","Database.$access: an object is { type, id }");return a(l,c.type),{type:c.type,id:C(`the id of a ${String(c.type)}`,c.id)}},ee=l=>{if(typeof l!="string")throw new h("bad_id","Database.$access: a subject is a user's id, a string");return C("a subject's id",l)},ye=(l,u)=>{if(typeof u=="string")return{type:te,id:C("a subject's id",u)};let c=u;return c!==null&&typeof c=="object"&&"user"in c?{type:te,id:ee(c.user)}:g(l,u)},Xe=(l,u,c,f)=>{let w=typeof c=="string"?a(l,u.type).kept.get(c):void 0;if(!w){let y=[...a(l,u.type).kept.keys()].sort().join(", ");throw new h("not_kept",`Database.$access: type ${u.type} keeps no relation ${JSON.stringify(c)} \u2014 ${y===""?"it keeps none: its relations are read from its table":`it keeps ${y}`}`)}if(!w.has(f.type))throw new h("not_kept",`Database.$access: ${u.type}.${String(c)} takes ${[...w].sort().join(" or ")}, not ${f.type}`)},k=async(l,u)=>{try{return await e().query(l,u)}catch(c){let f=D(c),w=f===void 0?void 0:sn[f],y=c instanceof Error?c.message:String(c);throw w!==void 0?new h(w,`Database.$access: ${y}`,{cause:c}):f==="42501"?new h("not_the_service",`Database.$access: ${y} \u2014 what names a subject or changes who holds what is the service role's: Database.$asService().$access`,{cause:c}):c}},T=l=>{if(t!=="service")throw new h("not_the_service",`Database.$access.${l} ${on}`)},ne=(l,u,c)=>{let f=l.caller();return f===void 0?c:u(f)},ge=(l,u)=>{let c=[],f=[],w={},y=(x,R)=>{f.push(R),c.push(`${x} = $${f.length}`),w[x]=R};if(u?.object!==void 0&&(a(l,u.object.type),y("object_type",u.object.type),u.object.id!==void 0&&y("object_id",C(`the id of a ${u.object.type}`,u.object.id))),u?.relation!==void 0){if(typeof u.relation!="string")throw new h("not_kept","Database.$access: a relation is its name");y("relation",u.relation)}if(u?.subject!==void 0){let x=ye(l,u.subject);y("subject_type",x.type),y("subject_id",x.id)}let b=u?.limit??100;if(!Number.isSafeInteger(b)||b<1||b>1e3)throw new h("bad_id","Database.$access: limit is a whole number from 1 to 1000");return{sql:c.length===0?"":`WHERE ${c.join(" AND ")}`,params:f,limit:b,columns:w}},he=l=>`to_char(${l} AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.US"Z"')`,be=l=>async(u,c,f,w)=>{let y=s();T(l);let b=g(y,u),x=ye(y,f);Xe(y,b,c,x);let R=w?.by;if(R!==void 0&&(typeof R!="string"||R===""||R.length>j))throw new h("bad_id",`Database.$access: by is who did it \u2014 a string of at most ${j} characters`);return o?o.change(l,b,c,x,R):(await k(`SELECT ${m(y.schema)}.${m(l)}($1, $2, $3, $4, $5, $6) AS v`,[b.type,b.id,c,x.type,x.id,R??null]))[0]?.v===!0};return{async can(l,u){let c=s(),f=g(c,u);return d(c,f.type,l),i?!1:o?ne(o,y=>o.check(y,l,f.type,f.id),!1):(await k(`SELECT ${m(c.schema)}.can($1, $2, $3) AS v`,[l,f.type,f.id]))[0]?.v===!0},async objects(l,u){let c=s();return d(c,u,l),i?[]:o?ne(o,w=>o.objects(w,l,u),[]):(await k(`SELECT o AS id FROM ${m(c.schema)}.my_objects($1, $2) AS o ORDER BY 1`,[l,u])).map(w=>w.id)},async held(l){let u=s(),c=g(u,l),f=[...a(u,c.type).names].sort();return i||f.length===0?[]:o?ne(o,y=>f.filter(b=>o.check(y,b,c.type,c.id)),[]):(await k(`SELECT name FROM unnest($1::text[]) AS name WHERE ${m(u.schema)}.can(name, $2, $3) ORDER BY 1`,[f,c.type,c.id])).map(y=>y.name)},async check(l,u,c){let f=s();T("check");let w=ee(l),y=g(f,c);return d(f,y.type,u),o?o.check(w,u,y.type,y.id):(await k(`SELECT ${m(f.schema)}.check($1, $2, $3, $4) AS v`,[w,u,y.type,y.id]))[0]?.v===!0},async objectsOf(l,u,c){let f=s();T("objectsOf");let w=ee(l);return d(f,c,u),o?o.objects(w,u,c):(await k(`SELECT o AS id FROM ${m(f.schema)}.objects($1, $2, $3) AS o ORDER BY 1`,[w,u,c])).map(b=>b.id)},async subjects(l,u){let c=s();T("subjects");let f=g(c,u);return d(c,f.type,l),o?o.subjects(l,f.type,f.id):(await k(`SELECT s AS id FROM ${m(c.schema)}.subjects($1, $2, $3) AS s ORDER BY 1`,[l,f.type,f.id])).map(y=>y.id)},grant:be("grant"),revoke:be("revoke"),async relationships(l){let u=s();T("relationships");let c=ge(u,l);return o?o.relationships(c.columns,c.limit):(await k(`SELECT object_type, object_id, relation, subject_type, subject_id, ${he("created_at")} AS since FROM access.relationships ${c.sql} ORDER BY object_type, object_id, relation, subject_type, subject_id LIMIT ${c.limit}`,c.params)).map(w=>({object:{type:w.object_type,id:w.object_id},relation:w.relation,subject:{type:w.subject_type,id:w.subject_id},since:w.since}))},async history(l){let u=s();T("history");let c=ge(u,l);return o?o.history(c.columns,c.limit):(await k(`SELECT ${he("at")} AS at, action, object_type, object_id, relation, subject_type, subject_id, actor FROM access.history ${c.sql} ORDER BY id DESC LIMIT ${c.limit}`,c.params)).map(w=>({at:w.at,action:w.action,object:{type:w.object_type,id:w.object_id},relation:w.relation,subject:{type:w.subject_type,id:w.subject_id},by:w.actor}))}}}var an=Symbol.for("palbase.data"),cn=globalThis,M=cn[an]??=new WeakSet;function Ne(e){return e instanceof Date||ArrayBuffer.isView(e)||e instanceof ArrayBuffer}function Pe(e){let n=[e];for(;n.length>0;){let t=n.pop();if(!(typeof t!="object"||t===null||M.has(t)||Ne(t))){M.add(t);for(let r of Array.isArray(t)?t:Object.values(t))n.push(r)}}return e}function v(e){return typeof e=="object"&&e!==null&&M.has(e)}function un(e){if(!Array.isArray(e))return e;for(let n of e)if(!(typeof n!="object"||n===null))for(let t of Object.values(n))typeof t=="object"&&t!==null&&Pe(t);return e}function _(e,n){return v(e)&&M.add(n),n}function Yn(e,n,t){if(!v(e))return;let r=`is data \u2014 sent by a request or read from a row \u2014 and ${t} is written in code: data gives values. Build it in code around the values you checked.`;throw Se(new N({fields:[{field:n,message:r}]},`${n} ${r}`))}var se=Symbol.for("palbase.db.ref"),ve=Symbol.for("palbase.tx.expr");function W(e,n){return Object.defineProperty(e,se,{value:n,enumerable:!1}),e}function E(e){if(!(typeof e!="object"||e===null))return Object.hasOwn(e,se)?e[se]:void 0}function I(e){return E(e)==="col"&&typeof e.$col=="string"}function $(e){if(E(e)!=="sql")return!1;let n=e.$sql;return n!==void 0&&Array.isArray(n.text)&&Array.isArray(n.values)}function Zn(e){if(E(e)!=="ref")return!1;let n=e.$ref;return n!==void 0&&typeof n.op=="number"&&typeof n.field=="string"}function Qn(e){if(E(e)!=="expr")return!1;let n=e.$expr;return n!==void 0&&(n.fn==="inc"||n.fn==="dec"||n.fn==="now")}function et(e){if(typeof e!="object"||e===null||E(e)!==void 0)return!1;let n=e.$ref;return n!==void 0&&typeof n=="object"&&n!==null}function nt(e){if(typeof e!="object"||e===null||E(e)!==void 0||ie(e))return null;let n=e;return typeof n.$col=="string"?"col":n.$sql!==void 0&&typeof n.$sql=="object"&&n.$sql!==null?"sql":n.$expr!==void 0&&typeof n.$expr=="object"&&n.$expr!==null?"expr":null}function ie(e){if(typeof e!="object"&&typeof e!="function"||e===null)return!1;try{return e[ve]!==void 0}catch{return!1}}function q(e){if(!ie(e))return!1;try{let n=e[ve];return typeof n=="object"&&n!==null&&n.fn==="now"}catch{return!1}}function tt(e,n,t,r){for(let o of t){let i=r[o];if(q(i))throw new Error(`${e}(${n}): "${o}" got now() where a value is expected. To write the server's time when a row is inserted, declare the column defaultNow(); to stamp an existing row, updateMany({ where, set: { ${o}: now() } }) or, in $transaction, tx.public.${n}.updateWhere(where, { ${o}: now() }).`);if(ie(i))throw new Error(`${e}(${n}): "${o}" got an expression handle (increment()/decrement()) where a value is expected. To add to a counter use updateMany({ where, set: { ${o}: increment(n) } }) or, in $transaction, tx.public.${n}.updateWhere(where, { ${o}: increment(n) }).`);if(I(i))throw new Error(`${e}(${n}): "${o}" got a col(). A column reference stands only in a filter; to write one column's value into another, use $query.`)}}var ln=new Set(["gt","gte","lt","lte","neq","in","contains","icontains","startsWith","endsWith","isNull","overlaps"]),De={eq:'equality is written bare: { <column>: <value> } (or { <column>: col("\u2026") } to compare with a column)'};function Ce(e,n,t){if(t&&!$(t))for(let[r,o]of Object.entries(t)){if(r==="OR"||r==="AND"||r==="NOT"){let s=r==="NOT"?[o]:o;if(!Array.isArray(s))throw new Error(`${e}(${n}): where.${r} must be an array`);for(let a of s){if(a===null||typeof a!="object")throw new Error(`${e}(${n}): the branches of where.${r} must be filter objects`);Ce(e,n,a)}continue}if(r==="has"){if(o===null||typeof o!="object"||Array.isArray(o))throw new Error(`${e}(${n}): where.has must be a map of relations ({ <relation>: { \u2026 } })`);for(let[s,a]of Object.entries(o)){if(a===null||typeof a!="object"||Array.isArray(a))throw new Error(`${e}(${n}): where.has.${s} must be a filter object`);Ce(e,n,a)}continue}if(o===void 0)throw new Error(`${e}(${n}): where.${r} is undefined \u2014 not a filter value. Bound, it is NULL, and '= NULL' matches no row, so the query would answer nothing and say nothing. Leave the key out when there is no value.`);if(o===null||typeof o!="object"||Array.isArray(o)||I(o)||q(o))continue;let i=Object.entries(o);if(i.length===0)throw new Error(`${e}(${n}): where.${r} is an empty operator object ({}) \u2014 it produces no condition, so the column would silently drop out of the filter. Leave the key out when there is no condition.`);for(let[s,a]of i){if(s==="in"){if(!Array.isArray(a))throw new Error(`${e}(${n}): where.${r}.in must be an array`);if(a.some(d=>d===void 0))throw new Error(`${e}(${n}): where.${r}.in holds undefined \u2014 bound as NULL it matches no row. Drop it when building the list.`);continue}if(De[s]!==void 0)throw new Error(`${e}(${n}): where.${r}.${s} is not in this filter language \u2014 ${De[s]}`);if(!ln.has(s))throw new Error(`${e}(${n}): where.${r} has an unknown operator "${s}" (gt/gte/lt/lte/neq/in/contains/icontains/startsWith/endsWith/isNull/overlaps)`);if(a===void 0)throw new Error(`${e}(${n}): where.${r}.${s} is undefined \u2014 the comparison's right side would be NULL and match no row. Leave the condition out.`)}}}var dn=["days","hours","minutes","seconds"],fn=2147483647,Me=e=>typeof e=="number"||typeof e=="boolean"||e===null||e===void 0?String(e):typeof e=="string"?JSON.stringify(e.slice(0,40)):typeof e;function ae(e){if(e===null||typeof e!="object"||Array.isArray(e))return{refused:"takes a span: { days?, hours?, minutes?, seconds? }"};let n={};for(let t of Object.keys(e)){if(!dn.includes(t))return{refused:`${Me(t)} is not a unit of the span \u2014 days, hours, minutes or seconds`};let r=e[t];if(typeof r!="number"||!Number.isSafeInteger(r)||r<0||r>fn)return{refused:`${t} is a whole number, 0 or more, got ${Me(r)}${r===void 0?" \u2014 leave the unit out instead":""}`};n[t]=r}return Object.keys(n).length===0?{refused:"was given no span \u2014 ago({}) would be now(); name days, hours, minutes or seconds, or write now()"}:{span:Object.freeze(n)}}function rt(e,n,t,r){for(let o of t)if(r[o]===void 0)throw new Error(`${e}(${n}): "${o}" is undefined \u2014 not a value to write. Write null to empty the column; leave the key out to leave the column as it is (a missing request field used to write NULL silently).`)}function We(e,n){let r=(n!==null&&typeof n=="object"?Object.keys(n):[]).filter(i=>i!=="id");if(r.length>0)throw new Error(`update(${e}): where takes the row's id alone, not ${r.map(i=>`"${i}"`).join(", ")} \u2014 a condition beside the id would be dropped. To update the rows a filter matches, updateMany({ where, set }).`);let o=n?.id;if(typeof o!="string"&&typeof o!="number"&&typeof o!="bigint")throw new Error(`update(${e}): where needs the row's id, one value \u2014 { where: { id }, set }. To update the rows a filter matches, updateMany({ where, set }).`);return String(o)}var V=class extends Error{constructor(n){super(n),this.name="TxRefError"}},p=class extends Error{constructor(n){super(n),this.name="TxPlanError"}},L=Symbol.for("palbase.tx.expr"),B=Symbol.for("palbase.tx.ref"),F=Symbol.for("palbase.tx.row"),Be=Symbol.for("palbase.tx.rows"),le=["then","valueOf","toString","toJSON",Symbol.toPrimitive];function de(e,n,t){let r=typeof e=="symbol"?e.description??String(e):e;throw new V(`${n} was used as a value (via \`${r}\`). Nothing in a transaction callback has run yet, so there is no value to read. ${t}`)}function at(){return Y({fn:"now"})}function ct(e){let n=ae(e);if("refused"in n)throw new p(`ago() ${n.refused}`);return Y(Object.freeze({fn:"now",minus:n.span}))}function Fe(e,n){if(e.fn!=="now"||e.minus===void 0)return;let t=ae(e.minus);if("refused"in t)throw new p(`\`${n}\`: ago() ${t.refused}`)}function ut(e){return Ue(e,"increment"),Y({fn:"inc",by:e})}function lt(e){return Ue(e,"decrement"),Y({fn:"dec",by:e})}function Ue(e,n){if(typeof e=="string"){if(!/^-?\d+(\.\d+)?$/.test(e))throw new p(`${n}() takes a decimal number as text, got "${e}" \u2014 "12", "12.50"`)}else if(typeof e!="number"||!Number.isFinite(e))throw new p(`${n}() needs a finite number, got ${String(e)}`);if(typeof e=="string"?e.trimStart().startsWith("-"):e<0){let r=n==="increment"?"decrement":"increment";throw new p(`${n}() takes no negative amount ("${String(e)}"). Use ${r}() for the other direction \u2014 a sign kept in the amount is seen by no code that reads the direction.`)}}function dt(e){return Z(e)}function Y(e){return new Proxy({[L]:e},{get(n,t){if(t===L)return n[L];le.includes(t)&&de(t,"A plan expression","Write it into an operation instead.")}})}function wn(e,n){let t={[B]:{op:e,field:n}};return new Proxy(t,{get(r,o){if(o===B)return r[B];le.includes(o)&&de(o,`\`${n}\` of a row this transaction has not written yet`,"Pass it to another operation in the same plan, or return it from the callback and read it after `$transaction` resolves.")}})}function pn(e){let n={[F]:e};return new Proxy(n,{get(t,r){if(r===F)return t[F];if(le.includes(r)&&de(r,"A row this transaction has not written yet","Read one of its columns to reference it, or return the row from the callback and read it after `$transaction` resolves."),typeof r!="symbol")return wn(e,r)}})}function J(e){if(typeof e!="object"||e===null)return null;let n=e[B];return typeof n=="object"&&n!==null&&typeof n.op=="number"&&typeof n.field=="string"?n:null}function X(e){if(typeof e!="object"||e===null)return null;let n=e[F];return typeof n=="number"?n:null}function Z(e){if(typeof e!="object"||e===null)return null;let n=e[L];return typeof n=="object"&&n!==null?n:null}function Q(e){return typeof e=="object"&&e!==null&&e[Be]!==void 0}function yn(e,n,t){let r=J(e);if(r)return W({$ref:{op:r.op,field:r.field}},"ref");let o=Z(e);if(o){if(o.fn!=="now"&&!t)throw new p(`\`${n}\`: ${o.fn}() reads the column's current value, so it is only valid in updateWhere(where, set).`);return Fe(o,n),W({$expr:o},"expr")}if(X(e)!==null)throw new p(`\`${n}\`: a row handle is not a value. Read the column you meant (e.g. \`row.id\`).`);if(Q(e))throw new p(`\`${n}\`: an operation result is not a value. Declare an expectation first (\`.expectOne(err)\`) and read a column from the row.`);return Ve(e,n),e}function ue(e,n){let t=J(e);if(t)return W({$ref:{op:t.op,field:t.field}},"ref");let r=Z(e);if(r&&r.fn!=="now")throw new p(`\`${n}\`: ${r.fn}() is a WRITE expression, not a comparison \u2014 it cannot stand in a filter. Compare the column with a value or a col().`);if(q(e))return r&&Fe(r,n),e;if(X(e)!==null)throw new p(`\`${n}\`: a row handle is not a value. Read the column you meant (e.g. \`row.id\`).`);if(Q(e))throw new p(`\`${n}\`: an operation result is not a value. Declare an expectation first (\`.expectOne(err)\`) and read a column from the row.`);if(Array.isArray(e))return _(e,e.map(o=>ue(o,n)));if(e!==null&&typeof e=="object"&&!(e instanceof Date)&&!I(e)&&!$(e)){let o=_(e,{});for(let[i,s]of Object.entries(e))o[i]=ue(s,n);return o}return e}function ce(e){if($(e))return e;let n=_(e,{});for(let t of Object.keys(e).sort()){let r=e[t];if(r===void 0)throw new p(`where.${t} is undefined \u2014 not a filter value. Dropped, the condition would silently go and the filter match more rows than it reads (a missing request field looks like this). Leave the key out when there is no condition; write null for IS NULL.`);n[t]=ue(r,t)}return n}function Ve(e,n){if(!(typeof e!="object"||e===null||e instanceof Date)){if(J(e)||Z(e)||X(e)!==null||Q(e))throw new p(`\`${n}\`: a plan handle is nested inside a value. It would be stored as literal JSON, not resolved. Put the reference directly in the column.`);for(let t of Array.isArray(e)?e:Object.values(e))Ve(t,n)}}function K(e,n){let t={};for(let r of Object.keys(e).sort()){let o=e[r];if(o===void 0)throw new p(`${r} is undefined \u2014 not a value to write. The key is there but its value is not, so the column would silently not be written (a missing request field looks like this). Leave the key out for the column default; write null for NULL.`);t[r]=yn(o,r,n)}return t}var U=-1,z=class{[Be]=!0;guarded=!1;builder;opIndex;what;constructor(n,t,r){this.builder=n,this.opIndex=t,this.what=r}then(){throw new V(`${this.what} cannot be awaited: a transaction callback builds a plan, it does not run statements. Remove the \`await\`.`)}expectOne(n){if(this.declareGuard("one",1,n),this.opIndex===U)throw n;return pn(this.opIndex)}expectNone(n){this.declareGuard("none",0,n)}expectAtLeast(n,t){if(Ie(n,"expectAtLeast"),this.declareGuard("atLeast",n,t),this.opIndex===U&&n>0)throw t}expectAtMost(n,t){Ie(n,"expectAtMost"),this.declareGuard("atMost",n,t)}declareGuard(n,t,r){if(!(r instanceof Error))throw new p(`${this.what}: an expectation needs the Error to throw when it does not hold (e.g. \`.expect\u2026(new Conflict("already accepted"))\`).`);if(this.guarded)throw new p(`${this.what} already has an expectation. One operation carries one expectation; declare the second on its own operation.`);this.guarded=!0,this.opIndex!==U&&this.builder.attachGuard(this.opIndex,n,t,r)}};function Ie(e,n){if(!Number.isInteger(e)||e<0)throw new p(`${n}(n) needs a non-negative integer, got ${String(e)}`)}var qe=1e3,Ke=5e3,H=class{ops=[];slots=[];table(n){return{insert:t=>{let r=K(t,!1);if(Object.keys(r).length===0)throw new p(`${n}.insert() needs at least one column`);return this.push({op:"insert",table:n,values:r},`${n}.insert()`)},put:(t,r)=>{let o=K(t,!1);if(Object.keys(o).length===0)throw new p(`${n}.put() needs at least one column`);if(r.onConflict.length===0)throw new p(`${n}.put() needs at least one onConflict column`);return this.push({op:"upsert",table:n,values:o,onConflict:r.onConflict},`${n}.put()`)},insertMany:(t,r)=>{if(t.length===0)return new z(this,U,`${n}.insertMany()`);if(t.length>Ke)throw new p(`${n}.insertMany() has ${t.length} rows; the limit is ${Ke}. Split the write.`);let o=t.map(i=>K(i,!1));return bn(o,n),this.push({op:"insertMany",table:n,rows:o,...hn(r,n)},`${n}.insertMany()`)},updateWhere:(t,r)=>{let o=ce(t),i=K(r,!0);if(Object.keys(o).length===0&&!$(o))throw new p(`${n}.updateWhere() needs a filter. An update with no filter rewrites the whole table.`);if(Object.keys(i).length===0)throw new p(`${n}.updateWhere() needs at least one column to set`);return this.push({op:"update",table:n,set:i,where:o},`${n}.updateWhere()`)},deleteWhere:t=>{let r=ce(t);if(Object.keys(r).length===0&&!$(r))throw new p(`${n}.deleteWhere() needs a filter. A delete with no filter empties the table.`);return this.push({op:"delete",table:n,where:r},`${n}.deleteWhere()`)},select:(t,r)=>{let o={op:"select",table:n},i=ce(t??{});if((Object.keys(i).length>0||$(i))&&(o.where=i),r?.limit!==void 0){if(!Number.isInteger(r.limit)||r.limit<0)throw new p(`${n}.select(): limit needs a non-negative integer, got ${String(r.limit)}`);o.limit=r.limit}return r?.lock!==void 0&&(o.lock=r.lock),this.push(o,`${n}.select()`)}}}push(n,t){if(this.ops.length>=qe)throw new p(`this transaction has ${qe} operations, the limit. Use insertMany() for bulk writes, or split the work.`);let r=this.ops.length;return this.ops.push(n),new z(this,r,t)}attachGuard(n,t,r,o){let i=this.ops[n];if(!i)throw new p(`internal: expectation on unknown operation ${n}`);let s=this.slots.length;this.slots.push(o),i.guard={kind:t,n:r,slot:s}}body(){return{ops:this.ops}}errorForSlot(n){return this.slots[n]??null}},gn=e=>typeof e=="string"?JSON.stringify(e.slice(0,40)):typeof e;function hn(e,n){if(e===void 0)return{};if(e.action!==void 0&&e.action!=="ignore"&&e.action!=="update")throw new p(`${n}.insertMany(): a conflict's action is "ignore" or "update", not ${gn(e.action)}.`);if(e.onConflict===void 0){if(e.action!=="ignore")throw new p(`${n}.insertMany() was given a conflict action with no onConflict columns. An overwrite is matched on columns: name them \u2014 action "ignore" alone skips a collision with any unique key.`);return{action:"ignore"}}if(e.onConflict.length===0)throw new p(`${n}.insertMany() was given an empty onConflict list. A collision is matched on columns: name them, or leave onConflict out with action "ignore" to skip a collision with any unique key.`);return{onConflict:e.onConflict,action:e.action??"ignore"}}function bn(e,n){let t=e[0];if(!t)return;let r=Object.keys(t),o=r.join(",");for(let i=1;i<e.length;i++){let s=Object.keys(e[i]);if(s.join(",")!==o)throw new p(`${n}.insertMany(): every row must set the same columns. Row 0 sets [${r.join(", ")}] but row ${i} sets [${s.join(", ")}]. (A property set to \`undefined\` counts as absent \u2014 use \`null\`.)`)}}function G(e,n){let t=J(e);if(t){let o=Le(n,t.op,`\`${t.field}\``);if(!(t.field in o))throw new p(`the transaction's operation ${t.op} returned no column \`${t.field}\`.`);return o[t.field]}let r=X(e);if(r!==null)return Le(n,r,"a row");if(Q(e))throw new p("an operation result cannot be returned from a transaction callback: its row count is not known until the plan runs. Declare an expectation (`.expectOne(err)`) and return the row, or a column of it.");if(Array.isArray(e))return e.map(o=>G(o,n));if(mn(e)){let o={};for(let[i,s]of Object.entries(e))o[i]=G(s,n);return o}return e}function Le(e,n,t){let r=e[n];if(!r)throw new p(`the transaction returned no result for operation ${n}, so ${t} cannot be read.`);let o=r.rows[0];if(!o)throw new p(`the transaction's operation ${n} returned no row, so ${t} cannot be read.`);return o}function mn(e){if(typeof e!="object"||e===null)return!1;let n=Object.getPrototypeOf(e);return n===Object.prototype||n===null}async function ze(e,n,t,r){let o=r(n),i=t.body();if(i.ops.length===0)return G(o,[]);let s;try{s=await e.txPlan(i)}catch(a){throw xn(a,t)}return G(o,s.results)}function xn(e,n){if(typeof e!="object"||e===null)return e;let t=e;return t.error_code!=="tx_guard_failed"||typeof t.slot!="number"?e:n.errorForSlot(t.slot)??e}import{AsyncLocalStorage as kn}from"node:async_hooks";function He(e){let n=e??0;if(!Number.isInteger(n)||n<0||n>10)throw new Error("transaction retry must be an integer between 0 and 10");return n}function wt(e){if(He(e.retry),e.isolation!==void 0&&!["read committed","repeatable read","serializable"].includes(e.isolation))throw new Error("transaction isolation must be read committed, repeatable read or serializable");if(e.readOnly!==void 0&&typeof e.readOnly!="boolean")throw new Error("transaction readOnly must be a boolean");for(let n of["lockTimeoutMs","statementTimeoutMs","timeoutMs"]){let t=e[n];if(t!==void 0&&(!Number.isInteger(t)||t<1||t>2147483647))throw new Error(`transaction ${n} must be a positive integer in milliseconds`)}if(e.signal!==void 0&&(typeof e.signal.aborted!="boolean"||typeof e.signal.addEventListener!="function"))throw new Error("transaction signal must be an AbortSignal")}function Ge(e){if(He(e?.retry)!==0)throw new Error("Database.$transaction is a savepoint plan on the request transaction and cannot retry its snapshot or COMMIT. Use Database.$atomic(async tx => { ... }, { retry, isolation }) and put all decision reads and writes inside that callback.")}function pt(e){if(e){if(e.returning!==void 0&&typeof e.returning!="boolean")throw new Error("insertMany returning must be a boolean");if(e.action!==void 0&&e.action!=="ignore"&&e.action!=="update")throw new Error("insertMany action must be ignore or update");if(e.onConflict!==void 0&&(!Array.isArray(e.onConflict)||e.onConflict.some(n=>typeof n!="string"||n.length===0)))throw new Error("insertMany onConflict must be an array of column names");if(e.action==="update"&&!e.onConflict?.length)throw new Error('insertMany action "update" overwrites the row a collision is matched on: name its columns in onConflict');if(e.action==="ignore"&&e.onConflict!==void 0&&e.onConflict.length===0)throw new Error('insertMany onConflict is an empty list: name the columns a collision is matched on, or leave it out \u2014 action "ignore" alone skips a collision with any unique key')}}function Ye(e,n){return new Proxy({},{get(t,r){if(typeof r!="string")return;let o=`${n}${r}`;return{insert:i=>e().insert(o,i),insertMany:(i,s)=>e().insertMany(o,i,s),aggregate:i=>e().aggregate(o,i),update:i=>e().update(o,We(o,i.where),i.set),delete:i=>e().delete(o,i),findById:i=>e().findById(o,i),findUnique:i=>e().findUnique(o,i.where,{select:i.select,with:i.with,lock:i.lock}),page:i=>{let{where:s,...a}=i??{};return e().page(o,s,a)},findMany:i=>{let{where:s,...a}=i??{};return e().findMany(o,s,a)},put:i=>e().put(o,i.data,{onConflict:i.onConflict}),updateMany:i=>e().updateMany(o,i.where,i.set,i.returning===void 0?void 0:{returning:i.returning}),deleteMany:i=>e().deleteMany(o,i.where),count:i=>e().count(o,i?.where),claim:(i,s)=>e().claim(o,i,s),search:(i,s)=>e().search(o,i,s)}}})}function Je(e,n=""){return new Proxy({},{get(t,r){if(typeof r=="string")return e.table(n+r)}})}function Rn(e){let n=Je(e);return new Proxy({},{get(t,r){if(typeof r=="string")return r==="tables"||r==="public"?n:Je(e,re(r,""))}})}function pe(e,n,t,r={}){let i=Object.assign({$query:(s,a)=>e().query(s,a),$diagnostics:()=>e().diagnostics(),$insert:(s,a)=>e().insert(s,a),$insertMany:((s,a,d)=>e().insertMany(s,a,d)),$update:(s,a,d)=>e().update(s,a,d),$delete:(s,a)=>e().delete(s,a),$findById:(s,a)=>e().findById(s,a),$findUnique:(s,a,d)=>e().findUnique(s,a,d),$page:(s,a,d)=>e().page(s,a,d),$findMany:(s,a,d)=>e().findMany(s,a,d),$put:(s,a,d)=>e().put(s,a,d),$updateMany:(s,a,d,g)=>e().updateMany(s,a,d,g),$deleteMany:(s,a)=>e().deleteMany(s,a),$count:(s,a)=>e().count(s,a),$search:(s,a,d)=>e().search(s,a,d),$aggregate:(s,a)=>e().aggregate(s,a),$claim:(s,a,d)=>e().claim(s,a,d),$lockRows:(s,a)=>e().lockRows(s,a),$lockRowsWhere:(s,a,d)=>e().lockRowsWhere(s,a,d),$advisoryXactLock:s=>e().advisoryXactLock(s)},r,{$access:_e(e,t.names,t.as,t.unanswered,t.via),$atomic(s,a){let d=e();if(typeof d.atomic!="function")throw new Error("Database.$atomic owns one transaction and identity; nested roots and $asService are not allowed");return d.atomic(g=>n(g,()=>s(pe(()=>g,n,t))),a)},$attempt:s=>e().attempt(s),$transaction(s,a){Ge(a);let d=new H;return ze(e(),Rn(d),d,s)}});return new Proxy(i,{get(s,a,d){return a==="tables"?Ye(e,""):typeof a=="string"&&!a.startsWith("$")&&!(a in s)?Ye(e,re(a,"")):Reflect.get(s,a,d)}})}var fe=new kn,we=()=>{throw new Error("Database.$atomic owns one transaction and identity; nested roots and $asService are not allowed")};function Rt(e,n={}){let t={names:n.access,as:n.as??"service",...n.unanswered===void 0?{}:{unanswered:n.unanswered},...n.via===void 0?{}:{via:n.via}},r={},o=()=>{let d=fe.getStore();return d?.owner===r?d.tx:e},i=(d,g)=>fe.run({owner:r,tx:Object.assign(Object.create(null),d,{atomic:we,asService:we})},g),s=new Proxy(Object.create(null),{get:()=>()=>{throw new Error("Database inside $asService().$atomic: the shared Database would bypass the caller's row-level security there \u2014 use the handle the callback is given")}}),a=(d,g)=>fe.run({owner:r,tx:s},g);return pe(o,i,t,{$asService(){let d=o();if(typeof d.asService!="function")return we();let g=d.asService();return pe(()=>g,a,{...t,as:"service"})}})}export{m as a,Pn as b,Dn as c,Cn as d,Mn as e,vn as f,Wn as g,In as h,qn as i,Ze as j,je as k,A as l,O as m,Se as n,An as o,N as p,Re as q,S as r,$e as s,On as t,Te as u,Ae as v,Oe as w,Ee as x,D as y,Qe as z,en as A,En as B,jn as C,Sn as D,_n as E,h as F,rn as G,Un as H,Ne as I,Pe as J,v as K,un as L,_ as M,Yn as N,W as O,I as P,$ as Q,Zn as R,Qn as S,et as T,nt as U,ie as V,q as W,tt as X,Ce as Y,ae as Z,rt as _,We as $,V as aa,p as ba,at as ca,ct as da,ut as ea,lt as fa,dt as ga,H as ha,ze as ia,He as ja,wt as ka,pt as la,Rt as ma};
@@ -0,0 +1,309 @@
1
+ /*! palgres 0.55.0 — Palbase SDK License (see LICENSE) */
2
+ import{createHash as fn}from"node:crypto";function is(t){return`${t}_lookup`}function as(t,e){let n=s=>s==="cascade"||s==="set null"||s==="set default";return n(t)||n(e)}var St=class extends Error{problems;constructor(e){super(`the schema is not valid:
3
+ - ${e.join(`
4
+ - `)}`),this.name="SchemaError",this.problems=e}},cs=()=>({tables:[],enums:[],extensions:[],raw:[]}),te=t=>`${t.schema}.${t.name}`,gn={int:"integer",int4:"integer",int2:"smallint",int8:"bigint",float4:"real",float8:"double precision",bool:"boolean",timestamptz:"timestamp with time zone",timestamp:"timestamp without time zone","timestamp without time zone":"timestamp without time zone",timetz:"time with time zone",time:"time without time zone",varchar:"character varying",char:"character",decimal:"numeric"};function et(t){let e=t.trim().replace(/\s+/g," "),n="";for(;e.endsWith("[]");)n+="[]",e=e.slice(0,-2).trim();let s=/^((?:"(?:[^"]|"")+"|[A-Za-z_][A-Za-z0-9_ ]*?)(?:\.(?:"(?:[^"]|"")+"|[A-Za-z_][A-Za-z0-9_]*))?)\s*(\(.*\))?$/.exec(e);if(!s)return t.trim()+n;let i=s[2]?s[2].replace(/\s+/g,""):"",r=En(s[1]);return r===void 0?t.trim()+n:r.length===1&&r[0].quoted?`"${r[0].name.replace(/"/g,'""')}"${i}${n}`:r.length===1?`${gn[r[0].name]??r[0].name}${i}${n}`:`${r.map(m=>Qe(m.name)).join(".")}${i}${n}`}var Qe=t=>/^[a-z_][a-z0-9_$]*$/.test(t)?t:`"${t.replace(/"/g,'""')}"`,ls=(t,e)=>`${Qe(t)}.${Qe(e)}`;function En(t){let e=[],n=0;for(;n<t.length;){if(t[n]==='"'){let s=n+1,i="";for(;;){if(s>=t.length)return;if(t[s]==='"'){if(t[s+1]==='"'){i+='"',s+=2;continue}break}i+=t[s++]}e.push({name:i,quoted:!0}),n=s+1}else{let s=/^[A-Za-z_][A-Za-z0-9_ ]*/.exec(t.slice(n));if(!s)return;e.push({name:s[0].trim().toLowerCase(),quoted:!1}),n+=s[0].length}if(n<t.length){if(t[n]!==".")return;n++}}return e}var hn=/^[A-Za-z_][A-Za-z0-9_$]*$/,$n=63;function Z(t,e,n=!1){if(typeof e!="string"||e==="")return`${t} has no name`;if(n?e.includes("\0"):!hn.test(e))return`${t} "${e}": a name is letters, digits and _ (starting with a letter or _)`;if(Buffer.byteLength(e)>$n)return`${t} "${e}": longer than Postgres' 63 bytes, it would be cut`;if(e.startsWith("palgres_")||e.startsWith("_palgres"))return`${t} "${e}": names starting with palgres_ are Palgres' own`}var yn="vector",Ct=["cosine","euclidean","inner_product"],tt=1536,bn=2e3,Je=4e3,Rn=/^(text|citext|public\.citext|character varying(\(\d+\))?)$/;function nt(t,e,n){let s=[];e.primaryKey.length!==1&&s.push(`${t} declares search and has ${e.primaryKey.length===0?"no primary key":`a primary key of ${e.primaryKey.length} columns`}: a row's vector is kept by its key \u2014 give the table a single-column primary key (uuid().primaryKey())`),(!Array.isArray(n.from)||n.from.length===0)&&s.push(`${t}: search.from is empty \u2014 name the text columns a row is found by (search: { from: ['title', 'body'], model })`);let i=new Set;for(let r of Array.isArray(n.from)?n.from:[]){i.has(r)&&s.push(`${t}: search.from names "${r}" twice \u2014 name each column once`),i.add(r);let m=e.columns.find(a=>a.name===r);m?m.ignored?s.push(`${t}: search.from names "${r}", which is ignored \u2014 take it out of search.from, or keep the column`):Rn.test(et(m.type))?m.generated&&s.push(`${t}: search.from names "${r}", a generated column \u2014 no write names it, so nothing would say when to embed the row again: name the columns it is computed from`):s.push(`${t}: search.from names "${r}", which is ${m.type} \u2014 search reads text (text, varchar, citext): name a text column, or keep the text in one`):s.push(`${t}: search.from names "${r}", which the table does not have \u2014 name its text columns`)}return(typeof n.model!="string"||n.model.trim()==="")&&s.push(`${t}: search.model is empty \u2014 name the embedding model (search: { from, model: 'embedding' })`),Ct.includes(n.metric)||s.push(`${t}: search.metric is ${JSON.stringify(n.metric)} \u2014 it is ${Ct.map(r=>`'${r}'`).join(", ")}`),(!Number.isInteger(n.dimensions)||n.dimensions<1||n.dimensions>Je)&&s.push(`${t}: search.dimensions is ${String(n.dimensions)} \u2014 it is 1 to ${Je}: pgvector indexes a vector of at most ${bn} dimensions and a half-precision one of at most ${Je}; ask the model for fewer (search: { dimensions: ${tt} })`),n.staleness!=="null"&&n.staleness!=="keep"&&s.push(`${t}: search.staleness is ${JSON.stringify(n.staleness)} \u2014 it is 'null' (a changed row is not found by its old meaning) or 'keep' (it is, until embedded again)`),e.columns.some(r=>r.name==="_score"&&!r.ignored)&&s.push(`${t} declares search and has a column "_score": search() answers each row with its _score \u2014 rename the column`),s}function us(t){let e=[],n=a=>a&&e.push(a),s=new Map,i=new Map,r=(a,p,b)=>{let I=`${a}.${p}`,j=i.get(I);j?e.push(`${b} "${p}" has the name of ${j} in schema ${a}`):i.set(I,b)};for(let a of t.enums)n(Z("an enum",a.name)),a.values.length===0&&e.push(`enum ${a.schema}.${a.name} has no values`),new Set(a.values).size!==a.values.length&&e.push(`enum ${a.schema}.${a.name} names a value twice`);for(let a of t.tables){let p=te(a);n(Z("a schema",a.schema)),n(Z("a table",a.name)),s.has(p)&&e.push(`table ${p} is declared twice`),s.set(p,a),r(a.schema,a.name,`table ${p}`);let b=new Map,I=(E,k)=>{let G=b.get(E);G?e.push(`${k} "${E}" has the name of a ${G} of table ${p}`):b.set(E,k)},j=new Map;for(let E of a.columns)n(Z(`column ${p}.${E.name}`,E.name)),j.has(E.name)&&e.push(`column ${p}.${E.name} is declared twice`),j.set(E.name,E),E.identity&&E.default!==void 0&&e.push(`column ${p}.${E.name}: an identity column has no default`),E.generated&&(E.default!==void 0||E.identity||E.fill!==void 0)&&e.push(`column ${p}.${E.name}: a generated column has no default, identity or fill`),E.generated&&!E.generated.expr.trim()&&e.push(`column ${p}.${E.name}: a generated column's expression is empty`),E.identity&&!["smallint","integer","bigint"].includes(et(E.type))&&e.push(`column ${p}.${E.name}: an identity column is smallint, integer or bigint`),E.identity&&E.nullable&&e.push(`column ${p}.${E.name}: an identity column is NOT NULL`);let L=(E,k)=>{let G=j.get(E);G?G.ignored&&e.push(`${k} names column "${E}", which is ignored`):e.push(`${k} names column "${E}", which ${p} does not have`)};for(let E of a.primaryKey)L(E,`the primary key of ${p}`);for(let E of a.primaryKey)j.get(E)?.nullable&&e.push(`column ${p}.${E} is in the primary key, so it is not nullable`);for(let E of a.uniques){n(Z(`a unique constraint of ${p}`,E.name,!0)),r(a.schema,E.name,`unique constraint ${p}.${E.name}`),I(E.name,"unique constraint"),E.columns.length===0&&e.push(`unique constraint ${E.name} names no column`);for(let k of E.columns)L(k,`unique constraint ${E.name}`)}for(let E of a.indexes){n(Z(`an index of ${p}`,E.name,!0)),r(a.schema,E.name,`index ${p}.${E.name}`),E.keys.length===0&&e.push(`index ${E.name} has no key`);for(let k of E.keys)"column"in k&&L(k.column,`index ${E.name}`);for(let k of E.include??[])L(k,`index ${E.name}`)}for(let E of a.checks)n(Z(`a check of ${p}`,E.name,!0)),I(E.name,"check"),E.expr.trim()||e.push(`check ${E.name} has no expression`);for(let E of a.foreignKeys){n(Z(`a foreign key of ${p}`,E.name,!0)),I(E.name,"foreign key"),(E.columns.length===0||E.columns.length!==E.refColumns.length)&&e.push(`foreign key ${E.name} names ${E.columns.length} column(s) and references ${E.refColumns.length}`);for(let k of E.columns)L(k,`foreign key ${E.name}`)}let v=new Set;for(let E of a.policies)n(Z(`a policy of ${p}`,E.name,!0)),v.has(E.name)&&e.push(`policy ${p}.${E.name} is declared twice`),v.add(E.name),E.to.length===0&&e.push(`policy ${p}.${E.name} names no role`),E.for==="insert"&&E.using!==void 0&&e.push(`policy ${p}.${E.name}: an insert policy has only withCheck`),(E.for==="select"||E.for==="delete")&&E.withCheck!==void 0&&e.push(`policy ${p}.${E.name}: a ${E.for} policy has only using`);a.policies.length>0&&!a.rls&&e.push(`table ${p} has policies but row-level security off: they would do nothing`),a.search!==void 0&&e.push(...nt(`table ${p}`,a,a.search))}for(let a of t.tables)for(let p of a.foreignKeys){let b=s.get(`${p.refSchema}.${p.refTable}`);if(!b){e.push(`foreign key ${p.name} of ${te(a)} references ${p.refSchema}.${p.refTable}, which is not declared`);continue}b.ignored&&e.push(`foreign key ${p.name} of ${te(a)} references ${te(b)}, which is ignored`);for(let I of p.refColumns)b.columns.some(j=>j.name===I&&!j.ignored)||e.push(`foreign key ${p.name} references ${te(b)}.${I}, which it does not have`)}let m=new Set;for(let a of t.raw)n(Z("a raw unit",a.name)),m.has(a.name)&&e.push(`raw unit ${a.name} is declared twice`),m.add(a.name),a.sql.trim()||e.push(`raw unit ${a.name} has no SQL`),a.before&&a.table!==void 0&&e.push(`raw unit ${a.name}: before is for a schema's unit, not a table's \u2014 a table's is made after its table`);return e}function It(t){let e=n=>[...n].sort((s,i)=>s.name<i.name?-1:s.name>i.name?1:0);return{tables:[...t.tables].map(n=>({...n,schema:n.schema||"public",columns:n.columns.map(s=>({...s,type:et(s.type)})),uniques:e(n.uniques),indexes:e(n.indexes),checks:e(n.checks),foreignKeys:e(n.foreignKeys),policies:e(n.policies).map(s=>({...s,to:[...s.to].sort()}))})).sort((n,s)=>te(n)<te(s)?-1:te(n)>te(s)?1:0),enums:[...t.enums].sort((n,s)=>`${n.schema}.${n.name}`<`${s.schema}.${s.name}`?-1:1),extensions:[...new Set([...t.extensions,...t.tables.some(n=>n.search!==void 0)?[yn]:[]])].sort(),raw:e(t.raw),...t.access!==void 0?{access:t.access}:{}}}function ps(t){let e=It(t),n=new Map(t.raw.map((s,i)=>[s.name,i]));return e.raw.sort((s,i)=>(n.get(s.name)??0)-(n.get(i.name)??0)),e}function Ze(t){return Array.isArray(t)?`[${t.map(Ze).join(",")}]`:t&&typeof t=="object"?`{${Object.entries(t).filter(([,n])=>n!==void 0).sort(([n],[s])=>n<s?-1:1).map(([n,s])=>`${JSON.stringify(n)}:${Ze(s)}`).join(",")}}`:JSON.stringify(t)}function ms(t){return fn("sha256").update(Ze(It(t))).digest("hex").slice(0,32)}var st=Symbol.for("palbase.table.meta"),ue=Symbol.for("palbase.ref.target"),ve=class{_def;constructor(e){if(e.trim()==="")throw new Error("foreignKey(name): a foreign key's name cannot be empty \u2014 Palbase reconciles constraints by name.");this._def={name:e,columns:[],refTable:"",refColumns:[]}}on(...e){return this._def.columns=e.map(n=>{let s=n.expr;if(s.kind!=="col")throw new Error(`foreignKey(${this._def.name}).on(): takes column references only \u2014 an expression cannot be part of a foreign key.`);return s.name}),this}references(e,...n){if(n.length===0)throw new Error(`foreignKey(${this._def.name}).references(): needs at least one target column.`);return this._def.refColumns=[...n],typeof e=="function"?(Object.defineProperty(this._def,ue,{value:()=>e()[st],enumerable:!1,configurable:!0}),this):(this._def.refTable=e[st].name,Object.defineProperty(this._def,ue,{value:e[st],enumerable:!1,configurable:!0}),this)}onUpdate(e){return this._def.onUpdate=e,this}onDelete(e){return this._def.onDelete=e,this}match(e){return this._def.match=e,this}index(e){if(e!==!1)throw new Error(`foreignKey(${this._def.name}).index(): only index(false) \u2014 an index is made unasked`);return this._def.index=!1,this}deferrable(e){if(e!==!1)throw new Error(`foreignKey(${this._def.name}).deferrable(): only deferrable(false) \u2014 a key with an action is deferrable unasked`);return this._def.deferrable=!1,this}};function Tn(t){return new ve(t)}function Lt(t){let e=t instanceof ve?t._def:t;if(e.columns.length===0)throw new Error(`foreignKey(${e.name}): needs at least one local column \u2014 call .on(...).`);let n=typeof e[ue]=="function";if(e.refColumns.length===0||e.refTable===""&&!n)throw new Error(`foreignKey(${e.name}): needs the target table and its columns \u2014 call .references(...).`);if(e.columns.length!==e.refColumns.length)throw new Error(`foreignKey(${e.name}): ${e.columns.length} local column(s) (${e.columns.join(", ")}) but ${e.refColumns.length} target column(s) (${e.refColumns.join(", ")}) \u2014 the two lists must be the same length.`);return e}var _=class extends Error{code;line;constructor(e,n,s=0){super(s>0?`line ${s}: ${n}`:n),this.name="AccessError",this.code=e,this.line=s}};var Nn=["->","!=","<=",">=","<>",":",",","=","<",">","+","&","-","(",")",".","|"],kt=256*1024,jt=256,Dt=32;function wn(t){if(t.length>kt)throw new _("too_large",`the schema is ${t.length} characters; at most ${kt}`);let e=[],n=0,s=1,i=r=>{throw new _("syntax",r,s)};for(;n<t.length;){let r=t[n];if(r===`
5
+ `){e.push({k:"nl",v:`
6
+ `,line:s,at:n,end:n+1}),s++,n++;continue}if(r===" "||r===" "||r==="\r"){n++;continue}if(r==="#"||r==="/"&&t[n+1]==="/"){for(;n<t.length&&t[n]!==`
7
+ `;)n++;continue}if(/[A-Za-z_]/.test(r)){let a=n+1;for(;a<t.length&&/[A-Za-z0-9_]/.test(t[a]);)a++;e.push({k:"word",v:t.slice(n,a),line:s,at:n,end:a}),n=a;continue}if(/[0-9]/.test(r)){let a=n+1;for(;a<t.length&&/[0-9]/.test(t[a]);)a++;if(t[a]==="."&&/[0-9]/.test(t[a+1]??""))for(a++;a<t.length&&/[0-9]/.test(t[a]);)a++;/[A-Za-z_]/.test(t[a]??"")&&i(`"${t.slice(n,a+1)}" is not a number`),e.push({k:"number",v:t.slice(n,a),line:s,at:n,end:a}),n=a;continue}if(r==='"'||r==="'"){let a=n+1,p="";for(;;){if((a>=t.length||t[a]===`
8
+ `)&&i(r==='"'?"a quoted name is not closed":"a text value is not closed"),t[a]===r){if(t[a+1]===r){p+=r,a+=2;continue}break}p+=t[a],a++}p.includes("\0")&&i("a NUL character cannot be in a name or a value"),r==='"'&&p===""&&i("a quoted name is empty"),e.push({k:r==='"'?"quoted":"string",v:p,line:s,at:n,end:a+1}),n=a+1;continue}let m=Nn.find(a=>t.startsWith(a,n));m||i(`unexpected character ${JSON.stringify(r)}`),e.push({k:"sym",v:m,line:s,at:n,end:n+m.length}),n+=m.length}return e.push({k:"nl",v:`
9
+ `,line:s,at:n,end:n}),e.push({k:"end",v:"",line:s,at:n,end:n}),e}var _n=["select","insert","update","delete"];function ge(t){let e=wn(t),n=0,s=(o=0)=>e[Math.min(n+o,e.length-1)],i=()=>e[Math.min(n++,e.length-1)],r=(o,u=s())=>{throw new _("syntax",o,u.line)},m=o=>o.k==="nl"?"the end of the line":o.k==="end"?"the end of the schema":`"${o.v}"`,a=(o,u=0)=>s(u).k==="sym"&&s(u).v===o,p=(o,u=0)=>s(u).k==="word"&&s(u).v===o,b=(o,u)=>(a(o)||r(`expected "${o}" ${u}, found ${m(s())}`),i()),I=()=>{for(;s().k==="nl";)i()},j=o=>{s().k!=="nl"&&s().k!=="end"&&r(`unexpected ${m(s())} after ${o}`)},L=o=>{let u=i();u.k!=="word"&&r(`expected ${o}, found ${m(u)}`,u);let l=u.v,f=s(),y=s(1);return f.k==="sym"&&f.v==="."&&f.at===u.end&&y.k==="word"&&y.at===f.end&&(i(),i(),l+=`.${y.v}`),l},v=o=>{let u=i();return u.k!=="word"&&u.k!=="quoted"&&r(`expected ${o}, found ${m(u)}`,u),u.v},E=()=>{let o=i();return o.k==="string"?(o.v.length>jt&&r(`a value is at most ${jt} characters; this one has ${o.v.length}`,o),{t:"string",v:o.v}):o.k==="number"?{t:"number",v:o.v}:o.k==="sym"&&o.v==="-"&&s().k==="number"&&s().at===o.end?{t:"number",v:`-${i().v}`}:o.k==="word"&&(o.v==="true"||o.v==="false")?{t:"boolean",v:o.v==="true"}:r(`expected a value ('text', a number, true or false), found ${m(o)}`,o)},k=0,G=o=>{if(++k>Dt)throw new _("too_deep",`parentheses and "not" nested more than ${Dt} deep`,s().line);try{return o()}finally{k--}},q=()=>{let o=P();if(!p("and")&&!p("or"))return o;let u=s().v,l=[o];for(;p("and")||p("or");)s().v!==u&&r(`"${u}" and "${s().v}" in one condition: put parentheses around one of them`),i(),l.push(P());return{op:u,parts:l}},P=()=>{if(p("not"))return i(),{op:"not",part:G(P)};if(a("(")){i();let l=G(q);return b(")","to close the condition"),l}let o=v("a column");if(p("is")){i();let l=!1;return p("not")&&(i(),l=!0),p("null")||r(`expected "null" after "is", found ${m(s())}`),i(),{op:"null",column:o,negated:l}}if(p("in")){i(),b("(",'after "in"');let l=[E()];for(;a(",");)i(),l.push(E());return b(")","to close the list"),{op:"in",column:o,values:l}}let u=i();return(u.k!=="sym"||!["=","!=","<>","<","<=",">",">="].includes(u.v))&&r(`expected a comparison after "${o}", found ${m(u)}`,u),{op:"cmp",column:o,cmp:u.v==="<>"?"!=":u.v,value:E()}},$=()=>{let o=h(),u=()=>{let R=0;for(;s(R).k==="nl";)R++;let g=s(R),U=g.k!=="sym"?null:g.v==="+"?"union":g.v==="&"?"intersect":g.v==="-"?"exclude":null;return U!==null&&(n+=R),U},l=u();if(l===null)return o;let f=o,y=[o];for(;;){let R=u();if(R===null)break;R!==l&&r(`"${s().v}" beside another operator: put parentheses around one of them`),i(),I();let g=h();l==="exclude"?f={op:"exclude",base:f,minus:g}:y.push(g)}return l==="exclude"?f:{op:l,parts:y}},h=()=>{if(a("(")){i(),I();let u=G($);return I(),b(")","to close the expression"),u}let o=L("a relation or a permission");return a("->")?(i(),{op:"arrow",relation:o,name:L('a relation or a permission after "->"')}):{op:"ref",name:o}},x=[];for(I();s().k!=="end";){p("type")||r(`expected "type", found ${m(s())}`);let o=i(),u={name:L("the type's name"),table:null,relations:[],permissions:[],rows:[],line:o.line};for(j("the type's name"),I();s().k!=="end"&&!p("type");){let l=i();if(l.k!=="word"&&r(`expected "table", "relation", "permission" or "rows", found ${m(l)}`,l),l.v==="table"){u.table&&r(`type ${u.name} names its table twice`,l);let f=null,y=v("a table");a(".")&&(i(),f=y,y=v("a table"));let R=null;p("key")&&(i(),R=v("the key column")),u.table={schema:f,name:y,key:R,line:l.line},j("the table")}else if(l.v==="relation"){let f=[L("the relation's name")];for(;a(",");)i(),f.push(L("a relation's name"));b(":","after the relation's name");let y=[L('"user" or a type')];for(;a("|");)i(),y.push(L('"user" or a type'));if(p("from")){i(),f.length>1&&r("a relation read from a column is declared alone, one per line",l),y.length>1&&r("a relation read from a column has one kind of subject",l);let R=v("a column"),g=null;p("where")&&(i(),g=q()),u.relations.push({kind:"column",name:f[0],subject:y[0],column:R,where:g,line:l.line})}else for(let R of f)u.relations.push({kind:"stored",name:R,subjects:[...y],line:l.line});j("the relation")}else if(l.v==="permission"){let f=L("the permission's name");b("=","after the permission's name"),I(),u.permissions.push({name:f,expr:$(),line:l.line}),j("the permission")}else if(l.v==="rows"){let f=[];for(;;){let y=i();if((y.k!=="word"||!_n.includes(y.v))&&r(`expected select, insert, update or delete, found ${m(y)}`,y),f.push(y.v),!a(","))break;i()}b(":","after the commands"),u.rows.push({commands:f,name:L("a permission"),line:l.line}),j("the rows rule")}else r(`expected "table", "relation", "permission" or "rows", found "${l.v}"`,l);I()}x.push(u)}return{types:x}}var K="user",ot=16,Ft=200,Mt=100,Ut=200,vt=200,Pt=50,Gt=25e3,Ht=300,it=150,xn=2,An=4,Kt=63,On=/^[a-z][a-z0-9_]{0,39}$/,Sn=/^[a-z][a-z0-9_]{0,39}(\.[a-z][a-z0-9_]{0,39})?$/,Ge=t=>t.replace(".","__"),Ee=t=>t.kind==="stored"?t.subjects.includes(K):t.subject===K,ne=t=>t.kind==="stored"?t.subjects.filter(e=>e!==K):t.subject===K?[]:[t.subject];function Pe(t){return t.op==="ref"||t.op==="arrow"?1:t.op==="exclude"?1+Pe(t.base)+Pe(t.minus):1+t.parts.reduce((e,n)=>e+Pe(n),0)}function _e(t){return"parts"in t?t.parts.reduce((e,n)=>e+_e(n),0):t.op==="not"?_e(t.part):t.op==="in"?t.values.length:1}function rt(t,e){if("parts"in t)for(let n of t.parts)rt(n,e);else t.op==="not"?rt(t.part,e):e.add(t.column)}function at(t){let e=new Set;return t&&rt(t,e),[...e]}function he(t){if(t.types.length>Ft)throw new _("too_large",`${t.types.length} types; at most ${Ft}`);let e=new Map;for(let $ of t.types){if($.name===K)throw new _("invalid_name",'"user" is whoever asks: a type cannot be called that',$.line);if(!On.test($.name)||$.name.includes("__"))throw new _("invalid_name",`type "${$.name}" is not a name: lowercase letters, digits and single underscores, starting with a letter, at most 40`,$.line);if(e.has($.name))throw new _("duplicate",`type "${$.name}" is declared twice`,$.line);let h=new Map,x=new Map,o=new Map,u=(l,f,y)=>{if(!Sn.test(l)||l.includes("__"))throw new _("invalid_name",`${y} "${l}" is not a name: lowercase letters, digits and single underscores, with at most one dot (code.write), at most 40 each side`,f);if(h.has(l)||x.has(l))throw new _("duplicate",`"${l}" is declared twice in type ${$.name}`,f);let R=Ge(l),g=`${$.name}__${R}`;if(g.length>Kt)throw new _("invalid_name",`${y} "${l}" of type ${$.name}: together they are asked as access.${g} \u2014 ${g.length} characters, and a name in the database holds ${Kt}. Shorten the type's name or this one`,f);let U=o.get(R);if(U!==void 0)throw new _("duplicate",`"${l}" and "${U}" of type ${$.name} would have one name in the database`,f);o.set(R,l)};for(let l of $.relations)u(l.name,l.line,"relation"),h.set(l.name,l);for(let l of $.permissions){if(u(l.name,l.line,"permission"),Pe(l.expr)>Ut)throw new _("too_large",`permission ${$.name}.${l.name} has more than ${Ut} terms`,l.line);x.set(l.name,l)}if(h.size+x.size>Mt)throw new _("too_large",`type ${$.name} declares more than ${Mt} names`,$.line);e.set($.name,{name:$.name,table:$.table?{schema:$.table.schema??"public",name:$.table.name,key:$.table.key}:null,relations:h,permissions:x,rows:[]})}let n=new Map;for(let $ of e.values()){if(!$.table)continue;let h=`${$.table.schema}\0${$.table.name}`,x=n.get(h);if(x!==void 0)throw new _("duplicate",`types ${x} and ${$.name} name the same table`,t.types.find(o=>o.name===$.name)?.line??0);n.set(h,$.name)}for(let $ of t.types){let h=e.get($.name);for(let x of $.relations)if(x.kind==="stored"){let o=new Set;for(let u of x.subjects){if(o.has(u))throw new _("duplicate",`relation ${h.name}.${x.name} names "${u}" twice`,x.line);if(o.add(u),u!==K&&!e.has(u))throw new _("unknown_type",`relation ${h.name}.${x.name}: there is no type "${u}"`,x.line)}}else{if(!h.table)throw new _("needs_table",`relation ${h.name}.${x.name} reads a column, and type ${h.name} names no table`,x.line);if(x.where&&_e(x.where)>Pt)throw new _("too_large",`relation ${h.name}.${x.name}: its condition holds more than ${Pt} comparisons`,x.line);if(x.subject!==K&&!e.has(x.subject))throw new _("unknown_type",`relation ${h.name}.${x.name}: there is no type "${x.subject}"`,x.line)}}let s=($,h)=>{let x=e.get($);return x.relations.get(h)??x.permissions.get(h)},i=($,h)=>e.get($).permissions.has(h),r=($,h)=>{let x=e.get($);if(x.permissions.has(h))return"yes";let o=x.relations.get(h);return o?Ee(o)?"yes":"objects":"missing"},m=new Map,a=($,h)=>`${$}\0${h}`;for(let $ of t.types){let h=e.get($.name);for(let o of $.permissions){let u=[],l=f=>{if(f.op==="ref"){let y=r(h.name,f.name);if(y==="missing")throw new _("unknown_name",`permission ${h.name}.${o.name}: type ${h.name} has no relation or permission "${f.name}"`,o.line);if(y==="objects")throw new _("not_a_holder",`permission ${h.name}.${o.name}: relation "${f.name}" leads to objects, no subject holds it \u2014 follow it with "->", as in ${f.name}->view`,o.line);u.push({type:h.name,name:f.name})}else if(f.op==="arrow"){let y=h.relations.get(f.relation);if(!y){let g=h.permissions.has(f.relation)?`"${f.relation}" is a permission; an arrow follows a relation`:`type ${h.name} has no relation "${f.relation}"`;throw new _("unknown_name",`permission ${h.name}.${o.name}: ${g}`,o.line)}let R=ne(y);if(R.length===0)throw new _("not_an_object_relation",`permission ${h.name}.${o.name}: relation "${f.relation}" leads to no object (its subjects are users), so "->" has nothing to follow`,o.line);for(let g of R){let U=r(g,f.name);if(U==="missing")throw new _("unknown_name",`permission ${h.name}.${o.name}: ${f.relation}->${f.name} \u2014 type ${g} has no relation or permission "${f.name}"`,o.line);if(U==="objects")throw new _("not_a_holder",`permission ${h.name}.${o.name}: ${f.relation}->${f.name} \u2014 "${f.name}" of type ${g} leads to objects, no subject holds it`,o.line);u.push({type:g,name:f.name})}}else if(f.op==="exclude")l(f.base),l(f.minus);else for(let y of f.parts)l(y)};l(o.expr),m.set(a(h.name,o.name),u)}let x=new Set;for(let o of $.rows){if(!h.table)throw new _("needs_table",`type ${h.name} has a rows rule and names no table`,o.line);let u=r(h.name,o.name);if(u==="missing")throw new _("unknown_name",`rows rule of type ${h.name}: there is no relation or permission "${o.name}"`,o.line);if(u==="objects")throw new _("not_a_holder",`rows rule of type ${h.name}: relation "${o.name}" leads to objects, no subject holds it`,o.line);for(let l of o.commands){if(x.has(l))throw new _("duplicate",`type ${h.name} has two rows rules for ${l}`,o.line);x.add(l),h.rows.push({command:l,name:o.name})}}}let p=[],b=new Map,I=($,h)=>s($,h)?.line??0,j=($,h,x)=>{let o=a($,h),u=b.get(o);if(typeof u=="number")return u;let l=`${$}.${h}`;if(u==="open"){let y=x.indexOf(l),R=[...x.slice(y),l].join(" \u2192 ");throw new _("cycle",`${R}: a permission derived from itself. A type that contains itself (a folder in a folder) is not supported; fixed levels are (company, product, session), however many`,I($,h))}b.set(o,"open");let f=0;if(i($,h))for(let y of m.get(o)??[])f=Math.max(f,1+j(y.type,y.name,[...x,l]));if(f>ot)throw new _("too_deep",`${l} is derived through more than ${ot} levels`,I($,h));return b.set(o,f),p.push({type:$,name:h}),f};for(let $ of e.values()){for(let h of $.relations.values())j($.name,h.name,[]);for(let h of $.permissions.values())j($.name,h.name,[])}let L=new Map,v=($,h)=>{let x=a($,h),o=L.get(x);if(o!==void 0)return o;let u=e.get($),l=u.permissions.get(h),f=R=>R.op==="ref"?v($,R.name):R.op==="arrow"?1+ne(u.relations.get(R.relation)).reduce((g,U)=>g+v(U,R.name),0):R.op==="exclude"?f(R.base)+f(R.minus):R.parts.reduce((g,U)=>g+f(U),0),y=l?f(l.expr):1;return L.set(x,y),y};for(let $ of e.values())for(let h of $.permissions.values()){let x=v($.name,h.name);if(x>vt)throw new _("too_large",`permission ${$.name}.${h.name} comes to ${x} relations once everything it is derived from is written out; at most ${vt}. It names the same permissions through several paths \u2014 derive it from fewer, or from relations directly`,h.line)}let E=new Map,k=($,h)=>{let x=a($,h),o=E.get(x);if(o!==void 0)return o;let u=e.get($),l=u.permissions.get(h),f=g=>g&&g.kind==="column"&&g.where?1+_e(g.where):1,y=g=>g.op==="ref"?k($,g.name):g.op==="arrow"?f(u.relations.get(g.relation)):g.op==="exclude"?y(g.base)+y(g.minus):g.parts.reduce((U,ee)=>U+y(ee),0),R=l?y(l.expr):f(u.relations.get(h));return E.set(x,R),R},G=new Map,q=($,h)=>{let x=a($,h),o=G.get(x);if(o!==void 0)return o;let u=e.get($),l=u.permissions.get(h),f=g=>g&&g.kind==="column"&&g.where?1+_e(g.where):1,y=g=>{if(g.op==="ref")return q($,g.name);if(g.op==="arrow"){let U=u.relations.get(g.relation),ee=U.kind==="column"?xn:An;return f(U)+ee*ne(U).reduce((je,De)=>je+q(De,g.name),0)}return g.op==="exclude"?y(g.base)+y(g.minus):g.parts.reduce((U,ee)=>U+y(ee),0)},R=l?y(l.expr):f(u.relations.get(h));return G.set(x,R),R};for(let $ of e.values())for(let h of $.permissions.values()){let x=q($.name,h.name);if(x>Ht)throw new _("too_large",`permission ${$.name}.${h.name} would be planned as ${x} lookups \u2014 what it reads through another type is planned inside it, two or four times over; at most ${Ht} (about 140 KB of the database's memory each, on every statement it guards). Read fewer levels deep through other types' permissions, or through relations read from columns`,h.line)}let P=0;for(let $ of e.values())for(let h of[...$.relations.keys(),...$.permissions.keys()])P+=k($.name,h);if(P>Gt)throw new _("too_large",`the schema comes to ${P} terms once each of its names is written out in full (a permission with what it names, a relation with its condition); at most ${Gt}. Derive permissions from one another's names through fewer copies, or shorten the conditions they repeat`);return{types:e,order:p,planned:q}}var xe=63,O=t=>{if(t.includes("\0"))throw new TypeError("a NUL character cannot be in a name");if(new TextEncoder().encode(t).length>xe)throw new _("invalid_name",`"${t}" is longer than the ${xe} bytes a name in the database holds`);return`"${t.replace(/"/g,'""')}"`},ct=(t,e)=>`${O(t)}.${O(e)}`;function T(t){if(t.includes("\0"))throw new TypeError("a NUL character cannot be sent to Postgres");return`E'${t.replace(/\\/g,"\\\\").replace(/'/g,"''")}'`}function D(t){let e="access";for(let n=0;t.includes(`$${e}$`);n++)e=`access${n}`;return`$${e}$${t}$${e}$`}var Cn={text:"text",varchar:"text",uuid:"uuid",int2:"int",int4:"int",int8:"int",bool:"bool",numeric:"numeric",float4:"numeric",float8:"numeric"};function lt(t){let e=typeof t=="string"?JSON.parse(t):t;if(!Array.isArray(e))throw new _("syntax","the catalog could not be read: its answer is not a list of tables");let n=new Map;for(let s of e){let i=new Map;for(let r of s.columns)i.set(r.name,{type:r.type,family:r.array?null:r.enum?"enum":Cn[r.type]??null});n.set(`${s.schema}\0${s.name}`,{schema:s.schema,name:s.name,kind:s.kind,primaryKey:s.pk,identifying:s.identifying??(s.pk.length===1?[...s.pk]:[]),columns:i,forcesRowSecurity:s.force,hasChildren:s.children===!0,hasParent:s.parent===!0,indexes:Number(s.indexes??(s.pk.length>0?1:0))})}return{table:(s,i)=>n.get(`${s}\0${i}`)}}function ut(t){return lt(t.map(e=>({schema:e.schema??"public",name:e.name,kind:"r",force:e.forcesRowSecurity??!1,pk:e.primaryKey,...e.identifying===void 0?{}:{identifying:e.identifying},...e.indexes===void 0?{}:{indexes:e.indexes},columns:Object.entries(e.columns).map(([n,s])=>({name:n,type:s,enum:e.enums?.includes(n)??!1,array:!1}))})))}var V="access",$e="palbase access",Ae="2",oe=["!access_fresh","!access_forget","!access_move","!access_empty"],pt=[...oe].sort((t,e)=>Buffer.from(t)<Buffer.from(e)?-1:1).at(-1),mt=t=>`(${t}.tgtype & 66) = 0 AND ${t}.tgname COLLATE "C" < ${T(pt)}`,Oe={authenticated:"authenticated",service:"service_role"},dt="^-?[0-9]{1,18}$",He="^[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}$",Se=256,B={unknown:"PA001",noObject:"PA002",badId:"PA003",tooMany:"PA004",notTaken:"PA005",notAllowed:"PA006"},W="SET search_path = pg_catalog, pg_temp";function Ke(t=Oe){let e=O(V),n=`${O(t.authenticated)}, ${O(t.service)}`,s=O(t.service);return[`CREATE SCHEMA IF NOT EXISTS ${e}`,`COMMENT ON SCHEMA ${e} IS ${T($e)}`,`CREATE TABLE IF NOT EXISTS ${e}.relationships (
10
+ object_type text NOT NULL, object_id text NOT NULL, relation text NOT NULL,
11
+ subject_type text NOT NULL, subject_id text NOT NULL,
12
+ created_at timestamptz NOT NULL DEFAULT now(),
13
+ given_in xid8 NOT NULL DEFAULT pg_current_xact_id(),
14
+ PRIMARY KEY (object_type, object_id, relation, subject_type, subject_id))`,`ALTER TABLE ${e}.relationships ADD COLUMN IF NOT EXISTS given_in xid8 NOT NULL DEFAULT pg_current_xact_id()`,`CREATE INDEX IF NOT EXISTS relationships_by_subject ON ${e}.relationships (subject_type, subject_id, object_type, relation, object_id)`,`CREATE TABLE IF NOT EXISTS ${e}.history (
15
+ id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
16
+ at timestamptz NOT NULL DEFAULT now(),
17
+ action text NOT NULL CHECK (action IN ('grant', 'revoke')),
18
+ object_type text NOT NULL, object_id text NOT NULL, relation text NOT NULL,
19
+ subject_type text NOT NULL, subject_id text NOT NULL,
20
+ actor text)`,`CREATE INDEX IF NOT EXISTS history_by_object ON ${e}.history (object_type, object_id, id DESC)`,`CREATE INDEX IF NOT EXISTS history_by_subject ON ${e}.history (subject_type, subject_id, id DESC)`,`CREATE TABLE IF NOT EXISTS ${e}.objects_touched (
21
+ object_type text NOT NULL, object_id text NOT NULL, touched xid8 NOT NULL DEFAULT pg_current_xact_id(),
22
+ PRIMARY KEY (object_type, object_id))`,`DROP FUNCTION IF EXISTS ${e}.moved_objects() CASCADE`,`DROP TABLE IF EXISTS ${e}.moves`,`CREATE TABLE IF NOT EXISTS ${e}.schemas (
23
+ digest text PRIMARY KEY, text text NOT NULL, engine text NOT NULL,
24
+ applied_at timestamptz NOT NULL DEFAULT now(), applied_by text NOT NULL DEFAULT session_user,
25
+ active boolean NOT NULL DEFAULT false)`,`CREATE OR REPLACE FUNCTION ${e}.may_name_a_subject() RETURNS boolean LANGUAGE sql STABLE ${W} AS ${D(`
26
+ SELECT pg_has_role(o.role, ${T(t.service)}, 'MEMBER')
27
+ OR EXISTS (SELECT 1 FROM pg_namespace n WHERE n.nspname = ${T(V)} AND pg_has_role(o.role, n.nspowner, 'MEMBER'))
28
+ FROM (SELECT CASE WHEN current_setting('role') IN ('none', '') THEN session_user ELSE current_setting('role')::name END AS role) o`)}`,`CREATE OR REPLACE FUNCTION ${e}.subject() RETURNS text LANGUAGE sql STABLE ${W} AS ${D(`
29
+ SELECT CASE WHEN ${e}.may_name_a_subject()
30
+ THEN coalesce(nullif(current_setting('access.subject', true), ''), c.sub)
31
+ ELSE c.sub END
32
+ FROM (SELECT nullif((nullif(current_setting('request.jwt.claims', true), ''))::jsonb ->> 'sub', '') AS sub) c`)}`,`CREATE OR REPLACE FUNCTION ${e}.subject_uuid() RETURNS uuid LANGUAGE sql STABLE ${W} AS ${D(`
33
+ SELECT CASE WHEN s ~ ${T(He)} THEN s::uuid END FROM (SELECT ${e}.subject() AS s) q`)}`,`CREATE OR REPLACE FUNCTION ${e}.subject_int() RETURNS bigint LANGUAGE sql STABLE ${W} AS ${D(`
34
+ SELECT CASE WHEN s ~ ${T(dt)} THEN s::bigint END FROM (SELECT ${e}.subject() AS s) q`)}`,`CREATE OR REPLACE FUNCTION ${e}.act_as(subject text) RETURNS void LANGUAGE plpgsql VOLATILE ${W} AS ${D(`
35
+ BEGIN
36
+ IF NOT ${e}.may_name_a_subject() THEN
37
+ RAISE EXCEPTION USING ERRCODE = ${T(B.notAllowed)}, MESSAGE = 'this role asks for itself alone: it cannot ask as another subject';
38
+ END IF;
39
+ PERFORM set_config('access.subject', coalesce(subject, ''), true);
40
+ END`)}`,`CREATE OR REPLACE FUNCTION ${e}.touch(object_type text, object_ids text[]) RETURNS void LANGUAGE sql VOLATILE SECURITY DEFINER ${W} AS ${D(`
41
+ INSERT INTO ${e}.objects_touched (object_type, object_id, touched)
42
+ SELECT $1, i, pg_current_xact_id() FROM unnest($2) AS i WHERE i IS NOT NULL ORDER BY 2
43
+ ON CONFLICT (object_type, object_id) DO UPDATE SET touched = excluded.touched`)}`,`CREATE OR REPLACE FUNCTION ${e}.older_snapshot() RETURNS boolean LANGUAGE sql STABLE ${W} AS ${D(`
44
+ SELECT current_setting('transaction_isolation') NOT IN ('read committed', 'read uncommitted')`)}`,`CREATE OR REPLACE FUNCTION ${e}.refuse(state text, message text) RETURNS boolean LANGUAGE plpgsql STABLE ${W} AS ${D(`
45
+ BEGIN RAISE EXCEPTION USING ERRCODE = state, MESSAGE = message; END`)}`,`CREATE OR REPLACE FUNCTION ${e}.refuse_text(state text, message text) RETURNS text LANGUAGE plpgsql STABLE ${W} AS ${D(`
46
+ BEGIN RAISE EXCEPTION USING ERRCODE = state, MESSAGE = message; END`)}`,`CREATE OR REPLACE FUNCTION ${e}.record() RETURNS trigger LANGUAGE plpgsql SECURITY DEFINER ${W} AS ${D(`
47
+ DECLARE who text := coalesce(nullif(current_setting('access.actor', true), ''), ${e}.subject(), session_user::text);
48
+ BEGIN
49
+ IF TG_OP <> 'INSERT' THEN
50
+ INSERT INTO ${e}.history (action, object_type, object_id, relation, subject_type, subject_id, actor)
51
+ VALUES ('revoke', OLD.object_type, OLD.object_id, OLD.relation, OLD.subject_type, OLD.subject_id, who);
52
+ END IF;
53
+ IF TG_OP <> 'DELETE' THEN
54
+ INSERT INTO ${e}.history (action, object_type, object_id, relation, subject_type, subject_id, actor)
55
+ VALUES ('grant', NEW.object_type, NEW.object_id, NEW.relation, NEW.subject_type, NEW.subject_id, who);
56
+ END IF;
57
+ RETURN NULL;
58
+ END`)}`,`CREATE OR REPLACE TRIGGER record AFTER INSERT OR UPDATE OR DELETE ON ${e}.relationships FOR EACH ROW EXECUTE FUNCTION ${e}.record()`,`CREATE OR REPLACE FUNCTION ${e}.forget_object() RETURNS trigger LANGUAGE plpgsql SECURITY DEFINER ${W} AS ${D(`
59
+ DECLARE gone text := to_jsonb(OLD) ->> TG_ARGV[1]; was text := current_setting('access.actor', true);
60
+ BEGIN
61
+ IF gone IS NULL THEN RETURN NULL; END IF;
62
+ IF ${e}.older_snapshot() THEN PERFORM ${e}.touch(TG_ARGV[0], ARRAY[gone]); END IF;
63
+ PERFORM set_config('access.actor', 'access: row deleted', true);
64
+ DELETE FROM ${e}.relationships WHERE object_type = TG_ARGV[0] AND object_id = gone;
65
+ DELETE FROM ${e}.relationships WHERE subject_type = TG_ARGV[0] AND subject_id = gone;
66
+ DELETE FROM ${e}.objects_touched WHERE object_type = TG_ARGV[0] AND object_id = gone;
67
+ PERFORM set_config('access.actor', coalesce(was, ''), true);
68
+ RETURN NULL;
69
+ END`)}`,`CREATE OR REPLACE FUNCTION ${e}.move_object() RETURNS trigger LANGUAGE plpgsql SECURITY DEFINER ${W} AS ${D(`
70
+ DECLARE old_id text := to_jsonb(OLD) ->> TG_ARGV[1]; new_id text := to_jsonb(NEW) ->> TG_ARGV[1]; was text := current_setting('access.actor', true);
71
+ BEGIN
72
+ IF old_id IS NULL OR new_id IS NULL OR old_id = new_id THEN RETURN NULL; END IF;
73
+ IF ${e}.older_snapshot() THEN PERFORM ${e}.touch(TG_ARGV[0], ARRAY[old_id, new_id]); END IF;
74
+ PERFORM set_config('access.actor', 'access: id used again', true);
75
+ DELETE FROM ${e}.relationships WHERE object_type = TG_ARGV[0] AND object_id = new_id;
76
+ DELETE FROM ${e}.relationships WHERE subject_type = TG_ARGV[0] AND subject_id = new_id;
77
+ PERFORM set_config('access.actor', 'access: key changed', true);
78
+ UPDATE ${e}.relationships SET object_id = new_id WHERE object_type = TG_ARGV[0] AND object_id = old_id;
79
+ UPDATE ${e}.relationships SET subject_id = new_id WHERE subject_type = TG_ARGV[0] AND subject_id = old_id;
80
+ DELETE FROM ${e}.objects_touched WHERE object_type = TG_ARGV[0] AND object_id = new_id;
81
+ UPDATE ${e}.objects_touched SET object_id = new_id WHERE object_type = TG_ARGV[0] AND object_id = old_id;
82
+ PERFORM set_config('access.actor', coalesce(was, ''), true);
83
+ RETURN NULL;
84
+ END`)}`,`CREATE OR REPLACE FUNCTION ${e}.fresh_objects() RETURNS trigger LANGUAGE plpgsql SECURITY DEFINER ${W} AS ${D(`
85
+ DECLARE made text := to_jsonb(NEW) ->> TG_ARGV[1]; cur xid8 := pg_current_xact_id(); was text := current_setting('access.actor', true);
86
+ BEGIN
87
+ IF made IS NULL THEN RETURN NULL; END IF;
88
+ IF NOT EXISTS (SELECT 1 FROM ${e}.relationships r WHERE r.object_type = TG_ARGV[0] AND r.object_id = made AND r.given_in <> cur)
89
+ AND NOT EXISTS (SELECT 1 FROM ${e}.relationships r WHERE r.subject_type = TG_ARGV[0] AND r.subject_id = made AND r.given_in <> cur) THEN
90
+ RETURN NULL;
91
+ END IF;
92
+ PERFORM set_config('access.actor', 'access: id used again', true);
93
+ DELETE FROM ${e}.relationships WHERE object_type = TG_ARGV[0] AND object_id = made AND given_in <> cur;
94
+ DELETE FROM ${e}.relationships WHERE subject_type = TG_ARGV[0] AND subject_id = made AND given_in <> cur;
95
+ PERFORM set_config('access.actor', coalesce(was, ''), true);
96
+ RETURN NULL;
97
+ END`)}`,`CREATE OR REPLACE FUNCTION ${e}.forget_all() RETURNS trigger LANGUAGE plpgsql SECURITY DEFINER ${W} AS ${D(`
98
+ DECLARE was text := current_setting('access.actor', true);
99
+ BEGIN
100
+ IF ${e}.older_snapshot() THEN
101
+ RAISE EXCEPTION USING ERRCODE = '55000', MESSAGE = format('TRUNCATE of the table of type %s: in a READ COMMITTED transaction \u2014 by an older snapshot, relationships given since could not be taken with its rows', TG_ARGV[0]);
102
+ END IF;
103
+ PERFORM set_config('access.actor', 'access: table emptied', true);
104
+ DELETE FROM ${e}.relationships WHERE object_type = TG_ARGV[0];
105
+ DELETE FROM ${e}.relationships WHERE subject_type = TG_ARGV[0];
106
+ DELETE FROM ${e}.objects_touched WHERE object_type = TG_ARGV[0];
107
+ PERFORM set_config('access.actor', coalesce(was, ''), true);
108
+ RETURN NULL;
109
+ END`)}`,`CREATE OR REPLACE FUNCTION ${e}.binding_guard() RETURNS trigger LANGUAGE plpgsql ${W} AS ${D(`
110
+ DECLARE i int;
111
+ BEGIN
112
+ FOR i IN 1 .. TG_NARGS - 1 LOOP
113
+ IF NEW.object_type = TG_ARGV[i] OR NEW.subject_type = TG_ARGV[i] THEN
114
+ RAISE EXCEPTION USING ERRCODE = '55000', MESSAGE = format('type %s is being given a table by the deploy of version %s: its relationships can be given once that deploy completes', TG_ARGV[i], TG_ARGV[0]);
115
+ END IF;
116
+ END LOOP;
117
+ RETURN NEW;
118
+ END`)}`,`CREATE OR REPLACE FUNCTION ${e}.forget_subject(subject text) RETURNS bigint LANGUAGE plpgsql VOLATILE SECURITY DEFINER ${W} AS ${D(`
119
+ DECLARE n bigint; was text := current_setting('access.actor', true);
120
+ BEGIN
121
+ PERFORM set_config('access.actor', 'access: subject deleted', true);
122
+ DELETE FROM ${e}.relationships WHERE subject_type = 'user' AND subject_id = $1;
123
+ GET DIAGNOSTICS n = ROW_COUNT;
124
+ PERFORM set_config('access.actor', coalesce(was, ''), true);
125
+ RETURN n;
126
+ END`)}`,`CREATE OR REPLACE VIEW ${e}.mine WITH (security_barrier = true) AS
127
+ SELECT object_type, object_id, relation FROM ${e}.relationships
128
+ WHERE subject_type = 'user' AND subject_id = (SELECT ${e}.subject())`,`DROP FUNCTION IF EXISTS ${e}.speaks(text)`,`REVOKE ALL ON SCHEMA ${e} FROM PUBLIC`,`GRANT USAGE ON SCHEMA ${e} TO ${n}`,`REVOKE ALL ON ALL TABLES IN SCHEMA ${e} FROM PUBLIC`,`REVOKE ALL ON ${e}.relationships, ${e}.history, ${e}.schemas, ${e}.objects_touched, ${e}.mine FROM ${n}`,`GRANT SELECT ON ${e}.mine TO ${n}`,`GRANT SELECT ON ${e}.relationships, ${e}.history, ${e}.schemas TO ${s}`,`REVOKE ALL ON ALL FUNCTIONS IN SCHEMA ${e} FROM PUBLIC`,`REVOKE ALL ON FUNCTION ${e}.subject(), ${e}.subject_uuid(), ${e}.subject_int(), ${e}.may_name_a_subject(), ${e}.refuse(text, text), ${e}.refuse_text(text, text), ${e}.act_as(text), ${e}.forget_subject(text), ${e}.record(), ${e}.forget_object(), ${e}.move_object(), ${e}.fresh_objects(), ${e}.forget_all(), ${e}.binding_guard(), ${e}.touch(text, text[]), ${e}.older_snapshot() FROM ${n}`,`GRANT EXECUTE ON FUNCTION ${e}.subject(), ${e}.subject_uuid(), ${e}.subject_int(), ${e}.may_name_a_subject(), ${e}.refuse(text, text), ${e}.refuse_text(text, text) TO ${n}`,`GRANT EXECUTE ON FUNCTION ${e}.act_as(text), ${e}.forget_subject(text) TO ${s}`]}import{createHash as Wt,randomUUID as In}from"node:crypto";var ft=1e4,qt=1e5,Bt=1e4,Xt=1e6,pe=96*1024,Ce=100,J="SET search_path = pg_catalog, pg_temp",S=O(V),Vt=["text","uuid","int"],ye=(t,e)=>t==="int"?`(CASE WHEN ${e} ~ ${T(dt)} THEN (${e})::bigint END)`:t==="uuid"?`(CASE WHEN ${e} ~ ${T(He)} THEN (${e})::uuid END)`:e,Ln=t=>t==="int"?`(SELECT ${S}.subject_int())`:t==="uuid"?`(SELECT ${S}.subject_uuid())`:`(SELECT ${S}.subject())`;function kn(t,e){let n=new Map;for(let s of t.types.values()){if(!s.table){n.set(s.name,{name:s.name,model:s,table:null,family:"text",idType:"text"});continue}let i=`${s.table.schema}.${s.table.name}`,r=e.table(s.table.schema,s.table.name);if(!r)throw new _("unknown_table",`type ${s.name}: there is no table ${i}`);if(r.kind==="p"||r.hasChildren||r.hasParent)throw new _("not_supported",`type ${s.name}: ${i} is partitioned, a partition, or tied to another table by inheritance; a type's table is one plain table (its rows could be read past its rules through the other)`);if(r.kind!=="r")throw new _("not_supported",`type ${s.name}: ${i} is not a table (a view or a foreign table cannot carry a type)`);if(r.indexes>it)throw new _("too_large",`type ${s.name}: ${i} has ${r.indexes} indexes; a type's table has at most ${it} \u2014 the database reads every one of them for each lookup through the table, on every statement a rule guards`);if(r.forcesRowSecurity)throw new _("forced_row_security",`type ${s.name}: ${i} forces row-level security on its owner (FORCE ROW LEVEL SECURITY); access reads a type's table as its owner, so it would read nothing`);let m=s.table.key;if(m===null){if(r.primaryKey.length!==1){let b=r.primaryKey.length===0?"has no primary key":`has a primary key of ${r.primaryKey.length} columns`;throw new _("key_not_supported",`type ${s.name}: ${i} ${b}; name one column that identifies a row \u2014 table ${s.table.name} key <column>`)}m=r.primaryKey[0]}let a=r.columns.get(m);if(!a)throw new _("unknown_column",`type ${s.name}: ${i} has no column "${m}"`);if(!r.identifying.includes(m))throw new _("key_not_supported",`type ${s.name}: ${i}.${m} does not identify a row by itself at every moment; an object's key is NOT NULL and unique alone \u2014 the primary key, or a unique constraint or index of that column and no other \u2014 and not DEFERRABLE`);if(!a.family||!Vt.includes(a.family))throw new _("key_not_supported",`type ${s.name}: the key ${i}.${m} is ${a.type}; an object's id is text, a uuid or an integer`);let p=a.family;n.set(s.name,{name:s.name,model:s,table:{sql:ct(r.schema,r.name),schema:r.schema,name:r.name,key:m,info:r},family:p,idType:p==="int"?"bigint":p})}for(let s of n.values())for(let i of s.model.relations.values()){if(i.kind!=="column")continue;let r=s.table.info,m=`${r.schema}.${r.name}`,a=`relation ${s.name}.${i.name}`,p=r.columns.get(i.column);if(!p)throw new _("unknown_column",`${a}: ${m} has no column "${i.column}"`,i.line);if(!p.family||!Vt.includes(p.family))throw new _("type_mismatch",`${a}: ${m}.${i.column} is ${p.type}; an id is text, a uuid or an integer`,i.line);if(i.subject!==K){let b=n.get(i.subject);if(b.table&&b.family!==p.family)throw new _("type_mismatch",`${a}: ${m}.${i.column} is ${p.type}, and the key of type ${b.name} is ${b.table.info.columns.get(b.table.key)?.type}`,i.line)}i.where&&gt(i.where,r,a,i.line)}return n}function gt(t,e,n,s){if("parts"in t){for(let b of t.parts)gt(b,e,n,s);return}if(t.op==="not")return gt(t.part,e,n,s);let i=`${e.schema}.${e.name}`,r=e.columns.get(t.column);if(!r)throw new _("unknown_column",`${n}: its condition reads "${t.column}", which ${i} does not have`,s);if(t.op==="null")return;let m=r.family;if(!m)throw new _("not_supported",`${n}: its condition compares ${i}.${t.column}, which is ${r.type}; a condition compares text, an enum, a uuid, a number or a boolean`,s);let a=t.op==="in"?t.values:[t.value];if(t.op==="cmp"&&t.cmp!=="="&&t.cmp!=="!="&&m!=="int"&&m!=="numeric")throw new _("not_supported",`${n}: "${t.column} ${t.op==="cmp"?t.cmp:""}" \u2014 only a number is compared by order; ${i}.${t.column} is ${r.type}`,s);for(let b of a){let I=m==="bool"?"boolean":m==="int"||m==="numeric"?"number":"string";if(b.t!==I)throw new _("type_mismatch",`${n}: ${i}.${t.column} is ${r.type}; its condition compares it with ${b.t==="string"?"a text":b.t==="number"?"a number":"true or false"}`,s);if(m==="int"&&b.t==="number"&&!/^-?[0-9]{1,18}$/.test(b.v))throw new _("type_mismatch",`${n}: ${i}.${t.column} is ${r.type}; ${b.v} is not a whole number it can hold`,s);if(m==="uuid"&&b.t==="string"&&!new RegExp(He).test(b.v))throw new _("type_mismatch",`${n}: ${i}.${t.column} is a uuid; '${b.v}' is not one`,s)}}var Yt=t=>t.t==="string"?T(t.v):t.t==="number"?t.v:t.v?"true":"false";function be(t,e){return"parts"in t?`(${t.parts.map(n=>be(n,e)).join(t.op==="and"?" AND ":" OR ")})`:t.op==="not"?`(NOT ${be(t.part,e)})`:t.op==="null"?`(${e(t.column)} IS ${t.negated?"NOT ":""}NULL)`:t.op==="in"?`(${e(t.column)} IN (${t.values.map(Yt).join(", ")}))`:`(${e(t.column)} ${t.cmp==="!="?"<>":t.cmp} ${Yt(t.value)})`}function zt(t,e){return`SELECT g.tgname INTO early FROM pg_catalog.pg_trigger g JOIN pg_catalog.pg_proc p ON p.oid = g.tgfoid JOIN pg_catalog.pg_namespace n ON n.oid = p.pronamespace
129
+ WHERE g.tgrelid = ${T(t)}::pg_catalog.regclass AND NOT g.tgisinternal AND n.nspname <> ${T(V)} AND ${mt("g")}
130
+ ORDER BY g.tgname COLLATE "C" LIMIT 1;
131
+ IF early IS NOT NULL THEN
132
+ RAISE EXCEPTION '% has a trigger of its own, "%", that fires after a change and is named to come before access'' (${pt}): rename it to come after, or make it fire before the change', ${T(e)}, early;
133
+ END IF;`}function We(t,e,n,s={}){let i={...Oe,...s.roles},r=s.rows!==!1,m=kn(t,e),a=`${V}_${In().replaceAll("-","")}`,p=O(a),b=`${O(i.authenticated)}, ${O(i.service)}`,I=O(i.service),j=new Map,L=(c,d)=>{let N=j.get(c);if(N!==void 0&&N!==d)throw new _("invalid_name",`${d} and ${N} would have one name in the database (${c})`);return j.set(c,d),c},v=c=>c.length<=xe?c:`${c.slice(0,xe-17)}~${Wt("sha256").update(c).digest("hex").slice(0,16)}`,E=(c,d)=>L(`${c}__${Ge(d)}`,`${c}.${d}`),k=(c,d)=>`${p}.${O(E(c,d))}`,G=(c,d,N)=>L(v(`${c}:${d}->${N}`),`the arrow ${c}.${d}->${N}`),q=(c,d)=>`${p}.${O(L(v(`${c}:${d}?`),`who holds ${c}.${d}`))}`,P=c=>m.get(c),$=(c,d)=>c.table?`(${d.key})::text`:d.key,h=(c,d,N)=>{if("parts"in d)return`(${d.parts.map(C=>h(c,C,N)).join(d.op==="union"?" OR ":" AND ")})`;if(d.op==="exclude")return`(${h(c,d.base,N)} AND (${h(c,d.minus,N)}) IS NOT TRUE)`;if(d.op==="ref"){let C=c.model.permissions.get(d.name);return C?h(c,C.expr,N):x(c,c.model.relations.get(d.name),N)}let A=c.model.relations.get(d.relation);if(A.kind==="column"){let C=P(A.subject),w=`EXISTS (SELECT 1 FROM ${k(C.name,d.name)} x WHERE x.id = ${C.table?N.col(A.column):`(${N.col(A.column)})::text`})`;return A.where?`(${w} AND ${be(A.where,N.col)})`:w}return`EXISTS (SELECT 1 FROM ${p}.${O(G(c.name,A.name,d.name))} h WHERE h.object_id = ${$(c,N)})`},x=(c,d,N)=>{if(d.kind==="stored")return`EXISTS (SELECT 1 FROM ${S}.mine m WHERE m.object_type = ${T(c.name)} AND m.relation = ${T(d.name)} AND m.object_id = ${$(c,N)})`;let A=c.table.info.columns.get(d.column)?.family,C=`${N.col(d.column)} = ${Ln(A)}`;return d.where?`(${C} AND ${be(d.where,N.col)})`:`(${C})`},o=(c,d)=>{if("parts"in d)return d.parts.flatMap(C=>o(c,C));if(d.op==="exclude")return[...o(c,d.base),...o(c,d.minus)];let N=c.table?"($1)::text":"$1";if(d.op==="ref"){let C=c.model.permissions.get(d.name);if(C)return o(c,C.expr);let w=c.model.relations.get(d.name);if(w.kind==="stored")return[`SELECT m.subject_id FROM ${S}.relationships m WHERE m.object_type = ${T(c.name)} AND m.object_id = ${N} AND m.relation = ${T(w.name)} AND m.subject_type = 'user'`];let F=c.table,H=w.where?` AND ${be(w.where,z=>`t.${O(z)}`)}`:"";return[`SELECT (t.${O(w.column)})::text FROM ${F.sql} AS t WHERE t.${O(F.key)} = $1 AND t.${O(w.column)} IS NOT NULL${H}`]}let A=c.model.relations.get(d.relation);if(A.kind==="column"){let C=c.table,w=P(A.subject),F=w.table?`t.${O(A.column)}`:`(t.${O(A.column)})::text`,H=A.where?` AND ${be(A.where,z=>`t.${O(z)}`)}`:"";return[`SELECT w FROM ${C.sql} AS t CROSS JOIN LATERAL ${q(w.name,d.name)}(${F}) AS w WHERE t.${O(C.key)} = $1${H}`]}return ne(A).map(C=>{let w=P(C);return`SELECT w FROM ${S}.relationships e CROSS JOIN LATERAL ${q(w.name,d.name)}(${ye(w.family,"e.subject_id")}) AS w WHERE e.object_type = ${T(c.name)} AND e.object_id = ${N} AND e.relation = ${T(A.name)} AND e.subject_type = ${T(w.name)} AND ${p}.walked(e.subject_id)`})},u=[`CREATE SCHEMA IF NOT EXISTS ${p}`];u.push(`CREATE OR REPLACE FUNCTION ${p}.walked(text) RETURNS boolean LANGUAGE plpgsql VOLATILE ${J} AS ${D(`
134
+ DECLARE n bigint := coalesce(nullif(pg_catalog.current_setting('access.walked', true), ''), '0')::bigint + 1;
135
+ BEGIN
136
+ IF n > ${Bt} THEN
137
+ PERFORM ${S}.refuse(${T(B.tooMany)}, 'more than ${Bt} objects related to this one would be walked to say who holds it: ask whether one subject holds it (check) instead of who does');
138
+ END IF;
139
+ PERFORM pg_catalog.set_config('access.walked', n::text, true);
140
+ RETURN true;
141
+ END`)}`);let l=[],f=new Set,y=new Set,R=c=>c.op==="arrow"?[c]:c.op==="ref"?[]:c.op==="exclude"?[...R(c.base),...R(c.minus)]:c.parts.flatMap(R);for(let{type:c,name:d}of t.order){let N=P(c),A=N.model.relations.get(d);if(A&&!Ee(A))continue;let C=N.model.permissions.get(d)?.expr??{op:"ref",name:d};for(let H of R(C)){let z=N.model.relations.get(H.relation),M=G(N.name,z.name,H.name);if(z.kind!=="stored"||f.has(M))continue;f.add(M);let ze=ne(z).map(ce=>{let se=P(ce);return`(e.subject_type = ${T(se.name)} AND EXISTS (SELECT 1 FROM ${k(se.name,H.name)} x WHERE x.id = ${ye(se.family,"e.subject_id")}))`});u.push(`CREATE OR REPLACE VIEW ${p}.${O(M)} WITH (security_barrier = true) AS
142
+ SELECT e.object_id FROM ${S}.relationships e
143
+ WHERE e.object_type = ${T(N.name)} AND e.relation = ${T(z.name)} AND (${ze.join(" OR ")}) IS TRUE`)}let w=N.table?{col:H=>`t.${O(H)}`,key:`t.${O(N.table.key)}`}:{col:()=>"",key:"t.k"},F=N.table?`${N.table.sql} AS t`:`(SELECT DISTINCT r.object_id AS k FROM ${S}.relationships r WHERE r.object_type = ${T(N.name)}) AS t`;u.push(`CREATE OR REPLACE VIEW ${k(c,d)} WITH (security_barrier = true) AS SELECT ${w.key} AS id FROM ${F} WHERE (${h(N,C,w)}) IS TRUE`),u.push(`CREATE OR REPLACE FUNCTION ${q(c,d)}(${N.idType}) RETURNS SETOF text LANGUAGE sql STABLE SECURITY DEFINER ${J} AS ${D(`
144
+ SELECT c.w FROM (
145
+ ${o(N,C).join(`
146
+ UNION ALL
147
+ `)}
148
+ ) AS c(w) LIMIT ${qt+1}`)}`),l.push({type:c,name:d,view:E(c,d),idType:N.table?N.table.info.columns.get(N.table.key)?.type:"text"})}let g=(c,d,N)=>`${N} = ${T(c.type)} AND ${d} = ${T(c.name)}`,U=(c,d)=>`'type ' || coalesce(${d}, '(null)') || ' has no relation or permission ' || coalesce(${c}, '(null)')`,ee=(c,d)=>l.length===0?d:`${l.map((N,A)=>`${A===0?"IF":"ELSIF"} ${g(N,"$1","$2")} THEN
149
+ ${c(N)}`).join(`
150
+ `)}
151
+ ELSE
152
+ ${d}
153
+ END IF;`;u.push(`CREATE OR REPLACE FUNCTION ${p}.can(permission text, object_type text, object_id text) RETURNS boolean LANGUAGE plpgsql STABLE ${J} AS ${D(`
154
+ BEGIN
155
+ ${ee(c=>`RETURN EXISTS (SELECT 1 FROM ${k(c.type,c.name)} v WHERE v.id = ${ye(P(c.type).family,"$3")});`,`RETURN ${S}.refuse(${T(B.unknown)}, ${U("$1","$2")});`)}
156
+ END`)}`,`CREATE OR REPLACE FUNCTION ${p}.my_objects(permission text, object_type text) RETURNS SETOF text LANGUAGE plpgsql STABLE ${J} AS ${D(`
157
+ BEGIN
158
+ ${ee(c=>`RETURN QUERY SELECT (v.id)::text FROM ${k(c.type,c.name)} v;`,`PERFORM ${S}.refuse(${T(B.unknown)}, ${U("$1","$2")});`)}
159
+ RETURN;
160
+ END`)}`,`CREATE OR REPLACE FUNCTION ${p}.check(subject text, permission text, object_type text, object_id text) RETURNS boolean LANGUAGE plpgsql VOLATILE ${J} AS ${D(`
161
+ DECLARE was text := current_setting('access.subject', true); answer boolean;
162
+ BEGIN
163
+ IF $1 IS NULL OR $1 = '' THEN RETURN false; END IF;
164
+ PERFORM ${S}.act_as($1);
165
+ answer := ${p}.can($2, $3, $4);
166
+ PERFORM set_config('access.subject', coalesce(was, ''), true);
167
+ RETURN answer;
168
+ END`)}`,`CREATE OR REPLACE FUNCTION ${p}.objects(subject text, permission text, object_type text) RETURNS SETOF text LANGUAGE plpgsql VOLATILE ${J} AS ${D(`
169
+ DECLARE was text := current_setting('access.subject', true);
170
+ BEGIN
171
+ IF $1 IS NULL OR $1 = '' THEN RETURN; END IF;
172
+ PERFORM ${S}.act_as($1);
173
+ RETURN QUERY SELECT o FROM ${p}.my_objects($2, $3) AS o;
174
+ PERFORM set_config('access.subject', coalesce(was, ''), true);
175
+ RETURN;
176
+ END`)}`,`CREATE OR REPLACE FUNCTION ${p}.subjects(permission text, object_type text, object_id text) RETURNS SETOF text LANGUAGE plpgsql VOLATILE ${J} AS ${D(`
177
+ DECLARE named text[]; seen bigint := 0; walked bigint; c text;
178
+ BEGIN
179
+ PERFORM pg_catalog.set_config('access.walked', '0', true);
180
+ ${ee(c=>`SELECT array_agg(DISTINCT w) FILTER (WHERE w IS NOT NULL AND w <> ''), count(*) INTO named, seen FROM ${q(c.type,c.name)}(${ye(P(c.type).family,"$3")}) AS w;`,`PERFORM ${S}.refuse(${T(B.unknown)}, ${U("$1","$2")});`)}
181
+ IF seen > ${qt} OR coalesce(array_length(named, 1), 0) > ${ft} THEN
182
+ PERFORM ${S}.refuse(${T(B.tooMany)}, 'more than ${ft} subjects are related to this object: ask whether one subject holds it (check) instead of who does');
183
+ END IF;
184
+ -- Each one is checked in turn, and a check reads the related objects again.
185
+ walked := coalesce(nullif(pg_catalog.current_setting('access.walked', true), ''), '0')::bigint;
186
+ IF coalesce(array_length(named, 1), 0) * (walked + 1) > ${Xt} THEN
187
+ PERFORM ${S}.refuse(${T(B.tooMany)}, pg_catalog.format('saying who holds it would check %s subjects, each through %s related objects: more than ${Xt} together; ask whether one subject holds it (check) instead of who does', array_length(named, 1), walked));
188
+ END IF;
189
+ FOREACH c IN ARRAY coalesce(named, '{}'::text[]) LOOP
190
+ IF ${p}.check(c, $1, $2, $3) THEN RETURN NEXT c; END IF;
191
+ END LOOP;
192
+ RETURN;
193
+ END`)}`);let je=[...m.values()].flatMap(c=>[...c.model.relations.values()].flatMap(d=>d.kind==="stored"?d.subjects.map(N=>`(${T(c.name)}, ${T(d.name)}, ${T(N)})`):[])),De=(c,d,N)=>je.length===0?"false":`(${c}, ${d}, ${N}) IN (${je.join(", ")})`,bt="'type ' || coalesce($1, '(null)') || ' keeps no relation ' || coalesce($3, '(null)') || ' that takes ' || coalesce($4, '(null)')",Rt=c=>`${S}.refuse(${T(B.badId)}, ${T(`${c} is empty or longer than ${Se} characters`)})`,Tt=[...m.values()].filter(c=>c.table).map(c=>T(c.name)),Ve=c=>Tt.length===0?"false":`${c} IN (${Tt.join(", ")})`,rn=`IF ${Ve("$4")} AND ($4, s) < ($1, o) THEN PERFORM ${S}.touch($4, ARRAY[s]); END IF;
194
+ IF ${Ve("$1")} THEN PERFORM ${S}.touch($1, ARRAY[o]); END IF;
195
+ IF ${Ve("$4")} AND ($4, s) > ($1, o) THEN PERFORM ${S}.touch($4, ARRAY[s]); END IF;`;u.push(`CREATE OR REPLACE FUNCTION ${p}.object(object_type text, object_id text) RETURNS text LANGUAGE plpgsql VOLATILE SECURITY DEFINER ${J} AS ${D(`
196
+ DECLARE canon text;
197
+ BEGIN
198
+ ${[...m.values()].map(c=>c.table?`IF $1 = ${T(c.name)} THEN
199
+ SELECT (t.${O(c.table.key)})::text INTO canon FROM ${c.table.sql} AS t WHERE t.${O(c.table.key)} = ${ye(c.family,"$2")} FOR KEY SHARE;
200
+ IF canon IS NULL THEN PERFORM ${S}.refuse(${T(B.noObject)}, 'there is no ' || $1 || ' ' || coalesce($2, '(null)')); END IF;
201
+ RETURN canon;
202
+ END IF;`:`IF $1 = ${T(c.name)} THEN
203
+ IF $2 IS NULL OR $2 = '' OR length($2) > ${Se} THEN PERFORM ${Rt(`the id of a ${c.name}`)}; END IF;
204
+ RETURN $2;
205
+ END IF;`).join(`
206
+ `)}
207
+ PERFORM ${S}.refuse(${T(B.unknown)}, 'there is no type ' || coalesce($1, '(null)'));
208
+ RETURN NULL;
209
+ END`)}`,`CREATE OR REPLACE FUNCTION ${p}.grant(object_type text, object_id text, relation text, subject_type text, subject_id text, actor text DEFAULT NULL) RETURNS boolean LANGUAGE plpgsql VOLATILE SECURITY DEFINER ${J} AS ${D(`
210
+ DECLARE o text; s text; n bigint; was text := current_setting('access.actor', true);
211
+ BEGIN
212
+ IF (${De("$1","$3","$4")}) IS NOT TRUE THEN PERFORM ${S}.refuse(${T(B.notTaken)}, ${bt}); END IF;
213
+ o := ${p}.object($1, $2);
214
+ IF $4 = 'user' THEN
215
+ IF $5 IS NULL OR $5 = '' OR length($5) > ${Se} THEN PERFORM ${Rt("a subject's id")}; END IF;
216
+ s := $5;
217
+ ELSE
218
+ s := ${p}.object($4, $5);
219
+ END IF;
220
+ -- The rows it is given on, met by whatever takes their relationships away by a snapshot that cannot see it.
221
+ ${rn}
222
+ IF $6 IS NOT NULL AND $6 <> '' THEN PERFORM set_config('access.actor', $6, true); END IF;
223
+ INSERT INTO ${S}.relationships (object_type, object_id, relation, subject_type, subject_id) VALUES ($1, o, $3, $4, s) ON CONFLICT DO NOTHING;
224
+ GET DIAGNOSTICS n = ROW_COUNT;
225
+ PERFORM set_config('access.actor', coalesce(was, ''), true);
226
+ RETURN n > 0;
227
+ END`)}`,`CREATE OR REPLACE FUNCTION ${p}.canon(object_type text, object_id text) RETURNS text LANGUAGE sql STABLE ${J} AS ${D(`
228
+ SELECT CASE
229
+ ${[...m.values()].map(c=>`WHEN $1 = ${T(c.name)} THEN ${c.table&&c.family!=="text"?`(${ye(c.family,"$2")})::text`:"$2"}`).join(`
230
+ `)}
231
+ ELSE $2 END`)}`,`CREATE OR REPLACE FUNCTION ${p}.revoke(object_type text, object_id text, relation text, subject_type text, subject_id text, actor text DEFAULT NULL) RETURNS boolean LANGUAGE plpgsql VOLATILE SECURITY DEFINER ${J} AS ${D(`
232
+ DECLARE n bigint; was text := current_setting('access.actor', true);
233
+ BEGIN
234
+ IF (${De("$1","$3","$4")}) IS NOT TRUE THEN PERFORM ${S}.refuse(${T(B.notTaken)}, ${bt}); END IF;
235
+ IF $6 IS NOT NULL AND $6 <> '' THEN PERFORM set_config('access.actor', $6, true); END IF;
236
+ DELETE FROM ${S}.relationships r
237
+ WHERE r.object_type = $1 AND r.object_id = ${p}.canon($1, $2) AND r.relation = $3 AND r.subject_type = $4
238
+ AND r.subject_id = CASE WHEN $4 = 'user' THEN $5 ELSE ${p}.canon($4, $5) END;
239
+ GET DIAGNOSTICS n = ROW_COUNT;
240
+ PERFORM set_config('access.actor', coalesce(was, ''), true);
241
+ RETURN n > 0;
242
+ END`)}`),u.push(`REVOKE ALL ON SCHEMA ${p} FROM PUBLIC, ${b}`,`GRANT USAGE ON SCHEMA ${p} TO ${b}`,`REVOKE ALL ON ALL TABLES IN SCHEMA ${p} FROM PUBLIC, ${b}`,...l.map(c=>`GRANT SELECT ON ${k(c.type,c.name)} TO ${b}`),`REVOKE ALL ON ALL FUNCTIONS IN SCHEMA ${p} FROM PUBLIC, ${b}`,`GRANT EXECUTE ON FUNCTION ${p}.can(text, text, text), ${p}.my_objects(text, text) TO ${b}`,`GRANT EXECUTE ON ALL FUNCTIONS IN SCHEMA ${p} TO ${I}`);let fe=[],Ye=[],Fe=[],Me=[],ie=(c,d,N,A,C)=>fe.push(`CREATE OR REPLACE FUNCTION ${S}.${O(c)}(${d}) RETURNS ${N} LANGUAGE sql ${A} AS ${D(` SELECT ${p}.${O(c)}(${C}) `)}`);ie("can","permission text, object_type text, object_id text","boolean","STABLE","$1, $2, $3"),ie("my_objects","permission text, object_type text","SETOF text","STABLE","$1, $2"),ie("check","subject text, permission text, object_type text, object_id text","boolean","VOLATILE","$1, $2, $3, $4"),ie("objects","subject text, permission text, object_type text","SETOF text","VOLATILE","$1, $2, $3"),ie("subjects","permission text, object_type text, object_id text","SETOF text","VOLATILE","$1, $2, $3"),ie("grant","object_type text, object_id text, relation text, subject_type text, subject_id text, actor text DEFAULT NULL","boolean","VOLATILE","$1, $2, $3, $4, $5, $6"),ie("revoke","object_type text, object_id text, relation text, subject_type text, subject_id text, actor text DEFAULT NULL","boolean","VOLATILE","$1, $2, $3, $4, $5, $6");let an=`${S}.can(text, text, text), ${S}.my_objects(text, text), ${S}.check(text, text, text, text), ${S}.objects(text, text, text), ${S}.subjects(text, text, text), ${S}.grant(text, text, text, text, text, text), ${S}.revoke(text, text, text, text, text, text)`;fe.push(`REVOKE ALL ON ALL FUNCTIONS IN SCHEMA ${S} FROM PUBLIC`,`REVOKE ALL ON FUNCTION ${an} FROM ${b}`,`GRANT EXECUTE ON FUNCTION ${S}.can(text, text, text), ${S}.my_objects(text, text) TO ${b}`,`GRANT EXECUTE ON FUNCTION ${S}.check(text, text, text, text), ${S}.objects(text, text, text), ${S}.subjects(text, text, text), ${S}.grant(text, text, text, text, text, text), ${S}.revoke(text, text, text, text, text, text) TO ${I}`);for(let c of l)s.aliases?.some(d=>d.name===c.view&&d.type!==c.idType)&&fe.push(`DROP VIEW ${S}.${O(c.view)}`),fe.push(`CREATE OR REPLACE VIEW ${S}.${O(c.view)} WITH (security_barrier = true) AS SELECT id FROM ${p}.${O(c.view)}`,`REVOKE ALL ON ${S}.${O(c.view)} FROM PUBLIC, ${b}`,`GRANT SELECT ON ${S}.${O(c.view)} TO ${b}`);let Nt=[],wt=[];for(let c of m.values()){if(!c.table)continue;let d=c.table;Nt.push({type:c.name,schema:d.schema,name:d.name,key:d.key});let N=`${d.schema}.${d.name}`;if(Ye.push(`DO $guard$
243
+ DECLARE early text;
244
+ BEGIN
245
+ IF EXISTS (SELECT 1 FROM pg_catalog.pg_trigger g JOIN pg_catalog.pg_proc p ON p.oid = g.tgfoid JOIN pg_catalog.pg_namespace n ON n.oid = p.pronamespace
246
+ WHERE g.tgrelid = ${T(d.sql)}::pg_catalog.regclass AND NOT g.tgisinternal AND g.tgname IN (${oe.map(A=>T(A)).join(", ")}) AND n.nspname <> ${T(V)}) THEN
247
+ RAISE EXCEPTION '% has a trigger of its own under a name access'' takes (${oe.join(", ")}): rename it', ${T(N)};
248
+ END IF;
249
+ ${zt(d.sql,N)}
250
+ END $guard$`,...oe.map(A=>`DROP TRIGGER IF EXISTS ${O(A)} ON ${d.sql}`),`CREATE TRIGGER ${O("!access_fresh")} AFTER INSERT ON ${d.sql} FOR EACH ROW EXECUTE FUNCTION ${S}.fresh_objects(${T(c.name)}, ${T(d.key)})`,`CREATE TRIGGER ${O("!access_forget")} AFTER DELETE ON ${d.sql} FOR EACH ROW EXECUTE FUNCTION ${S}.forget_object(${T(c.name)}, ${T(d.key)})`,`CREATE TRIGGER ${O("!access_move")} AFTER UPDATE ON ${d.sql} FOR EACH ROW WHEN (OLD.${O(d.key)} IS DISTINCT FROM NEW.${O(d.key)}) EXECUTE FUNCTION ${S}.move_object(${T(c.name)}, ${T(d.key)})`,`CREATE TRIGGER ${O("!access_empty")} AFTER TRUNCATE ON ${d.sql} FOR EACH STATEMENT EXECUTE FUNCTION ${S}.forget_all(${T(c.name)})`,...oe.map(A=>`ALTER TABLE ${d.sql} ENABLE TRIGGER ${O(A)}`)),!(!r||c.model.rows.length===0)){Fe.push(`ALTER TABLE ${d.sql} ENABLE ROW LEVEL SECURITY`);for(let A of c.model.rows){let C=`access_${A.command}`,w=At(c.name,A.name),F=A.command==="insert"?"":` USING (${w})`,H=A.command==="insert"||A.command==="update"?` WITH CHECK (${w})`:"";Fe.push(`DO $guard$
251
+ BEGIN
252
+ IF EXISTS (SELECT 1 FROM pg_catalog.pg_policy p WHERE p.polrelid = ${T(d.sql)}::pg_catalog.regclass AND p.polname = ${T(C)}
253
+ AND pg_catalog.obj_description(p.oid, 'pg_policy') IS DISTINCT FROM ${T($e)}) THEN
254
+ RAISE EXCEPTION '% has a policy of its own named % \u2014 the name a rows rule of the access schema takes: rename it', ${T(N)}, ${T(C)};
255
+ END IF;
256
+ END $guard$`,`DROP POLICY IF EXISTS ${O(C)} ON ${d.sql}`,`CREATE POLICY ${O(C)} ON ${d.sql} FOR ${A.command.toUpperCase()} TO ${O(i.authenticated)}${F}${H}`,`COMMENT ON POLICY ${O(C)} ON ${d.sql} IS ${T($e)}`),wt.push({schema:d.schema,table:d.name,name:C,command:A.command});for(let z of Ot(c.name,A.name))y.add(z)}}}Me.push(`REVOKE ALL ON ALL TABLES IN SCHEMA ${p} FROM ${b}`,...l.map(c=>`GRANT SELECT ON ${k(c.type,c.name)} TO ${b}`));for(let c of new Set([...y,...(s.policies??[]).flatMap(d=>Ot(d.type,d.name))]))Me.push(`GRANT SELECT ON ${p}.${O(c)} TO ${O(i.authenticated)}`);let Ue=Wt("sha256").update(JSON.stringify({engine:Ae,roles:i,sql:[...Ke(i),...u,...fe.filter(c=>!c.startsWith("DROP VIEW ")),...Ye,...Fe,...Me].map(c=>c.replaceAll(a,`${V}_`))})).digest("hex").slice(0,12),_t=`${V}_${Ue}`,xt=[`UPDATE ${S}.schemas SET active = false WHERE active AND digest <> ${T(Ue)}`,`INSERT INTO ${S}.schemas (digest, text, engine, active) VALUES (${T(Ue)}, ${T(n)}, ${T(Ae)}, true)
257
+ ON CONFLICT (digest) DO UPDATE SET active = true, text = excluded.text, engine = excluded.engine, applied_at = now(), applied_by = session_user`],ae=c=>c.replaceAll(a,_t),cn=l.filter(c=>P(c.type).table).map(c=>({type:c.type,name:c.name,sql:ae(At(c.type,c.name))})),we={watch:Ye.map(ae),open:Me.map(ae),rows:Fe.map(ae),point:fe.map(ae),record:xt};return{digest:Ue,schema:_t,build:u.map(ae),...we,activate:[...we.point,...we.watch,...we.rows,...we.open,...xt],recheck:[...un(),...pn()],tables:Nt,names:l,policies:wt,predicates:cn};function ln(c){let d=[...[...m.values()].flatMap(w=>(r&&w.table?w.model.rows:[]).map(F=>({type:w.name,command:F.command,using:F.command==="insert"?null:[F.name],check:F.command==="insert"||F.command==="update"?[F.name]:null}))),...s.guards??[]],N=(w,F)=>w.command===F||w.command==="all",A=w=>w.check??(w.command==="insert"?[]:w.using??[]),C=[];for(let w of m.values()){if(!w.table)continue;let F=d.filter(M=>M.type===w.name);if(F.length===0)continue;let H=F.filter(M=>N(M,"select")).flatMap(M=>M.using??[]),z=[["a SELECT",H],["an INSERT",[...F.filter(M=>N(M,"insert")).flatMap(A),...H]],["an UPDATE",[...F.filter(M=>N(M,"update")).flatMap(M=>[...M.using??[],...A(M)]),...H]],["a DELETE",[...F.filter(M=>N(M,"delete")).flatMap(M=>M.using??[]),...H]],["an INSERT \u2026 ON CONFLICT DO UPDATE",[...F.filter(M=>N(M,"insert")).flatMap(A),...F.filter(M=>N(M,"update")).flatMap(M=>[...M.using??[],...A(M)])]]];for(let[M,ze]of z){let ce=new Map;for(let Q of ze){let le=c.get(`${w.name}.${Q}`);le!==void 0&&ce.set(le,{what:`${w.name}.${Q}`,n:(ce.get(le)?.n??0)+1})}if([...ce.values()].reduce((Q,le)=>Q+le.n,0)<2)continue;let se=Q=>[...ce].map(([le,dn])=>`${dn.n} * ${Q}[${le}]`).join(" + "),mn=`${M} of ${w.table.schema}.${w.table.name} plans ${[...ce.values()].map(Q=>`${Q.what} ${Q.n===1?"once":`${Q.n} times`}`).join(" and ")}`;C.push(`
258
+ IF (${se("kbs")}) > ${pe} OR (${se("mss")}) > ${Ce} THEN
259
+ RAISE EXCEPTION USING ERRCODE = '54000', MESSAGE = pg_catalog.format('access: %s \u2014 the rows it reads, its USING and its WITH CHECK: %s MB and %s ms to plan, for every such statement; at most ${pe/1024} MB and ${Ce} ms', ${T(mn)}, round((${se("kbs")}) / 1024), round(${se("mss")}));
260
+ END IF;`)}}return C.join("")}function un(){let c=[...m.values()].filter(d=>d.table);return c.length===0?[]:[`DO $early$
261
+ DECLARE early text;
262
+ BEGIN
263
+ ${c.map(d=>zt(d.table.sql,`${d.table.schema}.${d.table.name}`)).join(`
264
+ `)}
265
+ END $early$`]}function pn(){if(l.length===0)return[];let c={int:"1",uuid:"00000000-0000-0000-0000-000000000001",text:"1"},d=l.map(w=>({what:`${w.type}.${w.name}`,view:ae(k(w.type,w.name)),key:P(w.type).table?c[P(w.type).family]:c.text,size:Math.max(1,t.planned(w.type,w.name))})).sort((w,F)=>w.size-F.size),N=w=>`ARRAY[${w.join(", ")}]`,A=new Map(d.map((w,F)=>[w.what,F+1])),C=ln(A);return[`DO $measure$
266
+ DECLARE
267
+ whats text[] := ${N(d.map(w=>T(w.what)))};
268
+ views text[] := ${N(d.map(w=>T(w.view)))};
269
+ keys text[] := ${N(d.map(w=>T(w.key)))};
270
+ sizes int[] := ${N(d.map(w=>String(w.size)))};
271
+ memory boolean := pg_catalog.current_setting('server_version_num')::int >= 170000;
272
+ per numeric := 0;
273
+ p json; kb numeric; ms numeric;
274
+ kbs numeric[] := '{}'; mss numeric[] := '{}';
275
+ BEGIN
276
+ FOR i IN 1 .. pg_catalog.array_length(views, 1) LOOP
277
+ IF per * sizes[i] > ${2*pe} THEN
278
+ RAISE EXCEPTION USING ERRCODE = '54000', MESSAGE = pg_catalog.format('access: %s would take the database about %s MB to plan, for every statement it guards (as its other names show); at most ${pe/1024} MB. What its tables carry is planned with it \u2014 their indexes, a partial index''s predicate, an index''s expressions, their statistics \u2014 and the indexes of access.relationships', whats[i], round(per * sizes[i] / 1024));
279
+ END IF;
280
+ ms := NULL;
281
+ -- The time, at its best of three: a database busy with other work is slower, not the schema.
282
+ FOR t IN 1 .. 3 LOOP
283
+ EXECUTE pg_catalog.format('EXPLAIN (%sSUMMARY, FORMAT JSON) SELECT id FROM %s WHERE id = %L', CASE WHEN memory THEN 'MEMORY, ' ELSE '' END, views[i], keys[i]) INTO p;
284
+ kb := coalesce((p -> 0 -> 'Planning' ->> 'Memory Used')::numeric, 0);
285
+ ms := least(coalesce(ms, 'Infinity'::numeric), (p -> 0 ->> 'Planning Time')::numeric);
286
+ EXIT WHEN ms <= ${Ce} OR kb > ${pe};
287
+ END LOOP;
288
+ IF kb > ${pe} OR ms > ${Ce} THEN
289
+ RAISE EXCEPTION USING ERRCODE = '54000', MESSAGE = pg_catalog.format('access: %s takes the database %s MB and %s ms to plan, for every statement it guards; at most ${pe/1024} MB and ${Ce} ms. What its tables carry is planned with it \u2014 their indexes, a partial index''s predicate, an index''s expressions, their statistics \u2014 and the indexes of access.relationships', whats[i], round(kb / 1024), round(ms));
290
+ END IF;
291
+ per := greatest(per, kb / sizes[i]);
292
+ kbs[i] := kb;
293
+ mss[i] := ms;
294
+ END LOOP;${C}
295
+ END $measure$`]}function At(c,d){let N=P(c),A=N.table,C={col:w=>`${O(A.name)}.${O(w)}`,key:`${O(A.name)}.${O(A.key)}`};return h(N,{op:"ref",name:d},C)}function Ot(c,d){let N=P(c),A=C=>{if("parts"in C)return C.parts.flatMap(A);if(C.op==="exclude")return[...A(C.base),...A(C.minus)];if(C.op==="ref"){let w=N.model.permissions.get(C.name);return w?A(w.expr):[]}return N.model.relations.get(C.relation).kind==="stored"?[G(N.name,C.relation,C.name)]:[]};return A({op:"ref",name:d})}}function jn(t){let e=[];for(let n of t.types.values())for(let s of n.relations.values())if(s.kind==="column"){e.push({type:n.name,column:s.column});for(let i of at(s.where))e.push({type:n.name,column:i})}return e}var Ps=`^${V}_[0-9a-f]{12}$`;function Fn(t){return[`DO $guard$
296
+ DECLARE held text;
297
+ BEGIN
298
+ SELECT string_agg(DISTINCT pg_catalog.pg_describe_object(d.classid, d.objid, d.objsubid), ', ') INTO held
299
+ FROM pg_catalog.pg_depend d
300
+ JOIN pg_catalog.pg_class c ON d.refclassid = 'pg_catalog.pg_class'::regclass AND d.refobjid = c.oid
301
+ JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace AND n.nspname = ${T(t)}
302
+ WHERE d.deptype = 'n'
303
+ AND NOT EXISTS (SELECT 1 FROM pg_catalog.pg_rewrite w JOIN pg_catalog.pg_class v ON v.oid = w.ev_class JOIN pg_catalog.pg_namespace vn ON vn.oid = v.relnamespace
304
+ WHERE d.classid = 'pg_catalog.pg_rewrite'::regclass AND d.objid = w.oid AND vn.nspname = ${T(t)});
305
+ IF held IS NOT NULL THEN
306
+ RAISE EXCEPTION 'the compiled schema % is still read by: % \u2014 these must read access.* instead', ${T(t)}, held;
307
+ END IF;
308
+ END $guard$`,`DROP SCHEMA IF EXISTS ${O(t)} CASCADE`]}function Mn(){let t=O(V);return[`DROP FUNCTION IF EXISTS ${t}.can(text, text, text), ${t}.my_objects(text, text), ${t}.check(text, text, text, text), ${t}.objects(text, text, text), ${t}.subjects(text, text, text), ${t}.grant(text, text, text, text, text, text), ${t}.revoke(text, text, text, text, text, text)`,`UPDATE ${t}.schemas SET active = false WHERE active`]}var Un=/^-?[0-9]{1,18}$/,vn=/^[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}$/;function re(t,e){return t==="text"?e:t==="uuid"?vn.test(e)?e.toLowerCase():null:t==="int"&&Un.test(e)?BigInt(e).toString():null}function me(t,e){return e===null?null:t==="int"?typeof e=="bigint"?e.toString():typeof e=="number"&&Number.isInteger(e)?BigInt(e).toString():null:t==="uuid"?typeof e=="string"?re("uuid",e):null:t==="text"&&typeof e=="string"?e:null}var Pn=/^(-?)([0-9]+)(?:\.([0-9]+))?$/;function Jt(t){let e=Pn.exec(t);if(!e)return null;let n=e[3]??"";return{digits:BigInt(`${e[1]}${e[2]}${n}`),scale:n.length}}function Et(t,e){let n=t.digits*10n**BigInt(e.scale),s=e.digits*10n**BigInt(t.scale);return n<s?-1:n>s?1:0}var Gn=t=>t.t==="string"?`'${t.v}'`:String(t.v),Ie=(t,e,n)=>new Error(`column "${t}" is ${e}: a condition cannot compare it with ${Gn(n)}`),qe=(t,e,n)=>new Error(`column "${t}" is ${e}: ${String(n)} is no value of it`);function Re(t,e){return Object.hasOwn(t,e)?t[e]??null:null}function Zt(t,e,n,s){if(s.t!=="number")throw Ie(e,t,s);let i=Jt(s.v);if(i===null)throw Ie(e,t,s);if(typeof n=="bigint")return Et({digits:n,scale:0},i);if(typeof n=="number"&&Number.isInteger(n))return Et({digits:BigInt(n),scale:0},i);if(typeof n=="number"&&Number.isFinite(n)){let r=Number(s.v);return n<r?-1:n>r?1:0}if(typeof n=="string"&&t==="numeric"){let r=Jt(n);if(r!==null)return Et(r,i)}throw qe(e,t,n)}function Qt(t,e,n,s){if(t==="int"||t==="numeric")return Zt(t,e,n,s)===0;if(t==="bool"){if(s.t!=="boolean")throw Ie(e,t,s);if(typeof n!="boolean")throw qe(e,t,n);return n===s.v}if(s.t!=="string")throw Ie(e,t,s);if(typeof n!="string")throw qe(e,t,n);if(t==="text")return n===s.v;let i=re("uuid",n),r=re("uuid",s.v);if(i===null)throw qe(e,t,n);if(r===null)throw Ie(e,t,s);return i===r}function en(t,e){function n(o){let u=t.types.get(o);if(!u)throw new Error(`the schema has no type "${o}"`);return u}function s(o,u){if(!o.relations.has(u)&&!o.permissions.has(u))throw new Error(`type ${o.name} has no relation or permission "${u}"`)}function i(o){let u=e.tables.get(o.name);if(!u)throw new Error(`the world has no table for type ${o.name}`);return u}function r(o,u){let l=i(o).shape.columns;if(!Object.hasOwn(l,u))throw new Error(`the world does not say how column "${u}" of type ${o.name}'s table compares`);return l[u]}function m(o,u){let l=i(o).shape.key;return me(r(o,l),Re(u,l))}function a(o,u){return o.table?i(o).rows.filter(l=>m(o,l)===u):[]}function p(o,u,l){if("parts"in o){let g=o.parts.map(U=>p(U,u,l));return o.op==="and"?g.includes(!1)?!1:g.includes(null)?null:!0:g.includes(!0)?!0:g.includes(null)?null:!1}if(o.op==="not"){let g=p(o.part,u,l);return g===null?null:!g}let f=r(u,o.column),y=Re(l,o.column);if(o.op==="null")return y===null!==o.negated;if(y===null)return null;if(o.op==="in")return o.values.map(g=>Qt(f,o.column,y,g)).includes(!0);if(f==="int"||f==="numeric"){let g=Zt(f,o.column,y,o.value);return o.cmp==="="?g===0:o.cmp==="!="?g!==0:o.cmp==="<"?g<0:o.cmp==="<="?g<=0:o.cmp===">"?g>0:g>=0}if(o.cmp!=="="&&o.cmp!=="!=")throw new Error(`column "${o.column}" is ${f}: "${o.cmp}" does not compare it`);let R=Qt(f,o.column,y,o.value);return o.cmp==="="?R:!R}function b(o,u,l){return Re(u,l.column)===null?!1:l.where===null||p(l.where,o,u)===!0}function I(o,u,l,f){if(!Ee(f))return!1;if(f.kind==="stored")return e.relationships.some(g=>g.objectType===u.name&&g.objectId===l&&g.relation===f.name&&g.subjectType===K&&g.subjectId===o);let y=r(u,f.column),R=re(y,o);return a(u,l).some(g=>b(u,g,f)&&R!==null&&R===me(y,Re(g,f.column)))}function j(o,u,l){if(l.kind==="stored"){let R=ne(l);return e.relationships.filter(g=>g.objectType===o.name&&g.objectId===u&&g.relation===l.name&&R.includes(g.subjectType)).map(g=>({type:g.subjectType,id:g.subjectId}))}if(l.subject===K)return[];let f=r(o,l.column),y=[];for(let R of a(o,u)){if(!b(o,R,l))continue;let g=me(f,Re(R,l.column));g!==null&&y.push({type:l.subject,id:g})}return y}function L(o,u){let l=o.relations.get(u);if(!l)throw new Error(`type ${o.name} has no relation "${u}"`);return l}function v(o,u,l,f){return o.op==="ref"?E(u,l,f,o.name):o.op==="arrow"?j(l,f,L(l,o.relation)).some(y=>E(u,n(y.type),y.id,o.name)):o.op==="exclude"?v(o.base,u,l,f)&&!v(o.minus,u,l,f):o.op==="union"?o.parts.some(y=>v(y,u,l,f)):o.parts.every(y=>v(y,u,l,f))}function E(o,u,l,f){if(o===""||u.table&&a(u,l).length===0)return!1;let y=u.relations.get(f);if(y)return I(o,u,l,y);let R=u.permissions.get(f);if(!R)throw new Error(`type ${u.name} has no relation or permission "${f}"`);return v(R.expr,o,u,l)}function k(o,u){return o.table?re(r(o,i(o).shape.key),u):u}function G(o,u,l,f){let y=n(u);s(y,f);let R=k(y,l);return R===null?!1:E(o,y,R,f)}function q(o,u,l){let f=n(u);s(f,l);let y=f.table?i(f).rows.map(g=>m(f,g)):e.relationships.filter(g=>g.objectType===f.name).map(g=>g.objectId),R=new Set;for(let g of y)g!==null&&G(o,u,g,l)&&R.add(g);return[...R].sort()}function P(o,u,l){if(o.table&&a(o,u).length===0)return[];let f=o.relations.get(l);if(f)return $(o,u,f);let y=o.permissions.get(l);if(!y)throw new Error(`type ${o.name} has no relation or permission "${l}"`);return h(y.expr,o,u)}function $(o,u,l){if(l.kind==="stored")return e.relationships.filter(R=>R.objectType===o.name&&R.objectId===u&&R.relation===l.name&&R.subjectType===K).map(R=>R.subjectId);if(l.subject!==K)return[];let f=r(o,l.column),y=[];for(let R of a(o,u)){if(!b(o,R,l))continue;let g=me(f,Re(R,l.column));g!==null&&y.push(g)}return y}function h(o,u,l){return o.op==="ref"?P(u,l,o.name):o.op==="arrow"?j(u,l,L(u,o.relation)).flatMap(f=>P(n(f.type),f.id,o.name)):o.op==="exclude"?[...h(o.base,u,l),...h(o.minus,u,l)]:o.parts.flatMap(f=>h(f,u,l))}function x(o,u,l){let f=n(o);s(f,l);let y=k(f,u);if(y===null)return[];let R=new Set;for(let g of P(f,y,l))G(g,o,u,l)&&R.add(g);return[...R].sort()}return{check:G,objects:q,subjects:x}}var ht=/\{\{access:([a-z][a-z0-9_]*(?:\.[a-z][a-z0-9_]*)?)\}\}/g,tn=t=>`{{access:${t}}}`,Hn=t=>t!==void 0&&t.includes("{{access:"),nn=/^[a-z][a-z0-9_]{0,39}(\.[a-z][a-z0-9_]{0,39})?$/,Kn={text:"text",uuid:"uuid",bigint:"int8",integer:"int4",smallint:"int2",boolean:"bool",numeric:"numeric",real:"float4","double precision":"float8","character varying":"varchar"};function Wn(t){let e=new Set(t.enums.flatMap(n=>[`${n.schema}.${n.name}`,n.name]));return ut(t.tables.filter(n=>!n.ignored).map(n=>{let s={},i=[];for(let p of n.columns){if(p.ignored)continue;let b=p.type.replace(/\(.*\)$/,"");e.has(b.replaceAll('"',""))&&i.push(p.name),s[p.name]=Kn[b]??b}let r=p=>n.columns.some(b=>b.name===p&&!b.nullable&&!b.ignored),m=[...new Set([...n.primaryKey.length===1?n.primaryKey:[],...n.uniques.filter(p=>p.columns.length===1&&r(p.columns[0])).map(p=>p.columns[0])])],a=(n.primaryKey.length>0?1:0)+n.uniques.length+n.indexes.length;return{schema:n.schema,name:n.name,primaryKey:n.primaryKey,identifying:m,indexes:a,columns:s,enums:i}}))}function qn(t,e){let n=[];for(let s of t.tables){let i=e(s);if(i!==void 0)for(let r of s.policies)for(let m of`${r.using??""} ${r.withCheck??""}`.matchAll(ht))n.push({type:i,name:m[1]})}return n}function Bn(t,e){let n=[],s=i=>i===void 0?null:[...i.matchAll(ht)].map(r=>r[1]);for(let i of t.tables){let r=e(i);if(r!==void 0)for(let m of i.policies)n.push({type:r,command:m.for,using:s(m.using),check:s(m.withCheck)})}return n}function Xn(t,e,n){if(t.access===void 0)return null;let s=he(ge(t.access.text));for(let r of s.types.values())if(r.rows.length>0)throw new _("not_supported",`type ${r.name} has a rows rule: in an app whose tables Palgres makes, a table's row policy is written with the table \u2014 policy(...).using((p) => p.can('${r.rows[0]?.name}'))`);let i=r=>[...s.types.values()].find(m=>m.table?.schema===r.schema&&m.table.name===r.name)?.name;return We(s,Wn(t),t.access.text,{roles:e,rows:!1,policies:qn(t,i),guards:Bn(t,i),...n===void 0?{}:{aliases:n}})}function yo(t,e,n){return Xn({...t,access:{text:e,compiled:""}},n).digest}function bo(t,e){let n=he(ge(e)),s=[];for(let i of n.types.values())for(let r of i.relations.values())if(r.kind==="stored")for(let m of r.subjects)s.push([i.name,r.name,m]);return{digest:t.digest,schema:t.schema,names:t.names,tables:t.tables,predicates:t.predicates,stored:s}}function Ro(t,e,n){if(!Hn(t))return{sql:t};if(!n)return{refused:"the schema declares no access schema for it to read"};let s=n.tables.find(m=>m.schema===e.schema&&m.name===e.name)?.type;if(s===void 0)return{refused:`no type of the access schema names the table ${e.schema}.${e.name}`};let i,r=t.replaceAll(ht,(m,a)=>{let p=n.predicates.find(b=>b.type===s&&b.name===a);return p||(i=a),`(${p?.sql??"false"})`});return i!==void 0?{refused:`type ${s} of the access schema has no relation or permission "${i}" a subject can hold`}:{sql:r}}var Y=class t{expr;constructor(e){this.expr=e}bin(e,n){return new t({kind:"binop",op:e,left:this.expr,right:Vn(n)})}eq(e){return this.bin("eq",e)}neq(e){return this.bin("neq",e)}gt(e){return this.bin("gt",e)}gte(e){return this.bin("gte",e)}lt(e){return this.bin("lt",e)}lte(e){return this.bin("lte",e)}isNull(e=!1){return new t({kind:"isNull",expr:this.expr,negated:e})}and(...e){return new t({kind:"and",parts:[this.expr,...e.map(n=>n.expr)]})}or(...e){return new t({kind:"or",parts:[this.expr,...e.map(n=>n.expr)]})}not(){return new t({kind:"not",expr:this.expr})}};function Vn(t){return t instanceof Y?t.expr:{kind:"lit",value:t}}function Ne(t,e=0,n=""){let s=`pb_e${e}`;return{col:i=>new Y(e===0?{kind:"col",name:i}:{kind:"col",name:i,alias:s}),auth:{uid:()=>new Y({kind:"authUid"})},can:i=>{if(e!==0)throw new Error(`policy expression: can("${i}") is about the policy's own row \u2014 use it outside existsIn`);if(!nn.test(i))throw new Error(`policy expression: can("${i}") \u2014 a relation or a permission is lowercase letters, digits and underscores, with at most one dot (code.write)`);return new Y({kind:"access",name:i})},lit:i=>new Y({kind:"lit",value:i}),and:(...i)=>new Y({kind:"and",parts:i.map(r=>r.expr)}),or:(...i)=>new Y({kind:"or",parts:i.map(r=>r.expr)}),not:i=>new Y({kind:"not",expr:i.expr}),existsIn:(i,r)=>{let m=i[Be],a=Ne(Object.keys(m.columns),e+1,n),p={kind:"exists",table:m.name,alias:`pb_e${e+1}`,outer:n,predicate:r(a).expr};return Object.defineProperty(p,ue,{value:m,enumerable:!1,configurable:!0}),new Y(p)}}}function X(t){return`"${t.replace(/"/g,'""')}"`}var ke=class{_def;constructor(e){this._def={name:e,command:"all",roles:["authenticated"],using:null,withCheck:null,permissive:!0}}for(e){return this._def.command=e,this}to(...e){return this._def.roles=e,this}using(e){return this._def.using=e instanceof Y?e.expr:e,this}memberOf(e,n,s={}){if(this._def.using!==null)throw new Error(`policy(${this._def.name}).memberOf(): this policy already has a using() expression. Write one or the other \u2014 memberOf IS the using expression.`);let i=s.column??"id",r=s.userColumn??"user_id";return this._def.using=`${X(i)} IN (SELECT ${X(n)} FROM ${X(e)} WHERE ${X(r)} = (select auth.uid()))`,this}withCheck(e){return this._def.withCheck=e instanceof Y?e.expr:e,this}withoutIndexes(){return this._def.indexes=!1,this}as(e){return this._def.permissive=e==="permissive",this}};function xo(t){return new ke(t)}function Le(t,e){switch(t.kind){case"exists":throw new Error(`check(${e}): \`existsIn(...)\` is a subquery and PostgreSQL forbids subqueries in a CHECK constraint \u2014 express a cross-table rule as a composite FOREIGN KEY (foreignKeys), or as a guard.`);case"access":throw new Error(`check(${e}): \`can("${t.name}")\` asks who the caller is, and a CHECK constraint is true of the row whoever writes it \u2014 say it in a policy (\`withCheck\`)`);case"authUid":throw new Error(`check(${e}): \`auth.uid()\` renders as a subquery \`(SELECT auth.uid())\` and PostgreSQL forbids subqueries in a CHECK constraint \u2014 a caller-dependent rule belongs in an RLS policy, not a CHECK.`);case"binop":Le(t.left,e),Le(t.right,e);return;case"and":case"or":for(let n of t.parts)Le(n,e);return;case"not":case"isNull":Le(t.expr,e);return;default:return}}var Yn={eq:"=",neq:"<>",gt:">",gte:">=",lt:"<",lte:"<="};function on(t){if(t===null)return"NULL";if(typeof t=="boolean")return t?"true":"false";if(typeof t=="number"){if(!Number.isFinite(t))throw new Error(`check(): ${t} is not an SQL number literal.`);return String(t)}return`'${t.replace(/'/g,"''")}'`}function Te(t,e){switch(t.kind){case"col":return X(t.name);case"lit":return on(t.value);case"binop":{let n=Yn[t.op];if(n===void 0)throw new Error(`check(${e}): \`${t.op}\` is not supported in a CHECK expression.`);return`(${Te(t.left,e)} ${n} ${Te(t.right,e)})`}case"and":case"or":{if(t.parts.length===0)return t.kind==="and"?"(true)":"(false)";let n=t.kind==="and"?" AND ":" OR ";return`(${t.parts.map(s=>Te(s,e)).join(n)})`}case"not":return`(NOT ${Te(t.expr,e)})`;case"isNull":return`(${Te(t.expr,e)} IS ${t.negated?"NOT NULL":"NULL"})`;default:{let n=t.kind;throw new Error(`check(${e}): a \`${n}\` node is not one a CHECK expression takes.`)}}}function zn(t,e){if(t.trim()==="")throw new Error("check(): the constraint's name cannot be empty \u2014 Palbase reconciles CHECKs by name.");return Le(e.expr,t),{name:t,expr:Te(e.expr,t)}}function Ao(t){if(t!==null)return typeof t=="string"?t:de(t,"")}var Jn={eq:"=",neq:"<>",gt:">",gte:">=",lt:"<",lte:"<="};function sn(t){let e=t.indexOf(".");return e<0?`${X("public")}.${X(t)}`:`${X(t.slice(0,e))}.${X(t.slice(e+1))}`}function de(t,e){switch(t.kind){case"col":return t.alias!==void 0?`${X(t.alias)}.${X(t.name)}`:e===""?X(t.name):`${sn(e)}.${X(t.name)}`;case"authUid":return"(SELECT auth.uid())";case"access":return tn(t.name);case"lit":return on(t.value);case"binop":{let n=Jn[t.op];if(n===void 0)throw new Error(`policy expression: \`${t.op}\` is not an operator a policy can use`);return`(${de(t.left,e)} ${n} ${de(t.right,e)})`}case"and":case"or":return t.parts.length===0?t.kind==="and"?"(true)":"(false)":`(${t.parts.map(n=>de(n,e)).join(t.kind==="and"?" AND ":" OR ")})`;case"not":return`(NOT ${de(t.expr,e)})`;case"isNull":return`(${de(t.expr,e)} IS ${t.negated?"NOT NULL":"NULL"})`;case"exists":if(t.outer==="")throw new Error("policy expression: an existsIn carries no outer table \u2014 its correlation would collapse to x = x and filter nothing");return`EXISTS (SELECT 1 FROM ${sn(t.table)} ${X(t.alias)} WHERE (${de(t.predicate,t.outer)}))`}}function $t(t,e){return t===""||t==="public"?e:`${t}.${e}`}var Xe=class{_def;constructor(e){if(e.trim()==="")throw new Error("index(name): an index's name cannot be empty \u2014 Palbase reconciles indexes by name.");this._def={name:e}}unique(){return this._def.unique=!0,this}on(...e){return this._def.columns=e.map(n=>{let s=n.expr;if(s.kind!=="col")throw new Error(`index(${this._def.name}).on(): takes column references only \u2014 for an expression, use onExpression("\u2026").`);return s.name}),this}onExpression(e){return this._def.expression=e,this}where(e){return this._def.where=e.expr,this}desc(){return this._def.sort="desc",this}asc(){return this._def.sort="asc",this}nulls(e){return this._def.nulls=e,this}include(e){return this._def.include=e,this}};function ko(t){return new Xe(t)}function Qn(t){return t instanceof ke?t._def:t}var Be=Symbol.for("palbase.table.meta");function jo(t,e){if(t.trim()==="")throw new Error("defineTable(name, \u2026): name must not be empty");let n=(e.policies?.(Ne(Object.keys(e.columns),0,t))??[]).map(Qn),s=n.length>0||e.rls!==!1,i={};for(let[I,j]of Object.entries(e.columns)){let L=j;ss(t,I,L._def),ts(t,I,L._def,e.columns);let v=Object.create(Object.getPrototypeOf(L));Object.defineProperty(v,"_def",{value:{...L._def},enumerable:!0,writable:!0}),i[I]=v}let r={name:t,columns:i,rls:s,policies:n};if(e.primaryKey!==void 0&&(r.primaryKey=[...e.primaryKey]),e.search!==void 0&&(r.search=Zn(t,e.search,i,r.primaryKey)),e.unique!==void 0&&(r.unique=e.unique.map(I=>({name:I.name,columns:[...I.columns]}))),e.raw!==void 0&&e.raw.length>0){for(let I of e.raw)if(I.drop!==void 0)throw new Error(`defineTable(${JSON.stringify(t)}): raw ${JSON.stringify(I.name)} carries a drop, but a table-level raw() has no teardown \u2014 a drop is run only for a schema-level unit: defineSchema(name, { tables, raw: [raw(name, up, { drop })] })`);r.raw=e.raw.slice()}let m=typeof e.checks=="function"?e.checks(Ne(Object.keys(e.columns),0,t)):e.checks?.slice()??[];m.length>0&&(r.checks=m);let a=(e.indexes?.(Ne(Object.keys(e.columns),0,t))??[]).map(I=>I instanceof Xe?I._def:I);a.length>0&&(r.indexes=a);let p=(e.foreignKeys?.(Ne(Object.keys(e.columns),0,t))??[]).map(Lt);p.length>0&&(r.foreignKeys=p),e.ignored===!0&&(r.ignored=!0),ns(t,r);for(let I of Object.values(i))I._def.ownerTable=r;let b={...i};return Object.defineProperty(b,Be,{value:r,enumerable:!1}),b}function Zn(t,e,n,s){if(e===null||typeof e!="object")throw new Error(`defineTable(${JSON.stringify(t)}): search is { from: [...columns], model } \u2014 got ${e===null?"null":typeof e}`);let i={from:Array.isArray(e.from)?[...e.from]:e.from,model:e.model,dimensions:e.dimensions??tt,metric:e.metric??"cosine",staleness:e.staleness??"null"},r=Object.entries(n).map(([a,p])=>({name:a,def:p._def})),m=nt(`defineTable(${JSON.stringify(t)})`,{columns:r.map(({name:a,def:p})=>({name:a,type:p.type==="sql"?p.sqlType??"sql":p.type,...p.ignored?{ignored:!0}:{},...p.generated?{generated:p.generated}:{}})),primaryKey:s??r.filter(({def:a})=>a.primaryKey===!0).map(({name:a})=>a)},i);if(m.length>0)throw new Error(m.join(`
309
+ `));return i}var yt=new WeakMap;function es(t,e){for(let n of Object.values(t))os(n,`table "${n.name}"`,e);for(let n of Object.values(t))for(let[s,i]of Object.entries(n.columns)){let r=i._def;if(r.selfRefColumn!==void 0){if(!(r.selfRefColumn in n.columns))throw new Error(`table "${n.name}" column "${s}": selfReferences("${r.selfRefColumn}") \u2014 no such column on this table`);r.references={table:$t(e,n.name),column:r.selfRefColumn};continue}if(r.referencesThunk===void 0)continue;let m=r.referencesThunk(),a=m?._def?.ownerTable;if(a===void 0)throw new Error(`table "${n.name}" column "${s}": references(() => \u2026) must point at a column of a table declared with defineTable(...)`);let p=Object.entries(a.columns).find(([,I])=>I._def===m._def)?.[0];if(p===void 0)throw new Error(`table "${n.name}" column "${s}": the referenced column was not found on table "${a.name}"`);let b=yt.get(a);if(b===void 0)throw new Error(`table "${n.name}" column "${s}": references(() => \u2026) points at table "${a.name}", which no defineSchema(...) has claimed yet \u2014 a foreign key cannot be written without its target's schema. Declare that table's schema first (one file per schema: db/public.ts, db/billing.ts \u2026, imported by this one).`);r.references={table:$t(b,a.name),column:p}}}function ts(t,e,n,s){if(n.encrypted===void 0)return;let i=`${e}_lookup`,r=n.defaultValue!==void 0||n.defaultSql!==void 0||n.defaultRandom===!0||n.defaultNow===!0?"it has a default \u2014 the database would write it in plain text; give the value in the write":n.fill!==void 0?".fillWith() is SQL over the row in plain text; give the value in the write":n.primaryKey===!0?"it is the primary key \u2014 a key the database matches rows by cannot be ciphertext; keep an id, and the encrypted value beside it":n.references!==void 0||n.referencesThunk!==void 0?"it references another table \u2014 a foreign key compares values the database cannot read":n.identity!==void 0||n.generated!==void 0?"the database makes its value":n.user!==void 0?"it holds a user's id, which the platform matches rows by":n.codec!==void 0||n.transform!==void 0?"it has a codec or a transform \u2014 encryption is its transform":n.unique===!0&&!n.encrypted.lookup?".unique() needs { lookup: true } \u2014 what equality is kept by is the lookup":i in s?`the table has a column "${i}" of its own, where the lookup is kept`:null;if(r!==null)throw new Error(`defineTable(${JSON.stringify(t)}): column "${e}" \u2014 .encrypted(): ${r}`)}function ns(t,e){let n=i=>e.columns[i]?._def.encrypted,s=i=>{throw new Error(`defineTable(${JSON.stringify(t)}): ${i}`)};for(let i of e.primaryKey??[])n(i)&&s(`the primary key names "${i}", which is .encrypted() \u2014 keep an id, and the encrypted value beside it`);for(let i of e.unique??[])for(let r of i.columns){let m=n(r);m&&!m.lookup&&s(`unique ${JSON.stringify(i.name)} names "${r}", which is .encrypted() without { lookup: true } \u2014 what equality is kept by is the lookup`)}for(let i of e.indexes??[]){let r=JSON.stringify([i.keys??[],i.columns??[]]);for(let m of Object.keys(e.columns))n(m)&&r.includes(JSON.stringify(m))&&s(`index ${JSON.stringify(i.name)} names "${m}", which is .encrypted() \u2014 an index of ciphertext orders nothing; equality is found by { lookup: true }, which is indexed`)}for(let i of e.search?.from??[])n(i)&&s(`search reads "${i}", which is .encrypted() \u2014 its text is not in the database to embed`)}function ss(t,e,n){if(n.fill===void 0)return;let s=n.defaultValue!==void 0||n.defaultRandom===!0||n.defaultNow===!0||n.defaultSql!==void 0?"the column has a default \u2014 the default already fills every row; keep one of the two":null;if(s!==null)throw new Error(`defineTable(${JSON.stringify(t)}): column "${e}" \u2014 .fillWith(): ${s}`)}function Do(t,e){if(typeof t!="string")throw new Error(`defineSchema(...) takes the schema NAME first: defineSchema("public", { tables: [todos, lists] }). The one-argument form defineSchema({ tables: { \u2026 } }) is gone \u2014 a schema that does not say its own name cannot be told apart from another schema's table of the same name, which is what a cross-schema foreign key has to do. Migrate db/public.ts (one file per schema: db/public.ts, db/billing.ts \u2026): name the schema, and lift each table key onto the table itself with defineTable("todos", { columns: { \u2026 } }), then list the tables in the array.`);if(t.trim()==="")throw new Error("defineSchema(name, \u2026): name must not be empty");let n={};for(let m of e.tables){let a=m[Be];if(n[a.name]!==void 0)throw new Error(`defineSchema("${t}"): two tables declare the name "${a.name}" \u2014 table names must be unique within a schema`);n[a.name]=a,yt.set(a,t)}es(n,t);let s=[...new Set(e.extensions??[])],i=(e.raw??[]).slice(),r=new Set;for(let m of i){if(typeof m.name!="string"||m.name.trim()==="")throw new Error(`defineSchema("${t}"): a raw unit needs a name`);if(r.has(m.name))throw new Error(`defineSchema("${t}"): two raw units are named "${m.name}" \u2014 a unit's name identifies it`);r.add(m.name)}return{name:t,tables:n,extensions:s,raw:i}}function os(t,e,n){let s=(m,a)=>{let p=m[ue];if(p===void 0)return;let b;try{b=typeof p=="function"?p():p}catch(L){throw new Error(`${e}: ${a} names its target through a callback that failed: ${L.message}`)}if(b==null||typeof b.name!="string")throw new Error(`${e}: ${a}'s callback does not answer a table \u2014 write references(() => otherTable, \u2026)`);let I=yt.get(b);if(I===void 0)throw new Error(`${e}: ${a} points at table "${b.name}", which no defineSchema(...) has claimed yet \u2014 a cross-table reference cannot be written without its target's schema. Declare that table's schema first (one file per schema: db/public.ts, db/billing.ts \u2026, imported by this one).`);let j=$t(I,b.name);m.refTable!==void 0&&(m.refTable=j),m.table!==void 0&&(m.table=j)};for(let m of t.foreignKeys??[])s(m,`foreignKey("${m.name}")`);let i=`${n}.${t.name}`,r=(m,a)=>{if(!(m==null||typeof m=="string"))switch(m.kind){case"exists":s(m,a),m.table.includes(".")||(m.table=`public.${m.table}`),m.outer=i,r(m.predicate,a);return;case"binop":r(m.left,a),r(m.right,a);return;case"and":case"or":for(let p of m.parts)r(p,a);return;case"not":case"isNull":r(m.expr,a);return;default:return}};for(let m of t.policies)r(m.using,`policy("${m.name}")`),r(m.withCheck,`policy("${m.name}")`);for(let m of t.indexes??[])r(m.where,`index("${m.name}")`)}export{is as a,as as b,St as c,cs as d,te as e,et as f,ls as g,bn as h,nt as i,us as j,It as k,ps as l,ms as m,_ as n,ge as o,K as p,Ee as q,he as r,oe as s,Se as t,Ke as u,jn as v,Fn as w,Mn as x,re as y,en as z,Hn as A,Xn as B,yo as C,bo as D,Ro as E,ve as F,Tn as G,$t as H,Xe as I,ko as J,Be as K,jo as L,Do as M,Y as N,Ne as O,ke as P,xo as Q,zn as R,Ao as S};