palgres 0.42.0 → 0.43.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,4 +1,4 @@
|
|
|
1
|
-
/*! palgres 0.
|
|
1
|
+
/*! palgres 0.43.0 — Palbase SDK License (see LICENSE) */
|
|
2
2
|
import{createHash as z}from"node:crypto";function de(n){return`${n}_lookup`}function me(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}},pe=()=>({tables:[],enums:[],extensions:[],raw:[]}),b=n=>`${n.schema}.${n.name}`,J={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 a=r[2]?r[2].replace(/\s+/g,""):"",o=Q(r[1]);return o===void 0?n.trim()+t:o.length===1&&o[0].quoted?`"${o[0].name.replace(/"/g,'""')}"${a}${t}`:o.length===1?`${J[o[0].name]??o[0].name}${a}${t}`:`${o.map(l=>N(l.name)).join(".")}${a}${t}`}var N=n=>/^[a-z_][a-z0-9_$]*$/.test(n)?n:`"${n.replace(/"/g,'""')}"`,he=(n,e)=>`${N(n)}.${N(e)}`;function Q(n){let e=[],t=0;for(;t<n.length;){if(n[t]==='"'){let r=t+1,a="";for(;;){if(r>=n.length)return;if(n[r]==='"'){if(n[r+1]==='"'){a+='"',r+=2;continue}break}a+=n[r++]}e.push({name:a,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 W=/^[A-Za-z_][A-Za-z0-9_$]*$/,Z=63;function g(n,e,t=!1){if(typeof e!="string"||e==="")return`${n} has no name`;if(t?e.includes("\0"):!W.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 V="vector",F=["cosine","euclidean","inner_product"],q=1536,G=2e3,R=4e3,X=/^(text|citext|public\.citext|character varying(\(\d+\))?)$/;function A(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 a=new Set;for(let o of Array.isArray(t.from)?t.from:[]){a.has(o)&&r.push(`${n}: search.from names "${o}" twice \u2014 name each column once`),a.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`):X.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 ${G} dimensions and a half-precision one of at most ${R}; ask the model for fewer (search: { dimensions: ${q} })`),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 ye(n){let e=[],t=i=>i&&e.push(i),r=new Map,a=new Map,o=(i,c,f)=>{let u=`${i}.${c}`,d=a.get(u);d?e.push(`${f} "${c}" has the name of ${d} in schema ${i}`):a.set(u,f)};for(let i of n.enums)t(g("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 c=b(i);t(g("a schema",i.schema)),t(g("a table",i.name)),r.has(c)&&e.push(`table ${c} is declared twice`),r.set(c,i),o(i.schema,i.name,`table ${c}`);let f=new Map,u=(s,m)=>{let C=f.get(s);C?e.push(`${m} "${s}" has the name of a ${C} of table ${c}`):f.set(s,m)},d=new Map;for(let s of i.columns)t(g(`column ${c}.${s.name}`,s.name)),d.has(s.name)&&e.push(`column ${c}.${s.name} is declared twice`),d.set(s.name,s),s.identity&&s.default!==void 0&&e.push(`column ${c}.${s.name}: an identity column has no default`),s.generated&&(s.default!==void 0||s.identity||s.fill!==void 0)&&e.push(`column ${c}.${s.name}: a generated column has no default, identity or fill`),s.generated&&!s.generated.expr.trim()&&e.push(`column ${c}.${s.name}: a generated column's expression is empty`),s.identity&&!["smallint","integer","bigint"].includes(D(s.type))&&e.push(`column ${c}.${s.name}: an identity column is smallint, integer or bigint`),s.identity&&s.nullable&&e.push(`column ${c}.${s.name}: an identity column is NOT NULL`);let h=(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 ${c} does not have`)};for(let s of i.primaryKey)h(s,`the primary key of ${c}`);for(let s of i.primaryKey)d.get(s)?.nullable&&e.push(`column ${c}.${s} is in the primary key, so it is not nullable`);for(let s of i.uniques){t(g(`a unique constraint of ${c}`,s.name,!0)),o(i.schema,s.name,`unique constraint ${c}.${s.name}`),u(s.name,"unique constraint"),s.columns.length===0&&e.push(`unique constraint ${s.name} names no column`);for(let m of s.columns)h(m,`unique constraint ${s.name}`)}for(let s of i.indexes){t(g(`an index of ${c}`,s.name,!0)),o(i.schema,s.name,`index ${c}.${s.name}`),s.keys.length===0&&e.push(`index ${s.name} has no key`);for(let m of s.keys)"column"in m&&h(m.column,`index ${s.name}`);for(let m of s.include??[])h(m,`index ${s.name}`)}for(let s of i.checks)t(g(`a check of ${c}`,s.name,!0)),u(s.name,"check"),s.expr.trim()||e.push(`check ${s.name} has no expression`);for(let s of i.foreignKeys){t(g(`a foreign key of ${c}`,s.name,!0)),u(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)h(m,`foreign key ${s.name}`)}let E=new Set;for(let s of i.policies)t(g(`a policy of ${c}`,s.name,!0)),E.has(s.name)&&e.push(`policy ${c}.${s.name} is declared twice`),E.add(s.name),s.to.length===0&&e.push(`policy ${c}.${s.name} names no role`),s.for==="insert"&&s.using!==void 0&&e.push(`policy ${c}.${s.name}: an insert policy has only withCheck`),(s.for==="select"||s.for==="delete")&&s.withCheck!==void 0&&e.push(`policy ${c}.${s.name}: a ${s.for} policy has only using`);i.policies.length>0&&!i.rls&&e.push(`table ${c} has policies but row-level security off: they would do nothing`),i.search!==void 0&&e.push(...A(`table ${c}`,i,i.search))}for(let i of n.tables)for(let c of i.foreignKeys){let f=r.get(`${c.refSchema}.${c.refTable}`);if(!f){e.push(`foreign key ${c.name} of ${b(i)} references ${c.refSchema}.${c.refTable}, which is not declared`);continue}f.ignored&&e.push(`foreign key ${c.name} of ${b(i)} references ${b(f)}, which is ignored`);for(let u of c.refColumns)f.columns.some(d=>d.name===u&&!d.ignored)||e.push(`foreign key ${c.name} references ${b(f)}.${u}, which it does not have`)}let l=new Set;for(let i of n.raw)t(g("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,a)=>r.name<a.name?-1:r.name>a.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)?[V]:[]])].sort(),raw:e(n.raw)}}function ge(n){let e=j(n),t=new Map(n.raw.map((r,a)=>[r.name,a]));return e.raw.sort((r,a)=>(t.get(r.name)??0)-(t.get(a.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 be(n){return z("sha256").update(O(j(n))).digest("hex").slice(0,32)}var v=Symbol.for("palbase.table.meta"),x=Symbol.for("palbase.ref.target"),P=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()[v],enumerable:!1,configurable:!0}),this):(this._def.refTable=e[v].name,Object.defineProperty(this._def,x,{value:e[v],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 Y(n){return new P(n)}function B(n){let e=n instanceof P?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 y=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 y?n.expr:{kind:"lit",value:n}}function k(n,e=0,t=""){let r=`pb_e${e}`;return{col:a=>new y(e===0?{kind:"col",name:a}:{kind:"col",name:a,alias:r}),auth:{uid:()=>new y({kind:"authUid"})},lit:a=>new y({kind:"lit",value:a}),and:(...a)=>new y({kind:"and",parts:a.map(o=>o.expr)}),or:(...a)=>new y({kind:"or",parts:a.map(o=>o.expr)}),not:a=>new y({kind:"not",expr:a.expr}),existsIn:(a,o)=>{let l=a[_],i=k(Object.keys(l.columns),e+1,t),c={kind:"exists",table:l.name,alias:`pb_e${e+1}`,outer:t,predicate:o(i).expr};return Object.defineProperty(c,x,{value:l,enumerable:!1,configurable:!0}),new y(c)}}}function p(n){return`"${n.replace(/"/g,'""')}"`}var S=class{_def;constructor(e){this._def={name:e,command:"all",roles:["authenticated"],using:null,withCheck:null,permissive:!0}}for(e){return this._def.command=e,this}to(...e){return this._def.roles=e,this}using(e){return this._def.using=e instanceof y?e.expr:e,this}memberOf(e,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 a=r.column??"id",o=r.userColumn??"user_id";return this._def.using=`${p(a)} IN (SELECT ${p(t)} FROM ${p(e)} WHERE ${p(o)} = (select auth.uid()))`,this}withCheck(e){return this._def.withCheck=e instanceof y?e.expr:e,this}withoutIndexes(){return this._def.indexes=!1,this}as(e){return this._def.permissive=e==="permissive",this}};function Ee(n){return new S(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 $(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`(${$(n.left,e)} ${t} ${$(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=>$(r,e)).join(t)})`}case"not":return`(NOT ${$(n.expr,e)})`;case"isNull":return`(${$(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:$(e.expr,n)}}function Ce(n){if(n!==null)return typeof n=="string"?n:w(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 w(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`(${w(n.left,e)} ${t} ${w(n.right,e)})`}case"and":case"or":return n.parts.length===0?n.kind==="and"?"(true)":"(false)":`(${n.parts.map(t=>w(t,e)).join(n.kind==="and"?" AND ":" OR ")})`;case"not":return`(NOT ${w(n.expr,e)})`;case"isNull":return`(${w(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 (${w(n.predicate,n.outer)}))`}}function M(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 Re(n){return new K(n)}function ie(n){return n instanceof S?n._def:n}var _=Symbol.for("palbase.table.meta");function Ne(n,e){if(n.trim()==="")throw new Error("defineTable(name, \u2026): name must not be empty");let t=(e.policies?.(k(Object.keys(e.columns),0,n))??[]).map(ie),r=t.length>0||e.rls!==!1,a={};for(let[u,d]of Object.entries(e.columns)){let h=d;ce(n,u,h._def),ae(n,u,h._def,e.columns);let E=Object.create(Object.getPrototypeOf(h));Object.defineProperty(E,"_def",{value:{...h._def},enumerable:!0,writable:!0}),a[u]=E}let o={name:n,columns:a,rls:r,policies:t};if(e.primaryKey!==void 0&&(o.primaryKey=[...e.primaryKey]),e.search!==void 0&&(o.search=se(n,e.search,a,o.primaryKey)),e.unique!==void 0&&(o.unique=e.unique.map(u=>({name:u.name,columns:[...u.columns]}))),e.raw!==void 0&&e.raw.length>0){for(let u of e.raw)if(u.drop!==void 0)throw new Error(`defineTable(${JSON.stringify(n)}): raw ${JSON.stringify(u.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(k(Object.keys(e.columns),0,n)):e.checks?.slice()??[];l.length>0&&(o.checks=l);let i=(e.indexes?.(k(Object.keys(e.columns),0,n))??[]).map(u=>u instanceof K?u._def:u);i.length>0&&(o.indexes=i);let c=(e.foreignKeys?.(k(Object.keys(e.columns),0,n))??[]).map(B);c.length>0&&(o.foreignKeys=c),e.ignored===!0&&(o.ignored=!0),le(n,o);for(let u of Object.values(a))u._def.ownerTable=o;let f={...a};return Object.defineProperty(f,_,{value:o,enumerable:!1}),f}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 a={from:Array.isArray(e.from)?[...e.from]:e.from,model:e.model,dimensions:e.dimensions??q,metric:e.metric??"cosine",staleness:e.staleness??"null"},o=Object.entries(t).map(([i,c])=>({name:i,def:c._def})),l=A(`defineTable(${JSON.stringify(n)})`,{columns:o.map(({name:i,def:c})=>({name:i,type:c.type==="sql"?c.sqlType??"sql":c.type,...c.ignored?{ignored:!0}:{},...c.generated?{generated:c.generated}:{}})),primaryKey:r??o.filter(({def:i})=>i.primaryKey===!0).map(({name:i})=>i)},a);if(l.length>0)throw new Error(l.join(`
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
/*! palgres 0.
|
|
2
|
-
import{p as q}from"./PEEE6WSA.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.43.0 — Palbase SDK License (see LICENSE) */
|
|
2
|
+
import{p as q}from"./JPDFD2W6.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,2 +1,2 @@
|
|
|
1
|
-
/*! palgres 0.
|
|
2
|
-
import{A as w,a as g,b as C,f as T,g as _}from"./PEEE6WSA.js";var E={uuid:"uuid",text:"text",integer:"integer",bigint:"bigint",numeric:"numeric",boolean:"boolean",timestamp:"timestamp with time zone",date:"date",jsonb:"jsonb"};function j(e){let n=Array.isArray(e)?e:[e],t={tables:[],enums:[],extensions:[],raw:[]},i=new Map;for(let u of n){for(let o of Object.values(u.tables))t.tables.push(S(u.name,o,i));t.extensions.push(...u.extensions);for(let o of u.raw??[])t.raw.push({name:o.name,schema:u.name,sql:o.up,...o.drop!==void 0?{drop:o.drop}:{},...o.before===!0?{before:!0}:{}})}t.enums=[...i.values()];for(let u of n)for(let o of Object.values(u.tables))for(let d of o.raw??[])t.raw.push({name:d.name,table:`${u.name}.${o.name}`,sql:d.up});return t}function D(e,n){return!n&&C(e.onDelete,e.onUpdate)?{...e,deferrable:!0}:e}function K(e){return e._def}function S(e,n,t){let i=[],u=r=>{let h=n.columns[r];return h!==void 0&&K(h).encrypted?.lookup?g(r):r},o=(n.unique??[]).map(r=>({name:r.name,columns:r.columns.map(u)})),d=[],s=[],a=new Set,m=[];for(let[r,h]of Object.entries(n.columns)){let l=K(h),c={name:r,type:A(e,r,n.name,l,t),nullable:l.nullable},x=q(l);x!==void 0&&(c.default=x),l.renamedFrom!==void 0&&(c.renamedFrom=l.renamedFrom),l.ignored&&(c.ignored=!0),l.fill!==void 0&&(c.fill=l.fill),l.identity!==void 0&&(c.identity=l.identity==="always"?"always":"by default"),l.generated!==void 0&&(c.generated={...l.generated}),l.user!==void 0&&(c.user={...l.user}),l.primaryKey&&s.push(r);let y=l.encrypted?.lookup?g(r):void 0;if(l.encrypted!==void 0&&(c.encrypted=y?{lookup:y}:{}),l.unique&&o.push(y?{name:`${n.name}_${y}_key`,columns:[y]}:{name:`${n.name}_${r}_key`,columns:[r]}),l.references!==void 0){let[b,k]=N(l.references.table);d.push(D({name:`${O(e,n.name)}_${r}_fkey`,columns:[r],refSchema:b,refTable:k,refColumns:[l.references.column],onDelete:l.onDeleteAction??"no action",onUpdate:l.onUpdateAction??"no action"},l.deferrable===!1)),l.index===!1&&a.add(r)}if(i.push(c),y){let b={name:y,type:"text",nullable:!0,lookupOf:r};l.renamedFrom!==void 0&&(b.renamedFrom=g(l.renamedFrom)),l.ignored&&(b.ignored=!0),i.push(b),l.unique||m.push({name:`${n.name}_${y}_idx`,keys:[{column:y}],unique:!1})}}for(let r of n.foreignKeys??[]){r.index===!1&&r.columns.length===1&&a.add(r.columns[0]);let[h,l]=N(r.refTable);d.push(D({name:r.name,columns:[...r.columns],refSchema:h,refTable:l,refColumns:[...r.refColumns],onDelete:r.onDelete??"no action",onUpdate:r.onUpdate??"no action",...r.match==="full"?{match:"full"}:{}},r.deferrable===!1))}let p={schema:e,name:n.name,columns:i,primaryKey:n.primaryKey!==void 0?[...n.primaryKey]:s,uniques:o,indexes:[...(n.indexes??[]).map(B),...m],checks:(n.checks??[]).map(r=>({name:r.name,expr:r.expr})),foreignKeys:d,rls:n.rls,policies:n.policies.map(Q)};return n.ignored&&(p.ignored=!0),n.search!==void 0&&(p.search={...n.search,from:[...n.search.from]}),p.uniques=v(p.uniques),W(p,a,new Set((n.raw??[]).map(r=>r.name)),new Set(n.policies.filter(r=>r.indexes===!1).map(r=>r.name))),p}function A(e,n,t,i,u){let o=i.type;if(o==="enum"||o==="enum[]"){let d=i.enumName,s=`${e}.${d}`,a=i.enumValues??[],m=u.get(s);if(m&&m.values.join()!==a.join())throw new Error(`enum ${s} is declared with different values by ${t}.${n}: (${m.values.join(", ")}) and (${a.join(", ")}) \u2014 one type has one list`);return u.set(s,{schema:e,name:d,values:[...a]}),o==="enum[]"?`${_(e,d)}[]`:_(e,d)}return o==="sql"?T(i.sqlType):o==="numeric"&&i.precision!==void 0?`numeric(${i.precision},${i.scale??0})`:o.endsWith("[]")?`${E[o.slice(0,-2)]??o.slice(0,-2)}[]`:E[o]??o}function q(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 B(e){let n=e.expression!==void 0?[{expr:e.expression}]:(e.columns??[]).map(u=>({column:u}));for(let u of n)e.sort==="desc"&&(u.desc=!0),e.nulls!==void 0&&(u.nulls=e.nulls);let t={name:e.name,keys:n,unique:e.unique===!0},i=e.where===void 0?void 0:w(e.where);return i!==void 0&&(t.where=i),e.include?.length&&(t.include=[...e.include]),t}function Q(e){let n={name:e.name,for:e.command,to:e.roles.length===0?["public"]:[...e.roles]},t=w(e.using),i=w(e.withCheck);return t!==void 0&&(n.using=t),i!==void 0&&(n.withCheck=i),e.permissive||(n.restrictive=!0),n}function W(e,n,t,i){let u=new Set,o=s=>s[0]!==void 0&&u.add(s[0]);o(e.primaryKey);for(let s of e.uniques)o(s.columns);for(let s of e.indexes){let a=s.keys[0];a&&"column"in a&&s.where===void 0&&u.add(a.column)}let d=s=>{if(u.has(s)||e.columns.find(m=>m.name===s)?.ignored)return;let a=`${e.name}_${s}_idx`;Buffer.byteLength(a)>63||e.indexes.some(m=>m.name===a)||t.has(a)||(e.indexes.push({name:a,keys:[{column:s}],unique:!1}),u.add(s))};for(let s of e.foreignKeys)s.columns.length===1&&!n.has(s.columns[0])&&d(s.columns[0]);for(let s of e.policies)if(!i.has(s.name))for(let a of $(e,s))d(a)}function $(e,n){let t=[];for(let i of[n.using,n.withCheck])if(i!==void 0)for(let u of i.matchAll(/(?<![.\w"])"((?:[^"]|"")+)"(?!\s*\.)/g)){let o=u[1].replace(/""/g,'"');e.columns.some(d=>d.name===o)&&!t.includes(o)&&t.push(o)}return t}function N(e){let n=e.indexOf(".");return n<0?["public",e]:[e.slice(0,n),e.slice(n+1)]}function O(e,n){return e==="public"?n:`${e}_${n}`}function v(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 P=new Set(["uuid","text","integer","bigint","numeric","boolean","timestamp","date","enum"]),L={number:{fromDb:e=>e==null?e:Number(e),toDb:e=>{if(e==null||typeof e!="number")return e==null?e:String(e);if(!Number.isFinite(e))throw new Error(`asNumber() cannot write ${e}: it is not a finite number, and the column holds one.`);if(Number.isInteger(e)&&!Number.isSafeInteger(e))throw new Error(`asNumber() cannot write ${e}: it is outside the safe integer range and would be stored as a different number. Declare .asDecimal() and hand this column a string.`);return String(e)},tsType:"number"},decimal:{fromDb:e=>e==null?e:String(e),toDb:e=>e==null?e:String(e),tsType:"string"}},f=class e{_def;constructor(n,t){this._def=t??{type:n,nullable:!1,primaryKey:!1}}primaryKey(){return this._def.primaryKey=!0,new e(this._def.type,this._def)}notNull(){return this._def.nullable=!1,new e(this._def.type,this._def)}nullable(){if(this._def.identity!==void 0)throw new Error(".nullable() on an identity column: an identity is always NOT NULL");return this._def.nullable=!0,new e(this._def.type,this._def)}default(n){return this._def.defaultValue=n,new e(this._def.type,this._def)}defaultRandom(){return this._def.defaultRandom=!0,new e(this._def.type,this._def)}defaultNow(){return this._def.defaultNow=!0,new e(this._def.type,this._def)}defaultSql(n){if(typeof n!="string"||n.trim()==="")throw new Error("defaultSql() takes the SQL of the default");return this._def.defaultSql=n,new e(this._def.type,this._def)}dbAssigned(){return this._def.dbAssigned=!0,new e(this._def.type,this._def)}array(){let n=this._def.type;if(!P.has(n))throw new Error(`${n} column: .array() is available on uuid(), text(), integer(), bigint(), numeric(), boolean(), timestamp(), date() and enumType()`);if(this._def.defaultValue!==void 0||this._def.defaultNow||this._def.defaultRandom||this._def.defaultSql!==void 0)throw new Error(`.array() comes before the default \u2014 write ${n}().array().default([])`);if(this._def.codec!==void 0||this._def.transform!==void 0)throw new Error(".array() cannot follow a codec or a transform \u2014 they convert one value, not a list of them");let t=`${n}[]`;return new e(t,{...this._def,type:t})}identity(n){if(this._def.type!=="integer"&&this._def.type!=="bigint"&&!(this._def.type==="sql"&&this._def.sqlType==="smallint"))throw new Error(`${this._def.type} column: .identity() is for integer(), bigint() and sqlType('smallint') columns`);if(this._def.defaultValue!==void 0||this._def.defaultNow||this._def.defaultRandom||this._def.defaultSql!==void 0||this._def.fill!==void 0)throw new Error(".identity() is the column's value \u2014 it cannot also have a default or a fill");let t=n?.always===!1?"byDefault":"always";return new e(this._def.type,{...this._def,nullable:!1,identity:t})}generated(n,t={}){if(typeof n!="string"||n.trim()==="")throw new Error(".generated() takes the SQL expression the column is");if(this._def.defaultValue!==void 0||this._def.defaultNow||this._def.defaultRandom||this._def.defaultSql!==void 0||this._def.fill!==void 0||this._def.identity!==void 0)throw new Error(".generated() is the column's value \u2014 it cannot also have a default, a fill or an identity");return new e(this._def.type,{...this._def,generated:{expr:n,stored:t.stored===!0}})}fillWith(n){return new e(this._def.type,{...this._def,fill:n})}renamedFrom(n){return this._def.renamedFrom=n,this}ignored(){return new e(this._def.type,{...this._def,ignored:!0})}encrypted(n={}){if(this._def.type!=="text")throw new Error(`.encrypted() is for a text() column \u2014 a ${this._def.type} column's value is not text to seal; keep it in a text() column (JSON.stringify it)`);return new e("text",{...this._def,encrypted:{lookup:n.lookup===!0}})}references(n,t){if(typeof n!="function")throw new Error('references(...) takes a callback: write references(() => otherTable.column). The two-string form references("table", "column") is gone \u2014 a string cannot be type-checked and cannot point at a table that does not exist yet.');return this._def.referencesThunk=n,t?.as!==void 0&&(this._def.refAs=t.as),t?.reverseAs!==void 0&&(this._def.reverseAs=t.reverseAs),t?.onDelete!==void 0&&(this._def.onDeleteAction=t.onDelete),t?.onUpdate!==void 0&&(this._def.onUpdateAction=t.onUpdate),t?.index===!1&&(this._def.index=!1),t?.deferrable===!1&&(this._def.deferrable=!1),new e(this._def.type,this._def)}selfReferences(n,t){return this._def.selfRefColumn=n,t?.as!==void 0&&(this._def.refAs=t.as),t?.onDelete!==void 0&&(this._def.onDeleteAction=t.onDelete),new e(this._def.type,this._def)}onDelete(n){return this._def.onDeleteAction=n,new e(this._def.type,this._def)}unique(){return this._def.unique=!0,new e(this._def.type,this._def)}asNumber(){return this.withCodec("number","asNumber")}asDecimal(){return this.withCodec("decimal","asDecimal")}withCodec(n,t){if(this._def.type!=="bigint"&&this._def.type!=="numeric")throw new Error(`${this._def.type} column: .${t}() is only available on bigint()/numeric() \u2014 those are the exact-precision types that surface as string.`);if(this._def.transform!==void 0)throw new Error(`.${t}() and .transform() are two ways to say the same thing on one column \u2014 keep .${t}().`);if(this._def.codec!==void 0)throw new Error(`column already declares .as${this._def.codec==="number"?"Number":"Decimal"}(); a column has ONE codec.`);return new e(this._def.type,{...this._def,codec:n})}transform(n){if(this._def.codec!==void 0)throw new Error("column already declares a named codec; .transform() and .as*() are two ways to say the same thing \u2014 keep the codec.");return new e(this._def.type,{...this._def,transform:n})}};function I(){return new f("uuid")}function M(){return new f("text")}function Y(){return new f("integer")}function H(){return new f("bigint")}function J(e){if(e===void 0)return new f("numeric");let{precision:n,scale:t=0}=e;if(!Number.isInteger(n)||n<1||n>1e3)throw new Error(`numeric({ precision: ${n} }): precision is a whole number from 1 to 1000`);if(!Number.isInteger(t)||t<0||t>n)throw new Error(`numeric({ precision: ${n}, scale: ${t} }): scale is a whole number from 0 to the precision`);return new f("numeric",{type:"numeric",nullable:!1,primaryKey:!1,precision:n,scale:t})}function z(){return new f("date")}var R={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 G(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=R[t];if(i!==void 0&&!(n.endsWith("[]")&&!P.has(i.slice(0,-2))))throw new Error(`sqlType(${JSON.stringify(n)}): the DSL has this type \u2014 declare it as ${i}${n.endsWith("[]")?".array()":""}`);return new f("sql",{type:"sql",nullable:!1,primaryKey:!1,sqlType:n})}var X=new Set(["smallint","real","double precision"]),Z=new Set(["json"]);function ee(){return new f("boolean")}function ne(){return new f("timestamp")}function te(){return new f("jsonb")}function re(e,n){let t=new f("enum");return t._def.enumName=e,t._def.enumValues=[...n],t}function ie(){let e=new f("text");return e._def.nullable=!1,e._def.user={onDelete:"cascade",owns:!0},e}function oe(e){let n=new f("text");return n._def.user={onDelete:e.onDelete,owns:!1},e.as!==void 0&&(n._def.refAs=e.as),n}export{j as a,$ as b,L as c,f as d,I as e,M as f,Y as g,H as h,J as i,z as j,G as k,X as l,Z as m,ee as n,ne as o,te as p,re as q,ie as r,oe as s};
|
|
1
|
+
/*! palgres 0.43.0 — Palbase SDK License (see LICENSE) */
|
|
2
|
+
import{A as w,a as g,b as C,f as T,g as _}from"./JPDFD2W6.js";var E={uuid:"uuid",text:"text",integer:"integer",bigint:"bigint",numeric:"numeric",boolean:"boolean",timestamp:"timestamp with time zone",date:"date",jsonb:"jsonb"};function j(e){let n=Array.isArray(e)?e:[e],t={tables:[],enums:[],extensions:[],raw:[]},i=new Map;for(let u of n){for(let o of Object.values(u.tables))t.tables.push(S(u.name,o,i));t.extensions.push(...u.extensions);for(let o of u.raw??[])t.raw.push({name:o.name,schema:u.name,sql:o.up,...o.drop!==void 0?{drop:o.drop}:{},...o.before===!0?{before:!0}:{}})}t.enums=[...i.values()];for(let u of n)for(let o of Object.values(u.tables))for(let d of o.raw??[])t.raw.push({name:d.name,table:`${u.name}.${o.name}`,sql:d.up});return t}function D(e,n){return!n&&C(e.onDelete,e.onUpdate)?{...e,deferrable:!0}:e}function K(e){return e._def}function S(e,n,t){let i=[],u=r=>{let h=n.columns[r];return h!==void 0&&K(h).encrypted?.lookup?g(r):r},o=(n.unique??[]).map(r=>({name:r.name,columns:r.columns.map(u)})),d=[],s=[],a=new Set,m=[];for(let[r,h]of Object.entries(n.columns)){let l=K(h),c={name:r,type:A(e,r,n.name,l,t),nullable:l.nullable},x=q(l);x!==void 0&&(c.default=x),l.renamedFrom!==void 0&&(c.renamedFrom=l.renamedFrom),l.ignored&&(c.ignored=!0),l.fill!==void 0&&(c.fill=l.fill),l.identity!==void 0&&(c.identity=l.identity==="always"?"always":"by default"),l.generated!==void 0&&(c.generated={...l.generated}),l.user!==void 0&&(c.user={...l.user}),l.primaryKey&&s.push(r);let y=l.encrypted?.lookup?g(r):void 0;if(l.encrypted!==void 0&&(c.encrypted=y?{lookup:y}:{}),l.unique&&o.push(y?{name:`${n.name}_${y}_key`,columns:[y]}:{name:`${n.name}_${r}_key`,columns:[r]}),l.references!==void 0){let[b,k]=N(l.references.table);d.push(D({name:`${O(e,n.name)}_${r}_fkey`,columns:[r],refSchema:b,refTable:k,refColumns:[l.references.column],onDelete:l.onDeleteAction??"no action",onUpdate:l.onUpdateAction??"no action"},l.deferrable===!1)),l.index===!1&&a.add(r)}if(i.push(c),y){let b={name:y,type:"text",nullable:!0,lookupOf:r};l.renamedFrom!==void 0&&(b.renamedFrom=g(l.renamedFrom)),l.ignored&&(b.ignored=!0),i.push(b),l.unique||m.push({name:`${n.name}_${y}_idx`,keys:[{column:y}],unique:!1})}}for(let r of n.foreignKeys??[]){r.index===!1&&r.columns.length===1&&a.add(r.columns[0]);let[h,l]=N(r.refTable);d.push(D({name:r.name,columns:[...r.columns],refSchema:h,refTable:l,refColumns:[...r.refColumns],onDelete:r.onDelete??"no action",onUpdate:r.onUpdate??"no action",...r.match==="full"?{match:"full"}:{}},r.deferrable===!1))}let p={schema:e,name:n.name,columns:i,primaryKey:n.primaryKey!==void 0?[...n.primaryKey]:s,uniques:o,indexes:[...(n.indexes??[]).map(B),...m],checks:(n.checks??[]).map(r=>({name:r.name,expr:r.expr})),foreignKeys:d,rls:n.rls,policies:n.policies.map(Q)};return n.ignored&&(p.ignored=!0),n.search!==void 0&&(p.search={...n.search,from:[...n.search.from]}),p.uniques=v(p.uniques),W(p,a,new Set((n.raw??[]).map(r=>r.name)),new Set(n.policies.filter(r=>r.indexes===!1).map(r=>r.name))),p}function A(e,n,t,i,u){let o=i.type;if(o==="enum"||o==="enum[]"){let d=i.enumName,s=`${e}.${d}`,a=i.enumValues??[],m=u.get(s);if(m&&m.values.join()!==a.join())throw new Error(`enum ${s} is declared with different values by ${t}.${n}: (${m.values.join(", ")}) and (${a.join(", ")}) \u2014 one type has one list`);return u.set(s,{schema:e,name:d,values:[...a]}),o==="enum[]"?`${_(e,d)}[]`:_(e,d)}return o==="sql"?T(i.sqlType):o==="numeric"&&i.precision!==void 0?`numeric(${i.precision},${i.scale??0})`:o.endsWith("[]")?`${E[o.slice(0,-2)]??o.slice(0,-2)}[]`:E[o]??o}function q(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 B(e){let n=e.expression!==void 0?[{expr:e.expression}]:(e.columns??[]).map(u=>({column:u}));for(let u of n)e.sort==="desc"&&(u.desc=!0),e.nulls!==void 0&&(u.nulls=e.nulls);let t={name:e.name,keys:n,unique:e.unique===!0},i=e.where===void 0?void 0:w(e.where);return i!==void 0&&(t.where=i),e.include?.length&&(t.include=[...e.include]),t}function Q(e){let n={name:e.name,for:e.command,to:e.roles.length===0?["public"]:[...e.roles]},t=w(e.using),i=w(e.withCheck);return t!==void 0&&(n.using=t),i!==void 0&&(n.withCheck=i),e.permissive||(n.restrictive=!0),n}function W(e,n,t,i){let u=new Set,o=s=>s[0]!==void 0&&u.add(s[0]);o(e.primaryKey);for(let s of e.uniques)o(s.columns);for(let s of e.indexes){let a=s.keys[0];a&&"column"in a&&s.where===void 0&&u.add(a.column)}let d=s=>{if(u.has(s)||e.columns.find(m=>m.name===s)?.ignored)return;let a=`${e.name}_${s}_idx`;Buffer.byteLength(a)>63||e.indexes.some(m=>m.name===a)||t.has(a)||(e.indexes.push({name:a,keys:[{column:s}],unique:!1}),u.add(s))};for(let s of e.foreignKeys)s.columns.length===1&&!n.has(s.columns[0])&&d(s.columns[0]);for(let s of e.policies)if(!i.has(s.name))for(let a of $(e,s))d(a)}function $(e,n){let t=[];for(let i of[n.using,n.withCheck])if(i!==void 0)for(let u of i.matchAll(/(?<![.\w"])"((?:[^"]|"")+)"(?!\s*\.)/g)){let o=u[1].replace(/""/g,'"');e.columns.some(d=>d.name===o)&&!t.includes(o)&&t.push(o)}return t}function N(e){let n=e.indexOf(".");return n<0?["public",e]:[e.slice(0,n),e.slice(n+1)]}function O(e,n){return e==="public"?n:`${e}_${n}`}function v(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 P=new Set(["uuid","text","integer","bigint","numeric","boolean","timestamp","date","enum"]),L={number:{fromDb:e=>e==null?e:Number(e),toDb:e=>{if(e==null||typeof e!="number")return e==null?e:String(e);if(!Number.isFinite(e))throw new Error(`asNumber() cannot write ${e}: it is not a finite number, and the column holds one.`);if(Number.isInteger(e)&&!Number.isSafeInteger(e))throw new Error(`asNumber() cannot write ${e}: it is outside the safe integer range and would be stored as a different number. Declare .asDecimal() and hand this column a string.`);return String(e)},tsType:"number"},decimal:{fromDb:e=>e==null?e:String(e),toDb:e=>e==null?e:String(e),tsType:"string"}},f=class e{_def;constructor(n,t){this._def=t??{type:n,nullable:!1,primaryKey:!1}}primaryKey(){return this._def.primaryKey=!0,new e(this._def.type,this._def)}notNull(){return this._def.nullable=!1,new e(this._def.type,this._def)}nullable(){if(this._def.identity!==void 0)throw new Error(".nullable() on an identity column: an identity is always NOT NULL");return this._def.nullable=!0,new e(this._def.type,this._def)}default(n){return this._def.defaultValue=n,new e(this._def.type,this._def)}defaultRandom(){return this._def.defaultRandom=!0,new e(this._def.type,this._def)}defaultNow(){return this._def.defaultNow=!0,new e(this._def.type,this._def)}defaultSql(n){if(typeof n!="string"||n.trim()==="")throw new Error("defaultSql() takes the SQL of the default");return this._def.defaultSql=n,new e(this._def.type,this._def)}dbAssigned(){return this._def.dbAssigned=!0,new e(this._def.type,this._def)}array(){let n=this._def.type;if(!P.has(n))throw new Error(`${n} column: .array() is available on uuid(), text(), integer(), bigint(), numeric(), boolean(), timestamp(), date() and enumType()`);if(this._def.defaultValue!==void 0||this._def.defaultNow||this._def.defaultRandom||this._def.defaultSql!==void 0)throw new Error(`.array() comes before the default \u2014 write ${n}().array().default([])`);if(this._def.codec!==void 0||this._def.transform!==void 0)throw new Error(".array() cannot follow a codec or a transform \u2014 they convert one value, not a list of them");let t=`${n}[]`;return new e(t,{...this._def,type:t})}identity(n){if(this._def.type!=="integer"&&this._def.type!=="bigint"&&!(this._def.type==="sql"&&this._def.sqlType==="smallint"))throw new Error(`${this._def.type} column: .identity() is for integer(), bigint() and sqlType('smallint') columns`);if(this._def.defaultValue!==void 0||this._def.defaultNow||this._def.defaultRandom||this._def.defaultSql!==void 0||this._def.fill!==void 0)throw new Error(".identity() is the column's value \u2014 it cannot also have a default or a fill");let t=n?.always===!1?"byDefault":"always";return new e(this._def.type,{...this._def,nullable:!1,identity:t})}generated(n,t={}){if(typeof n!="string"||n.trim()==="")throw new Error(".generated() takes the SQL expression the column is");if(this._def.defaultValue!==void 0||this._def.defaultNow||this._def.defaultRandom||this._def.defaultSql!==void 0||this._def.fill!==void 0||this._def.identity!==void 0)throw new Error(".generated() is the column's value \u2014 it cannot also have a default, a fill or an identity");return new e(this._def.type,{...this._def,generated:{expr:n,stored:t.stored===!0}})}fillWith(n){return new e(this._def.type,{...this._def,fill:n})}renamedFrom(n){return this._def.renamedFrom=n,this}ignored(){return new e(this._def.type,{...this._def,ignored:!0})}encrypted(n={}){if(this._def.type!=="text")throw new Error(`.encrypted() is for a text() column \u2014 a ${this._def.type} column's value is not text to seal; keep it in a text() column (JSON.stringify it)`);return new e("text",{...this._def,encrypted:{lookup:n.lookup===!0}})}references(n,t){if(typeof n!="function")throw new Error('references(...) takes a callback: write references(() => otherTable.column). The two-string form references("table", "column") is gone \u2014 a string cannot be type-checked and cannot point at a table that does not exist yet.');return this._def.referencesThunk=n,t?.as!==void 0&&(this._def.refAs=t.as),t?.reverseAs!==void 0&&(this._def.reverseAs=t.reverseAs),t?.onDelete!==void 0&&(this._def.onDeleteAction=t.onDelete),t?.onUpdate!==void 0&&(this._def.onUpdateAction=t.onUpdate),t?.index===!1&&(this._def.index=!1),t?.deferrable===!1&&(this._def.deferrable=!1),new e(this._def.type,this._def)}selfReferences(n,t){return this._def.selfRefColumn=n,t?.as!==void 0&&(this._def.refAs=t.as),t?.onDelete!==void 0&&(this._def.onDeleteAction=t.onDelete),new e(this._def.type,this._def)}onDelete(n){return this._def.onDeleteAction=n,new e(this._def.type,this._def)}unique(){return this._def.unique=!0,new e(this._def.type,this._def)}asNumber(){return this.withCodec("number","asNumber")}asDecimal(){return this.withCodec("decimal","asDecimal")}withCodec(n,t){if(this._def.type!=="bigint"&&this._def.type!=="numeric")throw new Error(`${this._def.type} column: .${t}() is only available on bigint()/numeric() \u2014 those are the exact-precision types that surface as string.`);if(this._def.transform!==void 0)throw new Error(`.${t}() and .transform() are two ways to say the same thing on one column \u2014 keep .${t}().`);if(this._def.codec!==void 0)throw new Error(`column already declares .as${this._def.codec==="number"?"Number":"Decimal"}(); a column has ONE codec.`);return new e(this._def.type,{...this._def,codec:n})}transform(n){if(this._def.codec!==void 0)throw new Error("column already declares a named codec; .transform() and .as*() are two ways to say the same thing \u2014 keep the codec.");return new e(this._def.type,{...this._def,transform:n})}};function I(){return new f("uuid")}function M(){return new f("text")}function Y(){return new f("integer")}function H(){return new f("bigint")}function J(e){if(e===void 0)return new f("numeric");let{precision:n,scale:t=0}=e;if(!Number.isInteger(n)||n<1||n>1e3)throw new Error(`numeric({ precision: ${n} }): precision is a whole number from 1 to 1000`);if(!Number.isInteger(t)||t<0||t>n)throw new Error(`numeric({ precision: ${n}, scale: ${t} }): scale is a whole number from 0 to the precision`);return new f("numeric",{type:"numeric",nullable:!1,primaryKey:!1,precision:n,scale:t})}function z(){return new f("date")}var R={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 G(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=R[t];if(i!==void 0&&!(n.endsWith("[]")&&!P.has(i.slice(0,-2))))throw new Error(`sqlType(${JSON.stringify(n)}): the DSL has this type \u2014 declare it as ${i}${n.endsWith("[]")?".array()":""}`);return new f("sql",{type:"sql",nullable:!1,primaryKey:!1,sqlType:n})}var X=new Set(["smallint","real","double precision"]),Z=new Set(["json"]);function ee(){return new f("boolean")}function ne(){return new f("timestamp")}function te(){return new f("jsonb")}function re(e,n){let t=new f("enum");return t._def.enumName=e,t._def.enumValues=[...n],t}function ie(){let e=new f("text");return e._def.nullable=!1,e._def.user={onDelete:"cascade",owns:!0},e}function oe(e){let n=new f("text");return n._def.user={onDelete:e.onDelete,owns:!1},e.as!==void 0&&(n._def.refAs=e.as),n}export{j as a,$ as b,L as c,f as d,I as e,M as f,Y as g,H as h,J as i,z as j,G as k,X as l,Z as m,ee as n,ne as o,te as p,re as q,ie as r,oe as s};
|
package/dist/dsl.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
/*! palgres 0.
|
|
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/
|
|
1
|
+
/*! palgres 0.43.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/SIOHY2RY.js";import{A as D,n,o as i,p as f,q as a,r as l,s as p,t as u,u as m,v as s,w as y,x as c,y as d,z as x}from"./chunks/JPDFD2W6.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.
|
|
2
|
-
import{a as Ws,b as js,c as Qe,l as Fn,m as qn}from"./chunks/
|
|
1
|
+
/*! palgres 0.43.0 — Palbase SDK License (see LICENSE) */
|
|
2
|
+
import{a as Ws,b as js,c as Qe,l as Fn,m as qn}from"./chunks/SIOHY2RY.js";import{$ as Zs,A as gn,B as J,C as _t,D as xe,E as en,F as Un,G as Ks,H as Gs,I as Vs,J as Bn,K as Wn,L as Dt,M as Xs,N as Ys,O as hn,P as Js,Q as oi,R as ii,S as ai,T as li,U as ci,V as ui,W as En,X as zs,Y as Qs,Z as jn,_ as Hn,a as Zo,aa as er,b as ei,c as oe,d as de,e as Ie,f as ni,g as Ce,h as Ct,i as ti,j as Ye,k as Je,l as xt,m as vt,n as ze,o as Be,p as ie,q as qs,r as Us,s as Bs,t as ge,u as Mn,v as fn,w as Hs,x as si,y as ri,z as Ze}from"./chunks/SF2MPMTK.js";import{a as Ds,b as Xe,c as qe,d as Lt,e as M,f as ue,g as pn,h as Ps,i as Ms,j as It,k as fe,l as Fs,m as Ue,p as Te}from"./chunks/JPDFD2W6.js";import{createHash as fi}from"node:crypto";function Kn(t){return typeof t=="function"?t():Promise.resolve(t)}var nr="pbe1.";function nn(t,e,n){return t==="public"?`${e}.${n}`:`${t}.${e}.${n}`}var he="palgres.sealing",Gn=5e3,Pt=3*Gn,yn=class{going=new Map;get(e){return this.going.get(e)}get size(){return this.going.size}async read(e){let n;try{n=await e(`SELECT address, direction, phase FROM ${he}`)}catch(s){let r=s.code??s.errno;if(r!=="42P01"&&r!=="3F000")throw s;n=[]}this.going=new Map(n.map(s=>[s.address,{direction:s.direction,phase:s.phase}]))}},wn=t=>`"${t.replace(/"/g,'""')}"`;function tr(t,e){let n=wn(t.column);return t.direction==="open"?{sql:`${n} LIKE 'pbe1.%'`,params:[]}:{sql:`(${n} NOT LIKE $1${t.lookup?` OR ${wn(t.lookup)} IS NULL`:""})`,params:[`pbe1.${e.currentKey()}.%`]}}async function Vn(t,e,n,s,r){let o=tr(e,n),i=wn(e.column),a=s===null?"":` AND ctid > $${o.params.length+1}::tid`,c=await t(`SELECT ctid::text AS at, ${i} AS value FROM ${e.table} WHERE ${i} IS NOT NULL AND ${o.sql}${a} ORDER BY ctid LIMIT ${r}`,s===null?o.params:[...o.params,s]);if(c.length===0)return{done:0,last:null};let l=[],d=c.map(h=>{let p=di(n,e.address,h.value),g=[h.at,h.value,e.direction==="seal"?n.encrypt(e.address,p):p,...e.lookup?[n.lookup(e.address,p)]:[]],T=l.length+1;return l.push(...g),`(${g.map((f,m)=>`$${T+m}::text`).join(", ")})`}),y=[`${i} = v.next`,...e.lookup?[`${wn(e.lookup)} = v.lookup`]:[]],u=await t(`WITH done AS (UPDATE ${e.table} AS t SET ${y.join(", ")} FROM (VALUES ${d.join(", ")}) AS v(at, old, next${e.lookup?", lookup":""}) WHERE t.ctid = v.at::tid AND t.${i} = v.old RETURNING 1) SELECT count(*)::int AS n FROM done`,l);return{done:Number(u[0]?.n??0),last:c.length<r?null:c[c.length-1].at}}function di(t,e,n){if(!t.isEncrypted(n))return n;try{return t.decrypt(e,n)}catch{return n}}function Xn(t,e){if(typeof e=="string"&&e.startsWith(nr))throw new TypeError(`${t} is going over between plain and encrypted: a value beginning ${nr} would read as an encrypted one \u2014 it is written once the migration completes`)}async function sr(t,e,n){let s=tr(e,n);return(await t(`SELECT 1 FROM ${e.table} WHERE ${wn(e.column)} IS NOT NULL AND ${s.sql} LIMIT 1`,s.params)).length>0}import{createHash as qt}from"node:crypto";var b=t=>`"${t.replace(/"/g,'""')}"`,D=(t,e)=>`${b(t)}.${b(e)}`,C=t=>`'${t.replace(/'/g,"''")}'`;function re(t){if(t.includes("\0"))throw new TypeError("a NUL character cannot be sent to Postgres");return`E'${t.replace(/\\/g,"\\\\").replace(/'/g,"''")}'`}var Se=t=>t.map(b).join(", "),mi=new Set(["now","current_timestamp","current_date","current_time","localtimestamp","localtime","transaction_timestamp","statement_timestamp"]);function rr(t){return[...Mt(t)].some(e=>e.call&&!mi.has(e.name.toLowerCase()))}function*Mt(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 Ne(t,e){for(let n of Mt(t))if(!n.call&&(n.quoted?n.name===e:n.name.toLowerCase()===e.toLowerCase()))return!0;return!1}function Re(t,e){if(e.size===0)return t;let n="",s=0;for(let r of Mt(t)){if(r.call)continue;let o=e.get(r.quoted?r.name:pi(e,r.name)??"");o!==void 0&&(n+=t.slice(s,r.start)+b(o),s=r.end)}return n+t.slice(s)}function pi(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 Yn=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 Q="palgres_search",Jn=(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]),or=48;function De(t,e){let n=t.replaceAll(".","__");return`${n.length<=or?n:`${n.slice(0,32)}_${qt("md5").update(n).digest("hex").slice(0,12)}`}__g${e}`}var ir=t=>({insert:`_palgres_search_g${t}_ins`,update:`_palgres_search_g${t}_upd`});function zn(t,e){let n=qt("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_${qt("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 Zn=(t,e)=>`to_tsvector('simple', ${Qn(t,e)})`;function $n(t,e){let n=t>Ps?"halfvec":"vector",s={cosine:["cosine","<=>"],euclidean:["l2","<->"],inner_product:["ip","<#>"]}[e];return{type:n,opclass:`${n}_${s[0]}_ops`,operator:s[1]}}function ar(t){let e=`${t.table.schema}.${t.table.name}`,n=D(t.table.schema,t.table.name),s=De(e,t.gen),r=D(Q,s),o=$n(t.search.dimensions,t.search.metric),i=b(t.pk.name),a=[t.roles.anon,t.roles.authenticated].map(b).join(", ");return[`INSERT INTO ${Q}.generations (table_key, gen, model, dimensions, metric, from_columns, status, promoted_at) VALUES (${C(e)}, ${t.gen}, ${C(t.search.model)}, ${t.search.dimensions}, ${C(t.search.metric)}, ARRAY[${t.search.from.map(C).join(", ")}]::text[], ${C(t.status)}, ${t.status==="active"?"now()":"NULL"})`,`CREATE TABLE ${r} (
|
|
5
5
|
id ${t.pk.type} PRIMARY KEY REFERENCES ${n} (${i}) ON DELETE CASCADE,
|
package/dist/testing.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
/*! palgres 0.
|
|
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/FLOZN74T.js";import"./chunks/PEEE6WSA.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.43.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/SF2MPMTK.js";import"./chunks/JPDFD2W6.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