palgres 0.65.0 → 0.66.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.
@@ -0,0 +1,2 @@
1
+ /*! palgres 0.66.0 — Palbase SDK License (see LICENSE) */
2
+ import{L as x,N as _,a as h,b as q,ca as b,f as v,g as w,k as C,n as D,q as A,u as T}from"./NDFZTRRI.js";var R={uuid:"uuid",text:"text",integer:"integer",bigint:"bigint",numeric:"numeric",boolean:"boolean",timestamp:"timestamp with time zone",date:"date",jsonb:"jsonb"};function Y(e,n={}){let u=Array.isArray(e)?e:[e],t={tables:[],enums:[],extensions:[],raw:[]},c=new Map;for(let o of u){for(let r of Object.values(o.tables))t.tables.push(N(o.name,r,c));t.extensions.push(...o.extensions);for(let r of o.raw??[])t.raw.push({name:r.name,schema:o.name,sql:r.up,...r.drop!==void 0?{drop:r.drop}:{},...r.before===!0?{before:!0}:{}})}t.enums=[...c.values()];for(let o of u)for(let r of Object.values(o.tables))for(let s of r.raw??[])t.raw.push({name:s.name,table:`${o.name}.${r.name}`,sql:s.up});return n.access!==void 0&&(I(t,n.access),t.access={text:n.access,compiled:_(C(t),n.access,n.roles??{authenticated:"authenticated",service:"service_role"})}),t}function I(e,n){let u;try{u=T(A(n))}catch(t){if(t instanceof D)return;throw t}for(let t of u.types.values()){let c=t.table;if(!c)continue;let o=e.tables.find(s=>s.schema===c.schema&&s.name===c.name);if(!o||o.ignored)continue;let r=O.get(o);if(o.policies.some(s=>!r?.unindexedPolicies.has(s.name)&&(x(s.using)||x(s.withCheck))))for(let s of t.relations.values())s.kind==="column"&&U(o,s.column,r?.rawNames??new Set)}}var O=new WeakMap;function U(e,n,u){let t=new Set,c=s=>s[0]!==void 0&&t.add(s[0]);c(e.primaryKey);for(let s of e.uniques)c(s.columns);for(let s of e.indexes){let l=s.keys[0];l&&"column"in l&&s.where===void 0&&t.add(l.column)}let o=e.columns.find(s=>s.name===n);if(t.has(n)||!o||o.ignored)return;let r=`${e.name}_${n}_idx`;Buffer.byteLength(r)>63||e.indexes.some(s=>s.name===r)||u.has(r)||e.indexes.push({name:r,keys:[{column:n}],unique:!1})}function j(e,n){return!n&&q(e.onDelete,e.onUpdate)?{...e,deferrable:!0}:e}function F(e){return e._def}function N(e,n,u){let t=[],c=i=>{let y=n.columns[i];return y!==void 0&&F(y).encrypted?.lookup?h(i):i},o=(n.unique??[]).map(i=>({name:i.name,columns:i.columns.map(c)})),r=[],s=[],l=new Set,f=[];for(let[i,y]of Object.entries(n.columns)){let a=F(y),d={name:i,type:P(e,i,n.name,a,u),nullable:a.nullable},S=L(a);S!==void 0&&(d.default=S),a.renamedFrom!==void 0&&(d.renamedFrom=a.renamedFrom),a.ignored&&(d.ignored=!0),a.fill!==void 0&&(d.fill=a.fill),a.identity!==void 0&&(d.identity=a.identity==="always"?"always":"by default"),a.generated!==void 0&&(d.generated={...a.generated}),a.user!==void 0&&(d.user={...a.user}),a.primaryKey&&s.push(i);let m=a.encrypted?.lookup?h(i):void 0;if(a.encrypted!==void 0&&(d.encrypted=m?{lookup:m}:{}),a.unique&&o.push(m?{name:`${n.name}_${m}_key`,columns:[m]}:{name:`${n.name}_${i}_key`,columns:[i]}),a.references!==void 0){let[g,E]=K(a.references.table);r.push(j({name:`${z(e,n.name)}_${i}_fkey`,columns:[i],refSchema:g,refTable:E,refColumns:[a.references.column],onDelete:a.onDeleteAction??"no action",onUpdate:a.onUpdateAction??"no action"},a.deferrable===!1)),a.index===!1&&l.add(i)}if(t.push(d),m){let g={name:m,type:"text",nullable:!0,lookupOf:i};a.renamedFrom!==void 0&&(g.renamedFrom=h(a.renamedFrom)),a.ignored&&(g.ignored=!0),t.push(g),a.unique||f.push({name:`${n.name}_${m}_idx`,keys:[{column:m}],unique:!1})}}for(let i of n.foreignKeys??[]){i.index===!1&&i.columns.length===1&&l.add(i.columns[0]);let[y,a]=K(i.refTable);r.push(j({name:i.name,columns:[...i.columns],refSchema:y,refTable:a,refColumns:[...i.refColumns],onDelete:i.onDelete??"no action",onUpdate:i.onUpdate??"no action",...i.match==="full"?{match:"full"}:{}},i.deferrable===!1))}let p={schema:e,name:n.name,columns:t,primaryKey:n.primaryKey!==void 0?[...n.primaryKey]:s,uniques:o,indexes:[...(n.indexes??[]).map(M),...f],checks:(n.checks??[]).map(i=>({name:i.name,expr:i.expr})),foreignKeys:r,rls:n.rls,policies:n.policies.map(B)};n.ignored&&(p.ignored=!0),n.search!==void 0&&(p.search={...n.search,from:[...n.search.from]}),p.uniques=J(p.uniques);let $=new Set((n.raw??[]).map(i=>i.name)),k=new Set(n.policies.filter(i=>i.indexes===!1).map(i=>i.name));return V(p,l,$,k),O.set(p,{rawNames:$,unindexedPolicies:k}),p}function P(e,n,u,t,c){let o=t.type;if(o==="enum"||o==="enum[]"){let r=t.enumName,s=`${e}.${r}`,l=t.enumValues??[],f=c.get(s);if(f&&f.values.join()!==l.join())throw new Error(`enum ${s} is declared with different values by ${u}.${n}: (${f.values.join(", ")}) and (${l.join(", ")}) \u2014 one type has one list`);return c.set(s,{schema:e,name:r,values:[...l]}),o==="enum[]"?`${w(e,r)}[]`:w(e,r)}return o==="sql"?v(t.sqlType):o==="numeric"&&t.precision!==void 0?`numeric(${t.precision},${t.scale??0})`:o.endsWith("[]")?`${R[o.slice(0,-2)]??o.slice(0,-2)}[]`:R[o]??o}function L(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 M(e){let n=e.expression!==void 0?[{expr:e.expression}]:(e.columns??[]).map(c=>({column:c}));for(let c of n)e.sort==="desc"&&(c.desc=!0),e.nulls!==void 0&&(c.nulls=e.nulls);let u={name:e.name,keys:n,unique:e.unique===!0},t=e.where===void 0?void 0:b(e.where);return t!==void 0&&(u.where=t),e.include?.length&&(u.include=[...e.include]),u}function B(e){let n={name:e.name,for:e.command,to:e.roles.length===0?["public"]:[...e.roles]},u=b(e.using),t=b(e.withCheck);return u!==void 0&&(n.using=u),t!==void 0&&(n.withCheck=t),e.permissive||(n.restrictive=!0),n}function V(e,n,u,t){let c=new Set,o=s=>s[0]!==void 0&&c.add(s[0]);o(e.primaryKey);for(let s of e.uniques)o(s.columns);for(let s of e.indexes){let l=s.keys[0];l&&"column"in l&&s.where===void 0&&c.add(l.column)}let r=s=>{if(c.has(s)||e.columns.find(f=>f.name===s)?.ignored)return;let l=`${e.name}_${s}_idx`;Buffer.byteLength(l)>63||e.indexes.some(f=>f.name===l)||u.has(l)||(e.indexes.push({name:l,keys:[{column:s}],unique:!1}),c.add(s))};for(let s of e.foreignKeys)s.columns.length===1&&!n.has(s.columns[0])&&r(s.columns[0]);for(let s of e.policies)if(!t.has(s.name))for(let l of W(e,s))r(l)}function W(e,n){let u=[];for(let t of[n.using,n.withCheck])if(t!==void 0)for(let c of t.matchAll(/(?<![.\w"])"((?:[^"]|"")+)"(?!\s*\.)/g)){let o=c[1].replace(/""/g,'"');e.columns.some(r=>r.name===o)&&!u.includes(o)&&u.push(o)}return u}function K(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 J(e){let n=new Map;return e.filter(u=>{let t=n.get(u.name);if(t===void 0)return n.set(u.name,u),!0;if(t.columns.join()!==u.columns.join())throw new Error(`palgres: unique ${u.name} is declared over (${t.columns.join(", ")}) and over (${u.columns.join(", ")}): give one of them another name`);return!1})}export{Y as a,W as b};
@@ -0,0 +1,3 @@
1
+ /*! palgres 0.66.0 — Palbase SDK License (see LICENSE) */
2
+ import{a as $,n as ke,p as $e,y as Re}from"./RN23MOOY.js";import{B as S,T as oe,o as te,p as re,q as be,r as O,s as A,t as me,u as xe}from"./NDFZTRRI.js";var g=class extends Error{code;constructor(n,t,o){super(t,o),this.name="AccessRefused",this.code=n}};function Ye(e,n){let t=xe(be(e)),o=new Map;for(let r of t.types.values()){let a=new Set,s=new Map;for(let i of r.relations.values())me(i)&&a.add(i.name),i.kind==="stored"&&s.set(i.name,new Set(i.subjects));for(let i of r.permissions.keys())a.add(i);o.set(r.name,{names:a,open:new Set([...a].filter(i=>t.open(r.name,i))),kept:s})}return{schema:`access_${n}`,types:o}}function mn(e,n){let t=Ye(e,""),o=r=>{let a=[...r].sort();return a.length===0?"never":a.map(s=>JSON.stringify(s)).join(" | ")};return[...t.types].map(([r,a])=>{let s=[...a.kept].sort(([i],[f])=>i<f?-1:i>f?1:0).map(([i,f])=>`${JSON.stringify(i)}: ${o(f)}`);return`${n}${r}: { names: ${o(a.names)}; relations: {${s.length===0?"":` ${s.join("; ")} `}} };`}).join(`
3
+ `)}var ze="names a subject or changes who holds what: it is the service role's \u2014 Database.$asService().$access",Ge={PA002:"no_object",PA008:"cycle",PA009:"too_deep",PA010:"too_many_parents"},Je={PA001:"unknown_name",PA003:"bad_id",PA004:"too_many",PA005:"not_kept",PA006:"not_the_service",PA007:"bad_time",...Ge};function _(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>S)throw new g("bad_id",`Database.$access: ${e} is empty or longer than ${S} characters`);return t}function Ae(e,n,t,o,r){let a=t==="anon",s=()=>{if(!n)throw new g("no_schema",`Database.$access: ${o??"the app declares no access schema \u2014 PalbaseFactory.create(\u2026, { db: { schemas, access } })"}`);return n},i=(l,u)=>{let c=typeof u=="string"?l.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 ${[...l.types.keys()].join(", ")||"none"}`);return c},f=(l,u,c)=>{let d=i(l,u);if(typeof c!="string"||!d.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 ${[...d.names].sort().join(", ")||"none"}`)},b=(l,u)=>{let c=u;if(c===null||typeof c!="object")throw new g("bad_id","Database.$access: an object is { type, id }");return i(l,c.type),{type:c.type,id:_(`the id of a ${String(c.type)}`,c.id)}},X=l=>{if(typeof l!="string")throw new g("bad_id","Database.$access: a subject is a user's id, a string");return _("a subject's id",l)},ye=(l,u)=>{let c=()=>new g("bad_id",`Database.$access: "*" is nobody's id \u2014 every signed-in user is { everyUser: true }, everyone is { public: true }`);if(u===A)throw c();if(typeof u=="string")return{type:O,id:_("a subject's id",u)};let d=u;if(d!==null&&typeof d=="object"&&"public"in d){if(d.public!==!0)throw new g("bad_id","Database.$access: everyone is { public: true }");return{type:re,id:A}}if(d!==null&&typeof d=="object"&&"everyUser"in d){if(d.everyUser!==!0)throw new g("bad_id","Database.$access: every signed-in user is { everyUser: true }");return{type:O,id:A}}if(d!==null&&typeof d=="object"&&"user"in d){let p=X(d.user);if(p===A)throw c();return{type:O,id:p}}let w=b(l,u);if(w.id===A)throw c();return w},Z=l=>l.type===O&&l.id===A?te:l.type,Fe=(l,u,c,d)=>{let w=typeof c=="string"?i(l,u.type).kept.get(c):void 0;if(!w){let h=[...i(l,u.type).kept.keys()].sort().join(", ");throw new g("not_kept",`Database.$access: type ${u.type} keeps no relation ${JSON.stringify(c)} \u2014 ${h===""?"it keeps none: its relations are read from its table":`it keeps ${h}`}`)}let p=Z(d);if(!w.has(p))throw new g("not_kept",`Database.$access: ${u.type}.${String(c)} takes ${[...w].sort().join(" or ")}, not ${p===te?"every signed-in user (user:*)":p===re?"the public":p}`)},m=async(l,u)=>{try{return await e().query(l,u)}catch(c){let d=Re(c),w=d===void 0?void 0:Je[d],p=c instanceof Error?c.message:String(c);throw w!==void 0?new g(w,`Database.$access: ${p}`,{cause:c}):d==="42501"?new g("not_the_service",`Database.$access: ${p} \u2014 what names a subject or changes who holds what is the service role's: Database.$asService().$access`,{cause:c}):c}},R=l=>{if(t!=="service")throw new g("not_the_service",`Database.$access.${l} ${ze}`)},Q=(l,u)=>u(l.caller()??null),ee=(l,u,c)=>a&&!i(l,u).open.has(c),He=l=>{if(l===void 0)return;let u=l instanceof Date?l.getTime():typeof l=="string"?Date.parse(l):Number.NaN;if(Number.isNaN(u))throw new g("bad_time","Database.$access: until is the moment a relationship ends \u2014 a Date, or ISO 8601 text (2026-12-01T00:00:00Z)");if(u<=Date.now())throw new g("bad_time",`Database.$access: a relationship is given until a moment still to come: ${new Date(u).toISOString()} has passed`);return u},ge=(l,u)=>{let c=[],d=[],w={},p=(x,k)=>{d.push(k),c.push(`${x} = $${d.length}`),w[x]=k};if(u?.object!==void 0&&(i(l,u.object.type),p("object_type",u.object.type),u.object.id!==void 0&&p("object_id",_(`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");p("relation",u.relation)}if(u?.subject!==void 0){let x=ye(l,u.subject);p("subject_type",x.type),p("subject_id",x.id)}let h=u?.limit??100;if(!Number.isSafeInteger(h)||h<1||h>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:d,limit:h,columns:w}},P=l=>`to_char(${l} AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.US"Z"')`,he=l=>async(u,c,d,w)=>{let p=s();R(l);let h=b(p,u),x=ye(p,d);Fe(p,h,c,x);let k=w?.by;if(k!==void 0&&(typeof k!="string"||k===""||k.length>S))throw new g("bad_id",`Database.$access: by is who did it \u2014 a string of at most ${S} characters`);if(l==="revoke"&&w?.until!==void 0)throw new g("bad_time","Database.$access: until is a grant's \u2014 a relationship is taken at once");let ne=l==="grant"?He(w?.until):void 0;return r?r.change(l,h,c,x,k,ne):(l==="grant"?await m(`SELECT ${$(p.schema)}.grant($1, $2, $3, $4, $5, $6, $7::timestamptz) AS v`,[h.type,h.id,c,Z(x),x.id,k??null,ne===void 0?null:new Date(ne).toISOString()]):await m(`SELECT ${$(p.schema)}.revoke($1, $2, $3, $4, $5, $6) AS v`,[h.type,h.id,c,Z(x),x.id,k??null]))[0]?.v===!0};return{async can(l,u){let c=s(),d=b(c,u);return f(c,d.type,l),ee(c,d.type,l)?!1:r?Q(r,p=>r.check(p,l,d.type,d.id)):(await m(`SELECT ${$(c.schema)}.can($1, $2, $3) AS v`,[l,d.type,d.id]))[0]?.v===!0},async objects(l,u){let c=s();return f(c,u,l),ee(c,u,l)?[]:r?Q(r,w=>r.objects(w,l,u)):(await m(`SELECT o AS id FROM ${$(c.schema)}.my_objects($1, $2) AS o ORDER BY 1`,[l,u])).map(w=>w.id)},async held(l){let u=s(),c=b(u,l),d=[...i(u,c.type).names].filter(p=>!ee(u,c.type,p)).sort();return d.length===0?[]:r?Q(r,p=>d.filter(h=>r.check(p,h,c.type,c.id))):(await m(`SELECT name FROM unnest($1::text[]) AS name WHERE ${$(u.schema)}.can(name, $2, $3) ORDER BY 1`,[d,c.type,c.id])).map(p=>p.name)},async check(l,u,c){let d=s();R("check");let w=X(l),p=b(d,c);return f(d,p.type,u),r?r.check(w,u,p.type,p.id):(await m(`SELECT ${$(d.schema)}.check($1, $2, $3, $4) AS v`,[w,u,p.type,p.id]))[0]?.v===!0},async objectsOf(l,u,c){let d=s();R("objectsOf");let w=X(l);return f(d,c,u),r?r.objects(w,u,c):(await m(`SELECT o AS id FROM ${$(d.schema)}.objects($1, $2, $3) AS o ORDER BY 1`,[w,u,c])).map(h=>h.id)},async subjects(l,u){let c=s();R("subjects");let d=b(c,u);return f(c,d.type,l),r?r.subjects(l,d.type,d.id):(await m(`SELECT s AS id FROM ${$(c.schema)}.subjects($1, $2, $3) AS s ORDER BY 1`,[l,d.type,d.id])).map(p=>p.id)},async openTo(l,u){let c=s();R("openTo");let d=b(c,u);return f(c,d.type,l),r?r.open(l,d.type,d.id):(await m(`SELECT ${$(c.schema)}.open($1, $2, $3) AS v`,[l,d.type,d.id]))[0]?.v??null},async sweep(l){s(),R("sweep");let u=l?.limit??1e4;if(!Number.isSafeInteger(u)||u<1||u>1e4)throw new g("bad_id","Database.$access: limit is a whole number from 1 to 10,000");if(r)return r.sweep(u);let c=await m("SELECT access.sweep($1::int)::text AS v",[u]);return Number(c[0]?.v??0)},grant:he("grant"),revoke:he("revoke"),async relationships(l){let u=s();R("relationships");let c=ge(u,l);if(r)return r.relationships(c.columns,c.limit);let d="(expires_at IS NULL OR expires_at > pg_catalog.statement_timestamp())";return(await m(`SELECT object_type, object_id, relation, subject_type, subject_id, ${P("created_at")} AS since, ${P("expires_at")} AS until FROM access.relationships ${c.sql===""?`WHERE ${d}`:`${c.sql} AND ${d}`} ORDER BY object_type, object_id, relation, subject_type, subject_id LIMIT ${c.limit}`,c.params)).map(p=>({object:{type:p.object_type,id:p.object_id},relation:p.relation,subject:{type:p.subject_type,id:p.subject_id},since:p.since,until:p.until}))},async history(l){let u=s();R("history");let c=ge(u,l);return r?r.history(c.columns,c.limit):(await m(`SELECT ${P("at")} AS at, action, object_type, object_id, relation, subject_type, subject_id, actor, ${P("expires_at")} AS until FROM access.past ${c.sql} ORDER BY past.at DESC, id DESC NULLS FIRST 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,until:w.until}))}}}var Xe=Symbol.for("palbase.data"),Ze=globalThis,v=Ze[Xe]??=new WeakSet;function Te(e){return e instanceof Date||ArrayBuffer.isView(e)||e instanceof ArrayBuffer}function je(e){let n=[e];for(;n.length>0;){let t=n.pop();if(!(typeof t!="object"||t===null||v.has(t)||Te(t))){v.add(t);for(let o of Array.isArray(t)?t:Object.values(t))n.push(o)}}return e}function N(e){return typeof e=="object"&&e!==null&&v.has(e)}function Qe(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&&je(t);return e}function E(e,n){return N(e)&&v.add(n),n}function An(e,n,t){if(!N(e))return;let o=`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 ke(new $e({fields:[{field:n,message:o}]},`${n} ${o}`))}var se=Symbol.for("palbase.db.ref"),Pe=Symbol.for("palbase.tx.expr");function D(e,n){return Object.defineProperty(e,se,{value:n,enumerable:!1}),e}function j(e){if(!(typeof e!="object"||e===null))return Object.hasOwn(e,se)?e[se]:void 0}function W(e){return j(e)==="col"&&typeof e.$col=="string"}function T(e){if(j(e)!=="sql")return!1;let n=e.$sql;return n!==void 0&&Array.isArray(n.text)&&Array.isArray(n.values)}function On(e){if(j(e)!=="ref")return!1;let n=e.$ref;return n!==void 0&&typeof n.op=="number"&&typeof n.field=="string"}function Sn(e){if(j(e)!=="expr")return!1;let n=e.$expr;return n!==void 0&&(n.fn==="inc"||n.fn==="dec"||n.fn==="now")}function En(e){if(typeof e!="object"||e===null||j(e)!==void 0)return!1;let n=e.$ref;return n!==void 0&&typeof n=="object"&&n!==null}function Pn(e){if(typeof e!="object"||e===null||j(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[Pe]!==void 0}catch{return!1}}function M(e){if(!ie(e))return!1;try{let n=e[Pe];return typeof n=="object"&&n!==null&&n.fn==="now"}catch{return!1}}function _n(e,n,t,o){for(let r of t){let a=o[r];if(M(a))throw new Error(`${e}(${n}): "${r}" 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: { ${r}: now() } }) or, in $transaction, tx.public.${n}.updateWhere(where, { ${r}: now() }).`);if(ie(a))throw new Error(`${e}(${n}): "${r}" got an expression handle (increment()/decrement()) where a value is expected. To add to a counter use updateMany({ where, set: { ${r}: increment(n) } }) or, in $transaction, tx.public.${n}.updateWhere(where, { ${r}: increment(n) }).`);if(W(a))throw new Error(`${e}(${n}): "${r}" got a col(). A column reference stands only in a filter; to write one column's value into another, use $query.`)}}var en=new Set(["gt","gte","lt","lte","neq","in","contains","icontains","startsWith","endsWith","isNull","overlaps"]),Oe={eq:'equality is written bare: { <column>: <value> } (or { <column>: col("\u2026") } to compare with a column)'};function Se(e,n,t){if(t&&!T(t))for(let[o,r]of Object.entries(t)){if(o==="OR"||o==="AND"||o==="NOT"){let s=o==="NOT"?[r]:r;if(!Array.isArray(s))throw new Error(`${e}(${n}): where.${o} must be an array`);for(let i of s){if(i===null||typeof i!="object")throw new Error(`${e}(${n}): the branches of where.${o} must be filter objects`);Se(e,n,i)}continue}if(o==="has"){if(r===null||typeof r!="object"||Array.isArray(r))throw new Error(`${e}(${n}): where.has must be a map of relations ({ <relation>: { \u2026 } })`);for(let[s,i]of Object.entries(r)){if(i===null||typeof i!="object"||Array.isArray(i))throw new Error(`${e}(${n}): where.has.${s} must be a filter object`);Se(e,n,i)}continue}if(r===void 0)throw new Error(`${e}(${n}): where.${o} 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(r===null||typeof r!="object"||Array.isArray(r)||W(r)||M(r))continue;let a=Object.entries(r);if(a.length===0)throw new Error(`${e}(${n}): where.${o} 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,i]of a){if(s==="in"){if(!Array.isArray(i))throw new Error(`${e}(${n}): where.${o}.in must be an array`);if(i.some(f=>f===void 0))throw new Error(`${e}(${n}): where.${o}.in holds undefined \u2014 bound as NULL it matches no row. Drop it when building the list.`);continue}if(Oe[s]!==void 0)throw new Error(`${e}(${n}): where.${o}.${s} is not in this filter language \u2014 ${Oe[s]}`);if(!en.has(s))throw new Error(`${e}(${n}): where.${o} has an unknown operator "${s}" (gt/gte/lt/lte/neq/in/contains/icontains/startsWith/endsWith/isNull/overlaps)`);if(i===void 0)throw new Error(`${e}(${n}): where.${o}.${s} is undefined \u2014 the comparison's right side would be NULL and match no row. Leave the condition out.`)}}}var nn=["days","hours","minutes","seconds"],tn=2147483647,Ee=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(!nn.includes(t))return{refused:`${Ee(t)} is not a unit of the span \u2014 days, hours, minutes or seconds`};let o=e[t];if(typeof o!="number"||!Number.isSafeInteger(o)||o<0||o>tn)return{refused:`${t} is a whole number, 0 or more, got ${Ee(o)}${o===void 0?" \u2014 leave the unit out instead":""}`};n[t]=o}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 vn(e,n,t,o){for(let r of t)if(o[r]===void 0)throw new Error(`${e}(${n}): "${r}" 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 _e(e,n){let o=(n!==null&&typeof n=="object"?Object.keys(n):[]).filter(a=>a!=="id");if(o.length>0)throw new Error(`update(${e}): where takes the row's id alone, not ${o.map(a=>`"${a}"`).join(", ")} \u2014 a condition beside the id would be dropped. To update the rows a filter matches, updateMany({ where, set }).`);let r=n?.id;if(typeof r!="string"&&typeof r!="number"&&typeof r!="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(r)}var U=class extends Error{constructor(n){super(n),this.name="TxRefError"}},y=class extends Error{constructor(n){super(n),this.name="TxPlanError"}},I=Symbol.for("palbase.tx.expr"),K=Symbol.for("palbase.tx.ref"),L=Symbol.for("palbase.tx.row"),Me=Symbol.for("palbase.tx.rows"),le=["then","valueOf","toString","toJSON",Symbol.toPrimitive];function de(e,n,t){let o=typeof e=="symbol"?e.description??String(e):e;throw new U(`${n} was used as a value (via \`${o}\`). Nothing in a transaction callback has run yet, so there is no value to read. ${t}`)}function Mn(){return H({fn:"now"})}function Cn(e){let n=ae(e);if("refused"in n)throw new y(`ago() ${n.refused}`);return H(Object.freeze({fn:"now",minus:n.span}))}function Ce(e,n){if(e.fn!=="now"||e.minus===void 0)return;let t=ae(e.minus);if("refused"in t)throw new y(`\`${n}\`: ago() ${t.refused}`)}function In(e){return Ie(e,"increment"),H({fn:"inc",by:e})}function Kn(e){return Ie(e,"decrement"),H({fn:"dec",by:e})}function Ie(e,n){if(typeof e=="string"){if(!/^-?\d+(\.\d+)?$/.test(e))throw new y(`${n}() takes a decimal number as text, got "${e}" \u2014 "12", "12.50"`)}else if(typeof e!="number"||!Number.isFinite(e))throw new y(`${n}() needs a finite number, got ${String(e)}`);if(typeof e=="string"?e.trimStart().startsWith("-"):e<0){let o=n==="increment"?"decrement":"increment";throw new y(`${n}() takes no negative amount ("${String(e)}"). Use ${o}() for the other direction \u2014 a sign kept in the amount is seen by no code that reads the direction.`)}}function Ln(e){return G(e)}function H(e){return new Proxy({[I]:e},{get(n,t){if(t===I)return n[I];le.includes(t)&&de(t,"A plan expression","Write it into an operation instead.")}})}function rn(e,n){let t={[K]:{op:e,field:n}};return new Proxy(t,{get(o,r){if(r===K)return o[K];le.includes(r)&&de(r,`\`${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 on(e){let n={[L]:e};return new Proxy(n,{get(t,o){if(o===L)return t[L];if(le.includes(o)&&de(o,"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 o!="symbol")return rn(e,o)}})}function Y(e){if(typeof e!="object"||e===null)return null;let n=e[K];return typeof n=="object"&&n!==null&&typeof n.op=="number"&&typeof n.field=="string"?n:null}function z(e){if(typeof e!="object"||e===null)return null;let n=e[L];return typeof n=="number"?n:null}function G(e){if(typeof e!="object"||e===null)return null;let n=e[I];return typeof n=="object"&&n!==null?n:null}function J(e){return typeof e=="object"&&e!==null&&e[Me]!==void 0}function sn(e,n,t){let o=Y(e);if(o)return D({$ref:{op:o.op,field:o.field}},"ref");let r=G(e);if(r){if(r.fn!=="now"&&!t)throw new y(`\`${n}\`: ${r.fn}() reads the column's current value, so it is only valid in updateWhere(where, set).`);return Ce(r,n),D({$expr:r},"expr")}if(z(e)!==null)throw new y(`\`${n}\`: a row handle is not a value. Read the column you meant (e.g. \`row.id\`).`);if(J(e))throw new y(`\`${n}\`: an operation result is not a value. Declare an expectation first (\`.expectOne(err)\`) and read a column from the row.`);return Ke(e,n),e}function ue(e,n){let t=Y(e);if(t)return D({$ref:{op:t.op,field:t.field}},"ref");let o=G(e);if(o&&o.fn!=="now")throw new y(`\`${n}\`: ${o.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(M(e))return o&&Ce(o,n),e;if(z(e)!==null)throw new y(`\`${n}\`: a row handle is not a value. Read the column you meant (e.g. \`row.id\`).`);if(J(e))throw new y(`\`${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,e.map(r=>ue(r,n)));if(e!==null&&typeof e=="object"&&!(e instanceof Date)&&!W(e)&&!T(e)){let r=E(e,{});for(let[a,s]of Object.entries(e))r[a]=ue(s,n);return r}return e}function ce(e){if(T(e))return e;let n=E(e,{});for(let t of Object.keys(e).sort()){let o=e[t];if(o===void 0)throw new y(`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(o,t)}return n}function Ke(e,n){if(!(typeof e!="object"||e===null||e instanceof Date)){if(Y(e)||G(e)||z(e)!==null||J(e))throw new y(`\`${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))Ke(t,n)}}function C(e,n){let t={};for(let o of Object.keys(e).sort()){let r=e[o];if(r===void 0)throw new y(`${o} 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[o]=sn(r,o,n)}return t}var B=-1,q=class{[Me]=!0;guarded=!1;builder;opIndex;what;constructor(n,t,o){this.builder=n,this.opIndex=t,this.what=o}then(){throw new U(`${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===B)throw n;return on(this.opIndex)}expectNone(n){this.declareGuard("none",0,n)}expectAtLeast(n,t){if(ve(n,"expectAtLeast"),this.declareGuard("atLeast",n,t),this.opIndex===B&&n>0)throw t}expectAtMost(n,t){ve(n,"expectAtMost"),this.declareGuard("atMost",n,t)}declareGuard(n,t,o){if(!(o instanceof Error))throw new y(`${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 y(`${this.what} already has an expectation. One operation carries one expectation; declare the second on its own operation.`);this.guarded=!0,this.opIndex!==B&&this.builder.attachGuard(this.opIndex,n,t,o)}};function ve(e,n){if(!Number.isInteger(e)||e<0)throw new y(`${n}(n) needs a non-negative integer, got ${String(e)}`)}var Ne=1e3,De=5e3,V=class{ops=[];slots=[];table(n){return{insert:t=>{let o=C(t,!1);if(Object.keys(o).length===0)throw new y(`${n}.insert() needs at least one column`);return this.push({op:"insert",table:n,values:o},`${n}.insert()`)},put:(t,o)=>{let r=C(t,!1);if(Object.keys(r).length===0)throw new y(`${n}.put() needs at least one column`);if(o.onConflict.length===0)throw new y(`${n}.put() needs at least one onConflict column`);return this.push({op:"upsert",table:n,values:r,onConflict:o.onConflict},`${n}.put()`)},insertMany:(t,o)=>{if(t.length===0)return new q(this,B,`${n}.insertMany()`);if(t.length>De)throw new y(`${n}.insertMany() has ${t.length} rows; the limit is ${De}. Split the write.`);let r=t.map(a=>C(a,!1));return un(r,n),this.push({op:"insertMany",table:n,rows:r,...cn(o,n)},`${n}.insertMany()`)},updateWhere:(t,o)=>{let r=ce(t),a=C(o,!0);if(Object.keys(r).length===0&&!T(r))throw new y(`${n}.updateWhere() needs a filter. An update with no filter rewrites the whole table.`);if(Object.keys(a).length===0)throw new y(`${n}.updateWhere() needs at least one column to set`);return this.push({op:"update",table:n,set:a,where:r},`${n}.updateWhere()`)},deleteWhere:t=>{let o=ce(t);if(Object.keys(o).length===0&&!T(o))throw new y(`${n}.deleteWhere() needs a filter. A delete with no filter empties the table.`);return this.push({op:"delete",table:n,where:o},`${n}.deleteWhere()`)},select:(t,o)=>{let r={op:"select",table:n},a=ce(t??{});if((Object.keys(a).length>0||T(a))&&(r.where=a),o?.limit!==void 0){if(!Number.isInteger(o.limit)||o.limit<0)throw new y(`${n}.select(): limit needs a non-negative integer, got ${String(o.limit)}`);r.limit=o.limit}return o?.lock!==void 0&&(r.lock=o.lock),this.push(r,`${n}.select()`)}}}push(n,t){if(this.ops.length>=Ne)throw new y(`this transaction has ${Ne} operations, the limit. Use insertMany() for bulk writes, or split the work.`);let o=this.ops.length;return this.ops.push(n),new q(this,o,t)}attachGuard(n,t,o,r){let a=this.ops[n];if(!a)throw new y(`internal: expectation on unknown operation ${n}`);let s=this.slots.length;this.slots.push(r),a.guard={kind:t,n:o,slot:s}}body(){return{ops:this.ops}}errorForSlot(n){return this.slots[n]??null}},an=e=>typeof e=="string"?JSON.stringify(e.slice(0,40)):typeof e;function cn(e,n){if(e===void 0)return{};if(e.action!==void 0&&e.action!=="ignore"&&e.action!=="update")throw new y(`${n}.insertMany(): a conflict's action is "ignore" or "update", not ${an(e.action)}.`);if(e.onConflict===void 0){if(e.action!=="ignore")throw new y(`${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 y(`${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 un(e,n){let t=e[0];if(!t)return;let o=Object.keys(t),r=o.join(",");for(let a=1;a<e.length;a++){let s=Object.keys(e[a]);if(s.join(",")!==r)throw new y(`${n}.insertMany(): every row must set the same columns. Row 0 sets [${o.join(", ")}] but row ${a} sets [${s.join(", ")}]. (A property set to \`undefined\` counts as absent \u2014 use \`null\`.)`)}}function F(e,n){let t=Y(e);if(t){let r=We(n,t.op,`\`${t.field}\``);if(!(t.field in r))throw new y(`the transaction's operation ${t.op} returned no column \`${t.field}\`.`);return r[t.field]}let o=z(e);if(o!==null)return We(n,o,"a row");if(J(e))throw new y("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(r=>F(r,n));if(ln(e)){let r={};for(let[a,s]of Object.entries(e))r[a]=F(s,n);return r}return e}function We(e,n,t){let o=e[n];if(!o)throw new y(`the transaction returned no result for operation ${n}, so ${t} cannot be read.`);let r=o.rows[0];if(!r)throw new y(`the transaction's operation ${n} returned no row, so ${t} cannot be read.`);return r}function ln(e){if(typeof e!="object"||e===null)return!1;let n=Object.getPrototypeOf(e);return n===Object.prototype||n===null}async function Le(e,n,t,o){let r=o(n),a=t.body();if(a.ops.length===0)return F(r,[]);let s;try{s=await e.txPlan(a)}catch(i){throw dn(i,t)}return F(r,s.results)}function dn(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 fn}from"node:async_hooks";function Be(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 Un(e){if(Be(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 Ue(e){if(Be(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 qn(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 qe(e,n){return new Proxy({},{get(t,o){if(typeof o!="string")return;let r=`${n}${o}`;return{insert:a=>e().insert(r,a),insertMany:(a,s)=>e().insertMany(r,a,s),aggregate:a=>e().aggregate(r,a),update:a=>e().update(r,_e(r,a.where),a.set),delete:a=>e().delete(r,a),findById:a=>e().findById(r,a),findUnique:a=>e().findUnique(r,a.where,{select:a.select,with:a.with,lock:a.lock}),page:a=>{let{where:s,...i}=a??{};return e().page(r,s,i)},findMany:a=>{let{where:s,...i}=a??{};return e().findMany(r,s,i)},put:a=>e().put(r,a.data,{onConflict:a.onConflict}),updateMany:a=>e().updateMany(r,a.where,a.set,a.returning===void 0?void 0:{returning:a.returning}),deleteMany:a=>e().deleteMany(r,a.where),count:a=>e().count(r,a?.where),claim:(a,s)=>e().claim(r,a,s),search:(a,s)=>e().search(r,a,s)}}})}function Ve(e,n=""){return new Proxy({},{get(t,o){if(typeof o=="string")return e.table(n+o)}})}function pn(e){let n=Ve(e);return new Proxy({},{get(t,o){if(typeof o=="string")return o==="tables"||o==="public"?n:Ve(e,oe(o,""))}})}function we(e,n,t,o={}){let a=Object.assign({$query:(s,i)=>e().query(s,i),$diagnostics:()=>e().diagnostics(),$insert:(s,i)=>e().insert(s,i),$insertMany:((s,i,f)=>e().insertMany(s,i,f)),$update:(s,i,f)=>e().update(s,i,f),$delete:(s,i)=>e().delete(s,i),$findById:(s,i)=>e().findById(s,i),$findUnique:(s,i,f)=>e().findUnique(s,i,f),$page:(s,i,f)=>e().page(s,i,f),$findMany:(s,i,f)=>e().findMany(s,i,f),$put:(s,i,f)=>e().put(s,i,f),$updateMany:(s,i,f,b)=>e().updateMany(s,i,f,b),$deleteMany:(s,i)=>e().deleteMany(s,i),$count:(s,i)=>e().count(s,i),$search:(s,i,f)=>e().search(s,i,f),$aggregate:(s,i)=>e().aggregate(s,i),$claim:(s,i,f)=>e().claim(s,i,f),$lockRows:(s,i)=>e().lockRows(s,i),$lockRowsWhere:(s,i,f)=>e().lockRowsWhere(s,i,f),$advisoryXactLock:s=>e().advisoryXactLock(s)},o,{$access:Ae(e,t.names,t.as,t.unanswered,t.via),$atomic(s,i){let f=e();if(typeof f.atomic!="function")throw new Error("Database.$atomic owns one transaction and identity; nested roots and $asService are not allowed");return f.atomic(b=>n(b,()=>s(we(()=>b,n,t))),i)},$attempt:s=>e().attempt(s),$transaction(s,i){Ue(i);let f=new V;return Le(e(),pn(f),f,s)}});return new Proxy(a,{get(s,i,f){return i==="tables"?qe(e,""):typeof i=="string"&&!i.startsWith("$")&&!(i in s)?qe(e,oe(i,"")):Reflect.get(s,i,f)}})}var fe=new fn,pe=()=>{throw new Error("Database.$atomic owns one transaction and identity; nested roots and $asService are not allowed")};function Xn(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}},o={},r=()=>{let f=fe.getStore();return f?.owner===o?f.tx:e},a=(f,b)=>fe.run({owner:o,tx:Object.assign(Object.create(null),f,{atomic:pe,asService:pe})},b),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")}}),i=(f,b)=>fe.run({owner:o,tx:s},b);return we(r,a,t,{$asService(){let f=r();if(typeof f.asService!="function")return pe();let b=f.asService();return we(()=>b,i,{...t,as:"service"})}})}export{g as a,Ye as b,mn as c,Ge as d,Te as e,je as f,N as g,Qe as h,E as i,An as j,D as k,W as l,T as m,On as n,Sn as o,En as p,Pn as q,ie as r,M as s,_n as t,Se as u,ae as v,vn as w,_e as x,U as y,y as z,Mn as A,Cn as B,In as C,Kn as D,Ln as E,V as F,Le as G,Be as H,Un as I,qn as J,Xn as K};