palgres 0.54.0 → 0.55.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chunks/5EMZSH7B.js +5 -0
- package/dist/chunks/DLP3GKUJ.js +309 -0
- package/dist/chunks/EBHTHWOS.js +2 -0
- package/dist/dsl.js +2 -2
- package/dist/index.js +2 -2
- package/dist/testing.js +2 -2
- package/package.json +1 -1
- package/types/access/src/apply.d.ts +2 -0
- package/types/palgres/src/query/access.d.ts +30 -1
- package/types/palgres/src/query/surface.d.ts +2 -1
- package/types/palgres/src/testing/access.d.ts +17 -0
- package/types/palgres/src/testing/fake.d.ts +13 -1
- package/types/palgres/src/testing/index.d.ts +2 -1
- package/dist/chunks/DMGBXJWT.js +0 -309
- package/dist/chunks/MMDAYJKI.js +0 -2
- package/dist/chunks/Q7U5AW6L.js +0 -5
package/dist/chunks/Q7U5AW6L.js
DELETED
|
@@ -1,5 +0,0 @@
|
|
|
1
|
-
/*! palgres 0.54.0 — Palbase SDK License (see LICENSE) */
|
|
2
|
-
import{F as ne,o as he,p as ee,q as me,r as be,t as j}from"./DMGBXJWT.js";var Je=Symbol.for("palbase.backend.httpError"),Oe=Symbol.for("palbase.backend.engineRaised"),$=Object.freeze({uniqueViolation:"23505",foreignKeyViolation:"23503",serializationFailure:"40001",deadlockDetected:"40P01",queryCancelled:"57014",lockNotAvailable:"55P03",inFailedTransaction:"25P02",insufficientPrivilege:"42501"}),T=class extends Error{[Je]=!0;status;error;errorDescription;data;retryAfter;constructor(n,t,r,o,s){super(r),this.name="HttpError",this.status=n,this.error=t,this.errorDescription=r,o!==void 0&&(this.data=o),s!==void 0&&(this.retryAfter=s)}};function Ee(e){return e[Oe]=!0,e}function $n(e){return typeof e=="object"&&e!==null&&e[Oe]===!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 _=class extends T{constructor(n,t){super(400,"bad_request",t??P("BadRequest"),n),this.name="BadRequest"}},xe=class extends T{constructor(n,t,r){super(404,t??"not_found",n??P("NotFound"),r),this.name="NotFound"}},S=class extends T{constructor(n,t,r){super(409,t??"conflict",n??P("Conflict"),r),this.name="Conflict"}},ke=class extends S{constraint;sqlstate=$.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 Tn(e){if(typeof e!="object"||e===null||e.retryable!==!0)return!1;let n=e.sqlstate;return n===$.serializationFailure||n===$.deadlockDetected}var Re=class extends S{retryable=!0;sqlstate;static is(n){return typeof n=="object"&&n!==null&&n.name==="SerializationFailure"}constructor(n=$.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}},$e=class extends S{retryable=!0;sqlstate;static is(n){return typeof n=="object"&&n!==null&&n.name==="DeadlockDetected"}constructor(n=$.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}},Te=class extends Error{sqlstate=$.inFailedTransaction;static is(n){return typeof n=="object"&&n!==null&&n.name==="TransactionAborted"}constructor(n,t){super(n,{cause:t}),this.name="TransactionAborted"}},Ae=class extends T{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 Xe=new Set(["57P03","53300","08001","08004","ERR_POSTGRES_CONNECTION_REFUSED","ERR_POSTGRES_CONNECTION_FAILED","ERR_POSTGRES_CONNECTION_TIMEOUT","ECONNREFUSED","CONNECT_TIMEOUT"]),Ze=new Set(["57P01","57P02","08000","08003","08006","08007","08P01","ERR_POSTGRES_CONNECTION_CLOSED","CONNECTION_CLOSED","CONNECTION_DESTROYED","ECONNRESET","ETIMEDOUT","EPIPE"]);function An(e){return e instanceof Error&&e.code===void 0&&e.message==="connection must be a PostgresSQLConnection"}function On(e){let n=e;for(let t=0;t<4&&typeof n=="object"&&n!==null;t++){let r=D(n),o=n.code,s=i=>r!==void 0&&i.has(r)||typeof o=="string"&&i.has(o);if(s(Ze))return"lost";if(s(Xe))return"never";n=n.cause}}function En(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 jn(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,'""')}"`,Nn=(e,n)=>`${m(e)}.${m(n)}`,_n=e=>`'${e.replace(/'/g,"''")}'`;function Pn(e){if(e.includes("\0"))throw new TypeError("a NUL character cannot be sent to Postgres");return`E'${e.replace(/\\/g,"\\\\").replace(/'/g,"''")}'`}var Dn=e=>e.map(m).join(", "),Qe=new Set(["now","current_timestamp","current_date","current_time","localtimestamp","localtime","transaction_timestamp","statement_timestamp"]);function vn(e){return[...te(e)].some(n=>n.call&&!Qe.has(n.name.toLowerCase()))}function*te(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 s=r+1;yield{start:n,end:s,name:o,quoted:!0,call:/^\s*\(/.test(e.slice(s))},n=s;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 Cn(e,n){for(let t of te(e))if(!t.call&&(t.quoted?t.name===n:t.name.toLowerCase()===n.toLowerCase()))return!0;return!1}function Mn(e,n){if(n.size===0)return e;let t="",r=0;for(let o of te(e)){if(o.call)continue;let s=n.get(o.quoted?o.name:en(n,o.name)??"");s!==void 0&&(t+=e.slice(r,o.start)+m(s),r=o.end)}return t+e.slice(r)}function en(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 Wn=e=>`(NOT EXISTS (SELECT 1 FROM unnest(i.indclass::oid[]) AS oc(oid) JOIN pg_catalog.pg_opclass o ON o.oid = oc.oid WHERE NOT o.opcdefault)
|
|
3
|
-
AND NOT i.indnullsnotdistinct AND ${e}.reloptions IS NULL
|
|
4
|
-
AND NOT EXISTS (SELECT 1 FROM unnest(i.indcollation::oid[], i.indkey::int2[]) AS x(coll, att) JOIN pg_catalog.pg_attribute a ON a.attrelid = i.indrelid AND a.attnum = x.att WHERE x.att > 0 AND x.coll <> a.attcollation))`;var g=class extends Error{code;constructor(n,t,r){super(t,r),this.name="AccessRefused",this.code=n}};function nn(e,n){let t=be(he(e)),r=new Map;for(let o of t.types.values()){let s=new Set,i=new Map;for(let a of o.relations.values())me(a)&&s.add(a.name),a.kind==="stored"&&i.set(a.name,new Set(a.subjects));for(let a of o.permissions.keys())s.add(a);r.set(o.name,{names:s,kept:i})}return{schema:`access_${n}`,types:r}}function Bn(e,n){let t=nn(e,""),r=o=>{let s=[...o].sort();return s.length===0?"never":s.map(i=>JSON.stringify(i)).join(" | ")};return[...t.types].map(([o,s])=>{let i=[...s.kept].sort(([a],[l])=>a<l?-1:a>l?1:0).map(([a,l])=>`${JSON.stringify(a)}: ${r(l)}`);return`${n}${o}: { names: ${r(s.names)}; relations: {${i.length===0?"":` ${i.join("; ")} `}} };`}).join(`
|
|
5
|
-
`)}var tn="names a subject or changes who holds what: it is the service role's \u2014 Database.$asService().$access",rn={PA001:"unknown_name",PA002:"no_object",PA003:"bad_id",PA004:"too_many",PA005:"not_kept",PA006:"not_the_service"};function v(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 g("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 g("bad_id",`Database.$access: ${e} is empty or longer than ${j} characters`);return t}function je(e,n,t,r){let o=t==="anon",s=()=>{if(!n)throw new g("no_schema",`Database.$access: ${r??"the app declares no access schema \u2014 PalbaseFactory.create(\u2026, { db: { schemas, access } })"}`);return n},i=(d,u)=>{let c=typeof u=="string"?d.types.get(u):void 0;if(!c)throw new g("unknown_type",`Database.$access: the access schema has no type ${JSON.stringify(u)} \u2014 it has ${[...d.types.keys()].join(", ")||"none"}`);return c},a=(d,u,c)=>{let p=i(d,u);if(typeof c!="string"||!p.names.has(c))throw new g("unknown_name",`Database.$access: type ${String(u)} has no relation or permission ${JSON.stringify(c)} a user can hold \u2014 it has ${[...p.names].sort().join(", ")||"none"}`)},l=(d,u)=>{let c=u;if(c===null||typeof c!="object")throw new g("bad_id","Database.$access: an object is { type, id }");return i(d,c.type),{type:c.type,id:v(`the id of a ${String(c.type)}`,c.id)}},h=d=>{if(typeof d!="string")throw new g("bad_id","Database.$access: a subject is a user's id, a string");return v("a subject's id",d)},we=(d,u)=>{if(typeof u=="string")return{type:ee,id:v("a subject's id",u)};let c=u;return c!==null&&typeof c=="object"&&"user"in c?{type:ee,id:h(c.user)}:l(d,u)},Ye=(d,u,c,p)=>{let f=typeof c=="string"?i(d,u.type).kept.get(c):void 0;if(!f){let y=[...i(d,u.type).kept.keys()].sort().join(", ");throw new g("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(!f.has(p.type))throw new g("not_kept",`Database.$access: ${u.type}.${String(c)} takes ${[...f].sort().join(" or ")}, not ${p.type}`)},x=async(d,u)=>{try{return await e().query(d,u)}catch(c){let p=D(c),f=p===void 0?void 0:rn[p],y=c instanceof Error?c.message:String(c);throw f!==void 0?new g(f,`Database.$access: ${y}`,{cause:c}):p==="42501"?new g("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}},R=d=>{if(t!=="service")throw new g("not_the_service",`Database.$access.${d} ${tn}`)},pe=(d,u)=>{let c=[],p=[],f=(b,O)=>{p.push(O),c.push(`${b} = $${p.length}`)};if(u?.object!==void 0&&(i(d,u.object.type),f("object_type",u.object.type),u.object.id!==void 0&&f("object_id",v(`the id of a ${u.object.type}`,u.object.id))),u?.relation!==void 0){if(typeof u.relation!="string")throw new g("not_kept","Database.$access: a relation is its name");f("relation",u.relation)}if(u?.subject!==void 0){let b=we(d,u.subject);f("subject_type",b.type),f("subject_id",b.id)}let y=u?.limit??100;if(!Number.isSafeInteger(y)||y<1||y>1e3)throw new g("bad_id","Database.$access: limit is a whole number from 1 to 1000");return{sql:c.length===0?"":`WHERE ${c.join(" AND ")}`,params:p,limit:y}},ye=d=>`to_char(${d} AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.US"Z"')`,ge=d=>async(u,c,p,f)=>{let y=s();R(d);let b=l(y,u),O=we(y,p);Ye(y,b,c,O);let E=f?.by;if(E!==void 0&&(typeof E!="string"||E===""||E.length>j))throw new g("bad_id",`Database.$access: by is who did it \u2014 a string of at most ${j} characters`);return(await x(`SELECT ${m(y.schema)}.${m(d)}($1, $2, $3, $4, $5, $6) AS v`,[b.type,b.id,c,O.type,O.id,E??null]))[0]?.v===!0};return{async can(d,u){let c=s(),p=l(c,u);return a(c,p.type,d),o?!1:(await x(`SELECT ${m(c.schema)}.can($1, $2, $3) AS v`,[d,p.type,p.id]))[0]?.v===!0},async objects(d,u){let c=s();return a(c,u,d),o?[]:(await x(`SELECT o AS id FROM ${m(c.schema)}.my_objects($1, $2) AS o ORDER BY 1`,[d,u])).map(f=>f.id)},async held(d){let u=s(),c=l(u,d),p=[...i(u,c.type).names].sort();return o||p.length===0?[]:(await x(`SELECT name FROM unnest($1::text[]) AS name WHERE ${m(u.schema)}.can(name, $2, $3) ORDER BY 1`,[p,c.type,c.id])).map(y=>y.name)},async check(d,u,c){let p=s();R("check");let f=h(d),y=l(p,c);return a(p,y.type,u),(await x(`SELECT ${m(p.schema)}.check($1, $2, $3, $4) AS v`,[f,u,y.type,y.id]))[0]?.v===!0},async objectsOf(d,u,c){let p=s();R("objectsOf");let f=h(d);return a(p,c,u),(await x(`SELECT o AS id FROM ${m(p.schema)}.objects($1, $2, $3) AS o ORDER BY 1`,[f,u,c])).map(b=>b.id)},async subjects(d,u){let c=s();R("subjects");let p=l(c,u);return a(c,p.type,d),(await x(`SELECT s AS id FROM ${m(c.schema)}.subjects($1, $2, $3) AS s ORDER BY 1`,[d,p.type,p.id])).map(y=>y.id)},grant:ge("grant"),revoke:ge("revoke"),async relationships(d){let u=s();R("relationships");let c=pe(u,d);return(await x(`SELECT object_type, object_id, relation, subject_type, subject_id, ${ye("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(f=>({object:{type:f.object_type,id:f.object_id},relation:f.relation,subject:{type:f.subject_type,id:f.subject_id},since:f.since}))},async history(d){let u=s();R("history");let c=pe(u,d);return(await x(`SELECT ${ye("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(f=>({at:f.at,action:f.action,object:{type:f.object_type,id:f.object_id},relation:f.relation,subject:{type:f.subject_type,id:f.subject_id},by:f.actor}))}}}var on=Symbol.for("palbase.data"),sn=globalThis,C=sn[on]??=new WeakSet;function Se(e){return e instanceof Date||ArrayBuffer.isView(e)||e instanceof ArrayBuffer}function Ne(e){let n=[e];for(;n.length>0;){let t=n.pop();if(!(typeof t!="object"||t===null||C.has(t)||Se(t))){C.add(t);for(let r of Array.isArray(t)?t:Object.values(t))n.push(r)}}return e}function M(e){return typeof e=="object"&&e!==null&&C.has(e)}function an(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&&Ne(t);return e}function N(e,n){return M(e)&&C.add(n),n}function Hn(e,n,t){if(!M(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 Ee(new _({fields:[{field:n,message:r}]},`${n} ${r}`))}var re=Symbol.for("palbase.db.ref"),ve=Symbol.for("palbase.tx.expr");function W(e,n){return Object.defineProperty(e,re,{value:n,enumerable:!1}),e}function A(e){if(!(typeof e!="object"||e===null))return Object.hasOwn(e,re)?e[re]:void 0}function I(e){return A(e)==="col"&&typeof e.$col=="string"}function k(e){if(A(e)!=="sql")return!1;let n=e.$sql;return n!==void 0&&Array.isArray(n.text)&&Array.isArray(n.values)}function Jn(e){if(A(e)!=="ref")return!1;let n=e.$ref;return n!==void 0&&typeof n.op=="number"&&typeof n.field=="string"}function Xn(e){if(A(e)!=="expr")return!1;let n=e.$expr;return n!==void 0&&(n.fn==="inc"||n.fn==="dec"||n.fn==="now")}function Zn(e){if(typeof e!="object"||e===null||A(e)!==void 0)return!1;let n=e.$ref;return n!==void 0&&typeof n=="object"&&n!==null}function Qn(e){if(typeof e!="object"||e===null||A(e)!==void 0||oe(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 oe(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(!oe(e))return!1;try{let n=e[ve];return typeof n=="object"&&n!==null&&n.fn==="now"}catch{return!1}}function et(e,n,t,r){for(let o of t){let s=r[o];if(q(s))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(oe(s))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(s))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 cn=new Set(["gt","gte","lt","lte","neq","in","contains","icontains","startsWith","endsWith","isNull","overlaps"]),_e={eq:'equality is written bare: { <column>: <value> } (or { <column>: col("\u2026") } to compare with a column)'};function Pe(e,n,t){if(t&&!k(t))for(let[r,o]of Object.entries(t)){if(r==="OR"||r==="AND"||r==="NOT"){let i=r==="NOT"?[o]:o;if(!Array.isArray(i))throw new Error(`${e}(${n}): where.${r} must be an array`);for(let a of i){if(a===null||typeof a!="object")throw new Error(`${e}(${n}): the branches of where.${r} must be filter objects`);Pe(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[i,a]of Object.entries(o)){if(a===null||typeof a!="object"||Array.isArray(a))throw new Error(`${e}(${n}): where.has.${i} must be a filter object`);Pe(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 s=Object.entries(o);if(s.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[i,a]of s){if(i==="in"){if(!Array.isArray(a))throw new Error(`${e}(${n}): where.${r}.in must be an array`);if(a.some(l=>l===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(_e[i]!==void 0)throw new Error(`${e}(${n}): where.${r}.${i} is not in this filter language \u2014 ${_e[i]}`);if(!cn.has(i))throw new Error(`${e}(${n}): where.${r} has an unknown operator "${i}" (gt/gte/lt/lte/neq/in/contains/icontains/startsWith/endsWith/isNull/overlaps)`);if(a===void 0)throw new Error(`${e}(${n}): where.${r}.${i} is undefined \u2014 the comparison's right side would be NULL and match no row. Leave the condition out.`)}}}var un=["days","hours","minutes","seconds"],ln=2147483647,De=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 se(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(!un.includes(t))return{refused:`${De(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>ln)return{refused:`${t} is a whole number, 0 or more, got ${De(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 nt(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 Ce(e,n){let r=(n!==null&&typeof n=="object"?Object.keys(n):[]).filter(s=>s!=="id");if(r.length>0)throw new Error(`update(${e}): where takes the row's id alone, not ${r.map(s=>`"${s}"`).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"}},w=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"),Ke=Symbol.for("palbase.tx.rows"),ce=["then","valueOf","toString","toJSON",Symbol.toPrimitive];function ue(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 st(){return Y({fn:"now"})}function it(e){let n=se(e);if("refused"in n)throw new w(`ago() ${n.refused}`);return Y(Object.freeze({fn:"now",minus:n.span}))}function Le(e,n){if(e.fn!=="now"||e.minus===void 0)return;let t=se(e.minus);if("refused"in t)throw new w(`\`${n}\`: ago() ${t.refused}`)}function at(e){return Be(e,"increment"),Y({fn:"inc",by:e})}function ct(e){return Be(e,"decrement"),Y({fn:"dec",by:e})}function Be(e,n){if(typeof e=="string"){if(!/^-?\d+(\.\d+)?$/.test(e))throw new w(`${n}() takes a decimal number as text, got "${e}" \u2014 "12", "12.50"`)}else if(typeof e!="number"||!Number.isFinite(e))throw new w(`${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 w(`${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 ut(e){return Z(e)}function Y(e){return new Proxy({[L]:e},{get(n,t){if(t===L)return n[L];ce.includes(t)&&ue(t,"A plan expression","Write it into an operation instead.")}})}function dn(e,n){let t={[B]:{op:e,field:n}};return new Proxy(t,{get(r,o){if(o===B)return r[B];ce.includes(o)&&ue(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 fn(e){let n={[F]:e};return new Proxy(n,{get(t,r){if(r===F)return t[F];if(ce.includes(r)&&ue(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 dn(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[Ke]!==void 0}function wn(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 w(`\`${n}\`: ${o.fn}() reads the column's current value, so it is only valid in updateWhere(where, set).`);return Le(o,n),W({$expr:o},"expr")}if(X(e)!==null)throw new w(`\`${n}\`: a row handle is not a value. Read the column you meant (e.g. \`row.id\`).`);if(Q(e))throw new w(`\`${n}\`: an operation result is not a value. Declare an expectation first (\`.expectOne(err)\`) and read a column from the row.`);return Fe(e,n),e}function ae(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 w(`\`${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&&Le(r,n),e;if(X(e)!==null)throw new w(`\`${n}\`: a row handle is not a value. Read the column you meant (e.g. \`row.id\`).`);if(Q(e))throw new w(`\`${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 N(e,e.map(o=>ae(o,n)));if(e!==null&&typeof e=="object"&&!(e instanceof Date)&&!I(e)&&!k(e)){let o=N(e,{});for(let[s,i]of Object.entries(e))o[s]=ae(i,n);return o}return e}function ie(e){if(k(e))return e;let n=N(e,{});for(let t of Object.keys(e).sort()){let r=e[t];if(r===void 0)throw new w(`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]=ae(r,t)}return n}function Fe(e,n){if(!(typeof e!="object"||e===null||e instanceof Date)){if(J(e)||Z(e)||X(e)!==null||Q(e))throw new w(`\`${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))Fe(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 w(`${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]=wn(o,r,n)}return t}var U=-1,z=class{[Ke]=!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 fn(this.opIndex)}expectNone(n){this.declareGuard("none",0,n)}expectAtLeast(n,t){if(Me(n,"expectAtLeast"),this.declareGuard("atLeast",n,t),this.opIndex===U&&n>0)throw t}expectAtMost(n,t){Me(n,"expectAtMost"),this.declareGuard("atMost",n,t)}declareGuard(n,t,r){if(!(r instanceof Error))throw new w(`${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 w(`${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 Me(e,n){if(!Number.isInteger(e)||e<0)throw new w(`${n}(n) needs a non-negative integer, got ${String(e)}`)}var We=1e3,Ie=5e3,H=class{ops=[];slots=[];table(n){return{insert:t=>{let r=K(t,!1);if(Object.keys(r).length===0)throw new w(`${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 w(`${n}.put() needs at least one column`);if(r.onConflict.length===0)throw new w(`${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>Ie)throw new w(`${n}.insertMany() has ${t.length} rows; the limit is ${Ie}. Split the write.`);let o=t.map(s=>K(s,!1));return gn(o,n),this.push({op:"insertMany",table:n,rows:o,...yn(r,n)},`${n}.insertMany()`)},updateWhere:(t,r)=>{let o=ie(t),s=K(r,!0);if(Object.keys(o).length===0&&!k(o))throw new w(`${n}.updateWhere() needs a filter. An update with no filter rewrites the whole table.`);if(Object.keys(s).length===0)throw new w(`${n}.updateWhere() needs at least one column to set`);return this.push({op:"update",table:n,set:s,where:o},`${n}.updateWhere()`)},deleteWhere:t=>{let r=ie(t);if(Object.keys(r).length===0&&!k(r))throw new w(`${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},s=ie(t??{});if((Object.keys(s).length>0||k(s))&&(o.where=s),r?.limit!==void 0){if(!Number.isInteger(r.limit)||r.limit<0)throw new w(`${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>=We)throw new w(`this transaction has ${We} 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 s=this.ops[n];if(!s)throw new w(`internal: expectation on unknown operation ${n}`);let i=this.slots.length;this.slots.push(o),s.guard={kind:t,n:r,slot:i}}body(){return{ops:this.ops}}errorForSlot(n){return this.slots[n]??null}},pn=e=>typeof e=="string"?JSON.stringify(e.slice(0,40)):typeof e;function yn(e,n){if(e===void 0)return{};if(e.action!==void 0&&e.action!=="ignore"&&e.action!=="update")throw new w(`${n}.insertMany(): a conflict's action is "ignore" or "update", not ${pn(e.action)}.`);if(e.onConflict===void 0){if(e.action!=="ignore")throw new w(`${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 w(`${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 gn(e,n){let t=e[0];if(!t)return;let r=Object.keys(t),o=r.join(",");for(let s=1;s<e.length;s++){let i=Object.keys(e[s]);if(i.join(",")!==o)throw new w(`${n}.insertMany(): every row must set the same columns. Row 0 sets [${r.join(", ")}] but row ${s} sets [${i.join(", ")}]. (A property set to \`undefined\` counts as absent \u2014 use \`null\`.)`)}}function G(e,n){let t=J(e);if(t){let o=qe(n,t.op,`\`${t.field}\``);if(!(t.field in o))throw new w(`the transaction's operation ${t.op} returned no column \`${t.field}\`.`);return o[t.field]}let r=X(e);if(r!==null)return qe(n,r,"a row");if(Q(e))throw new w("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(hn(e)){let o={};for(let[s,i]of Object.entries(e))o[s]=G(i,n);return o}return e}function qe(e,n,t){let r=e[n];if(!r)throw new w(`the transaction returned no result for operation ${n}, so ${t} cannot be read.`);let o=r.rows[0];if(!o)throw new w(`the transaction's operation ${n} returned no row, so ${t} cannot be read.`);return o}function hn(e){if(typeof e!="object"||e===null)return!1;let n=Object.getPrototypeOf(e);return n===Object.prototype||n===null}async function Ue(e,n,t,r){let o=r(n),s=t.body();if(s.ops.length===0)return G(o,[]);let i;try{i=await e.txPlan(s)}catch(a){throw mn(a,t)}return G(o,i.results)}function mn(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 bn}from"node:async_hooks";function Ve(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 dt(e){if(Ve(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 ze(e){if(Ve(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 ft(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 He(e,n){return new Proxy({},{get(t,r){if(typeof r!="string")return;let o=`${n}${r}`;return{insert:s=>e().insert(o,s),insertMany:(s,i)=>e().insertMany(o,s,i),aggregate:s=>e().aggregate(o,s),update:s=>e().update(o,Ce(o,s.where),s.set),delete:s=>e().delete(o,s),findById:s=>e().findById(o,s),findUnique:s=>e().findUnique(o,s.where,{select:s.select,with:s.with,lock:s.lock}),page:s=>{let{where:i,...a}=s??{};return e().page(o,i,a)},findMany:s=>{let{where:i,...a}=s??{};return e().findMany(o,i,a)},put:s=>e().put(o,s.data,{onConflict:s.onConflict}),updateMany:s=>e().updateMany(o,s.where,s.set,s.returning===void 0?void 0:{returning:s.returning}),deleteMany:s=>e().deleteMany(o,s.where),count:s=>e().count(o,s?.where),claim:(s,i)=>e().claim(o,s,i),search:(s,i)=>e().search(o,s,i)}}})}function Ge(e,n=""){return new Proxy({},{get(t,r){if(typeof r=="string")return e.table(n+r)}})}function xn(e){let n=Ge(e);return new Proxy({},{get(t,r){if(typeof r=="string")return r==="tables"||r==="public"?n:Ge(e,ne(r,""))}})}function fe(e,n,t,r={}){let s=Object.assign({$query:(i,a)=>e().query(i,a),$diagnostics:()=>e().diagnostics(),$insert:(i,a)=>e().insert(i,a),$insertMany:((i,a,l)=>e().insertMany(i,a,l)),$update:(i,a,l)=>e().update(i,a,l),$delete:(i,a)=>e().delete(i,a),$findById:(i,a)=>e().findById(i,a),$findUnique:(i,a,l)=>e().findUnique(i,a,l),$page:(i,a,l)=>e().page(i,a,l),$findMany:(i,a,l)=>e().findMany(i,a,l),$put:(i,a,l)=>e().put(i,a,l),$updateMany:(i,a,l,h)=>e().updateMany(i,a,l,h),$deleteMany:(i,a)=>e().deleteMany(i,a),$count:(i,a)=>e().count(i,a),$search:(i,a,l)=>e().search(i,a,l),$aggregate:(i,a)=>e().aggregate(i,a),$claim:(i,a,l)=>e().claim(i,a,l),$lockRows:(i,a)=>e().lockRows(i,a),$lockRowsWhere:(i,a,l)=>e().lockRowsWhere(i,a,l),$advisoryXactLock:i=>e().advisoryXactLock(i)},r,{$access:je(e,t.names,t.as,t.unanswered),$atomic(i,a){let l=e();if(typeof l.atomic!="function")throw new Error("Database.$atomic owns one transaction and identity; nested roots and $asService are not allowed");return l.atomic(h=>n(h,()=>i(fe(()=>h,n,t))),a)},$attempt:i=>e().attempt(i),$transaction(i,a){ze(a);let l=new H;return Ue(e(),xn(l),l,i)}});return new Proxy(s,{get(i,a,l){return a==="tables"?He(e,""):typeof a=="string"&&!a.startsWith("$")&&!(a in i)?He(e,ne(a,"")):Reflect.get(i,a,l)}})}var le=new bn,de=()=>{throw new Error("Database.$atomic owns one transaction and identity; nested roots and $asService are not allowed")};function xt(e,n={}){let t={names:n.access,as:n.as??"service",...n.unanswered===void 0?{}:{unanswered:n.unanswered}},r={},o=()=>{let l=le.getStore();return l?.owner===r?l.tx:e},s=(l,h)=>le.run({owner:r,tx:Object.assign(Object.create(null),l,{atomic:de,asService:de})},h),i=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=(l,h)=>le.run({owner:r,tx:i},h);return fe(o,s,t,{$asService(){let l=o();if(typeof l.asService!="function")return de();let h=l.asService();return fe(()=>h,a,{...t,as:"service"})}})}export{m as a,Nn as b,_n as c,Pn as d,Dn as e,vn as f,Cn as g,Mn as h,Wn as i,Je as j,Oe as k,$ as l,T as m,Ee as n,$n as o,_ as p,xe as q,S as r,ke as s,Tn as t,Re as u,$e as v,Te as w,Ae as x,D as y,Xe as z,Ze as A,An as B,On as C,En as D,jn as E,g as F,nn as G,Bn as H,Se as I,Ne as J,M as K,an as L,N as M,Hn as N,W as O,I as P,k as Q,Jn as R,Xn as S,Zn as T,Qn as U,oe as V,q as W,et as X,Pe as Y,se as Z,nt as _,Ce as $,V as aa,w as ba,st as ca,it as da,at as ea,ct as fa,ut as ga,H as ha,Ue as ia,Ve as ja,dt as ka,ft as la,xt as ma};
|