palgres 0.55.0 → 0.56.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.
@@ -1,5 +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)
1
+ /*! palgres 0.56.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"./YTA5WUZJ.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
3
  AND NOT i.indnullsnotdistinct AND ${e}.reloptions IS NULL
4
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
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};
@@ -1,2 +1,2 @@
1
- /*! palgres 0.55.0 — Palbase SDK License (see LICENSE) */
2
- import{A as x,C as A,S as w,a as g,b as D,f as K,g as _,k as N,n as P,o as k,r as S}from"./DLP3GKUJ.js";var q={uuid:"uuid",text:"text",integer:"integer",bigint:"bigint",numeric:"numeric",boolean:"boolean",timestamp:"timestamp with time zone",date:"date",jsonb:"jsonb"};function ne(e,n={}){let t=Array.isArray(e)?e:[e],i={tables:[],enums:[],extensions:[],raw:[]},a=new Map;for(let o of t){for(let l of Object.values(o.tables))i.tables.push(V(o.name,l,a));i.extensions.push(...o.extensions);for(let l of o.raw??[])i.raw.push({name:l.name,schema:o.name,sql:l.up,...l.drop!==void 0?{drop:l.drop}:{},...l.before===!0?{before:!0}:{}})}i.enums=[...a.values()];for(let o of t)for(let l of Object.values(o.tables))for(let r of l.raw??[])i.raw.push({name:r.name,table:`${o.name}.${l.name}`,sql:r.up});return n.access!==void 0&&(O(i,n.access),i.access={text:n.access,compiled:A(N(i),n.access,n.roles??{authenticated:"authenticated",service:"service_role"})}),i}function O(e,n){let t;try{t=S(k(n))}catch(i){if(i instanceof P)return;throw i}for(let i of t.types.values()){let a=i.table;if(!a)continue;let o=e.tables.find(r=>r.schema===a.schema&&r.name===a.name);if(!o||o.ignored)continue;let l=$.get(o);if(o.policies.some(r=>!l?.unindexedPolicies.has(r.name)&&(x(r.using)||x(r.withCheck))))for(let r of i.relations.values())r.kind==="column"&&U(o,r.column,l?.rawNames??new Set)}}var $=new WeakMap;function U(e,n,t){let i=new Set,a=r=>r[0]!==void 0&&i.add(r[0]);a(e.primaryKey);for(let r of e.uniques)a(r.columns);for(let r of e.indexes){let d=r.keys[0];d&&"column"in d&&r.where===void 0&&i.add(d.column)}let o=e.columns.find(r=>r.name===n);if(i.has(n)||!o||o.ignored)return;let l=`${e.name}_${n}_idx`;Buffer.byteLength(l)>63||e.indexes.some(r=>r.name===l)||t.has(l)||e.indexes.push({name:l,keys:[{column:n}],unique:!1})}function B(e,n){return!n&&D(e.onDelete,e.onUpdate)?{...e,deferrable:!0}:e}function Q(e){return e._def}function V(e,n,t){let i=[],a=s=>{let h=n.columns[s];return h!==void 0&&Q(h).encrypted?.lookup?g(s):s},o=(n.unique??[]).map(s=>({name:s.name,columns:s.columns.map(a)})),l=[],r=[],d=new Set,m=[];for(let[s,h]of Object.entries(n.columns)){let u=Q(h),c={name:s,type:j(e,s,n.name,u,t),nullable:u.nullable},E=F(u);E!==void 0&&(c.default=E),u.renamedFrom!==void 0&&(c.renamedFrom=u.renamedFrom),u.ignored&&(c.ignored=!0),u.fill!==void 0&&(c.fill=u.fill),u.identity!==void 0&&(c.identity=u.identity==="always"?"always":"by default"),u.generated!==void 0&&(c.generated={...u.generated}),u.user!==void 0&&(c.user={...u.user}),u.primaryKey&&r.push(s);let y=u.encrypted?.lookup?g(s):void 0;if(u.encrypted!==void 0&&(c.encrypted=y?{lookup:y}:{}),u.unique&&o.push(y?{name:`${n.name}_${y}_key`,columns:[y]}:{name:`${n.name}_${s}_key`,columns:[s]}),u.references!==void 0){let[b,R]=W(u.references.table);l.push(B({name:`${z(e,n.name)}_${s}_fkey`,columns:[s],refSchema:b,refTable:R,refColumns:[u.references.column],onDelete:u.onDeleteAction??"no action",onUpdate:u.onUpdateAction??"no action"},u.deferrable===!1)),u.index===!1&&d.add(s)}if(i.push(c),y){let b={name:y,type:"text",nullable:!0,lookupOf:s};u.renamedFrom!==void 0&&(b.renamedFrom=g(u.renamedFrom)),u.ignored&&(b.ignored=!0),i.push(b),u.unique||m.push({name:`${n.name}_${y}_idx`,keys:[{column:y}],unique:!1})}}for(let s of n.foreignKeys??[]){s.index===!1&&s.columns.length===1&&d.add(s.columns[0]);let[h,u]=W(s.refTable);l.push(B({name:s.name,columns:[...s.columns],refSchema:h,refTable:u,refColumns:[...s.refColumns],onDelete:s.onDelete??"no action",onUpdate:s.onUpdate??"no action",...s.match==="full"?{match:"full"}:{}},s.deferrable===!1))}let p={schema:e,name:n.name,columns:i,primaryKey:n.primaryKey!==void 0?[...n.primaryKey]:r,uniques:o,indexes:[...(n.indexes??[]).map(I),...m],checks:(n.checks??[]).map(s=>({name:s.name,expr:s.expr})),foreignKeys:l,rls:n.rls,policies:n.policies.map(L)};n.ignored&&(p.ignored=!0),n.search!==void 0&&(p.search={...n.search,from:[...n.search.from]}),p.uniques=H(p.uniques);let C=new Set((n.raw??[]).map(s=>s.name)),T=new Set(n.policies.filter(s=>s.indexes===!1).map(s=>s.name));return M(p,d,C,T),$.set(p,{rawNames:C,unindexedPolicies:T}),p}function j(e,n,t,i,a){let o=i.type;if(o==="enum"||o==="enum[]"){let l=i.enumName,r=`${e}.${l}`,d=i.enumValues??[],m=a.get(r);if(m&&m.values.join()!==d.join())throw new Error(`enum ${r} is declared with different values by ${t}.${n}: (${m.values.join(", ")}) and (${d.join(", ")}) \u2014 one type has one list`);return a.set(r,{schema:e,name:l,values:[...d]}),o==="enum[]"?`${_(e,l)}[]`:_(e,l)}return o==="sql"?K(i.sqlType):o==="numeric"&&i.precision!==void 0?`numeric(${i.precision},${i.scale??0})`:o.endsWith("[]")?`${q[o.slice(0,-2)]??o.slice(0,-2)}[]`:q[o]??o}function F(e){if(e.defaultSql!==void 0)return e.defaultSql;if(e.defaultRandom)return"gen_random_uuid()";if(e.defaultNow)return e.type==="date"?"CURRENT_DATE":"now()";let n=e.defaultValue;if(n!==void 0){if(Array.isArray(n)&&n.length===0&&e.type.endsWith("[]"))return"'{}'";if(typeof n=="string")return`'${n.replace(/'/g,"''")}'`;if(typeof n=="boolean")return n?"true":"false";if(typeof n=="number"){if(!Number.isFinite(n))throw new Error(`default ${n} is not a number Postgres can store`);return String(n)}return n===null?"NULL":`'${JSON.stringify(n).replace(/'/g,"''")}'::jsonb`}}function I(e){let n=e.expression!==void 0?[{expr:e.expression}]:(e.columns??[]).map(a=>({column:a}));for(let a of n)e.sort==="desc"&&(a.desc=!0),e.nulls!==void 0&&(a.nulls=e.nulls);let t={name:e.name,keys:n,unique:e.unique===!0},i=e.where===void 0?void 0:w(e.where);return i!==void 0&&(t.where=i),e.include?.length&&(t.include=[...e.include]),t}function L(e){let n={name:e.name,for:e.command,to:e.roles.length===0?["public"]:[...e.roles]},t=w(e.using),i=w(e.withCheck);return t!==void 0&&(n.using=t),i!==void 0&&(n.withCheck=i),e.permissive||(n.restrictive=!0),n}function M(e,n,t,i){let a=new Set,o=r=>r[0]!==void 0&&a.add(r[0]);o(e.primaryKey);for(let r of e.uniques)o(r.columns);for(let r of e.indexes){let d=r.keys[0];d&&"column"in d&&r.where===void 0&&a.add(d.column)}let l=r=>{if(a.has(r)||e.columns.find(m=>m.name===r)?.ignored)return;let d=`${e.name}_${r}_idx`;Buffer.byteLength(d)>63||e.indexes.some(m=>m.name===d)||t.has(d)||(e.indexes.push({name:d,keys:[{column:r}],unique:!1}),a.add(r))};for(let r of e.foreignKeys)r.columns.length===1&&!n.has(r.columns[0])&&l(r.columns[0]);for(let r of e.policies)if(!i.has(r.name))for(let d of Y(e,r))l(d)}function Y(e,n){let t=[];for(let i of[n.using,n.withCheck])if(i!==void 0)for(let a of i.matchAll(/(?<![.\w"])"((?:[^"]|"")+)"(?!\s*\.)/g)){let o=a[1].replace(/""/g,'"');e.columns.some(l=>l.name===o)&&!t.includes(o)&&t.push(o)}return t}function W(e){let n=e.indexOf(".");return n<0?["public",e]:[e.slice(0,n),e.slice(n+1)]}function z(e,n){return e==="public"?n:`${e}_${n}`}function H(e){let n=new Map;return e.filter(t=>{let i=n.get(t.name);if(i===void 0)return n.set(t.name,t),!0;if(i.columns.join()!==t.columns.join())throw new Error(`palgres: unique ${t.name} is declared over (${i.columns.join(", ")}) and over (${t.columns.join(", ")}): give one of them another name`);return!1})}var v=new Set(["uuid","text","integer","bigint","numeric","boolean","timestamp","date","enum"]),re={number:{fromDb:e=>e==null?e:Number(e),toDb:e=>{if(e==null||typeof e!="number")return e==null?e:String(e);if(!Number.isFinite(e))throw new Error(`asNumber() cannot write ${e}: it is not a finite number, and the column holds one.`);if(Number.isInteger(e)&&!Number.isSafeInteger(e))throw new Error(`asNumber() cannot write ${e}: it is outside the safe integer range and would be stored as a different number. Declare .asDecimal() and hand this column a string.`);return String(e)},tsType:"number"},decimal:{fromDb:e=>e==null?e:String(e),toDb:e=>e==null?e:String(e),tsType:"string"}},f=class e{_def;constructor(n,t){this._def=t??{type:n,nullable:!1,primaryKey:!1}}primaryKey(){return this._def.primaryKey=!0,new e(this._def.type,this._def)}notNull(){return this._def.nullable=!1,new e(this._def.type,this._def)}nullable(){if(this._def.identity!==void 0)throw new Error(".nullable() on an identity column: an identity is always NOT NULL");return this._def.nullable=!0,new e(this._def.type,this._def)}default(n){return this._def.defaultValue=n,new e(this._def.type,this._def)}defaultRandom(){return this._def.defaultRandom=!0,new e(this._def.type,this._def)}defaultNow(){return this._def.defaultNow=!0,new e(this._def.type,this._def)}defaultSql(n){if(typeof n!="string"||n.trim()==="")throw new Error("defaultSql() takes the SQL of the default");return this._def.defaultSql=n,new e(this._def.type,this._def)}dbAssigned(){return this._def.dbAssigned=!0,new e(this._def.type,this._def)}array(){let n=this._def.type;if(!v.has(n))throw new Error(`${n} column: .array() is available on uuid(), text(), integer(), bigint(), numeric(), boolean(), timestamp(), date() and enumType()`);if(this._def.defaultValue!==void 0||this._def.defaultNow||this._def.defaultRandom||this._def.defaultSql!==void 0)throw new Error(`.array() comes before the default \u2014 write ${n}().array().default([])`);if(this._def.codec!==void 0||this._def.transform!==void 0)throw new Error(".array() cannot follow a codec or a transform \u2014 they convert one value, not a list of them");let t=`${n}[]`;return new e(t,{...this._def,type:t})}identity(n){if(this._def.type!=="integer"&&this._def.type!=="bigint"&&!(this._def.type==="sql"&&this._def.sqlType==="smallint"))throw new Error(`${this._def.type} column: .identity() is for integer(), bigint() and sqlType('smallint') columns`);if(this._def.defaultValue!==void 0||this._def.defaultNow||this._def.defaultRandom||this._def.defaultSql!==void 0||this._def.fill!==void 0)throw new Error(".identity() is the column's value \u2014 it cannot also have a default or a fill");let t=n?.always===!1?"byDefault":"always";return new e(this._def.type,{...this._def,nullable:!1,identity:t})}generated(n,t={}){if(typeof n!="string"||n.trim()==="")throw new Error(".generated() takes the SQL expression the column is");if(this._def.defaultValue!==void 0||this._def.defaultNow||this._def.defaultRandom||this._def.defaultSql!==void 0||this._def.fill!==void 0||this._def.identity!==void 0)throw new Error(".generated() is the column's value \u2014 it cannot also have a default, a fill or an identity");return new e(this._def.type,{...this._def,generated:{expr:n,stored:t.stored===!0}})}fillWith(n){return new e(this._def.type,{...this._def,fill:n})}renamedFrom(n){return this._def.renamedFrom=n,this}ignored(){return new e(this._def.type,{...this._def,ignored:!0})}encrypted(n={}){if(this._def.type!=="text")throw new Error(`.encrypted() is for a text() column \u2014 a ${this._def.type} column's value is not text to seal; keep it in a text() column (JSON.stringify it)`);return new e("text",{...this._def,encrypted:{lookup:n.lookup===!0}})}references(n,t){if(typeof n!="function")throw new Error('references(...) takes a callback: write references(() => otherTable.column). The two-string form references("table", "column") is gone \u2014 a string cannot be type-checked and cannot point at a table that does not exist yet.');return this._def.referencesThunk=n,t?.as!==void 0&&(this._def.refAs=t.as),t?.reverseAs!==void 0&&(this._def.reverseAs=t.reverseAs),t?.onDelete!==void 0&&(this._def.onDeleteAction=t.onDelete),t?.onUpdate!==void 0&&(this._def.onUpdateAction=t.onUpdate),t?.index===!1&&(this._def.index=!1),t?.deferrable===!1&&(this._def.deferrable=!1),new e(this._def.type,this._def)}selfReferences(n,t){return this._def.selfRefColumn=n,t?.as!==void 0&&(this._def.refAs=t.as),t?.onDelete!==void 0&&(this._def.onDeleteAction=t.onDelete),new e(this._def.type,this._def)}onDelete(n){return this._def.onDeleteAction=n,new e(this._def.type,this._def)}unique(){return this._def.unique=!0,new e(this._def.type,this._def)}asNumber(){return this.withCodec("number","asNumber")}asDecimal(){return this.withCodec("decimal","asDecimal")}withCodec(n,t){if(this._def.type!=="bigint"&&this._def.type!=="numeric")throw new Error(`${this._def.type} column: .${t}() is only available on bigint()/numeric() \u2014 those are the exact-precision types that surface as string.`);if(this._def.transform!==void 0)throw new Error(`.${t}() and .transform() are two ways to say the same thing on one column \u2014 keep .${t}().`);if(this._def.codec!==void 0)throw new Error(`column already declares .as${this._def.codec==="number"?"Number":"Decimal"}(); a column has ONE codec.`);return new e(this._def.type,{...this._def,codec:n})}transform(n){if(this._def.codec!==void 0)throw new Error("column already declares a named codec; .transform() and .as*() are two ways to say the same thing \u2014 keep the codec.");return new e(this._def.type,{...this._def,transform:n})}};function ie(){return new f("uuid")}function oe(){return new f("text")}function se(){return new f("integer")}function le(){return new f("bigint")}function ue(e){if(e===void 0)return new f("numeric");let{precision:n,scale:t=0}=e;if(!Number.isInteger(n)||n<1||n>1e3)throw new Error(`numeric({ precision: ${n} }): precision is a whole number from 1 to 1000`);if(!Number.isInteger(t)||t<0||t>n)throw new Error(`numeric({ precision: ${n}, scale: ${t} }): scale is a whole number from 0 to the precision`);return new f("numeric",{type:"numeric",nullable:!1,primaryKey:!1,precision:n,scale:t})}function ae(){return new f("date")}var J={uuid:"uuid()",text:"text()",integer:"integer()",int:"integer()",int4:"integer()",bigint:"bigint()",int8:"bigint()",numeric:"numeric()",decimal:"numeric()",boolean:"boolean()",bool:"boolean()",timestamptz:"timestamp()","timestamp with time zone":"timestamp()",date:"date()",jsonb:"jsonb()"};function de(e){let n=typeof e=="string"?e.trim():"";if(n==="")throw new Error('sqlType() takes the Postgres type, e.g. sqlType("inet")');let t=n.toLowerCase().replace(/\[\]$/,""),i=J[t];if(i!==void 0&&!(n.endsWith("[]")&&!v.has(i.slice(0,-2))))throw new Error(`sqlType(${JSON.stringify(n)}): the DSL has this type \u2014 declare it as ${i}${n.endsWith("[]")?".array()":""}`);return new f("sql",{type:"sql",nullable:!1,primaryKey:!1,sqlType:n})}var fe=new Set(["smallint","real","double precision"]),me=new Set(["json"]);function ce(){return new f("boolean")}function ye(){return new f("timestamp")}function pe(){return new f("jsonb")}function he(e,n){let t=new f("enum");return t._def.enumName=e,t._def.enumValues=[...n],t}function be(){let e=new f("text");return e._def.nullable=!1,e._def.user={onDelete:"cascade",owns:!0},e}function ge(e){let n=new f("text");return n._def.user={onDelete:e.onDelete,owns:!1},e.as!==void 0&&(n._def.refAs=e.as),n}export{ne as a,Y as b,re as c,f as d,ie as e,oe as f,se as g,le as h,ue as i,ae as j,de as k,fe as l,me as m,ce as n,ye as o,pe as p,he as q,be as r,ge as s};
1
+ /*! palgres 0.56.0 — Palbase SDK License (see LICENSE) */
2
+ import{A as x,C as A,S as w,a as g,b as D,f as K,g as _,k as N,n as P,o as k,r as S}from"./YTA5WUZJ.js";var q={uuid:"uuid",text:"text",integer:"integer",bigint:"bigint",numeric:"numeric",boolean:"boolean",timestamp:"timestamp with time zone",date:"date",jsonb:"jsonb"};function ne(e,n={}){let t=Array.isArray(e)?e:[e],i={tables:[],enums:[],extensions:[],raw:[]},a=new Map;for(let o of t){for(let l of Object.values(o.tables))i.tables.push(V(o.name,l,a));i.extensions.push(...o.extensions);for(let l of o.raw??[])i.raw.push({name:l.name,schema:o.name,sql:l.up,...l.drop!==void 0?{drop:l.drop}:{},...l.before===!0?{before:!0}:{}})}i.enums=[...a.values()];for(let o of t)for(let l of Object.values(o.tables))for(let r of l.raw??[])i.raw.push({name:r.name,table:`${o.name}.${l.name}`,sql:r.up});return n.access!==void 0&&(O(i,n.access),i.access={text:n.access,compiled:A(N(i),n.access,n.roles??{authenticated:"authenticated",service:"service_role"})}),i}function O(e,n){let t;try{t=S(k(n))}catch(i){if(i instanceof P)return;throw i}for(let i of t.types.values()){let a=i.table;if(!a)continue;let o=e.tables.find(r=>r.schema===a.schema&&r.name===a.name);if(!o||o.ignored)continue;let l=$.get(o);if(o.policies.some(r=>!l?.unindexedPolicies.has(r.name)&&(x(r.using)||x(r.withCheck))))for(let r of i.relations.values())r.kind==="column"&&U(o,r.column,l?.rawNames??new Set)}}var $=new WeakMap;function U(e,n,t){let i=new Set,a=r=>r[0]!==void 0&&i.add(r[0]);a(e.primaryKey);for(let r of e.uniques)a(r.columns);for(let r of e.indexes){let d=r.keys[0];d&&"column"in d&&r.where===void 0&&i.add(d.column)}let o=e.columns.find(r=>r.name===n);if(i.has(n)||!o||o.ignored)return;let l=`${e.name}_${n}_idx`;Buffer.byteLength(l)>63||e.indexes.some(r=>r.name===l)||t.has(l)||e.indexes.push({name:l,keys:[{column:n}],unique:!1})}function B(e,n){return!n&&D(e.onDelete,e.onUpdate)?{...e,deferrable:!0}:e}function Q(e){return e._def}function V(e,n,t){let i=[],a=s=>{let h=n.columns[s];return h!==void 0&&Q(h).encrypted?.lookup?g(s):s},o=(n.unique??[]).map(s=>({name:s.name,columns:s.columns.map(a)})),l=[],r=[],d=new Set,m=[];for(let[s,h]of Object.entries(n.columns)){let u=Q(h),c={name:s,type:j(e,s,n.name,u,t),nullable:u.nullable},E=F(u);E!==void 0&&(c.default=E),u.renamedFrom!==void 0&&(c.renamedFrom=u.renamedFrom),u.ignored&&(c.ignored=!0),u.fill!==void 0&&(c.fill=u.fill),u.identity!==void 0&&(c.identity=u.identity==="always"?"always":"by default"),u.generated!==void 0&&(c.generated={...u.generated}),u.user!==void 0&&(c.user={...u.user}),u.primaryKey&&r.push(s);let y=u.encrypted?.lookup?g(s):void 0;if(u.encrypted!==void 0&&(c.encrypted=y?{lookup:y}:{}),u.unique&&o.push(y?{name:`${n.name}_${y}_key`,columns:[y]}:{name:`${n.name}_${s}_key`,columns:[s]}),u.references!==void 0){let[b,R]=W(u.references.table);l.push(B({name:`${z(e,n.name)}_${s}_fkey`,columns:[s],refSchema:b,refTable:R,refColumns:[u.references.column],onDelete:u.onDeleteAction??"no action",onUpdate:u.onUpdateAction??"no action"},u.deferrable===!1)),u.index===!1&&d.add(s)}if(i.push(c),y){let b={name:y,type:"text",nullable:!0,lookupOf:s};u.renamedFrom!==void 0&&(b.renamedFrom=g(u.renamedFrom)),u.ignored&&(b.ignored=!0),i.push(b),u.unique||m.push({name:`${n.name}_${y}_idx`,keys:[{column:y}],unique:!1})}}for(let s of n.foreignKeys??[]){s.index===!1&&s.columns.length===1&&d.add(s.columns[0]);let[h,u]=W(s.refTable);l.push(B({name:s.name,columns:[...s.columns],refSchema:h,refTable:u,refColumns:[...s.refColumns],onDelete:s.onDelete??"no action",onUpdate:s.onUpdate??"no action",...s.match==="full"?{match:"full"}:{}},s.deferrable===!1))}let p={schema:e,name:n.name,columns:i,primaryKey:n.primaryKey!==void 0?[...n.primaryKey]:r,uniques:o,indexes:[...(n.indexes??[]).map(I),...m],checks:(n.checks??[]).map(s=>({name:s.name,expr:s.expr})),foreignKeys:l,rls:n.rls,policies:n.policies.map(L)};n.ignored&&(p.ignored=!0),n.search!==void 0&&(p.search={...n.search,from:[...n.search.from]}),p.uniques=H(p.uniques);let C=new Set((n.raw??[]).map(s=>s.name)),T=new Set(n.policies.filter(s=>s.indexes===!1).map(s=>s.name));return M(p,d,C,T),$.set(p,{rawNames:C,unindexedPolicies:T}),p}function j(e,n,t,i,a){let o=i.type;if(o==="enum"||o==="enum[]"){let l=i.enumName,r=`${e}.${l}`,d=i.enumValues??[],m=a.get(r);if(m&&m.values.join()!==d.join())throw new Error(`enum ${r} is declared with different values by ${t}.${n}: (${m.values.join(", ")}) and (${d.join(", ")}) \u2014 one type has one list`);return a.set(r,{schema:e,name:l,values:[...d]}),o==="enum[]"?`${_(e,l)}[]`:_(e,l)}return o==="sql"?K(i.sqlType):o==="numeric"&&i.precision!==void 0?`numeric(${i.precision},${i.scale??0})`:o.endsWith("[]")?`${q[o.slice(0,-2)]??o.slice(0,-2)}[]`:q[o]??o}function F(e){if(e.defaultSql!==void 0)return e.defaultSql;if(e.defaultRandom)return"gen_random_uuid()";if(e.defaultNow)return e.type==="date"?"CURRENT_DATE":"now()";let n=e.defaultValue;if(n!==void 0){if(Array.isArray(n)&&n.length===0&&e.type.endsWith("[]"))return"'{}'";if(typeof n=="string")return`'${n.replace(/'/g,"''")}'`;if(typeof n=="boolean")return n?"true":"false";if(typeof n=="number"){if(!Number.isFinite(n))throw new Error(`default ${n} is not a number Postgres can store`);return String(n)}return n===null?"NULL":`'${JSON.stringify(n).replace(/'/g,"''")}'::jsonb`}}function I(e){let n=e.expression!==void 0?[{expr:e.expression}]:(e.columns??[]).map(a=>({column:a}));for(let a of n)e.sort==="desc"&&(a.desc=!0),e.nulls!==void 0&&(a.nulls=e.nulls);let t={name:e.name,keys:n,unique:e.unique===!0},i=e.where===void 0?void 0:w(e.where);return i!==void 0&&(t.where=i),e.include?.length&&(t.include=[...e.include]),t}function L(e){let n={name:e.name,for:e.command,to:e.roles.length===0?["public"]:[...e.roles]},t=w(e.using),i=w(e.withCheck);return t!==void 0&&(n.using=t),i!==void 0&&(n.withCheck=i),e.permissive||(n.restrictive=!0),n}function M(e,n,t,i){let a=new Set,o=r=>r[0]!==void 0&&a.add(r[0]);o(e.primaryKey);for(let r of e.uniques)o(r.columns);for(let r of e.indexes){let d=r.keys[0];d&&"column"in d&&r.where===void 0&&a.add(d.column)}let l=r=>{if(a.has(r)||e.columns.find(m=>m.name===r)?.ignored)return;let d=`${e.name}_${r}_idx`;Buffer.byteLength(d)>63||e.indexes.some(m=>m.name===d)||t.has(d)||(e.indexes.push({name:d,keys:[{column:r}],unique:!1}),a.add(r))};for(let r of e.foreignKeys)r.columns.length===1&&!n.has(r.columns[0])&&l(r.columns[0]);for(let r of e.policies)if(!i.has(r.name))for(let d of Y(e,r))l(d)}function Y(e,n){let t=[];for(let i of[n.using,n.withCheck])if(i!==void 0)for(let a of i.matchAll(/(?<![.\w"])"((?:[^"]|"")+)"(?!\s*\.)/g)){let o=a[1].replace(/""/g,'"');e.columns.some(l=>l.name===o)&&!t.includes(o)&&t.push(o)}return t}function W(e){let n=e.indexOf(".");return n<0?["public",e]:[e.slice(0,n),e.slice(n+1)]}function z(e,n){return e==="public"?n:`${e}_${n}`}function H(e){let n=new Map;return e.filter(t=>{let i=n.get(t.name);if(i===void 0)return n.set(t.name,t),!0;if(i.columns.join()!==t.columns.join())throw new Error(`palgres: unique ${t.name} is declared over (${i.columns.join(", ")}) and over (${t.columns.join(", ")}): give one of them another name`);return!1})}var v=new Set(["uuid","text","integer","bigint","numeric","boolean","timestamp","date","enum"]),re={number:{fromDb:e=>e==null?e:Number(e),toDb:e=>{if(e==null||typeof e!="number")return e==null?e:String(e);if(!Number.isFinite(e))throw new Error(`asNumber() cannot write ${e}: it is not a finite number, and the column holds one.`);if(Number.isInteger(e)&&!Number.isSafeInteger(e))throw new Error(`asNumber() cannot write ${e}: it is outside the safe integer range and would be stored as a different number. Declare .asDecimal() and hand this column a string.`);return String(e)},tsType:"number"},decimal:{fromDb:e=>e==null?e:String(e),toDb:e=>e==null?e:String(e),tsType:"string"}},f=class e{_def;constructor(n,t){this._def=t??{type:n,nullable:!1,primaryKey:!1}}primaryKey(){return this._def.primaryKey=!0,new e(this._def.type,this._def)}notNull(){return this._def.nullable=!1,new e(this._def.type,this._def)}nullable(){if(this._def.identity!==void 0)throw new Error(".nullable() on an identity column: an identity is always NOT NULL");return this._def.nullable=!0,new e(this._def.type,this._def)}default(n){return this._def.defaultValue=n,new e(this._def.type,this._def)}defaultRandom(){return this._def.defaultRandom=!0,new e(this._def.type,this._def)}defaultNow(){return this._def.defaultNow=!0,new e(this._def.type,this._def)}defaultSql(n){if(typeof n!="string"||n.trim()==="")throw new Error("defaultSql() takes the SQL of the default");return this._def.defaultSql=n,new e(this._def.type,this._def)}dbAssigned(){return this._def.dbAssigned=!0,new e(this._def.type,this._def)}array(){let n=this._def.type;if(!v.has(n))throw new Error(`${n} column: .array() is available on uuid(), text(), integer(), bigint(), numeric(), boolean(), timestamp(), date() and enumType()`);if(this._def.defaultValue!==void 0||this._def.defaultNow||this._def.defaultRandom||this._def.defaultSql!==void 0)throw new Error(`.array() comes before the default \u2014 write ${n}().array().default([])`);if(this._def.codec!==void 0||this._def.transform!==void 0)throw new Error(".array() cannot follow a codec or a transform \u2014 they convert one value, not a list of them");let t=`${n}[]`;return new e(t,{...this._def,type:t})}identity(n){if(this._def.type!=="integer"&&this._def.type!=="bigint"&&!(this._def.type==="sql"&&this._def.sqlType==="smallint"))throw new Error(`${this._def.type} column: .identity() is for integer(), bigint() and sqlType('smallint') columns`);if(this._def.defaultValue!==void 0||this._def.defaultNow||this._def.defaultRandom||this._def.defaultSql!==void 0||this._def.fill!==void 0)throw new Error(".identity() is the column's value \u2014 it cannot also have a default or a fill");let t=n?.always===!1?"byDefault":"always";return new e(this._def.type,{...this._def,nullable:!1,identity:t})}generated(n,t={}){if(typeof n!="string"||n.trim()==="")throw new Error(".generated() takes the SQL expression the column is");if(this._def.defaultValue!==void 0||this._def.defaultNow||this._def.defaultRandom||this._def.defaultSql!==void 0||this._def.fill!==void 0||this._def.identity!==void 0)throw new Error(".generated() is the column's value \u2014 it cannot also have a default, a fill or an identity");return new e(this._def.type,{...this._def,generated:{expr:n,stored:t.stored===!0}})}fillWith(n){return new e(this._def.type,{...this._def,fill:n})}renamedFrom(n){return this._def.renamedFrom=n,this}ignored(){return new e(this._def.type,{...this._def,ignored:!0})}encrypted(n={}){if(this._def.type!=="text")throw new Error(`.encrypted() is for a text() column \u2014 a ${this._def.type} column's value is not text to seal; keep it in a text() column (JSON.stringify it)`);return new e("text",{...this._def,encrypted:{lookup:n.lookup===!0}})}references(n,t){if(typeof n!="function")throw new Error('references(...) takes a callback: write references(() => otherTable.column). The two-string form references("table", "column") is gone \u2014 a string cannot be type-checked and cannot point at a table that does not exist yet.');return this._def.referencesThunk=n,t?.as!==void 0&&(this._def.refAs=t.as),t?.reverseAs!==void 0&&(this._def.reverseAs=t.reverseAs),t?.onDelete!==void 0&&(this._def.onDeleteAction=t.onDelete),t?.onUpdate!==void 0&&(this._def.onUpdateAction=t.onUpdate),t?.index===!1&&(this._def.index=!1),t?.deferrable===!1&&(this._def.deferrable=!1),new e(this._def.type,this._def)}selfReferences(n,t){return this._def.selfRefColumn=n,t?.as!==void 0&&(this._def.refAs=t.as),t?.onDelete!==void 0&&(this._def.onDeleteAction=t.onDelete),new e(this._def.type,this._def)}onDelete(n){return this._def.onDeleteAction=n,new e(this._def.type,this._def)}unique(){return this._def.unique=!0,new e(this._def.type,this._def)}asNumber(){return this.withCodec("number","asNumber")}asDecimal(){return this.withCodec("decimal","asDecimal")}withCodec(n,t){if(this._def.type!=="bigint"&&this._def.type!=="numeric")throw new Error(`${this._def.type} column: .${t}() is only available on bigint()/numeric() \u2014 those are the exact-precision types that surface as string.`);if(this._def.transform!==void 0)throw new Error(`.${t}() and .transform() are two ways to say the same thing on one column \u2014 keep .${t}().`);if(this._def.codec!==void 0)throw new Error(`column already declares .as${this._def.codec==="number"?"Number":"Decimal"}(); a column has ONE codec.`);return new e(this._def.type,{...this._def,codec:n})}transform(n){if(this._def.codec!==void 0)throw new Error("column already declares a named codec; .transform() and .as*() are two ways to say the same thing \u2014 keep the codec.");return new e(this._def.type,{...this._def,transform:n})}};function ie(){return new f("uuid")}function oe(){return new f("text")}function se(){return new f("integer")}function le(){return new f("bigint")}function ue(e){if(e===void 0)return new f("numeric");let{precision:n,scale:t=0}=e;if(!Number.isInteger(n)||n<1||n>1e3)throw new Error(`numeric({ precision: ${n} }): precision is a whole number from 1 to 1000`);if(!Number.isInteger(t)||t<0||t>n)throw new Error(`numeric({ precision: ${n}, scale: ${t} }): scale is a whole number from 0 to the precision`);return new f("numeric",{type:"numeric",nullable:!1,primaryKey:!1,precision:n,scale:t})}function ae(){return new f("date")}var J={uuid:"uuid()",text:"text()",integer:"integer()",int:"integer()",int4:"integer()",bigint:"bigint()",int8:"bigint()",numeric:"numeric()",decimal:"numeric()",boolean:"boolean()",bool:"boolean()",timestamptz:"timestamp()","timestamp with time zone":"timestamp()",date:"date()",jsonb:"jsonb()"};function de(e){let n=typeof e=="string"?e.trim():"";if(n==="")throw new Error('sqlType() takes the Postgres type, e.g. sqlType("inet")');let t=n.toLowerCase().replace(/\[\]$/,""),i=J[t];if(i!==void 0&&!(n.endsWith("[]")&&!v.has(i.slice(0,-2))))throw new Error(`sqlType(${JSON.stringify(n)}): the DSL has this type \u2014 declare it as ${i}${n.endsWith("[]")?".array()":""}`);return new f("sql",{type:"sql",nullable:!1,primaryKey:!1,sqlType:n})}var fe=new Set(["smallint","real","double precision"]),me=new Set(["json"]);function ce(){return new f("boolean")}function ye(){return new f("timestamp")}function pe(){return new f("jsonb")}function he(e,n){let t=new f("enum");return t._def.enumName=e,t._def.enumValues=[...n],t}function be(){let e=new f("text");return e._def.nullable=!1,e._def.user={onDelete:"cascade",owns:!0},e}function ge(e){let n=new f("text");return n._def.user={onDelete:e.onDelete,owns:!1},e.as!==void 0&&(n._def.refAs=e.as),n}export{ne as a,Y as b,re as c,f as d,ie as e,oe as f,se as g,le as h,ue as i,ae as j,de as k,fe as l,me as m,ce as n,ye as o,pe as p,he as q,be as r,ge as s};
@@ -1,4 +1,4 @@
1
- /*! palgres 0.55.0 — Palbase SDK License (see LICENSE) */
1
+ /*! palgres 0.56.0 — Palbase SDK License (see LICENSE) */
2
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
3
  - ${e.join(`
4
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===`
package/dist/dsl.js CHANGED
@@ -1,2 +1,2 @@
1
- /*! palgres 0.55.0 — Palbase SDK License (see LICENSE) */
2
- import{a as b,d as g,e as C,f as w,g as R,h as T,i as P,j as h,k as A,n as U,o as B,p as E,q as K,r as k,s as I}from"./chunks/EBHTHWOS.js";import{F as n,G as i,H as f,I as a,J as l,K as p,L as u,M as m,N as s,O as y,P as c,Q as d,R as x,S as D}from"./chunks/DLP3GKUJ.js";function M(o,t,e){if(e===void 0)return{name:o,up:t};let r={name:o,up:t};return e.drop!==void 0&&(r.drop=e.drop),e.before===!0&&(r.before=!0),r}export{g as ColumnBuilder,n as ForeignKeyBuilder,a as IndexBuilder,c as PolicyBuilder,s as PolicyExprRef,p as TABLE_META,T as bigint,U as boolean,x as check,h as date,m as defineSchema,u as defineTable,K as enumType,y as exprCtx,i as foreignKey,l as index,R as integer,E as jsonb,P as numeric,k as ownedByUser,d as policy,D as policySQL,f as qualifiedTableKey,M as raw,A as sqlType,w as text,B as timestamp,b as toModel,I as userRef,C as uuid};
1
+ /*! palgres 0.56.0 — Palbase SDK License (see LICENSE) */
2
+ import{a as b,d as g,e as C,f as w,g as R,h as T,i as P,j as h,k as A,n as U,o as B,p as E,q as K,r as k,s as I}from"./chunks/LQHZIV3S.js";import{F as n,G as i,H as f,I as a,J as l,K as p,L as u,M as m,N as s,O as y,P as c,Q as d,R as x,S as D}from"./chunks/YTA5WUZJ.js";function M(o,t,e){if(e===void 0)return{name:o,up:t};let r={name:o,up:t};return e.drop!==void 0&&(r.drop=e.drop),e.before===!0&&(r.before=!0),r}export{g as ColumnBuilder,n as ForeignKeyBuilder,a as IndexBuilder,c as PolicyBuilder,s as PolicyExprRef,p as TABLE_META,T as bigint,U as boolean,x as check,h as date,m as defineSchema,u as defineTable,K as enumType,y as exprCtx,i as foreignKey,l as index,R as integer,E as jsonb,P as numeric,k as ownedByUser,d as policy,D as policySQL,f as qualifiedTableKey,M as raw,A as sqlType,w as text,B as timestamp,b as toModel,I as userRef,C as uuid};
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
- /*! palgres 0.55.0 — Palbase SDK License (see LICENSE) */
2
- import{a as ir,b as ar,c as sn,l as Gn,m as Xn}from"./chunks/EBHTHWOS.js";import{$ as fr,A as rr,B as or,C as Ee,D as Kn,E as $n,F as Si,G as Ht,H as Kt,I as lr,J as Ri,K as bi,L as rn,M as Tn,N as Y,O as Gt,P as Fe,Q as on,R as Vn,S as cr,T as ur,U as dr,V as Yn,W as Jn,X as Xt,Y as mr,Z as pr,_ as Sn,a as b,aa as Ni,b as M,ba as Ai,c as x,ca as Oi,d as ne,da as ki,e as Re,ea as Li,f as tr,fa as Ii,g as Oe,ga as Rn,h as me,ha as gr,i as Hn,ia as hr,j as yi,ja as zn,k as wi,ka as Qn,l as le,la as Er,m as pe,ma as yr,n as De,o as $i,p as Pe,q as Bt,r as Ti,s as en,t as nn,u as Wt,v as jt,w as tn,x as Me,y as ce,z as sr}from"./chunks/5EMZSH7B.js";import{A as _e,B as Zs,D as er,E as nr,H as be,a as js,b as Ze,c as Ge,d as Mt,e as F,f as ae,g as wn,h as Hs,i as Ks,j as Ft,k as he,l as Gs,m as Xe,n as Xs,o as Vs,r as Ys,s as qt,u as Js,v as zs,w as Ut,x as Qs}from"./chunks/DLP3GKUJ.js";import{createHash as vr}from"node:crypto";function Zn(t){return typeof t=="function"?t():Promise.resolve(t)}var wr="pbe1.";function an(t,e,n){return t==="public"?`${e}.${n}`:`${t}.${e}.${n}`}var ye="palgres.sealing",et=5e3,Vt=3*et,bn=class{going=new Map;get(e){return this.going.get(e)}get size(){return this.going.size}async read(e){let n;try{n=await e(`SELECT address, direction, phase FROM ${ye}`)}catch(s){let r=s.code??s.errno;if(r!=="42P01"&&r!=="3F000")throw s;n=[]}this.going=new Map(n.map(s=>[s.address,{direction:s.direction,phase:s.phase}]))}},Nn=t=>`"${t.replace(/"/g,'""')}"`;function $r(t,e){let n=Nn(t.column);return t.direction==="open"?{sql:`${n} LIKE 'pbe1.%'`,params:[]}:{sql:`(${n} NOT LIKE $1${t.lookup?` OR ${Nn(t.lookup)} IS NULL`:""})`,params:[`pbe1.${e.currentKey()}.%`]}}async function nt(t,e,n,s,r){let o=$r(e,n),i=Nn(e.column),a=s===null?"":` AND ctid > $${o.params.length+1}::tid`,l=await t(`SELECT ctid::text AS at, ${i} AS value FROM ${e.table} WHERE ${i} IS NOT NULL AND ${o.sql}${a} ORDER BY ctid LIMIT ${r}`,s===null?o.params:[...o.params,s]);if(l.length===0)return{done:0,last:null};let c=[],d=l.map(m=>{let f=Ci(n,e.address,m.value),h=[m.at,m.value,e.direction==="seal"?n.encrypt(e.address,f):f,...e.lookup?[n.lookup(e.address,f)]:[]],T=c.length+1;return c.push(...h),`(${h.map((g,p)=>`$${T+p}::text`).join(", ")})`}),w=[`${i} = v.next`,...e.lookup?[`${Nn(e.lookup)} = v.lookup`]:[]],u=await t(`WITH done AS (UPDATE ${e.table} AS t SET ${w.join(", ")} FROM (VALUES ${d.join(", ")}) AS v(at, old, next${e.lookup?", lookup":""}) WHERE t.ctid = v.at::tid AND t.${i} = v.old RETURNING 1) SELECT count(*)::int AS n FROM done`,c);return{done:Number(u[0]?.n??0),last:l.length<r?null:l[l.length-1].at}}function Ci(t,e,n){if(!t.isEncrypted(n))return n;try{return t.decrypt(e,n)}catch{return n}}function tt(t,e){if(typeof e=="string"&&e.startsWith(wr))throw new TypeError(`${t} is going over between plain and encrypted: a value beginning ${wr} would read as an encrypted one \u2014 it is written once the migration completes`)}async function Tr(t,e,n){let s=$r(e,n);return(await t(`SELECT 1 FROM ${e.table} WHERE ${Nn(e.column)} IS NOT NULL AND ${s.sql} LIMIT 1`,s.params)).length>0}import{createHash as Jt}from"node:crypto";var J="palgres_search",st=(t,e)=>t.model===e.model&&t.dimensions===e.dimensions&&t.metric===e.metric&&t.from.length===e.from.length&&t.from.every((n,s)=>n===e.from[s]),Sr=48;function Be(t,e){let n=t.replaceAll(".","__");return`${n.length<=Sr?n:`${n.slice(0,32)}_${Jt("md5").update(n).digest("hex").slice(0,12)}`}__g${e}`}var Rr=t=>({insert:`_palgres_search_g${t}_ins`,update:`_palgres_search_g${t}_upd`});function rt(t,e){let n=Jt("sha256").update(JSON.stringify([t.schema,t.name,e])).digest("hex").slice(0,8),s=`_palgres_search_${t.name}_${n}`;return Buffer.byteLength(s)<=63?s:`_palgres_search_${Jt("sha256").update(`${t.schema}.${t.name}`).digest("hex").slice(0,16)}_${n}`}function ot(t,e){let n=e===void 0?"":`${b(e)}.`;return t.map(s=>`coalesce(${n}${b(s)}::text, '')`).join(" || ' ' || ")}var it=(t,e)=>`to_tsvector('simple', ${ot(t,e)})`;function An(t,e){let n=t>Hs?"halfvec":"vector",s={cosine:["cosine","<=>"],euclidean:["l2","<->"],inner_product:["ip","<#>"]}[e];return{type:n,opclass:`${n}_${s[0]}_ops`,operator:s[1]}}function br(t){let e=`${t.table.schema}.${t.table.name}`,n=M(t.table.schema,t.table.name),s=Be(e,t.gen),r=M(J,s),o=An(t.search.dimensions,t.search.metric),i=b(t.pk.name),a=[t.roles.anon,t.roles.authenticated].map(b).join(", ");return[`INSERT INTO ${J}.generations (table_key, gen, model, dimensions, metric, from_columns, status, promoted_at) VALUES (${x(e)}, ${t.gen}, ${x(t.search.model)}, ${t.search.dimensions}, ${x(t.search.metric)}, ARRAY[${t.search.from.map(x).join(", ")}]::text[], ${x(t.status)}, ${t.status==="active"?"now()":"NULL"})`,`CREATE TABLE ${r} (
1
+ /*! palgres 0.56.0 — Palbase SDK License (see LICENSE) */
2
+ import{a as ir,b as ar,c as sn,l as Gn,m as Xn}from"./chunks/LQHZIV3S.js";import{$ as fr,A as rr,B as or,C as Ee,D as Kn,E as $n,F as Si,G as Ht,H as Kt,I as lr,J as Ri,K as bi,L as rn,M as Tn,N as Y,O as Gt,P as Fe,Q as on,R as Vn,S as cr,T as ur,U as dr,V as Yn,W as Jn,X as Xt,Y as mr,Z as pr,_ as Sn,a as b,aa as Ni,b as M,ba as Ai,c as x,ca as Oi,d as ne,da as ki,e as Re,ea as Li,f as tr,fa as Ii,g as Oe,ga as Rn,h as me,ha as gr,i as Hn,ia as hr,j as yi,ja as zn,k as wi,ka as Qn,l as le,la as Er,m as pe,ma as yr,n as De,o as $i,p as Pe,q as Bt,r as Ti,s as en,t as nn,u as Wt,v as jt,w as tn,x as Me,y as ce,z as sr}from"./chunks/JPYKRUNF.js";import{A as _e,B as Zs,D as er,E as nr,H as be,a as js,b as Ze,c as Ge,d as Mt,e as F,f as ae,g as wn,h as Hs,i as Ks,j as Ft,k as he,l as Gs,m as Xe,n as Xs,o as Vs,r as Ys,s as qt,u as Js,v as zs,w as Ut,x as Qs}from"./chunks/YTA5WUZJ.js";import{createHash as vr}from"node:crypto";function Zn(t){return typeof t=="function"?t():Promise.resolve(t)}var wr="pbe1.";function an(t,e,n){return t==="public"?`${e}.${n}`:`${t}.${e}.${n}`}var ye="palgres.sealing",et=5e3,Vt=3*et,bn=class{going=new Map;get(e){return this.going.get(e)}get size(){return this.going.size}async read(e){let n;try{n=await e(`SELECT address, direction, phase FROM ${ye}`)}catch(s){let r=s.code??s.errno;if(r!=="42P01"&&r!=="3F000")throw s;n=[]}this.going=new Map(n.map(s=>[s.address,{direction:s.direction,phase:s.phase}]))}},Nn=t=>`"${t.replace(/"/g,'""')}"`;function $r(t,e){let n=Nn(t.column);return t.direction==="open"?{sql:`${n} LIKE 'pbe1.%'`,params:[]}:{sql:`(${n} NOT LIKE $1${t.lookup?` OR ${Nn(t.lookup)} IS NULL`:""})`,params:[`pbe1.${e.currentKey()}.%`]}}async function nt(t,e,n,s,r){let o=$r(e,n),i=Nn(e.column),a=s===null?"":` AND ctid > $${o.params.length+1}::tid`,l=await t(`SELECT ctid::text AS at, ${i} AS value FROM ${e.table} WHERE ${i} IS NOT NULL AND ${o.sql}${a} ORDER BY ctid LIMIT ${r}`,s===null?o.params:[...o.params,s]);if(l.length===0)return{done:0,last:null};let c=[],d=l.map(m=>{let f=Ci(n,e.address,m.value),h=[m.at,m.value,e.direction==="seal"?n.encrypt(e.address,f):f,...e.lookup?[n.lookup(e.address,f)]:[]],T=c.length+1;return c.push(...h),`(${h.map((g,p)=>`$${T+p}::text`).join(", ")})`}),w=[`${i} = v.next`,...e.lookup?[`${Nn(e.lookup)} = v.lookup`]:[]],u=await t(`WITH done AS (UPDATE ${e.table} AS t SET ${w.join(", ")} FROM (VALUES ${d.join(", ")}) AS v(at, old, next${e.lookup?", lookup":""}) WHERE t.ctid = v.at::tid AND t.${i} = v.old RETURNING 1) SELECT count(*)::int AS n FROM done`,c);return{done:Number(u[0]?.n??0),last:l.length<r?null:l[l.length-1].at}}function Ci(t,e,n){if(!t.isEncrypted(n))return n;try{return t.decrypt(e,n)}catch{return n}}function tt(t,e){if(typeof e=="string"&&e.startsWith(wr))throw new TypeError(`${t} is going over between plain and encrypted: a value beginning ${wr} would read as an encrypted one \u2014 it is written once the migration completes`)}async function Tr(t,e,n){let s=$r(e,n);return(await t(`SELECT 1 FROM ${e.table} WHERE ${Nn(e.column)} IS NOT NULL AND ${s.sql} LIMIT 1`,s.params)).length>0}import{createHash as Jt}from"node:crypto";var J="palgres_search",st=(t,e)=>t.model===e.model&&t.dimensions===e.dimensions&&t.metric===e.metric&&t.from.length===e.from.length&&t.from.every((n,s)=>n===e.from[s]),Sr=48;function Be(t,e){let n=t.replaceAll(".","__");return`${n.length<=Sr?n:`${n.slice(0,32)}_${Jt("md5").update(n).digest("hex").slice(0,12)}`}__g${e}`}var Rr=t=>({insert:`_palgres_search_g${t}_ins`,update:`_palgres_search_g${t}_upd`});function rt(t,e){let n=Jt("sha256").update(JSON.stringify([t.schema,t.name,e])).digest("hex").slice(0,8),s=`_palgres_search_${t.name}_${n}`;return Buffer.byteLength(s)<=63?s:`_palgres_search_${Jt("sha256").update(`${t.schema}.${t.name}`).digest("hex").slice(0,16)}_${n}`}function ot(t,e){let n=e===void 0?"":`${b(e)}.`;return t.map(s=>`coalesce(${n}${b(s)}::text, '')`).join(" || ' ' || ")}var it=(t,e)=>`to_tsvector('simple', ${ot(t,e)})`;function An(t,e){let n=t>Hs?"halfvec":"vector",s={cosine:["cosine","<=>"],euclidean:["l2","<->"],inner_product:["ip","<#>"]}[e];return{type:n,opclass:`${n}_${s[0]}_ops`,operator:s[1]}}function br(t){let e=`${t.table.schema}.${t.table.name}`,n=M(t.table.schema,t.table.name),s=Be(e,t.gen),r=M(J,s),o=An(t.search.dimensions,t.search.metric),i=b(t.pk.name),a=[t.roles.anon,t.roles.authenticated].map(b).join(", ");return[`INSERT INTO ${J}.generations (table_key, gen, model, dimensions, metric, from_columns, status, promoted_at) VALUES (${x(e)}, ${t.gen}, ${x(t.search.model)}, ${t.search.dimensions}, ${x(t.search.metric)}, ARRAY[${t.search.from.map(x).join(", ")}]::text[], ${x(t.status)}, ${t.status==="active"?"now()":"NULL"})`,`CREATE TABLE ${r} (
3
3
  id ${t.pk.type} PRIMARY KEY REFERENCES ${n} (${i}) ON DELETE CASCADE,
4
4
  embedding ${b(t.types)}.${o.type}(${t.search.dimensions}) NOT NULL,
5
5
  model text NOT NULL,
package/dist/testing.js CHANGED
@@ -1,2 +1,2 @@
1
- /*! palgres 0.55.0 — Palbase SDK License (see LICENSE) */
2
- import{F as pe,G as be,P as G,Q as Re,R as ne,V as te,W as J,X as re,Y as $e,_ as B,ga as U,la as Oe,ma as Ie,n as he,p as me}from"./chunks/5EMZSH7B.js";import{o as we,r as ye,y as K,z as Q}from"./chunks/DLP3GKUJ.js";import{randomUUID as De}from"node:crypto";var Te=/^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/,ke="user";function Se(n){let t=n.filter(i=>i!=null);return t.length===0?"text":t.every(i=>typeof i=="boolean")?"bool":t.every(i=>typeof i=="bigint"||typeof i=="number"&&Number.isInteger(i))?"int":t.every(i=>typeof i=="bigint"||typeof i=="number"&&Number.isFinite(i))?"numeric":t.every(i=>typeof i=="string"&&Te.test(i))?"uuid":"text"}function Ce(n,t){return t==null?null:n==="bool"||n==="int"||n==="numeric"||typeof t=="string"?t:String(t)}var je=n=>n.schema==="public"?n.name:`${n.schema}.${n.name}`;function xe(n,t){let i=ye(we(n)),l=be(n,"memory"),g,f=[],m=[],p=new Map,O=[...i.types.values()].filter(y=>y.table),k=y=>{let d=i.types.get(y),w=new Set;if(!d?.table)return[];w.add(d.table.key??"id");let e=r=>{let s=r;s.parts?s.parts.forEach(e):s.part?e(s.part):s.column&&w.add(s.column)};for(let r of d.relations.values())r.kind==="column"&&(w.add(r.column),r.where&&e(r.where));return[...w]},S=()=>{let y=new Map;for(let d of O){let w=d.table,e=t.rows(je(w)),r=w.key??"id",s={};for(let a of k(d.name))s[a]=Se(e.map(u=>u[a]));let o={key:r,columns:s};y.set(d.name,{shape:o,rows:e.map(a=>Object.fromEntries(Object.entries(s).map(([u,c])=>[u,Ce(c,a[u])])))})}return{tables:y,relationships:f}},N=(y,d,w)=>{let e=y.tables.get(d);if(!e)return w;let r=e.shape.columns[e.shape.key],s=K(r,w);return s===null?null:e.rows.some(a=>{let u=a[e.shape.key];return u!==null&&K(r,String(u))===s})?s:void 0},M=()=>{for(let d of O){let w=d.table,e=je(w),r=w.key??"id",s=t.deleted(e),o=Math.min(p.get(e)??0,s.length),a=c=>Te.test(c)?c.toLowerCase():c,u=new Set(s.slice(o).map(c=>c[r]).filter(c=>c!=null).map(c=>a(String(c))));p.set(e,s.length),u.size>0&&C(d.name,c=>u.has(a(c)),"access: row deleted")}let y=S();for(let d of O)C(d.name,w=>N(y,d.name,w)===void 0,"access: row deleted");return S()},C=(y,d,w)=>{let e=[];for(let r of f)r.objectType===y&&d(r.objectId)||r.subjectType===y&&d(r.subjectId)?E("revoke",r,w):e.push(r);f=e},E=(y,d,w)=>{m.unshift({at:new Date().toISOString(),action:y,object:{type:d.objectType,id:d.objectId},relation:d.relation,subject:{type:d.subjectType,id:d.subjectId},by:w})},T=(y,d)=>(y.object_type===void 0||y.object_type===d.objectType)&&(y.object_id===void 0||y.object_id===d.objectId)&&(y.relation===void 0||y.relation===d.relation)&&(y.subject_type===void 0||y.subject_type===d.subjectType)&&(y.subject_id===void 0||y.subject_id===d.subjectId),D=(y,d)=>{for(let w of["objectType","objectId","relation","subjectType","subjectId"])if(y[w]!==d[w])return y[w]<d[w]?-1:1;return 0};return{names:l,via:{caller:()=>g,check(y,d,w,e){let r=M(),s=N(r,w,e);return s==null?!1:Q(i,r).check(y,w,s,d)},objects:(y,d,w)=>Q(i,M()).objects(y,w,d),subjects(y,d,w){let e=M(),r=N(e,d,w);return r==null?[]:Q(i,e).subjects(d,r,y)},change(y,d,w,e,r){let s=M(),o=(u,c,h)=>{if(c===ke)return h;let b=N(s,c,h);if(b==null)throw new pe("no_object",`Database.$access: there is no ${c} ${JSON.stringify(h)} (${u}) \u2014 a relationship is given on an object that exists`);return b};if(y==="revoke"){let u=($,A)=>{let x=$===ke?void 0:s.tables.get($);return x?K(x.shape.columns[x.shape.key],A):A},c=u(d.type,d.id),h=u(e.type,e.id);if(c===null||h===null)return!1;let b={objectType:d.type,objectId:c,relation:w,subjectType:e.type,subjectId:h},R=f.findIndex($=>D($,b)===0);return R<0?!1:(f.splice(R,1),E("revoke",b,r??g??null),!0)}let a={objectType:d.type,objectId:o("the object",d.type,d.id),relation:w,subjectType:e.type,subjectId:o("the subject",e.type,e.id)};return f.some(u=>D(u,a)===0)?!1:(f.push({...a,since:new Date().toISOString()}),E("grant",a,r??g??null),!0)},relationships(y,d){return M(),f.filter(w=>T(y,w)).sort(D).slice(0,d).map(w=>({object:{type:w.objectType,id:w.objectId},relation:w.relation,subject:{type:w.subjectType,id:w.subjectId},since:w.since}))},history(y,d){return M(),m.filter(w=>T(y,{objectType:w.object.type,objectId:w.object.id,relation:w.relation,subjectType:w.subject.type,subjectId:w.subject.id})).slice(0,d).map(w=>({...w,object:{...w.object},subject:{...w.subject}}))}},signedInAs(y){g=y},snapshot(){let y={relationships:f.map(d=>({...d})),history:m.map(d=>({...d})),seen:new Map(p),user:g};return()=>{f=y.relationships,m=y.history,p=y.seen,g=y.user}}}}var Fe=/^\d{4}-\d{2}-\d{2}([T ]\d{2}:\d{2}(:\d{2}(\.\d+)?)?)?(Z|[+-]\d{2}(:?\d{2})?)?$/,Pe=/^([+-]?)(\d*)(?:\.(\d*))?$/;function v(n){if(n instanceof Date)return n.getTime();if(typeof n=="string"&&Fe.test(n)){let t=Date.parse(n);return Number.isNaN(t)?null:t}return null}function V(n){if(typeof n=="number")return Number.isFinite(n)?V(String(n)):null;if(typeof n!="string"||/e/i.test(n))return null;let t=Pe.exec(n.trim());if(t===null||t[2]===""&&(t[3]??"")==="")return null;let i=t[3]??"";return{unit:BigInt(`${t[1]==="-"?"-":""}${t[2]===""?"0":t[2]}${i}`),scale:i.length}}function Y(n,t){return n.unit*10n**BigInt(t-n.scale)}function ce(n,t){if(n==null||t===null||t===void 0)return null;let i=v(n),l=v(t);if(i!==null&&l!==null)return Math.sign(i-l);let g=V(n),f=V(t);if(g!==null&&f!==null){let m=Math.max(g.scale,f.scale),p=Y(g,m)-Y(f,m);return p===0n?0:p<0n?-1:1}return typeof n==typeof t&&(typeof n=="string"||typeof n=="boolean"||typeof n=="number")?n<t?-1:n>t?1:0:null}function P(n,t){return n==null||t===null||t===void 0?!1:n instanceof Date||t instanceof Date?v(n)!==null&&v(n)===v(t):Array.isArray(n)&&Array.isArray(t)?n.length===t.length&&n.every((i,l)=>P(i,t[l])):n===t}function Z(n){let t=((n?.days??0)*86400+(n?.hours??0)*3600+(n?.minutes??0)*60+(n?.seconds??0))*1e3;return new Date(Date.now()-t).toISOString()}function se(n,t,i){if(n==null)return null;if(typeof n=="number"&&typeof t=="number")return n+i*t;let l=V(n),g=V(t);if(l===null||g===null)throw new Error(`increment()/decrement() on a value that is not a number (${JSON.stringify(n)}): Postgres refuses it ("operator does not exist")`);let f=Math.max(l.scale,g.scale),m=Y(l,f)+BigInt(i)*Y(g,f);if(f===0)return typeof n=="number"?Number(m):m.toString();let p=m<0n,O=(p?-m:m).toString().padStart(f+1,"0"),k=`${p?"-":""}${O.slice(0,-f)}.${O.slice(-f)}`;return typeof n=="number"?Number(k):k}function _e(n,t){let i=T=>{let D=(T.unit<0n?-T.unit:T.unit).toString().padStart(T.scale+1,"0"),q=D.slice(0,D.length-T.scale),y=D.slice(D.length-T.scale),d=q.padStart(Math.ceil(q.length/4)*4,"0").match(/.{4}/g)??[],w=y.padEnd(Math.ceil(y.length/4)*4,"0").match(/.{4}/g)??[],r=[...d.map((s,o)=>[d.length-1-o,Number(s)]),...w.map((s,o)=>[-1-o,Number(s)])].find(([,s])=>s!==0);return r?[r[0],r[1]]:[0,0]},[l,g]=i(n),[f,m]=i(t),p=l-f-(g<=m?1:0),O=Math.min(Math.max(16-p*4,n.scale,t.scale,0),1e3),k=n.unit*10n**BigInt(O+t.scale),S=t.unit*10n**BigInt(n.scale),N=k/S,M=k%S;2n*(M<0n?-M:M)>=(S<0n?-S:S)&&(N+=k<0n!=S<0n?-1n:1n);let C=N<0n,E=(C?-N:N).toString().padStart(O+1,"0");return`${C?"-":""}${O===0?E:`${E.slice(0,-O)}.${E.slice(-O)}`}`}var j=n=>structuredClone(n);function ue(n,t,i){if(Re(i))throw new Error(`${n}(${t}): the fake database runs no SQL, so a sqlFragment cannot be evaluated \u2014 write the filter in the filter language (gt, gte, lt, lte, neq, in, contains, isNull, OR, AND, NOT), or test this against Postgres`);if(!(i===null||typeof i!="object"))for(let[l,g]of Object.entries(i))if(l==="OR"||l==="AND")for(let f of Array.isArray(g)?g:[])ue(n,t,f);else l==="NOT"&&ue(n,t,g)}function W(n,t,i){return he(new me({fields:[{field:t,message:i}]},`${n}: ${t} ${i}`))}function le(n,t,i="where"){for(let[l,g]of Object.entries(t))if(l==="OR"||l==="AND"){let f=g;if(l==="AND"&&f.length===0)throw W(n,`${i}.AND`,"is an empty list \u2014 no condition at all. Leave it out, or name a condition in it.");f.forEach((m,p)=>{if(Object.keys(m).length===0)throw W(n,`${i}.${l}[${p}]`,"holds no condition \u2014 a branch that matches every row. Name a condition in it, or leave it out.");le(n,m,`${i}.${l}[${p}]`)})}else if(l==="NOT"){if(Array.isArray(g))throw W(n,`${i}.NOT`,"is a list \u2014 NOT takes one filter object. For several conditions, NOT: { AND: [...] } or NOT: { OR: [...] }.");if(Object.keys(g).length===0)throw W(n,`${i}.NOT`,"holds no condition \u2014 NOT of nothing is not a filter. Name the condition to exclude.");le(n,g,`${i}.NOT`)}else if(l==="has"&&Object.keys(g??{}).length===0)throw W(n,`${i}.has`,"names no relation \u2014 no condition. Name one: has: { <relation>: { \u2026 } }.")}function L(n,t){if(Object.keys(t).length===0)throw W(n,"where",`holds no condition, so ${n} would reach EVERY row of the table. Name a condition.`)}function fe(n){let t=!1;for(let i of n){if(i===!1)return!1;i===null&&(t=!0)}return t?null:!0}function Ee(n){let t=!1;for(let i of n){if(i===!0)return!0;i===null&&(t=!0)}return t?null:!1}var F=n=>n==null;function H(n,t,i,l){return fe(Object.entries(l).map(([g,f])=>{if(g==="OR")return Ee(f.map(m=>H(n,t,i,m)));if(g==="AND")return fe(f.map(m=>H(n,t,i,m)));if(g==="NOT"){let m=H(n,t,i,f);return m===null?null:!m}if(g==="has")throw new Error(`${n}(${t}): the fake database has no relations, so a \`has\` filter cannot be decided for a row \u2014 read the related table first and filter by its ids ({ id: { in: [\u2026] } }), or test this against Postgres`);return Be(n,t,i,g,f)}))}var Ae=["neq","gt","gte","lt","lte"];function z(n,t){return F(n)||F(t)?null:P(n,t)}function Be(n,t,i,l,g){let f=i[l];return g===null?F(f):G(g)?z(f,i[g.$col]):J(g)?z(f,Z(U(g)?.minus)):typeof g=="object"&&!Array.isArray(g)&&!(g instanceof Date)?fe(Object.entries(g).map(([m,p])=>{if(J(p)){if(!Ae.includes(m))throw new Error(`${n}(${t}): where.${l}.${m} cannot take now()`);return X(m,f,Z(U(p)?.minus))}if(te(p))throw new Error(`${n}(${t}): where.${l}.${m} was given increment()/decrement() \u2014 a write, not a value to compare with`);if(G(p)){if(!Ae.includes(m))throw new Error(`${n}(${t}): where.${l}.${m} cannot take col()`);return X(m,f,i[p.$col])}switch(m){case"in":{if(!Array.isArray(p))throw new Error(`${n}(${t}): where.${l}.in is a list`);return Ee(p.map(O=>z(f,O)))}case"neq":return p===null?!F(f):X(m,f,p);case"gt":case"gte":case"lt":case"lte":return X(m,f,p);case"isNull":if(typeof p!="boolean")throw new Error(`${n}(${t}): where.${l}.isNull is true or false`);return p?F(f):!F(f);case"overlaps":if(!Array.isArray(p))throw new Error(`${n}(${t}): where.${l}.overlaps is a list`);if(f!=null&&!Array.isArray(f))throw new Error(`${n}(${t}): where.${l}: "overlaps" is an array column's operator`);return F(f)?null:p.some(O=>f.some(k=>P(O,k)));case"contains":case"icontains":case"startsWith":case"endsWith":{if(m==="contains"&&Array.isArray(p))return F(f)?null:Array.isArray(f)&&p.every(O=>f.some(k=>P(O,k)));if(typeof p!="string")throw new Error(`${n}(${t}): where.${l}.${m} is text`);return F(f)?null:typeof f!="string"?!1:m==="contains"?f.includes(p):m==="icontains"?f.toLowerCase().includes(p.toLowerCase()):m==="startsWith"?f.startsWith(p):f.endsWith(p)}default:throw new Error(`${n}(${t}): where.${l} has no operator "${m}"`)}})):z(f,g)}function X(n,t,i){if(F(t)||F(i))return null;if(n==="neq")return!P(t,i);let l=ce(t,i);return l===null?!1:n==="gt"?l>0:n==="gte"?l>=0:n==="lt"?l<0:l<=0}function We(n={}){let t=new Map,i=new Map,l=new Map,g=new Map,f=new Map,m=[],p=n.access===void 0?void 0:xe(n.access,{rows:e=>t.get(e)??[],deleted:e=>f.get(e)??[]});p?.signedInAs(n.user);let O=e=>{let r=t.get(e);return r||t.set(e,r=[]),r},k=(e,r,s)=>{let o=e.get(r);o?o.push(s):e.set(r,[s])},S=e=>e.id===void 0?{id:De(),...e}:{...e},N=()=>{let e={store:new Map([...t].map(([s,o])=>[s,o.map(j)])),inserted:oe(i),updated:oe(l),deleted:new Map([...g].map(([s,o])=>[s,[...o]])),removed:oe(f)},r=p?.snapshot();return()=>{t=e.store,i=e.inserted,l=e.updated,g=e.deleted,f=e.removed,r?.()}};function M(e,r,s){let o={};for(let[a,u]of Object.entries(s)){let c=U(u);if(c!==null&&c.fn==="now")o[a]=Z(c.minus);else{if(c!==null)throw new Error(`${e}(${r}): "${a}" was given ${c.fn==="inc"?"increment()":"decrement()"} \u2014 the row does not exist yet, so there is no current value to change`);o[a]=u}}return B(e,r,Object.keys(o),o),re(e,r,Object.keys(o),o),o}function C(e,r,s,o){B(e,r,Object.keys(o),o);let a={};for(let[u,c]of Object.entries(o)){let h=U(c);h!==null&&h.fn==="now"?a[u]=Z(h.minus):h!==null?a[u]=se(s[u],h.by,h.fn==="inc"?1:-1):a[u]=c}return re(e,r,Object.keys(a),a),a}function E(e,r,s){let o=S(M(e,r,s));return O(r).push(o),k(i,r,j(o)),j(o)}function T(e,r,s){return $e(e,r,s),ue(e,r,s),s!==void 0&&le(e,s),(t.get(r)??[]).filter(o=>s===void 0||H(e,r,o,s)===!0)}let D={diagnostics:()=>null,async query(e,r=[]){return m.push({sql:e,params:r}),[]},async findUnique(){throw new Error("the fake database knows no table's declared unique keys \u2014 find the row with findMany, or test this against Postgres")},async page(){throw new Error("the fake database cannot reproduce Postgres' cursor ordering, collation or row-level security \u2014 test pagination against Postgres")},async search(e){throw new Error(`search(${e}): the fake database has neither embeddings nor full text \u2014 test search against Postgres`)},async findById(e,r){let s=(t.get(e)??[]).find(o=>o.id===r);return s?j(s):null},async findMany(e,r,s){let{limit:o,offset:a}=s??{};if(o!==void 0&&(!Number.isInteger(o)||o<0))throw new Error(`findMany(${e}): limit is a whole number, 0 or more (got ${String(o)})`);if(a!==void 0){if(!Number.isInteger(a)||a<0)throw new Error(`findMany(${e}): offset is a whole number, 0 or more (got ${String(a)})`);if(o===void 0)throw new Error(`findMany(${e}): offset comes with limit \u2014 an offset into an unbounded result is not a page`)}if(s?.with!==void 0&&Object.keys(s.with).length>0)throw new Error(`findMany(${e}): the fake database has no relations, so \`with\` cannot be read \u2014 seed and query the related table on its own, or test this against Postgres`);let u=T("findMany",e,r),c=s?.orderBy===void 0?[]:Array.isArray(s.orderBy)?s.orderBy:[s.orderBy];c.length>0&&(u=[...u].sort((R,$)=>{for(let A of c){let x=A.direction==="desc"?-1:1,I=R[A.column],_=$[A.column],ee=I==null,de=_==null;if(ee||de){if(ee&&de)continue;let Ne=A.nulls===void 0?x===-1:A.nulls==="first";return(ee?1:-1)*(Ne?-1:1)}let ge=ce(I,_)??(String(I)<String(_)?-1:String(I)>String(_)?1:0);if(ge!==0)return ge*x}return 0}));let h=o===void 0?u:u.slice(a??0,(a??0)+o),b=s?.select;return h.map(R=>b===void 0||b.length===0?j(R):Object.fromEntries(b.map($=>[$,structuredClone(R[$])])))},async count(e,r={}){return T("count",e,r).length},async aggregate(e,r){let s=T("aggregate",e,r.where),o=r.groupBy??[],a=c=>{let h={},b=R=>c.map($=>$[R]).filter($=>$!=null);for(let R of r.sum??[]){let $=b(R);(h.sum??={})[R]=$.length===0?null:String($.reduce((A,x)=>se(A,x,1),"0"))}for(let R of r.avg??[]){let $=b(R),A=$.some(x=>typeof x=="number"&&!Number.isInteger(x));(h.avg??={})[R]=$.length===0?null:A?$.reduce((x,I)=>x+I,0)/$.length:_e(V($.reduce((x,I)=>se(x,I,1),"0")),{unit:BigInt($.length),scale:0})}for(let[R,$]of[["min",-1],["max",1]])for(let A of r[R]??[]){let x=b(A);(h[R]??={})[A]=x.length===0?null:x.reduce((I,_)=>(ce(_,I)??0)*$>0?_:I)}return r.count===!0?h.count=c.length:r.count!==void 0&&r.count!==!1&&(h.count=Object.fromEntries(Object.entries(r.count).map(([R,$])=>[R,c.filter(A=>H("aggregate",e,A,$)===!0).length]))),h};if(o.length===0)return a(s);let u=new Map;for(let c of s){let h=JSON.stringify(o.map(b=>c[b]));u.set(h,[...u.get(h)??[],c])}return[...u.values()].map(c=>({...a(c),...Object.fromEntries(o.map(h=>[h,c[0][h]]))}))},async insert(e,r){return E("insert",e,r)},insertMany:(async(e,r,s)=>{if(Oe(s),s?.onConflict?.length||s?.action!==void 0)throw new Error(`insertMany(${e}): the fake database knows no unique constraint to collide with \u2014 test onConflict against Postgres`);if(r.length===0)return s?.returning===!1?0:[];let o=Object.keys(r[0]);r.forEach((u,c)=>{let h=o.filter(R=>!(R in u)),b=Object.keys(u).filter(R=>!o.includes(R));if(h.length>0||b.length>0)throw new Error(`insertMany(${e}): row ${c} has not the first row's columns${h.length?` (missing ${h.join(", ")})`:""}${b.length?` (extra ${b.join(", ")})`:""} \u2014 write null for an empty one, or insert rows of another shape in a call of their own`)});let a=r.map(u=>E("insertMany",e,u));return s?.returning===!1?a.length:a}),async put(e,r,s){if(!s?.onConflict?.length)throw new Error(`put(${e}): onConflict names at least one column`);let o=M("put",e,r),a=O(e).find(u=>s.onConflict.every(c=>P(u[c],o[c])));if(!a)return E("put",e,r);for(let[u,c]of Object.entries(o))s.onConflict.includes(u)||(a[u]=c);return k(l,e,j(a)),j(a)},async update(e,r,s){let o=t.get(e)??[],a=o.findIndex(u=>u.id===r);return a<0?(B("update",e,Object.keys(s),s),null):(o[a]={...o[a],...C("update",e,o[a],s)},k(l,e,j(o[a])),j(o[a]))},async updateMany(e,r,s,o){L("updateMany",r);let a=T("updateMany",e,r),u=O(e),c=[];for(let h of a){let b=u.indexOf(h);u[b]={...h,...C("updateMany",e,h,s)},k(l,e,j(u[b])),c.push(j(u[b]))}return a.length===0&&B("updateMany",e,Object.keys(s),s),o?.returning===!1?c.length:c},async delete(e,r){let s=t.get(e)??[],o=s.findIndex(u=>u.id===r);if(o<0)return;let[a]=s.splice(o,1);k(g,e,r),k(f,e,a)},async deleteMany(e,r){L("deleteMany",r);let s=T("deleteMany",e,r);t.set(e,(t.get(e)??[]).filter(o=>!s.includes(o)));for(let o of s)k(g,e,String(o.id)),k(f,e,o);return s.length},async claim(e,r,s={}){let o=Object.keys(r);if(o.length===0)throw new Error(`claim(${e}): no unique field \u2014 claim takes a key; without one, insert(${e}, \u2026)`);B("claim",e,o,r);let a=(t.get(e)??[]).find(u=>o.every(c=>P(u[c],r[c])));return a?{inserted:!1,row:j(a)}:{inserted:!0,row:E("claim",e,{...r,...s})}},async lockRows(e,r){if(r.length===0)return;let s=t.get(e)??[],o=[...new Set(r)].filter(a=>!s.some(u=>u.id===a));if(o.length>0&&s.length>0)throw new Error(`lockRows(${e}): no row with id ${o.join(", ")}`)},async lockRowsWhere(e,r,s){let o=s?.mode??"update";if(!["update","share","noKeyUpdate"].includes(o))throw new Error(`lockRowsWhere(${e}): mode is "update", "share" or "noKeyUpdate" (got "${String(o)}")`);L("lockRowsWhere",r),T("lockRowsWhere",e,r)},async advisoryXactLock(){}};function q(e){let r=N(),s=[];try{for(let o of e.ops){let a=y(o,s);s.push(a);let u=Ve(o.guard,a.rows.length);if(u)throw u}}catch(o){throw r(),o}return{results:s}}function y(e,r){let s=a=>Object.fromEntries(Object.entries(a??{}).map(([u,c])=>[u,Me(c,r)])),o=`transaction plan ${e.op}`;switch(e.op){case"insert":return ie(E(o,e.table,s(e.values)));case"insertMany":{let a=(e.rows??[]).map(h=>s(h)),u=e.onConflict??[];if(e.action!==void 0&&u.length===0)throw new Error(`${o}(${e.table}): the fake database knows no unique key to collide with \u2014 name onConflict columns, or test this against Postgres`);let c=[];for(let h of a){let b=u.length>0?O(e.table).find(R=>u.every($=>P(R[$],h[$]))):void 0;if(!(b&&e.action==="ignore")){if(b&&e.action==="update"){Object.assign(b,C(o,e.table,b,Object.fromEntries(Object.entries(h).filter(([R])=>!u.includes(R))))),k(l,e.table,j(b)),c.push(j(b));continue}c.push(E(o,e.table,h))}}return{rows:c,rows_affected:c.length}}case"upsert":{let a=s(e.values),u=e.onConflict??[];if(Object.keys(a).length===0||u.length===0)throw Object.assign(new Error(`put on ${e.table} needs columns and onConflict`),{error_code:"tx_bad_upsert"});let c=O(e.table).find(h=>u.every(b=>P(h[b],a[b])));return c?(Object.assign(c,C(o,e.table,c,Object.fromEntries(Object.entries(a).filter(([h])=>!u.includes(h))))),k(l,e.table,j(c)),ie(j(c))):ie(E(o,e.table,a))}case"update":{let a=s(e.set);if(Object.keys(a).length===0)throw new Error(`update ${e.table}: nothing to set`);let u=ae(e.where,r);L(o,u);let c=O(e.table),h=[];for(let b of T(o,e.table,u)){let R=c.indexOf(b);c[R]={...b,...C(o,e.table,b,a)},k(l,e.table,j(c[R])),h.push(j(c[R]))}return{rows:h,rows_affected:h.length}}case"delete":{let a=ae(e.where,r);L(o,a);let u=T(o,e.table,a);t.set(e.table,O(e.table).filter(c=>!u.includes(c)));for(let c of u)k(g,e.table,String(c.id)),k(f,e.table,c);return{rows:u.map(j),rows_affected:u.length}}case"select":{let a=T(o,e.table,ae(e.where,r));return e.limit!==void 0&&(a=a.slice(0,e.limit)),{rows:a.map(j),rows_affected:a.length}}default:throw new Error(`unknown operation "${String(e.op)}" in a transaction plan`)}}let d={...D,async txPlan(e){return q(e)},async attempt(e){let r=N();try{return await e(D)}catch(s){throw r(),s}},async atomic(){throw new Error("the fake database cannot reproduce a transaction's isolation, COMMIT or retry \u2014 test $atomic against Postgres")}};return{...d,asService:()=>d,inserted:e=>(i.get(e)??[]).map(j),updated:e=>(l.get(e)??[]).map(j),deleted:e=>[...g.get(e)??[]],seed(e,r){t.set(e,r.map(j))},queries:m,...p===void 0?{}:{access:p}}}function oe(n){return new Map([...n].map(([t,i])=>[t,i.map(j)]))}function ie(n){return{rows:[n],rows_affected:1}}function Me(n,t){if(!ne(n))return n;let i=t[n.$ref.op]?.rows[0];if(!i)throw Object.assign(new Error(`transaction plan: operation ${n.$ref.op} produced no row to reference`),{error_code:"tx_ref_unresolved"});return i[n.$ref.field]}function ae(n,t){let i=l=>{if(ne(l)){let g=Me(l,t);if(g==null)throw Object.assign(new Error(`transaction plan: a filter's reference to operation ${l.$ref.op}'s "${l.$ref.field}" is NULL`),{error_code:"tx_ref_null"});return g}return Array.isArray(l)?l.map(i):l!==null&&typeof l=="object"&&!G(l)&&!te(l)&&!J(l)&&!(l instanceof Date)?Object.fromEntries(Object.entries(l).map(([g,f])=>[g,i(f)])):l};return i(n??{})}function Ve(n,t){return n?(n.kind==="one"?t===1:n.kind==="none"?t===0:n.kind==="atLeast"?t>=n.n:t<=n.n)?null:Object.assign(new Error(`transaction expectation failed: ${n.kind} (${t} row(s))`),{error_code:"tx_guard_failed",slot:n.slot}):null}export{We as createFakeClient,Ie as typedDatabase};
1
+ /*! palgres 0.56.0 — Palbase SDK License (see LICENSE) */
2
+ import{F as pe,G as be,P as G,Q as Re,R as ne,V as te,W as J,X as re,Y as $e,_ as B,ga as U,la as Oe,ma as Ie,n as he,p as me}from"./chunks/JPYKRUNF.js";import{o as we,r as ye,y as K,z as Q}from"./chunks/YTA5WUZJ.js";import{randomUUID as De}from"node:crypto";var Te=/^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/,ke="user";function Se(n){let t=n.filter(i=>i!=null);return t.length===0?"text":t.every(i=>typeof i=="boolean")?"bool":t.every(i=>typeof i=="bigint"||typeof i=="number"&&Number.isInteger(i))?"int":t.every(i=>typeof i=="bigint"||typeof i=="number"&&Number.isFinite(i))?"numeric":t.every(i=>typeof i=="string"&&Te.test(i))?"uuid":"text"}function Ce(n,t){return t==null?null:n==="bool"||n==="int"||n==="numeric"||typeof t=="string"?t:String(t)}var je=n=>n.schema==="public"?n.name:`${n.schema}.${n.name}`;function xe(n,t){let i=ye(we(n)),l=be(n,"memory"),g,f=[],m=[],p=new Map,O=[...i.types.values()].filter(y=>y.table),k=y=>{let d=i.types.get(y),w=new Set;if(!d?.table)return[];w.add(d.table.key??"id");let e=r=>{let s=r;s.parts?s.parts.forEach(e):s.part?e(s.part):s.column&&w.add(s.column)};for(let r of d.relations.values())r.kind==="column"&&(w.add(r.column),r.where&&e(r.where));return[...w]},S=()=>{let y=new Map;for(let d of O){let w=d.table,e=t.rows(je(w)),r=w.key??"id",s={};for(let a of k(d.name))s[a]=Se(e.map(u=>u[a]));let o={key:r,columns:s};y.set(d.name,{shape:o,rows:e.map(a=>Object.fromEntries(Object.entries(s).map(([u,c])=>[u,Ce(c,a[u])])))})}return{tables:y,relationships:f}},N=(y,d,w)=>{let e=y.tables.get(d);if(!e)return w;let r=e.shape.columns[e.shape.key],s=K(r,w);return s===null?null:e.rows.some(a=>{let u=a[e.shape.key];return u!==null&&K(r,String(u))===s})?s:void 0},M=()=>{for(let d of O){let w=d.table,e=je(w),r=w.key??"id",s=t.deleted(e),o=Math.min(p.get(e)??0,s.length),a=c=>Te.test(c)?c.toLowerCase():c,u=new Set(s.slice(o).map(c=>c[r]).filter(c=>c!=null).map(c=>a(String(c))));p.set(e,s.length),u.size>0&&C(d.name,c=>u.has(a(c)),"access: row deleted")}let y=S();for(let d of O)C(d.name,w=>N(y,d.name,w)===void 0,"access: row deleted");return S()},C=(y,d,w)=>{let e=[];for(let r of f)r.objectType===y&&d(r.objectId)||r.subjectType===y&&d(r.subjectId)?E("revoke",r,w):e.push(r);f=e},E=(y,d,w)=>{m.unshift({at:new Date().toISOString(),action:y,object:{type:d.objectType,id:d.objectId},relation:d.relation,subject:{type:d.subjectType,id:d.subjectId},by:w})},T=(y,d)=>(y.object_type===void 0||y.object_type===d.objectType)&&(y.object_id===void 0||y.object_id===d.objectId)&&(y.relation===void 0||y.relation===d.relation)&&(y.subject_type===void 0||y.subject_type===d.subjectType)&&(y.subject_id===void 0||y.subject_id===d.subjectId),D=(y,d)=>{for(let w of["objectType","objectId","relation","subjectType","subjectId"])if(y[w]!==d[w])return y[w]<d[w]?-1:1;return 0};return{names:l,via:{caller:()=>g,check(y,d,w,e){let r=M(),s=N(r,w,e);return s==null?!1:Q(i,r).check(y,w,s,d)},objects:(y,d,w)=>Q(i,M()).objects(y,w,d),subjects(y,d,w){let e=M(),r=N(e,d,w);return r==null?[]:Q(i,e).subjects(d,r,y)},change(y,d,w,e,r){let s=M(),o=(u,c,h)=>{if(c===ke)return h;let b=N(s,c,h);if(b==null)throw new pe("no_object",`Database.$access: there is no ${c} ${JSON.stringify(h)} (${u}) \u2014 a relationship is given on an object that exists`);return b};if(y==="revoke"){let u=($,A)=>{let x=$===ke?void 0:s.tables.get($);return x?K(x.shape.columns[x.shape.key],A):A},c=u(d.type,d.id),h=u(e.type,e.id);if(c===null||h===null)return!1;let b={objectType:d.type,objectId:c,relation:w,subjectType:e.type,subjectId:h},R=f.findIndex($=>D($,b)===0);return R<0?!1:(f.splice(R,1),E("revoke",b,r??g??null),!0)}let a={objectType:d.type,objectId:o("the object",d.type,d.id),relation:w,subjectType:e.type,subjectId:o("the subject",e.type,e.id)};return f.some(u=>D(u,a)===0)?!1:(f.push({...a,since:new Date().toISOString()}),E("grant",a,r??g??null),!0)},relationships(y,d){return M(),f.filter(w=>T(y,w)).sort(D).slice(0,d).map(w=>({object:{type:w.objectType,id:w.objectId},relation:w.relation,subject:{type:w.subjectType,id:w.subjectId},since:w.since}))},history(y,d){return M(),m.filter(w=>T(y,{objectType:w.object.type,objectId:w.object.id,relation:w.relation,subjectType:w.subject.type,subjectId:w.subject.id})).slice(0,d).map(w=>({...w,object:{...w.object},subject:{...w.subject}}))}},signedInAs(y){g=y},snapshot(){let y={relationships:f.map(d=>({...d})),history:m.map(d=>({...d})),seen:new Map(p),user:g};return()=>{f=y.relationships,m=y.history,p=y.seen,g=y.user}}}}var Fe=/^\d{4}-\d{2}-\d{2}([T ]\d{2}:\d{2}(:\d{2}(\.\d+)?)?)?(Z|[+-]\d{2}(:?\d{2})?)?$/,Pe=/^([+-]?)(\d*)(?:\.(\d*))?$/;function v(n){if(n instanceof Date)return n.getTime();if(typeof n=="string"&&Fe.test(n)){let t=Date.parse(n);return Number.isNaN(t)?null:t}return null}function V(n){if(typeof n=="number")return Number.isFinite(n)?V(String(n)):null;if(typeof n!="string"||/e/i.test(n))return null;let t=Pe.exec(n.trim());if(t===null||t[2]===""&&(t[3]??"")==="")return null;let i=t[3]??"";return{unit:BigInt(`${t[1]==="-"?"-":""}${t[2]===""?"0":t[2]}${i}`),scale:i.length}}function Y(n,t){return n.unit*10n**BigInt(t-n.scale)}function ce(n,t){if(n==null||t===null||t===void 0)return null;let i=v(n),l=v(t);if(i!==null&&l!==null)return Math.sign(i-l);let g=V(n),f=V(t);if(g!==null&&f!==null){let m=Math.max(g.scale,f.scale),p=Y(g,m)-Y(f,m);return p===0n?0:p<0n?-1:1}return typeof n==typeof t&&(typeof n=="string"||typeof n=="boolean"||typeof n=="number")?n<t?-1:n>t?1:0:null}function P(n,t){return n==null||t===null||t===void 0?!1:n instanceof Date||t instanceof Date?v(n)!==null&&v(n)===v(t):Array.isArray(n)&&Array.isArray(t)?n.length===t.length&&n.every((i,l)=>P(i,t[l])):n===t}function Z(n){let t=((n?.days??0)*86400+(n?.hours??0)*3600+(n?.minutes??0)*60+(n?.seconds??0))*1e3;return new Date(Date.now()-t).toISOString()}function se(n,t,i){if(n==null)return null;if(typeof n=="number"&&typeof t=="number")return n+i*t;let l=V(n),g=V(t);if(l===null||g===null)throw new Error(`increment()/decrement() on a value that is not a number (${JSON.stringify(n)}): Postgres refuses it ("operator does not exist")`);let f=Math.max(l.scale,g.scale),m=Y(l,f)+BigInt(i)*Y(g,f);if(f===0)return typeof n=="number"?Number(m):m.toString();let p=m<0n,O=(p?-m:m).toString().padStart(f+1,"0"),k=`${p?"-":""}${O.slice(0,-f)}.${O.slice(-f)}`;return typeof n=="number"?Number(k):k}function _e(n,t){let i=T=>{let D=(T.unit<0n?-T.unit:T.unit).toString().padStart(T.scale+1,"0"),q=D.slice(0,D.length-T.scale),y=D.slice(D.length-T.scale),d=q.padStart(Math.ceil(q.length/4)*4,"0").match(/.{4}/g)??[],w=y.padEnd(Math.ceil(y.length/4)*4,"0").match(/.{4}/g)??[],r=[...d.map((s,o)=>[d.length-1-o,Number(s)]),...w.map((s,o)=>[-1-o,Number(s)])].find(([,s])=>s!==0);return r?[r[0],r[1]]:[0,0]},[l,g]=i(n),[f,m]=i(t),p=l-f-(g<=m?1:0),O=Math.min(Math.max(16-p*4,n.scale,t.scale,0),1e3),k=n.unit*10n**BigInt(O+t.scale),S=t.unit*10n**BigInt(n.scale),N=k/S,M=k%S;2n*(M<0n?-M:M)>=(S<0n?-S:S)&&(N+=k<0n!=S<0n?-1n:1n);let C=N<0n,E=(C?-N:N).toString().padStart(O+1,"0");return`${C?"-":""}${O===0?E:`${E.slice(0,-O)}.${E.slice(-O)}`}`}var j=n=>structuredClone(n);function ue(n,t,i){if(Re(i))throw new Error(`${n}(${t}): the fake database runs no SQL, so a sqlFragment cannot be evaluated \u2014 write the filter in the filter language (gt, gte, lt, lte, neq, in, contains, isNull, OR, AND, NOT), or test this against Postgres`);if(!(i===null||typeof i!="object"))for(let[l,g]of Object.entries(i))if(l==="OR"||l==="AND")for(let f of Array.isArray(g)?g:[])ue(n,t,f);else l==="NOT"&&ue(n,t,g)}function W(n,t,i){return he(new me({fields:[{field:t,message:i}]},`${n}: ${t} ${i}`))}function le(n,t,i="where"){for(let[l,g]of Object.entries(t))if(l==="OR"||l==="AND"){let f=g;if(l==="AND"&&f.length===0)throw W(n,`${i}.AND`,"is an empty list \u2014 no condition at all. Leave it out, or name a condition in it.");f.forEach((m,p)=>{if(Object.keys(m).length===0)throw W(n,`${i}.${l}[${p}]`,"holds no condition \u2014 a branch that matches every row. Name a condition in it, or leave it out.");le(n,m,`${i}.${l}[${p}]`)})}else if(l==="NOT"){if(Array.isArray(g))throw W(n,`${i}.NOT`,"is a list \u2014 NOT takes one filter object. For several conditions, NOT: { AND: [...] } or NOT: { OR: [...] }.");if(Object.keys(g).length===0)throw W(n,`${i}.NOT`,"holds no condition \u2014 NOT of nothing is not a filter. Name the condition to exclude.");le(n,g,`${i}.NOT`)}else if(l==="has"&&Object.keys(g??{}).length===0)throw W(n,`${i}.has`,"names no relation \u2014 no condition. Name one: has: { <relation>: { \u2026 } }.")}function L(n,t){if(Object.keys(t).length===0)throw W(n,"where",`holds no condition, so ${n} would reach EVERY row of the table. Name a condition.`)}function fe(n){let t=!1;for(let i of n){if(i===!1)return!1;i===null&&(t=!0)}return t?null:!0}function Ee(n){let t=!1;for(let i of n){if(i===!0)return!0;i===null&&(t=!0)}return t?null:!1}var F=n=>n==null;function H(n,t,i,l){return fe(Object.entries(l).map(([g,f])=>{if(g==="OR")return Ee(f.map(m=>H(n,t,i,m)));if(g==="AND")return fe(f.map(m=>H(n,t,i,m)));if(g==="NOT"){let m=H(n,t,i,f);return m===null?null:!m}if(g==="has")throw new Error(`${n}(${t}): the fake database has no relations, so a \`has\` filter cannot be decided for a row \u2014 read the related table first and filter by its ids ({ id: { in: [\u2026] } }), or test this against Postgres`);return Be(n,t,i,g,f)}))}var Ae=["neq","gt","gte","lt","lte"];function z(n,t){return F(n)||F(t)?null:P(n,t)}function Be(n,t,i,l,g){let f=i[l];return g===null?F(f):G(g)?z(f,i[g.$col]):J(g)?z(f,Z(U(g)?.minus)):typeof g=="object"&&!Array.isArray(g)&&!(g instanceof Date)?fe(Object.entries(g).map(([m,p])=>{if(J(p)){if(!Ae.includes(m))throw new Error(`${n}(${t}): where.${l}.${m} cannot take now()`);return X(m,f,Z(U(p)?.minus))}if(te(p))throw new Error(`${n}(${t}): where.${l}.${m} was given increment()/decrement() \u2014 a write, not a value to compare with`);if(G(p)){if(!Ae.includes(m))throw new Error(`${n}(${t}): where.${l}.${m} cannot take col()`);return X(m,f,i[p.$col])}switch(m){case"in":{if(!Array.isArray(p))throw new Error(`${n}(${t}): where.${l}.in is a list`);return Ee(p.map(O=>z(f,O)))}case"neq":return p===null?!F(f):X(m,f,p);case"gt":case"gte":case"lt":case"lte":return X(m,f,p);case"isNull":if(typeof p!="boolean")throw new Error(`${n}(${t}): where.${l}.isNull is true or false`);return p?F(f):!F(f);case"overlaps":if(!Array.isArray(p))throw new Error(`${n}(${t}): where.${l}.overlaps is a list`);if(f!=null&&!Array.isArray(f))throw new Error(`${n}(${t}): where.${l}: "overlaps" is an array column's operator`);return F(f)?null:p.some(O=>f.some(k=>P(O,k)));case"contains":case"icontains":case"startsWith":case"endsWith":{if(m==="contains"&&Array.isArray(p))return F(f)?null:Array.isArray(f)&&p.every(O=>f.some(k=>P(O,k)));if(typeof p!="string")throw new Error(`${n}(${t}): where.${l}.${m} is text`);return F(f)?null:typeof f!="string"?!1:m==="contains"?f.includes(p):m==="icontains"?f.toLowerCase().includes(p.toLowerCase()):m==="startsWith"?f.startsWith(p):f.endsWith(p)}default:throw new Error(`${n}(${t}): where.${l} has no operator "${m}"`)}})):z(f,g)}function X(n,t,i){if(F(t)||F(i))return null;if(n==="neq")return!P(t,i);let l=ce(t,i);return l===null?!1:n==="gt"?l>0:n==="gte"?l>=0:n==="lt"?l<0:l<=0}function We(n={}){let t=new Map,i=new Map,l=new Map,g=new Map,f=new Map,m=[],p=n.access===void 0?void 0:xe(n.access,{rows:e=>t.get(e)??[],deleted:e=>f.get(e)??[]});p?.signedInAs(n.user);let O=e=>{let r=t.get(e);return r||t.set(e,r=[]),r},k=(e,r,s)=>{let o=e.get(r);o?o.push(s):e.set(r,[s])},S=e=>e.id===void 0?{id:De(),...e}:{...e},N=()=>{let e={store:new Map([...t].map(([s,o])=>[s,o.map(j)])),inserted:oe(i),updated:oe(l),deleted:new Map([...g].map(([s,o])=>[s,[...o]])),removed:oe(f)},r=p?.snapshot();return()=>{t=e.store,i=e.inserted,l=e.updated,g=e.deleted,f=e.removed,r?.()}};function M(e,r,s){let o={};for(let[a,u]of Object.entries(s)){let c=U(u);if(c!==null&&c.fn==="now")o[a]=Z(c.minus);else{if(c!==null)throw new Error(`${e}(${r}): "${a}" was given ${c.fn==="inc"?"increment()":"decrement()"} \u2014 the row does not exist yet, so there is no current value to change`);o[a]=u}}return B(e,r,Object.keys(o),o),re(e,r,Object.keys(o),o),o}function C(e,r,s,o){B(e,r,Object.keys(o),o);let a={};for(let[u,c]of Object.entries(o)){let h=U(c);h!==null&&h.fn==="now"?a[u]=Z(h.minus):h!==null?a[u]=se(s[u],h.by,h.fn==="inc"?1:-1):a[u]=c}return re(e,r,Object.keys(a),a),a}function E(e,r,s){let o=S(M(e,r,s));return O(r).push(o),k(i,r,j(o)),j(o)}function T(e,r,s){return $e(e,r,s),ue(e,r,s),s!==void 0&&le(e,s),(t.get(r)??[]).filter(o=>s===void 0||H(e,r,o,s)===!0)}let D={diagnostics:()=>null,async query(e,r=[]){return m.push({sql:e,params:r}),[]},async findUnique(){throw new Error("the fake database knows no table's declared unique keys \u2014 find the row with findMany, or test this against Postgres")},async page(){throw new Error("the fake database cannot reproduce Postgres' cursor ordering, collation or row-level security \u2014 test pagination against Postgres")},async search(e){throw new Error(`search(${e}): the fake database has neither embeddings nor full text \u2014 test search against Postgres`)},async findById(e,r){let s=(t.get(e)??[]).find(o=>o.id===r);return s?j(s):null},async findMany(e,r,s){let{limit:o,offset:a}=s??{};if(o!==void 0&&(!Number.isInteger(o)||o<0))throw new Error(`findMany(${e}): limit is a whole number, 0 or more (got ${String(o)})`);if(a!==void 0){if(!Number.isInteger(a)||a<0)throw new Error(`findMany(${e}): offset is a whole number, 0 or more (got ${String(a)})`);if(o===void 0)throw new Error(`findMany(${e}): offset comes with limit \u2014 an offset into an unbounded result is not a page`)}if(s?.with!==void 0&&Object.keys(s.with).length>0)throw new Error(`findMany(${e}): the fake database has no relations, so \`with\` cannot be read \u2014 seed and query the related table on its own, or test this against Postgres`);let u=T("findMany",e,r),c=s?.orderBy===void 0?[]:Array.isArray(s.orderBy)?s.orderBy:[s.orderBy];c.length>0&&(u=[...u].sort((R,$)=>{for(let A of c){let x=A.direction==="desc"?-1:1,I=R[A.column],_=$[A.column],ee=I==null,de=_==null;if(ee||de){if(ee&&de)continue;let Ne=A.nulls===void 0?x===-1:A.nulls==="first";return(ee?1:-1)*(Ne?-1:1)}let ge=ce(I,_)??(String(I)<String(_)?-1:String(I)>String(_)?1:0);if(ge!==0)return ge*x}return 0}));let h=o===void 0?u:u.slice(a??0,(a??0)+o),b=s?.select;return h.map(R=>b===void 0||b.length===0?j(R):Object.fromEntries(b.map($=>[$,structuredClone(R[$])])))},async count(e,r={}){return T("count",e,r).length},async aggregate(e,r){let s=T("aggregate",e,r.where),o=r.groupBy??[],a=c=>{let h={},b=R=>c.map($=>$[R]).filter($=>$!=null);for(let R of r.sum??[]){let $=b(R);(h.sum??={})[R]=$.length===0?null:String($.reduce((A,x)=>se(A,x,1),"0"))}for(let R of r.avg??[]){let $=b(R),A=$.some(x=>typeof x=="number"&&!Number.isInteger(x));(h.avg??={})[R]=$.length===0?null:A?$.reduce((x,I)=>x+I,0)/$.length:_e(V($.reduce((x,I)=>se(x,I,1),"0")),{unit:BigInt($.length),scale:0})}for(let[R,$]of[["min",-1],["max",1]])for(let A of r[R]??[]){let x=b(A);(h[R]??={})[A]=x.length===0?null:x.reduce((I,_)=>(ce(_,I)??0)*$>0?_:I)}return r.count===!0?h.count=c.length:r.count!==void 0&&r.count!==!1&&(h.count=Object.fromEntries(Object.entries(r.count).map(([R,$])=>[R,c.filter(A=>H("aggregate",e,A,$)===!0).length]))),h};if(o.length===0)return a(s);let u=new Map;for(let c of s){let h=JSON.stringify(o.map(b=>c[b]));u.set(h,[...u.get(h)??[],c])}return[...u.values()].map(c=>({...a(c),...Object.fromEntries(o.map(h=>[h,c[0][h]]))}))},async insert(e,r){return E("insert",e,r)},insertMany:(async(e,r,s)=>{if(Oe(s),s?.onConflict?.length||s?.action!==void 0)throw new Error(`insertMany(${e}): the fake database knows no unique constraint to collide with \u2014 test onConflict against Postgres`);if(r.length===0)return s?.returning===!1?0:[];let o=Object.keys(r[0]);r.forEach((u,c)=>{let h=o.filter(R=>!(R in u)),b=Object.keys(u).filter(R=>!o.includes(R));if(h.length>0||b.length>0)throw new Error(`insertMany(${e}): row ${c} has not the first row's columns${h.length?` (missing ${h.join(", ")})`:""}${b.length?` (extra ${b.join(", ")})`:""} \u2014 write null for an empty one, or insert rows of another shape in a call of their own`)});let a=r.map(u=>E("insertMany",e,u));return s?.returning===!1?a.length:a}),async put(e,r,s){if(!s?.onConflict?.length)throw new Error(`put(${e}): onConflict names at least one column`);let o=M("put",e,r),a=O(e).find(u=>s.onConflict.every(c=>P(u[c],o[c])));if(!a)return E("put",e,r);for(let[u,c]of Object.entries(o))s.onConflict.includes(u)||(a[u]=c);return k(l,e,j(a)),j(a)},async update(e,r,s){let o=t.get(e)??[],a=o.findIndex(u=>u.id===r);return a<0?(B("update",e,Object.keys(s),s),null):(o[a]={...o[a],...C("update",e,o[a],s)},k(l,e,j(o[a])),j(o[a]))},async updateMany(e,r,s,o){L("updateMany",r);let a=T("updateMany",e,r),u=O(e),c=[];for(let h of a){let b=u.indexOf(h);u[b]={...h,...C("updateMany",e,h,s)},k(l,e,j(u[b])),c.push(j(u[b]))}return a.length===0&&B("updateMany",e,Object.keys(s),s),o?.returning===!1?c.length:c},async delete(e,r){let s=t.get(e)??[],o=s.findIndex(u=>u.id===r);if(o<0)return;let[a]=s.splice(o,1);k(g,e,r),k(f,e,a)},async deleteMany(e,r){L("deleteMany",r);let s=T("deleteMany",e,r);t.set(e,(t.get(e)??[]).filter(o=>!s.includes(o)));for(let o of s)k(g,e,String(o.id)),k(f,e,o);return s.length},async claim(e,r,s={}){let o=Object.keys(r);if(o.length===0)throw new Error(`claim(${e}): no unique field \u2014 claim takes a key; without one, insert(${e}, \u2026)`);B("claim",e,o,r);let a=(t.get(e)??[]).find(u=>o.every(c=>P(u[c],r[c])));return a?{inserted:!1,row:j(a)}:{inserted:!0,row:E("claim",e,{...r,...s})}},async lockRows(e,r){if(r.length===0)return;let s=t.get(e)??[],o=[...new Set(r)].filter(a=>!s.some(u=>u.id===a));if(o.length>0&&s.length>0)throw new Error(`lockRows(${e}): no row with id ${o.join(", ")}`)},async lockRowsWhere(e,r,s){let o=s?.mode??"update";if(!["update","share","noKeyUpdate"].includes(o))throw new Error(`lockRowsWhere(${e}): mode is "update", "share" or "noKeyUpdate" (got "${String(o)}")`);L("lockRowsWhere",r),T("lockRowsWhere",e,r)},async advisoryXactLock(){}};function q(e){let r=N(),s=[];try{for(let o of e.ops){let a=y(o,s);s.push(a);let u=Ve(o.guard,a.rows.length);if(u)throw u}}catch(o){throw r(),o}return{results:s}}function y(e,r){let s=a=>Object.fromEntries(Object.entries(a??{}).map(([u,c])=>[u,Me(c,r)])),o=`transaction plan ${e.op}`;switch(e.op){case"insert":return ie(E(o,e.table,s(e.values)));case"insertMany":{let a=(e.rows??[]).map(h=>s(h)),u=e.onConflict??[];if(e.action!==void 0&&u.length===0)throw new Error(`${o}(${e.table}): the fake database knows no unique key to collide with \u2014 name onConflict columns, or test this against Postgres`);let c=[];for(let h of a){let b=u.length>0?O(e.table).find(R=>u.every($=>P(R[$],h[$]))):void 0;if(!(b&&e.action==="ignore")){if(b&&e.action==="update"){Object.assign(b,C(o,e.table,b,Object.fromEntries(Object.entries(h).filter(([R])=>!u.includes(R))))),k(l,e.table,j(b)),c.push(j(b));continue}c.push(E(o,e.table,h))}}return{rows:c,rows_affected:c.length}}case"upsert":{let a=s(e.values),u=e.onConflict??[];if(Object.keys(a).length===0||u.length===0)throw Object.assign(new Error(`put on ${e.table} needs columns and onConflict`),{error_code:"tx_bad_upsert"});let c=O(e.table).find(h=>u.every(b=>P(h[b],a[b])));return c?(Object.assign(c,C(o,e.table,c,Object.fromEntries(Object.entries(a).filter(([h])=>!u.includes(h))))),k(l,e.table,j(c)),ie(j(c))):ie(E(o,e.table,a))}case"update":{let a=s(e.set);if(Object.keys(a).length===0)throw new Error(`update ${e.table}: nothing to set`);let u=ae(e.where,r);L(o,u);let c=O(e.table),h=[];for(let b of T(o,e.table,u)){let R=c.indexOf(b);c[R]={...b,...C(o,e.table,b,a)},k(l,e.table,j(c[R])),h.push(j(c[R]))}return{rows:h,rows_affected:h.length}}case"delete":{let a=ae(e.where,r);L(o,a);let u=T(o,e.table,a);t.set(e.table,O(e.table).filter(c=>!u.includes(c)));for(let c of u)k(g,e.table,String(c.id)),k(f,e.table,c);return{rows:u.map(j),rows_affected:u.length}}case"select":{let a=T(o,e.table,ae(e.where,r));return e.limit!==void 0&&(a=a.slice(0,e.limit)),{rows:a.map(j),rows_affected:a.length}}default:throw new Error(`unknown operation "${String(e.op)}" in a transaction plan`)}}let d={...D,async txPlan(e){return q(e)},async attempt(e){let r=N();try{return await e(D)}catch(s){throw r(),s}},async atomic(){throw new Error("the fake database cannot reproduce a transaction's isolation, COMMIT or retry \u2014 test $atomic against Postgres")}};return{...d,asService:()=>d,inserted:e=>(i.get(e)??[]).map(j),updated:e=>(l.get(e)??[]).map(j),deleted:e=>[...g.get(e)??[]],seed(e,r){t.set(e,r.map(j))},queries:m,...p===void 0?{}:{access:p}}}function oe(n){return new Map([...n].map(([t,i])=>[t,i.map(j)]))}function ie(n){return{rows:[n],rows_affected:1}}function Me(n,t){if(!ne(n))return n;let i=t[n.$ref.op]?.rows[0];if(!i)throw Object.assign(new Error(`transaction plan: operation ${n.$ref.op} produced no row to reference`),{error_code:"tx_ref_unresolved"});return i[n.$ref.field]}function ae(n,t){let i=l=>{if(ne(l)){let g=Me(l,t);if(g==null)throw Object.assign(new Error(`transaction plan: a filter's reference to operation ${l.$ref.op}'s "${l.$ref.field}" is NULL`),{error_code:"tx_ref_null"});return g}return Array.isArray(l)?l.map(i):l!==null&&typeof l=="object"&&!G(l)&&!te(l)&&!J(l)&&!(l instanceof Date)?Object.fromEntries(Object.entries(l).map(([g,f])=>[g,i(f)])):l};return i(n??{})}function Ve(n,t){return n?(n.kind==="one"?t===1:n.kind==="none"?t===0:n.kind==="atLeast"?t>=n.n:t<=n.n)?null:Object.assign(new Error(`transaction expectation failed: ${n.kind} (${t} row(s))`),{error_code:"tx_guard_failed",slot:n.slot}):null}export{We as createFakeClient,Ie as typedDatabase};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "palgres",
3
- "version": "0.55.0",
3
+ "version": "0.56.0",
4
4
  "description": "Palgres: the typed Postgres layer of Palbase's DB machines — schema, migrations and queries.",
5
5
  "license": "SEE LICENSE IN LICENSE",
6
6
  "homepage": "https://palbase.studio",