palgres 0.9.1 → 0.10.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,2 +1,2 @@
1
- /*! palgres 0.9.1 — Palbase SDK License (see LICENSE) */
2
- import{a as b,e as g,f as p,z as c}from"./CBPYINOK.js";var w={uuid:"uuid",text:"text",integer:"integer",bigint:"bigint",numeric:"numeric",boolean:"boolean",timestamp:"timestamp with time zone",date:"date",jsonb:"jsonb"};function O(e){let n=Array.isArray(e)?e:[e],t={tables:[],enums:[],extensions:[],raw:[]},i=new Map;for(let s of n){for(let o of Object.values(s.tables))t.tables.push(D(s.name,o,i));t.extensions.push(...s.extensions);for(let o of s.raw??[])t.raw.push({name:o.name,schema:s.name,sql:o.up,...o.drop!==void 0?{drop:o.drop}:{},...o.before===!0?{before:!0}:{}})}t.enums=[...i.values()];for(let s of n)for(let o of Object.values(s.tables))for(let f of o.raw??[])t.raw.push({name:f.name,table:`${s.name}.${o.name}`,sql:f.up});return t}function _(e,n){return!n&&b(e.onDelete,e.onUpdate)?{...e,deferrable:!0}:e}function K(e){return e._def}function D(e,n,t){let i=[],s=(n.unique??[]).map(r=>({name:r.name,columns:[...r.columns]})),o=[],f=[],l=new Set;for(let[r,y]of Object.entries(n.columns)){let u=K(y),m={name:r,type:N(e,r,n.name,u,t),nullable:u.nullable},h=P(u);if(h!==void 0&&(m.default=h),u.renamedFrom!==void 0&&(m.renamedFrom=u.renamedFrom),u.ignored&&(m.ignored=!0),u.fill!==void 0&&(m.fill=u.fill),u.identity!==void 0&&(m.identity=u.identity==="always"?"always":"by default"),u.generated!==void 0&&(m.generated={...u.generated}),u.user!==void 0&&(m.user={...u.user}),u.primaryKey&&f.push(r),u.unique&&s.push({name:`${n.name}_${r}_key`,columns:[r]}),u.references!==void 0){let[T,E]=C(u.references.table);o.push(_({name:`${Q(e,n.name)}_${r}_fkey`,columns:[r],refSchema:T,refTable:E,refColumns:[u.references.column],onDelete:u.onDeleteAction??"no action",onUpdate:u.onUpdateAction??"no action"},u.deferrable===!1)),u.index===!1&&l.add(r)}i.push(m)}for(let r of n.foreignKeys??[]){r.index===!1&&r.columns.length===1&&l.add(r.columns[0]);let[y,u]=C(r.refTable);o.push(_({name:r.name,columns:[...r.columns],refSchema:y,refTable:u,refColumns:[...r.refColumns],onDelete:r.onDelete??"no action",onUpdate:r.onUpdate??"no action",...r.match==="full"?{match:"full"}:{}},r.deferrable===!1))}let a={schema:e,name:n.name,columns:i,primaryKey:n.primaryKey!==void 0?[...n.primaryKey]:f,uniques:s,indexes:(n.indexes??[]).map(S),checks:(n.checks??[]).map(r=>({name:r.name,expr:r.expr})),foreignKeys:o,rls:n.rls,policies:n.policies.map(A)};return n.ignored&&(a.ignored=!0),n.search!==void 0&&(a.search={...n.search,from:[...n.search.from]}),a.uniques=k(a.uniques),q(a,l,new Set((n.raw??[]).map(r=>r.name)),new Set(n.policies.filter(r=>r.indexes===!1).map(r=>r.name))),a}function N(e,n,t,i,s){let o=i.type;if(o==="enum"||o==="enum[]"){let f=i.enumName,l=`${e}.${f}`,a=i.enumValues??[],r=s.get(l);if(r&&r.values.join()!==a.join())throw new Error(`enum ${l} is declared with different values by ${t}.${n}: (${r.values.join(", ")}) and (${a.join(", ")}) \u2014 one type has one list`);return s.set(l,{schema:e,name:f,values:[...a]}),o==="enum[]"?`${p(e,f)}[]`:p(e,f)}return o==="sql"?g(i.sqlType):o==="numeric"&&i.precision!==void 0?`numeric(${i.precision},${i.scale??0})`:o.endsWith("[]")?`${w[o.slice(0,-2)]??o.slice(0,-2)}[]`:w[o]??o}function P(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 S(e){let n=e.expression!==void 0?[{expr:e.expression}]:(e.columns??[]).map(s=>({column:s}));for(let s of n)e.sort==="desc"&&(s.desc=!0),e.nulls!==void 0&&(s.nulls=e.nulls);let t={name:e.name,keys:n,unique:e.unique===!0},i=e.where===void 0?void 0:c(e.where);return i!==void 0&&(t.where=i),e.include?.length&&(t.include=[...e.include]),t}function A(e){let n={name:e.name,for:e.command,to:e.roles.length===0?["public"]:[...e.roles]},t=c(e.using),i=c(e.withCheck);return t!==void 0&&(n.using=t),i!==void 0&&(n.withCheck=i),e.permissive||(n.restrictive=!0),n}function q(e,n,t,i){let s=new Set,o=l=>l[0]!==void 0&&s.add(l[0]);o(e.primaryKey);for(let l of e.uniques)o(l.columns);for(let l of e.indexes){let a=l.keys[0];a&&"column"in a&&l.where===void 0&&s.add(a.column)}let f=l=>{if(s.has(l)||e.columns.find(r=>r.name===l)?.ignored)return;let a=`${e.name}_${l}_idx`;Buffer.byteLength(a)>63||e.indexes.some(r=>r.name===a)||t.has(a)||(e.indexes.push({name:a,keys:[{column:l}],unique:!1}),s.add(l))};for(let l of e.foreignKeys)l.columns.length===1&&!n.has(l.columns[0])&&f(l.columns[0]);for(let l of e.policies)if(!i.has(l.name))for(let a of B(e,l))f(a)}function B(e,n){let t=[];for(let i of[n.using,n.withCheck])if(i!==void 0)for(let s of i.matchAll(/(?<![.\w"])"((?:[^"]|"")+)"(?!\s*\.)/g)){let o=s[1].replace(/""/g,'"');e.columns.some(f=>f.name===o)&&!t.includes(o)&&t.push(o)}return t}function C(e){let n=e.indexOf(".");return n<0?["public",e]:[e.slice(0,n),e.slice(n+1)]}function Q(e,n){return e==="public"?n:`${e}_${n}`}function k(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 x=new Set(["uuid","text","integer","bigint","numeric","boolean","timestamp","date","enum"]),U={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"}},d=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(!x.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})}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 V(){return new d("uuid")}function j(){return new d("text")}function L(){return new d("integer")}function F(){return new d("bigint")}function I(e){if(e===void 0)return new d("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 d("numeric",{type:"numeric",nullable:!1,primaryKey:!1,precision:n,scale:t})}function M(){return new d("date")}var W={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 Y(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=W[t];if(i!==void 0&&!(n.endsWith("[]")&&!x.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 d("sql",{type:"sql",nullable:!1,primaryKey:!1,sqlType:n})}var H=new Set(["smallint","real","double precision"]),z=new Set(["json"]);function J(){return new d("boolean")}function G(){return new d("timestamp")}function X(){return new d("jsonb")}function Z(e,n){let t=new d("enum");return t._def.enumName=e,t._def.enumValues=[...n],t}function ee(){let e=new d("text");return e._def.nullable=!1,e._def.user={onDelete:"cascade",owns:!0},e}function ne(e){let n=new d("text");return n._def.user={onDelete:e.onDelete,owns:!1},e.as!==void 0&&(n._def.refAs=e.as),n}export{O as a,B as b,U as c,d,V as e,j as f,L as g,F as h,I as i,M as j,Y as k,H as l,z as m,J as n,G as o,X as p,Z as q,ee as r,ne as s};
1
+ /*! palgres 0.10.0 — Palbase SDK License (see LICENSE) */
2
+ import{a as b,e as g,f as p,z as c}from"./FTBMJL4C.js";var w={uuid:"uuid",text:"text",integer:"integer",bigint:"bigint",numeric:"numeric",boolean:"boolean",timestamp:"timestamp with time zone",date:"date",jsonb:"jsonb"};function O(e){let n=Array.isArray(e)?e:[e],t={tables:[],enums:[],extensions:[],raw:[]},i=new Map;for(let s of n){for(let o of Object.values(s.tables))t.tables.push(D(s.name,o,i));t.extensions.push(...s.extensions);for(let o of s.raw??[])t.raw.push({name:o.name,schema:s.name,sql:o.up,...o.drop!==void 0?{drop:o.drop}:{},...o.before===!0?{before:!0}:{}})}t.enums=[...i.values()];for(let s of n)for(let o of Object.values(s.tables))for(let f of o.raw??[])t.raw.push({name:f.name,table:`${s.name}.${o.name}`,sql:f.up});return t}function _(e,n){return!n&&b(e.onDelete,e.onUpdate)?{...e,deferrable:!0}:e}function K(e){return e._def}function D(e,n,t){let i=[],s=(n.unique??[]).map(r=>({name:r.name,columns:[...r.columns]})),o=[],f=[],l=new Set;for(let[r,y]of Object.entries(n.columns)){let u=K(y),m={name:r,type:N(e,r,n.name,u,t),nullable:u.nullable},h=P(u);if(h!==void 0&&(m.default=h),u.renamedFrom!==void 0&&(m.renamedFrom=u.renamedFrom),u.ignored&&(m.ignored=!0),u.fill!==void 0&&(m.fill=u.fill),u.identity!==void 0&&(m.identity=u.identity==="always"?"always":"by default"),u.generated!==void 0&&(m.generated={...u.generated}),u.user!==void 0&&(m.user={...u.user}),u.primaryKey&&f.push(r),u.unique&&s.push({name:`${n.name}_${r}_key`,columns:[r]}),u.references!==void 0){let[T,E]=C(u.references.table);o.push(_({name:`${Q(e,n.name)}_${r}_fkey`,columns:[r],refSchema:T,refTable:E,refColumns:[u.references.column],onDelete:u.onDeleteAction??"no action",onUpdate:u.onUpdateAction??"no action"},u.deferrable===!1)),u.index===!1&&l.add(r)}i.push(m)}for(let r of n.foreignKeys??[]){r.index===!1&&r.columns.length===1&&l.add(r.columns[0]);let[y,u]=C(r.refTable);o.push(_({name:r.name,columns:[...r.columns],refSchema:y,refTable:u,refColumns:[...r.refColumns],onDelete:r.onDelete??"no action",onUpdate:r.onUpdate??"no action",...r.match==="full"?{match:"full"}:{}},r.deferrable===!1))}let a={schema:e,name:n.name,columns:i,primaryKey:n.primaryKey!==void 0?[...n.primaryKey]:f,uniques:s,indexes:(n.indexes??[]).map(S),checks:(n.checks??[]).map(r=>({name:r.name,expr:r.expr})),foreignKeys:o,rls:n.rls,policies:n.policies.map(A)};return n.ignored&&(a.ignored=!0),n.search!==void 0&&(a.search={...n.search,from:[...n.search.from]}),a.uniques=k(a.uniques),q(a,l,new Set((n.raw??[]).map(r=>r.name)),new Set(n.policies.filter(r=>r.indexes===!1).map(r=>r.name))),a}function N(e,n,t,i,s){let o=i.type;if(o==="enum"||o==="enum[]"){let f=i.enumName,l=`${e}.${f}`,a=i.enumValues??[],r=s.get(l);if(r&&r.values.join()!==a.join())throw new Error(`enum ${l} is declared with different values by ${t}.${n}: (${r.values.join(", ")}) and (${a.join(", ")}) \u2014 one type has one list`);return s.set(l,{schema:e,name:f,values:[...a]}),o==="enum[]"?`${p(e,f)}[]`:p(e,f)}return o==="sql"?g(i.sqlType):o==="numeric"&&i.precision!==void 0?`numeric(${i.precision},${i.scale??0})`:o.endsWith("[]")?`${w[o.slice(0,-2)]??o.slice(0,-2)}[]`:w[o]??o}function P(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 S(e){let n=e.expression!==void 0?[{expr:e.expression}]:(e.columns??[]).map(s=>({column:s}));for(let s of n)e.sort==="desc"&&(s.desc=!0),e.nulls!==void 0&&(s.nulls=e.nulls);let t={name:e.name,keys:n,unique:e.unique===!0},i=e.where===void 0?void 0:c(e.where);return i!==void 0&&(t.where=i),e.include?.length&&(t.include=[...e.include]),t}function A(e){let n={name:e.name,for:e.command,to:e.roles.length===0?["public"]:[...e.roles]},t=c(e.using),i=c(e.withCheck);return t!==void 0&&(n.using=t),i!==void 0&&(n.withCheck=i),e.permissive||(n.restrictive=!0),n}function q(e,n,t,i){let s=new Set,o=l=>l[0]!==void 0&&s.add(l[0]);o(e.primaryKey);for(let l of e.uniques)o(l.columns);for(let l of e.indexes){let a=l.keys[0];a&&"column"in a&&l.where===void 0&&s.add(a.column)}let f=l=>{if(s.has(l)||e.columns.find(r=>r.name===l)?.ignored)return;let a=`${e.name}_${l}_idx`;Buffer.byteLength(a)>63||e.indexes.some(r=>r.name===a)||t.has(a)||(e.indexes.push({name:a,keys:[{column:l}],unique:!1}),s.add(l))};for(let l of e.foreignKeys)l.columns.length===1&&!n.has(l.columns[0])&&f(l.columns[0]);for(let l of e.policies)if(!i.has(l.name))for(let a of B(e,l))f(a)}function B(e,n){let t=[];for(let i of[n.using,n.withCheck])if(i!==void 0)for(let s of i.matchAll(/(?<![.\w"])"((?:[^"]|"")+)"(?!\s*\.)/g)){let o=s[1].replace(/""/g,'"');e.columns.some(f=>f.name===o)&&!t.includes(o)&&t.push(o)}return t}function C(e){let n=e.indexOf(".");return n<0?["public",e]:[e.slice(0,n),e.slice(n+1)]}function Q(e,n){return e==="public"?n:`${e}_${n}`}function k(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 x=new Set(["uuid","text","integer","bigint","numeric","boolean","timestamp","date","enum"]),U={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"}},d=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(!x.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})}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 V(){return new d("uuid")}function j(){return new d("text")}function L(){return new d("integer")}function F(){return new d("bigint")}function I(e){if(e===void 0)return new d("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 d("numeric",{type:"numeric",nullable:!1,primaryKey:!1,precision:n,scale:t})}function M(){return new d("date")}var W={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 Y(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=W[t];if(i!==void 0&&!(n.endsWith("[]")&&!x.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 d("sql",{type:"sql",nullable:!1,primaryKey:!1,sqlType:n})}var H=new Set(["smallint","real","double precision"]),z=new Set(["json"]);function J(){return new d("boolean")}function G(){return new d("timestamp")}function X(){return new d("jsonb")}function Z(e,n){let t=new d("enum");return t._def.enumName=e,t._def.enumValues=[...n],t}function ee(){let e=new d("text");return e._def.nullable=!1,e._def.user={onDelete:"cascade",owns:!0},e}function ne(e){let n=new d("text");return n._def.user={onDelete:e.onDelete,owns:!1},e.as!==void 0&&(n._def.refAs=e.as),n}export{O as a,B as b,U as c,d,V as e,j as f,L as g,F as h,I as i,M as j,Y as k,H as l,z as m,J as n,G as o,X as p,Z as q,ee as r,ne as s};
@@ -1,5 +1,5 @@
1
- /*! palgres 0.9.1 — Palbase SDK License (see LICENSE) */
1
+ /*! palgres 0.10.0 — Palbase SDK License (see LICENSE) */
2
2
  import{createHash as z}from"node:crypto";function fe(n,e){let t=r=>r==="cascade"||r==="set null"||r==="set default";return t(n)||t(e)}var L=class extends Error{problems;constructor(e){super(`the schema is not valid:
3
3
  - ${e.join(`
4
4
  - `)}`),this.name="SchemaError",this.problems=e}},ue=()=>({tables:[],enums:[],extensions:[],raw:[]}),b=n=>`${n.schema}.${n.name}`,Q={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 D(n){let e=n.trim().replace(/\s+/g," "),t="";for(;e.endsWith("[]");)t+="[]",e=e.slice(0,-2).trim();let r=/^((?:"(?:[^"]|"")+"|[A-Za-z_][A-Za-z0-9_ ]*?)(?:\.(?:"(?:[^"]|"")+"|[A-Za-z_][A-Za-z0-9_]*))?)\s*(\(.*\))?$/.exec(e);if(!r)return n.trim()+t;let c=r[2]?r[2].replace(/\s+/g,""):"",o=W(r[1]);return o===void 0?n.trim()+t:o.length===1&&o[0].quoted?`"${o[0].name.replace(/"/g,'""')}"${c}${t}`:o.length===1?`${Q[o[0].name]??o[0].name}${c}${t}`:`${o.map(l=>N(l.name)).join(".")}${c}${t}`}var N=n=>/^[a-z_][a-z0-9_$]*$/.test(n)?n:`"${n.replace(/"/g,'""')}"`,de=(n,e)=>`${N(n)}.${N(e)}`;function W(n){let e=[],t=0;for(;t<n.length;){if(n[t]==='"'){let r=t+1,c="";for(;;){if(r>=n.length)return;if(n[r]==='"'){if(n[r+1]==='"'){c+='"',r+=2;continue}break}c+=n[r++]}e.push({name:c,quoted:!0}),t=r+1}else{let r=/^[A-Za-z_][A-Za-z0-9_ ]*/.exec(n.slice(t));if(!r)return;e.push({name:r[0].trim().toLowerCase(),quoted:!1}),t+=r[0].length}if(t<n.length){if(n[t]!==".")return;t++}}return e}var J=/^[A-Za-z_][A-Za-z0-9_$]*$/,Z=63;function y(n,e,t=!1){if(typeof e!="string"||e==="")return`${n} has no name`;if(t?e.includes("\0"):!J.test(e))return`${n} "${e}": a name is letters, digits and _ (starting with a letter or _)`;if(Buffer.byteLength(e)>Z)return`${n} "${e}": longer than Postgres' 63 bytes, it would be cut`;if(e.startsWith("palgres_")||e.startsWith("_palgres"))return`${n} "${e}": names starting with palgres_ are Palgres' own`}var G="vector",F=["cosine","euclidean","inner_product"],A=1536,X=2e3,R=4e3,Y=/^(text|citext|public\.citext|character varying(\(\d+\))?)$/;function q(n,e,t){let r=[];e.primaryKey.length!==1&&r.push(`${n} 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(t.from)||t.from.length===0)&&r.push(`${n}: search.from is empty \u2014 name the text columns a row is found by (search: { from: ['title', 'body'], model })`);let c=new Set;for(let o of Array.isArray(t.from)?t.from:[]){c.has(o)&&r.push(`${n}: search.from names "${o}" twice \u2014 name each column once`),c.add(o);let l=e.columns.find(i=>i.name===o);l?l.ignored?r.push(`${n}: search.from names "${o}", which is ignored \u2014 take it out of search.from, or keep the column`):Y.test(D(l.type))?l.generated&&r.push(`${n}: search.from names "${o}", 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`):r.push(`${n}: search.from names "${o}", which is ${l.type} \u2014 search reads text (text, varchar, citext): name a text column, or keep the text in one`):r.push(`${n}: search.from names "${o}", which the table does not have \u2014 name its text columns`)}return(typeof t.model!="string"||t.model.trim()==="")&&r.push(`${n}: search.model is empty \u2014 name the embedding model (search: { from, model: 'embedding' })`),F.includes(t.metric)||r.push(`${n}: search.metric is ${JSON.stringify(t.metric)} \u2014 it is ${F.map(o=>`'${o}'`).join(", ")}`),(!Number.isInteger(t.dimensions)||t.dimensions<1||t.dimensions>R)&&r.push(`${n}: search.dimensions is ${String(t.dimensions)} \u2014 it is 1 to ${R}: pgvector indexes a vector of at most ${X} dimensions and a half-precision one of at most ${R}; ask the model for fewer (search: { dimensions: ${A} })`),t.staleness!=="null"&&t.staleness!=="keep"&&r.push(`${n}: search.staleness is ${JSON.stringify(t.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(o=>o.name==="_score"&&!o.ignored)&&r.push(`${n} declares search and has a column "_score": search() answers each row with its _score \u2014 rename the column`),r}function me(n){let e=[],t=i=>i&&e.push(i),r=new Map,c=new Map,o=(i,a,u)=>{let f=`${i}.${a}`,d=c.get(f);d?e.push(`${u} "${a}" has the name of ${d} in schema ${i}`):c.set(f,u)};for(let i of n.enums)t(y("an enum",i.name)),i.values.length===0&&e.push(`enum ${i.schema}.${i.name} has no values`),new Set(i.values).size!==i.values.length&&e.push(`enum ${i.schema}.${i.name} names a value twice`);for(let i of n.tables){let a=b(i);t(y("a schema",i.schema)),t(y("a table",i.name)),r.has(a)&&e.push(`table ${a} is declared twice`),r.set(a,i),o(i.schema,i.name,`table ${a}`);let u=new Map,f=(s,m)=>{let C=u.get(s);C?e.push(`${m} "${s}" has the name of a ${C} of table ${a}`):u.set(s,m)},d=new Map;for(let s of i.columns)t(y(`column ${a}.${s.name}`,s.name)),d.has(s.name)&&e.push(`column ${a}.${s.name} is declared twice`),d.set(s.name,s),s.fill!==void 0&&s.nullable&&e.push(`column ${a}.${s.name}: fillWith is for a column that is NOT NULL`),s.identity&&s.default!==void 0&&e.push(`column ${a}.${s.name}: an identity column has no default`),s.generated&&(s.default!==void 0||s.identity||s.fill!==void 0)&&e.push(`column ${a}.${s.name}: a generated column has no default, identity or fill`),s.generated&&!s.generated.expr.trim()&&e.push(`column ${a}.${s.name}: a generated column's expression is empty`),s.identity&&!["smallint","integer","bigint"].includes(D(s.type))&&e.push(`column ${a}.${s.name}: an identity column is smallint, integer or bigint`),s.identity&&s.nullable&&e.push(`column ${a}.${s.name}: an identity column is NOT NULL`);let g=(s,m)=>{let C=d.get(s);C?C.ignored&&e.push(`${m} names column "${s}", which is ignored`):e.push(`${m} names column "${s}", which ${a} does not have`)};for(let s of i.primaryKey)g(s,`the primary key of ${a}`);for(let s of i.primaryKey)d.get(s)?.nullable&&e.push(`column ${a}.${s} is in the primary key, so it is not nullable`);for(let s of i.uniques){t(y(`a unique constraint of ${a}`,s.name,!0)),o(i.schema,s.name,`unique constraint ${a}.${s.name}`),f(s.name,"unique constraint"),s.columns.length===0&&e.push(`unique constraint ${s.name} names no column`);for(let m of s.columns)g(m,`unique constraint ${s.name}`)}for(let s of i.indexes){t(y(`an index of ${a}`,s.name,!0)),o(i.schema,s.name,`index ${a}.${s.name}`),s.keys.length===0&&e.push(`index ${s.name} has no key`);for(let m of s.keys)"column"in m&&g(m.column,`index ${s.name}`);for(let m of s.include??[])g(m,`index ${s.name}`)}for(let s of i.checks)t(y(`a check of ${a}`,s.name,!0)),f(s.name,"check"),s.expr.trim()||e.push(`check ${s.name} has no expression`);for(let s of i.foreignKeys){t(y(`a foreign key of ${a}`,s.name,!0)),f(s.name,"foreign key"),(s.columns.length===0||s.columns.length!==s.refColumns.length)&&e.push(`foreign key ${s.name} names ${s.columns.length} column(s) and references ${s.refColumns.length}`);for(let m of s.columns)g(m,`foreign key ${s.name}`)}let k=new Set;for(let s of i.policies)t(y(`a policy of ${a}`,s.name,!0)),k.has(s.name)&&e.push(`policy ${a}.${s.name} is declared twice`),k.add(s.name),s.to.length===0&&e.push(`policy ${a}.${s.name} names no role`),s.for==="insert"&&s.using!==void 0&&e.push(`policy ${a}.${s.name}: an insert policy has only withCheck`),(s.for==="select"||s.for==="delete")&&s.withCheck!==void 0&&e.push(`policy ${a}.${s.name}: a ${s.for} policy has only using`);i.policies.length>0&&!i.rls&&e.push(`table ${a} has policies but row-level security off: they would do nothing`),i.search!==void 0&&e.push(...q(`table ${a}`,i,i.search))}for(let i of n.tables)for(let a of i.foreignKeys){let u=r.get(`${a.refSchema}.${a.refTable}`);if(!u){e.push(`foreign key ${a.name} of ${b(i)} references ${a.refSchema}.${a.refTable}, which is not declared`);continue}u.ignored&&e.push(`foreign key ${a.name} of ${b(i)} references ${b(u)}, which is ignored`);for(let f of a.refColumns)u.columns.some(d=>d.name===f&&!d.ignored)||e.push(`foreign key ${a.name} references ${b(u)}.${f}, which it does not have`)}let l=new Set;for(let i of n.raw)t(y("a raw unit",i.name)),l.has(i.name)&&e.push(`raw unit ${i.name} is declared twice`),l.add(i.name),i.sql.trim()||e.push(`raw unit ${i.name} has no SQL`),i.before&&i.table!==void 0&&e.push(`raw unit ${i.name}: before is for a schema's unit, not a table's \u2014 a table's is made after its table`);return e}function j(n){let e=t=>[...t].sort((r,c)=>r.name<c.name?-1:r.name>c.name?1:0);return{tables:[...n.tables].map(t=>({...t,schema:t.schema||"public",columns:t.columns.map(r=>({...r,type:D(r.type)})),uniques:e(t.uniques),indexes:e(t.indexes),checks:e(t.checks),foreignKeys:e(t.foreignKeys),policies:e(t.policies).map(r=>({...r,to:[...r.to].sort()}))})).sort((t,r)=>b(t)<b(r)?-1:b(t)>b(r)?1:0),enums:[...n.enums].sort((t,r)=>`${t.schema}.${t.name}`<`${r.schema}.${r.name}`?-1:1),extensions:[...new Set([...n.extensions,...n.tables.some(t=>t.search!==void 0)?[G]:[]])].sort(),raw:e(n.raw)}}function pe(n){let e=j(n),t=new Map(n.raw.map((r,c)=>[r.name,c]));return e.raw.sort((r,c)=>(t.get(r.name)??0)-(t.get(c.name)??0)),e}function O(n){return Array.isArray(n)?`[${n.map(O).join(",")}]`:n&&typeof n=="object"?`{${Object.entries(n).filter(([,t])=>t!==void 0).sort(([t],[r])=>t<r?-1:1).map(([t,r])=>`${JSON.stringify(t)}:${O(r)}`).join(",")}}`:JSON.stringify(n)}function he(n){return z("sha256").update(O(j(n))).digest("hex").slice(0,32)}var M=Symbol.for("palbase.table.meta"),x=Symbol.for("palbase.ref.target"),S=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(t=>{let r=t.expr;if(r.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 r.name}),this}references(e,...t){if(t.length===0)throw new Error(`foreignKey(${this._def.name}).references(): needs at least one target column.`);return this._def.refColumns=[...t],typeof e=="function"?(Object.defineProperty(this._def,x,{value:()=>e()[M],enumerable:!1,configurable:!0}),this):(this._def.refTable=e[M].name,Object.defineProperty(this._def,x,{value:e[M],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 V(n){return new S(n)}function B(n){let e=n instanceof S?n._def:n;if(e.columns.length===0)throw new Error(`foreignKey(${e.name}): needs at least one local column \u2014 call .on(...).`);let t=typeof e[x]=="function";if(e.refColumns.length===0||e.refTable===""&&!t)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 h=class n{expr;constructor(e){this.expr=e}bin(e,t){return new n({kind:"binop",op:e,left:this.expr,right:ee(t)})}eq(e){return this.bin("eq",e)}neq(e){return this.bin("neq",e)}gt(e){return this.bin("gt",e)}gte(e){return this.bin("gte",e)}lt(e){return this.bin("lt",e)}lte(e){return this.bin("lte",e)}isNull(e=!1){return new n({kind:"isNull",expr:this.expr,negated:e})}and(...e){return new n({kind:"and",parts:[this.expr,...e.map(t=>t.expr)]})}or(...e){return new n({kind:"or",parts:[this.expr,...e.map(t=>t.expr)]})}not(){return new n({kind:"not",expr:this.expr})}};function ee(n){return n instanceof h?n.expr:{kind:"lit",value:n}}function E(n,e=0,t=""){let r=`pb_e${e}`;return{col:c=>new h(e===0?{kind:"col",name:c}:{kind:"col",name:c,alias:r}),auth:{uid:()=>new h({kind:"authUid"})},lit:c=>new h({kind:"lit",value:c}),and:(...c)=>new h({kind:"and",parts:c.map(o=>o.expr)}),or:(...c)=>new h({kind:"or",parts:c.map(o=>o.expr)}),not:c=>new h({kind:"not",expr:c.expr}),existsIn:(c,o)=>{let l=c[_],i=E(Object.keys(l.columns),e+1,t),a={kind:"exists",table:l.name,alias:`pb_e${e+1}`,outer:t,predicate:o(i).expr};return Object.defineProperty(a,x,{value:l,enumerable:!1,configurable:!0}),new h(a)}}}function p(n){return`"${n.replace(/"/g,'""')}"`}var P=class{_def;constructor(e){this._def={name:e,command:"all",roles:["authenticated"],using:null,withCheck:null,permissive:!0}}for(e){return this._def.command=e,this}to(...e){return this._def.roles=e,this}using(e){return this._def.using=e instanceof h?e.expr:e,this}memberOf(e,t,r={}){if(this._def.using!==null)throw new Error(`policy(${this._def.name}).memberOf(): this policy already has a using() expression. Write one or the other \u2014 memberOf IS the using expression.`);let c=r.column??"id",o=r.userColumn??"user_id";return this._def.using=`${p(c)} IN (SELECT ${p(t)} FROM ${p(e)} WHERE ${p(o)} = (select auth.uid()))`,this}withCheck(e){return this._def.withCheck=e instanceof h?e.expr:e,this}withoutIndexes(){return this._def.indexes=!1,this}as(e){return this._def.permissive=e==="permissive",this}};function $e(n){return new P(n)}function T(n,e){switch(n.kind){case"exists":throw new Error(`check(${e}): \`existsIn(...)\` is a subquery and PostgreSQL forbids subqueries in a CHECK constraint \u2014 express a cross-table rule as a composite FOREIGN KEY (foreignKeys), or as a guard.`);case"authUid":throw new Error(`check(${e}): \`auth.uid()\` renders as a subquery \`(SELECT auth.uid())\` and PostgreSQL forbids subqueries in a CHECK constraint \u2014 a caller-dependent rule belongs in an RLS policy, not a CHECK.`);case"binop":T(n.left,e),T(n.right,e);return;case"and":case"or":for(let t of n.parts)T(t,e);return;case"not":case"isNull":T(n.expr,e);return;default:return}}var ne={eq:"=",neq:"<>",gt:">",gte:">=",lt:"<",lte:"<="};function U(n){if(n===null)return"NULL";if(typeof n=="boolean")return n?"true":"false";if(typeof n=="number"){if(!Number.isFinite(n))throw new Error(`check(): ${n} is not an SQL number literal.`);return String(n)}return`'${n.replace(/'/g,"''")}'`}function w(n,e){switch(n.kind){case"col":return p(n.name);case"lit":return U(n.value);case"binop":{let t=ne[n.op];if(t===void 0)throw new Error(`check(${e}): \`${n.op}\` is not supported in a CHECK expression.`);return`(${w(n.left,e)} ${t} ${w(n.right,e)})`}case"and":case"or":{if(n.parts.length===0)return n.kind==="and"?"(true)":"(false)";let t=n.kind==="and"?" AND ":" OR ";return`(${n.parts.map(r=>w(r,e)).join(t)})`}case"not":return`(NOT ${w(n.expr,e)})`;case"isNull":return`(${w(n.expr,e)} IS ${n.negated?"NOT NULL":"NULL"})`;default:{let t=n.kind;throw new Error(`check(${e}): a \`${t}\` node is not one a CHECK expression takes.`)}}}function te(n,e){if(n.trim()==="")throw new Error("check(): the constraint's name cannot be empty \u2014 Palbase reconciles CHECKs by name.");return T(e.expr,n),{name:n,expr:w(e.expr,n)}}function we(n){if(n!==null)return typeof n=="string"?n:$(n,"")}var re={eq:"=",neq:"<>",gt:">",gte:">=",lt:"<",lte:"<="};function H(n){let e=n.indexOf(".");return e<0?`${p("public")}.${p(n)}`:`${p(n.slice(0,e))}.${p(n.slice(e+1))}`}function $(n,e){switch(n.kind){case"col":return n.alias!==void 0?`${p(n.alias)}.${p(n.name)}`:e===""?p(n.name):`${H(e)}.${p(n.name)}`;case"authUid":return"(SELECT auth.uid())";case"lit":return U(n.value);case"binop":{let t=re[n.op];if(t===void 0)throw new Error(`policy expression: \`${n.op}\` is not an operator a policy can use`);return`(${$(n.left,e)} ${t} ${$(n.right,e)})`}case"and":case"or":return n.parts.length===0?n.kind==="and"?"(true)":"(false)":`(${n.parts.map(t=>$(t,e)).join(n.kind==="and"?" AND ":" OR ")})`;case"not":return`(NOT ${$(n.expr,e)})`;case"isNull":return`(${$(n.expr,e)} IS ${n.negated?"NOT NULL":"NULL"})`;case"exists":if(n.outer==="")throw new Error("policy expression: an existsIn carries no outer table \u2014 its correlation would collapse to x = x and filter nothing");return`EXISTS (SELECT 1 FROM ${H(n.table)} ${p(n.alias)} WHERE (${$(n.predicate,n.outer)}))`}}function v(n,e){return n===""||n==="public"?e:`${n}.${e}`}var K=class{_def;constructor(e){if(e.trim()==="")throw new Error("index(name): an index's name cannot be empty \u2014 Palbase reconciles indexes by name.");this._def={name:e}}unique(){return this._def.unique=!0,this}on(...e){return this._def.columns=e.map(t=>{let r=t.expr;if(r.kind!=="col")throw new Error(`index(${this._def.name}).on(): takes column references only \u2014 for an expression, use onExpression("\u2026").`);return r.name}),this}onExpression(e){return this._def.expression=e,this}where(e){return this._def.where=e.expr,this}desc(){return this._def.sort="desc",this}asc(){return this._def.sort="asc",this}nulls(e){return this._def.nulls=e,this}include(e){return this._def.include=e,this}};function Se(n){return new K(n)}function ie(n){return n instanceof P?n._def:n}var _=Symbol.for("palbase.table.meta");function _e(n,e){if(n.trim()==="")throw new Error("defineTable(name, \u2026): name must not be empty");let t=(e.policies?.(E(Object.keys(e.columns),0,n))??[]).map(ie),r=t.length>0||e.rls!==!1,c={};for(let[f,d]of Object.entries(e.columns)){let g=d;ae(n,f,g._def);let k=Object.create(Object.getPrototypeOf(g));Object.defineProperty(k,"_def",{value:{...g._def},enumerable:!0,writable:!0}),c[f]=k}let o={name:n,columns:c,rls:r,policies:t};if(e.primaryKey!==void 0&&(o.primaryKey=[...e.primaryKey]),e.search!==void 0&&(o.search=se(n,e.search,c,o.primaryKey)),e.unique!==void 0&&(o.unique=e.unique.map(f=>({name:f.name,columns:[...f.columns]}))),e.raw!==void 0&&e.raw.length>0){for(let f of e.raw)if(f.drop!==void 0)throw new Error(`defineTable(${JSON.stringify(n)}): raw ${JSON.stringify(f.name)} carries a drop, but a table-level raw() has no teardown \u2014 a drop is run only for a schema-level unit: defineSchema(name, { tables, raw: [raw(name, up, { drop })] })`);o.raw=e.raw.slice()}let l=typeof e.checks=="function"?e.checks(E(Object.keys(e.columns),0,n)):e.checks?.slice()??[];l.length>0&&(o.checks=l);let i=(e.indexes?.(E(Object.keys(e.columns),0,n))??[]).map(f=>f instanceof K?f._def:f);i.length>0&&(o.indexes=i);let a=(e.foreignKeys?.(E(Object.keys(e.columns),0,n))??[]).map(B);a.length>0&&(o.foreignKeys=a),e.ignored===!0&&(o.ignored=!0);for(let f of Object.values(c))f._def.ownerTable=o;let u={...c};return Object.defineProperty(u,_,{value:o,enumerable:!1}),u}function se(n,e,t,r){if(e===null||typeof e!="object")throw new Error(`defineTable(${JSON.stringify(n)}): search is { from: [...columns], model } \u2014 got ${e===null?"null":typeof e}`);let c={from:Array.isArray(e.from)?[...e.from]:e.from,model:e.model,dimensions:e.dimensions??A,metric:e.metric??"cosine",staleness:e.staleness??"null"},o=Object.entries(t).map(([i,a])=>({name:i,def:a._def})),l=q(`defineTable(${JSON.stringify(n)})`,{columns:o.map(({name:i,def:a})=>({name:i,type:a.type==="sql"?a.sqlType??"sql":a.type,...a.ignored?{ignored:!0}:{},...a.generated?{generated:a.generated}:{}})),primaryKey:r??o.filter(({def:i})=>i.primaryKey===!0).map(({name:i})=>i)},c);if(l.length>0)throw new Error(l.join(`
5
- `));return c}var I=new WeakMap;function oe(n,e){for(let t of Object.values(n))le(t,`table "${t.name}"`,e);for(let t of Object.values(n))for(let[r,c]of Object.entries(t.columns)){let o=c._def;if(o.selfRefColumn!==void 0){if(!(o.selfRefColumn in t.columns))throw new Error(`table "${t.name}" column "${r}": selfReferences("${o.selfRefColumn}") \u2014 no such column on this table`);o.references={table:v(e,t.name),column:o.selfRefColumn};continue}if(o.referencesThunk===void 0)continue;let l=o.referencesThunk(),i=l?._def?.ownerTable;if(i===void 0)throw new Error(`table "${t.name}" column "${r}": references(() => \u2026) must point at a column of a table declared with defineTable(...)`);let a=Object.entries(i.columns).find(([,f])=>f._def===l._def)?.[0];if(a===void 0)throw new Error(`table "${t.name}" column "${r}": the referenced column was not found on table "${i.name}"`);let u=I.get(i);if(u===void 0)throw new Error(`table "${t.name}" column "${r}": references(() => \u2026) points at table "${i.name}", which no defineSchema(...) has claimed yet \u2014 a foreign key cannot be written without its target's schema. Declare that table's schema first (one file per schema: db/public.ts, db/billing.ts \u2026, imported by this one).`);o.references={table:v(u,i.name),column:a}}}function ae(n,e,t){if(t.fill===void 0)return;let r=t.nullable===!0?"the column is .nullable() \u2014 .fillWith() fills a NOT NULL column; keep one of the two":t.ignored===!0?"the column is .ignored() \u2014 this release never writes it, so there is nothing to fill for it":t.defaultValue!==void 0||t.defaultRandom===!0||t.defaultNow===!0||t.defaultSql!==void 0?"the column has a default \u2014 the default already fills every row; keep one of the two":null;if(r!==null)throw new Error(`defineTable(${JSON.stringify(n)}): column "${e}" \u2014 .fillWith(): ${r}`)}function Ke(n,e){if(typeof n!="string")throw new Error(`defineSchema(...) takes the schema NAME first: defineSchema("public", { tables: [todos, lists] }). The one-argument form defineSchema({ tables: { \u2026 } }) is gone \u2014 a schema that does not say its own name cannot be told apart from another schema's table of the same name, which is what a cross-schema foreign key has to do. Migrate db/public.ts (one file per schema: db/public.ts, db/billing.ts \u2026): name the schema, and lift each table key onto the table itself with defineTable("todos", { columns: { \u2026 } }), then list the tables in the array.`);if(n.trim()==="")throw new Error("defineSchema(name, \u2026): name must not be empty");let t={};for(let l of e.tables){let i=l[_];if(t[i.name]!==void 0)throw new Error(`defineSchema("${n}"): two tables declare the name "${i.name}" \u2014 table names must be unique within a schema`);t[i.name]=i,I.set(i,n)}oe(t,n);let r=[...new Set(e.extensions??[])],c=(e.raw??[]).slice(),o=new Set;for(let l of c){if(typeof l.name!="string"||l.name.trim()==="")throw new Error(`defineSchema("${n}"): a raw unit needs a name`);if(o.has(l.name))throw new Error(`defineSchema("${n}"): two raw units are named "${l.name}" \u2014 a unit's name identifies it`);o.add(l.name)}return{name:n,tables:t,extensions:r,exposed:e.exposed??n==="public",raw:c}}function le(n,e,t){let r=(l,i)=>{let a=l[x];if(a===void 0)return;let u;try{u=typeof a=="function"?a():a}catch(g){throw new Error(`${e}: ${i} names its target through a callback that failed: ${g.message}`)}if(u==null||typeof u.name!="string")throw new Error(`${e}: ${i}'s callback does not answer a table \u2014 write references(() => otherTable, \u2026)`);let f=I.get(u);if(f===void 0)throw new Error(`${e}: ${i} points at table "${u.name}", which no defineSchema(...) has claimed yet \u2014 a cross-table reference cannot be written without its target's schema. Declare that table's schema first (one file per schema: db/public.ts, db/billing.ts \u2026, imported by this one).`);let d=v(f,u.name);l.refTable!==void 0&&(l.refTable=d),l.table!==void 0&&(l.table=d)};for(let l of n.foreignKeys??[])r(l,`foreignKey("${l.name}")`);let c=`${t}.${n.name}`,o=(l,i)=>{if(!(l==null||typeof l=="string"))switch(l.kind){case"exists":r(l,i),l.table.includes(".")||(l.table=`public.${l.table}`),l.outer=c,o(l.predicate,i);return;case"binop":o(l.left,i),o(l.right,i);return;case"and":case"or":for(let a of l.parts)o(a,i);return;case"not":case"isNull":o(l.expr,i);return;default:return}};for(let l of n.policies)o(l.using,`policy("${l.name}")`),o(l.withCheck,`policy("${l.name}")`);for(let l of n.indexes??[])o(l.where,`index("${l.name}")`)}export{fe as a,L as b,ue as c,b as d,D as e,de as f,X as g,q as h,me as i,j,pe as k,he as l,S as m,V as n,v as o,K as p,Se as q,_ as r,_e as s,Ke as t,h as u,E as v,P as w,$e as x,te as y,we as z};
5
+ `));return c}var I=new WeakMap;function oe(n,e){for(let t of Object.values(n))le(t,`table "${t.name}"`,e);for(let t of Object.values(n))for(let[r,c]of Object.entries(t.columns)){let o=c._def;if(o.selfRefColumn!==void 0){if(!(o.selfRefColumn in t.columns))throw new Error(`table "${t.name}" column "${r}": selfReferences("${o.selfRefColumn}") \u2014 no such column on this table`);o.references={table:v(e,t.name),column:o.selfRefColumn};continue}if(o.referencesThunk===void 0)continue;let l=o.referencesThunk(),i=l?._def?.ownerTable;if(i===void 0)throw new Error(`table "${t.name}" column "${r}": references(() => \u2026) must point at a column of a table declared with defineTable(...)`);let a=Object.entries(i.columns).find(([,f])=>f._def===l._def)?.[0];if(a===void 0)throw new Error(`table "${t.name}" column "${r}": the referenced column was not found on table "${i.name}"`);let u=I.get(i);if(u===void 0)throw new Error(`table "${t.name}" column "${r}": references(() => \u2026) points at table "${i.name}", which no defineSchema(...) has claimed yet \u2014 a foreign key cannot be written without its target's schema. Declare that table's schema first (one file per schema: db/public.ts, db/billing.ts \u2026, imported by this one).`);o.references={table:v(u,i.name),column:a}}}function ae(n,e,t){if(t.fill===void 0)return;let r=t.nullable===!0?"the column is .nullable() \u2014 .fillWith() fills a NOT NULL column; keep one of the two":t.ignored===!0?"the column is .ignored() \u2014 this release never writes it, so there is nothing to fill for it":t.defaultValue!==void 0||t.defaultRandom===!0||t.defaultNow===!0||t.defaultSql!==void 0?"the column has a default \u2014 the default already fills every row; keep one of the two":null;if(r!==null)throw new Error(`defineTable(${JSON.stringify(n)}): column "${e}" \u2014 .fillWith(): ${r}`)}function Ke(n,e){if(typeof n!="string")throw new Error(`defineSchema(...) takes the schema NAME first: defineSchema("public", { tables: [todos, lists] }). The one-argument form defineSchema({ tables: { \u2026 } }) is gone \u2014 a schema that does not say its own name cannot be told apart from another schema's table of the same name, which is what a cross-schema foreign key has to do. Migrate db/public.ts (one file per schema: db/public.ts, db/billing.ts \u2026): name the schema, and lift each table key onto the table itself with defineTable("todos", { columns: { \u2026 } }), then list the tables in the array.`);if(n.trim()==="")throw new Error("defineSchema(name, \u2026): name must not be empty");let t={};for(let l of e.tables){let i=l[_];if(t[i.name]!==void 0)throw new Error(`defineSchema("${n}"): two tables declare the name "${i.name}" \u2014 table names must be unique within a schema`);t[i.name]=i,I.set(i,n)}oe(t,n);let r=[...new Set(e.extensions??[])],c=(e.raw??[]).slice(),o=new Set;for(let l of c){if(typeof l.name!="string"||l.name.trim()==="")throw new Error(`defineSchema("${n}"): a raw unit needs a name`);if(o.has(l.name))throw new Error(`defineSchema("${n}"): two raw units are named "${l.name}" \u2014 a unit's name identifies it`);o.add(l.name)}return{name:n,tables:t,extensions:r,raw:c}}function le(n,e,t){let r=(l,i)=>{let a=l[x];if(a===void 0)return;let u;try{u=typeof a=="function"?a():a}catch(g){throw new Error(`${e}: ${i} names its target through a callback that failed: ${g.message}`)}if(u==null||typeof u.name!="string")throw new Error(`${e}: ${i}'s callback does not answer a table \u2014 write references(() => otherTable, \u2026)`);let f=I.get(u);if(f===void 0)throw new Error(`${e}: ${i} points at table "${u.name}", which no defineSchema(...) has claimed yet \u2014 a cross-table reference cannot be written without its target's schema. Declare that table's schema first (one file per schema: db/public.ts, db/billing.ts \u2026, imported by this one).`);let d=v(f,u.name);l.refTable!==void 0&&(l.refTable=d),l.table!==void 0&&(l.table=d)};for(let l of n.foreignKeys??[])r(l,`foreignKey("${l.name}")`);let c=`${t}.${n.name}`,o=(l,i)=>{if(!(l==null||typeof l=="string"))switch(l.kind){case"exists":r(l,i),l.table.includes(".")||(l.table=`public.${l.table}`),l.outer=c,o(l.predicate,i);return;case"binop":o(l.left,i),o(l.right,i);return;case"and":case"or":for(let a of l.parts)o(a,i);return;case"not":case"isNull":o(l.expr,i);return;default:return}};for(let l of n.policies)o(l.using,`policy("${l.name}")`),o(l.withCheck,`policy("${l.name}")`);for(let l of n.indexes??[])o(l.where,`index("${l.name}")`)}export{fe as a,L as b,ue as c,b as d,D as e,de as f,X as g,q as h,me as i,j,pe as k,he as l,S as m,V as n,v as o,K as p,Se as q,_ as r,_e as s,Ke as t,h as u,E as v,P as w,$e as x,te as y,we as z};
@@ -1,2 +1,2 @@
1
- /*! palgres 0.9.1 — Palbase SDK License (see LICENSE) */
2
- import{o as q}from"./CBPYINOK.js";var Te=Symbol.for("palbase.backend.httpError"),ee=Symbol.for("palbase.backend.engineRaised"),d=Object.freeze({uniqueViolation:"23505",foreignKeyViolation:"23503",serializationFailure:"40001",deadlockDetected:"40P01",queryCancelled:"57014",lockNotAvailable:"55P03",inFailedTransaction:"25P02",insufficientPrivilege:"42501"}),f=class extends Error{[Te]=!0;status;error;errorDescription;data;retryAfter;constructor(n,t,r,i,o){super(r),this.name="HttpError",this.status=n,this.error=t,this.errorDescription=r,i!==void 0&&(this.data=i),o!==void 0&&(this.retryAfter=o)}};function ne(e){return e[ee]=!0,e}function Ue(e){return typeof e=="object"&&e!==null&&e[ee]===!0}function g(e){let n=e.replace(/([a-z0-9])([A-Z])/g,"$1 $2");return n.charAt(0).toUpperCase()+n.slice(1).toLowerCase()}var y=class extends f{constructor(n,t){super(400,"bad_request",t??g("BadRequest"),n),this.name="BadRequest"}},H=class extends f{constructor(n,t,r){super(404,t??"not_found",n??g("NotFound"),r),this.name="NotFound"}},p=class extends f{constructor(n,t,r){super(409,t??"conflict",n??g("Conflict"),r),this.name="Conflict"}},X=class extends p{constraint;sqlstate=d.uniqueViolation;static is(n){return typeof n=="object"&&n!==null&&n.name==="UniqueViolation"&&typeof n.constraint=="string"}constructor(n,t,r,i){super(t??"Unique constraint violated",r??"unique_violation",i),this.name="UniqueViolation",this.constraint=n}};function Ve(e){if(typeof e!="object"||e===null||e.retryable!==!0)return!1;let n=e.sqlstate;return n===d.serializationFailure||n===d.deadlockDetected}var J=class extends p{retryable=!0;sqlstate;static is(n){return typeof n=="object"&&n!==null&&n.name==="SerializationFailure"}constructor(n=d.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}},Q=class extends p{retryable=!0;sqlstate;static is(n){return typeof n=="object"&&n!==null&&n.name==="DeadlockDetected"}constructor(n=d.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}},Y=class extends Error{sqlstate=d.inFailedTransaction;static is(n){return typeof n=="object"&&n!==null&&n.name==="TransactionAborted"}constructor(n,t){super(n,{cause:t}),this.name="TransactionAborted"}},Z=class extends f{constructor(n,t){super(429,"too_many_requests",t??g("TooManyRequests"),n,n.retryAfter),this.name="TooManyRequests"}};function te(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 $e=new Set(["57P03","53300","08001","08004","ERR_POSTGRES_CONNECTION_REFUSED","ERR_POSTGRES_CONNECTION_FAILED","ERR_POSTGRES_CONNECTION_TIMEOUT","ECONNREFUSED","CONNECT_TIMEOUT"]),Ee=new Set(["57P01","57P02","08000","08003","08006","08007","08P01","ERR_POSTGRES_CONNECTION_CLOSED","CONNECTION_CLOSED","CONNECTION_DESTROYED","ECONNRESET","ETIMEDOUT","EPIPE"]);function Fe(e){return e instanceof Error&&e.code===void 0&&e.message==="connection must be a PostgresSQLConnection"}function Ke(e){let n=e;for(let t=0;t<4&&typeof n=="object"&&n!==null;t++){let r=te(n),i=n.code,o=s=>r!==void 0&&s.has(r)||typeof i=="string"&&s.has(i);if(o(Ee))return"lost";if(o($e))return"never";n=n.cause}}function ze(e){let n=e;for(let t=0;t<4&&typeof n=="object"&&n!==null;t++){let r=n.sqlstate,i=te(n)??(typeof r=="string"?r:void 0);if(i!==void 0)return!i.startsWith("08")&&!/^57P0[123]$/.test(i);n=n.cause}return!1}function Ge(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 Oe=Symbol.for("palbase.data"),Se=globalThis,x=Se[Oe]??=new WeakSet;function re(e){return e instanceof Date||ArrayBuffer.isView(e)||e instanceof ArrayBuffer}function oe(e){let n=[e];for(;n.length>0;){let t=n.pop();if(!(typeof t!="object"||t===null||x.has(t)||re(t))){x.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&&x.has(e)}function Pe(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&&oe(t);return e}function h(e,n){return m(e)&&x.add(n),n}function Ye(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 ne(new y({fields:[{field:n,message:r}]},`${n} ${r}`))}var I=Symbol.for("palbase.db.ref"),ue=Symbol.for("palbase.tx.expr");function b(e,n){return Object.defineProperty(e,I,{value:n,enumerable:!1}),e}function w(e){if(!(typeof e!="object"||e===null))return Object.hasOwn(e,I)?e[I]:void 0}function R(e){return w(e)==="col"&&typeof e.$col=="string"}function l(e){if(w(e)!=="sql")return!1;let n=e.$sql;return n!==void 0&&Array.isArray(n.text)&&Array.isArray(n.values)}function nn(e){if(w(e)!=="ref")return!1;let n=e.$ref;return n!==void 0&&typeof n.op=="number"&&typeof n.field=="string"}function tn(e){if(w(e)!=="expr")return!1;let n=e.$expr;return n!==void 0&&(n.fn==="inc"||n.fn==="dec"||n.fn==="now")}function rn(e){if(typeof e!="object"||e===null||w(e)!==void 0)return!1;let n=e.$ref;return n!==void 0&&typeof n=="object"&&n!==null}function on(e){if(typeof e!="object"||e===null||w(e)!==void 0||_(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 _(e){if(typeof e!="object"&&typeof e!="function"||e===null)return!1;try{return e[ue]!==void 0}catch{return!1}}function k(e){if(!_(e))return!1;try{let n=e[ue];return typeof n=="object"&&n!==null&&n.fn==="now"}catch{return!1}}function sn(e,n,t,r){for(let i of t){let o=r[i];if(k(o))throw new Error(`${e}(${n}): "${i}" 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: { ${i}: now() } }) or, in $transaction, tx.public.${n}.updateWhere(where, { ${i}: now() }).`);if(_(o))throw new Error(`${e}(${n}): "${i}" got an expression handle (increment()/decrement()) where a value is expected. To add to a counter use updateMany({ where, set: { ${i}: increment(n) } }) or, in $transaction, tx.public.${n}.updateWhere(where, { ${i}: increment(n) }).`);if(R(o))throw new Error(`${e}(${n}): "${i}" got a col(). A column reference stands only in a filter; to write one column's value into another, use $query.`)}}var Ae=new Set(["gt","gte","lt","lte","neq","in","contains","icontains","startsWith","endsWith","isNull","overlaps"]),ie={eq:'equality is written bare: { <column>: <value> } (or { <column>: col("\u2026") } to compare with a column)'};function se(e,n,t){if(t&&!l(t))for(let[r,i]of Object.entries(t)){if(r==="OR"||r==="AND"||r==="NOT"){let s=r==="NOT"?[i]:i;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`);se(e,n,a)}continue}if(r==="has"){if(i===null||typeof i!="object"||Array.isArray(i))throw new Error(`${e}(${n}): where.has must be a map of relations ({ <relation>: { \u2026 } })`);for(let[s,a]of Object.entries(i)){if(a===null||typeof a!="object"||Array.isArray(a))throw new Error(`${e}(${n}): where.has.${s} must be a filter object`);se(e,n,a)}continue}if(i===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(i===null||typeof i!="object"||Array.isArray(i)||R(i)||k(i))continue;let o=Object.entries(i);if(o.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 o){if(s==="in"){if(!Array.isArray(a))throw new Error(`${e}(${n}): where.${r}.in must be an array`);if(a.some(c=>c===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(ie[s]!==void 0)throw new Error(`${e}(${n}): where.${r}.${s} is not in this filter language \u2014 ${ie[s]}`);if(!Ae.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 Ne=["days","hours","minutes","seconds"],je=2147483647,ae=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 B(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(!Ne.includes(t))return{refused:`${ae(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>je)return{refused:`${t} is a whole number, 0 or more, got ${ae(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 an(e,n,t,r){for(let i of t)if(r[i]===void 0)throw new Error(`${e}(${n}): "${i}" 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 le(e,n){let r=(n!==null&&typeof n=="object"?Object.keys(n):[]).filter(o=>o!=="id");if(r.length>0)throw new Error(`update(${e}): where takes the row's id alone, not ${r.map(o=>`"${o}"`).join(", ")} \u2014 a condition beside the id would be dropped. To update the rows a filter matches, updateMany({ where, set }).`);let i=n?.id;if(typeof i!="string"&&typeof i!="number"&&typeof i!="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(i)}var P=class extends Error{constructor(n){super(n),this.name="TxRefError"}},u=class extends Error{constructor(n){super(n),this.name="TxPlanError"}},$=Symbol.for("palbase.tx.expr"),E=Symbol.for("palbase.tx.ref"),O=Symbol.for("palbase.tx.row"),pe=Symbol.for("palbase.tx.rows"),V=["then","valueOf","toString","toJSON",Symbol.toPrimitive];function F(e,n,t){let r=typeof e=="symbol"?e.description??String(e):e;throw new P(`${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 dn(){return W({fn:"now"})}function fn(e){let n=B(e);if("refused"in n)throw new u(`ago() ${n.refused}`);return W(Object.freeze({fn:"now",minus:n.span}))}function he(e,n){if(e.fn!=="now"||e.minus===void 0)return;let t=B(e.minus);if("refused"in t)throw new u(`\`${n}\`: ago() ${t.refused}`)}function wn(e){return ye(e,"increment"),W({fn:"inc",by:e})}function pn(e){return ye(e,"decrement"),W({fn:"dec",by:e})}function ye(e,n){if(typeof e=="string"){if(!/^-?\d+(\.\d+)?$/.test(e))throw new u(`${n}() takes a decimal number as text, got "${e}" \u2014 "12", "12.50"`)}else if(typeof e!="number"||!Number.isFinite(e))throw new u(`${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 u(`${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 hn(e){return C(e)}function W(e){return new Proxy({[$]:e},{get(n,t){if(t===$)return n[$];V.includes(t)&&F(t,"A plan expression","Write it into an operation instead.")}})}function We(e,n){let t={[E]:{op:e,field:n}};return new Proxy(t,{get(r,i){if(i===E)return r[E];V.includes(i)&&F(i,`\`${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 De(e){let n={[O]:e};return new Proxy(n,{get(t,r){if(r===O)return t[O];if(V.includes(r)&&F(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 We(e,r)}})}function D(e){if(typeof e!="object"||e===null)return null;let n=e[E];return typeof n=="object"&&n!==null&&typeof n.op=="number"&&typeof n.field=="string"?n:null}function v(e){if(typeof e!="object"||e===null)return null;let n=e[O];return typeof n=="number"?n:null}function C(e){if(typeof e!="object"||e===null)return null;let n=e[$];return typeof n=="object"&&n!==null?n:null}function M(e){return typeof e=="object"&&e!==null&&e[pe]!==void 0}function ve(e,n,t){let r=D(e);if(r)return b({$ref:{op:r.op,field:r.field}},"ref");let i=C(e);if(i){if(i.fn!=="now"&&!t)throw new u(`\`${n}\`: ${i.fn}() reads the column's current value, so it is only valid in updateWhere(where, set).`);return he(i,n),b({$expr:i},"expr")}if(v(e)!==null)throw new u(`\`${n}\`: a row handle is not a value. Read the column you meant (e.g. \`row.id\`).`);if(M(e))throw new u(`\`${n}\`: an operation result is not a value. Declare an expectation first (\`.expectOne(err)\`) and read a column from the row.`);return ge(e,n),e}function U(e,n){let t=D(e);if(t)return b({$ref:{op:t.op,field:t.field}},"ref");let r=C(e);if(r&&r.fn!=="now")throw new u(`\`${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(k(e))return r&&he(r,n),e;if(v(e)!==null)throw new u(`\`${n}\`: a row handle is not a value. Read the column you meant (e.g. \`row.id\`).`);if(M(e))throw new u(`\`${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 h(e,e.map(i=>U(i,n)));if(e!==null&&typeof e=="object"&&!(e instanceof Date)&&!R(e)&&!l(e)){let i=h(e,{});for(let[o,s]of Object.entries(e))i[o]=U(s,n);return i}return e}function L(e){if(l(e))return e;let n=h(e,{});for(let t of Object.keys(e).sort()){let r=e[t];if(r===void 0)throw new u(`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]=U(r,t)}return n}function ge(e,n){if(!(typeof e!="object"||e===null||e instanceof Date)){if(D(e)||C(e)||v(e)!==null||M(e))throw new u(`\`${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))ge(t,n)}}function T(e,n){let t={};for(let r of Object.keys(e).sort()){let i=e[r];if(i===void 0)throw new u(`${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]=ve(i,r,n)}return t}var S=-1,A=class{[pe]=!0;guarded=!1;builder;opIndex;what;constructor(n,t,r){this.builder=n,this.opIndex=t,this.what=r}then(){throw new P(`${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===S)throw n;return De(this.opIndex)}expectNone(n){this.declareGuard("none",0,n)}expectAtLeast(n,t){if(ce(n,"expectAtLeast"),this.declareGuard("atLeast",n,t),this.opIndex===S&&n>0)throw t}expectAtMost(n,t){ce(n,"expectAtMost"),this.declareGuard("atMost",n,t)}declareGuard(n,t,r){if(!(r instanceof Error))throw new u(`${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 u(`${this.what} already has an expectation. One operation carries one expectation; declare the second on its own operation.`);this.guarded=!0,this.opIndex!==S&&this.builder.attachGuard(this.opIndex,n,t,r)}};function ce(e,n){if(!Number.isInteger(e)||e<0)throw new u(`${n}(n) needs a non-negative integer, got ${String(e)}`)}var de=1e3,fe=5e3,N=class{ops=[];slots=[];table(n){return{insert:t=>{let r=T(t,!1);if(Object.keys(r).length===0)throw new u(`${n}.insert() needs at least one column`);return this.push({op:"insert",table:n,values:r},`${n}.insert()`)},put:(t,r)=>{let i=T(t,!1);if(Object.keys(i).length===0)throw new u(`${n}.put() needs at least one column`);if(r.onConflict.length===0)throw new u(`${n}.put() needs at least one onConflict column`);return this.push({op:"upsert",table:n,values:i,onConflict:r.onConflict},`${n}.put()`)},insertMany:(t,r)=>{if(t.length===0)return new A(this,S,`${n}.insertMany()`);if(t.length>fe)throw new u(`${n}.insertMany() has ${t.length} rows; the limit is ${fe}. Split the write.`);let i=t.map(o=>T(o,!1));return qe(i,n),this.push({op:"insertMany",table:n,rows:i,...Me(r,n)},`${n}.insertMany()`)},updateWhere:(t,r)=>{let i=L(t),o=T(r,!0);if(Object.keys(i).length===0&&!l(i))throw new u(`${n}.updateWhere() needs a filter. An update with no filter rewrites the whole table.`);if(Object.keys(o).length===0)throw new u(`${n}.updateWhere() needs at least one column to set`);return this.push({op:"update",table:n,set:o,where:i},`${n}.updateWhere()`)},deleteWhere:t=>{let r=L(t);if(Object.keys(r).length===0&&!l(r))throw new u(`${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 i={op:"select",table:n},o=L(t??{});if((Object.keys(o).length>0||l(o))&&(i.where=o),r?.limit!==void 0){if(!Number.isInteger(r.limit)||r.limit<0)throw new u(`${n}.select(): limit needs a non-negative integer, got ${String(r.limit)}`);i.limit=r.limit}return r?.lock!==void 0&&(i.lock=r.lock),this.push(i,`${n}.select()`)}}}push(n,t){if(this.ops.length>=de)throw new u(`this transaction has ${de} operations, the limit. Use insertMany() for bulk writes, or split the work.`);let r=this.ops.length;return this.ops.push(n),new A(this,r,t)}attachGuard(n,t,r,i){let o=this.ops[n];if(!o)throw new u(`internal: expectation on unknown operation ${n}`);let s=this.slots.length;this.slots.push(i),o.guard={kind:t,n:r,slot:s}}body(){return{ops:this.ops}}errorForSlot(n){return this.slots[n]??null}},Ce=e=>typeof e=="string"?JSON.stringify(e.slice(0,40)):typeof e;function Me(e,n){if(e===void 0)return{};if(e.action!==void 0&&e.action!=="ignore"&&e.action!=="update")throw new u(`${n}.insertMany(): a conflict's action is "ignore" or "update", not ${Ce(e.action)}.`);if(e.onConflict===void 0){if(e.action!=="ignore")throw new u(`${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 u(`${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 qe(e,n){let t=e[0];if(!t)return;let r=Object.keys(t),i=r.join(",");for(let o=1;o<e.length;o++){let s=Object.keys(e[o]);if(s.join(",")!==i)throw new u(`${n}.insertMany(): every row must set the same columns. Row 0 sets [${r.join(", ")}] but row ${o} sets [${s.join(", ")}]. (A property set to \`undefined\` counts as absent \u2014 use \`null\`.)`)}}function j(e,n){let t=D(e);if(t){let i=we(n,t.op,`\`${t.field}\``);if(!(t.field in i))throw new u(`the transaction's operation ${t.op} returned no column \`${t.field}\`.`);return i[t.field]}let r=v(e);if(r!==null)return we(n,r,"a row");if(M(e))throw new u("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(i=>j(i,n));if(Ie(e)){let i={};for(let[o,s]of Object.entries(e))i[o]=j(s,n);return i}return e}function we(e,n,t){let r=e[n];if(!r)throw new u(`the transaction returned no result for operation ${n}, so ${t} cannot be read.`);let i=r.rows[0];if(!i)throw new u(`the transaction's operation ${n} returned no row, so ${t} cannot be read.`);return i}function Ie(e){if(typeof e!="object"||e===null)return!1;let n=Object.getPrototypeOf(e);return n===Object.prototype||n===null}async function xe(e,n,t,r){let i=r(n),o=t.body();if(o.ops.length===0)return j(i,[]);let s;try{s=await e.txPlan(o)}catch(a){throw _e(a,t)}return j(i,s.results)}function _e(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 Be}from"node:async_hooks";function me(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 gn(e){if(me(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 be(e){if(me(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 xn(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 Re(e,n){return new Proxy({},{get(t,r){if(typeof r!="string")return;let i=`${n}${r}`;return{insert:o=>e().insert(i,o),insertMany:(o,s)=>e().insertMany(i,o,s),aggregate:o=>e().aggregate(i,o),update:o=>e().update(i,le(i,o.where),o.set),delete:o=>e().delete(i,o),findById:o=>e().findById(i,o),findUnique:o=>e().findUnique(i,o.where,{select:o.select,with:o.with,lock:o.lock}),page:o=>{let{where:s,...a}=o??{};return e().page(i,s,a)},findMany:o=>{let{where:s,...a}=o??{};return e().findMany(i,s,a)},put:o=>e().put(i,o.data,{onConflict:o.onConflict}),updateMany:o=>e().updateMany(i,o.where,o.set,o.returning===void 0?void 0:{returning:o.returning}),deleteMany:o=>e().deleteMany(i,o.where),count:o=>e().count(i,o?.where),claim:(o,s)=>e().claim(i,o,s),search:(o,s)=>e().search(i,o,s)}}})}function ke(e,n=""){return new Proxy({},{get(t,r){if(typeof r=="string")return e.table(n+r)}})}function Le(e){let n=ke(e);return new Proxy({},{get(t,r){if(typeof r=="string")return r==="tables"||r==="public"?n:ke(e,q(r,""))}})}function G(e,n,t={}){let i=Object.assign({$query:(o,s)=>e().query(o,s),$diagnostics:()=>e().diagnostics(),$insert:(o,s)=>e().insert(o,s),$insertMany:((o,s,a)=>e().insertMany(o,s,a)),$update:(o,s,a)=>e().update(o,s,a),$delete:(o,s)=>e().delete(o,s),$findById:(o,s)=>e().findById(o,s),$findUnique:(o,s,a)=>e().findUnique(o,s,a),$page:(o,s,a)=>e().page(o,s,a),$findMany:(o,s,a)=>e().findMany(o,s,a),$put:(o,s,a)=>e().put(o,s,a),$updateMany:(o,s,a,c)=>e().updateMany(o,s,a,c),$deleteMany:(o,s)=>e().deleteMany(o,s),$count:(o,s)=>e().count(o,s),$search:(o,s,a)=>e().search(o,s,a),$aggregate:(o,s)=>e().aggregate(o,s),$claim:(o,s,a)=>e().claim(o,s,a),$lockRows:(o,s)=>e().lockRows(o,s),$lockRowsWhere:(o,s,a)=>e().lockRowsWhere(o,s,a),$advisoryXactLock:o=>e().advisoryXactLock(o)},t,{$atomic(o,s){let a=e();if(typeof a.atomic!="function")throw new Error("Database.$atomic owns one transaction and identity; nested roots and $asService are not allowed");return a.atomic(c=>n(c,()=>o(G(()=>c,n))),s)},$attempt:o=>e().attempt(o),$transaction(o,s){be(s);let a=new N;return xe(e(),Le(a),a,o)}});return new Proxy(i,{get(o,s,a){return s==="tables"?Re(e,""):typeof s=="string"&&!s.startsWith("$")&&!(s in o)?Re(e,q(s,"")):Reflect.get(o,s,a)}})}var K=new Be,z=()=>{throw new Error("Database.$atomic owns one transaction and identity; nested roots and $asService are not allowed")};function En(e){let n={},t=()=>{let s=K.getStore();return s?.owner===n?s.tx:e},r=(s,a)=>K.run({owner:n,tx:Object.assign(Object.create(null),s,{atomic:z,asService:z})},a),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")}}),o=(s,a)=>K.run({owner:n,tx:i},a);return G(t,r,{$asService(){let s=t();if(typeof s.asService!="function")return z();let a=s.asService();return G(()=>a,o)}})}export{Te as a,ee as b,d as c,f as d,ne as e,Ue as f,y as g,H as h,p as i,X as j,Ve as k,J as l,Q as m,Y as n,Z as o,te as p,$e as q,Ee as r,Fe as s,Ke as t,ze as u,Ge as v,re as w,oe as x,m as y,Pe as z,h as A,Ye as B,b as C,R as D,l as E,nn as F,tn as G,rn as H,on as I,_ as J,k as K,sn as L,se as M,B as N,an as O,le as P,P as Q,u as R,dn as S,fn as T,wn as U,pn as V,hn as W,N as X,xe as Y,me as Z,gn as _,xn as $,En as aa};
1
+ /*! palgres 0.10.0 — Palbase SDK License (see LICENSE) */
2
+ import{o as q}from"./FTBMJL4C.js";var Te=Symbol.for("palbase.backend.httpError"),ee=Symbol.for("palbase.backend.engineRaised"),d=Object.freeze({uniqueViolation:"23505",foreignKeyViolation:"23503",serializationFailure:"40001",deadlockDetected:"40P01",queryCancelled:"57014",lockNotAvailable:"55P03",inFailedTransaction:"25P02",insufficientPrivilege:"42501"}),f=class extends Error{[Te]=!0;status;error;errorDescription;data;retryAfter;constructor(n,t,r,i,o){super(r),this.name="HttpError",this.status=n,this.error=t,this.errorDescription=r,i!==void 0&&(this.data=i),o!==void 0&&(this.retryAfter=o)}};function ne(e){return e[ee]=!0,e}function Ue(e){return typeof e=="object"&&e!==null&&e[ee]===!0}function g(e){let n=e.replace(/([a-z0-9])([A-Z])/g,"$1 $2");return n.charAt(0).toUpperCase()+n.slice(1).toLowerCase()}var y=class extends f{constructor(n,t){super(400,"bad_request",t??g("BadRequest"),n),this.name="BadRequest"}},H=class extends f{constructor(n,t,r){super(404,t??"not_found",n??g("NotFound"),r),this.name="NotFound"}},p=class extends f{constructor(n,t,r){super(409,t??"conflict",n??g("Conflict"),r),this.name="Conflict"}},X=class extends p{constraint;sqlstate=d.uniqueViolation;static is(n){return typeof n=="object"&&n!==null&&n.name==="UniqueViolation"&&typeof n.constraint=="string"}constructor(n,t,r,i){super(t??"Unique constraint violated",r??"unique_violation",i),this.name="UniqueViolation",this.constraint=n}};function Ve(e){if(typeof e!="object"||e===null||e.retryable!==!0)return!1;let n=e.sqlstate;return n===d.serializationFailure||n===d.deadlockDetected}var J=class extends p{retryable=!0;sqlstate;static is(n){return typeof n=="object"&&n!==null&&n.name==="SerializationFailure"}constructor(n=d.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}},Q=class extends p{retryable=!0;sqlstate;static is(n){return typeof n=="object"&&n!==null&&n.name==="DeadlockDetected"}constructor(n=d.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}},Y=class extends Error{sqlstate=d.inFailedTransaction;static is(n){return typeof n=="object"&&n!==null&&n.name==="TransactionAborted"}constructor(n,t){super(n,{cause:t}),this.name="TransactionAborted"}},Z=class extends f{constructor(n,t){super(429,"too_many_requests",t??g("TooManyRequests"),n,n.retryAfter),this.name="TooManyRequests"}};function te(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 $e=new Set(["57P03","53300","08001","08004","ERR_POSTGRES_CONNECTION_REFUSED","ERR_POSTGRES_CONNECTION_FAILED","ERR_POSTGRES_CONNECTION_TIMEOUT","ECONNREFUSED","CONNECT_TIMEOUT"]),Ee=new Set(["57P01","57P02","08000","08003","08006","08007","08P01","ERR_POSTGRES_CONNECTION_CLOSED","CONNECTION_CLOSED","CONNECTION_DESTROYED","ECONNRESET","ETIMEDOUT","EPIPE"]);function Fe(e){return e instanceof Error&&e.code===void 0&&e.message==="connection must be a PostgresSQLConnection"}function Ke(e){let n=e;for(let t=0;t<4&&typeof n=="object"&&n!==null;t++){let r=te(n),i=n.code,o=s=>r!==void 0&&s.has(r)||typeof i=="string"&&s.has(i);if(o(Ee))return"lost";if(o($e))return"never";n=n.cause}}function ze(e){let n=e;for(let t=0;t<4&&typeof n=="object"&&n!==null;t++){let r=n.sqlstate,i=te(n)??(typeof r=="string"?r:void 0);if(i!==void 0)return!i.startsWith("08")&&!/^57P0[123]$/.test(i);n=n.cause}return!1}function Ge(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 Oe=Symbol.for("palbase.data"),Se=globalThis,x=Se[Oe]??=new WeakSet;function re(e){return e instanceof Date||ArrayBuffer.isView(e)||e instanceof ArrayBuffer}function oe(e){let n=[e];for(;n.length>0;){let t=n.pop();if(!(typeof t!="object"||t===null||x.has(t)||re(t))){x.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&&x.has(e)}function Pe(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&&oe(t);return e}function h(e,n){return m(e)&&x.add(n),n}function Ye(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 ne(new y({fields:[{field:n,message:r}]},`${n} ${r}`))}var I=Symbol.for("palbase.db.ref"),ue=Symbol.for("palbase.tx.expr");function b(e,n){return Object.defineProperty(e,I,{value:n,enumerable:!1}),e}function w(e){if(!(typeof e!="object"||e===null))return Object.hasOwn(e,I)?e[I]:void 0}function R(e){return w(e)==="col"&&typeof e.$col=="string"}function l(e){if(w(e)!=="sql")return!1;let n=e.$sql;return n!==void 0&&Array.isArray(n.text)&&Array.isArray(n.values)}function nn(e){if(w(e)!=="ref")return!1;let n=e.$ref;return n!==void 0&&typeof n.op=="number"&&typeof n.field=="string"}function tn(e){if(w(e)!=="expr")return!1;let n=e.$expr;return n!==void 0&&(n.fn==="inc"||n.fn==="dec"||n.fn==="now")}function rn(e){if(typeof e!="object"||e===null||w(e)!==void 0)return!1;let n=e.$ref;return n!==void 0&&typeof n=="object"&&n!==null}function on(e){if(typeof e!="object"||e===null||w(e)!==void 0||_(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 _(e){if(typeof e!="object"&&typeof e!="function"||e===null)return!1;try{return e[ue]!==void 0}catch{return!1}}function k(e){if(!_(e))return!1;try{let n=e[ue];return typeof n=="object"&&n!==null&&n.fn==="now"}catch{return!1}}function sn(e,n,t,r){for(let i of t){let o=r[i];if(k(o))throw new Error(`${e}(${n}): "${i}" 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: { ${i}: now() } }) or, in $transaction, tx.public.${n}.updateWhere(where, { ${i}: now() }).`);if(_(o))throw new Error(`${e}(${n}): "${i}" got an expression handle (increment()/decrement()) where a value is expected. To add to a counter use updateMany({ where, set: { ${i}: increment(n) } }) or, in $transaction, tx.public.${n}.updateWhere(where, { ${i}: increment(n) }).`);if(R(o))throw new Error(`${e}(${n}): "${i}" got a col(). A column reference stands only in a filter; to write one column's value into another, use $query.`)}}var Ae=new Set(["gt","gte","lt","lte","neq","in","contains","icontains","startsWith","endsWith","isNull","overlaps"]),ie={eq:'equality is written bare: { <column>: <value> } (or { <column>: col("\u2026") } to compare with a column)'};function se(e,n,t){if(t&&!l(t))for(let[r,i]of Object.entries(t)){if(r==="OR"||r==="AND"||r==="NOT"){let s=r==="NOT"?[i]:i;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`);se(e,n,a)}continue}if(r==="has"){if(i===null||typeof i!="object"||Array.isArray(i))throw new Error(`${e}(${n}): where.has must be a map of relations ({ <relation>: { \u2026 } })`);for(let[s,a]of Object.entries(i)){if(a===null||typeof a!="object"||Array.isArray(a))throw new Error(`${e}(${n}): where.has.${s} must be a filter object`);se(e,n,a)}continue}if(i===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(i===null||typeof i!="object"||Array.isArray(i)||R(i)||k(i))continue;let o=Object.entries(i);if(o.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 o){if(s==="in"){if(!Array.isArray(a))throw new Error(`${e}(${n}): where.${r}.in must be an array`);if(a.some(c=>c===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(ie[s]!==void 0)throw new Error(`${e}(${n}): where.${r}.${s} is not in this filter language \u2014 ${ie[s]}`);if(!Ae.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 Ne=["days","hours","minutes","seconds"],je=2147483647,ae=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 B(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(!Ne.includes(t))return{refused:`${ae(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>je)return{refused:`${t} is a whole number, 0 or more, got ${ae(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 an(e,n,t,r){for(let i of t)if(r[i]===void 0)throw new Error(`${e}(${n}): "${i}" 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 le(e,n){let r=(n!==null&&typeof n=="object"?Object.keys(n):[]).filter(o=>o!=="id");if(r.length>0)throw new Error(`update(${e}): where takes the row's id alone, not ${r.map(o=>`"${o}"`).join(", ")} \u2014 a condition beside the id would be dropped. To update the rows a filter matches, updateMany({ where, set }).`);let i=n?.id;if(typeof i!="string"&&typeof i!="number"&&typeof i!="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(i)}var P=class extends Error{constructor(n){super(n),this.name="TxRefError"}},u=class extends Error{constructor(n){super(n),this.name="TxPlanError"}},$=Symbol.for("palbase.tx.expr"),E=Symbol.for("palbase.tx.ref"),O=Symbol.for("palbase.tx.row"),pe=Symbol.for("palbase.tx.rows"),V=["then","valueOf","toString","toJSON",Symbol.toPrimitive];function F(e,n,t){let r=typeof e=="symbol"?e.description??String(e):e;throw new P(`${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 dn(){return W({fn:"now"})}function fn(e){let n=B(e);if("refused"in n)throw new u(`ago() ${n.refused}`);return W(Object.freeze({fn:"now",minus:n.span}))}function he(e,n){if(e.fn!=="now"||e.minus===void 0)return;let t=B(e.minus);if("refused"in t)throw new u(`\`${n}\`: ago() ${t.refused}`)}function wn(e){return ye(e,"increment"),W({fn:"inc",by:e})}function pn(e){return ye(e,"decrement"),W({fn:"dec",by:e})}function ye(e,n){if(typeof e=="string"){if(!/^-?\d+(\.\d+)?$/.test(e))throw new u(`${n}() takes a decimal number as text, got "${e}" \u2014 "12", "12.50"`)}else if(typeof e!="number"||!Number.isFinite(e))throw new u(`${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 u(`${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 hn(e){return C(e)}function W(e){return new Proxy({[$]:e},{get(n,t){if(t===$)return n[$];V.includes(t)&&F(t,"A plan expression","Write it into an operation instead.")}})}function We(e,n){let t={[E]:{op:e,field:n}};return new Proxy(t,{get(r,i){if(i===E)return r[E];V.includes(i)&&F(i,`\`${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 De(e){let n={[O]:e};return new Proxy(n,{get(t,r){if(r===O)return t[O];if(V.includes(r)&&F(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 We(e,r)}})}function D(e){if(typeof e!="object"||e===null)return null;let n=e[E];return typeof n=="object"&&n!==null&&typeof n.op=="number"&&typeof n.field=="string"?n:null}function v(e){if(typeof e!="object"||e===null)return null;let n=e[O];return typeof n=="number"?n:null}function C(e){if(typeof e!="object"||e===null)return null;let n=e[$];return typeof n=="object"&&n!==null?n:null}function M(e){return typeof e=="object"&&e!==null&&e[pe]!==void 0}function ve(e,n,t){let r=D(e);if(r)return b({$ref:{op:r.op,field:r.field}},"ref");let i=C(e);if(i){if(i.fn!=="now"&&!t)throw new u(`\`${n}\`: ${i.fn}() reads the column's current value, so it is only valid in updateWhere(where, set).`);return he(i,n),b({$expr:i},"expr")}if(v(e)!==null)throw new u(`\`${n}\`: a row handle is not a value. Read the column you meant (e.g. \`row.id\`).`);if(M(e))throw new u(`\`${n}\`: an operation result is not a value. Declare an expectation first (\`.expectOne(err)\`) and read a column from the row.`);return ge(e,n),e}function U(e,n){let t=D(e);if(t)return b({$ref:{op:t.op,field:t.field}},"ref");let r=C(e);if(r&&r.fn!=="now")throw new u(`\`${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(k(e))return r&&he(r,n),e;if(v(e)!==null)throw new u(`\`${n}\`: a row handle is not a value. Read the column you meant (e.g. \`row.id\`).`);if(M(e))throw new u(`\`${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 h(e,e.map(i=>U(i,n)));if(e!==null&&typeof e=="object"&&!(e instanceof Date)&&!R(e)&&!l(e)){let i=h(e,{});for(let[o,s]of Object.entries(e))i[o]=U(s,n);return i}return e}function L(e){if(l(e))return e;let n=h(e,{});for(let t of Object.keys(e).sort()){let r=e[t];if(r===void 0)throw new u(`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]=U(r,t)}return n}function ge(e,n){if(!(typeof e!="object"||e===null||e instanceof Date)){if(D(e)||C(e)||v(e)!==null||M(e))throw new u(`\`${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))ge(t,n)}}function T(e,n){let t={};for(let r of Object.keys(e).sort()){let i=e[r];if(i===void 0)throw new u(`${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]=ve(i,r,n)}return t}var S=-1,A=class{[pe]=!0;guarded=!1;builder;opIndex;what;constructor(n,t,r){this.builder=n,this.opIndex=t,this.what=r}then(){throw new P(`${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===S)throw n;return De(this.opIndex)}expectNone(n){this.declareGuard("none",0,n)}expectAtLeast(n,t){if(ce(n,"expectAtLeast"),this.declareGuard("atLeast",n,t),this.opIndex===S&&n>0)throw t}expectAtMost(n,t){ce(n,"expectAtMost"),this.declareGuard("atMost",n,t)}declareGuard(n,t,r){if(!(r instanceof Error))throw new u(`${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 u(`${this.what} already has an expectation. One operation carries one expectation; declare the second on its own operation.`);this.guarded=!0,this.opIndex!==S&&this.builder.attachGuard(this.opIndex,n,t,r)}};function ce(e,n){if(!Number.isInteger(e)||e<0)throw new u(`${n}(n) needs a non-negative integer, got ${String(e)}`)}var de=1e3,fe=5e3,N=class{ops=[];slots=[];table(n){return{insert:t=>{let r=T(t,!1);if(Object.keys(r).length===0)throw new u(`${n}.insert() needs at least one column`);return this.push({op:"insert",table:n,values:r},`${n}.insert()`)},put:(t,r)=>{let i=T(t,!1);if(Object.keys(i).length===0)throw new u(`${n}.put() needs at least one column`);if(r.onConflict.length===0)throw new u(`${n}.put() needs at least one onConflict column`);return this.push({op:"upsert",table:n,values:i,onConflict:r.onConflict},`${n}.put()`)},insertMany:(t,r)=>{if(t.length===0)return new A(this,S,`${n}.insertMany()`);if(t.length>fe)throw new u(`${n}.insertMany() has ${t.length} rows; the limit is ${fe}. Split the write.`);let i=t.map(o=>T(o,!1));return qe(i,n),this.push({op:"insertMany",table:n,rows:i,...Me(r,n)},`${n}.insertMany()`)},updateWhere:(t,r)=>{let i=L(t),o=T(r,!0);if(Object.keys(i).length===0&&!l(i))throw new u(`${n}.updateWhere() needs a filter. An update with no filter rewrites the whole table.`);if(Object.keys(o).length===0)throw new u(`${n}.updateWhere() needs at least one column to set`);return this.push({op:"update",table:n,set:o,where:i},`${n}.updateWhere()`)},deleteWhere:t=>{let r=L(t);if(Object.keys(r).length===0&&!l(r))throw new u(`${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 i={op:"select",table:n},o=L(t??{});if((Object.keys(o).length>0||l(o))&&(i.where=o),r?.limit!==void 0){if(!Number.isInteger(r.limit)||r.limit<0)throw new u(`${n}.select(): limit needs a non-negative integer, got ${String(r.limit)}`);i.limit=r.limit}return r?.lock!==void 0&&(i.lock=r.lock),this.push(i,`${n}.select()`)}}}push(n,t){if(this.ops.length>=de)throw new u(`this transaction has ${de} operations, the limit. Use insertMany() for bulk writes, or split the work.`);let r=this.ops.length;return this.ops.push(n),new A(this,r,t)}attachGuard(n,t,r,i){let o=this.ops[n];if(!o)throw new u(`internal: expectation on unknown operation ${n}`);let s=this.slots.length;this.slots.push(i),o.guard={kind:t,n:r,slot:s}}body(){return{ops:this.ops}}errorForSlot(n){return this.slots[n]??null}},Ce=e=>typeof e=="string"?JSON.stringify(e.slice(0,40)):typeof e;function Me(e,n){if(e===void 0)return{};if(e.action!==void 0&&e.action!=="ignore"&&e.action!=="update")throw new u(`${n}.insertMany(): a conflict's action is "ignore" or "update", not ${Ce(e.action)}.`);if(e.onConflict===void 0){if(e.action!=="ignore")throw new u(`${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 u(`${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 qe(e,n){let t=e[0];if(!t)return;let r=Object.keys(t),i=r.join(",");for(let o=1;o<e.length;o++){let s=Object.keys(e[o]);if(s.join(",")!==i)throw new u(`${n}.insertMany(): every row must set the same columns. Row 0 sets [${r.join(", ")}] but row ${o} sets [${s.join(", ")}]. (A property set to \`undefined\` counts as absent \u2014 use \`null\`.)`)}}function j(e,n){let t=D(e);if(t){let i=we(n,t.op,`\`${t.field}\``);if(!(t.field in i))throw new u(`the transaction's operation ${t.op} returned no column \`${t.field}\`.`);return i[t.field]}let r=v(e);if(r!==null)return we(n,r,"a row");if(M(e))throw new u("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(i=>j(i,n));if(Ie(e)){let i={};for(let[o,s]of Object.entries(e))i[o]=j(s,n);return i}return e}function we(e,n,t){let r=e[n];if(!r)throw new u(`the transaction returned no result for operation ${n}, so ${t} cannot be read.`);let i=r.rows[0];if(!i)throw new u(`the transaction's operation ${n} returned no row, so ${t} cannot be read.`);return i}function Ie(e){if(typeof e!="object"||e===null)return!1;let n=Object.getPrototypeOf(e);return n===Object.prototype||n===null}async function xe(e,n,t,r){let i=r(n),o=t.body();if(o.ops.length===0)return j(i,[]);let s;try{s=await e.txPlan(o)}catch(a){throw _e(a,t)}return j(i,s.results)}function _e(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 Be}from"node:async_hooks";function me(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 gn(e){if(me(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 be(e){if(me(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 xn(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 Re(e,n){return new Proxy({},{get(t,r){if(typeof r!="string")return;let i=`${n}${r}`;return{insert:o=>e().insert(i,o),insertMany:(o,s)=>e().insertMany(i,o,s),aggregate:o=>e().aggregate(i,o),update:o=>e().update(i,le(i,o.where),o.set),delete:o=>e().delete(i,o),findById:o=>e().findById(i,o),findUnique:o=>e().findUnique(i,o.where,{select:o.select,with:o.with,lock:o.lock}),page:o=>{let{where:s,...a}=o??{};return e().page(i,s,a)},findMany:o=>{let{where:s,...a}=o??{};return e().findMany(i,s,a)},put:o=>e().put(i,o.data,{onConflict:o.onConflict}),updateMany:o=>e().updateMany(i,o.where,o.set,o.returning===void 0?void 0:{returning:o.returning}),deleteMany:o=>e().deleteMany(i,o.where),count:o=>e().count(i,o?.where),claim:(o,s)=>e().claim(i,o,s),search:(o,s)=>e().search(i,o,s)}}})}function ke(e,n=""){return new Proxy({},{get(t,r){if(typeof r=="string")return e.table(n+r)}})}function Le(e){let n=ke(e);return new Proxy({},{get(t,r){if(typeof r=="string")return r==="tables"||r==="public"?n:ke(e,q(r,""))}})}function G(e,n,t={}){let i=Object.assign({$query:(o,s)=>e().query(o,s),$diagnostics:()=>e().diagnostics(),$insert:(o,s)=>e().insert(o,s),$insertMany:((o,s,a)=>e().insertMany(o,s,a)),$update:(o,s,a)=>e().update(o,s,a),$delete:(o,s)=>e().delete(o,s),$findById:(o,s)=>e().findById(o,s),$findUnique:(o,s,a)=>e().findUnique(o,s,a),$page:(o,s,a)=>e().page(o,s,a),$findMany:(o,s,a)=>e().findMany(o,s,a),$put:(o,s,a)=>e().put(o,s,a),$updateMany:(o,s,a,c)=>e().updateMany(o,s,a,c),$deleteMany:(o,s)=>e().deleteMany(o,s),$count:(o,s)=>e().count(o,s),$search:(o,s,a)=>e().search(o,s,a),$aggregate:(o,s)=>e().aggregate(o,s),$claim:(o,s,a)=>e().claim(o,s,a),$lockRows:(o,s)=>e().lockRows(o,s),$lockRowsWhere:(o,s,a)=>e().lockRowsWhere(o,s,a),$advisoryXactLock:o=>e().advisoryXactLock(o)},t,{$atomic(o,s){let a=e();if(typeof a.atomic!="function")throw new Error("Database.$atomic owns one transaction and identity; nested roots and $asService are not allowed");return a.atomic(c=>n(c,()=>o(G(()=>c,n))),s)},$attempt:o=>e().attempt(o),$transaction(o,s){be(s);let a=new N;return xe(e(),Le(a),a,o)}});return new Proxy(i,{get(o,s,a){return s==="tables"?Re(e,""):typeof s=="string"&&!s.startsWith("$")&&!(s in o)?Re(e,q(s,"")):Reflect.get(o,s,a)}})}var K=new Be,z=()=>{throw new Error("Database.$atomic owns one transaction and identity; nested roots and $asService are not allowed")};function En(e){let n={},t=()=>{let s=K.getStore();return s?.owner===n?s.tx:e},r=(s,a)=>K.run({owner:n,tx:Object.assign(Object.create(null),s,{atomic:z,asService:z})},a),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")}}),o=(s,a)=>K.run({owner:n,tx:i},a);return G(t,r,{$asService(){let s=t();if(typeof s.asService!="function")return z();let a=s.asService();return G(()=>a,o)}})}export{Te as a,ee as b,d as c,f as d,ne as e,Ue as f,y as g,H as h,p as i,X as j,Ve as k,J as l,Q as m,Y as n,Z as o,te as p,$e as q,Ee as r,Fe as s,Ke as t,ze as u,Ge as v,re as w,oe as x,m as y,Pe as z,h as A,Ye as B,b as C,R as D,l as E,nn as F,tn as G,rn as H,on as I,_ as J,k as K,sn as L,se as M,B as N,an as O,le as P,P as Q,u as R,dn as S,fn as T,wn as U,pn as V,hn as W,N as X,xe as Y,me as Z,gn as _,xn as $,En as aa};
package/dist/dsl.js CHANGED
@@ -1,2 +1,2 @@
1
- /*! palgres 0.9.1 — 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/Q2INGKOB.js";import{m as n,n as i,o as f,p as a,q as l,r as p,s as u,t as m,u as s,v as y,w as c,x as d,y as x,z as D}from"./chunks/CBPYINOK.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.10.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/AVV3KCH6.js";import{m as n,n as i,o as f,p as a,q as l,r as p,s as u,t as m,u as s,v as y,w as c,x as d,y as x,z as D}from"./chunks/FTBMJL4C.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.9.1 — Palbase SDK License (see LICENSE) */
2
- import{a as ws,b as ys,c as Ge,l as kn,m as Ln}from"./chunks/Q2INGKOB.js";import{$ as Is,A as an,B as Y,C as wt,D as xe,E as ln,F as yt,G as $s,H as Ss,I as Rs,J as In,K as Tt,L as bs,M as Ns,N as As,O as xn,P as Os,Q as No,R as Ao,S as Oo,T as ko,U as Lo,V as Io,W as vn,X as ks,Y as Ls,Z as Cn,_ as _n,a as yo,aa as xs,b as To,c as ne,d as oe,e as Ne,f as $o,g as Ae,h as gt,i as So,j as Ke,k as He,l as ht,m as Et,n as Ve,o as Me,p as ae,q as gs,r as hs,s as Es,t as ue,u as On,v as on,w as Ts,x as Ro,y as bo,z as Xe}from"./chunks/XPAEKET5.js";import{a as je,b as De,c as pt,d as D,e as be,f as rn,g as ms,h as ps,i as ft,j as ge,k as fs,l as Pe,o as he}from"./chunks/CBPYINOK.js";import{createHash as Co}from"node:crypto";import{createHash as Rt}from"node:crypto";var b=t=>`"${t.replace(/"/g,'""')}"`,P=(t,e)=>`${b(t)}.${b(e)}`,M=t=>`'${t.replace(/'/g,"''")}'`;function de(t){if(t.includes("\0"))throw new TypeError("a NUL character cannot be sent to Postgres");return`E'${t.replace(/\\/g,"\\\\").replace(/'/g,"''")}'`}var ye=t=>t.map(b).join(", "),xo=new Set(["now","current_timestamp","current_date","current_time","localtimestamp","localtime","transaction_timestamp","statement_timestamp"]);function vs(t){return[...$t(t)].some(e=>e.call&&!xo.has(e.name.toLowerCase()))}function*$t(t){let e=0;for(;e<t.length;){let n=t[e];if(n==="'"){for(e++;e<t.length;)if(t[e]==="'"&&t[e+1]==="'")e+=2;else{if(t[e]==="'")break;e++}e++;continue}if(n==="$"){let s=/^\$[A-Za-z_]*\$/.exec(t.slice(e));if(s){let r=t.indexOf(s[0],e+s[0].length);e=r<0?t.length:r+s[0].length;continue}}if(n==='"'){let s=e+1,r="";for(;s<t.length;)if(t[s]==='"'&&t[s+1]==='"')r+='"',s+=2;else{if(t[s]==='"')break;r+=t[s++]}let o=s+1;yield{start:e,end:o,name:r,quoted:!0,call:/^\s*\(/.test(t.slice(o))},e=o;continue}if(/[A-Za-z_]/.test(n)&&(e===0||!/[A-Za-z0-9_$]/.test(t[e-1]))){let s=/^[A-Za-z_][A-Za-z0-9_$]*/.exec(t.slice(e)),r=e+s[0].length;yield{start:e,end:r,name:s[0],quoted:!1,call:/^\s*\(/.test(t.slice(r))},e=r;continue}e++}}function Oe(t,e){for(let n of $t(t))if(!n.call&&(n.quoted?n.name===e:n.name.toLowerCase()===e.toLowerCase()))return!0;return!1}function ke(t,e){if(e.size===0)return t;let n="",s=0;for(let r of $t(t)){if(r.call)continue;let o=e.get(r.quoted?r.name:vo(e,r.name)??"");o!==void 0&&(n+=t.slice(s,r.start)+b(o),s=r.end)}return n+t.slice(s)}function vo(t,e){if(t.has(e))return e;let n=e.toLowerCase();for(let s of t.keys())if(s.toLowerCase()===n)return s}var Dn=t=>`(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.10.0 — Palbase SDK License (see LICENSE) */
2
+ import{a as ws,b as ys,c as Ge,l as kn,m as Ln}from"./chunks/AVV3KCH6.js";import{$ as Is,A as an,B as Y,C as wt,D as xe,E as ln,F as yt,G as $s,H as Ss,I as Rs,J as In,K as Tt,L as bs,M as Ns,N as As,O as xn,P as Os,Q as No,R as Ao,S as Oo,T as ko,U as Lo,V as Io,W as vn,X as ks,Y as Ls,Z as Cn,_ as _n,a as yo,aa as xs,b as To,c as ne,d as oe,e as Ne,f as $o,g as Ae,h as gt,i as So,j as Ke,k as He,l as ht,m as Et,n as Ve,o as Me,p as ae,q as gs,r as hs,s as Es,t as ue,u as On,v as on,w as Ts,x as Ro,y as bo,z as Xe}from"./chunks/IOL277J3.js";import{a as je,b as De,c as pt,d as D,e as be,f as rn,g as ms,h as ps,i as ft,j as ge,k as fs,l as Pe,o as he}from"./chunks/FTBMJL4C.js";import{createHash as Co}from"node:crypto";import{createHash as Rt}from"node:crypto";var b=t=>`"${t.replace(/"/g,'""')}"`,P=(t,e)=>`${b(t)}.${b(e)}`,M=t=>`'${t.replace(/'/g,"''")}'`;function de(t){if(t.includes("\0"))throw new TypeError("a NUL character cannot be sent to Postgres");return`E'${t.replace(/\\/g,"\\\\").replace(/'/g,"''")}'`}var ye=t=>t.map(b).join(", "),xo=new Set(["now","current_timestamp","current_date","current_time","localtimestamp","localtime","transaction_timestamp","statement_timestamp"]);function vs(t){return[...$t(t)].some(e=>e.call&&!xo.has(e.name.toLowerCase()))}function*$t(t){let e=0;for(;e<t.length;){let n=t[e];if(n==="'"){for(e++;e<t.length;)if(t[e]==="'"&&t[e+1]==="'")e+=2;else{if(t[e]==="'")break;e++}e++;continue}if(n==="$"){let s=/^\$[A-Za-z_]*\$/.exec(t.slice(e));if(s){let r=t.indexOf(s[0],e+s[0].length);e=r<0?t.length:r+s[0].length;continue}}if(n==='"'){let s=e+1,r="";for(;s<t.length;)if(t[s]==='"'&&t[s+1]==='"')r+='"',s+=2;else{if(t[s]==='"')break;r+=t[s++]}let o=s+1;yield{start:e,end:o,name:r,quoted:!0,call:/^\s*\(/.test(t.slice(o))},e=o;continue}if(/[A-Za-z_]/.test(n)&&(e===0||!/[A-Za-z0-9_$]/.test(t[e-1]))){let s=/^[A-Za-z_][A-Za-z0-9_$]*/.exec(t.slice(e)),r=e+s[0].length;yield{start:e,end:r,name:s[0],quoted:!1,call:/^\s*\(/.test(t.slice(r))},e=r;continue}e++}}function Oe(t,e){for(let n of $t(t))if(!n.call&&(n.quoted?n.name===e:n.name.toLowerCase()===e.toLowerCase()))return!0;return!1}function ke(t,e){if(e.size===0)return t;let n="",s=0;for(let r of $t(t)){if(r.call)continue;let o=e.get(r.quoted?r.name:vo(e,r.name)??"");o!==void 0&&(n+=t.slice(s,r.start)+b(o),s=r.end)}return n+t.slice(s)}function vo(t,e){if(t.has(e))return e;let n=e.toLowerCase();for(let s of t.keys())if(s.toLowerCase()===n)return s}var Dn=t=>`(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 ${t}.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 J="palgres_search",Pn=(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]),Cs=48;function ve(t,e){let n=t.replaceAll(".","__");return`${n.length<=Cs?n:`${n.slice(0,32)}_${Rt("md5").update(n).digest("hex").slice(0,12)}`}__g${e}`}var _s=t=>({insert:`_palgres_search_g${t}_ins`,update:`_palgres_search_g${t}_upd`});function Mn(t,e){let n=Rt("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_${Rt("sha256").update(`${t.schema}.${t.name}`).digest("hex").slice(0,16)}_${n}`}function qn(t,e){let n=e===void 0?"":`${b(e)}.`;return t.map(s=>`coalesce(${n}${b(s)}::text, '')`).join(" || ' ' || ")}var Fn=(t,e)=>`to_tsvector('simple', ${qn(t,e)})`;function cn(t,e){let n=t>ms?"halfvec":"vector",s={cosine:["cosine","<=>"],euclidean:["l2","<->"],inner_product:["ip","<#>"]}[e];return{type:n,opclass:`${n}_${s[0]}_ops`,operator:s[1]}}function Ds(t){let e=`${t.table.schema}.${t.table.name}`,n=P(t.table.schema,t.table.name),s=ve(e,t.gen),r=P(J,s),o=cn(t.search.dimensions,t.search.metric),a=b(t.pk.name),i=[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 (${M(e)}, ${t.gen}, ${M(t.search.model)}, ${t.search.dimensions}, ${M(t.search.metric)}, ARRAY[${t.search.from.map(M).join(", ")}]::text[], ${M(t.status)}, ${t.status==="active"?"now()":"NULL"})`,`CREATE TABLE ${r} (
5
5
  id ${t.pk.type} PRIMARY KEY REFERENCES ${n} (${a}) ON DELETE CASCADE,
@@ -265,7 +265,7 @@ END $palgres$`,mn=class extends Error{constructor(e,n){super(`palgres: ${e} was
265
265
  END LOOP; END $palgres$`,`INSERT INTO palgres.versions (n, digest, schema, layout, state, direct, ready_at) VALUES (1, ${M(g)}, ${M(JSON.stringify(i.schema))}::jsonb, ${M(JSON.stringify(l))}::jsonb, 'active', true, now())`]),this.log(`palgres: takes the database over as version 1 (${i.schema.tables.length} table(s))${i.unforce.length>0?`; FORCE row-level security off on ${i.unforce.join(", ")}`:""}${i.unmanaged.length>0?`
266
266
  left as it is:
267
267
  ${i.unmanaged.join(`
268
- `)}`:""}`)};return{version:{n:1,digest:g,state:"active",schema:i.schema},adoption:{unforced:i.unforce,unmanaged:i.unmanaged},layout:l,record:p}}async made(e,n,s,r){let o=`palgres_shadow_${Ko(6).toString("hex")}`;await e.query(`CREATE DATABASE ${b(o)}`);try{let a=this.shadow(o);try{await new t(a,{roles:this.roles,lockTimeoutMs:this.lockTimeoutMs}).start(n);let i=await Yn(a,s,this.roles);return await Yo(a,r,i),i}finally{await a.end()}}finally{await e.query(`DROP DATABASE IF EXISTS ${b(o)} WITH (FORCE)`)}}async planFrom(e,n,s){let r=new Set;for(let f of n?.schema.tables??[])(await e.query(`SELECT EXISTS (SELECT 1 FROM ${P(f.schema,f.name)}) AS any`))[0].any&&r.add(D(f));let o=new Map,a=[],i=(f,d)=>{let T=`${f}\0${d}`;return o.has(T)||(o.set(T,void 0),a.push([f,d])),o.get(T)},l=(await e.query("SELECT to_regclass('palgres.versions') IS NOT NULL AS there"))[0]?.there===!0?Number((await e.query("SELECT coalesce(max(n), 0) AS n FROM palgres.versions"))[0].n):0,u=Math.max(l,n?.n??0)+1,g=new Map,p=f=>(g.has(f)||g.set(f,void 0),g.get(f)),h=new Map;if((await e.query(`SELECT to_regclass('${J}.generations') IS NOT NULL AS there`))[0]?.there===!0)for(let f of await e.query(`SELECT table_key, gen, model, dimensions, metric, from_columns, status FROM ${J}.generations ORDER BY table_key, gen`)){let d=String(f.table_key);h.has(d)||h.set(d,[]),h.get(d).push({gen:Number(f.gen),model:String(f.model),dimensions:Number(f.dimensions),metric:f.metric,from:f.from_columns.map(String),status:f.status})}let m=(await e.query("SELECT n.nspname AS schema FROM pg_catalog.pg_extension e JOIN pg_catalog.pg_namespace n ON n.oid = e.extnamespace WHERE e.extname = 'vector'"))[0]?.schema,y=()=>Lt({from:n&&{n:n.n,schema:n.schema},next:u,to:s,hasRows:f=>r.has(f),castable:i,checkedDomain:p,roles:this.roles,generations:f=>h.get(f)??[],vectorSchema:typeof m=="string"?m:"public"}),S=y();if(a.length===0&&g.size===0)return S;for(let[f,d]of a)o.set(`${f}\0${d}`,await this.casts(e,f,d));for(let f of g.keys())g.set(f,await this.checkedDomain(e,f));return y()}async checkedDomain(e,n){let s=await e.query(`SELECT t.typtype = 'd' AND (t.typnotnull OR EXISTS (SELECT 1 FROM pg_catalog.pg_constraint c WHERE c.contypid = t.oid)) AS checked FROM pg_catalog.pg_type t WHERE t.oid = pg_catalog.to_regtype(${M(n)})`);return s.length===0?void 0:s[0].checked===!0}async casts(e,n,s){try{return await e.query(`SELECT CAST(NULL::${n} AS ${s})`),!0}catch(r){let o=ae(r);if(o==="42846")return!1;if(o==="42704")return;throw r}}async active(e){if(e.ledger===!1)return null;let n=await e.query("SELECT n, digest, schema FROM palgres.versions WHERE state = 'active' ORDER BY n DESC LIMIT 1"),s=await this.open(e),o=(s?await e.query(`SELECT n, digest, schema FROM palgres.versions WHERE n = ${s.from_n??-1}`):n)[0];return o?{n:Number(o.n),digest:String(o.digest),state:"active",schema:_t(o.schema)}:null}async version(e,n){if(e.ledger===!1)return null;let s=await e.query(`SELECT n, digest, state FROM palgres.versions WHERE n = ${n}`);return s[0]?{n,digest:String(s[0].digest),state:s[0].state}:null}async open(e){if(e.ledger===!1)return null;let s=(await e.query("SELECT from_n, to_n, plan, done, phase, to_jsonb(m) ->> 'opened_by' AS opened_by FROM palgres.migration m"))[0];return s?{from_n:s.from_n===null?null:Number(s.from_n),to_n:Number(s.to_n),plan:Xo(_t(s.plan),Number(s.to_n)),done:_t(s.done),phase:s.phase,opened_by:typeof s.opened_by=="string"?s.opened_by:null}:null}async session(e,n=!0,s){let r=await this.pool.reserve(),o={query:async a=>await r.unsafe(a)};try{if(await o.query("SET application_name = 'palgres:migrate'"),await o.query("SET search_path = public, pg_temp"),n){await o.query(`SELECT pg_advisory_lock(hashtextextended(${M(nr)}, 0))`);let a=(await o.query(`SELECT to_regclass('palgres.versions') IS NOT NULL AS there, (SELECT pg_catalog.obj_description(n.oid, 'pg_namespace') FROM pg_catalog.pg_namespace n WHERE n.nspname = '${J}') AS search`))[0];o.ledger=a.there===!0,o.searchLedger=typeof a.search=="string"?a.search:null,o.ledger&&await this.ensure(o)}else if((await o.query("SELECT to_regclass('palgres.migration') IS NULL AS none"))[0].none)return await(s?s(o):e(Go));return await e(o)}finally{n&&await o.query(`SELECT pg_advisory_unlock(hashtextextended(${M(nr)}, 0))`).catch(()=>{}),r.release()}}async ownAuth(e){let n=await this.authRefusals(e);if(n.length>0)throw new $e(n)}async authRefusals(e){let n={jwt:["SELECT coalesce(nullif(current_setting('request.jwt.claims', true), '')::jsonb, '{}'::jsonb)","SELECT coalesce(nullif(current_setting('request.jwt.claims', true),'')::jsonb, '{}'::jsonb)"],uid:["SELECT nullif(auth.jwt() ->> 'sub', '')","SELECT current_setting('request.jwt.claims', true)::jsonb ->> 'sub'","SELECT nullif(current_setting('request.jwt.claims', true)::jsonb ->> 'sub','')::text"],role:["SELECT nullif(auth.jwt() ->> 'role', '')","SELECT nullif(current_setting('request.jwt.claims', true)::jsonb ->> 'role','')::text"]},s=a=>a.replace(/\s+/g," ").trim();return(await e.query("SELECT p.proname AS name, p.prosrc AS src, pg_catalog.format_type(p.prorettype, NULL) AS returns FROM pg_catalog.pg_proc p JOIN pg_catalog.pg_namespace n ON n.oid = p.pronamespace WHERE n.nspname = 'auth' AND p.proname IN ('jwt', 'uid', 'role') AND p.pronargs = 0")).filter(a=>!(n[String(a.name)]??[]).some(i=>s(i)===s(String(a.src)))).map(a=>`auth.${a.name}() is the database's own (returns ${a.returns}: ${s(String(a.src)).slice(0,120)}): Palgres makes it read the request's claims (request.jwt.claims), and the app there now would read its caller otherwise \u2014 rename yours, or make it read the claims as Palgres does, before the take-over`)}async ensure(e){let n=[this.roles.anon,this.roles.authenticated,this.roles.service],s=await e.query(`SELECT r FROM unnest(ARRAY[${n.map(M).join(", ")}]) AS r WHERE NOT EXISTS (SELECT 1 FROM pg_roles WHERE rolname = r)`);if(s.length>0)throw new Error(`palgres: the database has no role ${s.map(o=>o.r).join(", ")} \u2014 the app's roles are made with the database`);let r=n.map(b).join(", ");await this.tx(e,["CREATE SCHEMA IF NOT EXISTS palgres",`CREATE TABLE IF NOT EXISTS palgres.versions (
268
+ `)}`:""}`)};return{version:{n:1,digest:g,state:"active",schema:i.schema},adoption:{unforced:i.unforce,unmanaged:i.unmanaged},layout:l,record:p}}async made(e,n,s,r){let o=`palgres_shadow_${Ko(6).toString("hex")}`;await e.query(`CREATE DATABASE ${b(o)}`);try{let a=this.shadow(o);try{await new t(a,{roles:this.roles,lockTimeoutMs:this.lockTimeoutMs}).start(n);let i=await Yn(a,s,this.roles);return await Yo(a,r,i),i}finally{await a.end()}}finally{await e.query(`DROP DATABASE IF EXISTS ${b(o)} WITH (FORCE)`)}}async planFrom(e,n,s){let r=new Set;for(let f of n?.schema.tables??[])(await e.query(`SELECT EXISTS (SELECT 1 FROM ${P(f.schema,f.name)}) AS any`))[0].any&&r.add(D(f));let o=new Map,a=[],i=(f,d)=>{let T=`${f}\0${d}`;return o.has(T)||(o.set(T,void 0),a.push([f,d])),o.get(T)},l=(await e.query("SELECT to_regclass('palgres.versions') IS NOT NULL AS there"))[0]?.there===!0?Number((await e.query("SELECT coalesce(max(n), 0) AS n FROM palgres.versions"))[0].n):0,u=Math.max(l,n?.n??0)+1,g=new Map,p=f=>(g.has(f)||g.set(f,void 0),g.get(f)),h=new Map;if((await e.query(`SELECT to_regclass('${J}.generations') IS NOT NULL AS there`))[0]?.there===!0)for(let f of await e.query(`SELECT table_key, gen, model, dimensions, metric, from_columns, status FROM ${J}.generations ORDER BY table_key, gen`)){let d=String(f.table_key);h.has(d)||h.set(d,[]),h.get(d).push({gen:Number(f.gen),model:String(f.model),dimensions:Number(f.dimensions),metric:f.metric,from:f.from_columns.map(String),status:f.status})}let m=(await e.query("SELECT n.nspname AS schema FROM pg_catalog.pg_extension e JOIN pg_catalog.pg_namespace n ON n.oid = e.extnamespace WHERE e.extname = 'vector'"))[0]?.schema,y=()=>Lt({from:n&&{n:n.n,schema:n.schema},next:u,to:s,hasRows:f=>r.has(f),castable:i,checkedDomain:p,roles:this.roles,generations:f=>h.get(f)??[],vectorSchema:typeof m=="string"?m:"public"}),S=y();if(a.length===0&&g.size===0)return S;for(let[f,d]of a)o.set(`${f}\0${d}`,await this.casts(e,f,d));for(let f of g.keys())g.set(f,await this.checkedDomain(e,f));return y()}async checkedDomain(e,n){let s=await e.query(`SELECT t.typtype = 'd' AND (t.typnotnull OR EXISTS (SELECT 1 FROM pg_catalog.pg_constraint c WHERE c.contypid = t.oid)) AS checked FROM pg_catalog.pg_type t WHERE t.oid = pg_catalog.to_regtype(${M(n)})`);return s.length===0?void 0:s[0].checked===!0}async casts(e,n,s){try{return await e.query(`SELECT CAST(NULL::${n} AS ${s})`),!0}catch(r){let o=ae(r);if(o==="42846")return!1;if(o==="42704")return;throw r}}async active(e){if(e.ledger===!1)return null;let n=await e.query("SELECT n, digest, schema FROM palgres.versions WHERE state = 'active' ORDER BY n DESC LIMIT 1"),s=await this.open(e),o=(s?await e.query(`SELECT n, digest, schema FROM palgres.versions WHERE n = ${s.from_n??-1}`):n)[0];return o?{n:Number(o.n),digest:String(o.digest),state:"active",schema:_t(o.schema)}:null}async version(e,n){if(e.ledger===!1)return null;let s=await e.query(`SELECT n, digest, state FROM palgres.versions WHERE n = ${n}`);return s[0]?{n,digest:String(s[0].digest),state:s[0].state}:null}async open(e){if(e.ledger===!1)return null;let s=(await e.query("SELECT from_n, to_n, plan, done, phase, to_jsonb(m) ->> 'opened_by' AS opened_by FROM palgres.migration m"))[0];return s?{from_n:s.from_n===null?null:Number(s.from_n),to_n:Number(s.to_n),plan:Xo(_t(s.plan),Number(s.to_n)),done:_t(s.done),phase:s.phase,opened_by:typeof s.opened_by=="string"?s.opened_by:null}:null}async session(e,n=!0,s){let r=await this.pool.reserve(),o={query:async a=>await r.unsafe(a)};try{if(await o.query("SET application_name = 'palgres:migrate'"),await o.query("SET search_path = public, pg_temp"),n){await o.query(`SELECT pg_advisory_lock(hashtextextended(${M(nr)}, 0))`);let a=(await o.query(`SELECT to_regclass('palgres.versions') IS NOT NULL AS there, (SELECT pg_catalog.obj_description(n.oid, 'pg_namespace') FROM pg_catalog.pg_namespace n WHERE n.nspname = '${J}') AS search`))[0];o.ledger=a.there===!0,o.searchLedger=typeof a.search=="string"?a.search:null,o.ledger&&await this.ensure(o)}else if((await o.query("SELECT to_regclass('palgres.migration') IS NULL AS none"))[0].none)return await(s?s(o):e(Go));return await e(o)}finally{n&&await o.query(`SELECT pg_advisory_unlock(hashtextextended(${M(nr)}, 0))`).catch(()=>{}),r.release()}}async ownAuth(e){let n=await this.authRefusals(e);if(n.length>0)throw new $e(n)}async authRefusals(e){let n={jwt:["SELECT coalesce(nullif(current_setting('request.jwt.claims', true), '')::jsonb, '{}'::jsonb)"],uid:["SELECT nullif(auth.jwt() ->> 'sub', '')","SELECT current_setting('request.jwt.claims', true)::jsonb ->> 'sub'"],role:["SELECT nullif(auth.jwt() ->> 'role', '')"]},s=a=>a.replace(/\s+/g," ").trim();return(await e.query("SELECT p.proname AS name, p.prosrc AS src, pg_catalog.format_type(p.prorettype, NULL) AS returns FROM pg_catalog.pg_proc p JOIN pg_catalog.pg_namespace n ON n.oid = p.pronamespace WHERE n.nspname = 'auth' AND p.proname IN ('jwt', 'uid', 'role') AND p.pronargs = 0")).filter(a=>!(n[String(a.name)]??[]).some(i=>s(i)===s(String(a.src)))).map(a=>`auth.${a.name}() is the database's own (returns ${a.returns}: ${s(String(a.src)).slice(0,120)}): Palgres makes it read the request's claims (request.jwt.claims), and the app there now would read its caller otherwise \u2014 rename yours, or make it read the claims as Palgres does, before the take-over`)}async ensure(e){let n=[this.roles.anon,this.roles.authenticated,this.roles.service],s=await e.query(`SELECT r FROM unnest(ARRAY[${n.map(M).join(", ")}]) AS r WHERE NOT EXISTS (SELECT 1 FROM pg_roles WHERE rolname = r)`);if(s.length>0)throw new Error(`palgres: the database has no role ${s.map(o=>o.r).join(", ")} \u2014 the app's roles are made with the database`);let r=n.map(b).join(", ");await this.tx(e,["CREATE SCHEMA IF NOT EXISTS palgres",`CREATE TABLE IF NOT EXISTS palgres.versions (
269
269
  n integer PRIMARY KEY,
270
270
  digest text NOT NULL,
271
271
  schema jsonb NOT NULL,
package/dist/testing.js CHANGED
@@ -1,2 +1,2 @@
1
- /*! palgres 0.9.1 — Palbase SDK License (see LICENSE) */
2
- import{$ as wn,D as U,E as fn,F as Y,J as Z,K as V,L as z,M as dn,O as P,W as _,aa as $n,e as cn,g as ln}from"./chunks/XPAEKET5.js";import"./chunks/CBPYINOK.js";import{randomUUID as Rn}from"node:crypto";var On=/^\d{4}-\d{2}-\d{2}([T ]\d{2}:\d{2}(:\d{2}(\.\d+)?)?)?(Z|[+-]\d{2}(:?\d{2})?)?$/,bn=/^([+-]?)(\d*)(?:\.(\d*))?$/;function q(e){if(e instanceof Date)return e.getTime();if(typeof e=="string"&&On.test(e)){let t=Date.parse(e);return Number.isNaN(t)?null:t}return null}function B(e){if(typeof e=="number")return Number.isFinite(e)?B(String(e)):null;if(typeof e!="string"||/e/i.test(e))return null;let t=bn.exec(e.trim());if(t===null||t[2]===""&&(t[3]??"")==="")return null;let a=t[3]??"";return{unit:BigInt(`${t[1]==="-"?"-":""}${t[2]===""?"0":t[2]}${a}`),scale:a.length}}function K(e,t){return e.unit*10n**BigInt(t-e.scale)}function tn(e,t){if(e==null||t===null||t===void 0)return null;let a=q(e),c=q(t);if(a!==null&&c!==null)return Math.sign(a-c);let w=B(e),f=B(t);if(w!==null&&f!==null){let d=Math.max(w.scale,f.scale),h=K(w,d)-K(f,d);return h===0n?0:h<0n?-1:1}return typeof e==typeof t&&(typeof e=="string"||typeof e=="boolean"||typeof e=="number")?e<t?-1:e>t?1:0:null}function N(e,t){return e==null||t===null||t===void 0?!1:e instanceof Date||t instanceof Date?q(e)!==null&&q(e)===q(t):Array.isArray(e)&&Array.isArray(t)?e.length===t.length&&e.every((a,c)=>N(a,t[c])):e===t}function H(e){let t=((e?.days??0)*86400+(e?.hours??0)*3600+(e?.minutes??0)*60+(e?.seconds??0))*1e3;return new Date(Date.now()-t).toISOString()}function v(e,t,a){if(e==null)return null;if(typeof e=="number"&&typeof t=="number")return e+a*t;let c=B(e),w=B(t);if(c===null||w===null)throw new Error(`increment()/decrement() on a value that is not a number (${JSON.stringify(e)}): Postgres refuses it ("operator does not exist")`);let f=Math.max(c.scale,w.scale),d=K(c,f)+BigInt(a)*K(w,f);if(f===0)return typeof e=="number"?Number(d):d.toString();let h=d<0n,R=(h?-d:d).toString().padStart(f+1,"0"),k=`${h?"-":""}${R.slice(0,-f)}.${R.slice(-f)}`;return typeof e=="number"?Number(k):k}function kn(e,t){let a=A=>{let C=(A.unit<0n?-A.unit:A.unit).toString().padStart(A.scale+1,"0"),J=C.slice(0,C.length-A.scale),n=C.slice(C.length-A.scale),r=J.padStart(Math.ceil(J.length/4)*4,"0").match(/.{4}/g)??[],s=n.padEnd(Math.ceil(n.length/4)*4,"0").match(/.{4}/g)??[],i=[...r.map((u,l)=>[r.length-1-l,Number(u)]),...s.map((u,l)=>[-1-l,Number(u)])].find(([,u])=>u!==0);return i?[i[0],i[1]]:[0,0]},[c,w]=a(e),[f,d]=a(t),h=c-f-(w<=d?1:0),R=Math.min(Math.max(16-h*4,e.scale,t.scale,0),1e3),k=e.unit*10n**BigInt(R+t.scale),E=t.unit*10n**BigInt(e.scale),T=k/E,x=k%E;2n*(x<0n?-x:x)>=(E<0n?-E:E)&&(T+=k<0n!=E<0n?-1n:1n);let I=T<0n,W=(I?-T:T).toString().padStart(R+1,"0");return`${I?"-":""}${R===0?W:`${W.slice(0,-R)}.${W.slice(-R)}`}`}var $=e=>structuredClone(e);function rn(e,t,a){if(fn(a))throw new Error(`${e}(${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(!(a===null||typeof a!="object"))for(let[c,w]of Object.entries(a))if(c==="OR"||c==="AND")for(let f of Array.isArray(w)?w:[])rn(e,t,f);else c==="NOT"&&rn(e,t,w)}function D(e,t,a){return cn(new ln({fields:[{field:t,message:a}]},`${e}: ${t} ${a}`))}function on(e,t,a="where"){for(let[c,w]of Object.entries(t))if(c==="OR"||c==="AND"){let f=w;if(c==="AND"&&f.length===0)throw D(e,`${a}.AND`,"is an empty list \u2014 no condition at all. Leave it out, or name a condition in it.");f.forEach((d,h)=>{if(Object.keys(d).length===0)throw D(e,`${a}.${c}[${h}]`,"holds no condition \u2014 a branch that matches every row. Name a condition in it, or leave it out.");on(e,d,`${a}.${c}[${h}]`)})}else if(c==="NOT"){if(Array.isArray(w))throw D(e,`${a}.NOT`,"is a list \u2014 NOT takes one filter object. For several conditions, NOT: { AND: [...] } or NOT: { OR: [...] }.");if(Object.keys(w).length===0)throw D(e,`${a}.NOT`,"holds no condition \u2014 NOT of nothing is not a filter. Name the condition to exclude.");on(e,w,`${a}.NOT`)}else if(c==="has"&&Object.keys(w??{}).length===0)throw D(e,`${a}.has`,"names no relation \u2014 no condition. Name one: has: { <relation>: { \u2026 } }.")}function F(e,t){if(Object.keys(t).length===0)throw D(e,"where",`holds no condition, so ${e} would reach EVERY row of the table. Name a condition.`)}function sn(e){let t=!1;for(let a of e){if(a===!1)return!1;a===null&&(t=!0)}return t?null:!0}function mn(e){let t=!1;for(let a of e){if(a===!0)return!0;a===null&&(t=!0)}return t?null:!1}var j=e=>e==null;function L(e,t,a,c){return sn(Object.entries(c).map(([w,f])=>{if(w==="OR")return mn(f.map(d=>L(e,t,a,d)));if(w==="AND")return sn(f.map(d=>L(e,t,a,d)));if(w==="NOT"){let d=L(e,t,a,f);return d===null?null:!d}if(w==="has")throw new Error(`${e}(${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 xn(e,t,a,w,f)}))}var gn=["neq","gt","gte","lt","lte"];function Q(e,t){return j(e)||j(t)?null:N(e,t)}function xn(e,t,a,c,w){let f=a[c];return w===null?j(f):U(w)?Q(f,a[w.$col]):V(w)?Q(f,H(_(w)?.minus)):typeof w=="object"&&!Array.isArray(w)&&!(w instanceof Date)?sn(Object.entries(w).map(([d,h])=>{if(V(h)){if(!gn.includes(d))throw new Error(`${e}(${t}): where.${c}.${d} cannot take now()`);return G(d,f,H(_(h)?.minus))}if(Z(h))throw new Error(`${e}(${t}): where.${c}.${d} was given increment()/decrement() \u2014 a write, not a value to compare with`);if(U(h)){if(!gn.includes(d))throw new Error(`${e}(${t}): where.${c}.${d} cannot take col()`);return G(d,f,a[h.$col])}switch(d){case"in":{if(!Array.isArray(h))throw new Error(`${e}(${t}): where.${c}.in is a list`);return mn(h.map(R=>Q(f,R)))}case"neq":return h===null?!j(f):G(d,f,h);case"gt":case"gte":case"lt":case"lte":return G(d,f,h);case"isNull":if(typeof h!="boolean")throw new Error(`${e}(${t}): where.${c}.isNull is true or false`);return h?j(f):!j(f);case"overlaps":if(!Array.isArray(h))throw new Error(`${e}(${t}): where.${c}.overlaps is a list`);if(f!=null&&!Array.isArray(f))throw new Error(`${e}(${t}): where.${c}: "overlaps" is an array column's operator`);return j(f)?null:h.some(R=>f.some(k=>N(R,k)));case"contains":case"icontains":case"startsWith":case"endsWith":{if(d==="contains"&&Array.isArray(h))return j(f)?null:Array.isArray(f)&&h.every(R=>f.some(k=>N(R,k)));if(typeof h!="string")throw new Error(`${e}(${t}): where.${c}.${d} is text`);return j(f)?null:typeof f!="string"?!1:d==="contains"?f.includes(h):d==="icontains"?f.toLowerCase().includes(h.toLowerCase()):d==="startsWith"?f.startsWith(h):f.endsWith(h)}default:throw new Error(`${e}(${t}): where.${c} has no operator "${d}"`)}})):Q(f,w)}function G(e,t,a){if(j(t)||j(a))return null;if(e==="neq")return!N(t,a);let c=tn(t,a);return c===null?!1:e==="gt"?c>0:e==="gte"?c>=0:e==="lt"?c<0:c<=0}function En(){let e=new Map,t=new Map,a=new Map,c=new Map,w=[],f=n=>{let r=e.get(n);return r||e.set(n,r=[]),r},d=(n,r,s)=>{let o=n.get(r);o?o.push(s):n.set(r,[s])},h=n=>n.id===void 0?{id:Rn(),...n}:{...n},R=()=>{let n={store:new Map([...e].map(([r,s])=>[r,s.map($)])),inserted:hn(t),updated:hn(a),deleted:new Map([...c].map(([r,s])=>[r,[...s]]))};return()=>{e=n.store,t=n.inserted,a=n.updated,c=n.deleted}};function k(n,r,s){let o={};for(let[i,u]of Object.entries(s)){let l=_(u);if(l!==null&&l.fn==="now")o[i]=H(l.minus);else{if(l!==null)throw new Error(`${n}(${r}): "${i}" was given ${l.fn==="inc"?"increment()":"decrement()"} \u2014 the row does not exist yet, so there is no current value to change`);o[i]=u}}return P(n,r,Object.keys(o),o),z(n,r,Object.keys(o),o),o}function E(n,r,s,o){P(n,r,Object.keys(o),o);let i={};for(let[u,l]of Object.entries(o)){let g=_(l);g!==null&&g.fn==="now"?i[u]=H(g.minus):g!==null?i[u]=v(s[u],g.by,g.fn==="inc"?1:-1):i[u]=l}return z(n,r,Object.keys(i),i),i}function T(n,r,s){let o=h(k(n,r,s));return f(r).push(o),d(t,r,$(o)),$(o)}function x(n,r,s){return dn(n,r,s),rn(n,r,s),s!==void 0&&on(n,s),(e.get(r)??[]).filter(o=>s===void 0||L(n,r,o,s)===!0)}let I={diagnostics:()=>null,async query(n,r=[]){return w.push({sql:n,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(n){throw new Error(`search(${n}): the fake database has neither embeddings nor full text \u2014 test search against Postgres`)},async findById(n,r){let s=(e.get(n)??[]).find(o=>o.id===r);return s?$(s):null},async findMany(n,r,s){let{limit:o,offset:i}=s??{};if(o!==void 0&&(!Number.isInteger(o)||o<0))throw new Error(`findMany(${n}): limit is a whole number, 0 or more (got ${String(o)})`);if(i!==void 0){if(!Number.isInteger(i)||i<0)throw new Error(`findMany(${n}): offset is a whole number, 0 or more (got ${String(i)})`);if(o===void 0)throw new Error(`findMany(${n}): 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(${n}): the fake database has no relations, so \`with\` cannot be read \u2014 seed and query the related table on its own, or test this against Postgres`);let u=x("findMany",n,r),l=s?.orderBy===void 0?[]:Array.isArray(s.orderBy)?s.orderBy:[s.orderBy];l.length>0&&(u=[...u].sort((y,p)=>{for(let O of l){let b=O.direction==="desc"?-1:1,M=y[O.column],S=p[O.column],X=M==null,an=S==null;if(X||an){if(X&&an)continue;let pn=O.nulls===void 0?b===-1:O.nulls==="first";return(X?1:-1)*(pn?-1:1)}let un=tn(M,S)??(String(M)<String(S)?-1:String(M)>String(S)?1:0);if(un!==0)return un*b}return 0}));let g=o===void 0?u:u.slice(i??0,(i??0)+o),m=s?.select;return g.map(y=>m===void 0||m.length===0?$(y):Object.fromEntries(m.map(p=>[p,structuredClone(y[p])])))},async count(n,r={}){return x("count",n,r).length},async aggregate(n,r){let s=x("aggregate",n,r.where),o=r.groupBy??[],i=l=>{let g={},m=y=>l.map(p=>p[y]).filter(p=>p!=null);for(let y of r.sum??[]){let p=m(y);(g.sum??={})[y]=p.length===0?null:String(p.reduce((O,b)=>v(O,b,1),"0"))}for(let y of r.avg??[]){let p=m(y),O=p.some(b=>typeof b=="number"&&!Number.isInteger(b));(g.avg??={})[y]=p.length===0?null:O?p.reduce((b,M)=>b+M,0)/p.length:kn(B(p.reduce((b,M)=>v(b,M,1),"0")),{unit:BigInt(p.length),scale:0})}for(let[y,p]of[["min",-1],["max",1]])for(let O of r[y]??[]){let b=m(O);(g[y]??={})[O]=b.length===0?null:b.reduce((M,S)=>(tn(S,M)??0)*p>0?S:M)}return r.count===!0?g.count=l.length:r.count!==void 0&&r.count!==!1&&(g.count=Object.fromEntries(Object.entries(r.count).map(([y,p])=>[y,l.filter(O=>L("aggregate",n,O,p)===!0).length]))),g};if(o.length===0)return i(s);let u=new Map;for(let l of s){let g=JSON.stringify(o.map(m=>l[m]));u.set(g,[...u.get(g)??[],l])}return[...u.values()].map(l=>({...i(l),...Object.fromEntries(o.map(g=>[g,l[0][g]]))}))},async insert(n,r){return T("insert",n,r)},insertMany:(async(n,r,s)=>{if(wn(s),s?.onConflict?.length||s?.action!==void 0)throw new Error(`insertMany(${n}): 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,l)=>{let g=o.filter(y=>!(y in u)),m=Object.keys(u).filter(y=>!o.includes(y));if(g.length>0||m.length>0)throw new Error(`insertMany(${n}): row ${l} has not the first row's columns${g.length?` (missing ${g.join(", ")})`:""}${m.length?` (extra ${m.join(", ")})`:""} \u2014 write null for an empty one, or insert rows of another shape in a call of their own`)});let i=r.map(u=>T("insertMany",n,u));return s?.returning===!1?i.length:i}),async put(n,r,s){if(!s?.onConflict?.length)throw new Error(`put(${n}): onConflict names at least one column`);let o=k("put",n,r),i=f(n).find(u=>s.onConflict.every(l=>N(u[l],o[l])));if(!i)return T("put",n,r);for(let[u,l]of Object.entries(o))s.onConflict.includes(u)||(i[u]=l);return d(a,n,$(i)),$(i)},async update(n,r,s){let o=e.get(n)??[],i=o.findIndex(u=>u.id===r);return i<0?(P("update",n,Object.keys(s),s),null):(o[i]={...o[i],...E("update",n,o[i],s)},d(a,n,$(o[i])),$(o[i]))},async updateMany(n,r,s,o){F("updateMany",r);let i=x("updateMany",n,r),u=f(n),l=[];for(let g of i){let m=u.indexOf(g);u[m]={...g,...E("updateMany",n,g,s)},d(a,n,$(u[m])),l.push($(u[m]))}return i.length===0&&P("updateMany",n,Object.keys(s),s),o?.returning===!1?l.length:l},async delete(n,r){let s=e.get(n)??[],o=s.findIndex(i=>i.id===r);o<0||(s.splice(o,1),d(c,n,r))},async deleteMany(n,r){F("deleteMany",r);let s=x("deleteMany",n,r);e.set(n,(e.get(n)??[]).filter(o=>!s.includes(o)));for(let o of s)d(c,n,String(o.id));return s.length},async claim(n,r,s={}){let o=Object.keys(r);if(o.length===0)throw new Error(`claim(${n}): no unique field \u2014 claim takes a key; without one, insert(${n}, \u2026)`);P("claim",n,o,r);let i=(e.get(n)??[]).find(u=>o.every(l=>N(u[l],r[l])));return i?{inserted:!1,row:$(i)}:{inserted:!0,row:T("claim",n,{...r,...s})}},async lockRows(n,r){if(r.length===0)return;let s=e.get(n)??[],o=[...new Set(r)].filter(i=>!s.some(u=>u.id===i));if(o.length>0&&s.length>0)throw new Error(`lockRows(${n}): no row with id ${o.join(", ")}`)},async lockRowsWhere(n,r,s){let o=s?.mode??"update";if(!["update","share","noKeyUpdate"].includes(o))throw new Error(`lockRowsWhere(${n}): mode is "update", "share" or "noKeyUpdate" (got "${String(o)}")`);F("lockRowsWhere",r),x("lockRowsWhere",n,r)},async advisoryXactLock(){}};function W(n){let r=R(),s=[];try{for(let o of n.ops){let i=A(o,s);s.push(i);let u=Tn(o.guard,i.rows.length);if(u)throw u}}catch(o){throw r(),o}return{results:s}}function A(n,r){let s=i=>Object.fromEntries(Object.entries(i??{}).map(([u,l])=>[u,yn(l,r)])),o=`transaction plan ${n.op}`;switch(n.op){case"insert":return nn(T(o,n.table,s(n.values)));case"insertMany":{let i=(n.rows??[]).map(g=>s(g)),u=n.onConflict??[];if(n.action!==void 0&&u.length===0)throw new Error(`${o}(${n.table}): the fake database knows no unique key to collide with \u2014 name onConflict columns, or test this against Postgres`);let l=[];for(let g of i){let m=u.length>0?f(n.table).find(y=>u.every(p=>N(y[p],g[p]))):void 0;if(!(m&&n.action==="ignore")){if(m&&n.action==="update"){Object.assign(m,E(o,n.table,m,Object.fromEntries(Object.entries(g).filter(([y])=>!u.includes(y))))),d(a,n.table,$(m)),l.push($(m));continue}l.push(T(o,n.table,g))}}return{rows:l,rows_affected:l.length}}case"upsert":{let i=s(n.values),u=n.onConflict??[];if(Object.keys(i).length===0||u.length===0)throw Object.assign(new Error(`put on ${n.table} needs columns and onConflict`),{error_code:"tx_bad_upsert"});let l=f(n.table).find(g=>u.every(m=>N(g[m],i[m])));return l?(Object.assign(l,E(o,n.table,l,Object.fromEntries(Object.entries(i).filter(([g])=>!u.includes(g))))),d(a,n.table,$(l)),nn($(l))):nn(T(o,n.table,i))}case"update":{let i=s(n.set);if(Object.keys(i).length===0)throw new Error(`update ${n.table}: nothing to set`);let u=en(n.where,r);F(o,u);let l=f(n.table),g=[];for(let m of x(o,n.table,u)){let y=l.indexOf(m);l[y]={...m,...E(o,n.table,m,i)},d(a,n.table,$(l[y])),g.push($(l[y]))}return{rows:g,rows_affected:g.length}}case"delete":{let i=en(n.where,r);F(o,i);let u=x(o,n.table,i);e.set(n.table,f(n.table).filter(l=>!u.includes(l)));for(let l of u)d(c,n.table,String(l.id));return{rows:u.map($),rows_affected:u.length}}case"select":{let i=x(o,n.table,en(n.where,r));return n.limit!==void 0&&(i=i.slice(0,n.limit)),{rows:i.map($),rows_affected:i.length}}default:throw new Error(`unknown operation "${String(n.op)}" in a transaction plan`)}}let C={...I,async txPlan(n){return W(n)},async attempt(n){let r=R();try{return await n(I)}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{...C,asService:()=>C,inserted:n=>(t.get(n)??[]).map($),updated:n=>(a.get(n)??[]).map($),deleted:n=>[...c.get(n)??[]],seed(n,r){e.set(n,r.map($))},queries:w}}function hn(e){return new Map([...e].map(([t,a])=>[t,a.map($)]))}function nn(e){return{rows:[e],rows_affected:1}}function yn(e,t){if(!Y(e))return e;let a=t[e.$ref.op]?.rows[0];if(!a)throw Object.assign(new Error(`transaction plan: operation ${e.$ref.op} produced no row to reference`),{error_code:"tx_ref_unresolved"});return a[e.$ref.field]}function en(e,t){let a=c=>{if(Y(c)){let w=yn(c,t);if(w==null)throw Object.assign(new Error(`transaction plan: a filter's reference to operation ${c.$ref.op}'s "${c.$ref.field}" is NULL`),{error_code:"tx_ref_null"});return w}return Array.isArray(c)?c.map(a):c!==null&&typeof c=="object"&&!U(c)&&!Z(c)&&!V(c)&&!(c instanceof Date)?Object.fromEntries(Object.entries(c).map(([w,f])=>[w,a(f)])):c};return a(e??{})}function Tn(e,t){return e?(e.kind==="one"?t===1:e.kind==="none"?t===0:e.kind==="atLeast"?t>=e.n:t<=e.n)?null:Object.assign(new Error(`transaction expectation failed: ${e.kind} (${t} row(s))`),{error_code:"tx_guard_failed",slot:e.slot}):null}export{En as createFakeClient,$n as typedDatabase};
1
+ /*! palgres 0.10.0 — Palbase SDK License (see LICENSE) */
2
+ import{$ as wn,D as U,E as fn,F as Y,J as Z,K as V,L as z,M as dn,O as P,W as _,aa as $n,e as cn,g as ln}from"./chunks/IOL277J3.js";import"./chunks/FTBMJL4C.js";import{randomUUID as Rn}from"node:crypto";var On=/^\d{4}-\d{2}-\d{2}([T ]\d{2}:\d{2}(:\d{2}(\.\d+)?)?)?(Z|[+-]\d{2}(:?\d{2})?)?$/,bn=/^([+-]?)(\d*)(?:\.(\d*))?$/;function q(e){if(e instanceof Date)return e.getTime();if(typeof e=="string"&&On.test(e)){let t=Date.parse(e);return Number.isNaN(t)?null:t}return null}function B(e){if(typeof e=="number")return Number.isFinite(e)?B(String(e)):null;if(typeof e!="string"||/e/i.test(e))return null;let t=bn.exec(e.trim());if(t===null||t[2]===""&&(t[3]??"")==="")return null;let a=t[3]??"";return{unit:BigInt(`${t[1]==="-"?"-":""}${t[2]===""?"0":t[2]}${a}`),scale:a.length}}function K(e,t){return e.unit*10n**BigInt(t-e.scale)}function tn(e,t){if(e==null||t===null||t===void 0)return null;let a=q(e),c=q(t);if(a!==null&&c!==null)return Math.sign(a-c);let w=B(e),f=B(t);if(w!==null&&f!==null){let d=Math.max(w.scale,f.scale),h=K(w,d)-K(f,d);return h===0n?0:h<0n?-1:1}return typeof e==typeof t&&(typeof e=="string"||typeof e=="boolean"||typeof e=="number")?e<t?-1:e>t?1:0:null}function N(e,t){return e==null||t===null||t===void 0?!1:e instanceof Date||t instanceof Date?q(e)!==null&&q(e)===q(t):Array.isArray(e)&&Array.isArray(t)?e.length===t.length&&e.every((a,c)=>N(a,t[c])):e===t}function H(e){let t=((e?.days??0)*86400+(e?.hours??0)*3600+(e?.minutes??0)*60+(e?.seconds??0))*1e3;return new Date(Date.now()-t).toISOString()}function v(e,t,a){if(e==null)return null;if(typeof e=="number"&&typeof t=="number")return e+a*t;let c=B(e),w=B(t);if(c===null||w===null)throw new Error(`increment()/decrement() on a value that is not a number (${JSON.stringify(e)}): Postgres refuses it ("operator does not exist")`);let f=Math.max(c.scale,w.scale),d=K(c,f)+BigInt(a)*K(w,f);if(f===0)return typeof e=="number"?Number(d):d.toString();let h=d<0n,R=(h?-d:d).toString().padStart(f+1,"0"),k=`${h?"-":""}${R.slice(0,-f)}.${R.slice(-f)}`;return typeof e=="number"?Number(k):k}function kn(e,t){let a=A=>{let C=(A.unit<0n?-A.unit:A.unit).toString().padStart(A.scale+1,"0"),J=C.slice(0,C.length-A.scale),n=C.slice(C.length-A.scale),r=J.padStart(Math.ceil(J.length/4)*4,"0").match(/.{4}/g)??[],s=n.padEnd(Math.ceil(n.length/4)*4,"0").match(/.{4}/g)??[],i=[...r.map((u,l)=>[r.length-1-l,Number(u)]),...s.map((u,l)=>[-1-l,Number(u)])].find(([,u])=>u!==0);return i?[i[0],i[1]]:[0,0]},[c,w]=a(e),[f,d]=a(t),h=c-f-(w<=d?1:0),R=Math.min(Math.max(16-h*4,e.scale,t.scale,0),1e3),k=e.unit*10n**BigInt(R+t.scale),E=t.unit*10n**BigInt(e.scale),T=k/E,x=k%E;2n*(x<0n?-x:x)>=(E<0n?-E:E)&&(T+=k<0n!=E<0n?-1n:1n);let I=T<0n,W=(I?-T:T).toString().padStart(R+1,"0");return`${I?"-":""}${R===0?W:`${W.slice(0,-R)}.${W.slice(-R)}`}`}var $=e=>structuredClone(e);function rn(e,t,a){if(fn(a))throw new Error(`${e}(${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(!(a===null||typeof a!="object"))for(let[c,w]of Object.entries(a))if(c==="OR"||c==="AND")for(let f of Array.isArray(w)?w:[])rn(e,t,f);else c==="NOT"&&rn(e,t,w)}function D(e,t,a){return cn(new ln({fields:[{field:t,message:a}]},`${e}: ${t} ${a}`))}function on(e,t,a="where"){for(let[c,w]of Object.entries(t))if(c==="OR"||c==="AND"){let f=w;if(c==="AND"&&f.length===0)throw D(e,`${a}.AND`,"is an empty list \u2014 no condition at all. Leave it out, or name a condition in it.");f.forEach((d,h)=>{if(Object.keys(d).length===0)throw D(e,`${a}.${c}[${h}]`,"holds no condition \u2014 a branch that matches every row. Name a condition in it, or leave it out.");on(e,d,`${a}.${c}[${h}]`)})}else if(c==="NOT"){if(Array.isArray(w))throw D(e,`${a}.NOT`,"is a list \u2014 NOT takes one filter object. For several conditions, NOT: { AND: [...] } or NOT: { OR: [...] }.");if(Object.keys(w).length===0)throw D(e,`${a}.NOT`,"holds no condition \u2014 NOT of nothing is not a filter. Name the condition to exclude.");on(e,w,`${a}.NOT`)}else if(c==="has"&&Object.keys(w??{}).length===0)throw D(e,`${a}.has`,"names no relation \u2014 no condition. Name one: has: { <relation>: { \u2026 } }.")}function F(e,t){if(Object.keys(t).length===0)throw D(e,"where",`holds no condition, so ${e} would reach EVERY row of the table. Name a condition.`)}function sn(e){let t=!1;for(let a of e){if(a===!1)return!1;a===null&&(t=!0)}return t?null:!0}function mn(e){let t=!1;for(let a of e){if(a===!0)return!0;a===null&&(t=!0)}return t?null:!1}var j=e=>e==null;function L(e,t,a,c){return sn(Object.entries(c).map(([w,f])=>{if(w==="OR")return mn(f.map(d=>L(e,t,a,d)));if(w==="AND")return sn(f.map(d=>L(e,t,a,d)));if(w==="NOT"){let d=L(e,t,a,f);return d===null?null:!d}if(w==="has")throw new Error(`${e}(${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 xn(e,t,a,w,f)}))}var gn=["neq","gt","gte","lt","lte"];function Q(e,t){return j(e)||j(t)?null:N(e,t)}function xn(e,t,a,c,w){let f=a[c];return w===null?j(f):U(w)?Q(f,a[w.$col]):V(w)?Q(f,H(_(w)?.minus)):typeof w=="object"&&!Array.isArray(w)&&!(w instanceof Date)?sn(Object.entries(w).map(([d,h])=>{if(V(h)){if(!gn.includes(d))throw new Error(`${e}(${t}): where.${c}.${d} cannot take now()`);return G(d,f,H(_(h)?.minus))}if(Z(h))throw new Error(`${e}(${t}): where.${c}.${d} was given increment()/decrement() \u2014 a write, not a value to compare with`);if(U(h)){if(!gn.includes(d))throw new Error(`${e}(${t}): where.${c}.${d} cannot take col()`);return G(d,f,a[h.$col])}switch(d){case"in":{if(!Array.isArray(h))throw new Error(`${e}(${t}): where.${c}.in is a list`);return mn(h.map(R=>Q(f,R)))}case"neq":return h===null?!j(f):G(d,f,h);case"gt":case"gte":case"lt":case"lte":return G(d,f,h);case"isNull":if(typeof h!="boolean")throw new Error(`${e}(${t}): where.${c}.isNull is true or false`);return h?j(f):!j(f);case"overlaps":if(!Array.isArray(h))throw new Error(`${e}(${t}): where.${c}.overlaps is a list`);if(f!=null&&!Array.isArray(f))throw new Error(`${e}(${t}): where.${c}: "overlaps" is an array column's operator`);return j(f)?null:h.some(R=>f.some(k=>N(R,k)));case"contains":case"icontains":case"startsWith":case"endsWith":{if(d==="contains"&&Array.isArray(h))return j(f)?null:Array.isArray(f)&&h.every(R=>f.some(k=>N(R,k)));if(typeof h!="string")throw new Error(`${e}(${t}): where.${c}.${d} is text`);return j(f)?null:typeof f!="string"?!1:d==="contains"?f.includes(h):d==="icontains"?f.toLowerCase().includes(h.toLowerCase()):d==="startsWith"?f.startsWith(h):f.endsWith(h)}default:throw new Error(`${e}(${t}): where.${c} has no operator "${d}"`)}})):Q(f,w)}function G(e,t,a){if(j(t)||j(a))return null;if(e==="neq")return!N(t,a);let c=tn(t,a);return c===null?!1:e==="gt"?c>0:e==="gte"?c>=0:e==="lt"?c<0:c<=0}function En(){let e=new Map,t=new Map,a=new Map,c=new Map,w=[],f=n=>{let r=e.get(n);return r||e.set(n,r=[]),r},d=(n,r,s)=>{let o=n.get(r);o?o.push(s):n.set(r,[s])},h=n=>n.id===void 0?{id:Rn(),...n}:{...n},R=()=>{let n={store:new Map([...e].map(([r,s])=>[r,s.map($)])),inserted:hn(t),updated:hn(a),deleted:new Map([...c].map(([r,s])=>[r,[...s]]))};return()=>{e=n.store,t=n.inserted,a=n.updated,c=n.deleted}};function k(n,r,s){let o={};for(let[i,u]of Object.entries(s)){let l=_(u);if(l!==null&&l.fn==="now")o[i]=H(l.minus);else{if(l!==null)throw new Error(`${n}(${r}): "${i}" was given ${l.fn==="inc"?"increment()":"decrement()"} \u2014 the row does not exist yet, so there is no current value to change`);o[i]=u}}return P(n,r,Object.keys(o),o),z(n,r,Object.keys(o),o),o}function E(n,r,s,o){P(n,r,Object.keys(o),o);let i={};for(let[u,l]of Object.entries(o)){let g=_(l);g!==null&&g.fn==="now"?i[u]=H(g.minus):g!==null?i[u]=v(s[u],g.by,g.fn==="inc"?1:-1):i[u]=l}return z(n,r,Object.keys(i),i),i}function T(n,r,s){let o=h(k(n,r,s));return f(r).push(o),d(t,r,$(o)),$(o)}function x(n,r,s){return dn(n,r,s),rn(n,r,s),s!==void 0&&on(n,s),(e.get(r)??[]).filter(o=>s===void 0||L(n,r,o,s)===!0)}let I={diagnostics:()=>null,async query(n,r=[]){return w.push({sql:n,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(n){throw new Error(`search(${n}): the fake database has neither embeddings nor full text \u2014 test search against Postgres`)},async findById(n,r){let s=(e.get(n)??[]).find(o=>o.id===r);return s?$(s):null},async findMany(n,r,s){let{limit:o,offset:i}=s??{};if(o!==void 0&&(!Number.isInteger(o)||o<0))throw new Error(`findMany(${n}): limit is a whole number, 0 or more (got ${String(o)})`);if(i!==void 0){if(!Number.isInteger(i)||i<0)throw new Error(`findMany(${n}): offset is a whole number, 0 or more (got ${String(i)})`);if(o===void 0)throw new Error(`findMany(${n}): 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(${n}): the fake database has no relations, so \`with\` cannot be read \u2014 seed and query the related table on its own, or test this against Postgres`);let u=x("findMany",n,r),l=s?.orderBy===void 0?[]:Array.isArray(s.orderBy)?s.orderBy:[s.orderBy];l.length>0&&(u=[...u].sort((y,p)=>{for(let O of l){let b=O.direction==="desc"?-1:1,M=y[O.column],S=p[O.column],X=M==null,an=S==null;if(X||an){if(X&&an)continue;let pn=O.nulls===void 0?b===-1:O.nulls==="first";return(X?1:-1)*(pn?-1:1)}let un=tn(M,S)??(String(M)<String(S)?-1:String(M)>String(S)?1:0);if(un!==0)return un*b}return 0}));let g=o===void 0?u:u.slice(i??0,(i??0)+o),m=s?.select;return g.map(y=>m===void 0||m.length===0?$(y):Object.fromEntries(m.map(p=>[p,structuredClone(y[p])])))},async count(n,r={}){return x("count",n,r).length},async aggregate(n,r){let s=x("aggregate",n,r.where),o=r.groupBy??[],i=l=>{let g={},m=y=>l.map(p=>p[y]).filter(p=>p!=null);for(let y of r.sum??[]){let p=m(y);(g.sum??={})[y]=p.length===0?null:String(p.reduce((O,b)=>v(O,b,1),"0"))}for(let y of r.avg??[]){let p=m(y),O=p.some(b=>typeof b=="number"&&!Number.isInteger(b));(g.avg??={})[y]=p.length===0?null:O?p.reduce((b,M)=>b+M,0)/p.length:kn(B(p.reduce((b,M)=>v(b,M,1),"0")),{unit:BigInt(p.length),scale:0})}for(let[y,p]of[["min",-1],["max",1]])for(let O of r[y]??[]){let b=m(O);(g[y]??={})[O]=b.length===0?null:b.reduce((M,S)=>(tn(S,M)??0)*p>0?S:M)}return r.count===!0?g.count=l.length:r.count!==void 0&&r.count!==!1&&(g.count=Object.fromEntries(Object.entries(r.count).map(([y,p])=>[y,l.filter(O=>L("aggregate",n,O,p)===!0).length]))),g};if(o.length===0)return i(s);let u=new Map;for(let l of s){let g=JSON.stringify(o.map(m=>l[m]));u.set(g,[...u.get(g)??[],l])}return[...u.values()].map(l=>({...i(l),...Object.fromEntries(o.map(g=>[g,l[0][g]]))}))},async insert(n,r){return T("insert",n,r)},insertMany:(async(n,r,s)=>{if(wn(s),s?.onConflict?.length||s?.action!==void 0)throw new Error(`insertMany(${n}): 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,l)=>{let g=o.filter(y=>!(y in u)),m=Object.keys(u).filter(y=>!o.includes(y));if(g.length>0||m.length>0)throw new Error(`insertMany(${n}): row ${l} has not the first row's columns${g.length?` (missing ${g.join(", ")})`:""}${m.length?` (extra ${m.join(", ")})`:""} \u2014 write null for an empty one, or insert rows of another shape in a call of their own`)});let i=r.map(u=>T("insertMany",n,u));return s?.returning===!1?i.length:i}),async put(n,r,s){if(!s?.onConflict?.length)throw new Error(`put(${n}): onConflict names at least one column`);let o=k("put",n,r),i=f(n).find(u=>s.onConflict.every(l=>N(u[l],o[l])));if(!i)return T("put",n,r);for(let[u,l]of Object.entries(o))s.onConflict.includes(u)||(i[u]=l);return d(a,n,$(i)),$(i)},async update(n,r,s){let o=e.get(n)??[],i=o.findIndex(u=>u.id===r);return i<0?(P("update",n,Object.keys(s),s),null):(o[i]={...o[i],...E("update",n,o[i],s)},d(a,n,$(o[i])),$(o[i]))},async updateMany(n,r,s,o){F("updateMany",r);let i=x("updateMany",n,r),u=f(n),l=[];for(let g of i){let m=u.indexOf(g);u[m]={...g,...E("updateMany",n,g,s)},d(a,n,$(u[m])),l.push($(u[m]))}return i.length===0&&P("updateMany",n,Object.keys(s),s),o?.returning===!1?l.length:l},async delete(n,r){let s=e.get(n)??[],o=s.findIndex(i=>i.id===r);o<0||(s.splice(o,1),d(c,n,r))},async deleteMany(n,r){F("deleteMany",r);let s=x("deleteMany",n,r);e.set(n,(e.get(n)??[]).filter(o=>!s.includes(o)));for(let o of s)d(c,n,String(o.id));return s.length},async claim(n,r,s={}){let o=Object.keys(r);if(o.length===0)throw new Error(`claim(${n}): no unique field \u2014 claim takes a key; without one, insert(${n}, \u2026)`);P("claim",n,o,r);let i=(e.get(n)??[]).find(u=>o.every(l=>N(u[l],r[l])));return i?{inserted:!1,row:$(i)}:{inserted:!0,row:T("claim",n,{...r,...s})}},async lockRows(n,r){if(r.length===0)return;let s=e.get(n)??[],o=[...new Set(r)].filter(i=>!s.some(u=>u.id===i));if(o.length>0&&s.length>0)throw new Error(`lockRows(${n}): no row with id ${o.join(", ")}`)},async lockRowsWhere(n,r,s){let o=s?.mode??"update";if(!["update","share","noKeyUpdate"].includes(o))throw new Error(`lockRowsWhere(${n}): mode is "update", "share" or "noKeyUpdate" (got "${String(o)}")`);F("lockRowsWhere",r),x("lockRowsWhere",n,r)},async advisoryXactLock(){}};function W(n){let r=R(),s=[];try{for(let o of n.ops){let i=A(o,s);s.push(i);let u=Tn(o.guard,i.rows.length);if(u)throw u}}catch(o){throw r(),o}return{results:s}}function A(n,r){let s=i=>Object.fromEntries(Object.entries(i??{}).map(([u,l])=>[u,yn(l,r)])),o=`transaction plan ${n.op}`;switch(n.op){case"insert":return nn(T(o,n.table,s(n.values)));case"insertMany":{let i=(n.rows??[]).map(g=>s(g)),u=n.onConflict??[];if(n.action!==void 0&&u.length===0)throw new Error(`${o}(${n.table}): the fake database knows no unique key to collide with \u2014 name onConflict columns, or test this against Postgres`);let l=[];for(let g of i){let m=u.length>0?f(n.table).find(y=>u.every(p=>N(y[p],g[p]))):void 0;if(!(m&&n.action==="ignore")){if(m&&n.action==="update"){Object.assign(m,E(o,n.table,m,Object.fromEntries(Object.entries(g).filter(([y])=>!u.includes(y))))),d(a,n.table,$(m)),l.push($(m));continue}l.push(T(o,n.table,g))}}return{rows:l,rows_affected:l.length}}case"upsert":{let i=s(n.values),u=n.onConflict??[];if(Object.keys(i).length===0||u.length===0)throw Object.assign(new Error(`put on ${n.table} needs columns and onConflict`),{error_code:"tx_bad_upsert"});let l=f(n.table).find(g=>u.every(m=>N(g[m],i[m])));return l?(Object.assign(l,E(o,n.table,l,Object.fromEntries(Object.entries(i).filter(([g])=>!u.includes(g))))),d(a,n.table,$(l)),nn($(l))):nn(T(o,n.table,i))}case"update":{let i=s(n.set);if(Object.keys(i).length===0)throw new Error(`update ${n.table}: nothing to set`);let u=en(n.where,r);F(o,u);let l=f(n.table),g=[];for(let m of x(o,n.table,u)){let y=l.indexOf(m);l[y]={...m,...E(o,n.table,m,i)},d(a,n.table,$(l[y])),g.push($(l[y]))}return{rows:g,rows_affected:g.length}}case"delete":{let i=en(n.where,r);F(o,i);let u=x(o,n.table,i);e.set(n.table,f(n.table).filter(l=>!u.includes(l)));for(let l of u)d(c,n.table,String(l.id));return{rows:u.map($),rows_affected:u.length}}case"select":{let i=x(o,n.table,en(n.where,r));return n.limit!==void 0&&(i=i.slice(0,n.limit)),{rows:i.map($),rows_affected:i.length}}default:throw new Error(`unknown operation "${String(n.op)}" in a transaction plan`)}}let C={...I,async txPlan(n){return W(n)},async attempt(n){let r=R();try{return await n(I)}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{...C,asService:()=>C,inserted:n=>(t.get(n)??[]).map($),updated:n=>(a.get(n)??[]).map($),deleted:n=>[...c.get(n)??[]],seed(n,r){e.set(n,r.map($))},queries:w}}function hn(e){return new Map([...e].map(([t,a])=>[t,a.map($)]))}function nn(e){return{rows:[e],rows_affected:1}}function yn(e,t){if(!Y(e))return e;let a=t[e.$ref.op]?.rows[0];if(!a)throw Object.assign(new Error(`transaction plan: operation ${e.$ref.op} produced no row to reference`),{error_code:"tx_ref_unresolved"});return a[e.$ref.field]}function en(e,t){let a=c=>{if(Y(c)){let w=yn(c,t);if(w==null)throw Object.assign(new Error(`transaction plan: a filter's reference to operation ${c.$ref.op}'s "${c.$ref.field}" is NULL`),{error_code:"tx_ref_null"});return w}return Array.isArray(c)?c.map(a):c!==null&&typeof c=="object"&&!U(c)&&!Z(c)&&!V(c)&&!(c instanceof Date)?Object.fromEntries(Object.entries(c).map(([w,f])=>[w,a(f)])):c};return a(e??{})}function Tn(e,t){return e?(e.kind==="one"?t===1:e.kind==="none"?t===0:e.kind==="atLeast"?t>=e.n:t<=e.n)?null:Object.assign(new Error(`transaction expectation failed: ${e.kind} (${t} row(s))`),{error_code:"tx_guard_failed",slot:e.slot}):null}export{En as createFakeClient,$n as typedDatabase};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "palgres",
3
- "version": "0.9.1",
3
+ "version": "0.10.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",
@@ -317,8 +317,6 @@ export interface TableDef<C extends ColumnMap = ColumnMap> {
317
317
  export interface SchemaDef<T extends Record<string, TableDef> = Record<string, TableDef>> {
318
318
  /** The schema's own name — `public`, `billing`, … Declared, never derived. */
319
319
  name: string;
320
- /** Accepted so older schema files still read; there is no REST surface over tables, so it changes nothing. */
321
- exposed: boolean;
322
320
  tables: T;
323
321
  /** Postgres extensions the deploy creates (CREATE EXTENSION IF NOT EXISTS). */
324
322
  extensions: string[];
@@ -446,7 +444,7 @@ export declare function defineTable<const N extends string, C extends ColumnMap,
446
444
  * `invoices` from another schema's `invoices`.
447
445
  *
448
446
  * The returned value is `{ name, tables: { todos: { name, columns, rls,
449
- * policies } }, extensions, exposed }` — the exact shape the runtime schema
447
+ * policies } }, extensions, raw }` — the exact shape the runtime schema
450
448
  * extractor parses. Per-column phantom types are preserved so
451
449
  * `Database.public.todos.insert({...})` stays typed.
452
450
  *
@@ -463,7 +461,6 @@ export declare function defineTable<const N extends string, C extends ColumnMap,
463
461
  */
464
462
  export declare function defineSchema<const T extends readonly TableHandle[]>(name: string, input: {
465
463
  tables: T;
466
- exposed?: boolean;
467
464
  extensions?: string[];
468
465
  raw?: RawUnitDef[];
469
466
  }): SchemaDef<TablesByName<T>>;
@@ -6,7 +6,7 @@ export interface Introspected {
6
6
  schema: Schema;
7
7
  /** What the database holds that the model cannot say, one line each: left as it is. */
8
8
  unmanaged: string[];
9
- /** Tables whose row-level security is FORCEd on their owner, as v2 made every table. */
9
+ /** Tables whose row-level security is FORCEd on their owner. */
10
10
  forced: string[];
11
11
  /** The objects outside the model by kind and name, each with Postgres' text of it: what a raw unit makes is compared by these. */
12
12
  objects: Map<string, string>;
@@ -65,7 +65,7 @@ export interface Plan {
65
65
  }
66
66
  /** A database taken over: what adoption changed itself, and what it left as it is. */
67
67
  export interface Adoption {
68
- /** Tables whose row-level security was FORCEd on their owner, as v2 made them: no longer. */
68
+ /** Tables whose row-level security was FORCEd on their owner: no longer. */
69
69
  unforced: string[];
70
70
  unmanaged: string[];
71
71
  }
@@ -10,7 +10,7 @@ import type { SearchRuntime } from './search.js';
10
10
  * Who a request is, as Postgres will see it: a signed-in caller is
11
11
  * `authenticated` with their claims (sub, role, …), anyone else `anon`. An
12
12
  * app whose every request is its operator's — Studio, whose tables are all
13
- * service_role's (v2 ran it with DB_ROLE=service_role) — binds its requests
13
+ * service_role's — binds its requests
14
14
  * as `service`.
15
15
  */
16
16
  export interface Identity {